Files
Chronos/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs
T
Alby96 13c2ac321c fix(archive): Reorganize checks each step before it moves, holds a failed plan, recovers file renames safely
Owner review 2, phase 4a review findings on the renamer.

- File rename recovery is safe to run again from wherever it stopped: once every
  file is at its temporary name the journal says phase 2, as Run does, so a second
  recovery (after a failure, a crash or a sidecar that could not be written) never
  moves a file that reached its new name. A new name something else took meanwhile
  is never written over: that photo and its companions go back to their old names,
  or to the first free _2, _3, recorded in the journal before they move, and the
  frame names where its photo is. A journal is never deleted while a temporary file
  of it is still there.
- Every check that can refuse a step runs under the step's leases before anything of
  it moves: where its sequences are, strangers inside, its new folder taken since the
  plan (a restore, an upload), a sidecar of a newer format, a title edited since the
  plan (compare-and-set against the planned from-title, sidecar and index), and its
  file renames, compared by a digest of every move at the planned frames version (a
  verify that hashes photos does not bump the version). Once the folder moved, every
  index row follows it before any file is renamed, and a photo in use or files found
  changed keep their names: the step completes.
- The same checks run up front for a held plan, so its retry either fits or is given up.
- A failed move job holds its plan, as a pause does: an archive open no longer
  applies the rest unasked; only the job's retry does. File renames a step left
  half-way are still completed at an archive open.
- Each sequence changed is told as its step is journaled, so a pause or a failure
  never keeps it untold; the plan's journal keeps the tally of every run, so the job
  log counts the whole plan.
- A selected sequence deleted while the job waited is named in the log and the plan
  refused with the localized stale-plan error, not a raw ArgumentException.
- The dry run renames no file of a newer-format sidecar.

New log lines and error (en, it): title and file names kept, file names kept because
a photo was in use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 1d1c888120edd709dbb5341c1922bf85085c4857)
2026-10-27 16:28:40 +01:00

611 lines
36 KiB
C#

