fix(reorganize): take along a sequence left inside a moving folder; keep a plan whose archive is offline

A selected sequence nested in another selected sequence's moving folder moves
out first. When the templates no longer gave it its folder (its first photo
gone, or an earlier one filed), it stayed inside, and the outer step then found
it as a stranger: StaleRenamePlanException at every retry, the plan held forever.

- A moving folder now takes along the sequences of earlier steps that stayed
  inside it (their index row still there): locked, moved and recorded with it,
  keeping their title and file names. They are reported TitlesKept instead of
  Dropped; a carried sequence whose carrier stayed is simply changed (or
  TitlesKept when it was to change more than its folder); Newer stays Newer.
  RefuseStaleAsync exempts exactly those, so a held plan either fits or is given up.
- MoveJobHandler: a journal not found on an offline archive tells nothing. A
  failed job keeps its plan:<id> checkpoint instead of becoming 'applied', and a
  retry while the archive is offline fails with "archive offline" instead of
  logging ReorganizedEarlier and ending done.
- The Fit.Names warning now says what happens to the folder (moved already,
  carried, or not moved to the planned one); stale ApplyAsync, RefuseStaleAsync,
  FitAsync and job docs corrected.

Tests: the nested case (fresh run and held retry, three levels), the same through
a held job, a carrier named otherwise with a carried sequence, Fit.Names on a
resumed step whose folder moved (held and not), and an offline retry that keeps
its plan and completes it once the archive is back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c5ffc87f1a3900442920693763fd04d28cb43aee)
This commit is contained in:
Alby96 committed 2026-10-27 19:46:16 +01:00
1 parent 0ff5852f60
commit d0da224de5
3 files changed
+332 -50

No files matched your search

