fix: keep render filing retryable and writers out of a folder another index moved

Third fix round of owner review 2, phase 4a (Reorganize), cross-cutting items.

- Server render filing now runs under the sequence lease, so it can meet a busy
  sequence or an offline archive. Both completions (client render uploads and
  render-node results) used to answer 500 and leave the upload stuck in
  Committing until a restart. They now answer 503 sequence_busy or
  archive_offline, which clients retry. The upload goes back to receiving with
  its part file and the node keeps its job (UploadService.ReceiveAgainAsync).
- Save both: when this PC's copy cannot be written (another index moved the
  folder), the server's version is no longer applied, even if this index's scan
  relocates the row before the apply would run. A copy that has to be dropped is
  deleted from where the folder is now, as a best effort.
- Export rebase on a folder move (scan and Reorganize): the sequence's own
  export follows the folder unless its file is still at the old path and not at
  the new one. A file written into a re-created old folder therefore keeps a row
  that finds it, so the file is never stranded.
- A render job refuses to start when its folder is not where the index has it,
  which also stops it from re-creating the old folder. Renders fetched by sync
  are now filed under the sequence lease into the current folder, or not at all
  (new string Errors.Archive.FolderMoved, en and it).
- The proxy pass holds the thumbnail lease one batch at a time (a quarter of
  the lease wait), then lets it go for longer than a waiter's poll and reads
  the folder and sidecar again. Before, another process's Reorganize, sequence
  deletion or pack compaction could wait out its lease wait and fail. Updated
  the stale comments on that lease and ARCHITECTURE.md to match.

Tests cover each fix, and each new test fails with its fix reverted. Also
covered: proxy store and pass in a moved folder, RenderStore with the folder
gone, Take server with the folder moved, and an editor save with the folder
moved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 811509d32a118ed50ad10d47d4b002e534da9d77)
This commit is contained in:
Alby96 committed 2026-10-27 19:16:28 +01:00
1 parent 0377040a19
commit c3756d03c9
26 files changed
+666 -134

No files matched your search

