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

+111 -82
View File
@@ -5,6 +5,7 @@ using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
@@ -57,6 +58,9 @@ public sealed class ArchiveImages
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
/// <summary>How long a proxy pass lets the thumbnail lease go between two batches: longer than a waiting writer sleeps between its tries.</summary>
private static readonly TimeSpan BatchGap = LeaseFile.LongestPoll * 1.5;
/// <summary>
/// Age of a proxy file under which its header is not kept: a file system's clock may give a file written again at
/// once (with the same length) the same write time, at a granularity of up to two seconds.
@@ -214,9 +218,9 @@ public sealed class ArchiveImages
int built = 0, reused = 0, undecodable = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
// Thumbnail writers exclude each other only; ingest keeps committing meanwhile. A Reorganize moves the folder under
// this lease too, so the folder is the one the index has once it is held: the pack never opens in a folder the
// sequence left, which opening it would create again.
// Image passes exclude each other only (a proxy pass holds this lease a batch at a time); ingest keeps committing
// meanwhile. A Reorganize moves the folder under this lease too, so the folder is the one the index has once it is
// held: the pack never opens in a folder the sequence left, which opening it would create again.
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
@@ -292,7 +296,10 @@ public sealed class ArchiveImages
/// proxies of the frames an earlier run did again (their headers only). The <see cref="FrameFlags.PreviewOnly"/> flag
/// of frames this host reads through their proxies follows whether they have one (<see cref="FrameTiers"/>). Several
/// originals are decoded at once (<see cref="PassParallelism"/>), and a checkpoint still means that every frame before
/// it has its proxy written (<see cref="OrderedWork{T}"/>).
/// it has its proxy written (<see cref="OrderedWork{T}"/>). The pass works in batches (<see cref="ProxyBatch"/>), each
/// under the thumbnail lease with the sequence's folder and sidecar read again; a folder that is not where the index
/// has it (another index moved it, until this index's next scan) stops the pass with an
/// <see cref="InvalidOperationException"/>, nothing written there.
/// </remarks>
public async Task<ImagePassResult> BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame,
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
@@ -301,99 +308,119 @@ public sealed class ArchiveImages
ArchiveVolume.EnsureWritable(paths);
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
if (policy.LongEdge == ProxyPolicy.Disabled) return new ImagePassResult(0, 0, 0);
SequenceManifest manifest;
SequenceManifest? manifest = null;
int built = 0, reused = 0, undecodable = 0, waiting = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
var cadence = new Cadence();
// Under the thumbnail lease, as the thumbnail pass: image passes exclude each other only, ingest keeps committing
// meanwhile, and a Reorganize waits for the pass, so the proxies go to the folder the index has once the lease is
// held, never into one the sequence left, which writing them would create again.
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
// meanwhile, and a Reorganize waits for the batch, so the proxies go to the folder the index has once the lease is
// held, never into one the sequence left, which writing them would create again. Between two batches the lease is let
// go for longer than a waiting writer sleeps between its tries, so another process's Reorganize, sequence deletion or
// pack compaction waits for one batch, not for the whole pass.
for (var next = 0; ;)
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
manifest = ManifestStore.ReadSequence(folder.ManifestPath);
Directory.CreateDirectory(folder.Proxies);
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
var cadence = new Cadence();
await using (var work = new OrderedWork<Made>(ProxyParallelism(manifest.Frames, policy), made =>
{
switch (made.Outcome)
{
case ProxyOutcome.Built:
built++;
break;
case ProxyOutcome.Reused:
reused++;
break;
case ProxyOutcome.Waiting:
waiting++;
break;
case ProxyOutcome.Failed:
undecodable++;
complete = false;
break;
default:
undecodable++;
break;
}
if (made.Tier is { } tier) tiers[made.FrameId] = tier;
return cadence.Due() ? checkpoint(made.Index + 1, manifest.Frames.Count) : ValueTask.CompletedTask;
}, cancellationToken))
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
for (var i = 0; i < manifest.Frames.Count; i++)
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
if (!Directory.Exists(folder.Folder)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
var read = ManifestStore.ReadSequence(folder.ManifestPath);
// Photos added, removed or renumbered since the last batch: what the earlier batches made may not be theirs.
if (manifest is not null && !SameFrames(read.Frames, manifest.Frames, names: false)) complete = false;
manifest = read;
Directory.CreateDirectory(folder.Proxies);
var companions = await GprCompanions.FindAsync(_db, archive, read.Frames, cancellationToken).ConfigureAwait(false);
var batch = Stopwatch.StartNew();
await using (var work = new OrderedWork<Made>(ProxyParallelism(read.Frames, policy), made =>
{
switch (made.Outcome)
{
case ProxyOutcome.Built:
built++;
break;
case ProxyOutcome.Reused:
reused++;
break;
case ProxyOutcome.Waiting:
waiting++;
break;
case ProxyOutcome.Failed:
undecodable++;
complete = false;
break;
default:
undecodable++;
break;
}
if (made.Tier is { } tier) tiers[made.FrameId] = tier;
return cadence.Due() ? checkpoint(made.Index + 1, read.Frames.Count) : ValueTask.CompletedTask;
}, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var frame = manifest.Frames[i];
var path = folder.Proxy(frame.I);
var done = i < startFrame;
if (NeedsProxy(frame.Format))
// At least one frame per batch, so the pass always moves on.
for (var first = next; next < read.Frames.Count && (next == first || batch.Elapsed < ProxyBatch); next++)
{
// Only a client or render node that decodes the original makes this proxy: a preview would make one the
// size of a thumbnail here. One left from a frame renumbered since goes, so it is asked for again, and so
// does one smaller than the policy's (made here from a preview by an earlier version).
var check = Check(path, frame.CapturedAt, frame.W, frame.H, policy).Check;
var usable = check is ProxyCheck.Current or ProxyCheck.Unverifiable;
if (check == ProxyCheck.Stale) Delete(path);
complete &= usable;
if (done) continue;
var outcome = usable ? ProxyOutcome.Reused
: (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? ProxyOutcome.Unreadable
: ProxyOutcome.Waiting;
await work.AddAsync(new Made(i, frame.Id, outcome, null)).ConfigureAwait(false);
continue;
cancellationToken.ThrowIfCancellationRequested();
var frame = read.Frames[next];
var path = folder.Proxy(frame.I);
var done = next < startFrame;
if (NeedsProxy(frame.Format))
{
// Only a client or render node that decodes the original makes this proxy: a preview would make one the
// size of a thumbnail here. One left from a frame renumbered since goes, so it is asked for again, and so
// does one smaller than the policy's (made here from a preview by an earlier version).
var check = Check(path, frame.CapturedAt, frame.W, frame.H, policy).Check;
var usable = check is ProxyCheck.Current or ProxyCheck.Unverifiable;
if (check == ProxyCheck.Stale) Delete(path);
complete &= usable;
if (done) continue;
var outcome = usable ? ProxyOutcome.Reused
: (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? ProxyOutcome.Unreadable
: ProxyOutcome.Waiting;
await work.AddAsync(new Made(next, frame.Id, outcome, null)).ConfigureAwait(false);
continue;
}
if (done)
{
// Made by the earlier run, unless the frame did not decode then.
complete &= ReadProxy(path, frame.CapturedAt).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
continue;
}
if (!force && ReadProxy(path, frame.CapturedAt).Check == ProxyCheck.Current)
{
reused++;
continue;
}
var index = next;
var companion = companions.GetValueOrDefault(frame.Id);
await work.AddAsync(ct =>
{
var (image, tier) = Render(folder, frame, companion, recordTier: true,
() => _renderer.Proxy(folder, frame, read.Camera, policy, ct, companion));
if (image is null) return new Made(index, frame.Id, ProxyOutcome.Failed, tier);
AtomicFile.WriteAllBytes(path, image.Jpeg);
Headers.TryRemove(path, out _);
return new Made(index, frame.Id, ProxyOutcome.Built, tier);
}).ConfigureAwait(false);
}
if (done)
{
// Made by the earlier run, unless the frame did not decode then.
complete &= ReadProxy(path, frame.CapturedAt).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
continue;
}
if (!force && ReadProxy(path, frame.CapturedAt).Check == ProxyCheck.Current)
{
reused++;
continue;
}
var index = i;
var companion = companions.GetValueOrDefault(frame.Id);
await work.AddAsync(ct =>
{
var (image, tier) = Render(folder, frame, companion, recordTier: true,
() => _renderer.Proxy(folder, frame, manifest.Camera, policy, ct, companion));
if (image is null) return new Made(index, frame.Id, ProxyOutcome.Failed, tier);
AtomicFile.WriteAllBytes(path, image.Jpeg);
Headers.TryRemove(path, out _);
return new Made(index, frame.Id, ProxyOutcome.Built, tier);
}).ConfigureAwait(false);
await work.CompleteAsync().ConfigureAwait(false);
}
await work.CompleteAsync().ConfigureAwait(false);
if (next >= read.Frames.Count) break;
}
await Task.Delay(BatchGap, cancellationToken).ConfigureAwait(false);
}
await _tiers.RecordAsync(archive, sequence, tiers, proxies: true, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, manifest, JobKind.Proxies, SequenceStatus.ProxiesBuilt, complete, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable, waiting);
}
/// <summary>
/// How long a proxy pass holds the thumbnail lease for one batch of frames: a quarter of the lease wait, so a writer of
/// another process waiting for the lease meanwhile gets it well before it gives up (the frames the batch started finish
/// first).
/// </summary>
private TimeSpan ProxyBatch => _writer.Options.LeaseWait / 4;
/// <summary>Photos a thumbnail pass draws at once (<see cref="PassParallelism"/>): previews of the thumbnail's size serve it.</summary>
private int ThumbnailParallelism(IReadOnlyList<SidecarFrame> frames, ThumbnailPolicy policy) =>
PassParallelism(_writer.Options.Parallelism(), _writer.Options.MemoryBudget(), frames, policy.LongEdge, preferPreview: true, _writer.Options.Decoder);
@@ -673,13 +700,15 @@ public sealed class ArchiveImages
/// removed, renumbered or replaced since have none of what the pass made. A hash learnt since (a verify hashing a
/// photo the scan adopted) changes nothing about the photo, and its thumbnail stays its own (<see cref="ThumbPack.IsFrom"/>).
/// </summary>
private static bool SameFrames(IReadOnlyList<SidecarFrame> current, IReadOnlyList<SidecarFrame> read)
/// <param name="names">Whether a file renamed since counts as a change (a pass's own batches: it does not, a proxy is
/// kept by frame index and a Reorganize renames files).</param>
private static bool SameFrames(IReadOnlyList<SidecarFrame> current, IReadOnlyList<SidecarFrame> read, bool names = true)
{
if (current.Count != read.Count) return false;
for (var i = 0; i < current.Count; i++)
{
var (now, then) = (current[i], read[i]);
if (now.Id != then.Id || now.I != then.I || now.File != then.File || now.Size != then.Size || now.CapturedAt != then.CapturedAt
if (now.Id != then.Id || now.I != then.I || (names && now.File != then.File) || now.Size != then.Size || now.CapturedAt != then.CapturedAt
|| (then.Sha256 is not null && !string.Equals(now.Sha256, then.Sha256, StringComparison.OrdinalIgnoreCase))) return false;
}
return true;