fix(archive): exports follow a Reorganize folder move; writers resolve the folder under the lease

A Reorganize step that moves a sequence folder carries its exports/ with it, but only
the sequences and frames rows followed: renders.output_path kept naming the old folder,
so the server answered 404 for the export, Get/Send exports and Reveal lost it, and no
scan or trash restore could repair it. RenderRepository.RebaseFolderAsync now rewrites
the archive-relative output paths of the step's sequence in the same transaction as the
frames (idempotent on resume; absolute outputs and the archive root are untouched).

Writers that read a sequence row before taking its lease wrote into the folder a
Reorganize had moved meanwhile, creating it again (project.json from the editor or a
sync, a thumbnail pack) or failing on its missing sidecar. They now take the folder from
the index row read under the lease (SequenceWriter.FolderAsync): the editor's save
refuses with FramesChangedException and reloads at the new folder, FramesCurrentAsync
reports a moved folder, and the sync apply, project store, thumbnail pass and its
status, decode tiers, analyses, verify, info edits, ingest, duplicate flags, pack
compaction and photo restores write where the sequence is now; a photo deletion planned
before the move is refused as stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit be28d8acf0d96012c94a266f8af61e9bbafaa28d)
This commit is contained in:
Alby96 committed 2026-10-27 16:29:59 +01:00
1 parent b253cac8d4
commit 9ce201cd70
22 files changed
+343 -35

No files matched your search

