fix(archive): exports follow a folder any index moved; proxies, exports and copies no longer recreate it

Second review of owner review 2, phase 4a (Reorganize), cross-cutting findings.

- A second index of the archive (a desktop sharing a server's archive, or a folder moved by
  hand) moved the sequence row at its next scan but left renders.output_path at the old
  folder: the export answered 404 there. The scan now rebases the render rows in the same
  transaction when it finds a sequence in another folder.
- The rebase covers every render of the archive under the old folder: the sequence's own
  exports always, and another sequence's export saved inside it (through the Export folder
  picker) when its file moved with the folder. That check keeps the exports of a sequence
  that took the old folder since (a later Reorganize on the other index) where they are. A
  change of case only counts as a move.
- The desktop now tells an open editor after each Reorganize step
  (ArchiveServiceOptions.SequenceChanged -> AppServices.SequenceReorganized), and the editor
  reads its sequence again where it is now, so frames no longer decode blank until the next
  save. LocalSequenceSource.LoadAsync also requires the same folder on both row reads, so a
  move that commits during the frame listing is never taken as current.
- Writers that wrote without the lease, or trusted a row another index had moved, could
  create the old folder again. A proxy sent by a client is now filed under the sequence's
  lease into the folder the index has then, and a gone sequence or folder answers 404
  (sequence_busy 503 after the lease wait). The server files a render a client or render
  node sends under the lease (ArchiveService.UnderLeaseAsync). "Save both" keeps its copy
  under the lease. The proxy pass holds the thumbnail lease, as the thumbnail pass does. The
  deep analysis opens its checkpoint under the sequence lock only while the folder is still
  there, and a pass whose folder another process moved records nothing (the job logs
  Advisor.Log.FramesChangedElsewhere). Editor saves and sync applies refuse when the folder
  is gone.
- ARCHITECTURE.md no longer claims more than this: a render of another process whose folder
  moves while it runs is still not stopped.
- ArchiveVerifier.FlushAsync: corrected the comment. A move keeps each file's stamp, so only a
  check that found the file missing no longer applies.

Tests cover the scan path with a later swap into the vacated folder, another sequence's
export inside a moving folder, a photo deletion refused when the folder moved while it
waited for the lease, proxies sent and made after a move, Save both during a move, a deep
analysis whose folder another index moved, a render filed after a move on the server, and
an open editor reloaded by a Move job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c857b98f795b22956c060f1c5acf4d94b6d1c994)
This commit is contained in:
Alby96 committed 2026-10-27 18:09:02 +01:00
1 parent 765f0ad36b
commit 6e99a4b269
20 files changed
+561 -160

No files matched your search

