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

- A merge plan hashes the kept sequence's unhashed frames that match a hashed
  photo of the other by size and time: the same content is no longer a false
  last copy, and another content is copied in as a second version instead of
  going to the trash with the other sequence.
- The Replace stage trashes a losing version of the kept sequence only while
  another sequence still holds it or the plan listed it as a last copy;
  otherwise the journal goes and the job fails as a stale plan.
- A details conflict at the merge's or the Integrate's Details stage drops
  the journal, so a retry plans again instead of failing the same way.
- The Integrate's Projects stage keeps a project for good only for a
  permanent refusal; a server out of reach fails the job with the journal
  kept, and the retry finishes the same copy.
- A pair read as deleted on the server is cleared when the server lists it
  again or a link to that sequence is made.
- An upload of a sequence kept apart from a server sequence goes under a
  session key of the job, making a new server sequence; a link made over a
  kept-apart pair moves it to Linked.

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 10:45:11 +01:00
1 parent c3273b7da5
commit 123ceba845
13 files changed
+418 -13

No files matched your search

@@ -450,6 +450,109 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
}
[Test]
public async Task AnUnhashedPhotoOfTheKeptOneIsHashedByThePlanAndAnotherPhotoOfTheOtherIsKeptAsASecondVersion()
{
var fx = await FixtureAsync();
// The kept one adopted and not verified, the other hashed: one photo of the same size and time, other bytes.
var keep = await SequenceAsync(fx, "keep", [(1, 0, "IMG_0001.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(2, 0, "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);
Assert.Empty(plan.LastCopies);
Assert.SequenceEqual([(PhotoAction.FetchVersion, Sha(2, 0))], plan.Photos.Select(p => (p.Action, p.Sha256!)));
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
var frames = await fx.Db.Frames.ListBySequenceAsync(keep.Id);
Assert.Count(2, frames);
Assert.Contains(Sha(2, 0), frames.Select(f => f.Sha256));
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
}
[Test]
public async Task AnUnhashedPhotoOfTheKeptOneWithTheSameContentIsNoLastCopy()
{
var fx = await FixtureAsync();
var keep = await SequenceAsync(fx, "keep", [(1, 0, "IMG_0001.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(1, 0, "IMG_0001.JPG")]);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [keep.Id], Ct);
var copy = await PairAsync(fx, keep.Id, drop.Id);
var plan = await Merger(fx).PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.Empty(plan.LastCopies);
Assert.Empty(plan.Photos);
}
[Test]
public async Task ALosingVersionWhoseOtherHolderIsFlaggedMeanwhileIsNeverTrashedUnlisted()
{
var fx = await FixtureAsync();
var keep = await SequenceAsync(fx, "keep", [(1, 0, "IMG_0001.JPG"), (4, 30_250, "IMG_0004.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(1, 0, "IMG_0001.JPG"), (5, 30_250, "IMG_0004.JPG")]);
// A third sequence holds the kept one's losing version: not a last copy when planned.
var third = await SequenceAsync(fx, "third", [(4, 30_250, "IMG_0004.JPG")]);
var copy = await PairAsync(fx, keep.Id, drop.Id);
var merger = Merger(fx);
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
await engine.StartAsync(Ct);
var choices = await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.OtherWins);
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, choices, NoContext, Ct);
Assert.Empty(plan.LastCopies);
Assert.Contains(plan.Photos, p => p.Action == PhotoAction.TrashHere);
// While the photos are copied, a verify flags the third's copy Corrupt.
handler.BeforeStage = async stage =>
{
if (stage != MergeStage.Replace) return;
var held = (await fx.Db.Frames.ListBySequenceAsync(third.Id)).Single();
await fx.Db.Frames.UpdateFlagsAsync([held.Id], FrameFlags.Corrupt, FrameFlags.None, Ct);
};
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
// Its only usable copy now: the kept one still holds it (beside the other's version), nothing went to the trash, and
// the journal went so the next run plans again.
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
var kept = await fx.Db.Frames.ListBySequenceAsync(keep.Id);
Assert.Contains(kept, f => f.Sha256 == Sha(4, 30_250) && f.Flags == FrameFlags.None
&& Sha(File.ReadAllBytes(fx.Paths.FromRelative(f.RelativePath))) == Sha(4, 30_250));
Assert.Contains(Sha(5, 30_250), kept.Select(f => f.Sha256));
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)));
}
[Test]
public async Task ADetailsChangeOfTheKeptOneBeforeTheDetailsStageMakesTheRetryPlanAgain()
{
var fx = await FixtureAsync();
var s = await ScenarioAsync(fx, 0);
var merger = Merger(fx);
var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
await engine.StartAsync(Ct);
handler.BeforeStage = stage => stage == MergeStage.Details ? fx.Db.Sequences.SetTagsAsync(s.Keep.Id, ["edited"], Ct) : Task.CompletedTask;
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);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.DetailsChanged"), failed.Error);
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)), "the next run plans again");
// The Retry plans again and says what the new plan needs (the new detail line) instead of failing the same way.
handler.BeforeStage = null;
await engine.ResumeAsync(job.Id, Ct);
failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.Plural("Errors.Copies.DetailsUnchosen", 1), failed.Error);
Assert.NotNull(await fx.Db.Sequences.GetAsync(s.Drop.Id));
}
[Test]
public async Task ADamagedPhotoOfTheKeptOneIsRepairedFromTheOther()
{
@@ -647,6 +647,89 @@ public sealed class IntegrateTests(TestContext context)
Assert.Equal(CopyState.Linked, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
}
[Test]
public async Task ARetryAfterTheDetailsChangedPlansAgainInsteadOfFailingTheSameWay()
{
await using var f = await FixtureAsync(context);
var (engine, handler) = Engine(f);
await using var _ = engine;
await engine.StartAsync(f.Ct);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos.Take(2).ToList(), SyncFixture.Window33);
var remote = f.Remote.Add("Comet NAS", [photos[0], photos[2]], SyncFixture.Window33);
var pair = await PairAsync(f, local.Id, remote.Id);
handler.BeforeStage = async stage =>
{
if (stage == IntegrateStage.Details) await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
};
var plan = await Planner(f).PlanAsync(f.Remote, pair, await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.Union), PlanContext(), 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);
Assert.Equal(Loc.L("Errors.Copies.DetailsChanged"), failed.Error);
Assert.False(File.Exists(IntegrateJournal.PathFor(f.Archive.Paths, job.Id)), "the next run plans again");
// The edit never goes back: the Retry plans again against both sides as they are now and names the new difference.
handler.BeforeStage = null;
await engine.ResumeAsync(job.Id, f.Ct);
failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.Plural("Errors.Copies.DetailsUnchosen", 1), failed.Error);
var after = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal(CopyState.Linked, after.State);
// Compared again, the photos moved are the same on both sides and only the details differ.
var again = await Planner(f).PlanAsync(f.Remote, after, await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.Union), PlanContext(), f.Ct);
Assert.Empty(again.Photos);
}
[Test]
public async Task AServerOutOfReachDuringTheProjectsFailsTheJobAndTheRetryFinishesTheSameCopy()
{
await using var f = await FixtureAsync(context);
f.Remote.Capabilities.Add(ServerCapabilities.Projects);
var (local, remote, pair) = await ScenarioAsync(f);
var standIn = await LocalAsync(f, "Stand-in", [(50, 0, "IMG_0050.JPG"), (51, 5_000, "IMG_0051.JPG")]);
var projects = f.Archive.Service.Projects;
var serverHome = new ArchiveProjectHome(f.Db, projects, standIn.Id);
var localFrames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
var project = await projects.CreateAsync(local.Id, "Vertical", cancellationToken: f.Ct);
await projects.PushAsync(project.Id, Projects.ProjectServiceTests.Draft(await projects.HeadAsync(project.Id, f.Ct),
new ProjectSettings { ExcludedFrames = [1] }, localFrames), f.Ct);
var planner = new IntegratePlanner(f.Sync, new CopySides(f.Db), projects, (_, _) => serverHome);
var plan = await planner.PlanAsync(f.Remote, pair, await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.Union), PlanContext(keepsProjects: true), f.Ct);
Assert.SequenceEqual(["ThisPc:Vertical"], plan.Projects.Select(p => $"{p.From}:{p.TargetName}"));
var copier = new FlakyCopier(new ProjectTransplant());
var connector = new SyncFixture.Connector(f.Remote);
var handler = new IntegrateJobHandler(f.Sync, planner, copier, connector, f.Sync.Copies, f.Archive.Service);
await using var engine = new JobEngine(f.Db, [.. f.Archive.Service.CreateJobHandlers(), .. f.Sync.CreateJobHandlers(connector), handler],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(f.Ct);
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
await f.Archive.WaitForAsync(job.Id, JobState.Failed);
// Not a project kept for good: the journal and the pair's job stay for the retry.
Assert.True(File.Exists(IntegrateJournal.PathFor(f.Archive.Paths, job.Id)), "a retry resumes the copy");
Assert.Equal(job.Id, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.JobId);
await engine.ResumeAsync(job.Id, f.Ct);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.Equal(CopyState.Integrated, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.SequenceEqual(["Vertical"], (await projects.ListAsync(standIn.Id, f.Ct)).Where(p => !p.IsMain).Select(p => p.Name));
Assert.Equal(2, copier.Calls);
}
/// <summary>A project copier whose first copy meets a server out of reach (a network error, gone a moment later).</summary>
private sealed class FlakyCopier(IProjectCopier inner) : IProjectCopier
{
public int Calls { get; private set; }
public async Task<SequenceProject> CopyAsync(IProjectHome from, SequenceProject source, IProjectHome to, string name, TransplantStep? journal,
Func<TransplantStep, ValueTask> save, CancellationToken ct)
{
if (++Calls == 1) throw new HomeUnavailableException("The server cannot be reached: connection reset");
return await inner.CopyAsync(from, source, to, name, journal, save, ct);
}
}
[Test]
public async Task AServerTitleEditMeanwhileOverAPlannedLineThisPcWinsStopsTheDetails()
{
@@ -177,6 +177,39 @@ public sealed class SyncServiceCopyTests(TestContext context)
Assert.True(pair.NeedsAttention);
}
[Test]
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet", photos);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), pair.Id], f.Ct);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.True((await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGone);
// Restored from the server's trash: listed again, it no longer reads "deleted on server".
nas.Sequences[remote.Id] = remote;
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((0, (DateTimeOffset?)null, false), (pair.RemoteGoneHits, pair.RemoteGoneAt, pair.RemoteGone));
Assert.Equal(CopyState.Candidate, pair.State);
// A pair still marked (the listing missed it) is cleared by a link to that very sequence: automatic photos may move again.
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_hits = 2, remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow, pair.Id], f.Ct);
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
pair = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((0, false, CopyState.Linked), (pair.RemoteGoneHits, pair.RemoteGone, pair.State));
}
[Test]
public async Task ASequenceBackOnTheServerIsAskedAboutAgain()
{
@@ -143,6 +143,35 @@ public sealed class SyncTransferCopyTests(TestContext context)
Assert.True(target.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
}
[Test]
public async Task AnUploadOfASequenceKeptApartMakesANewServerSequenceAndLeavesTheOtherAlone()
{
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 first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
// Unlinked ("Stop syncing these sequences"): the pair is kept apart.
await f.Sync.UnlinkAsync(f.Server, first, local.Id, f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == first);
Assert.Equal(CopyState.KeptApart, pair.State);
// A new photo, then a plain Upload.
await f.AddLocalAsync(local.Id, photos[2]);
job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The sequence kept apart gets nothing, and stays apart and unlinked; a new one holds every photo.
Assert.True(f.Remote.Sequences[first].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.Null((await f.Sync.Links.GetAsync(f.Server, first, f.Ct))!.LocalId);
var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
Assert.NotEqual(first, link.RemoteId);
Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
}
[Test]
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
{