fix(archive): a rebase moves no row of the sequence that took the old folder; writers refuse a folder another sequence holds

Round 4 let every row under the old folder follow when that folder holds another sequence
now. When the scan took the new holder first, its own row (already rebased into the old
folder) then followed the moving sequence too and named that sequence's file, leaving its
own export without a row; a second scan did not repair it. Only the moving sequence's own
rows now follow because the old folder is taken, and a row of the sequence holding the old
folder never follows: its export is in its own folder whatever the other one took along
under the same name. The rebase callback now gets the owner of each row.

Writers that file into the folder the index has for a sequence checked only that the folder
existed. After another index moved the sequence away and another one into that folder, Take
server wrote the server's settings into the other sequence's project.json, Save both wrote
this PC's copy into its .chronos, and a render sent for the sequence was filed among its
exports. SequenceFolders.Holds treats a folder whose sidecar names another sequence exactly
like a missing one, and every such writer asks it: settings sync and conflict resolution
(Errors.Archive.FolderMoved), Save both's copy and its clean-up, server render filing (503
folder_moved, the upload kept), export downloads, render jobs as they start, proxies sent and
proxy passes, the deep analysis checkpoint and the editor's project save. A thumbnail pass
refuses a sidecar of another sequence before it opens the pack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit b406a4f6a9a7a3121e9e40289663fb62ee31948e)
This commit is contained in:
Alby96 committed 2026-10-27 20:36:20 +01:00
1 parent 26b03d1c6d
commit 8c2b9f1bfe
17 files changed
+260 -57

No files matched your search

