fix(archive): exports follow a Reorganize folder move; writers resolve the folder under the lease

A Reorganize step that moves a sequence folder carries its exports/ with it, but only
the sequences and frames rows followed: renders.output_path kept naming the old folder,
so the server answered 404 for the export, Get/Send exports and Reveal lost it, and no
scan or trash restore could repair it. RenderRepository.RebaseFolderAsync now rewrites
the archive-relative output paths of the step's sequence in the same transaction as the
frames (idempotent on resume; absolute outputs and the archive root are untouched).

Writers that read a sequence row before taking its lease wrote into the folder a
Reorganize had moved meanwhile, creating it again (project.json from the editor or a
sync, a thumbnail pack) or failing on its missing sidecar. They now take the folder from
the index row read under the lease (SequenceWriter.FolderAsync): the editor's save
refuses with FramesChangedException and reloads at the new folder, FramesCurrentAsync
reports a moved folder, and the sync apply, project store, thumbnail pass and its
status, decode tiers, analyses, verify, info edits, ingest, duplicate flags, pack
compaction and photo restores write where the sequence is now; a photo deletion planned
before the move is refused as stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit be28d8acf0d96012c94a266f8af61e9bbafaa28d)
This commit is contained in:
Alby96 committed 2026-10-27 16:29:59 +01:00
1 parent b253cac8d4
commit 9ce201cd70
22 files changed
+343 -35

No files matched your search

