fix(copies): address the owner review 6 findings

The review of the found-copies work showed pairs that could stick, jobs that
could act on a pair the user had answered otherwise, and detection gaps:

- forgetting a link on an address-keyed server deletes the pair and Candidate
  rows of that remote and resets the probe, so the sequence is found again
  when it is back; a Linked/Integrated row with no link is asked again
- 404s count only on id-keyed servers, at most once per recheck interval
- probes store the server's newest update time (copy_probes.server_newest,
  migration 0012) instead of comparing with this PC's clock; the lookup
  sample carries hashed photos by size and capture time too, for servers
  that have not hashed their copy
- the older-server gate no longer re-compares unchanged manifests
- a failed Integrate keeps its job id so a retry resumes only an untouched
  pair; cancel and stale plans release the pair (ReleaseAsync)
- automatic photo transfers never create or retarget a sequence
- a first upload files photos the server holds elsewhere into the new
  sequence
- Unlink re-compares before keeping apart; Trash here names only true last
  copies; Drop... trashes one version on both sides after re-checking the
  other
- a merge keeping the pair's other sequence swaps the dialog's columns and
  re-keys Different choices; Upload all reads every pair

Each fix has a regression test where it makes sense.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 13:12:00 +01:00
1 parent 96b5b4078b
commit fe752a0a21
33 files changed
+957 -123

No files matched your search

