Files
Alphaeus Mote 4cb34ce7e5 Merge parallel dispatch and batched job-state writes [skip ci]
Batched final states keep Restart After Run (Requested/Refused) in the same conditional update, without replacing one the restart request stored; the restart request keeps the in-memory ApplyJobState. Dispatch test send delay raised so overlap holds on a loaded runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 07:18:28 -05:00

254 lines
12 KiB
C#

using System.Collections.Concurrent;
using System.Net.Http.Json;
using Backend.Data;
using Backend.Jobs;
using Backend.Messaging;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Api;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Shared.Infrastructure.Nats;
using Xunit;
namespace Backend.Tests;
public class BatchedJobStateTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private MessagingWorkers Workers => fixture.Services.GetServices<IHostedService>().OfType<MessagingWorkers>().Single();
/// <summary>What happened to each message on the stream, in order.</summary>
private readonly ConcurrentQueue<(int Message, string Outcome)> settled = new();
private MessagingWorkers.JobStateMessage Message(int index, JobStatePayload payload)
=> Message(index, NatsSubjects.JobState(payload.JobId), MessageEnvelope.Create(
MessageTypes.JobState, new EndpointRef(EndpointKinds.Agent, payload.ClientId), payload).ToUtf8Bytes());
private MessagingWorkers.JobStateMessage Message(int index, string subject, byte[] data) => new(
subject, data, DateTimeOffset.UtcNow,
_ => Settle(index, "ack"),
_ => Settle(index, "term"),
(_, _) => Settle(index, "nak"));
private ValueTask Settle(int index, string outcome)
{
settled.Enqueue((index, outcome));
return ValueTask.CompletedTask;
}
private string? Outcome(int index) => settled.Where(s => s.Message == index).Select(s => s.Outcome).SingleOrDefault();
private static JobStatePayload State(JobEntity job, JobState state, DateTimeOffset at, int? exitCode = null)
=> new(job.JobId, job.ClientId, state, exitCode, at, state == JobState.Running ? null : "done");
/// <summary>A run of <paramref name="count"/> devices, its jobs dispatched (as the console starts one).</summary>
private async Task<(Guid RunId, List<JobEntity> Jobs, HttpClient Client)> StartRunAsync(string name, int count)
{
fixture.Scripts.Accept = true;
var client = await fixture.SignedInAsync($"{name}-admin");
var scriptId = await fixture.SeedScriptAsync(name);
var devices = new List<string>();
for (var i = 0; i < count; i++)
{
devices.Add(await fixture.SeedDeviceAsync($"{name}-{i}"));
}
var response = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, scriptId, ClientIds: devices), JsonDefaults.Options);
response.EnsureSuccessStatusCode();
var run = (await response.Content.ReadFromJsonAsync<GroupRunDto>(JsonDefaults.Options))!;
var jobs = await JobsAsync(run.RunId!.Value);
Assert.All(jobs, j => Assert.Equal(JobState.Dispatched, j.State));
return (run.RunId!.Value, jobs, client);
}
private Task<List<JobEntity>> JobsAsync(Guid runId)
=> fixture.WithDbAsync(db => db.Jobs.AsNoTracking().Where(j => j.RunId == runId).OrderBy(j => j.ClientId).ToListAsync());
[Fact]
public async Task ABatchIsStoredInOrderInOneTransactionAndAckedOnlyAfterItCommits()
{
var (runId, jobs, client) = await StartRunAsync("batch", 20);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-1);
var messages = new List<MessagingWorkers.JobStateMessage>();
foreach (var job in jobs)
{
messages.Add(Message(messages.Count, State(job, JobState.Running, t0)));
}
// Half succeed, a quarter fail, the rest are still running; one Running comes after its final state.
for (var i = 0; i < 15; i++)
{
messages.Add(Message(messages.Count, State(jobs[i], i < 10 ? JobState.Succeeded : JobState.Failed, t0.AddSeconds(30), i < 10 ? 0 : 1)));
}
var late = messages.Count;
messages.Add(Message(late, State(jobs[0], JobState.Running, t0.AddSeconds(40))));
// Another device's job, and something that is not a state at all.
var foreign = messages.Count;
messages.Add(Message(foreign, new JobStatePayload(jobs[19].JobId, jobs[0].ClientId, JobState.Succeeded, 0, t0, "not yours")));
var garbage = messages.Count;
messages.Add(Message(garbage, NatsSubjects.JobState(Guid.NewGuid()), "not json"u8.ToArray()));
var commits = new List<(int States, int AckedBefore)>();
Workers.BeforeStateCommit = states => commits.Add((states.Count, settled.Count(s => s.Outcome == "ack")));
try
{
await Workers.StoreJobStatesAsync(messages, CancellationToken.None);
}
finally
{
Workers.BeforeStateCommit = null;
}
// One transaction for every state; nothing stored was acked before it committed.
var (states, ackedBefore) = Assert.Single(commits);
Assert.Equal(messages.Count - 1, states);
Assert.Equal(0, ackedBefore);
Assert.Equal("term", Outcome(garbage));
Assert.All(Enumerable.Range(0, messages.Count).Where(i => i != garbage), i => Assert.Equal("ack", Outcome(i)));
var stored = await JobsAsync(runId);
Assert.All(stored.Take(10), j =>
{
Assert.Equal(JobState.Succeeded, j.State);
Assert.Equal(0, j.ExitCode);
Assert.Equal(t0, j.StartedUtc);
Assert.Equal(t0.AddSeconds(30), j.CompletedUtc);
});
Assert.All(stored.Skip(10).Take(5), j => Assert.Equal(JobState.Failed, j.State));
Assert.All(stored.Skip(15), j =>
{
Assert.Equal(JobState.Running, j.State);
Assert.Null(j.CompletedUtc);
});
// The run's numbers, as the console reads them.
var detail = (await client.GetFromJsonAsync<ExecutionDetailDto>(ApiRoutes.For.Execution(runId), JsonDefaults.Options))!;
Assert.Equal((20, 10, 5, 5, 0), (detail.Counts!.Targets, detail.Counts.Succeeded, detail.Counts.Failed, detail.Counts.Running, detail.Counts.Pending));
}
[Fact]
public async Task AFinalStateIsNeverReplacedAndTheFirstStartIsKept()
{
var (runId, jobs, _) = await StartRunAsync("forward", 2);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-5);
// Out of order across batches: the final state first, then its Running, then a second final state.
await Workers.StoreJobStatesAsync([Message(0, State(jobs[0], JobState.Running, t0)), Message(1, State(jobs[1], JobState.Running, t0))], CancellationToken.None);
await Workers.StoreJobStatesAsync([Message(2, State(jobs[0], JobState.Succeeded, t0.AddSeconds(5), 0))], CancellationToken.None);
await Workers.StoreJobStatesAsync(
[
Message(3, State(jobs[0], JobState.Running, t0.AddSeconds(6))),
Message(4, State(jobs[0], JobState.Failed, t0.AddSeconds(7), 9)),
Message(5, State(jobs[1], JobState.Running, t0.AddSeconds(8))),
Message(6, new JobStatePayload(jobs[1].JobId, jobs[1].ClientId, JobState.Dispatched, null, t0.AddSeconds(9), null)),
], CancellationToken.None);
var stored = await JobsAsync(runId);
Assert.Equal((JobState.Succeeded, 0, t0, t0.AddSeconds(5)), (stored[0].State, stored[0].ExitCode, stored[0].StartedUtc, stored[0].CompletedUtc));
Assert.Equal((JobState.Running, t0), (stored[1].State, stored[1].StartedUtc));
Assert.All(Enumerable.Range(0, 7), i => Assert.Equal("ack", Outcome(i)));
}
[Fact]
public async Task AFinalStateInABatchCarriesItsRestartButKeepsOneAlreadyStored()
{
var (runId, jobs, _) = await StartRunAsync("restart-batch", 3);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-1);
// The restart request got there first for the third job (Restarting is newer than Requested).
await fixture.WithDbAsync(db => db.Jobs.Where(j => j.JobId == jobs[2].JobId).ExecuteUpdateAsync(s => s
.SetProperty(j => j.RestartState, JobRestartState.Restarting)
.SetProperty(j => j.RestartDelaySeconds, 30)
.SetProperty(j => j.RestartMessage, "from the request")));
await Workers.StoreJobStatesAsync(
[
Message(0, new JobStatePayload(jobs[0].JobId, jobs[0].ClientId, JobState.Succeeded, 3010, t0, "done",
Restart: JobRestartState.Requested, RestartDelaySeconds: 120, RestartMessage: new string('m', 600))),
Message(1, new JobStatePayload(jobs[1].JobId, jobs[1].ClientId, JobState.Succeeded, 3010, t0, "done",
Restart: JobRestartState.Refused, RestartMessage: "Restart refused: AllowRestart is off on this device.")),
Message(2, new JobStatePayload(jobs[2].JobId, jobs[2].ClientId, JobState.Succeeded, 0, t0, "done",
Restart: JobRestartState.Requested, RestartDelaySeconds: 5, RestartMessage: "from the state")),
], CancellationToken.None);
var stored = (await JobsAsync(runId)).ToDictionary(j => j.JobId);
var requested = stored[jobs[0].JobId];
Assert.Equal((JobState.Succeeded, JobRestartState.Requested, 120, 500), (requested.State, requested.RestartState, requested.RestartDelaySeconds, requested.RestartMessage!.Length));
Assert.Equal((JobState.Succeeded, JobRestartState.Refused), (stored[jobs[1].JobId].State, stored[jobs[1].JobId].RestartState));
var kept = stored[jobs[2].JobId];
Assert.Equal((JobState.Succeeded, JobRestartState.Restarting, 30, "from the request"), (kept.State, kept.RestartState, kept.RestartDelaySeconds, kept.RestartMessage));
}
[Fact]
public async Task AFailedBatchKeepsNothingAndIsStoredOneStateAtATime()
{
var (runId, jobs, _) = await StartRunAsync("recover", 6);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-1);
var messages = jobs.Select((job, i) => Message(i, State(job, JobState.Succeeded, t0, i))).ToList();
var poisoned = jobs[2].JobId;
var batches = new List<int>();
// The batch fails (as the database might); alone, every state but one goes in.
Workers.BeforeStateCommit = states =>
{
batches.Add(states.Count);
if (states.Count > 1 || states[0].JobId == poisoned)
{
throw new InvalidOperationException("the database said no");
}
};
try
{
await Workers.StoreJobStatesAsync(messages, CancellationToken.None);
}
finally
{
Workers.BeforeStateCommit = null;
}
Assert.Equal([6, 1, 1, 1, 1, 1, 1], batches);
Assert.Equal("nak", Outcome(2));
Assert.All(Enumerable.Range(0, 6).Where(i => i != 2), i => Assert.Equal("ack", Outcome(i)));
var stored = await JobsAsync(runId);
Assert.Equal(JobState.Dispatched, stored.Single(j => j.JobId == poisoned).State);
Assert.All(stored.Where(j => j.JobId != poisoned), j => Assert.Equal(JobState.Succeeded, j.State));
// Redelivered (nak), it is stored like any other.
await Workers.StoreJobStatesAsync([Message(10, State(jobs[2], JobState.Succeeded, t0, 2))], CancellationToken.None);
Assert.Equal("ack", Outcome(10));
var poison = (await JobsAsync(runId)).Single(j => j.JobId == poisoned);
Assert.Equal((JobState.Succeeded, 2), (poison.State, poison.ExitCode));
}
[Fact]
public async Task TheErrorAnAgentReportsIsKeptAndOldAgentsLeaveItEmpty()
{
var (runId, jobs, _) = await StartRunAsync("errors", 2);
var old = JsonDefaults.Deserialize<JobStatePayload>(
$$"""{"jobId":"{{jobs[1].JobId}}","clientId":"{{jobs[1].ClientId}}","state":"failed","exitCode":1,"timestampUtc":"2026-01-01T00:00:00Z","message":"m"}""")!;
await Workers.StoreJobStatesAsync(
[
Message(0, new JobStatePayload(
jobs[0].JobId, jobs[0].ClientId, JobState.Failed, 5, DateTimeOffset.UtcNow, "summary", "System.IO.IOException", "Id", new string('m', 3000))),
Message(1, old),
], CancellationToken.None);
var stored = await JobsAsync(runId);
Assert.Equal(5, stored[0].ExitCode);
Assert.Equal("System.IO.IOException", stored[0].ErrorType);
Assert.Equal("Id", stored[0].ErrorId);
Assert.Equal(2000, stored[0].ErrorMessage!.Length);
Assert.Equal(JobState.Failed, stored[1].State);
Assert.Null(stored[1].ErrorType);
Assert.Null(stored[1].ErrorMessage);
}
}