feat(jobs): progress detail contract and a 2/s publish throttle

Mass passes need to say what they do now (photo x of y, sequence n of m) without
slowing down. This adds the contract and the engine side; handlers and displays
follow in their own parcels.

- Core: JobDetail (step, item, item x of y, part n of m with unit), JobStep and
  JobPartUnit appended-only and stored by kebab name; Job.Detail.
- Protocol: JobDetailDto, appended as JobDto.Detail, JobProgressEvent.Detail and
  NodeProgress.Detail, so older peers ignore it and newer ones fall back.
- Data: JobContext keeps a detail across reports (ReportAsync with a detail,
  ReportItemAsync without allocating, CheckpointAsync with a detail) and publishes
  at most once per ProgressInterval (500 ms on the engine's TimeProvider), at once
  for the first report, a new step or a completed count; a dropped report costs no
  allocation or lock, and the persist that falls due publishes what it saves.
  Persist stays at most every 5 s. JobWire maps steps, units and details; an
  unknown name reads as none.
- Migration 0011 adds jobs.progress_detail (nullable JSON text); an unreadable
  cell reads as no detail. Lists return it.
- Server: ProgressGate (500 ms per job, step-change and completion bypass)
  shared by the engine host and render nodes; node details are stored and
  broadcast, an older node without one still works.

Refs #65

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 13:02:59 +01:00
1 parent 58ed737310
commit ee9505df22
20 files changed
+968 -63

No files matched your search

@@ -0,0 +1,225 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
/// <summary>
/// How a running job's progress goes out (owner review 5, #65): at most twice a second, at once for the run's first report,
/// a new step and a completed count, and with the persist that falls due when the last report was dropped; saved at most
/// every checkpoint interval and at each checkpoint, with its detail.
/// </summary>
[Category("jobs")]
public sealed class JobContextProgressTests(TestContext context)
{
private static readonly TimeSpan Tick = TimeSpan.FromMilliseconds(10);
[Test]
public async Task AHundredReportsInASecondGoOutAtMostThreeTimes()
{
await using var run = await StartAsync();
for (var i = 1; i <= 100; i++)
{
await run.Context.ReportAsync(i, 1000);
run.Time.Advance(Tick);
}
Assert.True(run.Published.Count <= 3, $"{run.Published.Count} publishes");
// The first at once, then one per half second.
Assert.SequenceEqual([1L, 51L], run.Published.Select(p => p.Done));
}
[Test]
public async Task ANewStepAndACompletedCountGoOutAtOnce()
{
await using var run = await StartAsync();
var index = new JobDetail(JobStep.Index, "2024/Harbour sunset", 1, 5, 1, 2, JobPartUnit.Folder);
await run.Context.ReportAsync(1, 10, new JobDetail(JobStep.List));
run.Time.Advance(Tick);
await run.Context.ReportAsync(2, 10, new JobDetail(JobStep.List));
run.Time.Advance(Tick);
await run.Context.ReportAsync(3, 10, index);
run.Time.Advance(Tick);
await run.Context.ReportItemAsync(4, 10, 2, 5);
run.Time.Advance(Tick);
await run.Context.ReportAsync(10, 10);
run.Time.Advance(Tick);
await run.Context.ReportAsync(10, 10);
Assert.SequenceEqual([1L, 3L, 10L], run.Published.Select(p => p.Done));
Assert.Equal(index, run.Published[1].Detail);
// A report without a detail keeps the last one, with the item counts reported since.
Assert.Equal(index with { ItemDone = 2 }, run.Published[2].Detail);
Assert.Equal(index with { ItemDone = 2 }, run.Context.Detail);
}
[Test]
public async Task ADroppedReportGoesOutWithThePersistThatFallsDue()
{
await using var run = await StartAsync();
await run.Context.ReportAsync(1, 100);
run.Time.Advance(TimeSpan.FromSeconds(4.8));
await run.Context.ReportAsync(2, 100);
Assert.Equal(0L, (await run.StoredAsync()).ProgressDone);
run.Time.Advance(TimeSpan.FromSeconds(0.2));
// Too soon for a publish, but the persist falls due: it shows what it saves.
await run.Context.ReportAsync(3, 100);
Assert.SequenceEqual([1L, 2L, 3L], run.Published.Select(p => p.Done));
Assert.Equal(3L, (await run.StoredAsync()).ProgressDone);
}
[Test]
public async Task ProgressIsSavedAtMostEveryCheckpointIntervalAndAtEachCheckpoint()
{
await using var run = await StartAsync();
for (var i = 1; i <= 50; i++)
{
await run.Context.ReportAsync(i, 100);
run.Time.Advance(TimeSpan.FromMilliseconds(99));
}
Assert.Equal(0L, (await run.StoredAsync()).ProgressDone);
run.Time.Advance(TimeSpan.FromMilliseconds(50));
await run.Context.ReportAsync(51, 100);
Assert.Equal(51L, (await run.StoredAsync()).ProgressDone);
var published = run.Published.Count;
// A checkpoint is saved at once; it goes out as any report would.
run.Time.Advance(Tick);
await run.Context.CheckpointAsync("52", 52, 100);
var stored = await run.StoredAsync();
Assert.Equal((52L, "52"), (stored.ProgressDone, stored.Checkpoint));
Assert.Null(stored.Detail);
Assert.Equal(published, run.Published.Count);
var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 1, 9, 1, 3, JobPartUnit.Sequence);
run.Time.Advance(Tick);
await run.Context.CheckpointAsync("53", 53, 100, verify);
stored = await run.StoredAsync();
Assert.Equal((53L, "53", verify), (stored.ProgressDone, stored.Checkpoint, stored.Detail));
Assert.Equal(verify, run.Published[^1].Detail);
// A checkpoint without a detail keeps it.
run.Time.Advance(Tick);
await run.Context.CheckpointAsync("54", 54, 100);
Assert.Equal(verify, (await run.StoredAsync()).Detail);
}
[Test]
public async Task TheRateIsTheSameUnderThePublishThrottle()
{
await using var run = await StartAsync();
// 100 photos a second for ten seconds, every photo reported.
for (var i = 1; i <= 1000; i++)
{
await run.Context.ReportAsync(i, 2000);
run.Time.Advance(Tick);
}
Assert.True(run.Published.Count <= 22, $"{run.Published.Count} publishes");
var last = run.Published[^1];
Assert.Approximately(100, last.ItemsPerSecond!.Value, 0.5);
Assert.Approximately((2000 - last.Done) / 100.0, last.Eta!.Value.TotalSeconds, 0.1);
}
[Test]
public async Task ItemCountsWithoutADetailAreAPhotoPass()
{
await using var run = await StartAsync();
Assert.Null(run.Context.Detail);
await run.Context.ReportItemAsync(1, 10, 3, 9);
Assert.Equal(new JobDetail(JobStep.Process, null, 3, 9), run.Context.Detail);
Assert.Equal(run.Context.Detail, run.Published.Single().Detail);
// A plain report keeps the detail and drops the old free text.
await run.Context.ReportAsync(2, 10, "IMG_0001.CR3");
await run.Context.ReportAsync(3, 10);
Assert.Null(run.Context.Message);
Assert.Equal(new JobDetail(JobStep.Process, null, 3, 9), run.Context.Detail);
}
[Test]
public async Task ADroppedReportAllocatesNothing()
{
await using var run = await StartAsync();
var thumbs = new JobDetail(JobStep.Thumbs, "Harbour sunset", 0, 3600, 2, 7, JobPartUnit.Sequence);
await run.Context.ReportAsync(1, 1_000_000, thumbs);
var job = run.Context;
var dropped = 0;
for (var i = 0; i < 200; i++) dropped += Drop(job, thumbs, i) ? 1 : 0;
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 20_000; i++) dropped += Drop(job, thumbs, i) ? 1 : 0;
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.Equal(20_200, dropped);
Assert.Equal(0L, allocated);
Assert.Count(1, run.Published);
}
[Test]
public async Task TheEngineSendsAndSavesTheDetail()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
var verify = new JobDetail(JobStep.Verify, "Harbour sunset", 5, 9, 1, 2, JobPartUnit.Sequence);
var handler = new CallbackHandler(JobKind.Verify, async c =>
{
await c.CheckpointAsync("1", 1, 2, verify);
await c.ReportAsync(2, 2);
});
await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "t" });
var published = new List<JobProgressInfo>();
engine.Progress += p =>
{
lock (published) published.Add(p);
};
await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(JobKind.Verify, [Guid.NewGuid()], cancellationToken: context.Cancellation);
var until = DateTime.UtcNow.AddSeconds(15);
Job? done = null;
while (DateTime.UtcNow < until && (done = await db.Jobs.GetAsync(job.Id, context.Cancellation))?.State != JobState.Done) await Task.Delay(20, context.Cancellation);
Assert.Equal(JobState.Done, done?.State);
Assert.Equal(verify, done!.Detail);
lock (published) Assert.SequenceEqual([verify, verify], published.Select(p => p.Detail));
}
/// <summary>One report dropped by the throttle: no new step, no completed count, no time passed.</summary>
private static bool Drop(JobContext job, JobDetail detail, int i)
{
var item = job.ReportItemAsync(2 + i, 1_000_000, i, 3600);
var full = job.ReportAsync(3 + i, 1_000_000, detail);
return item.IsCompletedSuccessfully && full.IsCompletedSuccessfully;
}
private async Task<Run> StartAsync()
{
var time = new ManualTime();
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(), "jobs.db")), context.Cancellation);
var engine = new JobEngine(db, [], new JobEngineOptions { WorkerId = "t", Time = time });
var run = new Run(db, engine, time);
engine.Progress += run.Published.Add;
await db.Jobs.EnqueueAsync(new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Queued, Created = DateTimeOffset.UtcNow },
context.Cancellation);
var claimed = Assert.NotNull(await db.Jobs.ClaimNextAsync("t", null, context.Cancellation));
run.Context = new JobContext(engine, claimed, context.Cancellation);
return run;
}
private sealed class Run(ChronosDatabase db, JobEngine engine, ManualTime time) : IAsyncDisposable
{
public ManualTime Time { get; } = time;
public JobContext Context { get; set; } = null!;
public List<JobProgressInfo> Published { get; } = [];
public async Task<Job> StoredAsync() => (await db.Jobs.GetAsync(Context.Job.Id))!;
public async ValueTask DisposeAsync()
{
await engine.DisposeAsync();
await db.DisposeAsync();
}
}
private sealed class CallbackHandler(JobKind kind, Func<JobContext, Task> run) : IJobHandler
{
public JobKind Kind => kind;
public Task RunAsync(JobContext context) => run(context);
}
}
@@ -1,5 +1,6 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
@@ -29,4 +30,72 @@ public sealed class JobWireTests
Assert.Equal(names.Count, names.Distinct(StringComparer.Ordinal).Count());
Assert.False(JobWire.TryParseKind("workspace-teleport", out _));
}
/// <summary>Steps and units are stored and sent by name, appended only: these values and names are pinned once shipped.</summary>
[Theory]
[Case(JobStep.None, 0, "none")]
[Case(JobStep.List, 1, "list")]
[Case(JobStep.Verify, 4, "verify")]
[Case(JobStep.CopyPhoto, 11, "copy-photo")]
[Case(JobStep.CopyOriginal, 13, "copy-original")]
[Case(JobStep.FollowUps, 22, "follow-ups")]
[Case(JobStep.Process, 23, "process")]
public void StepsKeepTheirValueAndName(JobStep step, int value, string name)
{
Assert.Equal(value, (int)step);
Assert.Equal(name, JobWire.Step(step));
Assert.True(JobWire.TryParseStep(name, out var parsed), name);
Assert.Equal(step, parsed);
}
[Test]
public void EveryStepAndUnitHasItsOwnName()
{
var steps = Enum.GetValues<JobStep>().Select(JobWire.Step).ToList();
Assert.Equal(steps.Count, steps.Distinct(StringComparer.Ordinal).Count());
Assert.SequenceEqual(["none", "sequence", "folder", "render", "entry", "step"], Enum.GetValues<JobPartUnit>().Select(JobWire.PartUnit));
Assert.False(JobWire.TryParseStep("teleport", out _));
Assert.False(JobWire.TryParsePartUnit(null, out _));
}
[Test]
public void ADetailCrossesTheWireAndBack()
{
var detail = new JobDetail(JobStep.CopyOriginal, "2024/2024-09-27 Harbour sunset", 1240, 3600, 12, 340, JobPartUnit.Folder);
var dto = JobWire.Detail(detail)!;
Assert.Equal(new JobDetailDto("copy-original", "2024/2024-09-27 Harbour sunset", 1240, 3600, 12, 340, "folder"), dto);
Assert.Equal(detail, JobWire.FromDto(dto));
// A unit of none is left out; nothing is none.
Assert.Null(JobWire.Detail(new JobDetail(JobStep.Backup))!.PartUnit);
Assert.Null(JobWire.Detail(null));
Assert.Null(JobWire.FromDto((JobDetailDto?)null));
// A newer peer's step or unit reads as none and its counts stay; nonsense counts read as 0.
Assert.Equal(new JobDetail(JobStep.None, "x", 0, 9, 2, 0), JobWire.FromDto(new JobDetailDto("teleport", "x", -4, 9, 2, -1, "galaxy")));
Assert.Equal(new JobDetail(JobStep.None), JobWire.FromDto(new JobDetailDto(null!)));
}
[Test]
public void AnItemIsCutToItsLongestLengthWithoutSplittingACharacter()
{
var plain = new string('a', JobDetail.MaxItemLength + 40);
Assert.Equal(JobDetail.MaxItemLength, new JobDetail(JobStep.Index, plain).Item!.Length);
// A pair whose high half would be the last kept character goes whole.
var emoji = new string('a', JobDetail.MaxItemLength - 1) + "\U0001F4F7" + "tail";
var cut = new JobDetail(JobStep.Index, emoji).Item!;
Assert.Equal(JobDetail.MaxItemLength - 1, cut.Length);
Assert.False(char.IsHighSurrogate(cut[^1]));
Assert.Equal(JobDetail.MaxItemLength, (new JobDetail(JobStep.Index) with { Item = plain }).Item!.Length);
Assert.Equal(JobDetail.MaxItemLength, JobWire.FromDto(new JobDetailDto("index", plain))!.Item!.Length);
Assert.Equal("short", new JobDetail(JobStep.Index, "short").Item);
}
[Test]
public void AServerJobBringsItsDetail()
{
var dto = new JobDto(Guid.NewGuid(), "verify", [], "Archive", "paused", "normal", 4, 10, null, null, null, null, 1, null, DateTimeOffset.UtcNow, null, null,
Detail: new JobDetailDto("verify", "Harbour sunset", 812, 2400, 3, 41, "sequence"));
Assert.Equal(new JobDetail(JobStep.Verify, "Harbour sunset", 812, 2400, 3, 41, JobPartUnit.Sequence), JobWire.FromDto(dto)!.Detail);
Assert.Null(JobWire.FromDto(dto with { Detail = null })!.Detail);
}
}
@@ -139,6 +139,24 @@ public abstract class MigrationTests(TestContext context) : RepositoryTest(conte
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT bytes FROM render_copies WHERE path = $1", ["C:/Videos/b"], Ct));
}
[Test]
public async Task TheProgressDetailColumnJoinsAnIndexOfTheVideosRelease()
{
var database = await OpenDatabaseAsync();
var all = MigrationRunner.Load(Dialect);
Assert.Equal(10, await MigrationRunner.MigrateAsync(database, [.. all.Where(m => m.Version <= 10)], Ct));
var id = Guid.CreateVersion7();
await using (var session = await database.OpenAsync(Ct))
await session.ExecuteAsync("INSERT INTO jobs (id, kind, state, priority, created) VALUES ($1, $2, $3, $4, $5)",
[id, (int)JobKind.Verify, (int)JobState.Paused, (int)JobPriority.Normal, DateTimeOffset.UtcNow], Ct);
Assert.Equal(11, all.Single(m => m.Name == "job_progress_detail").Version);
Assert.Equal(all[^1].Version, await MigrationRunner.MigrateAsync(database, Ct));
await using var after = await database.OpenAsync(Ct);
// No backfill: a job of 1.0 has no detail.
Assert.Equal(1L, await after.ScalarAsync<long>("SELECT count(*) FROM jobs WHERE id = $1 AND progress_detail IS NULL", [id], Ct));
}
[Test]
public async Task AppliesOnlyPendingMigrations()
{
@@ -30,12 +30,52 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c
Started = TestData.Now.AddMinutes(1),
Finished = TestData.Now.AddMinutes(2),
ScheduleId = Guid.CreateVersion7(),
Detail = new JobDetail(JobStep.Encode, "Harbour sunset", 5, 10, 1, 2, JobPartUnit.Render),
};
await db.Jobs.EnqueueAsync(job, Ct);
var read = Assert.NotNull(await db.Jobs.GetAsync(job.Id, Ct));
Assert.SequenceEqual(job.TargetIds, read.TargetIds);
Assert.Equal(job with { TargetIds = read.TargetIds }, read);
Assert.Null((await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!.ScheduleId);
var plain = (await db.Jobs.GetAsync((await EnqueueAsync(db, TestData.Job())).Id, Ct))!;
Assert.Null(plain.ScheduleId);
Assert.Null(plain.Detail);
}
[Test]
public async Task TheProgressDetailIsSavedWithTheProgressAndListedWithTheJob()
{
var db = await OpenChronosAsync();
var job = TestData.Job(JobKind.Verify);
await db.Jobs.EnqueueAsync(job, Ct);
await db.Jobs.ClaimNextAsync("w", cancellationToken: Ct);
var detail = new JobDetail(JobStep.Verify, "Harbour sunset · 2024", 812, 2400, 3, 41, JobPartUnit.Sequence);
Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 4, 10, null, null, "cursor:4", null, detail, Ct));
Assert.Equal(detail, (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
// Lists read it too: a paused job tells where it stopped.
Assert.SequenceEqual([detail], (await db.Jobs.ListBriefAsync(JobState.Running, null, cancellationToken: Ct)).Items.Select(j => j.Detail));
// Without a detail the column is cleared; a node's progress keeps or replaces it.
Assert.True(await db.Jobs.UpdateProgressAsync(job.Id, 5, 10, null, null, "cursor:5", null, Ct));
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
var node = new JobDetail(JobStep.Encode, null, 120, 3600);
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 6, 10, null, null, null, node, Ct));
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 7, 10, null, null, "line", Ct));
Assert.Equal(node, (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
Assert.True(await db.Jobs.UpdateNodeProgressAsync(job.Id, "w", 8, 10, null, null, null, null, Ct));
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
// A cell this build cannot read is no detail, never an error.
foreach (var unreadable in new[] { "not json", "42", "[]", "{\"step\": 7}" })
{
await using (var session = await db.Database.OpenAsync(Ct))
await session.ExecuteAsync("UPDATE jobs SET progress_detail = $1 WHERE id = $2", [unreadable, job.Id], Ct);
Assert.Null((await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
}
// One of a newer build: its step and unit read as none, the counts stay.
await using (var session = await db.Database.OpenAsync(Ct))
await session.ExecuteAsync("UPDATE jobs SET progress_detail = $1 WHERE id = $2",
["""{"step":"teleport","itemDone":3,"itemTotal":9,"part":2,"parts":4,"partUnit":"galaxy","future":true}""", job.Id], Ct);
Assert.Equal(new JobDetail(JobStep.None, null, 3, 9, 2, 4), (await db.Jobs.GetAsync(job.Id, Ct))!.Detail);
}
[Test]