using System.Collections.Concurrent;
using System.Security.Cryptography;
using Chronos.Core.Archiving;
using Chronos.Core.Import;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Naming;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Repositories;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
namespace Chronos.Data.Tests.Archiving;
/// <summary>
/// Reorganize (owner review 2, R7): new folder, file and title templates applied to sequences already in the archive, with a
/// dry run, two-phase file renames under a journal, crash recovery, stale plans and the <c>move</c> job.
/// </summary>
[Category("archive")]
public sealed class ReorganizeTests(TestContext context)
{
private static IngestRequest Upload(ArchiveFixture fx, (string Path, long Size, string Sha256) staged, string name, string key) =>
new(fx.Archive.Id, null, null, key, staged.Path, name, staged.Size, staged.Sha256, null, null);
/// <summary>Uploads photos ten seconds apart (from <paramref name="firstSecond"/>) into the sequence of <paramref name="key"/>; returns its id.</summary>
private static async Task<Guid> UploadAsync(ArchiveFixture fx, int count, int firstSeed = 1, int firstSecond = 0, string key = "upload-1")
{
Guid id = default;
for (var i = 0; i < count; i++)
{
var staged = fx.Stage(Start.AddSeconds(firstSecond + 10 * i), firstSeed + i);
id = (await fx.Service.Ingest.CommitAsync(Upload(fx, staged, $"IMG_{firstSeed + i:0000}.JPG", key), fx.Ct)).SequenceId;
}
return id;
}
/// <summary>
/// A sequence whose names follow "{n:0}" no more: two photos filed as 1 and 2, then an earlier one filed before them as 1_2.
/// Renamed with "{n:0}" again they chain: 1_2→1, 1→2, 2→3.
/// </summary>
private static async Task<Guid> ChainAsync(ArchiveFixture fx)
{
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{n:0}" } }, fx.Ct);
await UploadAsync(fx, 2, firstSeed: 2, firstSecond: 10);
var id = await UploadAsync(fx, 1, firstSeed: 1);
Assert.SequenceEqual(["originals/1_2.JPG", "originals/1.JPG", "originals/2.JPG"], await FilesAsync(fx, id));
return id;
}
/// <summary>
/// The files of a sequence as its sidecar names them, after checking that the index names the same files in the same
/// order at the same frames version, that every file holds its frame's photo and that no journal is left.
/// </summary>
private static async Task<List<string>> FilesAsync(ArchiveFixture fx, Guid id)
{
var sequence = Assert.NotNull(await fx.Db.Sequences.GetAsync(id));
var folder = fx.Paths.Sequence(sequence.Folder);
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath);
var rows = await fx.Db.Frames.ListBySequenceAsync(id);
Assert.SequenceEqual(sidecar.Frames.Select(f => f.Id), rows.Select(r => r.Id));
Assert.Equal(sidecar.Versions.Frames, sequence.FramesVersion);
Assert.Equal(sidecar.Title, sequence.Title);
foreach (var (frame, row) in sidecar.Frames.Zip(rows))
{
Assert.Equal(folder.ArchiveRelative(frame.File), row.RelativePath);
Assert.Equal(Path.GetFileName(frame.File), row.FileName);
Assert.Equal(frame.Sha256, Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(folder.File(frame.File)))));
}
Assert.Null(FileRenameJournal.Read(folder));
Assert.Empty(Directory.EnumerateFiles(folder.Originals, ".chronos-rename-*"));
return [.. sidecar.Frames.Select(f => f.File)];
}
[Test]
public async Task FilesAreRenamedExactlyAsTheDryRunSaid()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 3);
var before = await FilesAsync(fx, id);
var version = (await fx.Db.Sequences.GetAsync(id))!.FramesVersion;
var templates = new RenameTemplates(File: "{title}_{n:000}", Title: "Roof");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
var step = plan.Steps.Single();
Assert.Equal((3, version, "Roof"), (step.FileChanges, step.FramesVersion, step.ToTitle));
Assert.SequenceEqual(before.Zip(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], (f, t) => $"{f}>{t}"),
step.FileSamples.Select(s => $"{s.From}>{s.To}"));
Assert.SequenceEqual(before, await FilesAsync(fx, id));
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.Equal(3, result.Files);
Assert.SequenceEqual([id], result.Changed);
Assert.SequenceEqual(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], await FilesAsync(fx, id));
Assert.Equal(version + 1, (await fx.Db.Sequences.GetAsync(id))!.FramesVersion);
Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
// Applied again, the templates change nothing.
Assert.False((await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct)).Steps.Any(s => s.Changes));
}
[Test]
public async Task ASecondReorganizeWithTheSameTemplatesPlansNothing()
{
await using var fx = await CreateAsync(context);
var first = await UploadAsync(fx, 2);
var second = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2");
// One day for both: the second sequence's folder gets " (2)".
var templates = new RenameTemplates(Folder: "days/{date}", File: "{date}_{n:000}");
await fx.Service.ApplyRenameAsync(await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, templates, fx.Ct), null, fx.Ct);
var folders = new List<string>();
foreach (var id in new[] { first, second }) folders.Add((await fx.Db.Sequences.GetAsync(id))!.Folder);
Assert.SequenceEqual(["days/2026-09-28", "days/2026-09-28 (2)"], folders.Order(StringComparer.Ordinal));
var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, templates, fx.Ct);
Assert.Count(2, again.Subjects);
Assert.False(again.Steps.Any(s => s.Changes), string.Join(", ", again.Steps.Select(s => $"{s.FromFolder}>{s.ToFolder}")));
}
[Test]
public async Task UploadsAndImportsAreNamedAsReorganizeNamesThem()
{
await using var fx = await CreateAsync(context);
await UploadAsync(fx, 3);
var card = context.CreateTempDirectory("card");
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start.AddDays(1), 4, firstSeed: 30);
var import = await fx.Service.PlanImportAsync(fx.Archive.Id, card,
new ImportOptions { FolderTemplate = fx.Archive.FolderTemplate, FileTemplate = fx.Archive.FileTemplate }, null, null, fx.Ct);
var engine = await fx.StartEngineAsync();
await fx.WaitForAsync((await engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive, import, null), cancellationToken: fx.Ct)).Id, JobState.Done);
Assert.Count(2, await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id));
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, new RenameTemplates(File: fx.Archive.FileTemplate), fx.Ct);
Assert.Empty(plan.Steps);
Assert.Count(2, plan.Subjects);
}
[Test]
public async Task AChainOfNewNamesIsRenamedThroughTemporaryNames()
{
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);
Assert.Equal(3, plan.Steps.Single().FileChanges);
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual(["originals/1.JPG", "originals/2.JPG", "originals/3.JPG"], await FilesAsync(fx, id));
}
[Theory]
[Case(1)]
[Case(2)]
public async Task ARenameACrashInterruptedIsCompletedAtTheNextOpen(int phase)
{
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);
// The process stopped inside the step: the plan's journal and the sequence's, files part-way through their phase.
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 = phase };
FileRenameJournal.Write(folder, journal);
File.Move(folder.File(journal.Files[0].From), folder.File(journal.Files[0].Temp));
if (phase == 2)
{
foreach (var file in journal.Files.Skip(1)) File.Move(folder.File(file.From), folder.File(file.Temp));
File.Move(folder.File(journal.Files[0].Temp), folder.File(journal.Files[0].To));
}
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.SequenceEqual(["originals/1.JPG", "originals/2.JPG", "originals/3.JPG"], await FilesAsync(fx, id));
Assert.Equal(manifest.Versions.Frames + 1, (await fx.Db.Sequences.GetAsync(id))!.FramesVersion);
}
[Test]
public async Task APlanWhosePhotosChangedIsRefusedOrResumedWithoutTheirNames()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}", Title: "Roof"), fx.Ct);
// A photo arrives after the dry run: the names shown are no longer the ones the template gives.
await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5);
var before = await FilesAsync(fx, id);
var stale = await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.Equal(id, stale.SequenceId);
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
// Interrupted before its step began, the plan resumes: the title changes, the files keep their names.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task CompanionsMoveWithTheirPhoto()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
var before = await FilesAsync(fx, id);
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
File.WriteAllText(folder.File(Path.ChangeExtension(before[0], ".xmp")), "first");
File.WriteAllText(folder.File(before[1] + ".xmp"), "second");
await fx.ScanAsync();
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}"), fx.Ct);
Assert.Equal(2, plan.Steps.Single().FileChanges);
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, id));
Assert.Equal("first", File.ReadAllText(folder.File("originals/001.xmp")));
Assert.Equal("second", File.ReadAllText(folder.File("originals/002.JPG.xmp")));
Assert.SequenceEqual(["001.JPG", "001.xmp", "002.JPG", "002.JPG.xmp"], Directory.EnumerateFiles(folder.Originals).Select(Path.GetFileName).Order(StringComparer.Ordinal));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task PhotosAdoptedInPlaceKeepTheirNames()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a"), Start, 3);
await fx.ScanAsync();
var id = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single().Id;
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}"), fx.Ct);
var step = plan.Steps.Single();
Assert.False(step.Changes);
Assert.Equal((RenameBlock.InPlace, 3), (step.Blocked.Single().Reason, step.Blocked.Single().Frames));
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.Empty(result.Changed);
Assert.SequenceEqual(["IMG_0001.JPG", "IMG_0002.JPG", "IMG_0003.JPG"], ManifestStore.ReadSequence(fx.Paths.Sequence("inbox/a").ManifestPath).Frames.Select(f => f.File));
}
[Test]
public async Task AMoveJobAppliesTheConfirmedPlanAndRefusesOneTheArchiveOutgrew()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 3);
var engine = await fx.StartEngineAsync();
var templates = new RenameTemplates(Folder: "reorganized/{date}", File: "{n:000}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
var job = await engine.EnqueueAsync(ArchiveJobs.Reorganize(fx.Archive, plan, templates), cancellationToken: fx.Ct);
Assert.Equal(JobKind.Move, job.Kind);
var done = await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Equal((1, 1), (done.ProgressDone, done.ProgressTotal));
Assert.Contains(Loc.L("Archive.Log.Reorganized", 1, 3), done.LogTail);
Assert.Equal("reorganized/2026-09-28", (await fx.Db.Sequences.GetAsync(id))!.Folder);
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, id));
var back = new RenameTemplates(File: "{date}_{n:0000}");
var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], back, fx.Ct);
await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5);
var before = await FilesAsync(fx, id);
var refused = await fx.WaitForAsync((await engine.EnqueueAsync(ArchiveJobs.Reorganize(fx.Archive, again, back), cancellationToken: fx.Ct)).Id, JobState.Failed);
Assert.Equal(Loc.L("Archive.Error.StalePlan"), refused.Error);
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AHeldPlanWaitsForItsJob()
{
await using var fx = await CreateAsync(context);
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);
Assert.Count(2, plan.Steps);
var untouched = await FilesAsync(fx, second);
// The job stops after the first sequence (paused) and holds its plan: an archive open leaves the rest alone.
using var cts = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan, null, (_, _) =>
{
cts.Cancel();
return ValueTask.CompletedTask;
}, cts.Token));
Assert.True(MassRenamer.Hold(fx.Archive, plan.Id));
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, first));
Assert.SequenceEqual(untouched, await FilesAsync(fx, second));
Assert.True(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Held);
// Resumed from its checkpoint, the job completes it and counts the whole plan; once its journal is gone a run finds the plan complete.
var engine = await fx.StartEngineAsync();
var request = ArchiveJobs.Reorganize(fx.Archive, plan, templates);
var resumed = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, request, "plan:" + plan.Id.ToString("N"))).Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.Reorganized", 2, 4), resumed.LogTail);
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, second));
Assert.Null(RenameJournal.Read(fx.Paths, plan.Id));
var later = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, request, "plan:" + plan.Id.ToString("N"))).Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.ReorganizedEarlier"), later.LogTail);
}
/// <summary>
/// An uploaded sequence with a nested one adopted from a subfolder of its folder ("extra"), planned to move to
/// "moved/{date}" with new file names: the nested one is carried.
/// </summary>
private static async Task<(Guid Parent, Guid Nested, RenamePlan Plan)> CarrierAsync(ArchiveFixture fx)
{
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 plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [parent], new RenameTemplates(Folder: "moved/{date}", File: "{n:000}"), fx.Ct);
Assert.SequenceEqual([(parent, false, 2), (nested, true, 0)], plan.Steps.Select(s => (s.SequenceId, s.Carried, s.FileChanges)));
return (parent, nested, plan);
}
/// <summary>The folder of a sequence as the index has it, after checking that every frame the index lists is on disk there.</summary>
private static async Task<string> FolderAsync(ArchiveFixture fx, Guid id)
{
var sequence = Assert.NotNull(await fx.Db.Sequences.GetAsync(id));
foreach (var frame in await fx.Db.Frames.ListBySequenceAsync(id))
{
Assert.True(frame.RelativePath.StartsWith(sequence.Folder + "/", StringComparison.Ordinal), frame.RelativePath);
Assert.FileExists(fx.Paths.FromRelative(frame.RelativePath));
}
return sequence.Folder;
}
[Test]
public async Task AStepWhosePhotosChangedIsRefusedUnderItsLeasesBeforeAnythingMoves()
{
await using var fx = await CreateAsync(context);
var (parent, nested, plan) = await CarrierAsync(fx);
var from = await FolderAsync(fx, parent);
// A photo uploaded once the plan's own checks passed, before its step: nothing of that step moves.
var stale = await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan,
async _ => await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5), null, fx.Ct));
Assert.Equal(parent, stale.SequenceId);
var before = await FilesAsync(fx, parent);
Assert.Equal((from, from + "/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested)));
Assert.Empty(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Completed);
// Resumed after an interruption, the folder moves with the one inside it, whose index row follows, and the files keep their names.
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([parent], result.FilesKept);
Assert.SequenceEqual([parent, nested], result.Changed);
Assert.Equal(("moved/2026-09-28", "moved/2026-09-28/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested)));
Assert.SequenceEqual(before, await FilesAsync(fx, parent));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AFileThatCannotTakeItsNewNameKeepsTheNamesAndTheStepCompletes()
{
await using var fx = await CreateAsync(context);
var (parent, nested, plan) = await CarrierAsync(fx);
var before = await FilesAsync(fx, parent);
// A folder holds the name the second photo gets: that file cannot move there, so every file goes back to its name.
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(parent))!.Folder);
Directory.CreateDirectory(folder.File(plan.Steps[0].FileSamples[1].To));
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual([parent], result.FilesBusy);
Assert.SequenceEqual([parent, nested], result.Changed);
Assert.Equal(0, result.Files);
// The folder moved, the one inside it with it, both index rows followed, and the files kept their names.
Assert.Equal(("moved/2026-09-28", "moved/2026-09-28/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested)));
Assert.SequenceEqual(before, await FilesAsync(fx, parent));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AFailedJobHoldsItsPlanAndTellsTheSequencesItChanged()
{
await using var fx = await CreateAsync(context);
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);
var told = new ConcurrentQueue<(Guid, string)>();
var service = new ArchiveService(fx.Db, new ArchiveServiceOptions
{
Owner = "jobs",
LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)),
SequenceChanged = (id, change, _) =>
{
told.Enqueue((id, change));
return Task.CompletedTask;
},
});
await using var engine = new JobEngine(fx.Db, service.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(fx.Ct);
// An editor holds the first sequence while the job starts its plan (planned again: its own id); a photo reaches the second meanwhile.
Job job;
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{first:N}", "editor", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
{
job = await engine.EnqueueAsync(ArchiveJobs.Reorganize(fx.Archive, plan, templates), cancellationToken: fx.Ct);
var until = DateTime.UtcNow.AddSeconds(TestTiming.Budget(15));
while (RenameJournal.ListPending(fx.Paths).Count == 0)
{
Assert.True(DateTime.UtcNow < until, "the job never started its plan");
await Task.Delay(20, fx.Ct);
}
await UploadAsync(fx, 1, firstSeed: 30, firstSecond: 3605, key: "upload-2");
}
var failed = await fx.WaitForAsync(job.Id, JobState.Failed, (int)TestTiming.Budget(60));
Assert.Equal(Loc.L("Archive.Error.StalePlan"), failed.Error);
Assert.Contains(Loc.L("Archive.Log.Reorganized", 1, 2), failed.LogTail);
Assert.SequenceEqual([(first, MoveJobHandler.Change)], told);
var journal = RenameJournal.ListPending(fx.Paths).Single();
Assert.True(journal.Held, "only the job's retry goes on with it");
Assert.SequenceEqual([first], journal.Completed);
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, first));
var untouched = await FilesAsync(fx, second);
Assert.Count(3, untouched);
// An archive open leaves it alone; the retry checks the rest as a plan applied anew and gives it up.
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.SequenceEqual(untouched, await FilesAsync(fx, second));
var retried = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, ArchiveJobs.Reorganize(fx.Archive, plan, templates),
"plan:" + journal.Plan.Id.ToString("N"))).Id, JobState.Failed, (int)TestTiming.Budget(60));
Assert.Equal(Loc.L("Archive.Error.StalePlan"), retried.Error);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.SequenceEqual(untouched, await FilesAsync(fx, second));
Assert.Count(1, told);
}
[Test]
public async Task FileRenamesLeftHalfWayAreCompletedAtAnOpenWhileTheirPlanWaitsForItsJob()
{
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}", Title: "Roof"), fx.Ct);
// Its job failed inside the step once every file reached its temporary name: the plan held, the sequence's journal left.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, [], Held: true));
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
var moves = FileRenames.Plan(manifest, "Roof", PathTemplate.Parse("{n:0}"), FileRenames.ListPresent(folder, manifest)).Moves;
var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "held") with { Phase = 2 };
FileRenameJournal.Write(folder, journal);
foreach (var file in journal.Files) File.Move(folder.File(file.From), folder.File(file.Temp));
// Every photo goes on to its new name and the sidecar names it; the rest (the title) waits for the job.
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct);
Assert.SequenceEqual(["originals/1.JPG", "originals/2.JPG", "originals/3.JPG"], ManifestStore.ReadSequence(folder.ManifestPath).Frames.Select(f => f.File));
Assert.Null(FileRenameJournal.Read(folder));
Assert.Empty(Directory.EnumerateFiles(folder.Originals, ".chronos-rename-*"));
Assert.True(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Held);
Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title);
// Its job's retry completes it: the index follows the sidecar and the title changes.
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([id], result.Changed);
Assert.SequenceEqual(["originals/1.JPG", "originals/2.JPG", "originals/3.JPG"], await FilesAsync(fx, id));
Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task ASequenceDeletedBeforeTheJobRanIsNamedAndThePlanRefused()
{
await using var fx = await CreateAsync(context);
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 request = ArchiveJobs.Reorganize(fx.Archive, await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second], templates, fx.Ct), templates);
var before = await FilesAsync(fx, first);
// Deleted while the job waited in the queue.
await fx.Service.Trash.DeleteAsync(await fx.Service.Trash.PlanAsync([second], null, fx.Ct), null, null, fx.Ct);
var engine = await fx.StartEngineAsync();
var failed = await fx.WaitForAsync((await engine.EnqueueAsync(request, cancellationToken: fx.Ct)).Id, JobState.Failed);
Assert.Equal(Loc.L("Archive.Error.StalePlan"), failed.Error);
Assert.Contains(Loc.L("Archive.Log.SequenceMissing", second), failed.LogTail);
Assert.SequenceEqual(before, await FilesAsync(fx, first));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task ATitleEditedAfterThePlanIsNeverWrittenOver()
{
await using var fx = await CreateAsync(context);
var first = await UploadAsync(fx, 1);
var second = await UploadAsync(fx, 1, firstSeed: 20, firstSecond: 3600, key: "upload-2");
foreach (var id in new[] { first, second }) await fx.Service.SetSequenceInfoAsync(id, "Roof", [], 0, null, fx.Ct);
var templates = new RenameTemplates(Title: "{title} 2026");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second], templates, fx.Ct);
// Retitled once the first sequence is done: refused before anything of it changes.
var stale = await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan, null,
async (_, _) => await fx.Service.SetSequenceInfoAsync(second, "Roof north", [], 0, null, fx.Ct), fx.Ct));
Assert.Equal(second, stale.SequenceId);
Assert.Equal(("Roof 2026", "Roof north"), ((await fx.Db.Sequences.GetAsync(first))!.Title, (await fx.Db.Sequences.GetAsync(second))!.Title));
await FilesAsync(fx, second);
// Held by its job, the rest is refused as a plan applied anew.
Assert.True(MassRenamer.Hold(fx.Archive, plan.Id));
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.Null(RenameJournal.Read(fx.Paths, plan.Id));
// Interrupted, the rest resumes without it; an edit only the index has (the server's API) counts as well.
var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [second], templates, fx.Ct);
RenameJournal.Write(fx.Paths, new RenameJournal(again, []));
await fx.Db.Sequences.EditAsync(second, new SequenceEdit { Title = "Roof south" }, null, fx.Ct);
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, again.Id, null, fx.Ct));
Assert.SequenceEqual([second], result.Dropped);
Assert.Empty(result.Changed);
var row = Assert.NotNull(await fx.Db.Sequences.GetAsync(second));
Assert.Equal(("Roof south", "Roof north"), (row.Title, ManifestStore.ReadSequence(fx.Paths.Sequence(row.Folder).ManifestPath).Title));
}
[Test]
public async Task ASidecarOfANewerFormatIsNeverRewrittenNorAreItsFilesRenamed()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
var before = await FilesAsync(fx, id);
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
var templates = new RenameTemplates(File: "{n:000}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
Assert.Equal(2, plan.Steps.Single().FileChanges);
// A newer Chronos sharing the archive rewrote the sidecar after the dry run: refused before any file moves.
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);
await Assert.ThrowsAsync<NewerFormatException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.SequenceEqual(before, await FilesAsync(fx, id));
// So is its step, under its lease, when the sidecar changes once the plan's own checks passed.
File.WriteAllText(folder.ManifestPath, json);
await Assert.ThrowsAsync<NewerFormatException>(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan, _ =>
{
File.WriteAllText(folder.ManifestPath, newer);
return ValueTask.CompletedTask;
}, null, fx.Ct));
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Null(FileRenameJournal.Read(folder));
// Interrupted there, the plan resumes at the next open without its files; a new dry run renames none of them.
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.SequenceEqual(before, await FilesAsync(fx, id));
var again = (await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct)).Steps.Single();
Assert.Equal((0, RenameBlock.Unreadable), (again.FileChanges, again.Blocked.Single().Reason));
}
[Test]
public async Task AFolderTakenAfterThePlanIsNeverMovedInto()
{
await using var fx = await CreateAsync(context);
var first = await UploadAsync(fx, 1);
var second = await UploadAsync(fx, 1, firstSeed: 20, firstSecond: 86400, key: "upload-2");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second], new RenameTemplates(Folder: "moved/{date}"), fx.Ct);
Assert.SequenceEqual(["moved/2026-09-28", "moved/2026-09-29"], plan.Steps.Select(s => s.ToFolder));
var from = await FolderAsync(fx, second);
var stranger = fx.Paths.FromRelative("moved/2026-09-29/note.txt");
// Once the first moved, something takes the second's new folder (a restore from the trash, a copy).
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan, null, (_, _) =>
{
Directory.CreateDirectory(Path.GetDirectoryName(stranger)!);
File.WriteAllText(stranger, "kept");
return ValueTask.CompletedTask;
}, fx.Ct));
Assert.Equal(("moved/2026-09-28", from), (await FolderAsync(fx, first), await FolderAsync(fx, second)));
// Held, the rest is refused before anything moves; interrupted, it is dropped.
Assert.True(MassRenamer.Hold(fx.Archive, plan.Id));
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
RenameJournal.Write(fx.Paths, new RenameJournal(plan, [first]));
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([second], result.Dropped);
Assert.Equal(from, await FolderAsync(fx, second));
Assert.Equal("kept", File.ReadAllText(stranger));
Assert.SequenceEqual(["note.txt"], Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(stranger)!).Select(Path.GetFileName));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task PhotosHashedAfterThePlanKeepTheNamesItShowed()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 3);
var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
// The second photo was never verified: the dry run says it keeps its name.
ManifestStore.WriteSequence(folder.ManifestPath, manifest with { Frames = [manifest.Frames[0], manifest.Frames[1] with { Sha256 = null }, manifest.Frames[2]] });
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}"), fx.Ct);
Assert.Equal((2, RenameBlock.Unhashed), (plan.Steps.Single().FileChanges, plan.Steps.Single().Blocked.Single().Reason));
// A verify hashes it afterwards, which leaves the frames version as it is: the plan would now rename it too.
ManifestStore.WriteSequence(folder.ManifestPath, manifest);
var before = await FilesAsync(fx, id);
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.SequenceEqual(before, await FilesAsync(fx, id));
// Interrupted before its step, it resumes without renaming any of them.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([id], result.FilesKept);
Assert.SequenceEqual(before, await FilesAsync(fx, id));
}
}