+9 -6
View File
@@ -199,17 +199,20 @@ public sealed class ArchiveImages
ArchiveVolume.EnsureWritable(paths);
var archiveManifest = ManifestStore.ReadArchive(paths.ManifestPath);
var policy = archiveManifest.ThumbnailPolicy;
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
SequenceManifest manifest;
int built = 0, reused = 0, undecodable = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
// Thumbnail writers exclude each other only; ingest keeps committing meanwhile.
// 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.
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{sequence.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
using (var pack = ThumbPackWriter.Open(folder.ThumbsPackPath))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
manifest = ManifestStore.ReadSequence(folder.ManifestPath);
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
using var pack = ThumbPackWriter.Open(folder.ThumbsPackPath);
for (var i = 0; i < startFrame && i < manifest.Frames.Count; i++)
{
var frame = manifest.Frames[i];
@@ -626,9 +629,9 @@ public sealed class ArchiveImages
private async Task MarkAsync(Archive archive, ArchivePaths paths, Sequence sequence, SequenceManifest read, JobKind pass, SequenceStatus flag,
bool complete, CancellationToken cancellationToken)
{
var folder = paths.Sequence(sequence.Folder);
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
var built = complete && (SameFrames(manifest.Frames, read.Frames)
|| await _db.Jobs.IsQueuedAsync(pass, sequence.Id, cancellationToken).ConfigureAwait(false));
+1 -1
View File
@@ -292,9 +292,9 @@ public sealed class ArchiveIngest : IArchiveIngest
?? throw new InvalidOperationException($"Sequence {sequenceId} is not indexed.");
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var sequence = paths.Sequence(row.Folder);
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
{
var sequence = await SequenceWriter.FolderAsync(_db, paths, row, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(sequence, sequenceId);
// Asked before this batch changes the folder: whether this index holds it as it is (ArchiveIndexer.InStepAsync), and
// when it does not, whether photos were copied in or removed by hand since the last scan, which this batch's
@@ -230,7 +230,13 @@ public sealed class ArchiveMaintenance
await using (await _writer.LockAsync(paths, location.Id, cancellationToken).ConfigureAwait(false))
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, $"thumbs-{location.Id:N}", _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
ThumbPackWriter.Compact(sequence.ThumbsPackPath);
{
// Where the pack is now: a Reorganize may have moved the folder since the listing, and compacting a pack
// that is not there would create it (and the folder) again.
var pack = paths.Sequence((await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false))?.Folder ?? location.Folder)
.ThumbsPackPath;
if (File.Exists(pack)) ThumbPackWriter.Compact(pack);
}
}
return compacted;
}
@@ -251,9 +257,9 @@ public sealed class ArchiveMaintenance
if (await _db.Sequences.GetAsync(bySequence.Key, cancellationToken).ConfigureAwait(false) is not { } sequence) continue;
var changes = bySequence.ToDictionary(x => x.Key, x => (Func<SidecarFrame, SidecarFrame>)(f =>
f with { Flags = x.Set ? f.Flags | FrameFlags.Duplicate : f.Flags & ~FrameFlags.Duplicate }));
var folder = paths.Sequence(sequence.Folder);
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
// The scan stamps follow only when the index held the folder as it was: frames another process listed in the
// sidecar meanwhile are still indexed by the next scan.
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
+1 -1
View File
@@ -268,9 +268,9 @@ public sealed class ArchiveService : IJobHandlerProvider
var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(folder, sequenceId);
var inStep = await Indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
for (var attempt = 1; ; attempt++)
@@ -112,9 +112,10 @@ public sealed class ArchiveVerifier
private async Task FlushAsync(Archive archive, ArchivePaths paths, Sequence target, List<PendingCheck> pending, CancellationToken cancellationToken)
{
if (pending.Count == 0) return;
var sequence = paths.Sequence(target.Folder);
await using (await _writer.LockAsync(paths, target.Id, cancellationToken).ConfigureAwait(false))
{
// Where the sequence is now (a Reorganize may have moved it); a check of a file that moved since no longer applies.
var sequence = await SequenceWriter.FolderAsync(_db, paths, target, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(sequence, target.Id);
var current = manifest.Frames.ToDictionary(f => f.Id);
var found = pending.Where(p => current.TryGetValue(p.Check.Frame.Id, out var now) && StillApplies(sequence, p, now)).Select(p => p.Check).ToList();
@@ -164,9 +165,9 @@ public sealed class ArchiveVerifier
/// </summary>
private async Task StampAsync(Archive archive, ArchivePaths paths, Sequence target, CancellationToken cancellationToken)
{
var sequence = paths.Sequence(target.Folder);
await using (await _writer.LockAsync(paths, target.Id, cancellationToken).ConfigureAwait(false))
{
var sequence = await SequenceWriter.FolderAsync(_db, paths, target, cancellationToken).ConfigureAwait(false);
var m = SequenceWriter.ReadLocked(sequence, target.Id);
var inStep = await _indexer.InStepAsync(archive, sequence, m, cancellationToken).ConfigureAwait(false);
var clean = m.Frames.All(f => (f.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0);
+1 -1
View File
@@ -79,9 +79,9 @@ internal sealed class FrameTiers(ChronosDatabase db, SequenceWriter writer, Arch
if (tiers.Count == 0 && !proxies) return [];
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(db, paths, sequence, cancellationToken).ConfigureAwait(false);
var m = SequenceWriter.ReadLocked(folder, sequence.Id);
var changed = new List<SidecarFrame>();
var gained = false;
@@ -150,13 +150,13 @@ public sealed partial class FrameTrash
private async Task<(PhotoRestoreResult, List<Stay>)> IntoSequenceAsync(Archive archive, ArchivePaths paths, Sequence sequence, string recordPath,
string entryFolder, string lease, List<TrashedPhoto> intact, CancellationToken cancellationToken)
{
var folder = paths.Sequence(sequence.Folder);
var left = new List<Stay>();
int restored;
SequenceManifest updated;
var indexed = true;
await using (await _writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id, lease);
// A restore of another entry, busy now, is not settled yet: its journal is not written over.
EnsureSettled(folder);
+3
View File
@@ -229,6 +229,9 @@ public sealed partial class FrameTrash
bool indexed;
await using (await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false))
{
// A Reorganize moves the folder under this lease: moved since the plan, the plan names other paths.
if ((await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false))?.Folder != revised.Sequence.Folder)
throw new StaleDeletePlanException(id);
var manifest = SequenceWriter.ReadLocked(folder, id);
var plannedPaths = plan.Frames.ToDictionary(f => f.Id, f => f.RelativePath);
var planned = plannedPaths.Keys.ToHashSet();
+7 -2
View File
@@ -578,7 +578,8 @@ public sealed class MassRenamer
}
/// <summary>
/// Sidecar title, then index (folder, title, frames' paths); each part is idempotent so a resumed step can repeat it.
/// Sidecar title, then index (folder, title, frames' paths and the paths of renders whose export moved with the
/// folder, in one transaction); each part is idempotent so a resumed step can repeat it.
/// The index row changes in its folder and title only (<see cref="SequenceRepository.RelocateAsync"/>): a settings edit
/// committed meanwhile stays, and frames another process listed in the sidecar are left to the next scan, for which
/// the folder keeps no stamps unless the index held it as it was
@@ -606,7 +607,11 @@ public sealed class MassRenamer
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
{
await tx.Sequences.RelocateAsync(step.SequenceId, step.ToFolder, retitle ? step.ToTitle : null, cancellationToken).ConfigureAwait(false);
if (step.MovesFolder) await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
if (step.MovesFolder)
{
await tx.Frames.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
await tx.Renders.RebaseFolderAsync(step.SequenceId, step.FromFolder, step.ToFolder, cancellationToken).ConfigureAwait(false);
}
await tx.Archives.DeleteFolderStateAsync(archive.Id, step.FromFolder, cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
@@ -1,6 +1,7 @@
using System.Collections.Concurrent;
using Chronos.Core.Archiving;
using Chronos.Core.Imaging;
using Chronos.Core.Model;
namespace Chronos.Data.Archiving;
@@ -127,6 +128,15 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
return manifest;
}
/// <summary>
/// The folder of a sequence whose lock the caller holds, as the index has it now. A Reorganize moves a folder and
/// updates its row under the sequence's lease (and its thumbnail lease), so a writer that read the row before taking
/// the lease writes where the sequence is, never into the folder it left, which the write would create again. The
/// folder of <paramref name="sequence"/> when the row is gone (reading its sidecar then fails as it did).
/// </summary>
public static async Task<SequencePaths> FolderAsync(ChronosDatabase db, ArchivePaths archive, Sequence sequence, CancellationToken cancellationToken) =>
archive.Sequence((await db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false))?.Folder ?? sequence.Folder);
/// <summary>Applies <paramref name="edit"/> to the sidecar under the lock; a null result writes nothing.</summary>
public async Task<SequenceManifest> UpdateAsync(ArchivePaths archive, Guid sequenceId, string folder,
Func<SequenceManifest, SequenceManifest?> edit, CancellationToken cancellationToken)
+5 -2
View File
@@ -44,14 +44,17 @@ internal sealed class ProjectStore(ChronosDatabase db, SequenceWriter writer)
return await UpdateLockedAsync(paths, sequence, edit, cancellationToken).ConfigureAwait(false);
}
/// <summary><see cref="UpdateAsync"/> for a caller that holds the sequence lock already.</summary>
/// <summary>
/// <see cref="UpdateAsync"/> for a caller that holds the sequence lock already. The file goes to the folder of the row
/// read under the lock: a Reorganize moves the folder and its row under the same lock.
/// </summary>
/// <exception cref="InvalidDataException">The stored settings cannot be read; nothing is written.</exception>
public async Task<bool> UpdateLockedAsync(ArchivePaths paths, Sequence sequence, Func<ProjectSettings, ProjectSettings> edit, CancellationToken cancellationToken)
{
var folder = paths.Sequence(sequence.Folder);
for (var attempt = 1; ; attempt++)
{
var row = await db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false) ?? sequence;
var folder = paths.Sequence(row.Folder);
var current = Read(row, folder);
var before = current.ToJson();
var edited = edit(current);
@@ -98,6 +98,8 @@ internal sealed class SequenceAnalyser(ChronosDatabase db, ProcessingOptions opt
// then follows the report analysis.json holds: its own, or the one it left in place.
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
// Where the sequence is now: a Reorganize may have moved its folder while the pass ran.
folder = await SequenceWriter.FolderAsync(db, paths, sequence, cancellationToken).ConfigureAwait(false);
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
var change = await FramesChangeAsync(sequence, manifest, cancellationToken).ConfigureAwait(false);
// The frames as this host reads them now: a proxy that arrived while the pass ran moves no frames version but
@@ -45,6 +45,23 @@ public sealed class RenderRepository
return true;
}, cancellationToken);
/// <summary>
/// Rewrites the output paths of a sequence's renders after its folder moved (Reorganize): an export inside the folder
/// moved with it. Outputs elsewhere (absolute paths, other folders of the archive) stay as they are.
/// </summary>
/// <remarks>Only paths still under <paramref name="oldFolder"/> change, so repeating it after a crash is harmless.</remarks>
public Task<int> RebaseFolderAsync(Guid sequenceId, string oldFolder, string newFolder, CancellationToken cancellationToken = default)
{
// The archive root never moves, and its prefix ("/") would match absolute paths outside the archive.
if (oldFolder.Length == 0) return Task.FromResult(0);
// substr counts characters (code points) on both dialects; the tail starts with the '/' after the folder.
var prefix = oldFolder + "/";
var length = prefix.EnumerateRunes().Count();
return _db.ExecuteAsync(
"UPDATE renders SET output_path = $2 || substr(output_path, $3) WHERE sequence_id = $1 AND substr(output_path, 1, $4) = $5",
[sequenceId, newFolder, length, length, prefix], cancellationToken);
}
/// <summary>
/// Serialises render changes per sequence on PostgreSQL, so the recount (a new statement, hence a new snapshot)
/// sees every committed render; SQLite's write lock already does this.
+2 -1
View File
@@ -734,12 +734,13 @@ public sealed class SyncService
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(local.Folder);
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
// The frames cannot change under the lease: the positions are moved to them as they are now.
if (await positions.ToLocalAsync(payload.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } current) return null;
var row = current.Local;
// The folder too: a Reorganize moves it and its row under this lease.
var folder = paths.Sequence(row.Folder);
payload = payload with { SettingsJson = current.SettingsJson };
var metadata = !payload.SameMetadata(SyncPayload.Of(row));
var settings = !SyncRules.SameSettings(payload.SettingsJson, row.SettingsJson);