fix(copies): close the eighth verification round of owner review 6

- A merge's Renders stage never deletes what sits at a journaled render
  target: a file or folder it did not copy there (a render of the kept
  sequence made after a failed run), or a path another render of the kept
  sequence names, makes the copy take a new free name instead.
- A merge's Verify stage records the hash it read for each kept frame the
  index had none for, the Details stage leaves the versions the verify filed
  out of Main, and Two versions also lists a whole-second instant holding two
  frames of one size and other content (owner Q3).
- The Integrate journal keeps the losers the plan listed as last copies; a
  loser that became the only copy while the job ran is never trashed: the
  journal goes and the job fails as a stale plan.
- Download originals of a server sequence whose earlier download was
  unlinked or kept apart makes a new local sequence under a key of the job,
  instead of filling the old one, re-linking it and overwriting its details.
- An upload never links again from its checkpoint a server sequence the user
  kept apart since the attempt that made it.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 11:38:18 +01:00
1 parent 123ceba845
commit aad8ae46dd
11 files changed
+536 -36

No files matched your search

@@ -404,6 +404,79 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
Assert.Equal(stages.Count, projects.Copied.Count);
}
[Test]
public async Task AResumedRendersStageNeverOverwritesARenderMadeAtItsTargetMeanwhile()
{
var fx = await FixtureAsync();
var s = await ScenarioAsync(fx, 0);
// The other also holds an image-sequence export inside its folder.
var frames = Path.Combine(fx.Paths.Sequence(s.Drop.Folder).Exports, "frames");
Directory.CreateDirectory(frames);
File.WriteAllBytes(Path.Combine(frames, "0001.png"), [1, 2, 3]);
var folder = new Render
{
Id = Guid.CreateVersion7(),
SequenceId = s.Drop.Id,
PresetName = "PNG",
OutputPath = fx.Paths.ToRelative(frames),
Bytes = 3,
Created = DateTimeOffset.UtcNow,
};
await fx.Db.Renders.InsertAsync(folder, fx.Ct);
var merger = Merger(fx);
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
await engine.StartAsync(Ct);
var failedOnce = false;
handler.BeforeStage = stage =>
{
if (stage != MergeStage.Renders || failedOnce) return Task.CompletedTask;
failedOnce = true;
throw new IOException("the other's drive failed a read");
};
var plan = await merger.PlanAsync(s.Copy.Id, s.Keep.Id, s.Drop.Id, s.Choices, NoContext, Ct);
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, s.Keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Failed);
// The failed run had journaled where the copies go and copied nothing; meanwhile the user renders the kept sequence
// with the same names (same date, title and preset).
var keep = (await fx.Db.Sequences.GetAsync(s.Keep.Id))!;
var exports = fx.Paths.Sequence(keep.Folder).Exports;
var clip = Path.Combine(exports, "clip.mp4");
var images = Path.Combine(exports, "frames");
Directory.CreateDirectory(images);
var fresh = RandomNumberGenerator.GetBytes(2048);
File.WriteAllBytes(clip, fresh);
File.WriteAllBytes(Path.Combine(images, "0001.png"), [9, 9, 9]);
await fx.Db.Renders.InsertAsync(new Render
{
Id = Guid.CreateVersion7(),
SequenceId = keep.Id,
PresetName = "1080p",
OutputPath = fx.Paths.ToRelative(clip),
Bytes = fresh.Length,
Sha256 = Sha(fresh),
Created = DateTimeOffset.UtcNow,
}, fx.Ct);
var journal = MergeJournal.Read(fx.Paths, job.Id)!;
journal.RenderTargets[s.Render.Id] = fx.Paths.ToRelative(clip);
journal.RenderTargets[folder.Id] = fx.Paths.ToRelative(images);
journal.Save(fx.Paths);
await engine.ResumeAsync(job.Id, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
// The new renders are as the user made them; the other's go beside them under free names.
Assert.SequenceEqual(fresh, File.ReadAllBytes(clip));
Assert.SequenceEqual(new byte[] { 9, 9, 9 }, File.ReadAllBytes(Path.Combine(images, "0001.png")));
Assert.Count(1, Directory.GetFiles(images));
var movedClip = (await fx.Db.Renders.GetAsync(s.Render.Id))!;
Assert.NotEqual(fx.Paths.ToRelative(clip), movedClip.OutputPath);
Assert.Equal(s.Render.Sha256, Sha(File.ReadAllBytes(fx.Paths.FromRelative(movedClip.OutputPath))));
var movedFolder = (await fx.Db.Renders.GetAsync(folder.Id))!;
Assert.NotEqual(fx.Paths.ToRelative(images), movedFolder.OutputPath);
Assert.SequenceEqual(new byte[] { 1, 2, 3 }, File.ReadAllBytes(Path.Combine(fx.Paths.FromRelative(movedFolder.OutputPath), "0001.png")));
}
[Test]
public async Task APhotoOfTheOtherThatChangedOnDiskFailsTheVerifyAndNothingGoesToTheTrash()
{
@@ -477,6 +550,77 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
}
[Test]
public async Task ASecondVersionOfAnUnhashedKeptPhotoIsListedAndLeftOutOfMain()
{
var fx = await FixtureAsync();
// The kept one adopted and not verified, the other hashed: one photo of the same size and sub-second time, other bytes.
var keep = await SequenceAsync(fx, "keep", [(1, 250, "IMG_0001.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(2, 250, "IMG_0001.JPG")]);
var access = new DbAccess(fx.Db.Database);
await access.ExecuteAsync("UPDATE frames SET size = 1000 WHERE sequence_id = $1 OR sequence_id = $2", [keep.Id, drop.Id], Ct);
await access.ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [keep.Id], Ct);
var copy = await PairAsync(fx, keep.Id, drop.Id);
var merger = Merger(fx);
var (engine, _) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
await engine.StartAsync(Ct);
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
// The kept photo has the hash the merge read, so Two versions lists the pair, the other's version left out of Main.
Assert.Contains(Sha(1, 250), (await fx.Db.Frames.ListBySequenceAsync(keep.Id)).Select(f => f.Sha256));
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(1, 250), Sha(2, 250));
}
[Test]
public async Task APhotoTheVerifyFindsIsAnotherVersionIsListedAtAWholeSecondAndLeftOutOfMain()
{
var fx = await FixtureAsync();
// A camera that records whole seconds, photos of one size (an uncompressed RAW series): neither side hashed, compared
// as the same photo, another photo after all.
var (mine, theirs) = EqualSizeSeeds(0);
var keep = await SequenceAsync(fx, "keep", [(mine, 0, "IMG_0001.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(theirs, 0, "IMG_0001.JPG")]);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1 OR sequence_id = $2", [keep.Id, drop.Id], Ct);
var copy = await PairAsync(fx, keep.Id, drop.Id);
var merger = Merger(fx);
var (engine, _) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
await engine.StartAsync(Ct);
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.Empty(plan.Photos);
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
// Filed at the verify as a second version: listed, and Main renders one photo at that instant.
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0), Sha(theirs, 0)]));
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
}
/// <summary>One photo listed in two versions: <paramref name="kept"/> in Main, <paramref name="incoming"/> left out.</summary>
private static void AssertVersions(IReadOnlyList<PhotoVersions> listed, string kept, string incoming)
{
Assert.Count(1, listed);
var versions = listed[0];
var excluded = new Dictionary<string, bool> { [versions.FirstSha256] = versions.FirstExcluded, [versions.SecondSha256] = versions.SecondExcluded };
Assert.False(excluded[kept]);
Assert.True(excluded[incoming]);
}
/// <summary>Two seeds whose photos at <paramref name="ms"/> have the same size and other bytes.</summary>
private static (int, int) EqualSizeSeeds(int ms)
{
var bySize = new Dictionary<int, int>();
for (var seed = 1; ; seed++)
{
var length = Photos.Jpeg(Start.AddMilliseconds(ms), seed).Length;
if (bySize.TryGetValue(length, out var other)) return (other, seed);
bySize[length] = seed;
}
}
[Test]
public async Task AnUnhashedPhotoOfTheKeptOneWithTheSameContentIsNoLastCopy()
{
@@ -527,6 +527,43 @@ public sealed class IntegrateTests(TestContext context)
Assert.Equal(CopyState.Linked, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
}
[Test]
public async Task ALoserWhoseOtherHolderGoesBeforeTheTrashIsNeverTrashedUnlisted()
{
await using var f = await FixtureAsync(context);
var (engine, handler) = Engine(f);
await using var _ = engine;
await engine.StartAsync(f.Ct);
// This PC's losing version (the server wins) and the server's (this PC wins), each held by a third local sequence
// when planned: neither is a last copy. That sequence's copy is flagged corrupt while the photos move.
foreach (var (n, policy, loser) in new[] { (1, CopyPhotoPolicy.OtherWins, 104), (2, CopyPhotoPolicy.ThisPcWins, 205) })
{
var (local, remote, pair) = await ScenarioAsync(f, n);
var third = await LocalAsync(f, $"Third {n}", [(loser, 30_250, "IMG_0004.JPG")]);
var plan = await Planner(f).PlanAsync(f.Remote, pair, await ChoicesAsync(f, local.Id, remote.Id, policy), PlanContext(), f.Ct);
Assert.True(plan.Destructive, policy.ToString());
Assert.Empty(plan.LastCopies);
handler.BeforeStage = async stage =>
{
if (stage != IntegrateStage.Trash) return;
var held = (await f.Db.Frames.ListBySequenceAsync(third.Id, cancellationToken: f.Ct)).Single();
await f.Db.Frames.UpdateFlagsAsync([held.Id], FrameFlags.Corrupt, FrameFlags.None, f.Ct);
};
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
// Its only copy now: it stays where it was (nothing in either trash), and the journal goes so a retry plans again.
Assert.Equal(Loc.L("Errors.Copies.StalePlan"), failed.Error);
if (policy == CopyPhotoPolicy.OtherWins) Assert.Contains(Sha(loser, 30_250), await LocalHashesAsync(f, local.Id));
else Assert.Contains(Sha(loser, 30_250), RemoteHashes(remote));
Assert.Empty(f.Remote.Trashed);
Assert.False(File.Exists(IntegrateJournal.PathFor(f.Archive.Paths, job.Id)));
handler.BeforeStage = null;
await WaitIdleAsync(f, local.Id);
}
}
[Test]
public async Task TheServersLoserGoesToItsTrashAtTheVersionItsDryRunRead()
{
@@ -2,6 +2,7 @@ using System.Security.Cryptography;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
@@ -35,6 +36,19 @@ public sealed class SyncTransferCopyTests(TestContext context)
return f;
}
/// <summary>Waits until no pass a download queued works on <paramref name="sequenceId"/>.</summary>
private static async Task WaitIdleAsync(SyncFixture f, Guid sequenceId)
{
var until = DateTime.UtcNow.AddSeconds(30);
while (DateTime.UtcNow < until)
{
var held = await f.Db.Jobs.ListPendingTargetsAsync(JobKind.Thumbs, f.Ct);
held.UnionWith(await f.Db.Jobs.ListPendingTargetsAsync(JobKind.LightAnalyse, f.Ct));
if (!held.Contains(sequenceId)) return;
await Task.Delay(20, f.Ct);
}
}
[Test]
public async Task OnlyThePhotosAskedForGoEachWay()
{
@@ -172,6 +186,83 @@ public sealed class SyncTransferCopyTests(TestContext context)
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
}
[Test]
public async Task ARetriedUploadNeverLinksAgainTheServerSequenceItsFirstAttemptMadeAndTheUserKeptApart()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var started = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
// The user keeps the pair apart while a run of the upload that made it is still to be retried.
await f.Sync.UnlinkAsync(f.Server, started, local.Id, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == started);
await f.AddLocalAsync(local.Id, photos[2]);
// The retry resumes from the checkpoint naming the sequence that run made.
var row = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.UploadCommit,
TargetIds = [local.Id],
State = JobState.Running,
NodeId = "t#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
Checkpoint = started.ToString(),
};
await f.Db.Jobs.EnqueueAsync(row, f.Ct);
var retry = new JobContext(new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" }), row, f.Ct);
await new SyncTransfers(f.Sync).UploadAsync(retry, f.Remote, local.Id);
// The sequence kept apart stays apart, unlinked and as it was; a new one holds every photo.
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.Null((await f.Sync.Links.GetAsync(f.Server, started, f.Ct))!.LocalId);
Assert.True(f.Remote.Sequences[started].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
Assert.NotEqual(started, link.RemoteId);
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
}
[Test]
public async Task DownloadingAgainAServerSequenceUnlinkedFromItsDownloadMakesANewLocalSequence()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(3);
var remote = f.Remote.Add("Comet", photos);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
await WaitIdleAsync(f, local);
// Here: one photo deleted, the title edited; then the pair is unlinked (kept apart).
var sequence = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
var gone = (await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct))[0];
var delete = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local, [gone.Id], sequence.FramesVersion, f.Ct);
await f.Archive.Service.FrameTrash.DeleteAsync(delete, cancellationToken: f.Ct);
await f.Db.Sequences.EditAsync(local, new SequenceEdit { Title = "Mine" }, null, f.Ct);
await f.Sync.UnlinkAsync(f.Server, remote.Id, local, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
Assert.Equal(CopyState.KeptApart, pair.State);
// Download originals again: a separate local copy.
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The sequence kept apart is as the user left it: its photos, its deletion, its title, its pair.
var after = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
Assert.Equal("Mine", after.Title);
Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
Assert.Contains(gone.Sha256, (await f.Db.FrameRemovals.ListBySequenceAsync(local, f.Ct)).Select(r => r.Sha256));
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
var copy = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
Assert.NotEqual(local, copy);
Assert.True((await LocalHashesAsync(f, copy)).SetEquals(photos.Select(Sha)));
}
[Test]
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
{