From f8c445fac371f923f26b44216217967891270506 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 27 Oct 2026 21:02:35 +0100 Subject: [PATCH] fix(archive): a third sequence's export follows its file; resumed renders and restored originals stay out of folders a sequence left Round 5 stopped clearing "behind" for rows of a third sequence (neither the one moving nor the one now holding the old folder). Such a row, an export one sequence saved in another's exports through the Export folder picker, then stayed at its old path whenever the sequence that moved into the folder brought an export of the same name, and named that sequence's file (Send exports would upload it). A file at the old path is never "behind" while the old folder holds another sequence: it is that sequence's, so every row other than the holder's follows its file. A resumed render job deleted the output its crashed attempt was writing at the absolute path in the checkpoint. After another index moved the sequence away and another sequence into the folder it left, and this index scanned, that path named the other sequence's export. The checkpoint now keeps the sequence's folder when the output was chosen; a pending output there is rebased into the folder the sequence is in now, one in the sequence's current exports or outside the archive (an export folder chosen on a client) is discarded as before, and one anywhere else in the archive is left alone (the entry renders under another name). Older checkpoints, without the folder, only discard in the current exports. Download originals put an original flagged missing back at the path read before the transfer, with no lease and no check of the folder: after another index moved the sequence, it recreated the folder it left or filed the photo among another sequence's originals. The restores now run after the transfers under the sequence's lease, in the folder the index has then, which must hold the sequence (SequenceFolders.Holds), at each frame's path read under that lease. Otherwise nothing is restored, the copies stay staged for the next attempt and the job fails with Errors.Archive.FolderMoved after its other work. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit ad46ef68180845de4b9b605a4ce2529a148c6f13) --- src/Chronos.Data/Archiving/ArchiveIndexer.cs | 18 +++--- .../Processing/Jobs/RenderJobHandler.cs | 28 +++++++-- src/Chronos.Data/Processing/ProcessingJobs.cs | 5 +- src/Chronos.Data/Sync/SyncTransfers.cs | 61 ++++++++++++++----- .../Archiving/MassRenameTests.cs | 34 +++++++++++ .../Processing/RenderJobTests.cs | 44 +++++++++++++ .../Sync/SyncTransferTests.cs | 49 +++++++++++++++ 7 files changed, 210 insertions(+), 29 deletions(-) diff --git a/src/Chronos.Data/Archiving/ArchiveIndexer.cs b/src/Chronos.Data/Archiving/ArchiveIndexer.cs index b85b400c..f3c3934a 100644 --- a/src/Chronos.Data/Archiving/ArchiveIndexer.cs +++ b/src/Chronos.Data/Archiving/ArchiveIndexer.cs @@ -188,14 +188,14 @@ public sealed class ArchiveIndexer /// /// The render rows of the archive that follow a sequence's folder from to , /// in the caller's transaction (). An export is a file, or - /// 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. + /// 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: a + /// file there is that sequence's, which moved into the folder since and brought an export of that name. 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 too. 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. /// internal static Task RebaseRendersAsync(ChronosRepositories tx, Archive archive, Guid sequenceId, string from, string to, CancellationToken cancellationToken) @@ -209,7 +209,7 @@ public sealed class ArchiveIndexer 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)) - && !(own && holder.Value is not null); + && holder.Value is null; return own ? moved || !behind : moved && !behind; }, cancellationToken); } diff --git a/src/Chronos.Data/Processing/Jobs/RenderJobHandler.cs b/src/Chronos.Data/Processing/Jobs/RenderJobHandler.cs index 3f7ce48a..70e9be93 100644 --- a/src/Chronos.Data/Processing/Jobs/RenderJobHandler.cs +++ b/src/Chronos.Data/Processing/Jobs/RenderJobHandler.cs @@ -20,8 +20,9 @@ namespace Chronos.Data.Processing.Jobs; /// preset render after one preparation pass into the sequence's exports/ (or the export folder, never on a /// server), named by the template without taking a name another render of this process is writing, and each finished /// 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 +/// Checkpoint: the entries recorded and the output being written, so a crashed attempt's leftovers are removed (where a +/// Reorganize took them since, never in the folder the sequence left, ) 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; the folder /// it left may hold another sequence now) is refused. /// @@ -59,7 +60,8 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt { if (!done.Contains(i) && await db.Renders.GetAsync(RenderId(context.Job.Id, i), cancellation).ConfigureAwait(false) is not null) done.Add(i); } - if (resume is { Pending: { } pending, PendingOutput: { } output } && !done.Contains(pending) && names.TryReserve(output)) + if (resume is { Pending: { } pending, PendingOutput: { } chosen } && !done.Contains(pending) + && Leftover(paths, folder, resume.Folder, chosen) is { } output && names.TryReserve(output)) { // Unless another render recorded that name since (the output did not exist yet when it chose it). var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false); @@ -78,7 +80,7 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt outcomes = await render.RenderAllAsync( targets, (target, setup) => names.Reserve(taken => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), taken)), - (index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total), + (index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path, sequence.Folder).ToJson(), context.Done, context.Total), async (index, target, result) => { // The output is complete: record it even if the job is being cancelled, so it is never orphaned. @@ -149,6 +151,24 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt return new Guid(hash[..16], bigEndian: true); } + /// + /// Where the output a crashed attempt was writing is now, for its leftovers to be removed: among the exports of the + /// sequence's folder (the one the index has now, which holds the sequence; one chosen in the folder the sequence had + /// before a Reorganize moved it is where the folder took it), or in an export folder chosen on a client outside the + /// archive. Null, and the leftovers stay, for one anywhere else in the archive: an export folder chosen in it, or the + /// exports of a folder the sequence left, which may hold another sequence now with its own export of that name. + /// + /// The sequence's archive-relative folder when the attempt chose the output; null when unknown. + private static string? Leftover(ArchivePaths paths, SequencePaths folder, string? chosenIn, string output) + { + var relative = paths.ToRelative(output); + if (relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative)) return output; + var cut = relative.LastIndexOf('/'); + var (parent, name) = (cut < 0 ? string.Empty : relative[..cut], relative[(cut + 1)..]); + if (parent == paths.ToRelative(folder.Exports)) return output; + return chosenIn is not null && parent == paths.ToRelative(paths.Sequence(chosenIn).Exports) ? Path.Combine(folder.Exports, name) : null; + } + /// /// Removes what an interrupted attempt left of : the encoder's hidden temporary file or /// folder, and an output that was completed but never recorded (it renders again under the same name). diff --git a/src/Chronos.Data/Processing/ProcessingJobs.cs b/src/Chronos.Data/Processing/ProcessingJobs.cs index 7c669cc8..f361b269 100644 --- a/src/Chronos.Data/Processing/ProcessingJobs.cs +++ b/src/Chronos.Data/Processing/ProcessingJobs.cs @@ -156,9 +156,10 @@ public static class ProcessingJobs /// /// Resume point of a render job: the batch targets already recorded, and the output a crashed attempt was writing -/// (its leftovers are removed before that target renders again). +/// (its leftovers are removed before that target renders again) with the sequence's archive-relative folder when it +/// chose that output (null in checkpoints written before it was kept), so the leftovers are found after a Reorganize. /// -internal sealed record RenderCheckpoint(IReadOnlyList Done, int? Pending, string? PendingOutput) +internal sealed record RenderCheckpoint(IReadOnlyList Done, int? Pending, string? PendingOutput, string? Folder = null) { public static RenderCheckpoint Empty { get; } = new([], null, null); diff --git a/src/Chronos.Data/Sync/SyncTransfers.cs b/src/Chronos.Data/Sync/SyncTransfers.cs index 99e7c9a4..da3ea16f 100644 --- a/src/Chronos.Data/Sync/SyncTransfers.cs +++ b/src/Chronos.Data/Sync/SyncTransfers.cs @@ -25,7 +25,8 @@ namespace Chronos.Data.Sync; /// original the server has not hashed yet, its size, and hash it here) and commit them through the archive ingest, /// which names them and writes the sidecar; the first original creates the local /// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the -/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place. +/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place in +/// the folder the sequence is in (never one it left). /// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked /// upload) and the server's into the local copy's exports. A resumed job skips what is already on the other side, so /// pausing or a crash loses at most the files in flight. @@ -244,14 +245,14 @@ internal sealed class SyncTransfers(SyncService sync) await progress.StepAsync().ConfigureAwait(false); } var sequenceId = local?.Id; - int restored = 0, refused = 0; + var refused = 0; + var restores = new ConcurrentBag<(string Staged, Guid FrameId)>(); await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) => { var (staged, sha) = await FetchOriginalAsync(remote, frame, staging, token).ConfigureAwait(false); - if (restore.TryGetValue(sha, out var place)) + if (restore.TryGetValue(sha, out var frameId)) { - Restore(staged, place); - Interlocked.Increment(ref restored); + restores.Add((staged, frameId)); } else if (frame.Sha256.Length == 0 && (tombstones.DeletedLocally(sha) || have.Contains(tombstones.Canonical(sha)!))) { @@ -267,26 +268,30 @@ internal sealed class SyncTransfers(SyncService sync) } await progress.StepAsync().ConfigureAwait(false); }).ConfigureAwait(false); - TryDeleteDirectory(staging); + // Null when the sequence is not in the folder the index has: the copies stay staged for the next attempt. + var restored = restores.IsEmpty ? 0 : await RestoreAsync(local!, paths, restores, ct).ConfigureAwait(false); + if (restored is not null) TryDeleteDirectory(staging); // Restored originals are checked against their records, which clears their missing flag. if (restored > 0) await VerifyAsync(archive, local!.Id, ct).ConfigureAwait(false); if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false); await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false); - if (sequenceId is { } downloaded && wanted.Count > restored + refused) + if (sequenceId is { } downloaded && wanted.Count > restores.Count + refused) { var label = local!.DisplayTitle; await EnqueueFollowUpAsync(context, ArchiveJobs.Thumbnails([downloaded], label)).ConfigureAwait(false); await EnqueueFollowUpAsync(context, ProcessingJobs.LightAnalysis([downloaded], label)).ConfigureAwait(false); } + if (restored is null) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved")); } /// - /// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and where - /// each original flagged missing belongs. Frames not hashed yet (an adopted folder never verified) are hashed first - /// through the archive's verify, so the server's copies of them are recognised instead of committed again as duplicates. + /// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and the + /// frame each original flagged missing restores. Frames not hashed yet (an adopted folder never verified) are hashed + /// first through the archive's verify, so the server's copies of them are recognised instead of committed again as + /// duplicates. /// - private async Task<(HashSet Have, Dictionary Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local, + private async Task<(HashSet Have, Dictionary Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local, CancellationToken ct) { var frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false); @@ -297,12 +302,11 @@ internal sealed class SyncTransfers(SyncService sync) } var have = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0 && f.Sha256 is not null).Select(f => f.Sha256!.ToLowerInvariant()) .ToHashSet(StringComparer.Ordinal); - var paths = new ArchivePaths(archive.RootPath); - var restore = new Dictionary(StringComparer.Ordinal); + var restore = new Dictionary(StringComparer.Ordinal); foreach (var frame in frames.Where(f => (f.Flags & FrameFlags.Missing) != 0 && f.Sha256 is not null)) { var sha = frame.Sha256!.ToLowerInvariant(); - if (!have.Contains(sha)) restore.TryAdd(sha, paths.FromRelative(frame.RelativePath)); + if (!have.Contains(sha)) restore.TryAdd(sha, frame.Id); } var photos = SyncRules.Photos([.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0)]); return (have, restore, photos); @@ -311,6 +315,35 @@ internal sealed class SyncTransfers(SyncService sync) private Task VerifyAsync(Archive archive, Guid sequenceId, CancellationToken ct) => sync.Archives.Verifier.VerifyAsync(archive, [sequenceId], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: ct); + /// + /// Puts the verified copies of originals flagged missing (, each with the frame it restores) + /// back where their records say, under the sequence's lease in its folder as the index has it then: a Reorganize moves + /// the folder and the frames' paths under that lease. Returns how many went back; a file that reappeared meanwhile is + /// kept, and the copy of a frame that left the index is dropped. Null, with nothing restored and every copy kept in + /// staging for the next attempt, when the sequence is not in that folder (another index moved it, and maybe another + /// sequence into it; this index's next scan finds them): the folder it left is not created again, nor given an + /// original of this sequence when it holds another one now. + /// + private Task RestoreAsync(Sequence local, ArchivePaths paths, IReadOnlyCollection<(string Staged, Guid FrameId)> staged, CancellationToken ct) => + sync.Archives.UnderLeaseAsync(local, async row => + { + if (row is null) throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing")); + if (!SequenceFolders.Holds(paths.Sequence(row.Folder), row.Id)) return (int?)null; + var restored = 0; + foreach (var (copy, frameId) in staged) + { + // Read under the lease, as the folder: where the photo belongs in the folder the sequence is in now. + if (await sync.Database.Frames.GetAsync(frameId, ct).ConfigureAwait(false) is not { } frame || frame.SequenceId != row.Id) + { + File.Delete(copy); + continue; + } + Restore(copy, paths.FromRelative(frame.RelativePath)); + restored++; + } + return restored; + }, ct); + /// Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept. private static void Restore(string staged, string place) { diff --git a/tests/Chronos.Data.Tests/Archiving/MassRenameTests.cs b/tests/Chronos.Data.Tests/Archiving/MassRenameTests.cs index 86ee6a6b..1037a9a8 100644 --- a/tests/Chronos.Data.Tests/Archiving/MassRenameTests.cs +++ b/tests/Chronos.Data.Tests/Archiving/MassRenameTests.cs @@ -391,6 +391,40 @@ public sealed class MassRenameTests(TestContext context) } } + [Test] + public async Task AnExportSavedInAnotherSequencesFolderNeverNamesTheOneBroughtIntoIt() + { + // The new folder is scanned after "inbox/a", then before it. + foreach (var template in new[] { "moved/{date}", "done/{date}" }) + { + await using var fx = await CreateAsync(context); + var ids = await PopulateAsync(fx); + // "inbox/b" saved an export in the exports of "inbox/a" (the Export tab's folder picker); "inbox/c" has one of the same name. + List renders = + [ + await RenderAsync(fx, ids[1], "inbox/a/exports/Clip.mp4"), + await RenderAsync(fx, ids[2], "inbox/c/exports/Clip.mp4"), + ]; + await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/a/exports/Clip.mp4"), "b", fx.Ct); + await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/c/exports/Clip.mp4"), "c", fx.Ct); + var (server, archive) = await fx.OtherWriterAsync(); + + // The other index moves "inbox/a", the export of "inbox/b" along, then "inbox/c" into the folder it left, its export along. + var first = await server.PlanRenameAsync(archive.Id, [ids[0]], template, null, fx.Ct); + await server.ApplyRenameAsync(first, null, fx.Ct); + await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [ids[2]], "inbox/a", null, fx.Ct), null, fx.Ct); + + // The export of "inbox/b" follows the folder its file moved with and never names the one of "inbox/c". + await fx.ScanAsync(); + string[] expected = [first.Steps.Single().ToFolder + "/exports/Clip.mp4", "inbox/a/exports/Clip.mp4"]; + Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), template); + Assert.Equal("b", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[0]), fx.Ct), template); + Assert.Equal("c", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[1]), fx.Ct), template); + Assert.Equal(0, (await fx.ScanAsync()).Indexed); + Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), template); + } + } + [Test] public async Task APhotoDeletionWhoseFolderMovedWhileItWaitedForTheLeaseIsRefused() { diff --git a/tests/Chronos.Data.Tests/Processing/RenderJobTests.cs b/tests/Chronos.Data.Tests/Processing/RenderJobTests.cs index b60e4f99..abacdad5 100644 --- a/tests/Chronos.Data.Tests/Processing/RenderJobTests.cs +++ b/tests/Chronos.Data.Tests/Processing/RenderJobTests.cs @@ -375,6 +375,50 @@ public sealed class RenderJobTests(TestContext context) Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)); } + [Test] + public async Task ARenderResumedAfterItsFolderMovedNeverDeletesWhatAnotherSequenceBroughtIntoIt() + { + // The crashed attempt's checkpoint names the folder it chose the output in, or (written by an older version) does not. + foreach (var named in new[] { true, false }) + { + await using var fx = await ProcessingFixture.CreateAsync(context); + var sequence = await fx.AddAsync(Scene()); + var stranger = await fx.AddAsync(Scene(), "Other"); + var output = Path.Combine(fx.Folder(sequence).Exports, "clip-MJPEG.avi"); + // The crashed attempt left its encoder's temporary file and a finished output it never recorded; the other + // sequence has an export of that name, and a hidden file that looks like such a leftover. + Directory.CreateDirectory(fx.Folder(sequence).Exports); + await File.WriteAllBytesAsync(Path.Combine(fx.Folder(sequence).Exports, ".clip-MJPEG.avi.0badf00d.tmp"), new byte[100], fx.Ct); + await File.WriteAllBytesAsync(output, new byte[100], fx.Ct); + Directory.CreateDirectory(fx.Folder(stranger).Exports); + await File.WriteAllBytesAsync(Path.Combine(fx.Folder(stranger).Exports, ".clip-MJPEG.avi.0ddba11.tmp"), new byte[50], fx.Ct); + await File.WriteAllBytesAsync(Path.Combine(fx.Folder(stranger).Exports, "clip-MJPEG.avi"), Encoding.ASCII.GetBytes("RIFF theirs"), fx.Ct); + + // Another index moves the folder away, the leftovers along, then the other sequence into the folder it left; this + // index's scan finds both before the job resumes. + 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 server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [stranger.Id], sequence.Folder, null, fx.Ct), null, fx.Ct); + await fx.Archive.ScanAsync(); + var before = ArchiveFixture.FilesOf(fx.Folder(sequence).Folder); + await fx.StartEngineAsync(); + + var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg, 96, 64), + new RenderCheckpoint([], 0, output, named ? sequence.Folder : null).ToJson()); + await fx.WaitForAsync(job.Id, JobState.Done); + + Assert.SequenceEqual(before, ArchiveFixture.FilesOf(fx.Folder(sequence).Folder), $"{named}: the other sequence's files are untouched"); + // Its leftovers are removed where the folder took them when the checkpoint says where it chose the output, and + // stay otherwise: the render then takes another name. + var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder).Exports; + Assert.SequenceEqual(named ? ["clip-MJPEG.avi"] : [".clip-MJPEG.avi.0badf00d.tmp", "clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(moved), named.ToString()); + var rendered = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).Single().OutputPath; + Assert.Equal(plan.Steps.Single().ToFolder + (named ? "/exports/clip-MJPEG.avi" : "/exports/clip-MJPEG (2).avi"), rendered); + Assert.Equal("RIFF", Encoding.ASCII.GetString((await File.ReadAllBytesAsync(fx.Archive.Paths.FromRelative(rendered), fx.Ct))[..4])); + } + } + [Test] public async Task ConcurrentRendersOfOnePresetKeepBothOutputs() { diff --git a/tests/Chronos.Data.Tests/Sync/SyncTransferTests.cs b/tests/Chronos.Data.Tests/Sync/SyncTransferTests.cs index a748828c..fea24a8e 100644 --- a/tests/Chronos.Data.Tests/Sync/SyncTransferTests.cs +++ b/tests/Chronos.Data.Tests/Sync/SyncTransferTests.cs @@ -6,6 +6,7 @@ using Chronos.Core.Model; using Chronos.Core.Project; using Chronos.Core.Render; using Chronos.Data.Sync; +using Chronos.Data.Tests.Archiving; using Chronos.Protocol; using Chronos.Testing; @@ -384,6 +385,54 @@ public sealed class SyncTransferTests(TestContext context) Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status); } + [Test] + public async Task AnOriginalIsRestoredOnlyWhereTheSequenceIsNow() + { + // The folder the sequence left holds another sequence now, or nothing. + foreach (var taken in new[] { true, false }) + { + await using var f = await SyncFixture.CreateAsync(context); + var photos = f.NewPhotos(3); + var local = await f.LocalAsync("Harbour", photos); + var stranger = taken ? await f.LocalAsync("Stranger", f.NewPhotos(2)) : null; + var lost = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1]; + File.Delete(f.Archive.Paths.FromRelative(lost.RelativePath)); + await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct); + var remote = f.Remote.Add("Harbour", photos); + await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct); + await f.RefreshAsync(); + var engine = await f.StartEngineAsync(); + + // Another index moves the folder away, then the other sequence (first parked elsewhere: its folder is the same + // name with a number) into the folder it left; this index has scanned neither. + var folder = f.Archive.Paths.Sequence(local.Folder).Folder; + var (other, archive) = await f.Archive.OtherWriterAsync(); + var moves = stranger is null ? [(local.Id, "moved/{title}")] : new[] { (local.Id, "moved/{title}"), (stranger.Id, "parked/{title}"), (stranger.Id, local.Folder) }; + foreach (var (id, template) in moves) + await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], template, null, f.Ct), null, f.Ct); + var before = taken ? ArchiveFixture.FilesOf(folder) : null; + + var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null); + var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed); + Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error, taken.ToString()); + if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are untouched"); + else Assert.False(Directory.Exists(folder), "the folder it left is not created again"); + + // Once this index's scan found it there, the original goes back into the folder the sequence is in now. + await f.Archive.ScanAsync(); + job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null); + await f.Archive.WaitForAsync(job.Id, JobState.Done); + var moved = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Folder; + Assert.Equal("moved/Harbour", moved); + var restored = (await f.Db.Frames.GetAsync(lost.Id, f.Ct))!; + Assert.Equal(moved + lost.RelativePath[local.Folder.Length..], restored.RelativePath); + Assert.Equal(lost.Sha256, Sha(await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(restored.RelativePath), f.Ct))); + Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).All(fr => (fr.Flags & FrameFlags.Missing) == 0), "nothing missing"); + if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are still untouched"); + else Assert.False(Directory.Exists(folder)); + } + } + [Test] public async Task OriginalsTheServerHasNotHashedAreDownloadedAndHashedHere() {