fix(server): a verify that hashes photos plans Reorganize again; keep refusals, bound planning

The kept-plan stamp left out whether a planned sequence's photos are hashed.
A verify writes frames.sha256 (and only status and verified_at on the row)
without another frames version, so after verifying never-hashed photos the
same dry run kept answering "verify the sequence first" for up to five
minutes, and its confirmation queued a job certain to fail.

- SequenceRepository.GetStampAsync adds, for every planned sequence, how many
  of its photos have their hash in the index (one grouped query over the
  archive with all, the selected ids in batches of 500 otherwise).
- ReorganizePlanCache keeps a refusal (nested_target, not_found) as it keeps
  a plan: for the same stamp and templates it is the same, and a long plan
  that ends refused after a cut-off is no longer planned again on every retry.
  Failures are still not kept.
- Planning is bounded: at most two plans are made at once, the others wait for
  their turn; a plan still being made 15 minutes after it was asked, let go at
  capacity, or when the server stops is cancelled, and whoever waits for it
  gets 503 plan_dropped. A read that hangs keeps its turn until it returns but
  no longer keeps its waiters.
- The Capacity summary now says what eviction does (the kept plan asked for
  first, else the plan being made asked for first); the stamp, protocol and
  endpoint docs say that a verify hashing photos is a change the plan reads.
- Tests: a scan's photos, verified, are planned again and renamed by the job;
  the stamp follows hashes of planned photos only; refusals kept, failures
  not; turns, eviction and deadline of plans being made, a hung read included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 56582df45453fc555e525f19de7de1803204d12c)
This commit is contained in:
Alby96 committed 2026-10-27 19:16:42 +01:00
1 parent c3756d03c9
commit 1fb040afe6
8 files changed
+320 -58

No files matched your search

