feat(copies): pure comparison, detection rules, details payload and comparison sides

Detection, Integrate and Merge need one comparison of two copies of a time-lapse, so
this adds it: CopyComparer classifies every photo (same, converted, same unhashed,
deleted here/there, differs, two versions, only here/there) with strict Differs and
Versions rules so whole-second capture times and bursts never pair, unusable frames
held as nothing and marked for repair, and the score of design 3.2.
CopyRules ports 1.1's same-originals gate exactly for "Link when half shared" and
holds the Decide table, ask-again thresholds, fingerprints, hints and the probe
sample. CopyPayload compares details in portable form (same photo at another index is
no line) and merges the chosen sides into one payload that must parse as a project.
CopySides reads both sides from the index and a server and answers the last-copy
check across every archive. SyncTombstones gains FromDtos for local pairs.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 19:58:07 +01:00
1 parent 283d04d9cd
commit f6f81e2c37
9 files changed
+1465

No files matched your search

@@ -0,0 +1,139 @@
using System.Globalization;
using Chronos.Core.Project;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>The details of two copies line by line and the one payload both get (owner review 6, Q4; design §4.3, §5e).</summary>
[Category("sync")]
public sealed class CopyPayloadTests
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0, 250);
private static string Sha(int n) => Convert.ToHexStringLower(BitConverter.GetBytes((long)n)).PadLeft(64, 'b');
private static FramePhoto Photo(int n) => new(Sha(n), 1000 + n, Start.AddSeconds(5 * n));
/// <summary>Photos 0–19 at indices 0–19.</summary>
private static readonly FramePhotos Here = new(Enumerable.Range(0, 20).Select(i => (i, Photo(i))));
/// <summary>Two photos more before them (100, 101): photo n at index n + 2.</summary>
private static readonly FramePhotos There = new(new[] { (0, Photo(100)), (1, Photo(101)) }.Concat(Enumerable.Range(0, 20).Select(i => (i + 2, Photo(i)))));
private static SyncPayload Payload(ProjectSettings settings, string? title = "Harbour", params string[] tags) =>
new(title, tags, 3, null, settings.ToJson());
private static IReadOnlyDictionary<string, CopySide> Choose(IEnumerable<DetailLine> lines, CopySide side, params (string Path, CopySide Side)[] except)
{
var choices = lines.ToDictionary(l => l.Path, _ => side, StringComparer.Ordinal);
foreach (var (path, chosen) in except) choices[path] = chosen;
return choices;
}
[Test]
public void TheSameExclusionAtAnotherIndexIsNoLine()
{
var here = Payload(new ProjectSettings { ExcludedFrames = [10], HeroFrame = 3 });
var there = Payload(new ProjectSettings { ExcludedFrames = [12], HeroFrame = 5 });
Assert.Empty(CopyPayload.Lines(here, Here, there, There));
// Another photo excluded there: one line, the frame positions.
var other = Payload(new ProjectSettings { ExcludedFrames = [11], HeroFrame = 5 });
var lines = CopyPayload.Lines(here, Here, other, There);
var line = Assert.Contains(lines, l => l.Path == CopyPayload.PendingFramesPath);
Assert.Count(1, lines);
Assert.Contains(Sha(10), line.Here);
Assert.Contains(Sha(9), line.There);
}
[Test]
public void FramePositionsCollapseIntoOneLine()
{
var here = Payload(new ProjectSettings { ExcludedFrames = [1, 2], HeroFrame = 3 }, "Harbour", "dusk");
var there = Payload(new ProjectSettings { ExcludedFrames = [9], HeroFrame = 7, Stack = new StackSettings { Length = 15 } }, "Harbour at dusk", "dusk", "sea");
var lines = CopyPayload.Lines(here, Here, there, There);
Assert.Count(4, lines);
Assert.True(lines.Select(l => l.Path).ToHashSet().SetEquals(["sequence.title", "sequence.tags", CopyPayload.PendingFramesPath, "stack.length"]));
var stack = lines.Single(l => l.Path == "stack.length");
Assert.Equal(("9", "15"), (stack.Here, stack.There));
}
[Test]
public void MergeTakesTheChosenSideOfEachLine()
{
var here = Payload(new ProjectSettings { ExcludedFrames = [1], Stack = new StackSettings { Length = 9 }, Export = new ExportSettings { NameTemplate = "{title}" } },
"Harbour", "dusk");
var there = Payload(new ProjectSettings { ExcludedFrames = [9], Stack = new StackSettings { Length = 15 }, Export = new ExportSettings { NameTemplate = "{date}" } },
"Harbour at dusk", "dusk", "sea");
var lines = CopyPayload.Lines(here, Here, there, There);
var choices = Choose(lines, CopySide.ThisPc, ("sequence.title", CopySide.Other), ("stack.length", CopySide.Other), (CopyPayload.PendingFramesPath, CopySide.Other));
var merged = CopyPayload.Merge(CopyPayload.Portable(here, Here), CopyPayload.Portable(there, There), choices, lines);
Assert.Equal("Harbour at dusk", merged.Title);
Assert.SequenceEqual(["dusk"], merged.Tags);
var settings = ProjectSettings.FromJson(merged.SettingsJson!);
Assert.Equal((15, "{title}"), (settings.Stack.Length, settings.Export.NameTemplate));
// Portable: placed on this PC's frames, the exclusion is there's photo 7 (index 9 there).
Assert.SequenceEqual([7], ProjectSettings.FromJson(ProjectContent.Place(merged.SettingsJson!, Here)).ExcludedFrames);
Assert.SequenceEqual([9], ProjectSettings.FromJson(ProjectContent.Place(merged.SettingsJson!, There)).ExcludedFrames);
// Every line this PC's: the merged payload is this PC's.
var mine = CopyPayload.Merge(CopyPayload.Portable(here, Here), CopyPayload.Portable(there, There), Choose(lines, CopySide.ThisPc), lines);
Assert.Empty(CopyPayload.Lines(mine, new FramePhotos([]), CopyPayload.Portable(here, Here), new FramePhotos([])));
}
[Test]
public void AnUnchosenLineThrows()
{
var here = Payload(new ProjectSettings(), "Harbour");
var there = Payload(new ProjectSettings { Stack = new StackSettings { Length = 15 } }, "Harbour at dusk");
var lines = CopyPayload.Lines(here, Here, there, There);
var choices = new Dictionary<string, CopySide> { ["sequence.title"] = CopySide.Other };
Assert.Throws<ArgumentException>(() => CopyPayload.Merge(here, there, choices, lines));
}
[Test]
public void AMergeThatIsNoProjectIsRefused()
{
var here = Payload(new ProjectSettings());
var there = new SyncPayload("Harbour", [], 3, null, "not a project");
var lines = CopyPayload.Lines(here, Here, there, There);
Assert.Equal("settings", Assert.Contains(lines, l => l.Path == "settings").Path);
Assert.Throws<InvalidDataException>(() => CopyPayload.Merge(here, there, Choose(lines, CopySide.Other), lines));
var kept = CopyPayload.Merge(here, there, Choose(lines, CopySide.ThisPc), lines);
Assert.Equal(9, ProjectSettings.FromJson(kept.SettingsJson!).Stack.Length);
}
[Test]
public void ExcludeVersionsExcludesByPhoto()
{
var portable = CopyPayload.Portable(Payload(new ProjectSettings { HeroFrame = 4 }), Here);
var unhashed = string.Create(CultureInfo.InvariantCulture, $"u:777:{Start.AddSeconds(500).Ticks / TimeSpan.TicksPerMillisecond}");
var excluded = CopyPayload.ExcludeVersions(portable, [Sha(99), Sha(4), unhashed]);
var pending = ProjectSettings.FromJson(excluded.SettingsJson!).PendingFrames!;
Assert.True(pending.Single(p => p.Sha256 == Sha(99)).Excluded);
// The hero's photo keeps its hero flag and is excluded too.
var hero = pending.Single(p => p.Sha256 == Sha(4));
Assert.True(hero.Excluded && hero.Hero);
var byTime = pending.Single(p => string.IsNullOrEmpty(p.Sha256));
Assert.Equal((777L, Start.AddSeconds(500)), (byTime.Size, byTime.CapturedAt!.Value));
// Placed on frames holding the version, it is excluded there.
var frames = new FramePhotos([(0, Photo(1)), (1, new FramePhoto(Sha(99), 5, Start)), (2, Photo(4))]);
var placed = ProjectSettings.FromJson(ProjectContent.Place(excluded.SettingsJson!, frames));
Assert.SequenceEqual([1, 2], placed.ExcludedFrames.Order());
Assert.Equal(2, placed.HeroFrame);
Assert.Same(portable, CopyPayload.ExcludeVersions(portable, []));
}
[Test]
public void MovedNamesThePathsThatChanged()
{
var before = CopyPayload.Portable(Payload(new ProjectSettings { ExcludedFrames = [1] }), Here);
var after = CopyPayload.Portable(Payload(new ProjectSettings { ExcludedFrames = [2], Stack = new StackSettings { Length = 3 } }, "Pier"), Here);
Assert.True(CopyPayload.Moved(before, after).SetEquals(["sequence.title", CopyPayload.PendingFramesPath, "stack.length"]));
Assert.Empty(CopyPayload.Moved(before, before));
}
}
@@ -0,0 +1,180 @@
using Chronos.Core.Project;
using Chronos.Data.Copies;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>The detection rules (owner review 6, Q1; design §3.1, §3.2, §3.6): pairs, the Link matches setting, 1.1's gate, asking again.</summary>
[Category("sync")]
public sealed class CopyRulesTests
{
private static readonly DateTime First = new(2026, 9, 28, 18, 0, 0, 400);
private static CopyScore Identical(int shared = 10, int unhashed = 0) =>
CopyScore.None with { Shared = shared, SharedUnhashed = unhashed, LocalPhotos = shared + unhashed, OtherPhotos = shared + unhashed, Containment = 1000, Overlap = 1000 };
private static CopyScore Partial(int shared, int onlyHere) =>
CopyScore.None with { Shared = shared, OnlyHere = onlyHere, LocalPhotos = shared + onlyHere, OtherPhotos = shared, Containment = 1000 };
/// <summary>1.1's gate passing: both unlinked, same second, same camera, half of 10 shared.</summary>
private static SameOriginalsInput Gate(int shared = 5) => new(true, First, First.AddMilliseconds(300), "EOS R5", "eos r5", 10, 10, shared);
private static readonly SameOriginalsInput Closed = new(false, null, null, null, null, 0, 0, 0);
private static FoundCopy KeptApart(int answeredShared, string? fingerprint = null) => new()
{
Id = Guid.NewGuid(),
Kind = CopyKind.LocalServer,
LocalId = Guid.NewGuid(),
Server = "https://nas.test:8443",
RemoteId = Guid.NewGuid(),
Evidence = CopyEvidence.Hashes,
State = CopyState.KeptApart,
Score = Partial(answeredShared, 5),
Fingerprint = "f",
AnsweredShared = answeredShared,
AnsweredFingerprint = fingerprint,
};
[Test]
public void APairNeedsALinkASessionKeyOrEnoughShared()
{
Assert.True(CopyRules.IsCopy(CopyEvidence.Link, CopyScore.None));
Assert.True(CopyRules.IsCopy(CopyEvidence.SessionKey, CopyScore.None));
Assert.False(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None));
Assert.True(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { Shared = 1, Containment = 100 }));
Assert.False(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { Shared = 1, Containment = 99 }));
// Tombstoned content is evidence too.
Assert.True(CopyRules.IsCopy(CopyEvidence.Hashes, CopyScore.None with { SharedRemoved = 3, Containment = 300 }));
Assert.True(CopyRules.IsCopy(CopyEvidence.SizeAndTime, CopyScore.None with { SharedUnhashed = 2, Containment = 1000 }));
}
[Test]
public void AskAlwaysNeverLinks()
{
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, Identical(), Gate()));
Assert.Equal(CopyDecision.None, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, CopyScore.None, Gate()));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.AskAlways, CopyKind.LocalServer, CopyScore.None, Closed, CopyEvidence.SessionKey));
}
[Test]
public void WhenIdenticalLinksOnlyTheSamePhotosKnownByHash()
{
Assert.Equal(CopyDecision.Link, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical(), Closed));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Partial(10, 1), Gate()));
// A size and time identity always asks.
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical(8, 2), Closed));
// Photos deleted on one side only are no identity.
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { DeletedThere = 1, SharedRemoved = 1 }, Closed));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { DeletedHere = 1, SharedRemoved = 1 }, Closed));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenIdentical, CopyKind.LocalServer, Identical() with { Differs = 1 }, Closed));
}
[Test]
public void IdenticalNeedsNothingDeletedOnOneSide()
{
Assert.True(Identical().Identical);
Assert.False((Identical() with { DeletedHere = 1 }).Identical);
Assert.False((Identical() with { DeletedThere = 1 }).Identical);
Assert.False(CopyScore.None.Identical);
}
[Test]
public void WhenHalfSharedKeeps11sGates()
{
Assert.Equal(CopyDecision.Link, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate()));
// A different first-capture second, or another camera: asked.
var otherSecond = Gate() with { RemoteFirst = First.AddSeconds(1) };
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), otherSecond));
var otherCamera = Gate() with { RemoteCamera = "EOS R6" };
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), otherCamera));
// Fewer than half of the smaller side, nothing hashed here, or a side linked already: asked.
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(4, 6), Gate(4)));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate() with { LocalHashed = 0 }));
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(CopyLinking.WhenHalfShared, CopyKind.LocalServer, Partial(5, 5), Gate() with { BothUnlinked = false }));
}
[Test]
public void SameOriginalsIsThe11Rule()
{
Assert.True(CopyRules.SameOriginals(Gate()));
// Half of the smaller side: 3 of a 6-frame server sequence is enough against 10 local hashes.
Assert.True(CopyRules.SameOriginals(Gate(3) with { RemoteFrames = 6 }));
Assert.False(CopyRules.SameOriginals(Gate(0) with { RemoteFrames = 0 }));
Assert.False(CopyRules.SameOriginals(Gate() with { LocalFirst = null }));
// Both without a camera model count as equal, as in 1.1.
Assert.True(CopyRules.SameOriginals(Gate() with { LocalCamera = null, RemoteCamera = null }));
}
[Test]
public void ALocalPairIsNeverLinkedByItself()
{
foreach (var linking in Enum.GetValues<CopyLinking>())
Assert.Equal(CopyDecision.Ask, CopyRules.Decide(linking, CopyKind.LocalLocal, Identical(), Gate()));
}
[Test]
public void AKeptApartPairAsksAgainOnlyWhenItGrewALotOrBecameIdentical()
{
// Ten more shared photos at least, and a quarter of the answered count.
Assert.False(CopyRules.AsksAgain(KeptApart(20), Partial(29, 5)));
Assert.True(CopyRules.AsksAgain(KeptApart(20), Partial(30, 5)));
Assert.False(CopyRules.AsksAgain(KeptApart(100), Partial(124, 5)));
Assert.True(CopyRules.AsksAgain(KeptApart(100), Partial(125, 5)));
// Identical now, and not when answered.
Assert.True(CopyRules.AsksAgain(KeptApart(20, CopyRules.Fingerprint(Partial(20, 5), 1, 1)), Identical(20)));
// Kept apart while identical: an identity is no news.
Assert.False(CopyRules.AsksAgain(KeptApart(20, CopyRules.Fingerprint(Identical(20), 1, 1)), Identical(20)));
// Only kept-apart pairs ask again.
Assert.False(CopyRules.AsksAgain(KeptApart(20) with { State = CopyState.Linked }, Partial(90, 5)));
}
[Test]
public void FingerprintsFollowTheScoreAndTheVersions()
{
var a = CopyRules.Fingerprint(Partial(5, 5), 3, 4);
Assert.Equal(a, CopyRules.Fingerprint(Partial(5, 5), 3, 4));
Assert.NotEqual(a, CopyRules.Fingerprint(Partial(5, 5), 3, 5));
Assert.NotEqual(a, CopyRules.Fingerprint(Partial(6, 5), 3, 4));
var plan = CopyRules.PlanFingerprint(["send a", "fetch b"]);
Assert.Equal(64, plan.Length);
Assert.Equal(plan, CopyRules.PlanFingerprint(["send a", "fetch b"]));
Assert.NotEqual(plan, CopyRules.PlanFingerprint(["fetch b", "send a"]));
Assert.Equal("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", CopyRules.PlanFingerprint([]));
}
[Test]
public void AProbeIsEvenlySpacedWithTheFirstAndTheLast()
{
var photos = Enumerable.Range(0, 1000).Select(i => new FramePhoto(i.ToString("x64"), i, null)).ToList();
var probe = CopyRules.Probe(photos);
Assert.Count(64, probe);
Assert.Same(photos[0], probe[0]);
Assert.Same(photos[^1], probe[^1]);
Assert.Count(64, probe.Distinct());
var gaps = probe.Zip(probe.Skip(1), (a, b) => b.Size - a.Size).ToList();
Assert.InRange(gaps.Min(), 15, 16);
Assert.InRange(gaps.Max(), 15, 16);
Assert.Count(10, CopyRules.Probe(photos.Take(10).ToList()));
Assert.SequenceEqual([photos[0], photos[999]], CopyRules.Probe(photos, 2));
Assert.Empty(CopyRules.Probe([]));
}
[Test]
public void HintsScoreRangeCameraIntervalAndTitle()
{
var start = new DateTime(2026, 9, 28, 18, 0, 0);
var a = new CopyHintsInput(start, start.AddHours(2), "EOS R5", 5, "Harbour sunset");
Assert.Equal(100, CopyRules.Hints(a, a with { Camera = "eos r5", Title = "harbour" }));
// Half of the shorter range shared: 20.
Assert.Equal(20, CopyRules.Hints(a, new CopyHintsInput(start.AddHours(1), start.AddHours(3), null, null, null)));
Assert.Equal(25, CopyRules.Hints(a, new CopyHintsInput(null, null, "EOS R5", null, null)));
Assert.Equal(20, CopyRules.Hints(a, new CopyHintsInput(null, null, null, 5.4, null)));
Assert.Equal(0, CopyRules.Hints(a, new CopyHintsInput(null, null, null, 6, "Sun")));
// A null Last reads as First: a sequence with its first capture inside the other's range overlaps fully.
Assert.Equal(40, CopyRules.Hints(a, new CopyHintsInput(start.AddMinutes(30), null, null, null, null)));
Assert.Equal(0, CopyRules.Hints(a, new CopyHintsInput(start.AddHours(3), null, null, null, null)));
Assert.Equal(40, CopyRules.Hints(new CopyHintsInput(start, null, null, null, null), new CopyHintsInput(start, null, null, null, null)));
}
}
@@ -0,0 +1,130 @@
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Tests.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>The two sides of a comparison read from the index and from a server, and the last-copy check (owner review 6, #73; design §4.2).</summary>
[Category("sync")]
public abstract class CopySidesTests(TestContext context) : RepositoryTest(context)
{
private static string Sha(int n) => Convert.ToHexStringLower(BitConverter.GetBytes((long)n)).PadLeft(64, 'c');
private async Task<(Archive Archive, Sequence Sequence)> SequenceAsync(ChronosDatabase db, Archive? archive = null)
{
if (archive is null)
{
archive = TestData.Archive("A" + Guid.NewGuid().ToString("N")[..6]);
await db.Archives.UpsertAsync(archive, Ct);
}
var sequence = TestData.Sequence(archive.Id);
await db.Sequences.UpsertAsync(sequence, Ct);
return (archive, sequence);
}
private async Task<Frame> FrameAsync(ChronosDatabase db, Guid sequenceId, int index, string? sha, FrameFlags flags = FrameFlags.None)
{
var frame = TestData.Frame(sequenceId, index) with { Sha256 = sha, Flags = flags };
await db.Frames.InsertAsync(frame, Ct);
return frame;
}
[Test]
public async Task ALocalSideHoldsItsFramesTombstonesAndUnusableFlags()
{
var db = await OpenChronosAsync();
var (_, sequence) = await SequenceAsync(db);
var frames = new[]
{
await FrameAsync(db, sequence.Id, 0, Sha(0)),
await FrameAsync(db, sequence.Id, 1, Sha(1), FrameFlags.Missing),
await FrameAsync(db, sequence.Id, 2, Sha(2), FrameFlags.Corrupt | FrameFlags.Excluded),
await FrameAsync(db, sequence.Id, 3, null),
await FrameAsync(db, sequence.Id, 4, Sha(4), FrameFlags.Excluded),
};
await db.FrameRemovals.SyncSequenceAsync(sequence.Id,
[
new FrameRemoval(sequence.Id, Sha(8), null, RemovalReason.Deleted, TestData.Now),
new FrameRemoval(sequence.Id, Sha(9), Sha(4), RemovalReason.Replaced, TestData.Now.AddMinutes(1)),
], Ct);
var side = await new CopySides(db).LocalAsync(sequence.Id, Ct);
Assert.SequenceEqual(frames.Select(f => f.Id), side.Photos.Select(p => p.FrameId));
Assert.SequenceEqual([false, true, true, false, false], side.Photos.Select(p => p.Unusable));
Assert.Null(side.Photos[3].Sha256);
Assert.Equal((frames[0].FileName, frames[0].Size, frames[0].CapturedAt), (side.Photos[0].FileName, side.Photos[0].Size, side.Photos[0].CapturedAt));
Assert.SequenceEqual([(Sha(8), (string?)null, "deleted"), (Sha(9), Sha(4), "replaced")], side.Removed.Select(r => (r.Sha256, r.Replacement, r.Reason)));
// Compared with a copy holding every photo, the unusable frames are repaired and the converted one is the same photo.
var there = new CopySideInput([.. Enumerable.Range(0, 5).Select(i => new CopyPhotoInput(Guid.NewGuid(), i, frames[i].FileName,
i == 4 ? Sha(9) : Sha(i), frames[i].Size, frames[i].CapturedAt, false))], []);
var result = CopyComparer.Compare(side, there);
Assert.Equal((2, 1, 2), (result.Score.Shared, result.Score.SharedUnhashed, result.Score.OnlyThere));
Assert.True(result.Of(PhotoClass.OnlyThere).All(p => p.RepairsHere));
Assert.Equal(Sha(9), Assert.Contains(result.Photos, p => p.Class == PhotoClass.Converted).There!.Sha256);
}
[Test]
public async Task ARemoteSideTakesCaptureTimesFromTheFrameRows()
{
var db = await OpenChronosAsync();
using var remote = new FakeSyncRemote();
var at = new DateTime(2026, 9, 28, 18, 0, 0, 120);
var sequence = remote.Add("Harbour", []);
sequence.AddFrame([1, 2, 3], "IMG_0001.JPG", at);
sequence.AddFrame([4, 5, 6], "IMG_0002.JPG", at.AddSeconds(5));
sequence.Removed.Add(new RemovedPhotoDto(Sha(7), null, "deleted", TestData.Now));
var side = await new CopySides(db).RemoteAsync(remote, sequence.Id, Ct);
Assert.SequenceEqual(sequence.Frames.Select(f => (f.Id, f.FileName, f.Sha256, (long)f.Bytes.Length, f.CapturedAt)),
side.Photos.Select(p => (p.FrameId, p.FileName, p.Sha256!, p.Size, p.CapturedAt)));
Assert.True(side.Photos.All(p => !p.Unusable));
Assert.SequenceEqual([Sha(7)], side.Removed.Select(r => r.Sha256));
// A server that never hashed its originals lists none: they compare by size and time.
sequence.Unhashed = true;
Assert.True((await new CopySides(db).RemoteAsync(remote, sequence.Id, Ct)).Photos.All(p => p.Sha256 is null));
}
[Test]
public async Task HeldElsewhereLooksAcrossEveryArchiveOfTheIndex()
{
var db = await OpenChronosAsync();
var (_, mine) = await SequenceAsync(db);
var (other, inOther) = await SequenceAsync(db);
var (_, alsoInOther) = await SequenceAsync(db, other);
await FrameAsync(db, mine.Id, 0, Sha(1));
await FrameAsync(db, mine.Id, 1, Sha(2));
await FrameAsync(db, mine.Id, 2, Sha(3));
await FrameAsync(db, inOther.Id, 0, Sha(1));
await FrameAsync(db, alsoInOther.Id, 0, Sha(2), FrameFlags.Missing);
await FrameAsync(db, alsoInOther.Id, 1, Sha(4));
var sides = new CopySides(db);
var held = await sides.HeldElsewhereAsync([Sha(1).ToUpperInvariant(), Sha(2), Sha(3), Sha(4), string.Empty], [mine.Id], Ct);
// Photo 2's other frame is missing: it holds nothing. Photo 3 is only in the compared sequence.
Assert.True(held.SetEquals([Sha(1), Sha(4)]));
Assert.True((await sides.HeldElsewhereAsync([Sha(1), Sha(4)], [mine.Id, inOther.Id, alsoInOther.Id], Ct)).Count == 0);
Assert.True((await sides.HeldElsewhereAsync([Sha(1)], [], Ct)).SetEquals([Sha(1)]));
Assert.Empty(await sides.HeldElsewhereAsync([], [mine.Id], Ct));
// Batched: more hashes than one statement takes.
var many = Enumerable.Range(100, 1200).Select(Sha).Append(Sha(4)).ToList();
Assert.True((await sides.HeldElsewhereAsync(many, [mine.Id], Ct)).SetEquals([Sha(4)]));
}
}
public sealed class SqliteCopySidesTests(TestContext context) : CopySidesTests(context)
{
protected override Backend Backend => Backend.SqliteMemory;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresCopySidesTests(TestContext context) : CopySidesTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,228 @@
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.Data.Tests.Sync;
/// <summary>The photo-by-photo comparison of two copies (owner review 6, #73; design §4.1).</summary>
[Category("sync")]
public sealed class CopyComparisonTests
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0, 250);
private static string Sha(int n) => Convert.ToHexStringLower(BitConverter.GetBytes((long)n)).PadLeft(64, 'a');
/// <summary>Photo n: its own SHA-256, size and a sub-second capture time 5 s after the one before.</summary>
private static CopyPhotoInput Photo(int n, int index = -1, bool hashed = true, bool unusable = false, string? name = null, DateTime? at = null, long? size = null) =>
new(Guid.NewGuid(), index < 0 ? n : index, name ?? $"IMG_{n:0000}.JPG", hashed ? Sha(n) : null, size ?? 1000 + n, at ?? Start.AddSeconds(5 * n), unusable);
private static CopySideInput Side(params CopyPhotoInput[] photos) => new(photos, []);
private static CopySideInput Side(IEnumerable<CopyPhotoInput> photos, params RemovedPhotoDto[] removed) => new([.. photos], removed);
private static RemovedPhotoDto Deleted(int n) => new(Sha(n), null, "deleted", DateTimeOffset.UnixEpoch);
private static RemovedPhotoDto Replaced(int n, int by) => new(Sha(n), Sha(by), "replaced", DateTimeOffset.UnixEpoch);
private static int Count(CopyComparisonResult result, PhotoClass c) => result.Of(c).Count();
[Test]
public void IdenticalCopiesAreAllSame()
{
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), Photo(3)), Side(Photo(1), Photo(2), Photo(3)));
Assert.Equal(3, Count(result, PhotoClass.Same));
Assert.Equal((3, 0, 0, 1000, 1000), (result.Score.Shared, result.Score.OnlyHere, result.Score.OnlyThere, result.Score.Containment, result.Score.Overlap));
Assert.True(result.Score.Identical);
Assert.True(result.Score.ByHash);
Assert.Count(9, result.Totals);
}
[Test]
public void ASubsetReadsFullyContainedAndASupersetToo()
{
// The Uploader sent part of the card: the server holds a subset.
var all = Enumerable.Range(1, 10).Select(n => Photo(n)).ToArray();
var part = Enumerable.Range(1, 4).Select(n => Photo(n)).ToArray();
var subset = CopyComparer.Compare(Side(all), Side(part));
Assert.Equal((4, 6, 0, 1000, 400), (subset.Score.Shared, subset.Score.OnlyHere, subset.Score.OnlyThere, subset.Score.Containment, subset.Score.Overlap));
Assert.False(subset.Score.Identical);
var superset = CopyComparer.Compare(Side(part), Side(all));
Assert.Equal((4, 0, 6, 1000), (superset.Score.Shared, superset.Score.OnlyHere, superset.Score.OnlyThere, superset.Score.Containment));
}
[Test]
public void AConvertedPhotoIsConvertedNotOnlyOnOneSide()
{
// This PC replaced photo 2 by a converted file (photo 50's content); the server still holds the original.
var here = Side([Photo(1), Photo(50, index: 1, at: Start.AddSeconds(10))], Replaced(2, 50));
var result = CopyComparer.Compare(here, Side(Photo(1), Photo(2)));
var converted = Assert.Contains(result.Photos, p => p.Class == PhotoClass.Converted);
Assert.Equal((Sha(50), Sha(2)), (converted.Here!.Sha256, converted.There!.Sha256));
Assert.Equal((2, 0, 0), (result.Score.Shared, result.Score.OnlyHere, result.Score.OnlyThere));
Assert.True(result.Score.Identical);
}
[Test]
public void ATombstonedPhotoIsDeletedOnThatSideNotOnlyOnTheOther()
{
var result = CopyComparer.Compare(Side([Photo(1), Photo(2)], Deleted(3)), Side([Photo(1), Photo(3)], Deleted(2)));
Assert.Equal(Sha(2), Assert.Contains(result.Photos, p => p.Class == PhotoClass.DeletedThere).Key);
Assert.Equal(Sha(3), Assert.Contains(result.Photos, p => p.Class == PhotoClass.DeletedHere).Key);
Assert.Equal((0, 0, 1, 1, 2), (result.Score.OnlyHere, result.Score.OnlyThere, result.Score.DeletedHere, result.Score.DeletedThere, result.Score.SharedRemoved));
Assert.False(result.Score.Identical);
Assert.Equal(1000, result.Score.Containment);
}
[Test]
public void CopiesOfOnePhotoInsideASideCountOnce()
{
var copy = Photo(2) with { FrameId = Guid.NewGuid(), Index = 5, FileName = "IMG_0002 (1).JPG" };
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), copy), Side(Photo(1), Photo(2)));
Assert.Equal((2, 2, 2), (result.Score.Shared, result.Score.LocalPhotos, result.Score.OtherPhotos));
var same = Assert.Contains(result.Photos, p => p.Key == Sha(2));
Assert.Equal((2, 1), (same.HereOccurrences, same.ThereOccurrences));
Assert.True(result.Score.Identical);
}
[Test]
public void AnUnhashedPhotoMatchesBySizeAndMillisecond()
{
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, hashed: false)), Side(Photo(1), Photo(2)));
var unhashed = Assert.Contains(result.Photos, p => p.Class == PhotoClass.SameUnhashed);
Assert.Equal(Sha(2), unhashed.Key);
Assert.Equal((1, 1), (result.Score.Shared, result.Score.SharedUnhashed));
Assert.True(result.Score.Identical);
Assert.False(result.Score.ByHash);
}
[Test]
public void UnhashedLeftoversStayOnTheirSide()
{
// Another size at the same time is another photo: unlike CompareOriginals, nothing is assumed to match.
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, hashed: false, size: 7)), Side(Photo(1), Photo(3, hashed: false)));
Assert.Equal((1, 0, 1, 1), (result.Score.Shared, result.Score.SharedUnhashed, result.Score.OnlyHere, result.Score.OnlyThere));
Assert.True(Assert.Contains(result.Photos, p => p.Class == PhotoClass.OnlyHere).Key.StartsWith("u:7:", StringComparison.Ordinal));
}
[Test]
public void DiffersPairsOnePhotoPerSideWithTheSameNameAndSubSecondInstant()
{
// Photo 2 edited on one side: another SHA-256, same name, same sub-second capture time.
var edited = Photo(2) with { Sha256 = Sha(99), Size = 4242 };
var result = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), edited));
var differs = Assert.Contains(result.Photos, p => p.Class == PhotoClass.Differs);
Assert.Equal((Sha(2), Sha(99), 1002L), (differs.Here!.Sha256, differs.There!.Sha256, differs.Bytes));
Assert.Equal((1, 0, 0), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
Assert.False(result.Score.Identical);
var total = Assert.Contains(result.Totals, t => t.Class == PhotoClass.Differs);
Assert.Equal((1002L, 4242L), (total.HereBytes, total.ThereBytes));
// Another name, or another millisecond, is no pair.
Assert.Equal(0, CopyComparer.Compare(Side(Photo(2)), Side(edited with { FileName = "DSC_0002.JPG" })).Score.Differs);
Assert.Equal(0, CopyComparer.Compare(Side(Photo(2)), Side(edited with { CapturedAt = edited.CapturedAt!.Value.AddMilliseconds(1) })).Score.Differs);
}
[Test]
public void WholeSecondCaptureTimesNeverPairAsDiffers()
{
// A camera that records whole seconds: two different photos at one second with one name are not one photo edited.
var at = new DateTime(2026, 9, 28, 18, 0, 0);
var result = CopyComparer.Compare(Side(Photo(1, at: at, name: "IMG_0001.JPG")), Side(Photo(2, at: at, name: "IMG_0001.JPG")));
Assert.Equal((0, 1, 1), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
}
[Test]
public void BurstsNeverPairAsDiffers()
{
// Two photos of a burst at one instant on each side: which is which cannot be told, so nothing pairs.
var at = Start.AddMilliseconds(130);
var result = CopyComparer.Compare(
Side(Photo(1, at: at, name: "IMG_0001.JPG"), Photo(2, at: at, name: "IMG_0001.JPG")),
Side(Photo(3, at: at, name: "IMG_0001.JPG"), Photo(4, at: at, name: "IMG_0001.JPG")));
Assert.Equal((0, 2, 2), (result.Score.Differs, result.Score.OnlyHere, result.Score.OnlyThere));
}
[Test]
public void TwoVersionsAfterAKeepBothAreVersions()
{
// A Union keep-both left both versions of photo 2 on both sides, at its one capture instant.
var version = Photo(2) with { FrameId = Guid.NewGuid(), Index = 3, Sha256 = Sha(99), Size = 4242 };
var result = CopyComparer.Compare(Side(Photo(1), Photo(2), version), Side(Photo(1), Photo(2), version with { FrameId = Guid.NewGuid() }));
Assert.Equal(2, Count(result, PhotoClass.Versions));
Assert.Equal((3, 2), (result.Score.Shared, result.Score.Versions));
Assert.True(result.Score.Identical);
// At a whole second they stay Same.
var at = new DateTime(2026, 9, 28, 18, 0, 10);
var whole = CopyComparer.Compare(Side(Photo(2, at: at), version with { CapturedAt = at }), Side(Photo(2, at: at), version with { CapturedAt = at }));
Assert.Equal((2, 0), (Count(whole, PhotoClass.Same), whole.Score.Versions));
}
[Test]
public void AnUnusableFrameHoldsNothingAndMarksTheRepair()
{
var result = CopyComparer.Compare(Side(Photo(1), Photo(2, unusable: true)), Side(Photo(1), Photo(2), Photo(3, unusable: true)));
var brought = Assert.Contains(result.Photos, p => p.Key == Sha(2));
Assert.Equal((PhotoClass.OnlyThere, true, false), (brought.Class, brought.RepairsHere, brought.RepairsThere));
Assert.DoesNotContain(Sha(3), result.Photos.Select(p => p.Key));
Assert.Equal((1, 2), (result.Score.LocalPhotos, result.Score.OtherPhotos));
// A Missing or Corrupt frame there is repaired by this PC's copy.
var other = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), Photo(2, unusable: true)));
var sent = Assert.Contains(other.Photos, p => p.Key == Sha(2));
Assert.Equal((PhotoClass.OnlyHere, true), (sent.Class, sent.RepairsThere));
}
[Test]
public void BytesArePerClassAndSide()
{
var result = CopyComparer.Compare(Side(Photo(1), Photo(2)), Side(Photo(1), Photo(3)));
Assert.Equal((1001L, 1001L), Totals(PhotoClass.Same));
Assert.Equal((1002L, 0L), Totals(PhotoClass.OnlyHere));
Assert.Equal((0L, 1003L), Totals(PhotoClass.OnlyThere));
Assert.Equal(1003L, Assert.Contains(result.Photos, p => p.Class == PhotoClass.OnlyThere).Bytes);
(long, long) Totals(PhotoClass c)
{
var total = result.Totals.Single(t => t.Class == c);
return (total.HereBytes, total.ThereBytes);
}
}
[Test]
public void TheResultDoesNotDependOnTheOrderOfTheInputs()
{
var edited = Photo(7) with { Sha256 = Sha(97) };
CopyPhotoInput[] here = [Photo(1), Photo(2), Photo(3, hashed: false), Photo(4), Photo(5), Photo(6), Photo(7), Photo(8, unusable: true)];
CopyPhotoInput[] there = [Photo(1), Photo(3), Photo(4, hashed: false), Photo(6), edited, Photo(8), Photo(9)];
var removedHere = new[] { Deleted(9) };
var removedThere = new[] { Deleted(5) };
var a = CopyComparer.Compare(Side(here, removedHere), Side(there, removedThere));
var b = CopyComparer.Compare(Side(Enumerable.Reverse(here), removedHere), Side(Enumerable.Reverse(there), removedThere));
Assert.Equal(a.Score, b.Score);
Assert.SequenceEqual(a.Photos.Select(p => (p.Class, p.Key, p.Here?.FrameId, p.There?.FrameId)), b.Photos.Select(p => (p.Class, p.Key, p.Here?.FrameId, p.There?.FrameId)));
Assert.Equal((2, 2, 1, 1, 1, 1, 1), (a.Score.Shared, a.Score.SharedUnhashed, a.Score.Differs, a.Score.DeletedHere, a.Score.DeletedThere, a.Score.OnlyHere, a.Score.OnlyThere));
}
[Test]
public void DeletionsCountWhatTheOtherSideTombstonedAndNoLongerHolds()
{
var tombstones = SyncTombstones.FromDtos([Deleted(3)], [Deleted(2), Deleted(1)]);
FramePhoto[] here = [new(Sha(1), 1, null), new(Sha(2), 2, null), new(Sha(2), 2, null)];
FramePhoto[] there = [new(Sha(1), 1, null), new(Sha(3), 3, null)];
Assert.Equal((1, 1), CopyComparer.Deletions(here, there, tombstones));
Assert.Equal((0, 0), CopyComparer.Deletions(here, there, SyncTombstones.None));
}
[Test]
public void TombstonesFromDtosReadBothSides()
{
var tombstones = SyncTombstones.FromDtos([Replaced(2, 50), Deleted(4)], [Deleted(5)]);
Assert.Equal(tombstones.Canonical(Sha(50)), tombstones.Canonical(Sha(2)));
Assert.True(tombstones.DeletedLocally(Sha(4)));
Assert.False(tombstones.DeletedLocally(Sha(2)));
Assert.True(tombstones.DeletedRemotely(Sha(5)));
Assert.True(SyncTombstones.FromDtos([], null).IsEmpty);
}
}