feat(jobs): every job handler reports a structured progress detail

The job list showed a bar and a free-text line that each handler worded
its own way. Each handler now reports its step, the item it is on, photo
x of y and sequence/folder/output/step n of m through the P2.1 JobContext
detail. Clients can word and lay that out themselves, and the 2/s
throttle keeps the cost low: counts within a step go through
ReportItemAsync, which allocates nothing.

- scan: List, then Index (folder n of m, photo x of y as an adopted or
  reconciled folder is read) or Check, then FollowUps
- verify, thumbs, proxies, deep analysis: photo x of y of sequence n of m;
  light analysis: sequence n of m; a thumbnail/proxy checkpoint carries
  the frame count it saves
- convert: Verify (resume), Convert photo x of y, Replace; reorganize:
  step n of m with the title; import: the file being copied, photo x of y
- maintenance: the step key, step n of 5, then Check; duplicates, orphans
  and backup run with no count; cleanup names step n of m; empty trash:
  entry n of m
- render (local, workspace, render node): Analyse, Encode (frames of the
  last output, output n of m in a batch), Verify; sync, video copy,
  workspace copy/send/move: Upload/Download/CopyProxy/CopyOriginal/
  CopyVideo/Reorganize with their items and counts

The detail carries keys and names only, never localized text. The
existing Message strings stay for clients that still show them.

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:38:05 +01:00
1 parent ee9505df22
commit 45e6911082
31 files changed
+759 -119

No files matched your search

