Files
Alphaeus Mote df62b38a00 feat(jobs): a run's breakdown of exit codes, errors and completions
GET /api/executions/{runId}/breakdown (jobs.view, scoped): exit-code counts,
failed jobs grouped by exception type and first line (position text and paths
cut, up to five sample devices, every job id) and finished jobs by outcome in
buckets sized to the run. Jobs from older agents fall back to their summary,
then their first Error-stream line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:19:39 -04:00

244 lines
11 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Backend.Data;
using Backend.Jobs;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
public class RunBreakdownNormalizeTests
{
[Theory]
[InlineData("Access is denied.", "Access is denied.")]
[InlineData("boom\nAt line:1 char:1\n+ throw 'boom'\n+ ~~~~", "boom")]
[InlineData("\n\n first real line \nsecond", "first real line")]
[InlineData("It broke At line:12 char:5 + something", "It broke")]
[InlineData("It broke At C:\\Temp\\job\\payload.ps1:3 char:1", "It broke")]
[InlineData("Cannot find path 'C:\\Program Files\\App\\a.txt' because it does not exist.", "Cannot find path '…' because it does not exist.")]
[InlineData("Cannot open \"\\\\server\\share\\a b.txt\" now", "Cannot open \"…\" now")]
[InlineData("Could not read '/var/log/app/a b.log'", "Could not read '…'")]
[InlineData("Failed loading C:\\Temp\\a.dll, retrying", "Failed loading …, retrying")]
[InlineData("Failed loading /usr/lib/x/a.so now", "Failed loading … now")]
[InlineData("Failed on \\\\server\\share\\x now", "Failed on … now")]
[InlineData("Use and/or check http://example.test/a/b", "Use and/or check http://example.test/a/b")]
[InlineData("many spaces\there", "many spaces here")]
[InlineData("", RunBreakdown.NoMessage)]
[InlineData(" \n ", RunBreakdown.NoMessage)]
[InlineData(null, RunBreakdown.NoMessage)]
public void ANormalizedMessageKeepsWhatDevicesShare(string? text, string expected)
=> Assert.Equal(expected, RunBreakdown.Normalize(text));
[Fact]
public void AVeryLongLineIsCut()
{
var message = RunBreakdown.Normalize(new string('x', 1000));
Assert.Equal(RunBreakdown.MaxMessageLength, message.Length);
Assert.EndsWith("…", message);
}
private static RunBreakdownJob Job(JobState state, int? exit, DateTimeOffset created, double? finishedAfter, string? type = null, string? message = null, string? summary = null)
=> new(Guid.NewGuid(), Guid.NewGuid().ToString("N"), state, exit, created, finishedAfter is { } s ? created.AddSeconds(s) : null, type, message, summary);
private static ExecutionBreakdownDto Build(params RunBreakdownJob[] jobs)
=> RunBreakdown.Build(jobs, new Dictionary<Guid, string>(), new Dictionary<string, string>());
[Fact]
public void TheBucketFitsTheRunsLength()
{
var now = DateTimeOffset.UtcNow;
var quick = Build(Job(JobState.Succeeded, 0, now, 0), Job(JobState.Failed, 1, now, 12));
Assert.Equal(5, quick.BucketSeconds);
Assert.Equal(3, quick.Completions.Count);
Assert.Equal((1, 0), (quick.Completions[0].Succeeded, quick.Completions[0].Failed));
Assert.Equal((0, 1), (quick.Completions[2].Succeeded, quick.Completions[2].Failed));
var hour = Build(Job(JobState.Succeeded, 0, now, 3000));
Assert.Equal(60, hour.BucketSeconds);
Assert.Equal(51, hour.Completions.Count);
var weeks = Build(Job(JobState.Succeeded, 0, now, 86_400 * 90));
Assert.True(weeks.Completions.Count <= 61);
Assert.Equal(1, weeks.Completions[^1].Succeeded);
Assert.Empty(Build(Job(JobState.Running, null, now, null)).Completions);
}
[Fact]
public void ACompletionBeforeTheStartLandsInTheFirstBucket()
{
var breakdown = Build(Job(JobState.Succeeded, 0, DateTimeOffset.UtcNow, -30));
Assert.Equal(1, breakdown.Completions[0].Succeeded);
}
[Fact]
public void CompletionsKeepEachOutcomeApart()
{
var now = DateTimeOffset.UtcNow;
var bucket = Assert.Single(Build(
Job(JobState.Succeeded, 0, now, 1), Job(JobState.Failed, 3, now, 1),
Job(JobState.TimedOut, -1, now, 1), Job(JobState.Cancelled, -1, now, 1)).Completions);
Assert.Equal((1, 1, 1, 1), (bucket.Succeeded, bucket.Failed, bucket.TimedOut, bucket.Cancelled));
}
}
public class RunBreakdownTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private async Task<(Guid RunId, Dictionary<string, Guid> Jobs)> SeedRunAsync(string name, params (string Host, Action<JobEntity> Shape)[] devices)
{
var scriptId = await fixture.SeedScriptAsync(name);
var runId = Guid.NewGuid();
var jobs = new Dictionary<string, Guid>();
foreach (var (host, shape) in devices)
{
var clientId = await fixture.SeedDeviceAsync(host);
var job = new JobEntity
{
JobId = Guid.NewGuid(), RunId = runId, ClientId = clientId, ScriptId = scriptId, ScriptName = name,
State = JobState.Succeeded, ExitCode = 0,
CreatedUtc = DateTimeOffset.UtcNow.AddMinutes(-10), CompletedUtc = DateTimeOffset.UtcNow,
};
shape(job);
jobs[host] = job.JobId;
await fixture.WithDbAsync(async db =>
{
db.Jobs.Add(job);
await db.SaveChangesAsync();
});
}
return (runId, jobs);
}
private static Task<ExecutionBreakdownDto?> GetAsync(HttpClient client, Guid runId)
=> client.GetFromJsonAsync<ExecutionBreakdownDto>(ApiRoutes.For.ExecutionBreakdown(runId), JsonDefaults.Options);
private static Action<JobEntity> Failed(int code, string? type = null, string? message = null, string? summary = null) => job =>
{
job.State = JobState.Failed;
job.ExitCode = code;
job.ErrorType = type;
job.ErrorMessage = message;
job.OutputSummary = summary;
};
[Fact]
public async Task ExitCodesAndErrorsAreCountedAndGrouped()
{
using var client = await fixture.SignedInAsync("breakdown-admin");
var (runId, jobs) = await SeedRunAsync("grouped",
("GROUPED-OK-1", _ => { }),
("GROUPED-OK-2", _ => { }),
("GROUPED-A", Failed(1, "System.IO.IOException", "Cannot read 'C:\\Users\\a\\x.txt' now")),
("GROUPED-B", Failed(1, "System.IO.IOException", "Cannot read 'C:\\Users\\b\\y.txt' now")),
("GROUPED-C", Failed(5, summary: "The script exited with 5.")),
("GROUPED-TIMEOUT", job =>
{
job.State = JobState.TimedOut;
job.ExitCode = -1;
job.OutputSummary = "Execution exceeded the 3600s timeout.";
}),
("GROUPED-RUNNING", job =>
{
job.State = JobState.Running;
job.ExitCode = null;
job.CompletedUtc = null;
}));
var breakdown = (await GetAsync(client, runId))!;
Assert.Equal(
[(0, 2), (1, 2), (-1, 1), (5, 1)],
breakdown.ExitCodes.Select(c => (c.ExitCode, c.Count)));
Assert.Equal(3, breakdown.Errors.Count);
var top = breakdown.Errors[0];
Assert.Equal("System.IO.IOException", top.Type);
Assert.Equal("Cannot read '…' now", top.Message);
Assert.Equal(2, top.Count);
Assert.Equal(["GROUPED-A", "GROUPED-B"], top.Samples.Select(s => s.Hostname).Order());
Assert.Equal(new[] { jobs["GROUPED-A"], jobs["GROUPED-B"] }.Order(), top.JobIds.Order());
Assert.Contains(breakdown.Errors, e => e.Message == "Execution exceeded the 3600s timeout." && e.Type is null);
var finished = breakdown.Completions.Sum(b => b.Succeeded + b.Failed + b.TimedOut + b.Cancelled);
Assert.Equal(5 + 1, finished);
}
[Fact]
public async Task SamplesStopAtFiveButEveryJobIsListed()
{
using var client = await fixture.SignedInAsync("breakdown-admin");
var devices = Enumerable.Range(0, 7)
.Select(i => ($"SAMPLES-{i}", Failed(1, message: "Same problem")))
.ToArray();
var (runId, _) = await SeedRunAsync("samples", devices);
var group = Assert.Single((await GetAsync(client, runId))!.Errors);
Assert.Equal(7, group.Count);
Assert.Equal(RunBreakdown.MaxSamples, group.Samples.Count);
Assert.Equal(7, group.JobIds.Count);
}
[Fact]
public async Task OlderJobsFallBackToTheirFirstErrorLine()
{
using var client = await fixture.SignedInAsync("breakdown-admin");
var (runId, jobs) = await SeedRunAsync("fallback",
("FALLBACK-A", Failed(1)),
("FALLBACK-QUIET", Failed(1)));
await fixture.WithDbAsync(async db =>
{
var job = jobs["FALLBACK-A"];
db.JobOutput.AddRange(
new JobOutputEntity { JobId = job, Sequence = 1, Stream = OutputStreamKind.Output, TimestampUtc = DateTimeOffset.UtcNow, Text = "not this" },
new JobOutputEntity { JobId = job, Sequence = 2, Stream = OutputStreamKind.Error, TimestampUtc = DateTimeOffset.UtcNow, Text = "the first error\nAt line:1 char:1" },
new JobOutputEntity { JobId = job, Sequence = 3, Stream = OutputStreamKind.Error, TimestampUtc = DateTimeOffset.UtcNow, Text = "the second error" });
await db.SaveChangesAsync();
});
var errors = (await GetAsync(client, runId))!.Errors;
Assert.Equal(["No Error Reported", "the first error"], errors.Select(e => e.Message).Order(StringComparer.Ordinal));
}
[Fact]
public async Task AScopedRoleOnlySeesItsOwnDevices()
{
using var admin = await fixture.SignedInAsync("breakdown-admin");
var (runId, jobs) = await SeedRunAsync("scope",
("SCOPE-MINE", Failed(2, message: "Mine failed")),
("SCOPE-THEIRS", Failed(3, message: "Theirs failed")));
var mine = await fixture.WithDbAsync(db =>
{
var id = jobs["SCOPE-MINE"];
return db.Jobs.Where(j => j.JobId == id).Select(j => j.ClientId).SingleAsync();
});
var stranger = await fixture.SeedDeviceAsync("SCOPE-OUTSIDE");
using var scoped = await fixture.ScopedSignedInAsync("breakdown-scoped", mine);
using var outside = await fixture.ScopedSignedInAsync("breakdown-outside", stranger);
var breakdown = (await GetAsync(scoped, runId))!;
Assert.Equal([2], breakdown.ExitCodes.Select(c => c.ExitCode));
Assert.Equal("Mine failed", Assert.Single(breakdown.Errors).Message);
Assert.Equal(HttpStatusCode.NotFound, (await outside.GetAsync(ApiRoutes.For.ExecutionBreakdown(runId))).StatusCode);
}
[Fact]
public async Task AnUnknownRunIsNotFound()
{
using var client = await fixture.SignedInAsync("breakdown-admin");
Assert.Equal(HttpStatusCode.NotFound, (await client.GetAsync(ApiRoutes.For.ExecutionBreakdown(Guid.NewGuid()))).StatusCode);
}
}