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

- A merge verify that finds a hashed photo the plan did not copy (held by
  a third sequence when planned) held by nothing now drops its journal and
  fails as a stale plan, so the retry plans again and lists the photo as a
  last copy instead of failing with "did not match after copying" forever.
- A comparison settles no details of a pair being integrated, and the
  Integrate's Details stage refuses a line decided as the server's whose
  server value is now this PC's own, so a background push or pull no longer
  reverses the user's line-by-line choice (owner Q4).
- A 404 for a server sequence no local copy is linked to deletes only its
  Candidate pairs; a Kept apart answer counts the hit as a linked pair does
  (two 404s GoneRecheck apart), so a moment's 404 neither re-asks nor
  auto-links a pair the user kept separate (owner Q1). Upload all local
  sends the local sequence once the deletion is confirmed.
- Download originals into a local copy the server key names and that is
  paired with the server sequence links it first and fills it as a linked
  copy: its tombstones hold and its details are compared, not overwritten.
- An upload of a sequence with a Candidate pair goes under a key of the
  job, and one that joins a server sequence this PC already knows compares
  its details instead of sending them all over the server's.

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 13:17:23 +01:00
1 parent c1c02d8ef7
commit e002c583d6
12 files changed
+383 -34

No files matched your search

@@ -1093,6 +1093,43 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
Assert.Contains(again.LastCopies, l => l.Key == Sha(5, 30_250));
}
[Test]
public async Task APhotoHeldByAThirdSequenceThatIsGoneByTheVerifyMakesTheRetryPlanAgain()
{
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 other's losing version: not a last copy when planned.
var third = await SequenceAsync(fx, "third", [(5, 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 plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.ThisPcWins), NoContext, Ct);
Assert.Empty(plan.LastCopies);
handler.BeforeStage = async stage =>
{
if (stage == MergeStage.Verify) await fx.Db.Sequences.DeleteAsync(third.Id, Ct);
};
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
// A last copy the plan did not list, not a failed copy: the journal goes and nothing goes to the trash.
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
Assert.Contains(Sha(5, 30_250), await HashesAsync(fx, drop.Id));
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)), "the next run plans again");
// The Retry asks for a new comparison instead of the same verify error, and the new plan lists the photo.
handler.BeforeStage = null;
await engine.ResumeAsync(job.Id, Ct);
failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
var again = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.ThisPcWins), NoContext, Ct);
Assert.Contains(again.LastCopies, l => l.Key == Sha(5, 30_250));
}
[Test]
public async Task APhotoAddedToTheOtherOrDeletedFromTheKeptOneMeanwhileKeepsTheOtherOutOfTheTrash()
{
@@ -276,7 +276,7 @@ public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(
}
[Test]
public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsUnlinkedMatches()
public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsCandidatesAndCountsOnItsKeptApartAnswers()
{
var (db, _, s) = await SetupAsync(4);
var store = new FoundCopyStore(db);
@@ -289,18 +289,35 @@ public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(
var elsewhere = await store.UpsertFoundAsync(Remote(s[3].Id, Guid.CreateVersion7()), Ct);
// An observation-only link answers 404: no local copy is linked to it.
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now, Ct);
var first = Guid.NewGuid();
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now, Ct);
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(1), Ct);
// Its matches nobody linked are gone, so Upload all local reads their local sequences as local only again.
// The unanswered match is gone; the Keep apart answer stays and counts the 404 once, not read as deleted yet.
Assert.Null(await store.GetAsync(candidate.Id, Ct));
Assert.Null(await store.GetAsync(apart.Id, Ct));
var row = (await store.GetAsync(apart.Id, Ct))!;
Assert.Equal((CopyState.KeptApart, 1, false), (row.State, row.RemoteGoneHits, row.RemoteGone));
Assert.Equal(CopyState.Linked, (await store.GetAsync(linked.Id, Ct))!.State);
Assert.Equal(CopyState.Candidate, (await store.GetAsync(elsewhere.Id, Ct))!.State);
var left = await store.ListAsync(Ct);
var entries = s[..2].Select(q => new SyncEntry(q, null, SyncStatus.LocalOnly)).ToList();
var (upload, skipped) = UploadAllRule.Select(entries, left, new HashSet<Guid>(), new HashSet<Guid>());
var (upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Equal(s[0].Id, upload.Single().Local!.Id);
Assert.Equal((s[1].Id, UploadSkip.DeletedOnServer), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
// A second 404 within the re-check is the same moment; one after it confirms the deletion.
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddMinutes(5), Ct);
Assert.Equal(1, (await store.GetAsync(apart.Id, Ct))!.RemoteGoneHits);
await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddHours(1), Ct);
row = (await store.GetAsync(apart.Id, Ct))!;
Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
(upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(skipped);
Assert.Count(2, upload);
// Listed again: the count clears and the answer is the user's as before.
await store.ClearRemoteGoneAsync(Nas, remote, Ct);
row = (await store.GetAsync(apart.Id, Ct))!;
Assert.Equal((CopyState.KeptApart, 0), (row.State, row.RemoteGoneHits));
}
[Test]
@@ -800,6 +800,73 @@ public sealed class IntegrateTests(TestContext context)
Assert.Equal("Comet (night)", remote.Title);
}
/// <summary>
/// A linked pair whose details were agreed, then edited on this PC (Window41, not sent yet), with every detail line
/// decided as the server's (Window33): the plan of an Integrate the user confirmed.
/// </summary>
private static async Task<(Sequence Local, FakeSequence Remote, FoundCopy Pair, IntegratePlan Plan)> EditedHereServerChosenAsync(SyncFixture f)
{
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos.Take(2).ToList(), SyncFixture.Window33);
var remote = f.Remote.Add("Comet", [photos[0], photos[2]], SyncFixture.Window33);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.Sync.RefreshSequencesAsync(f.Remote, [remote.Id], new SyncPolicy(AutoSyncSettings: false), f.Ct);
Assert.Equal(local.SettingsVersion, (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!.BaseLocalSettings);
local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
var pair = (await f.Sync.Copies.FindRemoteAsync(local.Id, f.Server, remote.Id, f.Ct))!;
var choices = await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.Union);
Assert.NotEmpty(choices.Details);
choices = choices with { Details = choices.Details.ToDictionary(d => d.Key, _ => CopySide.Other) };
var plan = await Planner(f).PlanAsync(f.Remote, pair, choices, PlanContext(), f.Ct);
return (local, remote, pair, plan);
}
[Test]
public async Task ABackgroundSyncDuringTheIntegrateLeavesTheDetailsToTheUsersChoice()
{
await using var f = await FixtureAsync(context);
var (engine, handler) = Engine(f);
await using var _ = engine;
await engine.StartAsync(f.Ct);
var (local, remote, _, plan) = await EditedHereServerChosenAsync(f);
// The server fires sequenceChanged as the photos land (or the periodic refresh runs): the agent compares the pair.
handler.BeforeStage = async stage =>
{
if (stage == IntegrateStage.Details) await f.Sync.RefreshSequencesAsync(f.Remote, [remote.Id], new SyncPolicy(), f.Ct);
};
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The server's settings the user kept are on both sides: this PC's edit was not pushed over them meanwhile.
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson), remote.SettingsJson);
Assert.True(SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
}
[Test]
public async Task AServerValueThatIsThisPcsOwnOverALineDecidedAsTheServersStopsTheDetails()
{
await using var f = await FixtureAsync(context);
var (engine, handler) = Engine(f);
await using var _ = engine;
await engine.StartAsync(f.Ct);
var (local, remote, pair, plan) = await EditedHereServerChosenAsync(f);
// This PC's planned value reaches the server while the photos travel (a push the job did not make).
handler.BeforeStage = stage =>
{
if (stage == IntegrateStage.Photos) f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
return Task.CompletedTask;
};
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
// Not absorbed as a newer edit, which would reverse the user's choice on both sides: the details stop, the photos stay.
Assert.Equal(Loc.L("Errors.Copies.DetailsChanged"), failed.Error);
Assert.Equal(CopyState.Linked, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.Equal(3, RemoteHashes(remote).Count);
}
[Test]
public async Task ACancelledQueuedJobSetsThePairBack()
{
@@ -203,6 +203,34 @@ public sealed class SyncServiceCopyTests(TestContext context)
Assert.Equal(local.Id, upload.Single().Local!.Id);
}
[Test]
public async Task AKeptApartServerSequenceAnswering404OnceKeepsTheAnswerAndIsNeverLinkedByItself()
{
await using var f = await SyncFixture.CreateAsync(context);
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("2026-09-28 Canon", photos);
remote.FirstCapture = local.FirstCapture;
remote.CameraModel = local.CameraModel;
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
// Moved to the server's trash and restored: one refresh gets a 404, the next lists it again.
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Equal((CopyState.KeptApart, 1), ((await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits));
nas.Sequences[remote.Id] = remote;
await f.Sync.RefreshAsync(nas, new SyncPolicy { Linking = CopyLinking.WhenIdentical }, f.Ct);
// Keep separate is remembered (owner Q1): not asked again, and not linked although the photos are identical.
var after = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
Assert.Equal((pair.Id, CopyState.KeptApart, 0), (after.Id, after.State, after.RemoteGoneHits));
Assert.Null(await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct));
}
[Test]
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
{
@@ -292,6 +292,108 @@ public sealed class SyncTransferCopyTests(TestContext context)
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
}
[Test]
public async Task DownloadingAgainIntoTheOwnLocalCopyOfAPairAskedAgainKeepsItsDeletionsAndDetails()
{
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);
// While linked: one photo deleted here (the server keeps it, owner Q6) and the title edited; then unlinked and
// asked about again (Ask again, or a Keep apart undone).
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.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
// Download originals of the server sequence: it refills its own local copy, as a linked 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 photo deleted here stays deleted, and the title is not overwritten by the server's.
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
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("Mine", (await f.Db.Sequences.GetAsync(local, f.Ct))!.Title);
Assert.Equal("Comet", remote.Title);
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
}
[Test]
public async Task AnUploadOfASequenceAskedAboutAgainMakesANewServerSequenceAndLeavesTheOtherAlone()
{
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, then asked about again: the pair is a Candidate and nothing links the two.
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.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
// Renamed on the server (the web, another desktop); a new photo here.
var server = f.Remote.Sequences[first];
server.Title = "Comet NAS";
server.SettingsVersion++;
server.UpdatedAt = DateTimeOffset.UtcNow;
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 other is not joined through the key, linked unasked or overwritten: a new server sequence holds every photo.
Assert.Equal("Comet NAS", server.Title);
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
Assert.Equal(CopyState.Candidate, (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 AnUploadThatJoinsAServerSequenceItKnowsAlreadyComparesItsDetailsInsteadOfOverwritingThem()
{
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;
// The link and its pair were forgotten (a sweep of 404s: the server served another archive for a while); the
// server sequence is listed again, as an observation.
var observed = Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, first, f.Ct)) with { LocalId = null };
await f.Sync.Links.UpsertAsync(observed, f.Ct);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("DELETE FROM found_copies WHERE remote_id = $1", [first], f.Ct);
var server = f.Remote.Sequences[first];
server.Title = "Comet NAS";
server.SettingsVersion++;
server.UpdatedAt = DateTimeOffset.UtcNow;
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);
// Joined through this sequence's key, not made by this upload: the server's title is not overwritten unseen.
Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
Assert.Equal("Comet NAS", server.Title);
Assert.Equal("Comet", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
}
[Test]
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
{