Files
Chronos/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs
T
Alby96 9e1f109b58 fix(reorganize): a sequence still receiving photos keeps its file names and the job goes on
A Reorganize with a file template failed its job at the step of a sequence
a camera was still uploading into, and its retry gave the rest up. Photos
changed since the plan now never refuse a step: that sequence keeps its file
names (FilesKept), its folder and title change as planned, the other steps go
on and the job ends with ReorganizeKept. The fingerprint, the job's
confirmation and the check under the leases pin file renames by their digest
instead of the frames version, so photos filed under the names the plan gives
them no longer make a dry run or a queued job stale.

- A step whose folder or files a template names after {title} checks the
  title as a retitle does (RenameStep.NamedByTitle): no name comes from a
  title edited since the plan.
- Recovery sends a photo that already took its new name back together with a
  companion whose new name was taken, so the two never end up apart.
- ArchiveService.OpenAsync logs a NewerFormatException from resuming a plan
  and keeps its journal, so a server still boots.
- Once a step's folder moved, every index row of the step follows it even
  when a sidecar cannot be read or written; the step then fails for a retry.
- Job log lines and errors give the real reason for files kept busy (in use
  or a new name taken) and for a sidecar of a newer format (new Newer
  outcome; strings en and it).
- A plan an archive open completes tells sequenceChanged; the docs that
  promised more than that are corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f8554b8af0828ab9b0ff128e694abacdd53e6fd7)
2026-10-27 18:08:07 +01:00