@@ -305,6 +305,29 @@ public sealed class MassRenameTests(TestContext context)
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
}
[Test]
public async Task AnExportWrittenWhereItsFolderWasStaysWithItsFile()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
List<Guid> renders = [await RenderAsync(fx, ids[0], "inbox/a/exports/A.mp4")];
var (server, archive) = await fx.OtherWriterAsync();
// The other index moves "inbox/a"; a writer here that read the folder before files an export where it was, creating
// it again. Another export of the sequence is missing from both places.
var plan = await server.PlanRenameAsync(archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
await server.ApplyRenameAsync(plan, null, fx.Ct);
renders.Add(await RenderAsync(fx, ids[0], "inbox/a/exports/Late.mp4"));
renders.Add(await RenderAsync(fx, ids[0], "inbox/a/exports/Gone.mp4", write: false));
// The scan here moves the rows whose file went with the folder or is nowhere, and keeps the one whose file stayed.
await fx.ScanAsync();
Assert.Equal("moved/2026-09-28", (await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!.Folder);
string[] expected = ["moved/2026-09-28/exports/A.mp4", "inbox/a/exports/Late.mp4", "moved/2026-09-28/exports/Gone.mp4"];
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
foreach (var path in expected[..2]) Assert.FileExists(fx.Paths.FromRelative(path));
}
[Test]
public async Task APhotoDeletionWhoseFolderMovedWhileItWaitedForTheLeaseIsRefused()
{
@@ -2,9 +2,11 @@ using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Tests.Processing;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
@@ -88,6 +90,95 @@ public sealed class ProxyTests(TestContext context)
Assert.FileMissing(now.Proxy(1));
}
[Test]
public async Task ProxiesOfAFolderAnotherIndexMovedWaitForThisIndexsScan()
{
await using var fx = await CreateAsync(context);
var (sequence, frames) = await HeifSequenceAsync(fx);
var images = fx.Service.Images;
var left = fx.Paths.Sequence(sequence.Folder).Folder;
var (server, archive) = await fx.OtherWriterAsync();
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "moved/{date}", null, fx.Ct);
await server.ApplyRenameAsync(plan, null, fx.Ct);
var moved = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
// This index still has the folder where it was: a proxy sent and a proxy pass write nothing, anywhere.
var proxy = Proxy(frames[0].CapturedAt!.Value, 2);
Assert.Equal(ProxyStoreResult.Gone, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], proxy, fx.Ct));
var refused = await Assert.ThrowsAsync<InvalidOperationException>(() =>
images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct));
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), refused.Message);
Assert.False(Directory.Exists(left), "the folder it left is not created again");
Assert.FileMissing(moved.Proxy(0));
// Once this index's scan found it there, they go where it is.
await fx.ScanAsync();
Assert.Equal(ProxyStoreResult.Stored, await images.StoreProxyAsync(fx.Archive, sequence, frames[0], proxy, fx.Ct));
Assert.SequenceEqual(proxy, await File.ReadAllBytesAsync(moved.Proxy(0), fx.Ct));
}
[Test]
public async Task AProxyPassLetsAnotherProcessReorganizeBetweenItsBatches()
{
await using var fx = await CreateAsync(context);
Guid id = default;
for (var i = 0; i < 4; i++)
{
var staged = fx.Stage(Start.AddSeconds(10 * i), 60 + i);
id = (await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, null, null, "batches", staged.Path, $"IMG_{i + 1:0000}.JPG",
staged.Size, staged.Sha256, null, null), fx.Ct)).SequenceId;
}
var sequence = (await fx.Db.Sequences.GetAsync(id, fx.Ct))!;
var left = fx.Paths.Sequence(sequence.Folder).Folder;
// The second photo is read as a PNG, through the decoders (JPEGs are decoded without them), and slowly.
var sidecar = ManifestStore.ReadSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath);
ManifestStore.WriteSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath, sidecar with
{
Frames = [.. sidecar.Frames.Select(f => f.I == 1 ? f with { Format = ImageFileFormat.Png } : f)],
});
var gate = new GateDecoder { Hold = Path.GetFileName(sidecar.Frames[1].File) };
var (server, archive) = await fx.OtherWriterAsync();
var plan = await server.PlanRenameAsync(archive.Id, [id], "moved/{date}", null, fx.Ct);
var moved = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
// A proxy pass here, one photo at a time, in batches of a quarter of its lease wait.
var batch = TimeSpan.FromSeconds(TestTiming.Budget(2));
var here = new ArchiveService(fx.Db, new ArchiveServiceOptions
{
Owner = "test",
LeaseWait = batch * 4,
Decoder = new ImageDecoder([gate]),
Parallelism = () => 1,
});
var pass = Task.Run(() => here.Images.BuildProxiesAsync(fx.Archive, sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct));
await Task.WhenAny(gate.Holding.Task, pass).WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
if (pass.IsCompleted) Assert.Fail($"The pass ended before the held photo: {await pass}");
var held = DateTime.UtcNow;
// Another process sharing the archive reorganizes the sequence: it holds the sequence, then waits for the thumbnail lease.
var move = Task.Run(() => server.ApplyRenameAsync(plan, null, fx.Ct));
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
while (LeaseFile.Holder(fx.Paths.LocksDirectory, $"seq-{id:N}")?.Owner != "other")
{
Assert.False(move.IsCompleted, "the Reorganize waits for the pass");
Assert.True(DateTime.UtcNow < until, "the Reorganize holds the sequence");
await Task.Delay(20, fx.Ct);
}
var rest = held + batch + TimeSpan.FromSeconds(0.5) - DateTime.UtcNow;
if (rest > TimeSpan.Zero) await Task.Delay(rest, fx.Ct);
gate.Release();
// The batch ends with that photo and lets the lease go: the Reorganize moves the folder before the pass ends, and the
// pass, finding the folder gone from where this index has it, stops there.
await move.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(60)), fx.Ct);
var stopped = await Assert.ThrowsAsync<InvalidOperationException>(() => pass);
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), stopped.Message);
Assert.False(Directory.Exists(left), "the folder it left is not created again");
Assert.FileExists(moved.Proxy(0));
Assert.FileExists(moved.Proxy(1));
Assert.FileMissing(moved.Proxy(2));
}
[Test]
public async Task AProxyLeftByARenumberedFrameIsAskedForAgain()
{
@@ -126,6 +126,34 @@ public sealed class RenderJobTests(TestContext context)
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ARenderOfAFolderAnotherIndexMovedWaitsForThisIndexsScan()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var left = fx.Folder(sequence).Folder;
var (server, archive) = await fx.Archive.OtherWriterAsync();
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct);
await server.ApplyRenameAsync(plan, null, fx.Ct);
await fx.StartEngineAsync();
// A server sharing the archive moved the folder; this index has not scanned since. Nothing renders, nothing is flagged.
var job = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error);
Assert.False(Directory.Exists(left), "the folder it left is not created again");
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
Assert.True((await fx.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fx.Ct)).All(f => (f.Flags & (FrameFlags.Missing | FrameFlags.Undecodable)) == 0), "no frame flagged");
// Once this index's scan found it there, the render goes into its exports.
await fx.Archive.ScanAsync();
var again = await fx.EnqueueAsync(ProcessingJobs.Render(sequence, Mjpeg, 96, 64));
await fx.WaitForAsync(again.Id, JobState.Done);
var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder);
Assert.FileExists(Path.Combine(moved.Exports, "clip-MJPEG.avi"));
Assert.False(Directory.Exists(left));
}
[Test]
public async Task AFrameThatNoLongerDecodesIsReplacedByItsNeighbourAndLeftOutNextTime()
{
@@ -121,12 +121,20 @@ internal sealed class FakeSyncRemote : ISyncRemote
}
}
public Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
/// <summary>Runs once, before the next frame listing is answered (frame positions translated against the server's frames).</summary>
public Func<Task>? OnceBeforeFrames { get; set; }
public async Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
{
if (OnceBeforeFrames is { } before)
{
OnceBeforeFrames = null;
await before();
}
lock (_gate)
{
var sequence = Find(sequenceId);
return Task.FromResult<IReadOnlyList<FrameDto>>([.. sequence.Frames.Select(sequence.FrameDto)]);
return [.. sequence.Frames.Select(sequence.FrameDto)];
}
}
@@ -456,6 +456,77 @@ public sealed class SyncServiceTests(TestContext context)
Assert.False(Directory.Exists(left), "the folder it left is not created again");
}
[Test]
public async Task SaveBothThatCannotKeepThisPcsVersionTakesNothing()
{
await using var f = await SyncFixture.CreateAsync(context);
// The server holds a photo this PC does not have yet, and its settings name a frame: taking them reads the server's
// frames, after this PC's copy was kept and before the server's version is written.
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Holy grail", photos[..2]);
var remote = f.Remote.Add("Holy grail", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
var theirs = """{"heroFrame":1,"exposure":{"deflickerWindow":{"isAuto":false,"manual":33}}}""";
f.Remote.EditSettings(remote.Id, theirs);
await f.RefreshAsync();
Assert.NotNull((await f.EntryAsync("Holy grail")).Link!.ConflictRemote);
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
// Another index moves the folder while the server's version is read, so this PC's version cannot be kept there; this
// index's scan finds the folder before the server's version would be written.
var (other, archive) = await f.Archive.OtherWriterAsync();
string? moved = null;
f.Remote.OnceBeforeManifest = async () =>
{
var plan = await other.PlanRenameAsync(archive.Id, [local.Id], "moved/{title}", null, f.Ct);
await other.ApplyRenameAsync(plan, null, f.Ct);
moved = plan.Steps.Single().ToFolder;
};
f.Remote.OnceBeforeFrames = () => f.Archive.ScanAsync();
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct));
// The server's frames were not read for a version that is not taken: the scan comes now.
f.Remote.OnceBeforeFrames = null;
await f.Archive.ScanAsync();
var kept = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.Equal(moved, kept.Folder, "the scan found the folder");
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, kept.SettingsJson), "this PC's version is not replaced without its copy");
var meta = f.Archive.Paths.Sequence(kept.Folder).MetaDirectory;
Assert.Empty(Directory.GetFiles(meta, SyncService.SavedCopyPattern));
Assert.False(Directory.Exists(left), "the folder it left is not created again");
Assert.NotNull((await f.EntryAsync("Holy grail")).Link!.ConflictRemote, "still a conflict");
// Asked again where the sequence is now, both versions are kept.
var copy = await f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.SaveBoth, f.Ct);
Assert.Equal(copy, Assert.Contains(Directory.GetFiles(meta, SyncService.SavedCopyPattern), _ => true));
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(copy!, f.Ct)), "this PC's version is kept");
}
[Test]
public async Task TakeServerWhereAnotherIndexMovedTheFolderWritesNothing()
{
await using var f = await SyncFixture.CreateAsync(context);
var (local, remote) = await ConflictAsync(f);
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
// Another index moves the folder while the server's version is read; this index has not scanned it since.
var (other, archive) = await f.Archive.OtherWriterAsync();
f.Remote.OnceBeforeManifest = async () =>
{
var plan = await other.PlanRenameAsync(archive.Id, [local.Id], "moved/{title}", null, f.Ct);
await other.ApplyRenameAsync(plan, null, f.Ct);
};
await Assert.ThrowsAsync<SyncConflictChangedException>(() => f.Sync.ResolveAsync(f.Remote, remote.Id, SyncResolution.TakeServer, f.Ct));
Assert.Null(f.Remote.OnceBeforeManifest, "the folder moved during the resolution");
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson), "nothing applied");
Assert.False(Directory.Exists(left), "the folder it left is not created again");
Assert.True(SyncRules.SameSettings(SyncFixture.Window41, await File.ReadAllTextAsync(f.Archive.Paths.Sequence("moved/Holy grail").ProjectPath, f.Ct)),
"the moved project is this PC's version");
}
[Test]
public async Task KeepMineRefusesWhenTheServerChangedAfterTheConflictWasShown()
{
@@ -600,6 +600,55 @@ public sealed class SyncTransferTests(TestContext context)
Assert.Equal(0, (await f.EntryAsync("Star trails")).Link!.ExportsToGet);
}
[Test]
public async Task TheServersRendersGoWhereTheSequenceIsNow()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Star trails", photos);
var remote = f.Remote.Add("Star trails", photos);
var first = new FakeRender(Guid.CreateVersion7(), "Star trails 4K.mp4", "4K HEVC", [.. Enumerable.Range(0, 3000).Select(i => (byte)i)]);
remote.Renders.Add(first);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
var left = f.Archive.Paths.Sequence(local.Folder).Folder;
// A Reorganize here moves the folder while the server's renders are listed: the render goes where the sequence is.
string? moved = null;
f.Remote.OnceBeforeManifest = async () =>
{
var plan = await f.Archive.Service.PlanRenameAsync(f.Archive.Archive.Id, [local.Id], "moved/{title}", null, f.Ct);
await f.Archive.Service.ApplyRenameAsync(plan, null, f.Ct);
moved = plan.Steps.Single().ToFolder;
};
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal($"{moved}/exports/Star trails 4K.mp4", (await f.Db.Renders.GetAsync(first.Id, f.Ct))!.OutputPath);
Assert.FileExists(f.Archive.Paths.FromRelative($"{moved}/exports/Star trails 4K.mp4"));
Assert.False(Directory.Exists(left), "the folder it left is not created again");
// Another index moves it: nothing is filed until this index's scan finds it there.
var second = new FakeRender(Guid.CreateVersion7(), "Star trails 1080p.mp4", "1080p", [.. Enumerable.Range(0, 2000).Select(i => (byte)(i * 3))]);
remote.Renders.Add(second);
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
var (other, archive) = await f.Archive.OtherWriterAsync();
var away = await other.PlanRenameAsync(archive.Id, [local.Id], "elsewhere/{title}", null, f.Ct);
await other.ApplyRenameAsync(away, null, f.Ct);
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error);
Assert.False(Directory.Exists(f.Archive.Paths.Sequence(moved!).Folder), "the folder it left is not created again");
Assert.Null(await f.Db.Renders.GetAsync(second.Id, f.Ct));
await f.Archive.ScanAsync();
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Star trails", SyncDownloadMode.Exports, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var fetched = (await f.Db.Renders.GetAsync(second.Id, f.Ct))!;
Assert.Equal("elsewhere/Star trails/exports/Star trails 1080p.mp4", fetched.OutputPath);
Assert.SequenceEqual(second.Bytes, await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(fetched.OutputPath), f.Ct));
}
[Test]
public async Task RendersMadeHereAreSentOnRequestAndAGoneFileIsReported()
{