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

- A merge leaves each second version out of Main as it files it (Copy
  stage keep-both and SameUnhashed versions, Verify stage versions), so a
  merge abandoned before its Details stage (details changed meanwhile, a
  stale stage, a cancel) no longer leaves both versions in Main for good,
  which a new plan could not undo (owner Q3).
- A merge plan whose kept sequence has tombstones hashes the other's
  unhashed frames matched by size and time, so content the kept sequence
  deleted is listed as a last copy; a verify that still finds such content
  drops the journal and fails as a stale plan instead of failing on every
  retry.
- Download originals uses a key of the job only when the holder of the
  server sequence's key is kept apart from it or linked elsewhere: a link
  a 404 forgot (pair Candidate) refills and re-links the local copy
  instead of duplicating every photo into a new sequence.
- A 404 for a server sequence no local copy is linked to deletes its
  Candidate and Kept apart pairs, so Upload all local sends the local
  sequence again instead of skipping the only copy as a suspected one
  (owner Q8).

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 12:21:57 +01:00
1 parent aad8ae46dd
commit c1c02d8ef7
10 files changed
+286 -16

No files matched your search

@@ -599,6 +599,94 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
}
[Test]
public async Task ASecondVersionCopiedInByAMergeAbandonedBeforeItsDetailsStaysOutOfMain()
{
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")]);
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);
// While the photos are copied the user tags the kept one: its details moved, so the Details stage abandons the merge.
handler.BeforeStage = stage => stage == MergeStage.Details ? fx.Db.Sequences.SetTagsAsync(keep.Id, ["edited"], Ct) : Task.CompletedTask;
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.SequenceEqual([(PhotoAction.FetchVersion, Sha(5, 30_250))], plan.Photos.Select(p => (p.Action, p.Sha256!)));
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.DetailsChanged"), failed.Error);
// The version copied in is already left out of Main.
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(4, 30_250), Sha(5, 30_250));
// Planned again (the kept one holds both versions now) and merged: still one photo in Main at that instant.
handler.BeforeStage = null;
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);
job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(4, 30_250), Sha(5, 30_250));
}
[Test]
public async Task AnUnhashedPhotoMatchedBySizeAndTimeWhoseContentTheKeptOneDeletedIsALastCopy()
{
var fx = await FixtureAsync();
// A whole-second camera shooting a burst of one size: the other holds two photos at one second, not hashed; the kept
// one holds one of them, hashed, and deleted the other.
var (deleted, kept) = EqualSizeSeeds(0);
var keep = await SequenceAsync(fx, "keep", [(kept, 0, "IMG_0002.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(deleted, 0, "IMG_0001.JPG"), (kept, 0, "IMG_0002.JPG")]);
await fx.Db.FrameRemovals.SyncSequenceAsync(keep.Id, [new FrameRemoval(keep.Id, Sha(deleted, 0), null, RemovalReason.Deleted, DateTimeOffset.UtcNow)], Ct);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [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);
// Compared by content: the deleted photo is a last copy to confirm, nothing to copy.
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);
Assert.SequenceEqual([(CopySide.Other, Sha(deleted, 0))], plan.LastCopies.Select(l => (l.Side, l.Key)));
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(kept, 0)]));
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
}
[Test]
public async Task APhotoTheKeptOneDeletesAfterThePlanMakesTheVerifyAskForANewPlan()
{
var fx = await FixtureAsync();
var (deleted, kept) = EqualSizeSeeds(0);
var keep = await SequenceAsync(fx, "keep", [(kept, 0, "IMG_0002.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(deleted, 0, "IMG_0001.JPG"), (kept, 0, "IMG_0002.JPG")]);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [drop.Id], Ct);
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.Union), NoContext, Ct);
Assert.Empty(plan.LastCopies);
// Once planned, the kept one's tombstone for the other photo arrives (a sync of a deletion made elsewhere).
handler.BeforeStage = stage => stage == MergeStage.Verify
? fx.Db.FrameRemovals.SyncSequenceAsync(keep.Id, [new FrameRemoval(keep.Id, Sha(deleted, 0), null, RemovalReason.Deleted, DateTimeOffset.UtcNow)], Ct)
: Task.CompletedTask;
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
// Not a verify that fails on every retry: the journal goes, and the new plan lists the photo as a last copy.
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)));
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.SequenceEqual([(CopySide.Other, Sha(deleted, 0))], plan.LastCopies.Select(l => (l.Side, l.Key)));
}
/// <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)
{
@@ -275,6 +275,34 @@ public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(
Assert.Equal(1, (await store.GetAsync(row.Id, Ct))!.RemoteGoneHits);
}
[Test]
public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsUnlinkedMatches()
{
var (db, _, s) = await SetupAsync(4);
var store = new FoundCopyStore(db);
var remote = Guid.CreateVersion7();
var candidate = await store.UpsertFoundAsync(Remote(s[0].Id, remote), Ct);
var apart = await store.UpsertFoundAsync(Remote(s[1].Id, remote), Ct);
Assert.True(await store.SetStateAsync(apart.Id, CopyState.Candidate, CopyState.KeptApart, Answer(), Ct));
var linked = await store.UpsertFoundAsync(Remote(s[2].Id, remote), Ct);
Assert.True(await store.SetStateAsync(linked.Id, CopyState.Candidate, CopyState.Linked, Answer(), Ct));
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);
// Its matches nobody linked are gone, so Upload all local reads their local sequences as local only again.
Assert.Null(await store.GetAsync(candidate.Id, Ct));
Assert.Null(await store.GetAsync(apart.Id, Ct));
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>());
Assert.Empty(skipped);
Assert.Count(2, upload);
}
[Test]
public async Task MoveToKeptMovesKeysLinksAndPairsAndIsIdempotent()
{
@@ -177,6 +177,32 @@ public sealed class SyncServiceCopyTests(TestContext context)
Assert.True(pair.NeedsAttention);
}
[Test]
public async Task AMatchWhoseServerSequenceIsDeletedIsGoneAfterTheRefreshAndUploadAllSendsTheLocalOne()
{
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.Equal((CopyState.Candidate, local.Id), (pair.State, pair.LocalId));
Assert.Null((await f.Sync.Links.GetAsync(nas.Server, remote.Id, f.Ct))!.LocalId);
// Deleted on the server: no longer listed, and a 404 when asked for.
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Null(await f.Sync.Copies.GetAsync(pair.Id, f.Ct));
var entries = (await f.Sync.ListAsync(nas.Server, f.Ct)).Where(e => e.Local?.Id == local.Id).ToList();
var (upload, skipped) = UploadAllRule.Select(entries, await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(skipped);
Assert.Equal(local.Id, upload.Single().Local!.Id);
}
[Test]
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
{
@@ -263,6 +263,35 @@ public sealed class SyncTransferCopyTests(TestContext context)
Assert.True((await LocalHashesAsync(f, copy)).SetEquals(photos.Select(Sha)));
}
[Test]
public async Task DownloadingAgainAServerSequenceWhoseLinkA404ForgotRefillsAndLinksItsOwnLocalCopy()
{
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);
// A refresh's 404 forgot the link (the archive was briefly offline); listed again, the pair is asked about again.
await f.Sync.Links.DeleteAsync(f.Server, remote.Id, 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, pair.State, CopyState.Candidate, null, f.Ct));
// Download originals of the server-only sequence: it goes back into its own local copy, linked again.
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);
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
Assert.True((await LocalHashesAsync(f, local)).SetEquals(photos.Select(Sha)));
var keys = await f.Db.Sequences.ListSessionKeysAsync(f.Archive.Archive.Id, SyncService.SessionKey(remote.Id) + "%", f.Ct);
Assert.True(keys.All(k => k.SequenceId == local), "no second local sequence holds a key of the server sequence");
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
}
[Test]
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
{