+8 -5
View File
@@ -168,7 +168,8 @@ public sealed class ArchiveImages
/// 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 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"/>).
/// index moved, which this index finds at its next scan, takes nothing, nor does that folder when it holds another
/// sequence now: <see cref="ProxyStoreResult.Gone"/>).
/// </summary>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than the lease wait.</exception>
@@ -191,7 +192,7 @@ public sealed class ArchiveImages
{
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;
if (!SequenceFolders.Holds(folder, row.Id)) return ProxyStoreResult.Gone;
Directory.CreateDirectory(folder.Proxies);
var path = folder.Proxy(frame.Index);
AtomicFile.WriteAllBytes(path, jpeg);
@@ -226,6 +227,8 @@ public sealed class ArchiveImages
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
manifest = ManifestStore.ReadSequence(folder.ManifestPath);
// Another sequence's folder now (another index moved this one away and that one in): its pack is never opened.
if (manifest.Id != sequence.Id) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
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++)
@@ -298,8 +301,8 @@ public sealed class ArchiveImages
/// 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}"/>). 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.
/// has it (another index moved it, until this index's next scan), or that holds another sequence now, 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)
@@ -324,7 +327,7 @@ public sealed class ArchiveImages
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, sequence, cancellationToken).ConfigureAwait(false);
if (!Directory.Exists(folder.Folder)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
if (!SequenceFolders.Holds(folder, sequence.Id)) 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;
+14 -15
View File
@@ -188,33 +188,32 @@ public sealed class ArchiveIndexer
/// <summary>
/// The render rows of the archive that follow a sequence's folder from <paramref name="from"/> to <paramref name="to"/>,
/// in the caller's transaction (<see cref="Repositories.RenderRepository.RebaseFolderAsync"/>). An export is a file, or
/// a folder for an image sequence. It is at its old path still when it is there, the new path is not the same one (on a
/// file system that ignores case it is, when only the case changed) and the old folder holds no other sequence now. The
/// sequence's own exports inside the folder follow unless they are at the old path still and not at the new one:
/// written there after the move by a writer that read the old folder, which created it again, so the row keeps naming
/// where the export is. Another sequence's export follows only when it moved with the folder (at its new path and no
/// longer at the old one). An export missing from both places follows if it is the sequence's own, and so does one whose
/// old path is another sequence's: a sequence that moved into the old folder since brought an export of that name.
/// a folder for an image sequence. It is at its old path still when it is there and the new path is not the same one
/// (on a file system that ignores case it is, when only the case changed). The sequence's own exports inside the folder
/// follow unless they are at the old path still and not at the new one: written there after the move by a writer that
/// read the old folder, which created it again, so the row keeps naming where the export is. An export of its own
/// missing from both places follows, and so does one at its old path when the old folder holds another sequence now:
/// that sequence moved into it since and brought an export of that name. Another sequence's export follows only when it
/// moved with the folder (at its new path and no longer at the old one), and an export of the sequence the old folder
/// holds now never does: that one is in its own folder, whatever the moving sequence took along under the same name.
/// </summary>
internal static Task<int> RebaseRendersAsync(ChronosRepositories tx, Archive archive, Guid sequenceId, string from, string to,
CancellationToken cancellationToken)
{
var paths = new ArchivePaths(archive.RootPath);
// Read once, and only for an export found at its old path.
bool? taken = null;
return tx.Renders.RebaseFolderAsync(archive.Id, sequenceId, from, to, (before, after, own) =>
// The sequence the old folder holds now, when another one: read once, and only when a row asks.
var holder = new Lazy<Guid?>(() => SequenceFolders.OtherSequence(paths.Sequence(from), sequenceId), LazyThreadSafetyMode.None);
return tx.Renders.RebaseFolderAsync(archive.Id, sequenceId, from, to, (before, after, owner) =>
{
var own = owner == sequenceId;
if (!own && owner == holder.Value) return false;
var moved = Path.Exists(paths.FromRelative(after));
var behind = !string.Equals(before, after, StringComparison.OrdinalIgnoreCase) && Path.Exists(paths.FromRelative(before))
&& !(taken ??= TakenByAnother(paths.Sequence(from), sequenceId));
&& !(own && holder.Value is not null);
return own ? moved || !behind : moved && !behind;
}, cancellationToken);
}
/// <summary>Whether <paramref name="folder"/> is another sequence's now: its sidecar names another id.</summary>
private static bool TakenByAnother(SequencePaths folder, Guid sequenceId) =>
File.Exists(folder.ManifestPath) && SequenceTrash.SidecarId(folder.ManifestPath) is { } id && id != sequenceId;
/// <summary>
/// Remembers the current stamps of a folder whose sidecar and index were just updated together, so the next
/// incremental scan does not re-read what is already indexed.
@@ -0,0 +1,24 @@
using Chronos.Core.Archiving;
namespace Chronos.Data.Archiving;
/// <summary>Whether a sequence is in the folder the index has for it, as writers that file into that folder ask.</summary>
public static class SequenceFolders
{
/// <summary>
/// Whether <paramref name="folder"/>, the one the index has for sequence <paramref name="sequenceId"/>, holds it: the
/// folder is there and its sidecar, when it has one, names no other sequence. Another index of the archive that moved
/// the sequence away may have moved another one into the folder it left since; until this index's next scan finds both,
/// a writer of the sequence files nothing there, exactly as when the folder is missing, so none of its writes lands in
/// the other sequence's folder.
/// </summary>
public static bool Holds(SequencePaths folder, Guid sequenceId)
{
ArgumentNullException.ThrowIfNull(folder);
return Directory.Exists(folder.Folder) && OtherSequence(folder, sequenceId) is null;
}
/// <summary>The sequence other than <paramref name="sequenceId"/> whose sidecar <paramref name="folder"/> holds; null when none does.</summary>
internal static Guid? OtherSequence(SequencePaths folder, Guid sequenceId) =>
File.Exists(folder.ManifestPath) && SequenceTrash.SidecarId(folder.ManifestPath) is { } id && id != sequenceId ? id : null;
}
@@ -22,7 +22,8 @@ namespace Chronos.Data.Processing.Jobs;
/// output is recorded at once (its row id derives from the job and the entry, so every attempt knows what is recorded).
/// Checkpoint: the entries recorded and the output being written, so a crashed attempt's leftovers are removed and only
/// unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone. A
/// sequence whose folder is not where the index has it (another index moved it, until this index's next scan) is refused.
/// sequence whose folder is not where the index has it (another index moved it, until this index's next scan; the folder
/// it left may hold another sequence now) is refused.
/// </summary>
internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions options, FrameTiers tiers) : IJobHandler
{
@@ -42,8 +43,8 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
// A folder another index moved is found by this index's next scan. Until then nothing renders: its photos would all be
// stand-ins, and its outputs would create the old folder again.
if (!Directory.Exists(folder.Folder)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
// stand-ins, and its outputs would create the old folder again, or land among the exports of a sequence moved into it.
if (!SequenceFolders.Holds(folder, sequence.Id)) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
// A server writes only inside its archive (BRIEF §14.2): an export folder chosen on a client means nothing there.
if (options.Host == EncoderHost.Server) export = export with { Folder = null };
var project = (parameters.SettingsJson is { } embedded ? ProjectStore.Parse(embedded) : ProjectStore.Read(sequence, folder)) with { Export = export };
@@ -359,14 +359,15 @@ internal sealed class SequenceAnalyser(ChronosDatabase db, ProcessingOptions opt
}
/// <summary>
/// The sequence lock, taken while <paramref name="folder"/>, where the pass reads the frames, is still there: a
/// Reorganize, of this process or another sharing the archive, moves the folder under that lock's lease.
/// The sequence lock, taken while <paramref name="folder"/>, where the pass reads the frames, still holds the sequence: a
/// Reorganize, of this process or another sharing the archive, moves the folder under that lock's lease, and another one
/// may move another sequence into the folder it left.
/// </summary>
/// <exception cref="FolderMovedException">The folder moved since the pass read the sequence.</exception>
private async Task<IAsyncDisposable> InPlaceAsync(ArchivePaths paths, Sequence sequence, SequencePaths folder, CancellationToken cancellationToken)
{
var held = await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false);
if (Directory.Exists(folder.Folder)) return held;
if (SequenceFolders.Holds(folder, sequence.Id)) return held;
await held.DisposeAsync().ConfigureAwait(false);
throw new FolderMovedException();
}
@@ -57,9 +57,9 @@ public sealed class RenderRepository
/// into the old folder. Outputs elsewhere (absolute paths, other folders) stay as they are.
/// </summary>
/// <param name="follows">Whether the render at the first archive-relative path follows to the second one; the third
/// argument says whether it is one of the sequence's own.</param>
/// argument is the sequence it is an export of.</param>
/// <remarks>Only paths still under <paramref name="oldFolder"/> change, so repeating it after a crash is harmless.</remarks>
public async Task<int> RebaseFolderAsync(Guid archiveId, Guid sequenceId, string oldFolder, string newFolder, Func<string, string, bool, bool> follows,
public async Task<int> RebaseFolderAsync(Guid archiveId, Guid sequenceId, string oldFolder, string newFolder, Func<string, string, Guid, bool> follows,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(follows);
@@ -75,9 +75,8 @@ public sealed class RenderRepository
foreach (var (id, owner, path) in under)
{
var to = newFolder.Length == 0 ? path[prefix.Length..] : newFolder + path[oldFolder.Length..];
var own = owner == sequenceId;
var taken = own && under.Any(o => o.SequenceId != sequenceId && string.Equals(o.Path, path, StringComparison.Ordinal));
if (!taken && !follows(path, to, own)) continue;
var taken = owner == sequenceId && under.Any(o => o.SequenceId != sequenceId && string.Equals(o.Path, path, StringComparison.Ordinal));
if (!taken && !follows(path, to, owner)) continue;
rebased += await _db.ExecuteAsync("UPDATE renders SET output_path = $2 WHERE id = $1", [id, to], cancellationToken).ConfigureAwait(false);
}
return rebased;
+13 -8
View File
@@ -754,9 +754,10 @@ public sealed class SyncService
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. One another index moved is found by the next
// scan; nothing is written until then, so the folder it left is not created again.
// scan; nothing is written until then, so the folder it left is not created again, nor written in when it holds
// another sequence now.
var folder = paths.Sequence(row.Folder);
if (!Directory.Exists(folder.Folder)) return null;
if (!SequenceFolders.Holds(folder, row.Id)) return null;
payload = payload with { SettingsJson = current.SettingsJson };
var metadata = !payload.SameMetadata(SyncPayload.Of(row));
var settings = !SyncRules.SameSettings(payload.SettingsJson, row.SettingsJson);
@@ -808,7 +809,8 @@ public sealed class SyncService
/// "Save both": this PC's project is kept next to <c>project.json</c> as <c>project.this-pc-&lt;local time&gt;.json</c>
/// before the server's replaces it; returns that file. Written under the sequence's lease into its folder as the index
/// has it then: a Reorganize may have moved it while the server was asked, and the folder it left is never created again.
/// Null, with nothing written, when the sequence is not in that folder (another index moved it; the next scan finds it).
/// Null, with nothing written, when the sequence is not in that folder (another index moved it, and maybe another
/// sequence into it; the next scan finds them, <see cref="SequenceFolders.Holds"/>).
/// </summary>
private async Task<string?> SaveCopyAsync(Sequence local, CancellationToken cancellationToken)
{
@@ -820,7 +822,7 @@ public sealed class SyncService
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, local, cancellationToken).ConfigureAwait(false);
if (!Directory.Exists(folder.Folder)) return null;
if (!SequenceFolders.Holds(folder, local.Id)) return null;
Directory.CreateDirectory(folder.MetaDirectory);
path = Path.Combine(folder.MetaDirectory, SavedCopyName(DateTime.Now));
AtomicFile.WriteAllText(path, SyncRules.NormalizeSettings(local.SettingsJson));
@@ -831,7 +833,8 @@ public sealed class SyncService
/// <summary>
/// Whether the sequence is not in the folder the index has for it now, on an archive that is there: another index moved
/// it, and this index's next scan finds it. Read without the lease, to tell why a resolution wrote nothing.
/// it (and maybe another sequence into that folder), and this index's next scan finds it. Read without the lease, to
/// tell why a resolution wrote nothing.
/// </summary>
private async Task<bool> FolderMovedAsync(Sequence local, CancellationToken cancellationToken)
{
@@ -839,13 +842,14 @@ public sealed class SyncService
|| await _db.Archives.GetAsync(row.ArchiveId, cancellationToken).ConfigureAwait(false) is not { } archive)
return false;
var paths = new ArchivePaths(archive.RootPath);
return Directory.Exists(paths.Root) && !Directory.Exists(paths.Sequence(row.Folder).Folder);
return Directory.Exists(paths.Root) && !SequenceFolders.Holds(paths.Sequence(row.Folder), row.Id);
}
/// <summary>
/// Deletes a "Save both" copy of a version the user did not keep from the sequence's folder as the index has it now: a
/// Reorganize may have moved the folder, the copy with it, since the copy was written. Best effort: a copy that cannot
/// be reached (the folder gone, the sequence busy, the archive offline) stays, as one more copy of this PC's version.
/// be reached (the folder gone or another sequence's now, the sequence busy, the archive offline) stays, as one more
/// copy of this PC's version.
/// </summary>
private async Task DeleteCopyAsync(Sequence local, string saved, CancellationToken cancellationToken)
{
@@ -857,7 +861,8 @@ public sealed class SyncService
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, local, cancellationToken).ConfigureAwait(false);
if (Directory.Exists(folder.MetaDirectory)) File.Delete(Path.Combine(folder.MetaDirectory, Path.GetFileName(saved)));
if (SequenceFolders.Holds(folder, local.Id) && Directory.Exists(folder.MetaDirectory))
File.Delete(Path.Combine(folder.MetaDirectory, Path.GetFileName(saved)));
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
+3 -2
View File
@@ -379,12 +379,13 @@ internal sealed class SyncTransfers(SyncService sync)
// Filed under the sequence's lease into its folder as the index has it then, as a server files a render: a
// Reorganize may have moved it since the sequence was read, and moves the row's path along when it moves it later.
// One another index moved is found by this index's next scan; until then nothing is filed (the download stays
// staged for the next attempt), so the folder it left is not created again.
// staged for the next attempt), so the folder it left is not created again, nor filed into when it holds another
// sequence now.
var filed = await sync.Archives.UnderLeaseAsync(local, async row =>
{
if (row is null) throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
var folder = paths.Sequence(row.Folder);
if (!Directory.Exists(folder.Folder)) return false;
if (!SequenceFolders.Holds(folder, row.Id)) return false;
Directory.CreateDirectory(folder.Exports);
var target = Unique(folder.Exports, name);
File.Move(part, target);