@@ -215,6 +215,44 @@ public sealed class ProjectStoreTests(TestContext context)
}
}
[Test]
public async Task AnEditorOpenWhileAReorganizeMovesItsFolderSavesWhereTheSequenceIsNow()
{
var (db, sequenceId, root) = await ArchiveAsync(6);
await using (db)
{
var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) };
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, options);
var content = await source.LoadAsync(context.Cancellation);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(session.SetHero(2));
Assert.True(await session.FlushAsync());
// Only the folder template changed: the Reorganize moves the folder and keeps the frames version.
var service = new ArchiveService(db, options);
var plan = await service.PlanRenameAsync(content.Sequence.ArchiveId, [sequenceId], "Moved/{title}", null, context.Cancellation);
await service.ApplyRenameAsync(plan, null, context.Cancellation);
var moved = new ArchivePaths(root).Sequence(plan.Steps.Single().ToFolder);
Assert.Equal(content.Sequence.FramesVersion, (await db.Sequences.GetAsync(sequenceId))!.FramesVersion);
Assert.False(await source.FramesCurrentAsync(context.Cancellation), "the files are no longer where the editor read them");
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.4 } });
Assert.True(await session.FlushAsync());
var row = (await db.Sequences.GetAsync(sequenceId))!;
Assert.Equal(0.4, ProjectSettings.FromJson(row.SettingsJson!).Exposure.ExposureOffsetEv);
Assert.Equal(row.SettingsJson, File.ReadAllText(moved.ProjectPath), "the moved folder's project has the edit");
Assert.False(Directory.Exists(Path.Combine(root, "Synthetic")), "the folder it left is not created again");
Assert.True(await source.FramesCurrentAsync(context.Cancellation));
Assert.Equal(moved.Exports, session.Content.ExportsFolder);
using var frame = await source.DecodeAsync(1, 32, DecodePurpose.Thumbnail, context.Cancellation);
Assert.NotNull(frame, "the frames are read where they are now");
}
}
}
[Test]
public async Task ASaveThatDoesNotReachTheIndexThrows()
{
@@ -1,5 +1,8 @@
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Processing;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
@@ -233,6 +236,135 @@ public sealed class MassRenameTests(TestContext context)
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task ExportsInsideAMovedFolderAreStillReachable()
{
await using var fx = await CreateAsync(context);
var ids = await NestedAsync(fx);
// Exports of "trips" and of "trips/day2" in their folders, one of "trips" outside the archive, and a row whose
// path only starts with the same letters.
var outside = Path.Combine(context.CreateTempDirectory("exports"), "Trips elsewhere.mp4");
List<Guid> renders =
[
await RenderAsync(fx, ids[0], "trips/exports/Trips.mp4"),
await RenderAsync(fx, ids[1], "trips/day2/exports/Day 2.mp4"),
await RenderAsync(fx, ids[0], outside),
await RenderAsync(fx, ids[0], "trips 2/exports/Other.mp4", write: false),
];
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
Assert.SequenceEqual([false, true, true], plan.Steps.Select(s => s.Carried));
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
string[] expected = ["moved/2026-09-28/exports/Trips.mp4", "moved/2026-09-28/day2/exports/Day 2.mp4", outside, "trips 2/exports/Other.mp4"];
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
foreach (var path in expected[..3]) Assert.FileExists(Path.IsPathRooted(path) ? path : fx.Paths.FromRelative(path));
// A crash after the steps were recorded but before the journal said so: completed again, and again, nothing moves twice.
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders));
}
[Test]
public async Task AnInterruptedMoveTakesTheExportsAlongWhenItResumes()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
List<Guid> renders = [];
foreach (var (id, folder) in ids.Zip(["inbox/a", "inbox/b", "inbox/c"])) renders.Add(await RenderAsync(fx, id, $"{folder}/exports/Clip.mp4"));
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "renamed/{date}", null, fx.Ct);
using var cts = new CancellationTokenSource();
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.ApplyRenameAsync(plan, new SyncProgress(_ => cts.Cancel()), cts.Token));
Assert.Count(1, RenameJournal.ListPending(fx.Paths).Single().Completed);
// Crash in the middle of the next step: its folder moved with its export, the index not yet updated.
var next = plan.Steps[1];
Directory.CreateDirectory(Path.GetDirectoryName(fx.Paths.FromRelative(next.ToFolder))!);
Directory.Move(fx.Paths.FromRelative(next.FromFolder), fx.Paths.FromRelative(next.ToFolder));
await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct); // the next start finds the journal
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
var outputs = await OutputsAsync(fx, renders);
Assert.SequenceEqual(ids.Select(id => $"{plan.Steps.Single(s => s.SequenceId == id).ToFolder}/exports/Clip.mp4"), outputs);
foreach (var path in outputs) Assert.FileExists(fx.Paths.FromRelative(path));
}
[Test]
public async Task WritersThatReadTheSequenceBeforeItsFolderMovedWriteWhereItIsNow()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var stale = (await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!;
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
var now = fx.Paths.Sequence(plan.Steps.Single().ToFolder);
var left = fx.Paths.Sequence(stale.Folder).Folder;
Assert.False(Directory.Exists(left));
// A thumbnail pass and an analysis's project update that read the row before the move take their leases after it.
await fx.Service.Images.BuildThumbnailsAsync(fx.Archive, stale, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.FileExists(now.ThumbsPackPath);
Assert.True(((await fx.Db.Sequences.GetAsync(ids[0], fx.Ct))!.Status & SequenceStatus.ThumbsBuilt) != 0, "the pass is recorded");
var projects = new ProjectStore(fx.Db, new SequenceWriter(new ArchiveServiceOptions { Owner = "analysis" }));
Assert.True(await projects.UpdateAsync(fx.Paths, stale, p => p with { HeroFrame = 1 }, fx.Ct));
Assert.Equal(1, ProjectSettings.FromJson(await File.ReadAllTextAsync(now.ProjectPath, fx.Ct)).HeroFrame);
Assert.False(Directory.Exists(left), "the folder it left is not created again");
}
[Test]
public async Task APhotoFiledWhileTheFolderMovesGoesWhereTheSequenceIsNow()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
var staged = fx.Stage(Start.AddMinutes(30), 99);
var pause = TimeSpan.FromSeconds(TestTiming.Budget(0.5));
// Another process writes the sequence: the move waits for it, and an upload that read the row meanwhile waits behind the move.
Task apply;
Task<IngestResult> upload;
using (await LeaseFile.AcquireAsync(fx.Paths.LocksDirectory, $"seq-{ids[0]:N}", "other", TimeSpan.FromSeconds(5), cancellationToken: fx.Ct))
{
apply = fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
await Task.Delay(pause, fx.Ct);
upload = fx.Service.Ingest.CommitAsync(new IngestRequest(fx.Archive.Id, ids[0], null, null, staged.Path, "LATE.JPG", staged.Size, staged.Sha256,
null, null), fx.Ct);
await Task.Delay(pause, fx.Ct);
Assert.False(apply.IsCompleted || upload.IsCompleted, "both wait for the other process");
}
await apply;
var filed = await upload;
var now = plan.Steps.Single().ToFolder;
Assert.True(filed.RelativePath.StartsWith(now + "/", StringComparison.Ordinal), filed.RelativePath);
Assert.FileExists(fx.Paths.FromRelative(filed.RelativePath));
Assert.Count(4, await fx.Db.Frames.ListBySequenceAsync(ids[0], cancellationToken: fx.Ct));
Assert.False(Directory.Exists(fx.Paths.FromRelative("inbox/a")), "the folder it left is not created again");
}
/// <summary>A render row of <paramref name="sequenceId"/> at <paramref name="output"/> (archive-relative or absolute), with its file unless told otherwise.</summary>
private static async Task<Guid> RenderAsync(ArchiveFixture fx, Guid sequenceId, string output, bool write = true)
{
if (write)
{
var file = Path.IsPathRooted(output) ? output : fx.Paths.FromRelative(output);
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
await File.WriteAllBytesAsync(file, [1, 2, 3], fx.Ct);
}
var render = new Render { Id = Guid.CreateVersion7(), SequenceId = sequenceId, PresetName = "1080p", OutputPath = output, Bytes = 3, Created = DateTimeOffset.UtcNow };
await fx.Db.Renders.InsertAsync(render, fx.Ct);
return render.Id;
}
private static async Task<List<string>> OutputsAsync(ArchiveFixture fx, IEnumerable<Guid> renders)
{
var outputs = new List<string>();
foreach (var id in renders) outputs.Add((await fx.Db.Renders.GetAsync(id, fx.Ct))!.OutputPath);
return outputs;
}
[Test]
public async Task AFolderInsideASequenceFolderIsRefused()
{
@@ -103,13 +103,21 @@ internal sealed class FakeSyncRemote : ISyncRemote
}
}
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
/// <summary>Runs once, before the next manifest is answered: the archive on this PC changing while the sync compares.</summary>
public Func<Task>? OnceBeforeManifest { get; set; }
public async Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
{
if (OnceBeforeManifest is { } before)
{
OnceBeforeManifest = null;
await before();
}
lock (_gate)
{
ManifestCalls++;
if (Refused.Contains(id)) throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "refused"));
return Task.FromResult(Find(id).Manifest(SentProxies.ContainsKey));
return Find(id).Manifest(SentProxies.ContainsKey);
}
}
@@ -97,6 +97,35 @@ public sealed class SyncServiceTests(TestContext context)
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task SettingsTakenWhileAReorganizeMovesTheFolderGoWhereTheSequenceIsNow()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var left = f.Archive.Paths.Sequence((await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Folder).Folder;
// The server's edit is taken after a Reorganize moved the folder of the copy the comparison had read.
f.Remote.EditSettings(remote.Id, SyncFixture.Window33);
f.Remote.OnceBeforeManifest = async () =>
{
var plan = await f.Archive.Service.PlanRenameAsync(f.Archive.Archive.Id, [local.Id], "moved/{title}", null, f.Ct);
await f.Archive.Service.ApplyRenameAsync(plan, null, f.Ct);
};
await f.RefreshAsync();
Assert.Null(f.Remote.OnceBeforeManifest, "the folder moved during the comparison");
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.Equal("moved/Harbour", taken.Folder);
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, taken.SettingsJson), "the server's edit reached this PC");
var project = await File.ReadAllTextAsync(f.Archive.Paths.Sequence(taken.Folder).ProjectPath, f.Ct);
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, project), "project.json in the moved folder follows the index");
Assert.False(Directory.Exists(left), "the folder it left is not created again");
}
[Test]
public async Task PositionsSentToTheServerNameItsFramesAndWaitForPhotosItLacks()
{
@@ -80,6 +80,43 @@ public sealed class ReorganizeTests(TestContext context)
}
}
[Test]
public async Task AnExportMovesWithItsFolderAndStaysDownloadable()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
var id = (await Uploads.UploadAsync(editor, Photo(1), "IMG_0001.JPG", sessionKey: "roof")).SequenceId;
await UntilIdleAsync(server);
var folder = (await server.Database.Sequences.GetAsync(id))!.Folder;
var video = Uploads.Photo(4096, 28);
var relative = $"{folder}/exports/Roof - 4K.mp4";
Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(server.Options.ArchivePath, relative))!);
await File.WriteAllBytesAsync(Path.Combine(server.Options.ArchivePath, relative), video);
var render = new Render { Id = Guid.CreateVersion7(), SequenceId = id, PresetName = "4K HEVC", OutputPath = relative, Bytes = video.Length, Created = DateTimeOffset.UtcNow };
await server.Database.Renders.InsertAsync(render);
// A new folder and title, the files keep their names: the folder moves with its exports.
var request = new ReorganizeRequest([id], false, "reorganized/{title}", null, "Roof", DryRun: true);
ReorganizePlanDto plan;
using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest))
plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto);
JobDto job;
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
{
await applied.ExpectAsync(HttpStatusCode.Accepted);
job = await applied.ReadAsync(ProtocolJson.Default.JobDto);
}
await UntilJobAsync(admin, job.Id, "done");
Assert.Equal("reorganized/Roof", (await server.Database.Sequences.GetAsync(id))!.Folder);
Assert.Equal("reorganized/Roof/exports/Roof - 4K.mp4", (await server.Database.Renders.GetAsync(render.Id))!.OutputPath);
using var response = await editor.GetAsync($"/api/v1/renders/{render.Id}/file");
await response.ExpectAsync(HttpStatusCode.OK);
await Http.BytesEqualAsync(video, response.Content.ReadAsByteArrayAsync());
Assert.False(Directory.Exists(Path.Combine(server.Options.ArchivePath, folder)), "nothing is left at the old place");
}
[Test]
public async Task AReorganizeAsksForTheArchiveAndAValidRequest()
{