+100 -81
View File
@@ -15,7 +15,7 @@ namespace Chronos.Data.Archiving;
/// client or render node that can (BRIEF §2.3): unlike <paramref name="Undecodable"/> ones, nothing is wrong with them.</param>
public sealed record ImagePassResult(int Built, int Reused, int Undecodable, int Waiting = 0);
/// <summary>What became of a proxy sent by a client or render node (<see cref="ArchiveImages.StoreProxy"/>).</summary>
/// <summary>What became of a proxy sent by a client or render node (<see cref="ArchiveImages.StoreProxyAsync"/>).</summary>
public enum ProxyStoreResult
{
Stored,
@@ -31,6 +31,9 @@ public enum ProxyStoreResult
/// <summary>Smaller than the archive's proxies of that frame: made from an embedded preview, not the original.</summary>
TooSmall,
/// <summary>The frame's sequence left the index meanwhile (deleted), or its folder (moved by another index): nothing was written.</summary>
Gone,
}
/// <summary>
@@ -38,7 +41,7 @@ public enum ProxyStoreResult
/// regenerable and self-validating: a thumbnail carries its source fingerprint, a proxy its capture time, so after
/// frames were renumbered the stale ones are rebuilt and the rest reused. A frame whose original this host cannot
/// decode (<see cref="NeedsProxy(ImageDecoder, ImageFileFormat)"/>) gets its proxy from a client or render node that can
/// (<see cref="StoreProxy"/>, BRIEF §2.3) and its thumbnail from that proxy. A frame nothing decodes is flagged
/// (<see cref="StoreProxyAsync"/>, BRIEF §2.3) and its thumbnail from that proxy. A frame nothing decodes is flagged
/// undecodable (BRIEF §8.2 tier 3); one flagged so that decodes after all gets its tier probed again.
/// </summary>
public sealed class ArchiveImages
@@ -122,7 +125,7 @@ public sealed class ArchiveImages
Check(proxy, capturedAt, width, height, policy).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
/// <summary>
/// A proxy of the original at <paramref name="path"/> for a server that cannot decode it (<see cref="StoreProxy"/>):
/// A proxy of the original at <paramref name="path"/> for a server that cannot decode it (<see cref="StoreProxyAsync"/>):
/// at <paramref name="longEdge"/> (0 = full size) and <paramref name="quality"/>, with <paramref name="frame"/>'s capture
/// data (the server's record, which it checks) and <paramref name="camera"/> in its Exif. Null when
/// <paramref name="decoder"/> cannot decode the original either.
@@ -159,10 +162,13 @@ public sealed class ArchiveImages
/// Files a proxy made elsewhere (a client or render node whose decoders read the original) as the frame's proxy,
/// replacing the one there: a JPEG of at most <see cref="MaxProxyBytes"/> that decodes, whose Exif capture time is the
/// frame's (proxies carry it, so the proxy counts as current and cannot belong to another photo) and whose size is
/// the policy's (<see cref="TooSmall"/>), written atomically.
/// the policy's (<see cref="TooSmall"/>), written atomically under the sequence's lease into its folder as the index has
/// it then: a Reorganize moves the folder under that lease, and the folder it left is never created again (one another
/// index moved, which this index finds at its next scan, takes nothing: <see cref="ProxyStoreResult.Gone"/>).
/// </summary>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
public ProxyStoreResult StoreProxy(Archive archive, Sequence sequence, Frame frame, byte[] jpeg)
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than the lease wait.</exception>
public async Task<ProxyStoreResult> StoreProxyAsync(Archive archive, Sequence sequence, Frame frame, byte[] jpeg, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(jpeg);
var paths = new ArchivePaths(archive.RootPath);
@@ -177,11 +183,16 @@ public sealed class ArchiveImages
using var stream = new MemoryStream(jpeg, writable: false);
if (!SameCapture(MetadataReader.Read(stream, "proxy.jpg").CapturedAt, captured)) return ProxyStoreResult.WrongFrame;
}
var folder = paths.Sequence(sequence.Folder);
Directory.CreateDirectory(folder.Proxies);
var path = folder.Proxy(frame.Index);
AtomicFile.WriteAllBytes(path, jpeg);
Headers.TryRemove(path, out _);
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
if (await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false) is not { } row) return ProxyStoreResult.Gone;
var folder = paths.Sequence(row.Folder);
if (!Directory.Exists(folder.Folder)) return ProxyStoreResult.Gone;
Directory.CreateDirectory(folder.Proxies);
var path = folder.Proxy(frame.Index);
AtomicFile.WriteAllBytes(path, jpeg);
Headers.TryRemove(path, out _);
}
return ProxyStoreResult.Stored;
}
@@ -290,85 +301,93 @@ 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);
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
Directory.CreateDirectory(folder.Proxies);
SequenceManifest manifest;
int built = 0, reused = 0, undecodable = 0, waiting = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
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))
// 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))
{
for (var i = 0; i < manifest.Frames.Count; i++)
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))
{
cancellationToken.ThrowIfCancellationRequested();
var frame = manifest.Frames[i];
var path = folder.Proxy(frame.I);
var done = i < startFrame;
if (NeedsProxy(frame.Format))
for (var i = 0; i < manifest.Frames.Count; i++)
{
// 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 = manifest.Frames[i];
var path = folder.Proxy(frame.I);
var done = i < 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(i, 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 = 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);
}
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);
}
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);