fix(reorganize): never name a folder or title after a photo no longer first, and retry a kept job honestly

A Reorganize step whose photos changed after the plan kept its file names but still moved its folder and wrote
the title the plan had computed from the old first photo, so a trashed first photo or an earlier photo filed
since left the sequence named after a photo that is no longer first. The plan now journals its folder and
title templates, and under the step's leases each folder move or retitle is expanded again from the settled
sidecar: it is applied only when it gives what the plan gives (the folder itself or its " (n)"); otherwise the
sequence stays as it was (Dropped, "changed after the plan"), or keeps its title and file names when an
interrupted run moved its folder already (TitlesKept). Plans journaled before this change are applied as made.

A Move job that ended failed with sequences kept, or whose held plan was given up, kept its plan:<id>
checkpoint after the plan's journal was gone, so a retry logged "completed when the archive was opened" and
ended done. Such a job now saves the checkpoint "applied": a retry plans again and applies only a plan that is
still the one confirmed. A job that succeeds keeps plan:<id>, so a crash before it is marked done still finds
the plan completed.

Sequences a folder was to carry when that folder stayed (dropped, its title edited, its names no longer given,
or a newer sidecar) were reported as "changed after the plan", and a newer-format carrier failed the job with
ReorganizeKept. They are now a separate outcome, CarriedKept (journaled), logged with the new
Archive.Log.ReorganizeCarriedKept (en+it) and not counted in the job's error, which follows the carrier's own
reason.

When a step's sidecar cannot be read or written after its folder moved, every sequence of the step is told
(sequenceChanged "reorganized") before the failure is thrown, since the retry that would tell them may never
come.

Tests: Core APlanKeepsItsTemplatesSoTheNamesOfAFirstPhotoNoLongerFirstAreTold; Data
AFolderOrTitleNamedAfterAPhotoNoLongerFirstIsNeverGiven, ARetryOfAJobThatKeptSequencesPlansAgain,
ASequenceAFolderWasToCarryIsToldItStayedWithIt, AnArchiveOpensWhenAnInterruptedRenameMeetsASidecarOfANewerFormat,
AResumedStepWhoseFolderMovedKeepsATitleEditedSinceAndTheNamesFromIt, and
AMovedFolderWhoseSidecarCannotBeReadThereHasItsIndexRowFollowAndIsTold, which breaks the sidecar with a
relative symbolic link instead of a read-only file, so it also runs on the Linux runner as root.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 130701afab224d47ea066eb7cc8debb16d1fb432)
This commit is contained in:
Alby96 committed 2026-10-27 19:16:27 +01:00
1 parent 37800b28ef
commit 8127373fd5
9 files changed
+455 -77

No files matched your search