@@ -0,0 +1,180 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Jobs;
using Chronos.Data.Tests.Jobs;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Archiving;
/// <summary>
/// What the archive jobs say they are doing (owner review 5, #65): the step, the item, photo x of y and sequence, folder
/// or step n of m, sent as the job's progress detail; no localized text in it.
/// </summary>
[Category("archive")]
public sealed class ArchiveProgressDetailTests(TestContext context)
{
private static void Populate(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "a"), Start, 4);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "b"), Start.AddDays(1), 3, firstSeed: 50);
}
private static async Task<(DetailRecorder Recorder, JobEngine Engine)> StartAsync(ArchiveFixture fx)
{
var recorder = new DetailRecorder();
var engine = recorder.Engine(fx.Db, fx.Service.CreateJobHandlers());
await engine.StartAsync(fx.Ct);
return (recorder, engine);
}
private static async Task<Guid> RunAsync(ArchiveFixture fx, JobEngine engine, ArchiveJobRequest request)
{
var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
return job.Id;
}
[Test]
public async Task AScanListsThenIndexesEachNewFolderPhotoByPhotoAndChecksThemOnARescan()
{
await using var fx = await CreateAsync(context);
Populate(fx);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var first = await RunAsync(fx, engine, ArchiveJobs.Scan(fx.Archive));
var details = recorder.Details(first);
Assert.Equal(JobStep.List, details[0].Step);
var index = details.Where(d => d.Step == JobStep.Index).ToList();
Assert.Equal(new JobDetail(JobStep.Index, "a", 0, 0, 1, 2, JobPartUnit.Folder), index[0]);
// Photo after photo inside an adopted folder, then the next folder.
Assert.SequenceEqual([1L, 2L, 3L, 4L], index.Where(d => d.Item == "a" && d.ItemTotal > 0).Select(d => d.ItemDone));
Assert.True(index.Where(d => d.ItemTotal > 0).All(d => d.ItemTotal == (d.Item == "a" ? 4 : 3)));
Assert.SequenceEqual([1, 2], index.Select(d => d.Part).Distinct());
Assert.True(index.All(d => d.Parts == 2 && d.PartUnit == JobPartUnit.Folder));
Assert.Equal(JobStep.Index, recorder.Steps(first)[1]);
// Nothing changed: each folder is checked, folder n of m, and nothing is indexed.
var again = await RunAsync(fx, engine, ArchiveJobs.Scan(fx.Archive));
Assert.SequenceEqual([JobStep.List, JobStep.Check], recorder.Steps(again));
var check = recorder.Details(again).Where(d => d.Step == JobStep.Check).ToList();
Assert.SequenceEqual([("a", 1), ("b", 2)], check.Select(d => (d.Item!, d.Part)));
Assert.True(check.All(d => d.Parts == 2 && d.PartUnit == JobPartUnit.Folder));
}
[Test]
public async Task AVerifyCountsThePhotosOfEachSequence()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Verify(fx.Archive));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Verify && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([(1, 1L), (1, 2L), (1, 3L), (1, 4L), (2, 1L), (2, 2L), (2, 3L)], details.Select(d => (d.Part, d.ItemDone)));
Assert.SequenceEqual([4L, 3L], details.GroupBy(d => d.Part).Select(g => g.Max(d => d.ItemTotal)));
Assert.True(details.All(d => !string.IsNullOrEmpty(d.Item)));
}
[Test]
public async Task AThumbnailPassReportsEachFrameOfEachSequence()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var ids = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Select(l => l.Id).ToList();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Thumbnails(ids));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Thumbs && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([1, 2], details.Select(d => d.Part).Distinct());
// Every frame of a sequence goes out, up to its last.
Assert.SequenceEqual([(1, 4L), (2, 3L)], details.GroupBy(d => d.Part).Select(g => (g.Key, g.Max(d => d.ItemDone))));
Assert.True(details.GroupBy(d => d.Part).All(g => g.Count() >= g.Max(d => d.ItemTotal)));
}
[Test]
public async Task MaintenanceNamesItsStepsInOrder()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.Maintenance(fx.Archive));
var details = recorder.Details(id);
var steps = details.Where(d => d.Step == JobStep.Maintenance).ToList();
Assert.SequenceEqual(["leases", "temp", "packs", "duplicates", "vacuum"], steps.Select(d => d.Item!));
Assert.SequenceEqual([1, 2, 3, 4, 5], steps.Select(d => d.Part));
Assert.True(steps.All(d => d.Parts == 5 && d.PartUnit == JobPartUnit.Step));
Assert.SequenceEqual([JobStep.Maintenance, JobStep.Check], recorder.Steps(id));
}
[Test]
public async Task DuplicatesAndOrphansRunWithoutACount()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
foreach (var request in new[] { ArchiveJobs.Duplicates(fx.Archive), ArchiveJobs.Orphans(fx.Archive) })
{
var id = await RunAsync(fx, engine, request);
// Every report until the one that completes it.
var reports = recorder.Of(id);
var running = reports.TakeWhile(p => p.Total == 0 || p.Done < p.Total).ToList();
Assert.NotEmpty(running);
Assert.True(running.All(p => p.Detail == new JobDetail(JobStep.Check) && p.Total == 0),
$"{request.Kind}: {string.Join("; ", reports.Select(p => $"{p.Done}/{p.Total} {p.Detail}"))}");
}
}
[Test]
public async Task ABackupRunsWithoutACountAndACleanupNamesItsSteps()
{
await using var fx = await CreateAsync(context);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var backup = await RunAsync(fx, engine, ArchiveJobs.Backup(keep: 1));
var reports = recorder.Of(backup);
var running = reports.TakeWhile(p => p.Total == 0 || p.Done < p.Total).ToList();
Assert.NotEmpty(running);
Assert.True(running.All(p => p.Detail == new JobDetail(JobStep.Backup) && p.Total == 0), string.Join("; ", reports.Select(p => $"{p.Done}/{p.Total} {p.Detail}")));
var cleanup = await RunAsync(fx, engine, ArchiveJobs.Cleanup(fx.Archive, [CleanupSteps.JobHistory, CleanupSteps.Audit], 0));
var steps = recorder.Details(cleanup);
Assert.SequenceEqual([(CleanupSteps.JobHistory, 1), (CleanupSteps.Audit, 2)], steps.Select(d => (d.Item!, d.Part)));
Assert.True(steps.All(d => d.Step == JobStep.Cleanup && d.Parts == 2 && d.PartUnit == JobPartUnit.Step));
}
[Test]
public async Task EmptyingTheTrashCountsItsEntries()
{
await using var fx = await CreateAsync(context);
Populate(fx);
await fx.ScanAsync();
var ids = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Select(l => l.Id).ToList();
await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync(ids, null, fx.Ct), null, null, fx.Ct);
var empty = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, null, fx.Ct);
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var id = await RunAsync(fx, engine, ArchiveJobs.EmptyTrash(fx.Archive, empty));
var details = recorder.Details(id);
Assert.True(details.All(d => d.Step == JobStep.Erase && d.PartUnit == JobPartUnit.Entry && d.Parts == 2), string.Join("; ", details));
Assert.SequenceEqual([1, 2], details.Select(d => d.Part));
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
}
}
@@ -366,7 +366,7 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The first verify of photos a scan adopted hashes them all; a thumbnail pass records a preview-only frame meanwhile.
var recorded = false;
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (_, _) =>
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async _ =>
{
if (recorded) return;
recorded = true;
@@ -399,7 +399,7 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The verify finds the file missing, and an upload puts it back before the verify writes what it found.
var checkedFrames = 0;
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (_, _) =>
var report = await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async _ =>
{
if (++checkedFrames != 2) return;
Assert.True((await fx.Service.Ingest.CommitAsync(Upload(fx.Stage(Start.AddSeconds(10), seed: 2)), fx.Ct)).Repaired, "repaired");
@@ -570,9 +570,9 @@ public abstract class PartialRowWriterTests(TestContext context) : DatabaseTest(
// The server's PATCH takes the row as the last photo is checked, and commits while the verify stamps the sequence.
Task? commit = null;
await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async (done, total) =>
await fx.Service.Verifier.VerifyAsync(fx.Archive, [sequence.Id], default, (_, _, _) => ValueTask.CompletedTask, async p =>
{
if (done < total || commit is not null) return;
if (p.BytesDone < p.BytesTotal || commit is not null) return;
var tx = await fx.Db.BeginAsync(fx.Ct);
await tx.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = """{"heroFrame":1}""" }, sequence.SettingsVersion, fx.Ct);
commit = CommitLaterAsync(tx, fx.Ct);
@@ -0,0 +1,62 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.Data.Tests.Jobs;
/// <summary>
/// Every progress report a job engine publishes, kept to tell which details a handler sent and in what order (owner review
/// 5, #65). The engine it records has no publish throttle (<see cref="Options"/>), so each report a handler makes goes out.
/// </summary>
internal sealed class DetailRecorder
{
private readonly List<JobProgressInfo> _published = [];
/// <summary>A started engine's options that publish every report: one worker, fast polls and checkpoints, no progress interval.</summary>
public static JobEngineOptions Options(string worker = "detail") => new()
{
Workers = 1,
WorkerId = worker,
PollInterval = TimeSpan.FromMilliseconds(50),
CheckpointInterval = TimeSpan.FromMilliseconds(50),
ProgressInterval = TimeSpan.Zero,
};
/// <summary>A new engine with <paramref name="handlers"/>, recorded, not started.</summary>
public JobEngine Engine(ChronosDatabase db, IEnumerable<IJobHandler> handlers, string worker = "detail")
{
var engine = new JobEngine(db, [.. handlers], Options(worker));
engine.Progress += p =>
{
lock (_published) _published.Add(p);
};
return engine;
}
/// <summary>The reports of <paramref name="jobId"/> in the order they went out.</summary>
public IReadOnlyList<JobProgressInfo> Of(Guid jobId)
{
lock (_published) return [.. _published.Where(p => p.JobId == jobId)];
}
/// <summary>The details of <paramref name="jobId"/>, without repeats of the one before.</summary>
public IReadOnlyList<JobDetail> Details(Guid jobId)
{
var details = new List<JobDetail>();
foreach (var report in Of(jobId))
{
if (report.Detail is { } detail && (details.Count == 0 || details[^1] != detail)) details.Add(detail);
}
return details;
}
/// <summary>The steps of <paramref name="jobId"/> in order, each once in a row.</summary>
public IReadOnlyList<JobStep> Steps(Guid jobId)
{
var steps = new List<JobStep>();
foreach (var detail in Details(jobId))
{
if (steps.Count == 0 || steps[^1] != detail.Step) steps.Add(detail.Step);
}
return steps;
}
}
@@ -0,0 +1,82 @@
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Tests.Jobs;
using Chronos.Testing;
namespace Chronos.Data.Tests.Processing;
/// <summary>What the analysis and render jobs say they are doing (owner review 5, #65), as the job's progress detail.</summary>
[Category("processing")]
public sealed class ProcessingProgressDetailTests(TestContext context)
{
private const int Frames = 12;
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
private static async Task<(DetailRecorder Recorder, JobEngine Engine)> StartAsync(ProcessingFixture fx)
{
var recorder = new DetailRecorder();
var engine = recorder.Engine(fx.Db, fx.Processing.CreateJobHandlers());
await engine.StartAsync(fx.Ct);
return (recorder, engine);
}
private static async Task<Guid> RunAsync(ProcessingFixture fx, JobEngine engine, ArchiveJobRequest request)
{
var job = await engine.EnqueueAsync(request, cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
return job.Id;
}
[Test]
public async Task AnAnalysisNamesEachSequenceAndADeepOneCountsItsPhotos()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var first = await fx.AddAsync(Scene(), "First");
var second = await fx.AddAsync(Scene(), "Second");
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var light = await RunAsync(fx, engine, ProcessingJobs.LightAnalysis([first.Id, second.Id], "both"));
var details = recorder.Details(light);
Assert.True(details.All(d => d.Step == JobStep.Analyse && d.PartUnit == JobPartUnit.Sequence && d.Parts == 2 && d.ItemTotal == 0), string.Join("; ", details));
Assert.SequenceEqual([(1, first.DisplayTitle), (2, second.DisplayTitle)], details.Select(d => (d.Part, d.Item!)));
var deep = await RunAsync(fx, engine, ProcessingJobs.DeepAnalysis([first.Id]));
details = recorder.Details(deep);
Assert.True(details.All(d => d.Step == JobStep.Analyse && d.Item == first.DisplayTitle && d.Part == 1 && d.Parts == 1 && d.ItemTotal == Frames),
string.Join("; ", details));
Assert.True(details.Max(d => d.ItemDone) > 0, string.Join("; ", details));
Assert.True(details.All(d => d.ItemDone <= Frames));
}
[Test]
public async Task ARenderPreparesEncodesThenVerifiesWithoutTextInTheDetail()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var (recorder, engine) = await StartAsync(fx);
await using var _ = engine;
var mjpeg = new ExportSettings
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
var id = await RunAsync(fx, engine, ProcessingJobs.Render(sequence, mjpeg, 96, 64));
Assert.SequenceEqual([JobStep.Analyse, JobStep.Encode, JobStep.Verify], recorder.Steps(id));
var details = recorder.Details(id);
Assert.Equal(new JobDetail(JobStep.Analyse, sequence.DisplayTitle), details[0]);
var encode = details.Where(d => d.Step == JobStep.Encode).ToList();
Assert.True(encode.All(d => d.Item == sequence.DisplayTitle && d.Parts == 0 && d.ItemDone <= d.ItemTotal), string.Join("; ", encode));
Assert.True(encode.Max(d => d.ItemDone) > 0, string.Join("; ", encode));
Assert.Equal(new JobDetail(JobStep.Verify, "clip-MJPEG.avi"), details[^1]);
}
}