feat: owner review 2 phase 4b: mass conversion after import #13

Merged
Alby96 merged 82 commits from claude/owner-review-2-p4b-rc7 into main 2026-11-03 10:41:59 +01:00
7 changed files with 210 additions and 29 deletions
Showing only changes of commit f8c445fac3 - Show all commits

No files matched your search

+9 -9
View File
@@ -188,14 +188,14 @@ public sealed class ArchiveIndexer
/// <summary>
/// The render rows of the archive that follow a sequence's folder from <paramref name="from"/> to <paramref name="to"/>,
/// in the caller's transaction (<see cref="Repositories.RenderRepository.RebaseFolderAsync"/>). An export is a file, or
/// a folder for an image sequence. It is at its old path still when it is there and the new path is not the same one
/// (on a file system that ignores case it is, when only the case changed). The sequence's own exports inside the folder
/// follow unless they are at the old path still and not at the new one: written there after the move by a writer that
/// read the old folder, which created it again, so the row keeps naming where the export is. An export of its own
/// missing from both places follows, and so does one at its old path when the old folder holds another sequence now:
/// that sequence moved into it since and brought an export of that name. Another sequence's export follows only when it
/// moved with the folder (at its new path and no longer at the old one), and an export of the sequence the old folder
/// holds now never does: that one is in its own folder, whatever the moving sequence took along under the same name.
/// a folder for an image sequence. It is at its old path still when it is there, the new path is not the same one (on
/// a file system that ignores case it is, when only the case changed) and the old folder holds no other sequence now: a
/// file there is that sequence's, which moved into the folder since and brought an export of that name. The sequence's
/// own exports inside the folder follow unless they are at the old path still and not at the new one: written there
/// after the move by a writer that read the old folder, which created it again, so the row keeps naming where the export
/// is. An export of its own missing from both places follows too. Another sequence's export follows only when it moved
/// with the folder (at its new path and no longer at the old one), and an export of the sequence the old folder holds
/// now never does: that one is in its own folder, whatever the moving sequence took along under the same name.
/// </summary>
internal static Task<int> RebaseRendersAsync(ChronosRepositories tx, Archive archive, Guid sequenceId, string from, string to,
CancellationToken cancellationToken)
@@ -209,7 +209,7 @@ public sealed class ArchiveIndexer
if (!own && owner == holder.Value) return false;
var moved = Path.Exists(paths.FromRelative(after));
var behind = !string.Equals(before, after, StringComparison.OrdinalIgnoreCase) && Path.Exists(paths.FromRelative(before))
&& !(own && holder.Value is not null);
&& holder.Value is null;
return own ? moved || !behind : moved && !behind;
}, cancellationToken);
}
@@ -20,8 +20,9 @@ namespace Chronos.Data.Processing.Jobs;
/// preset render after one preparation pass into the sequence's <c>exports/</c> (or the export folder, never on a
/// server), named by the template without taking a name another render of this process is writing, and each finished
/// output is recorded at once (its row id derives from the job and the entry, so every attempt knows what is recorded).
/// Checkpoint: the entries recorded and the output being written, so a crashed attempt's leftovers are removed and only
/// unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone. A
/// Checkpoint: the entries recorded and the output being written, so a crashed attempt's leftovers are removed (where a
/// Reorganize took them since, never in the folder the sequence left, <see cref="Leftover"/>) and only unfinished entries
/// render again. A failed entry fails the job after the others ran; retrying renders it alone. A
/// sequence whose folder is not where the index has it (another index moved it, until this index's next scan; the folder
/// it left may hold another sequence now) is refused.
/// </summary>
@@ -59,7 +60,8 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
{
if (!done.Contains(i) && await db.Renders.GetAsync(RenderId(context.Job.Id, i), cancellation).ConfigureAwait(false) is not null) done.Add(i);
}
if (resume is { Pending: { } pending, PendingOutput: { } output } && !done.Contains(pending) && names.TryReserve(output))
if (resume is { Pending: { } pending, PendingOutput: { } chosen } && !done.Contains(pending)
&& Leftover(paths, folder, resume.Folder, chosen) is { } output && names.TryReserve(output))
{
// Unless another render recorded that name since (the output did not exist yet when it chose it).
var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false);
@@ -78,7 +80,7 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
outcomes = await render.RenderAllAsync(
targets,
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), taken)),
(index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total),
(index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path, sequence.Folder).ToJson(), context.Done, context.Total),
async (index, target, result) =>
{
// The output is complete: record it even if the job is being cancelled, so it is never orphaned.
@@ -149,6 +151,24 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
return new Guid(hash[..16], bigEndian: true);
}
/// <summary>
/// Where the output a crashed attempt was writing is now, for its leftovers to be removed: among the exports of the
/// sequence's folder (the one the index has now, which holds the sequence; one chosen in the folder the sequence had
/// before a Reorganize moved it is where the folder took it), or in an export folder chosen on a client outside the
/// archive. Null, and the leftovers stay, for one anywhere else in the archive: an export folder chosen in it, or the
/// exports of a folder the sequence left, which may hold another sequence now with its own export of that name.
/// </summary>
/// <param name="chosenIn">The sequence's archive-relative folder when the attempt chose the output; null when unknown.</param>
private static string? Leftover(ArchivePaths paths, SequencePaths folder, string? chosenIn, string output)
{
var relative = paths.ToRelative(output);
if (relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative)) return output;
var cut = relative.LastIndexOf('/');
var (parent, name) = (cut < 0 ? string.Empty : relative[..cut], relative[(cut + 1)..]);
if (parent == paths.ToRelative(folder.Exports)) return output;
return chosenIn is not null && parent == paths.ToRelative(paths.Sequence(chosenIn).Exports) ? Path.Combine(folder.Exports, name) : null;
}
/// <summary>
/// Removes what an interrupted attempt left of <paramref name="output"/>: the encoder's hidden temporary file or
/// folder, and an output that was completed but never recorded (it renders again under the same name).
@@ -156,9 +156,10 @@ public static class ProcessingJobs
/// <summary>
/// Resume point of a render job: the batch targets already recorded, and the output a crashed attempt was writing
/// (its leftovers are removed before that target renders again).
/// (its leftovers are removed before that target renders again) with the sequence's archive-relative folder when it
/// chose that output (null in checkpoints written before it was kept), so the leftovers are found after a Reorganize.
/// </summary>
internal sealed record RenderCheckpoint(IReadOnlyList<int> Done, int? Pending, string? PendingOutput)
internal sealed record RenderCheckpoint(IReadOnlyList<int> Done, int? Pending, string? PendingOutput, string? Folder = null)
{
public static RenderCheckpoint Empty { get; } = new([], null, null);
+47 -14
View File
@@ -25,7 +25,8 @@ namespace Chronos.Data.Sync;
/// original the server has not hashed yet, its size, and hash it here) and commit them through the archive ingest,
/// which names them and writes the sidecar; the first original creates the local
/// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the
/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place.
/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place in
/// the folder the sequence is in (never one it left).
/// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked
/// upload) and the server's into the local copy's exports. A resumed job skips what is already on the other side, so
/// pausing or a crash loses at most the files in flight.
@@ -244,14 +245,14 @@ internal sealed class SyncTransfers(SyncService sync)
await progress.StepAsync().ConfigureAwait(false);
}
var sequenceId = local?.Id;
int restored = 0, refused = 0;
var refused = 0;
var restores = new ConcurrentBag<(string Staged, Guid FrameId)>();
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
{
var (staged, sha) = await FetchOriginalAsync(remote, frame, staging, token).ConfigureAwait(false);
if (restore.TryGetValue(sha, out var place))
if (restore.TryGetValue(sha, out var frameId))
{
Restore(staged, place);
Interlocked.Increment(ref restored);
restores.Add((staged, frameId));
}
else if (frame.Sha256.Length == 0 && (tombstones.DeletedLocally(sha) || have.Contains(tombstones.Canonical(sha)!)))
{
@@ -267,26 +268,30 @@ internal sealed class SyncTransfers(SyncService sync)
}
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
TryDeleteDirectory(staging);
// Null when the sequence is not in the folder the index has: the copies stay staged for the next attempt.
var restored = restores.IsEmpty ? 0 : await RestoreAsync(local!, paths, restores, ct).ConfigureAwait(false);
if (restored is not null) TryDeleteDirectory(staging);
// Restored originals are checked against their records, which clears their missing flag.
if (restored > 0) await VerifyAsync(archive, local!.Id, ct).ConfigureAwait(false);
if (created) await sync.TakeAllAsync(remote, remoteId, ct).ConfigureAwait(false);
await sync.RecompareAsync(remote, remoteId, ct).ConfigureAwait(false);
if (sequenceId is { } downloaded && wanted.Count > restored + refused)
if (sequenceId is { } downloaded && wanted.Count > restores.Count + refused)
{
var label = local!.DisplayTitle;
await EnqueueFollowUpAsync(context, ArchiveJobs.Thumbnails([downloaded], label)).ConfigureAwait(false);
await EnqueueFollowUpAsync(context, ProcessingJobs.LightAnalysis([downloaded], label)).ConfigureAwait(false);
}
if (restored is null) throw new InvalidOperationException(Loc.L("Errors.Archive.FolderMoved"));
}
/// <summary>
/// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and where
/// each original flagged missing belongs. Frames not hashed yet (an adopted folder never verified) are hashed first
/// through the archive's verify, so the server's copies of them are recognised instead of committed again as duplicates.
/// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and the
/// frame each original flagged missing restores. Frames not hashed yet (an adopted folder never verified) are hashed
/// first through the archive's verify, so the server's copies of them are recognised instead of committed again as
/// duplicates.
/// </summary>
private async Task<(HashSet<string> Have, Dictionary<string, string> Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local,
private async Task<(HashSet<string> Have, Dictionary<string, Guid> Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local,
CancellationToken ct)
{
var frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false);
@@ -297,12 +302,11 @@ internal sealed class SyncTransfers(SyncService sync)
}
var have = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0 && f.Sha256 is not null).Select(f => f.Sha256!.ToLowerInvariant())
.ToHashSet(StringComparer.Ordinal);
var paths = new ArchivePaths(archive.RootPath);
var restore = new Dictionary<string, string>(StringComparer.Ordinal);
var restore = new Dictionary<string, Guid>(StringComparer.Ordinal);
foreach (var frame in frames.Where(f => (f.Flags & FrameFlags.Missing) != 0 && f.Sha256 is not null))
{
var sha = frame.Sha256!.ToLowerInvariant();
if (!have.Contains(sha)) restore.TryAdd(sha, paths.FromRelative(frame.RelativePath));
if (!have.Contains(sha)) restore.TryAdd(sha, frame.Id);
}
var photos = SyncRules.Photos([.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0)]);
return (have, restore, photos);
@@ -311,6 +315,35 @@ internal sealed class SyncTransfers(SyncService sync)
private Task VerifyAsync(Archive archive, Guid sequenceId, CancellationToken ct) =>
sync.Archives.Verifier.VerifyAsync(archive, [sequenceId], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: ct);
/// <summary>
/// Puts the verified copies of originals flagged missing (<paramref name="staged"/>, each with the frame it restores)
/// back where their records say, under the sequence's lease in its folder as the index has it then: a Reorganize moves
/// the folder and the frames' paths under that lease. Returns how many went back; a file that reappeared meanwhile is
/// kept, and the copy of a frame that left the index is dropped. Null, with nothing restored and every copy kept in
/// staging for the next attempt, when the sequence is not in that folder (another index moved it, and maybe another
/// sequence into it; this index's next scan finds them): the folder it left is not created again, nor given an
/// original of this sequence when it holds another one now.
/// </summary>
private Task<int?> RestoreAsync(Sequence local, ArchivePaths paths, IReadOnlyCollection<(string Staged, Guid FrameId)> staged, CancellationToken ct) =>
sync.Archives.UnderLeaseAsync(local, async row =>
{
if (row is null) throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
if (!SequenceFolders.Holds(paths.Sequence(row.Folder), row.Id)) return (int?)null;
var restored = 0;
foreach (var (copy, frameId) in staged)
{
// Read under the lease, as the folder: where the photo belongs in the folder the sequence is in now.
if (await sync.Database.Frames.GetAsync(frameId, ct).ConfigureAwait(false) is not { } frame || frame.SequenceId != row.Id)
{
File.Delete(copy);
continue;
}
Restore(copy, paths.FromRelative(frame.RelativePath));
restored++;
}
return restored;
}, ct);
/// <summary>Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept.</summary>
private static void Restore(string staged, string place)
{
@@ -391,6 +391,40 @@ public sealed class MassRenameTests(TestContext context)
}
}
[Test]
public async Task AnExportSavedInAnotherSequencesFolderNeverNamesTheOneBroughtIntoIt()
{
// The new folder is scanned after "inbox/a", then before it.
foreach (var template in new[] { "moved/{date}", "done/{date}" })
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
// "inbox/b" saved an export in the exports of "inbox/a" (the Export tab's folder picker); "inbox/c" has one of the same name.
List<Guid> renders =
[
await RenderAsync(fx, ids[1], "inbox/a/exports/Clip.mp4"),
await RenderAsync(fx, ids[2], "inbox/c/exports/Clip.mp4"),
];
await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/a/exports/Clip.mp4"), "b", fx.Ct);
await File.WriteAllTextAsync(fx.Paths.FromRelative("inbox/c/exports/Clip.mp4"), "c", fx.Ct);
var (server, archive) = await fx.OtherWriterAsync();
// The other index moves "inbox/a", the export of "inbox/b" along, then "inbox/c" into the folder it left, its export along.
var first = await server.PlanRenameAsync(archive.Id, [ids[0]], template, null, fx.Ct);
await server.ApplyRenameAsync(first, null, fx.Ct);
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [ids[2]], "inbox/a", null, fx.Ct), null, fx.Ct);
// The export of "inbox/b" follows the folder its file moved with and never names the one of "inbox/c".
await fx.ScanAsync();
string[] expected = [first.Steps.Single().ToFolder + "/exports/Clip.mp4", "inbox/a/exports/Clip.mp4"];
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), template);
Assert.Equal("b", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[0]), fx.Ct), template);
Assert.Equal("c", await File.ReadAllTextAsync(fx.Paths.FromRelative(expected[1]), fx.Ct), template);
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
Assert.SequenceEqual(expected, await OutputsAsync(fx, renders), template);
}
}
[Test]
public async Task APhotoDeletionWhoseFolderMovedWhileItWaitedForTheLeaseIsRefused()
{
@@ -375,6 +375,50 @@ public sealed class RenderJobTests(TestContext context)
Assert.Count(2, await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct));
}
[Test]
public async Task ARenderResumedAfterItsFolderMovedNeverDeletesWhatAnotherSequenceBroughtIntoIt()
{
// The crashed attempt's checkpoint names the folder it chose the output in, or (written by an older version) does not.
foreach (var named in new[] { true, false })
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var stranger = await fx.AddAsync(Scene(), "Other");
var output = Path.Combine(fx.Folder(sequence).Exports, "clip-MJPEG.avi");
// The crashed attempt left its encoder's temporary file and a finished output it never recorded; the other
// sequence has an export of that name, and a hidden file that looks like such a leftover.
Directory.CreateDirectory(fx.Folder(sequence).Exports);
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(sequence).Exports, ".clip-MJPEG.avi.0badf00d.tmp"), new byte[100], fx.Ct);
await File.WriteAllBytesAsync(output, new byte[100], fx.Ct);
Directory.CreateDirectory(fx.Folder(stranger).Exports);
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(stranger).Exports, ".clip-MJPEG.avi.0ddba11.tmp"), new byte[50], fx.Ct);
await File.WriteAllBytesAsync(Path.Combine(fx.Folder(stranger).Exports, "clip-MJPEG.avi"), Encoding.ASCII.GetBytes("RIFF theirs"), fx.Ct);
// Another index moves the folder away, the leftovers along, then the other sequence into the folder it left; this
// index's scan finds both before the job resumes.
var (server, archive) = await fx.Archive.OtherWriterAsync();
var plan = await server.PlanRenameAsync(archive.Id, [sequence.Id], "Moved/{date}", null, fx.Ct);
await server.ApplyRenameAsync(plan, null, fx.Ct);
await server.ApplyRenameAsync(await server.PlanRenameAsync(archive.Id, [stranger.Id], sequence.Folder, null, fx.Ct), null, fx.Ct);
await fx.Archive.ScanAsync();
var before = ArchiveFixture.FilesOf(fx.Folder(sequence).Folder);
await fx.StartEngineAsync();
var job = await fx.Archive.EnqueueWithCheckpointAsync(fx.Engine, ProcessingJobs.Render(sequence, Mjpeg, 96, 64),
new RenderCheckpoint([], 0, output, named ? sequence.Folder : null).ToJson());
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.SequenceEqual(before, ArchiveFixture.FilesOf(fx.Folder(sequence).Folder), $"{named}: the other sequence's files are untouched");
// Its leftovers are removed where the folder took them when the checkpoint says where it chose the output, and
// stay otherwise: the render then takes another name.
var moved = fx.Archive.Paths.Sequence(plan.Steps.Single().ToFolder).Exports;
Assert.SequenceEqual(named ? ["clip-MJPEG.avi"] : [".clip-MJPEG.avi.0badf00d.tmp", "clip-MJPEG (2).avi", "clip-MJPEG.avi"], Entries(moved), named.ToString());
var rendered = (await fx.Db.Renders.ListBySequenceAsync(sequence.Id, fx.Ct)).Single().OutputPath;
Assert.Equal(plan.Steps.Single().ToFolder + (named ? "/exports/clip-MJPEG.avi" : "/exports/clip-MJPEG (2).avi"), rendered);
Assert.Equal("RIFF", Encoding.ASCII.GetString((await File.ReadAllBytesAsync(fx.Archive.Paths.FromRelative(rendered), fx.Ct))[..4]));
}
}
[Test]
public async Task ConcurrentRendersOfOnePresetKeepBothOutputs()
{
@@ -6,6 +6,7 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Archiving;
using Chronos.Protocol;
using Chronos.Testing;
@@ -384,6 +385,54 @@ public sealed class SyncTransferTests(TestContext context)
Assert.Equal(SyncStatus.InSync, (await f.EntryAsync("Harbour")).Status);
}
[Test]
public async Task AnOriginalIsRestoredOnlyWhereTheSequenceIsNow()
{
// The folder the sequence left holds another sequence now, or nothing.
foreach (var taken in new[] { true, false })
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Harbour", photos);
var stranger = taken ? await f.LocalAsync("Stranger", f.NewPhotos(2)) : null;
var lost = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct))[1];
File.Delete(f.Archive.Paths.FromRelative(lost.RelativePath));
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
// Another index moves the folder away, then the other sequence (first parked elsewhere: its folder is the same
// name with a number) into the folder it left; this index has scanned neither.
var folder = f.Archive.Paths.Sequence(local.Folder).Folder;
var (other, archive) = await f.Archive.OtherWriterAsync();
var moves = stranger is null ? [(local.Id, "moved/{title}")] : new[] { (local.Id, "moved/{title}"), (stranger.Id, "parked/{title}"), (stranger.Id, local.Folder) };
foreach (var (id, template) in moves)
await other.ApplyRenameAsync(await other.PlanRenameAsync(archive.Id, [id], template, null, f.Ct), null, f.Ct);
var before = taken ? ArchiveFixture.FilesOf(folder) : null;
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Archive.FolderMoved"), failed.Error, taken.ToString());
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are untouched");
else Assert.False(Directory.Exists(folder), "the folder it left is not created again");
// Once this index's scan found it there, the original goes back into the folder the sequence is in now.
await f.Archive.ScanAsync();
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Originals, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var moved = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Folder;
Assert.Equal("moved/Harbour", moved);
var restored = (await f.Db.Frames.GetAsync(lost.Id, f.Ct))!;
Assert.Equal(moved + lost.RelativePath[local.Folder.Length..], restored.RelativePath);
Assert.Equal(lost.Sha256, Sha(await File.ReadAllBytesAsync(f.Archive.Paths.FromRelative(restored.RelativePath), f.Ct)));
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).All(fr => (fr.Flags & FrameFlags.Missing) == 0), "nothing missing");
if (taken) Assert.SequenceEqual(before!, ArchiveFixture.FilesOf(folder), "the other sequence's files are still untouched");
else Assert.False(Directory.Exists(folder));
}
}
[Test]
public async Task OriginalsTheServerHasNotHashedAreDownloadedAndHashedHere()
{