@@ -32,8 +32,8 @@ public abstract class SequenceStampTests(TestContext context) : RepositoryTest(c
// What the plan does not read: another archive, and the writes of every upload, verify, tag or status change elsewhere.
await db.Sequences.UpsertAsync(TestData.Sequence(other.Id), Ct);
await PhotoAsync(db, ridge, 0);
await PhotoAsync(db, inner, 0);
await VerifyAsync(db, await PhotoAsync(db, ridge, 0, hashed: false));
await VerifyAsync(db, await PhotoAsync(db, inner, 0, hashed: false));
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(ridge.Id, new SequenceEdit { Title = "Ridge at dawn", Notes = "cold" }, null, Ct)).Outcome);
foreach (var id in new[] { roof.Id, ridge.Id })
{
@@ -48,8 +48,10 @@ public abstract class SequenceStampTests(TestContext context) : RepositoryTest(c
async Task ChangedAsync(string what) => Assert.True(seen.Add(await db.Sequences.GetStampAsync(archive.Id, planned, Ct)), what);
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(roof.Id, new SequenceEdit { Title = "Roof at noon" }, null, Ct)).Outcome);
await ChangedAsync("title");
await PhotoAsync(db, roof, 0);
var scanned = await PhotoAsync(db, roof, 0, hashed: false);
await ChangedAsync("photos");
await VerifyAsync(db, scanned);
await ChangedAsync("photos hashed by a verify, which a file template renames");
Assert.Equal(SequenceEditOutcome.Updated, (await db.Sequences.EditAsync(inner.Id, new SequenceEdit { Title = "Inner court" }, null, Ct)).Outcome);
await ChangedAsync("title of a sequence a moving folder would carry");
Assert.True(await db.Sequences.RelocateAsync(ridge.Id, "2026/ridge", null, Ct));
@@ -62,20 +64,40 @@ public abstract class SequenceStampTests(TestContext context) : RepositoryTest(c
Assert.True(await db.Sequences.DeleteAsync(added.Id, Ct));
Assert.Contains(await db.Sequences.GetStampAsync(archive.Id, planned, Ct), seen);
// With every sequence planned, a photo anywhere changes the plan read; a verify still does not.
// With every sequence planned, a photo anywhere changes the plan read, and so does a verify that hashes one; a verify
// that hashes none still does not.
var all = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
Assert.True(await db.Sequences.RecordVerifiedAsync(ridge.Id, SequenceStatus.None, SequenceStatus.None, TestData.Now.AddDays(1), Ct));
Assert.Equal(all, await db.Sequences.GetStampAsync(archive.Id, null, Ct));
await PhotoAsync(db, ridge, 1);
Assert.NotEqual(all, await db.Sequences.GetStampAsync(archive.Id, null, Ct));
var photo = await PhotoAsync(db, ridge, 1, hashed: false);
var uploaded = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
Assert.NotEqual(all, uploaded);
await VerifyAsync(db, photo);
var verified = await db.Sequences.GetStampAsync(archive.Id, null, Ct);
Assert.False(verified == all || verified == uploaded, "a photo hashed");
}
/// <summary>A photo indexed into a sequence, as an upload does: the frame, then the row's counts and frames version.</summary>
private async Task PhotoAsync(ChronosDatabase db, Sequence sequence, int index)
/// <summary>
/// A photo indexed into a sequence, as an upload does, or without its hash, as a scan does: the frame, then the row's
/// counts and frames version.
/// </summary>
private async Task<Frame> PhotoAsync(ChronosDatabase db, Sequence sequence, int index, bool hashed = true)
{
var frame = TestData.Frame(sequence.Id, index);
await db.Frames.BulkInsertAsync([frame with { RelativePath = $"{sequence.Folder}/originals/{frame.FileName}" }], Ct);
frame = frame with { RelativePath = $"{sequence.Folder}/originals/{frame.FileName}", Sha256 = hashed ? frame.Sha256 : null };
await db.Frames.BulkInsertAsync([frame], Ct);
Assert.NotNull(await db.Sequences.RefreshStatsAsync(sequence.Id, Ct));
return frame;
}
/// <summary>What a verify writes once it hashed a photo never hashed: the hash, then the sequence's verify time, and not another frames version.</summary>
private async Task VerifyAsync(ChronosDatabase db, Frame frame)
{
var version = (await db.Sequences.GetAsync(frame.SequenceId, Ct))!.FramesVersion;
var sha256 = TestData.Frame(frame.SequenceId, frame.Index).Sha256;
Assert.Equal(1, await db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frame.Id, FrameFlags.None, sha256)], Ct));
Assert.True(await db.Sequences.RecordVerifiedAsync(frame.SequenceId, SequenceStatus.Verified, SequenceStatus.None, TestData.Now, Ct));
Assert.Equal(version, (await db.Sequences.GetAsync(frame.SequenceId, Ct))!.FramesVersion);
}
}
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
@@ -496,7 +497,8 @@ public sealed class ReorganizeTests(TestContext context)
Directory.CreateDirectory(target);
Assert.Equal(shown.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
// Neither are what the plan does not read: a photo uploaded into another sequence (and the jobs it queues), a verify.
// Neither are what the plan does not read: a photo uploaded into another sequence (and the jobs it queues), a verify
// of photos an upload hashed already.
var versions = (await server.Database.Sequences.GetAsync(other))!.FramesVersion;
await Uploads.UploadAsync(editor, Photo(6), "IMG_0101.JPG", sessionKey: "other");
using (var verify = await admin.PostAsync("/api/v1/archive/verify", null)) await verify.ExpectAsync(HttpStatusCode.Accepted);
@@ -534,6 +536,35 @@ public sealed class ReorganizeTests(TestContext context)
Assert.Equal("moved/2026-09-28 (2)", (await server.Database.Sequences.GetAsync(id))!.Folder);
}
[Test]
public async Task ADryRunPlansAgainOnceAVerifyHashedItsPhotos()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
// Photos copied into the archive's layout by hand and found by a scan: never hashed, they keep their names.
var originals = Path.Combine(server.Options.ArchivePath, "trips", "originals");
Directory.CreateDirectory(originals);
for (var i = 0; i < 2; i++) await File.WriteAllBytesAsync(Path.Combine(originals, $"IMG_{i:0000}.JPG"), Photo(i));
using (var scan = await admin.PostAsync("/api/v1/archive/scan", null)) await scan.ExpectAsync(HttpStatusCode.Accepted);
await UntilIdleAsync(server);
var id = (await server.Database.Sequences.ListLocationsAsync((await server.Database.Archives.ListAsync()).Single().Id)).Single().Id;
var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true);
var unhashed = await DryRunAsync(admin, request);
Assert.Equal((0, 2), (unhashed.Files, unhashed.Kept));
Assert.Equal("unhashed", unhashed.Steps.Single().Blocked.Single().Reason);
// A verify hashes them and leaves the sequence's frames version as it was: the same dry run plans again, and renames them.
var versions = (await server.Database.Sequences.GetAsync(id))!.FramesVersion;
using (var verify = await admin.PostAsync("/api/v1/archive/verify", null)) await verify.ExpectAsync(HttpStatusCode.Accepted);
await UntilIdleAsync(server);
Assert.Equal(versions, (await server.Database.Sequences.GetAsync(id))!.FramesVersion);
var hashed = await DryRunAsync(admin, request);
Assert.Equal((2, 0), (hashed.Files, hashed.Kept));
await UntilJobAsync(admin, await ConfirmAsync(admin, request with { DryRun = false, Fingerprint = hashed.Fingerprint }), "done");
Assert.SequenceEqual(["trips/originals/001.JPG", "trips/originals/002.JPG"], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.RelativePath));
Assert.True(File.Exists(Path.Combine(originals, "001.JPG")), "renamed on disk");
}
[Test]
public async Task KeptPlansAreTheNewestFewWithinTheirLifetime()
{
@@ -542,7 +573,7 @@ public sealed class ReorganizeTests(TestContext context)
var archive = Guid.NewGuid();
var templates = new RenameTemplates(Folder: "moved/{date}");
var made = 0;
Task<RenamePlan> Plan()
Task<RenamePlan> Plan(CancellationToken stop)
{
made++;
return Task.FromResult(new RenamePlan(Guid.NewGuid(), archive, []));
@@ -580,9 +611,15 @@ public sealed class ReorganizeTests(TestContext context)
await plans.GetOrPlanAsync(Key(0), Plan);
Assert.Equal(3 + ReorganizePlanCache.Capacity, made);
// A refusal is not kept, and a plan forgotten is made again.
await Assert.ThrowsAsync<NestedRenameException>(() => plans.GetOrPlanAsync(Key(99), () => throw new NestedRenameException("a/b", "a")));
await plans.GetOrPlanAsync(Key(99), Plan);
// A refusal follows from the same reads, and is kept as a plan is: a folder inside a sequence's, a sequence not in the
// archive. A failure is not kept, and neither is a plan or refusal forgotten.
await Assert.ThrowsAsync<NestedRenameException>(() => plans.GetOrPlanAsync(Key(99), _ => throw new NestedRenameException("a/b", "a")));
await Assert.ThrowsAsync<NestedRenameException>(() => plans.GetOrPlanAsync(Key(99), Plan));
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(Key(98), _ => throw new ArgumentException("Not in the archive.")));
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(Key(98), Plan));
Assert.Equal(3 + ReorganizePlanCache.Capacity, made);
await Assert.ThrowsAsync<IOException>(() => plans.GetOrPlanAsync(Key(97), _ => throw new IOException("The sidecar cannot be read.")));
await plans.GetOrPlanAsync(Key(97), Plan);
Assert.Equal(4 + ReorganizePlanCache.Capacity, made);
plans.Forget(Key(99));
await plans.GetOrPlanAsync(Key(99), Plan);
@@ -598,7 +635,7 @@ public sealed class ReorganizeTests(TestContext context)
var key = ReorganizePlanCache.Key.Of(Guid.NewGuid(), "stamp", null, templates);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var made = 0;
async Task<RenamePlan> SlowPlan()
async Task<RenamePlan> SlowPlan(CancellationToken stop)
{
Interlocked.Increment(ref made);
await release.Task;
@@ -632,13 +669,97 @@ public sealed class ReorganizeTests(TestContext context)
await plans.GetOrPlanAsync(key, SlowPlan);
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
Task<RenamePlan> PlanAtOnce()
Task<RenamePlan> PlanAtOnce(CancellationToken stop)
{
Interlocked.Increment(ref made);
return Task.FromResult(new RenamePlan(Guid.NewGuid(), key.ArchiveId, []));
}
}
[Test]
public async Task PlansAreMadeAFewAtOnceAndStopWhenLetGoOrPastTheirTime()
{
var clock = new SteppedTimeProvider();
using var plans = new ReorganizePlanCache(clock);
var archive = Guid.NewGuid();
var templates = new RenameTemplates(Folder: "moved/{date}");
ReorganizePlanCache.Key Key(int i) => ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var started = new ConcurrentDictionary<int, bool>();
var stopped = new ConcurrentDictionary<int, bool>();
// A plan made once released, which tells when it starts and when it is stopped.
Func<CancellationToken, Task<RenamePlan>> Plan(int i) => async stop =>
{
started[i] = true;
try
{
await release.Task.WaitAsync(stop);
}
catch (OperationCanceledException)
{
stopped[i] = true;
throw;
}
return new RenamePlan(Guid.NewGuid(), archive, []);
};
// A few are made at once; the others wait for their turn.
var asked = Enumerable.Range(0, ReorganizePlanCache.Capacity).Select(i => plans.GetOrPlanAsync(Key(i), Plan(i))).ToList();
await EventuallyAsync(() => started.Count == ReorganizePlanCache.Concurrency);
await Task.Delay(200);
Assert.SequenceEqual(Enumerable.Range(0, ReorganizePlanCache.Concurrency), started.Keys.Order());
// One more lets go the plan asked first, being made with none kept: it stops, its waiter is told, the next one starts.
var newest = plans.GetOrPlanAsync(Key(ReorganizePlanCache.Capacity), Plan(ReorganizePlanCache.Capacity));
await Assert.ThrowsAsync<OperationCanceledException>(() => asked[0]);
await EventuallyAsync(() => stopped.ContainsKey(0) && started.ContainsKey(ReorganizePlanCache.Concurrency));
Assert.Equal(ReorganizePlanCache.Capacity, plans.Count);
release.SetResult();
foreach (var plan in asked.Skip(1).Append(newest)) await plan;
Assert.SequenceEqual([0], stopped.Keys);
// A plan still being made at its time stops, also when its work never ends (a read that hangs), and so does one still
// waiting for its turn, which never starts.
var hang = new TaskCompletionSource<RenamePlan>(TaskCreationOptions.RunContinuationsAsynchronously);
Func<CancellationToken, Task<RenamePlan>> Hanging(int i) => _ =>
{
started[i] = true;
return hang.Task;
};
var hung = plans.GetOrPlanAsync(Key(20), Hanging(20));
var stuck = plans.GetOrPlanAsync(Key(21), Hanging(21));
await EventuallyAsync(() => started.ContainsKey(20) && started.ContainsKey(21));
var waiting = plans.GetOrPlanAsync(Key(22), Plan(22));
clock.Advance(ReorganizePlanCache.PlanTimeout - TimeSpan.FromSeconds(1));
Assert.False(hung.IsCompleted, "still in time");
clock.Advance(TimeSpan.FromSeconds(1));
foreach (var plan in new[] { hung, stuck, waiting }) await Assert.ThrowsAsync<OperationCanceledException>(() => plan);
Assert.False(started.ContainsKey(22), "stopped before its turn");
Assert.Equal(0, plans.Count);
// Asked again, it is made once a turn is free: the work that hangs holds its turn until it ends, and what it makes
// then is not kept.
var again = plans.GetOrPlanAsync(Key(20), Plan(30));
await Task.Delay(200);
Assert.False(started.ContainsKey(30), "no turn while two works hang");
hang.SetResult(new RenamePlan(Guid.NewGuid(), archive, []));
var made = await again;
Assert.True(ReferenceEquals(made, await plans.GetOrPlanAsync(Key(20), Plan(31))), "kept");
Assert.False(started.ContainsKey(31), "kept, not made again");
Assert.Equal(1, plans.Count);
}
/// <summary>Waits until <paramref name="condition"/> holds.</summary>
private static async Task EventuallyAsync(Func<bool> condition, [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(condition))] string? expression = null)
{
var until = DateTime.UtcNow + Wait;
while (!condition())
{
Assert.True(DateTime.UtcNow < until, expression);
await Task.Delay(10);
}
}
private static async Task<ReorganizePlanDto> DryRunAsync(HttpClient client, ReorganizeRequest request)
{
using var response = await client.PostAsJsonAsync(Url, request with { DryRun = true }, ProtocolJson.Default.ReorganizeRequest);