@@ -932,4 +932,229 @@ public sealed class ReorganizeTests(TestContext context)
await FilesAsync(fx, parent);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AMovedFolderWhoseSidecarCannotBeReadThereHasItsIndexRowFollowAndIsTold()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
// The sidecar is a link, relative to where it lies, to a file outside the archive: one level deeper it leads nowhere.
// Unlike a read-only file, this holds whoever runs the test (root on the Linux runner).
var outside = Path.Combine(context.CreateTempDirectory("outside"), "sequence.json");
File.Move(folder.ManifestPath, outside);
try
{
File.CreateSymbolicLink(folder.ManifestPath, Path.GetRelativePath(folder.MetaDirectory, outside));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
File.Move(outside, folder.ManifestPath);
TestContext.Skip("needs symbolic links (Developer Mode on Windows)");
}
var deeper = string.Concat(Enumerable.Repeat("moved/", folder.RelativeFolder.Split('/').Length)) + "{date}";
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: deeper, Title: "Roof"), fx.Ct);
var to = plan.Steps.Single().ToFolder;
var told = new ConcurrentQueue<(Guid, string)>();
var service = new ArchiveService(fx.Db, new ArchiveServiceOptions
{
Owner = "test",
SequenceChanged = (sequence, change, _) =>
{
told.Enqueue((sequence, change));
return Task.CompletedTask;
},
});
// The new title cannot be read where the folder moved: its index row followed it all the same, and clients hear of it.
await Assert.ThrowsAsync<IOException>(() => service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.Equal(to, await FolderAsync(fx, id));
Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.SequenceEqual([(id, MassRenamer.Change)], told);
Assert.Empty(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Completed);
// Readable again, the retry completes the step.
var sidecar = fx.Paths.Sequence(to).ManifestPath;
File.Delete(sidecar);
File.Move(outside, sidecar);
var result = Assert.NotNull(await service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([id], result.Changed);
Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title);
await FilesAsync(fx, id);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
/// <summary>Moves the first photo of a sequence to the trash, as the editor's Delete does.</summary>
private static async Task TrashFirstPhotoAsync(ArchiveFixture fx, Guid id)
{
var sequence = Assert.NotNull(await fx.Db.Sequences.GetAsync(id));
var first = (await fx.Db.Frames.ListBySequenceAsync(id))[0];
var plan = await fx.Service.FrameTrash.PlanDeleteAsync(id, [first.Id], sequence.FramesVersion, fx.Ct);
Assert.True(plan.CanDelete, string.Join(", ", plan.Blocked));
await fx.Service.FrameTrash.DeleteAsync(plan, "editor", null, fx.Ct);
}
[Test]
public async Task AFolderOrTitleNamedAfterAPhotoNoLongerFirstIsNeverGiven()
{
await using var fx = await CreateAsync(context);
var trashed = await UploadAsync(fx, 3);
var earlier = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2");
var other = await UploadAsync(fx, 2, firstSeed: 40, firstSecond: 7200, key: "upload-3");
var templates = new RenameTemplates(Folder: "moved/{date} {time}", File: "{n:000}", Title: "{time}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [trashed, earlier, other], templates, fx.Ct);
Assert.SequenceEqual(["moved/2026-09-28 18-00-00", "moved/2026-09-28 19-00-00", "moved/2026-09-28 20-00-00"], plan.Steps.Select(s => s.ToFolder));
var from = new Dictionary<Guid, string>();
foreach (var id in new[] { trashed, earlier }) from[id] = await FolderAsync(fx, id);
var files = new Dictionary<Guid, List<string>>();
// Once the plan's own checks passed, the first photo of one goes to the trash and a photo taken before the first of
// another is filed into it: the templates now name each after another photo.
var result = await fx.Service.Renamer.ApplyAsync(fx.Archive, plan, async _ =>
{
await TrashFirstPhotoAsync(fx, trashed);
await UploadAsync(fx, 1, firstSeed: 30, firstSecond: 3595, key: "upload-2");
foreach (var id in from.Keys) files[id] = await FilesAsync(fx, id);
}, null, fx.Ct);
// Both stay as they were, their folder, title and file names; the other is reorganized.
Assert.SequenceEqual([trashed, earlier], result.Dropped);
Assert.SequenceEqual([other], result.Changed);
foreach (var id in from.Keys)
{
Assert.Equal(from[id], await FolderAsync(fx, id));
Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.SequenceEqual(files[id], await FilesAsync(fx, id));
}
Assert.Equal(("moved/2026-09-28 20-00-00", "20-00-00"), (await FolderAsync(fx, other), (await fx.Db.Sequences.GetAsync(other))!.Title));
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, other));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
// Planned now, they are named after their first photo as it is.
var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [trashed, earlier], templates, fx.Ct);
Assert.SequenceEqual([("moved/2026-09-28 18-00-10", "18-00-10"), ("moved/2026-09-28 18-59-55", "18-59-55")],
again.Steps.Select(s => (s.ToFolder, s.ToTitle)));
}
[Test]
public async Task ARetryOfAJobThatKeptSequencesPlansAgain()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
var from = await FolderAsync(fx, id);
var templates = new RenameTemplates(Folder: "moved/{date} {time}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
// Its job held the plan before its step (paused); the first photo then went to the trash.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, [], Held: true));
await TrashFirstPhotoAsync(fx, id);
// Resumed, the job leaves the sequence as it was and says why it failed.
var engine = await fx.StartEngineAsync();
var job = await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Reorganize(fx.Archive, plan, templates), "plan:" + plan.Id.ToString("N"));
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.Plural("Archive.Error.ReorganizeKept", 1), failed.Error);
Assert.Contains(Loc.L("Archive.Log.ReorganizeDropped", from), failed.LogTail);
Assert.Equal(from, await FolderAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
// Retried, it plans again instead of taking the plan for one an archive open completed: the archive is no longer
// the one the plan was confirmed for.
await engine.ResumeAsync(job.Id, fx.Ct);
var retried = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Archive.Error.StalePlan"), retried.Error);
Assert.False(retried.LogTail!.Contains(Loc.L("Archive.Log.ReorganizedEarlier"), StringComparison.Ordinal), retried.LogTail);
Assert.Equal(from, await FolderAsync(fx, id));
}
[Test]
public async Task ASequenceAFolderWasToCarryIsToldItStayedWithIt()
{
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), 2, 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}", Title: "Roof");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [parent], templates, fx.Ct);
Assert.SequenceEqual([(parent, false), (nested, true)], plan.Steps.Select(s => (s.SequenceId, s.Carried)));
var inner = plan.Steps[1].ToTitle ?? plan.Steps[1].FromFolder;
// Interrupted before its step; a newer Chronos then rewrote the sidecar of the folder that carries the other.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
var sidecar = fx.Paths.Sequence(folder).ManifestPath;
var json = File.ReadAllText(sidecar);
Assert.Contains("\"schemaVersion\":1", json);
File.WriteAllText(sidecar, json.Replace("\"schemaVersion\":1", $"\"schemaVersion\":{SequenceManifest.CurrentSchemaVersion + 1}", StringComparison.Ordinal));
// Resumed, both stay where they are: the one inside is not said to have changed, and the job fails for the newer sidecar alone.
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.ReorganizeNewer", 1), failed.Error);
Assert.Contains(Loc.L("Archive.Log.ReorganizeNewerKept", "Roof"), failed.LogTail);
Assert.Contains(Loc.L("Archive.Log.ReorganizeCarriedKept", inner), failed.LogTail);
Assert.False(failed.LogTail!.Contains(Loc.L("Archive.Log.ReorganizeDropped", inner), StringComparison.Ordinal), failed.LogTail);
Assert.Equal((folder, folder + "/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested)));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AnArchiveOpensWhenAnInterruptedRenameMeetsASidecarOfANewerFormat()
{
await using var fx = await CreateAsync(context);
var id = await ChainAsync(fx);
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:0}"), fx.Ct);
// Interrupted inside the step once every file reached its temporary name; a newer Chronos then rewrote the sidecar.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
var moves = FileRenames.Plan(manifest, null, PathTemplate.Parse("{n:0}"), FileRenames.ListPresent(folder, manifest)).Moves;
var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "crash") with { Phase = 2 };
FileRenameJournal.Write(folder, journal);
foreach (var file in journal.Files) File.Move(folder.File(file.From), folder.File(file.Temp));
var json = File.ReadAllText(folder.ManifestPath);
Assert.Contains("\"schemaVersion\":1", json);
var newer = json.Replace("\"schemaVersion\":1", $"\"schemaVersion\":{SequenceManifest.CurrentSchemaVersion + 1}", StringComparison.Ordinal);
File.WriteAllText(folder.ManifestPath, newer);
// Completing it would rewrite that sidecar, which this build never does: each open logs it, and the archive opens.
for (var open = 0; open < 2; open++)
{
Assert.Equal(fx.Archive.Id, (await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct)).Id);
// Nothing is lost: the plan and the sequence's journal wait, and every photo is at the name that journal gives it.
Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id));
Assert.NotNull(FileRenameJournal.Read(folder));
foreach (var file in journal.Files) Assert.FileExists(folder.File(file.To));
Assert.Equal(newer, File.ReadAllText(folder.ManifestPath));
}
}
[Test]
public async Task AResumedStepWhoseFolderMovedKeepsATitleEditedSinceAndTheNamesFromIt()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
await fx.Service.SetSequenceInfoAsync(id, "Roof", [], 0, null, fx.Ct);
// The folder and the files are named after the title, which the plan does not change.
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: "moved/{title}", File: "{title}_{n:000}"), fx.Ct);
var step = plan.Steps.Single();
Assert.True(step is { ToFolder: "moved/Roof", FileChanges: 2, Retitles: false, NamedByTitle: true });
// Retitled since the plan, and a run of it interrupted once the folder moved, before its index row followed.
await fx.Service.SetSequenceInfoAsync(id, "Roof north", [], 0, null, fx.Ct);
var before = await FilesAsync(fx, id);
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
RenamePlanner.MoveFolder(fx.Paths, step);
// Resumed, its index row follows the folder; the title stays, and so do the file names that came from the old one.
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.Equal(0, result.Files);
Assert.Equal("moved/Roof", await FolderAsync(fx, id));
Assert.Equal("Roof north", (await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
}