@@ -1157,4 +1157,197 @@ public sealed class ReorganizeTests(TestContext context)
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
/// <summary>"trips" with photos of its own, "trips/day2" inside it and "trips/day2/dawn" inside that, adopted by a scan; their ids in that order.</summary>
private static async Task<List<Guid>> NestedAsync(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips"), Start, 2);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2"), Start.AddDays(1), 3, firstSeed: 10);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2", "dawn"), Start.AddDays(2), 2, firstSeed: 20);
await fx.ScanAsync();
var locations = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).OrderBy(l => l.Folder, StringComparer.Ordinal).ToList();
Assert.SequenceEqual(["trips", "trips/day2", "trips/day2/dawn"], locations.Select(l => l.Folder));
return [.. locations.Select(l => l.Id)];
}
[Theory]
[Case(false)]
[Case(true)]
public async Task ASequenceLeftAsItWasInsideAFolderThatMovesGoesWithIt(bool held)
{
await using var fx = await CreateAsync(context);
var ids = await NestedAsync(fx);
var (trips, day2, dawn) = (ids[0], ids[1], ids[2]);
var templates = new RenameTemplates(Folder: "moved/{date} {time}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [trips, day2], templates, fx.Ct);
// The inner one moves out first, with the one inside it; then the folder around it moves.
Assert.SequenceEqual([(day2, false), (trips, false), (dawn, true)], plan.Steps.Select(s => (s.SequenceId, s.Carried)));
var title = (await fx.Db.Sequences.GetAsync(day2))!.Title;
var files = new List<string>();
// Once the plan's own checks passed, the first photo of the inner one goes to the trash: the templates now name it after another.
using var pause = new CancellationTokenSource();
Func<int, IReadOnlyList<Guid>, ValueTask>? stepDone = null;
if (held)
{
stepDone = (_, _) =>
{
pause.Cancel();
return ValueTask.CompletedTask;
};
}
var run = fx.Service.Renamer.ApplyAsync(fx.Archive, plan, async _ =>
{
await TrashFirstPhotoAsync(fx, day2);
files.AddRange((await fx.Db.Frames.ListBySequenceAsync(day2)).Select(f => f.FileName));
}, stepDone, pause.Token);
RenameResult result;
if (held)
{
// Its job paused once the inner one stayed, with the one inside it, and held the plan; retried, it goes on.
await Assert.ThrowsAsync<OperationCanceledException>(() => run);
Assert.SequenceEqual(new[] { day2, dawn }.Order(), Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Completed.Order());
Assert.True(MassRenamer.Hold(fx.Archive, plan.Id));
result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
}
else
{
result = await run;
}
// It stays in the folder around it, which moves as planned and takes it along with the one inside it: no index row
// is left behind, its title and file names stay, and neither is said to have stayed as it was.
Assert.SequenceEqual([trips, day2, dawn], result.Changed);
Assert.SequenceEqual([day2], result.TitlesKept);
Assert.Empty(result.Dropped);
Assert.Empty(result.CarriedKept);
Assert.Equal(("moved/2026-09-28 18-00-00", "moved/2026-09-28 18-00-00/day2", "moved/2026-09-28 18-00-00/day2/dawn"),
(await FolderAsync(fx, trips), await FolderAsync(fx, day2), await FolderAsync(fx, dawn)));
Assert.Equal(title, (await fx.Db.Sequences.GetAsync(day2))!.Title);
Assert.Count(2, files);
Assert.SequenceEqual(files, (await fx.Db.Frames.ListBySequenceAsync(day2)).Select(f => f.FileName));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task ARetriedJobTakesAlongASequenceLeftAsItWasInsideAFolderItMoves()
{
await using var fx = await CreateAsync(context);
var parent = await UploadAsync(fx, 2);
var folder = (await fx.Db.Sequences.GetAsync(parent))!.Folder;
Photos.WriteSeries(Path.Combine(fx.Paths.FromRelative(folder), "extra"), Start.AddDays(3), 3, firstSeed: 50);
await fx.ScanAsync();
var nested = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == folder + "/extra").Id;
var templates = new RenameTemplates(Folder: "moved/{date} {time}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [parent, nested], templates, fx.Ct);
Assert.SequenceEqual([nested, parent], plan.Steps.Select(s => s.SequenceId));
var name = plan.Steps[0].ToTitle ?? plan.Steps[0].FromFolder;
// Its job held the plan before its first step (paused); the first photo of the inner one then went to the trash.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, [], Held: true));
await TrashFirstPhotoAsync(fx, nested);
// Resumed, the job moves the folder around it as planned, with it inside, and fails for it alone: never for the plan.
var engine = await fx.StartEngineAsync();
var failed = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Reorganize(fx.Archive, plan, templates),
"plan:" + plan.Id.ToString("N"))).Id, JobState.Failed);
Assert.Equal(Loc.Plural("Archive.Error.ReorganizeKept", 1), failed.Error);
Assert.Contains(Loc.L("Archive.Log.Reorganized", 2, 0), failed.LogTail);
Assert.Contains(Loc.L("Archive.Log.ReorganizeTitleKept", name), failed.LogTail);
Assert.False(failed.LogTail!.Contains(Loc.L("Archive.Log.ReorganizeDropped", name), StringComparison.Ordinal), failed.LogTail);
Assert.Equal(("moved/2026-09-28 18-00-00", "moved/2026-09-28 18-00-00/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested)));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AFolderNamedAfterAPhotoNoLongerFirstStaysWithTheSequencesInside()
{
await using var fx = await CreateAsync(context);
var parent = await UploadAsync(fx, 3);
var folder = (await fx.Db.Sequences.GetAsync(parent))!.Folder;
Photos.WriteSeries(Path.Combine(fx.Paths.FromRelative(folder), "extra"), Start.AddDays(3), 2, firstSeed: 50);
await fx.ScanAsync();
var nested = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == folder + "/extra").Id;
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [parent], new RenameTemplates(Folder: "moved/{date} {time}", File: "{n:000}"), fx.Ct);
Assert.SequenceEqual([(parent, false, 3), (nested, true, 0)], plan.Steps.Select(s => (s.SequenceId, s.Carried, s.FileChanges)));
var files = new List<string>();
// Once the plan's own checks passed, the first photo of the folder that carries the other goes to the trash.
var result = await fx.Service.Renamer.ApplyAsync(fx.Archive, plan, async _ =>
{
await TrashFirstPhotoAsync(fx, parent);
files.AddRange(await FilesAsync(fx, parent));
}, null, fx.Ct);
// It stays as it was, and the one inside stays with it, told why; the plan is over.
Assert.SequenceEqual([parent], result.Dropped);
Assert.SequenceEqual([nested], result.CarriedKept);
Assert.Empty(result.Changed);
Assert.Equal((folder, folder + "/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested)));
Assert.SequenceEqual(files, await FilesAsync(fx, parent));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Theory]
[Case(false)]
[Case(true)]
public async Task AStepWhoseFolderMovedBeforeItsFirstPhotoWentKeepsItsTitleAndFileNames(bool held)
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 3);
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: "moved/{date} {time}", File: "{n:000}", Title: "{time}"),
fx.Ct);
var step = plan.Steps.Single();
Assert.True(step is { ToFolder: "moved/2026-09-28 18-00-00", ToTitle: "18-00-00", FileChanges: 3 });
// The first photo went to the trash; a run of the plan was then interrupted (or failed, and its job held it) once
// the folder moved, before its index row followed.
await TrashFirstPhotoAsync(fx, id);
var before = await FilesAsync(fx, id);
RenameJournal.Write(fx.Paths, new RenameJournal(plan, [], Held: held));
RenamePlanner.MoveFolder(fx.Paths, step);
// Resumed, its index row follows the folder; the title and file names stay, the templates naming it after another photo now.
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([id], result.TitlesKept);
Assert.SequenceEqual([id], result.Changed);
Assert.Empty(result.Dropped);
Assert.Equal(0, result.Files);
Assert.Equal("moved/2026-09-28 18-00-00", await FolderAsync(fx, id));
Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AJobRetriedWhileTheArchiveIsOfflineKeepsItsPlanForTheNextRetry()
{
var root = context.CreateTempDirectory("archive");
await using var fx = await CreateAsync(context, root);
var first = await UploadAsync(fx, 2);
var second = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2");
var templates = new RenameTemplates(File: "{n:000}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second], templates, fx.Ct);
// Its job held the plan before its first step (paused); the drive was then unplugged.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, [], Held: true));
var unplugged = root + "-unplugged";
Directory.Move(root, unplugged);
// Retried, the job fails as the archive does: no journal found there says nothing, and it keeps its plan.
var engine = await fx.StartEngineAsync();
var checkpoint = "plan:" + plan.Id.ToString("N");
var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Reorganize(fx.Archive, plan, templates), checkpoint);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Archive.Error.Offline", fx.Paths.Root), failed.Error);
Assert.Equal(checkpoint, failed.Checkpoint);
Assert.False(failed.LogTail!.Contains(Loc.L("Archive.Log.ReorganizedEarlier"), StringComparison.Ordinal), failed.LogTail);
// Plugged in again, the next retry completes the plan.
Directory.Move(unplugged, root);
await engine.ResumeAsync(job.Id, fx.Ct);
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.Reorganized", 2, 4), done.LogTail);
foreach (var id in new[] { first, second }) Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
}