856 lines
50 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(fx.Archive.FolderTemplate, fx.Archive.FileTemplate), fx.Ct);
Assert.Empty(plan.Steps);
Assert.Count(2, plan.Subjects);
}
[Test]
public async Task UploadsAreFiledWithTheirSequencesCameraAndLensAsReorganizeNamesThem()
{
await using var fx = await CreateAsync(context);
const string FolderTemplate = "{year}/{date} {camera} {ext}", FileTemplate = "{camera}_{lens}_{n:0000}";
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = FolderTemplate, File = FileTemplate } }, fx.Ct);
// A sequence created with the camera it is for, whose photos name none: the hint names them.
var hinted = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = fx.Archive.Id,
Title = "Roof",
Folder = string.Empty,
CameraModel = "GoPro HERO12 Black",
Origin = SequenceOrigin.Server,
UpdatedAt = DateTimeOffset.UtcNow,
};
await fx.Db.Sequences.UpsertAsync(hinted, fx.Ct);
for (var i = 0; i < 2; i++)
{
var staged = fx.Stage(Start.AddSeconds(10 * i), 40 + i, make: null, model: null);
await fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, hinted.Id, null, null, staged.Path, $"GOPR{i:0000}.JPG", staged.Size,
staged.Sha256, null, null), fx.Ct);
}
// A lens changed during a session: its photos take the first one's, as the sequence does.
Guid lensed = default;
foreach (var (lens, i) in new[] { "RF15-35mm", "RF24-70mm" }.Select((l, i) => (l, i)))
{
var staged = fx.Stage(Start.AddHours(2).AddSeconds(10 * i), 50 + i, lens: lens);
lensed = (await fx.Service.Ingest.CommitAsync(Upload(fx, staged, $"IMG_{i:0000}.JPG", "upload-2"), fx.Ct)).SequenceId;
}
Assert.SequenceEqual(["originals/GoPro HERO12 Black__0001.JPG", "originals/GoPro HERO12 Black__0002.JPG"], await FilesAsync(fx, hinted.Id));
Assert.Equal("2026/2026-09-28 GoPro HERO12 Black JPG", (await fx.Db.Sequences.GetAsync(hinted.Id))!.Folder);
Assert.SequenceEqual(["originals/Canon EOS R5_RF15-35mm_0001.JPG", "originals/Canon EOS R5_RF15-35mm_0002.JPG"], await FilesAsync(fx, lensed));
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, new RenameTemplates(FolderTemplate, FileTemplate), fx.Ct);
Assert.Count(2, plan.Subjects);
Assert.Empty(plan.Steps);
}
[Test]
public async Task ASequenceWhoseSidecarCannotBeReadStaysAsItIsAndTheOthersMove()
{
await using var fx = await CreateAsync(context);
var good = await UploadAsync(fx, 2);
var torn = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2");
var foreign = await UploadAsync(fx, 2, firstSeed: 30, firstSecond: 7200, key: "upload-3");
var last = await UploadAsync(fx, 2, firstSeed: 40, firstSecond: 10800, key: "upload-4");
async Task<SequencePaths> FolderOf(Guid id) => fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder);
File.WriteAllText((await FolderOf(torn)).ManifestPath, "{ \"schemaVersion\": 1, \"id\": ");
File.Copy((await FolderOf(good)).ManifestPath, (await FolderOf(foreign)).ManifestPath, overwrite: true);
var kept = new Dictionary<Guid, string>();
foreach (var id in new[] { torn, foreign }) kept[id] = (await fx.Db.Sequences.GetAsync(id))!.Folder;
var templates = new RenameTemplates(Folder: "moved/{date}", Title: "{title} {hm}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, templates, fx.Ct);
foreach (var id in kept.Keys)
{
var step = plan.Steps.Single(s => s.SequenceId == id);
Assert.Equal((kept[id], step.FromTitle), (step.ToFolder, step.ToTitle));
Assert.False(step.Changes);
Assert.Equal(RenameBlock.Unreadable, step.Blocked.Single().Reason);
}
// The one after them gets the " (2)" they never take.
Assert.Equal(("moved/2026-09-28 (2)", "21-00"), (plan.Steps.Single(s => s.SequenceId == last).ToFolder, plan.Steps.Single(s => s.SequenceId == last).ToTitle));
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual([good, last], result.Changed);
Assert.Equal("moved/2026-09-28", (await fx.Db.Sequences.GetAsync(good))!.Folder);
foreach (var id in kept.Keys) Assert.Equal(kept[id], (await fx.Db.Sequences.GetAsync(id))!.Folder);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
}
[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 APlanWhosePhotosChangedAppliesWithoutTheirNames()
{
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, filed between them: 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);
// The title changes, the files keep their names.
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual([id], result.FilesKept);
Assert.SequenceEqual([id], result.Changed);
Assert.Equal(0, result.Files);
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 PhotosReceivedUnderTheNamesThePlanGivesLeaveItAsItWas()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
// The archive files new photos as the Reorganize names them, which its photos do not follow yet.
const string Template = "{n:000}";
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = Template } }, fx.Ct);
var templates = new RenameTemplates(File: Template);
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
Assert.Equal(2, plan.Steps.Single().FileChanges);
var request = ArchiveJobs.Reorganize(fx.Archive, plan, templates);
// A camera still uploads into it: its photo is filed under the name the plan leaves it, which changes nothing of the plan.
await UploadAsync(fx, 1, firstSeed: 3, firstSecond: 20);
Assert.Equal("originals/003.JPG", (await FilesAsync(fx, id))[2]);
var now = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
Assert.NotEqual(plan.Steps.Single().FramesVersion, now.Steps.Single().FramesVersion);
Assert.Equal(plan.Fingerprint(), now.Fingerprint());
// The job confirmed before it applies it as it was shown.
var engine = await fx.StartEngineAsync();
var done = await fx.WaitForAsync((await engine.EnqueueAsync(request, cancellationToken: fx.Ct)).Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.Reorganized", 1, 2), done.LogTail);
Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, id));
}
[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 AStepWhosePhotosChangedUnderItsLeasesMovesWithoutRenamingThem()
{
await using var fx = await CreateAsync(context);
var (parent, nested, plan) = await CarrierAsync(fx);
// A photo uploaded once the plan's own checks passed, before its step: the folder moves with the one inside it,
// whose index row follows, and the files keep their names.
var result = await fx.Service.Renamer.ApplyAsync(fx.Archive, plan, async _ => await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5), 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)));
var files = await FilesAsync(fx, parent);
Assert.Count(3, files);
Assert.Empty(files.Intersect(plan.Steps[0].FileSamples.Select(s => s.To)));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task ASequenceStillReceivingPhotosKeepsItsFileNamesWhileTheJobGoesOn()
{
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 third = await UploadAsync(fx, 2, firstSeed: 40, firstSecond: 7200, key: "upload-3");
var templates = new RenameTemplates(Folder: "moved/{date} {hm}", File: "{n:000}");
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second, third], templates, fx.Ct);
var told = new ConcurrentQueue<Guid>();
var service = new ArchiveService(fx.Db, new ArchiveServiceOptions
{
Owner = "jobs",
LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)),
SequenceChanged = (id, _, _) =>
{
told.Enqueue(id);
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);
// A camera uploads into the second sequence while the job waits for the first.
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 received = await FilesAsync(fx, second);
// Its folder moves and its files keep their names; the sequence after it is reorganized; the job then says why it failed.
var failed = await fx.WaitForAsync(job.Id, JobState.Failed, (int)TestTiming.Budget(60));
Assert.Equal(Loc.Plural("Archive.Error.ReorganizeKept", 1), failed.Error);
Assert.Contains(Loc.L("Archive.Log.Reorganized", 3, 4), failed.LogTail);
Assert.Contains(Loc.L("Archive.Log.ReorganizeFilesKept", plan.Steps.Single(s => s.SequenceId == second).FromFolder), failed.LogTail);
Assert.Equal(("moved/2026-09-28 18-00", "moved/2026-09-28 19-00", "moved/2026-09-28 20-00"),
(await FolderAsync(fx, first), await FolderAsync(fx, second), await FolderAsync(fx, third)));
Assert.SequenceEqual(received, await FilesAsync(fx, second));
foreach (var id in new[] { first, third }) Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, id));
Assert.SequenceEqual([first, second, third], told);
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}", Title: "Roof");
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); the second is retitled 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 fx.Service.SetSequenceInfoAsync(second, "Roof north", [], 0, null, fx.Ct);
}
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.Equal("Roof north", (await fx.Db.Sequences.GetAsync(second))!.Title);
// 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, its job resumes the plan without its files and says why; a new dry run renames none of them.
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", plan.Steps.Single().FromFolder), failed.LogTail);
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, so none is.
ManifestStore.WriteSequence(folder.ManifestPath, manifest);
var before = await FilesAsync(fx, id);
var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual([id], result.FilesKept);
Assert.Empty(result.Changed);
Assert.SequenceEqual(before, await FilesAsync(fx, id));
// So it is when resumed after an interruption before its step.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
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));
}
[Test]
public async Task NamesComeFromATitleEditedAfterThePlanNever()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 2);
await fx.Service.SetSequenceInfoAsync(id, "Roof", [], 0, null, fx.Ct);
var from = await FolderAsync(fx, id);
// 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);
Assert.True(plan.Steps.Single() is { ToFolder: "moved/Roof", FileChanges: 2, Retitles: false, NamedByTitle: true });
var before = await FilesAsync(fx, id);
// Retitled once the plan's own checks passed: refused before anything of it moves.
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan,
async _ => await fx.Service.SetSequenceInfoAsync(id, "Roof north", [], 0, null, fx.Ct), null, fx.Ct));
Assert.Equal(from, await FolderAsync(fx, id));
Assert.SequenceEqual(before, await FilesAsync(fx, id));
// Held by its job, the rest is refused as a plan applied anew; 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, []));
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([id], result.Dropped);
Assert.Equal(from, await FolderAsync(fx, id));
Assert.SequenceEqual(before, await FilesAsync(fx, id));
Assert.Equal("Roof north", (await fx.Db.Sequences.GetAsync(id))!.Title);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task APlanAnArchiveOpenCompletesTellsTheSequencesItChanged()
{
await using var fx = await CreateAsync(context);
var id = await UploadAsync(fx, 1);
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: "moved/{date}"), fx.Ct);
// Its job yielded to another, or its host stopped, before the step: the plan is not held.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
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;
},
});
await service.OpenAsync(fx.Archive.RootPath, fx.Ct);
Assert.SequenceEqual([(id, MassRenamer.Change)], told);
Assert.Equal("moved/2026-09-28", await FolderAsync(fx, id));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
[WindowsOnly]
public async Task AMovedFolderWhoseSidecarCannotBeWrittenHasEveryIndexRowFollowIt()
{
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 plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [parent], new RenameTemplates(Folder: "moved/{date}", Title: "Roof"), fx.Ct);
Assert.SequenceEqual([(parent, false), (nested, true)], plan.Steps.Select(s => (s.SequenceId, s.Carried)));
string[] sidecars = [fx.Paths.Sequence(folder).ManifestPath, fx.Paths.Sequence("moved/2026-09-28").ManifestPath];
void Writable(bool writable)
{
foreach (var sidecar in sidecars.Where(File.Exists))
File.SetAttributes(sidecar, writable ? File.GetAttributes(sidecar) & ~FileAttributes.ReadOnly : File.GetAttributes(sidecar) | FileAttributes.ReadOnly);
}
try
{
// Its sidecar can be read, not written: the new title fails once the folder moved.
Writable(false);
await Assert.ThrowsAsync<UnauthorizedAccessException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
// Both index rows followed the folder all the same; the title waits for the rest of the step.
Assert.Equal(("moved/2026-09-28", "moved/2026-09-28/extra"), (await FolderAsync(fx, parent), await FolderAsync(fx, nested)));
Assert.Null((await fx.Db.Sequences.GetAsync(parent))!.Title);
Assert.Empty(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Completed);
}
finally
{
Writable(true);
}
var result = Assert.NotNull(await fx.Service.Renamer.ResumeAsync(fx.Archive, plan.Id, null, fx.Ct));
Assert.SequenceEqual([parent, nested], result.Changed);
Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(parent))!.Title);
await FilesAsync(fx, parent);
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
}