@@ -3,6 +3,7 @@ using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Sync;
using Chronos.Protocol;
using Chronos.Testing;
@@ -168,14 +169,16 @@ public sealed class CopyEngineTests(TestContext context)
var (gone, restored) = (remote.Frames[1], remote.Frames[2]);
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([gone.Id, restored.Id], null, false), f.Ct);
var plan = await engine.PlanTrashHereAsync(pair.Id, [Sha(photos[1]), Sha(photos[2])], f.Ct);
var (plan, lasts) = await engine.PlanTrashHereAsync(pair.Id, [Sha(photos[1]), Sha(photos[2])], f.Ct);
Assert.Equal(2, plan.Frames.Count);
// No other sequence of this PC holds them: the trash takes their last copies, and the confirmation says so.
Assert.SequenceEqual(new[] { Sha(photos[1]), Sha(photos[2]) }.Order(StringComparer.Ordinal), lasts.Select(l => l.Key).Order(StringComparer.Ordinal));
// Restored on the server after the dry run: nothing moves, all or nothing.
remote.AddFrame(photos[2], restored.FileName);
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.TrashHereAsync(pair.Id, plan, f.Remote, f.Ct));
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
var again = await engine.PlanTrashHereAsync(pair.Id, [Sha(photos[1])], f.Ct);
var again = (await engine.PlanTrashHereAsync(pair.Id, [Sha(photos[1])], f.Ct)).Plan;
Assert.Equal(1, await engine.TrashHereAsync(pair.Id, again, f.Remote, f.Ct));
var left = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.SequenceEqual(new[] { Sha(photos[0]), Sha(photos[2]) }.Order(StringComparer.Ordinal), left.Select(fr => fr.Sha256!).Order(StringComparer.Ordinal));
@@ -210,6 +213,104 @@ public sealed class CopyEngineTests(TestContext context)
Assert.Equal(Sha(photos[2]), f.Remote.Trashed.Single().Frame.Sha256);
}
[Test]
public async Task TrashHereNamesNoLastCopyForAPhotoAnotherSequenceHolds()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
await f.LocalAsync("Comet backup", [photos[1]]);
var remote = f.Remote.Add("Comet NAS", photos);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([remote.Frames[1].Id], null, false), f.Ct);
var plan = await engine.PlanTrashHereAsync(pair.Id, [Sha(photos[1])], f.Ct);
Assert.Equal((1, 0), (plan.Plan.Frames.Count, plan.LastCopies.Count));
}
[Test]
public async Task UnlinkKeepsApartAgainstWhatTheTwoHoldNowNotAtTheLastComparison()
{
await using var f = await FixtureAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet NAS", [photos[0]]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.Sync.Copies.EnsureLinkedAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
// The server copy grows to hold every photo: the pair's score follows at the next comparison.
remote.AddFrame(photos[1], "IMG_0002.JPG");
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
var pair = (await f.Sync.Copies.FindRemoteAsync(local.Id, f.Server, remote.Id, f.Ct))!;
Assert.Equal((2, 0, 0), (pair.Score.Shared, pair.Score.OnlyHere, pair.Score.OnlyThere));
using var engine = Engine(f);
await engine.UnlinkAsync(pair.Id, f.Remote, f.Ct);
await f.RefreshAsync(new SyncPolicy { Linking = CopyLinking.AskAlways });
// Answered against two identical copies: nothing grew since, so the pair is not asked about again.
var kept = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((CopyState.KeptApart, 2), (kept.State, kept.AnsweredShared ?? -1));
}
[Test]
public async Task DropVersionTrashesOneVersionOnBothSidesAndIsRefusedOnceTheOtherIsGone()
{
await using var f = await FixtureAsync(context);
var (local, remote, a, b) = await VersionsAsync(f);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
var review = await engine.CompareAsync(pair.Id, f.Remote, f.Ct);
Assert.Count(2, review.Photos.Of(PhotoClass.Versions));
var plan = await engine.PlanDropVersionAsync(pair.Id, Sha(a), f.Remote, f.Ct);
Assert.Equal((Sha(b), 2), (plan.PartnerKey, plan.Photos));
Assert.Equal(2, await engine.DropVersionAsync(plan, f.Remote, f.Ct));
var left = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.SequenceEqual(new[] { Sha(b) }, left.Select(fr => fr.Sha256!).Where(s => s == Sha(a) || s == Sha(b)));
Assert.False(remote.Frames.Any(fr => fr.Sha256 == Sha(a)));
Assert.True(remote.Frames.Any(fr => fr.Sha256 == Sha(b)));
Assert.Equal(Sha(a), f.Remote.Trashed.Single().Frame.Sha256);
}
[Test]
public async Task DropVersionIsRefusedWhenTheOtherVersionLeftOneSide()
{
await using var f = await FixtureAsync(context);
var (local, remote, a, b) = await VersionsAsync(f);
var pair = await PairAsync(f, local.Id, remote.Id);
using var engine = Engine(f);
var plan = await engine.PlanDropVersionAsync(pair.Id, Sha(a), f.Remote, f.Ct);
// The other version leaves the server after the dry run: dropping this one would leave the server without the photo.
await f.Remote.DeleteFramesAsync(remote.Id, new FrameDeleteRequest([remote.Frames.Single(fr => fr.Sha256 == Sha(b)).Id], null, false), f.Ct);
await Assert.ThrowsAsync<StaleCopyPlanException>(() => engine.DropVersionAsync(plan, f.Remote, f.Ct));
Assert.True(remote.Frames.Any(fr => fr.Sha256 == Sha(a)));
Assert.Count(1, f.Remote.Trashed);
Assert.True((await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Any(fr => fr.Sha256 == Sha(a)));
}
/// <summary>
/// A pair holding one photo in two versions (a Union keep-both): two files of one sub-second capture time, on both sides,
/// besides one plain photo.
/// </summary>
private static async Task<(Sequence Local, FakeSequence Remote, byte[] A, byte[] B)> VersionsAsync(SyncFixture f)
{
var plainAt = ArchiveFixture.Start;
var at = ArchiveFixture.Start.AddSeconds(5).AddMilliseconds(250);
var (plain, a, b) = (Photos.Jpeg(plainAt, 7001), Photos.Jpeg(at, 7002), Photos.Jpeg(at, 7003));
var local = await f.LocalAsync("Comet", [plain, a, b], capturedAt: [plainAt, at, at]);
var remote = f.Remote.Add("Comet NAS", []);
remote.AddFrame(plain, "IMG_0001.JPG", plainAt);
remote.AddFrame(a, "IMG_0002.JPG", at);
remote.AddFrame(b, "IMG_0003.JPG", at);
return (local, remote, a, b);
}
[Test]
public async Task TrashThereIsRefusedForAPhotoThisPcStillHolds()
{
@@ -170,6 +170,43 @@ public sealed class CopyFinderServerTests(TestContext context)
Assert.Equal(CopyEvidence.SizeAndTime, (await PairsAsync(f)).Single().Evidence);
}
[Test]
public async Task AServerCopyNotHashedYetIsFoundByTheSizeAndTimeOfHashedPhotos()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
// Adopted on the server and not verified there: it lists no hash, so only size and capture time can find it.
var remote = f.Remote.Add("Comet", photos);
remote.Unhashed = true;
await f.RefreshAsync();
var pair = (await PairsAsync(f)).Single();
Assert.Equal((local.Id, remote.Id), (pair.LocalId, pair.RemoteId!.Value));
Assert.Equal(CopyState.Candidate, pair.State);
}
[Test]
public async Task ASequenceAddedOnAServerWhoseClockIsBehindIsStillLookedFor()
{
await using var f = await LookupAsync(context);
var photos = f.NewPhotos(3);
await f.LocalAsync("Comet", photos);
var other = f.Remote.Add("Harbour", f.NewPhotos(2));
other.UpdatedAt = DateTimeOffset.UtcNow.AddHours(-3);
await f.RefreshAsync();
Assert.Count(1, f.Remote.Lookups);
// Added after the probe by a server whose clock is three hours behind this PC's: later than the newest it showed.
var remote = f.Remote.Add("Comet", photos);
remote.UpdatedAt = other.UpdatedAt.AddMinutes(1);
await f.RefreshAsync();
Assert.Count(2, f.Remote.Lookups);
Assert.Equal(remote.Id, (await PairsAsync(f)).Single().RemoteId!.Value);
}
[Test]
public async Task OneRefreshComparesAtMostFiftyPairs()
{
@@ -488,6 +488,66 @@ public sealed class IntegrateTests(TestContext context)
Assert.True((await Planner(f).PlanAsync(f.Remote, after, plan.Choices, PlanContext(), f.Ct)).CanApply);
}
[Test]
public async Task ARetryAfterThePairWasAnsweredOtherwiseRefusesAndTouchesNothing()
{
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) = await ScenarioAsync(f);
handler.BeforeStage = stage => stage == IntegrateStage.Photos ? throw new IOException("crash before Photos") : Task.CompletedTask;
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);
await f.Archive.WaitForAsync(job.Id, JobState.Failed);
// The failed job still names the pair, so a retry may resume it while nobody answered otherwise.
var held = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((CopyState.Linked, (Guid?)job.Id), (held.State, held.JobId));
// Kept apart meanwhile: the retry refuses, sends nothing and forgets its journal.
Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, null, CopyState.KeptApart, new CopyAnswer(pair.Fingerprint, null, null, false, DateTimeOffset.UtcNow), f.Ct));
handler.BeforeStage = null;
var uploads = f.Remote.IntoUploads;
await engine.ResumeAsync(job.Id, f.Ct);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Copies.StalePlan"), failed.Error);
Assert.Equal(uploads, f.Remote.IntoUploads);
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct));
Assert.Equal(CopyState.KeptApart, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
Assert.False(File.Exists(IntegrateJournal.PathFor(f.Archive.Paths, job.Id)));
}
[Test]
public async Task ACancelAfterTheLinkLeavesThePairLinkedAndFreeOfTheJob()
{
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) = await ScenarioAsync(f);
var running = new TaskCompletionSource<Guid>(TaskCreationOptions.RunContinuationsAsynchronously);
handler.BeforeStage = async stage =>
{
if (stage == IntegrateStage.Photos) await engine.CancelAsync(await running.Task, CancellationToken.None);
};
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);
running.SetResult(job.Id);
await f.Archive.WaitForAsync(job.Id, JobState.Cancelled);
var until = DateTime.UtcNow.AddSeconds(10);
var after = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
while ((after.State != CopyState.Linked || after.JobId is not null) && DateTime.UtcNow < until)
{
await Task.Delay(20, f.Ct);
after = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
}
// The link the job made stays (both sides are joined); the pair no longer waits for the cancelled job.
Assert.Equal((CopyState.Linked, (Guid?)null), (after.State, after.JobId));
Assert.Equal(local.Id, (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))?.LocalId);
}
[Test]
public async Task ProjectsAreCopiedAcrossBothWaysUnderFreeNames()
{