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:
1 parent
283d04d9cd
commit
f6f81e2c37
9 files changed
+1465
No files matched your search
@@ -0,0 +1,280 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Copies;
|
||||
|
||||
namespace Chronos.Data.Sync;
|
||||
|
||||
/// <summary>
|
||||
/// The photo-by-photo comparison of two copies of one time-lapse (owner review 6, #73; design §4.1): which photos both hold,
|
||||
/// which only one holds, which one side deleted, which differ and which a Union kept in two versions. Detection, the Compare
|
||||
/// dialog, Integrate and Merge all read this one comparison. Pure: no I/O, thread-safe, O(n log n).
|
||||
/// </summary>
|
||||
public static class CopyComparer
|
||||
{
|
||||
/// <summary>The unhashed key prefix: "u:<size>:<capture millisecond>".</summary>
|
||||
internal const string UnhashedPrefix = "u:";
|
||||
|
||||
/// <summary>
|
||||
/// Compares <paramref name="here"/> (this PC, or the kept sequence of a merge) with <paramref name="there"/> (the server,
|
||||
/// or the other local sequence). Each photo lands in exactly one class; unusable frames (Missing or Corrupt) hold nothing
|
||||
/// and mark the photo the other side brings as a repair.
|
||||
/// </summary>
|
||||
public static CopyComparisonResult Compare(CopySideInput here, CopySideInput there)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(here);
|
||||
ArgumentNullException.ThrowIfNull(there);
|
||||
// 1. Tombstones of both sides; unusable frames left out of their side's holdings.
|
||||
var tombstones = SyncTombstones.FromDtos(here.Removed ?? [], there.Removed);
|
||||
var mine = Holdings(here.Photos, tombstones);
|
||||
var theirs = Holdings(there.Photos, tombstones);
|
||||
var brokenHere = Broken(here.Photos, tombstones);
|
||||
var brokenThere = Broken(there.Photos, tombstones);
|
||||
var theirsByKey = theirs.ToDictionary(h => h.Key, StringComparer.Ordinal);
|
||||
var done = new HashSet<Holding>(ReferenceEqualityComparer.Instance);
|
||||
var photos = new List<ComparedPhoto>(mine.Count + theirs.Count);
|
||||
|
||||
// 3. Same and Converted: one canonical key on both sides.
|
||||
foreach (var h in mine)
|
||||
{
|
||||
if (!h.Hashed || !theirsByKey.TryGetValue(h.Key, out var t)) continue;
|
||||
var (hereFrame, thereFrame, same) = Pick(h, t);
|
||||
photos.Add(new ComparedPhoto(same ? PhotoClass.Same : PhotoClass.Converted, h.Key, hereFrame, thereFrame, h.Occurrences, t.Occurrences, hereFrame.Size));
|
||||
done.Add(h);
|
||||
done.Add(t);
|
||||
}
|
||||
|
||||
// 4. SameUnhashed: one side not hashed, the same size and capture millisecond (FramePhoto.Matches), one to one.
|
||||
var bySizeAndTime = new Dictionary<(long Size, long Ms), List<Holding>>();
|
||||
foreach (var t in theirs)
|
||||
{
|
||||
if (done.Contains(t) || t.Ms is not { } ms) continue;
|
||||
if (!bySizeAndTime.TryGetValue((t.First.Size, ms), out var list)) bySizeAndTime[(t.First.Size, ms)] = list = [];
|
||||
list.Add(t);
|
||||
}
|
||||
foreach (var h in mine)
|
||||
{
|
||||
if (done.Contains(h) || h.Ms is not { } ms || !bySizeAndTime.TryGetValue((h.First.Size, ms), out var candidates)) continue;
|
||||
var t = candidates.FirstOrDefault(c => !done.Contains(c) && (!h.Hashed || !c.Hashed));
|
||||
if (t is null) continue;
|
||||
var key = h.Hashed ? h.Key : t.Hashed ? t.Key : h.Key;
|
||||
photos.Add(new ComparedPhoto(PhotoClass.SameUnhashed, key, h.First, t.First, h.Occurrences, t.Occurrences, h.First.Size));
|
||||
done.Add(h);
|
||||
done.Add(t);
|
||||
}
|
||||
|
||||
// 5. Deleted there / deleted here: held by one side, tombstoned by the other, which does not hold it.
|
||||
foreach (var h in mine.Where(h => !done.Contains(h) && h.Hashed && tombstones.DeletedRemotely(h.Key)))
|
||||
{
|
||||
photos.Add(new ComparedPhoto(PhotoClass.DeletedThere, h.Key, h.First, null, h.Occurrences, 0, h.First.Size));
|
||||
done.Add(h);
|
||||
}
|
||||
foreach (var t in theirs.Where(t => !done.Contains(t) && t.Hashed && tombstones.DeletedLocally(t.Key)))
|
||||
{
|
||||
photos.Add(Brought(PhotoClass.DeletedHere, t, brokenHere));
|
||||
done.Add(t);
|
||||
}
|
||||
|
||||
// 6. Differs, strictly: one hashed photo per side at one sub-second instant, with the same file name.
|
||||
var hereAt = HashedAt(mine.Where(h => !done.Contains(h)));
|
||||
var thereAt = HashedAt(theirs.Where(t => !done.Contains(t)));
|
||||
foreach (var (ms, onHere) in hereAt)
|
||||
{
|
||||
if (onHere.Count != 1 || !SubSecond(ms) || !thereAt.TryGetValue(ms, out var onThere) || onThere.Count != 1) continue;
|
||||
var (h, t) = (onHere[0], onThere[0]);
|
||||
if (!string.Equals(h.First.FileName, t.First.FileName, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
photos.Add(new ComparedPhoto(PhotoClass.Differs, h.Key, h.First, t.First, h.Occurrences, t.Occurrences, h.First.Size));
|
||||
done.Add(h);
|
||||
done.Add(t);
|
||||
}
|
||||
|
||||
// 7. Versions: a sub-second instant holding exactly the same two shared photos on both sides (a Union keep-both).
|
||||
MarkVersions(photos, mine, theirs);
|
||||
|
||||
// 8. The rest is on one side only (unhashed leftovers are not assumed to match).
|
||||
foreach (var h in mine.Where(h => !done.Contains(h)))
|
||||
photos.Add(new ComparedPhoto(PhotoClass.OnlyHere, h.Key, h.First, null, h.Occurrences, 0, h.First.Size, RepairsThere: Repairs(h, brokenThere)));
|
||||
foreach (var t in theirs.Where(t => !done.Contains(t))) photos.Add(Brought(PhotoClass.OnlyThere, t, brokenHere));
|
||||
|
||||
photos.Sort(Order);
|
||||
return new CopyComparisonResult(photos, Totals(photos), Score(photos, mine.Count, theirs.Count));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For linked pairs at each reconcile: only the deletion counts, cheaply. Deleted there: distinct photos this side holds
|
||||
/// that the other side tombstoned and does not hold; deleted here the other way round (as <see cref="SyncRules.CompareOriginals(IReadOnlyCollection{FramePhoto}, IReadOnlyCollection{FramePhoto}, SyncTombstones)"/>
|
||||
/// leaves them out).
|
||||
/// </summary>
|
||||
public static (int DeletedHere, int DeletedThere) Deletions(IReadOnlyCollection<FramePhoto> here, IReadOnlyCollection<FramePhoto> there, SyncTombstones tombstones)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(here);
|
||||
ArgumentNullException.ThrowIfNull(there);
|
||||
ArgumentNullException.ThrowIfNull(tombstones);
|
||||
if (tombstones.IsEmpty) return (0, 0);
|
||||
var mine = here.Select(tombstones.Canonical).ToList();
|
||||
var theirs = there.Select(tombstones.Canonical).ToList();
|
||||
var minePhotos = new FramePhotos(mine.Select((p, i) => (i, p)));
|
||||
var theirPhotos = new FramePhotos(theirs.Select((p, i) => (i, p)));
|
||||
return (Count(theirs, tombstones.DeletedLocally, minePhotos), Count(mine, tombstones.DeletedRemotely, theirPhotos));
|
||||
|
||||
static int Count(List<FramePhoto> side, Func<string?, bool> deleted, FramePhotos other) =>
|
||||
side.Where(p => p.IsHashed && deleted(p.Sha256) && other.IndexOf(p) is null).Select(p => p.Sha256!.ToLowerInvariant()).Distinct(StringComparer.Ordinal).Count();
|
||||
}
|
||||
|
||||
/// <summary>The key of an unhashed photo by its size and capture time; a photo without a time is keyed by its frame (it matches nothing).</summary>
|
||||
internal static string UnhashedKey(long size, DateTime? capturedAt, Guid frameId) => capturedAt is { } at
|
||||
? string.Create(CultureInfo.InvariantCulture, $"{UnhashedPrefix}{size}:{Millisecond(at)}")
|
||||
: string.Create(CultureInfo.InvariantCulture, $"{UnhashedPrefix}{size}:{frameId:N}");
|
||||
|
||||
internal static long Millisecond(DateTime time) => time.Ticks / TimeSpan.TicksPerMillisecond;
|
||||
|
||||
/// <summary>A capture millisecond with a sub-second part: the camera records real sub-second times.</summary>
|
||||
private static bool SubSecond(long ms) => ms % 1000 != 0;
|
||||
|
||||
/// <summary>One photo of one side: its key and the frames holding it, in index order (the first stands for it).</summary>
|
||||
private sealed class Holding(string key, bool hashed, List<CopyPhotoInput> frames)
|
||||
{
|
||||
public string Key { get; } = key;
|
||||
|
||||
public bool Hashed { get; } = hashed;
|
||||
|
||||
public List<CopyPhotoInput> Frames { get; } = frames;
|
||||
|
||||
public CopyPhotoInput First => Frames[0];
|
||||
|
||||
public int Occurrences => Frames.Count;
|
||||
|
||||
public long? Ms => First.CapturedAt is { } at ? Millisecond(at) : null;
|
||||
}
|
||||
|
||||
/// <summary>2. A side's usable frames grouped by photo key (copies of one photo inside a side count once), in index order.</summary>
|
||||
private static List<Holding> Holdings(IReadOnlyList<CopyPhotoInput> photos, SyncTombstones tombstones)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(photos);
|
||||
var result = new List<Holding>();
|
||||
var byKey = new Dictionary<string, Holding>(StringComparer.Ordinal);
|
||||
foreach (var frame in photos.Where(p => p is { Unusable: false }).OrderBy(p => p.Index).ThenBy(p => p.FrameId))
|
||||
{
|
||||
var hashed = !string.IsNullOrEmpty(frame.Sha256);
|
||||
var key = Key(frame, tombstones);
|
||||
if (byKey.TryGetValue(key, out var holding))
|
||||
{
|
||||
holding.Frames.Add(frame);
|
||||
continue;
|
||||
}
|
||||
byKey[key] = holding = new Holding(key, hashed, [frame]);
|
||||
result.Add(holding);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string Key(CopyPhotoInput frame, SyncTombstones tombstones) => string.IsNullOrEmpty(frame.Sha256)
|
||||
? UnhashedKey(frame.Size, frame.CapturedAt, frame.FrameId)
|
||||
: tombstones.Canonical(frame.Sha256)!;
|
||||
|
||||
/// <summary>The keys of a side's unusable frames: canonical SHA-256 and size and capture time, so a photo either way marks a repair.</summary>
|
||||
private static HashSet<string> Broken(IReadOnlyList<CopyPhotoInput> photos, SyncTombstones tombstones)
|
||||
{
|
||||
var broken = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var frame in photos.Where(p => p is { Unusable: true }))
|
||||
{
|
||||
broken.Add(Key(frame, tombstones));
|
||||
if (frame.CapturedAt is not null) broken.Add(UnhashedKey(frame.Size, frame.CapturedAt, frame.FrameId));
|
||||
}
|
||||
return broken;
|
||||
}
|
||||
|
||||
private static bool Repairs(Holding brought, HashSet<string> broken) =>
|
||||
broken.Count > 0 && (broken.Contains(brought.Key) || (brought.First.CapturedAt is not null
|
||||
&& broken.Contains(UnhashedKey(brought.First.Size, brought.First.CapturedAt, brought.First.FrameId))));
|
||||
|
||||
/// <summary>A photo only the other side holds (or holds and this side deleted).</summary>
|
||||
private static ComparedPhoto Brought(PhotoClass c, Holding t, HashSet<string> brokenHere) =>
|
||||
new(c, t.Key, null, t.First, 0, t.Occurrences, t.First.Size, RepairsHere: Repairs(t, brokenHere));
|
||||
|
||||
/// <summary>The frames standing for a photo both hold: one with the same raw SHA-256 on each side when there is one (Same), else the first (Converted).</summary>
|
||||
private static (CopyPhotoInput Here, CopyPhotoInput There, bool Same) Pick(Holding h, Holding t)
|
||||
{
|
||||
foreach (var mine in h.Frames)
|
||||
{
|
||||
var theirs = t.Frames.FirstOrDefault(f => string.Equals(f.Sha256, mine.Sha256, StringComparison.OrdinalIgnoreCase));
|
||||
if (theirs is not null) return (mine, theirs, true);
|
||||
}
|
||||
return (h.First, t.First, false);
|
||||
}
|
||||
|
||||
/// <summary>The hashed photos left at each capture millisecond.</summary>
|
||||
private static SortedDictionary<long, List<Holding>> HashedAt(IEnumerable<Holding> holdings)
|
||||
{
|
||||
var at = new SortedDictionary<long, List<Holding>>();
|
||||
foreach (var h in holdings)
|
||||
{
|
||||
if (!h.Hashed || h.Ms is not { } ms) continue;
|
||||
if (!at.TryGetValue(ms, out var list)) at[ms] = list = [];
|
||||
list.Add(h);
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
private static void MarkVersions(List<ComparedPhoto> photos, List<Holding> mine, List<Holding> theirs)
|
||||
{
|
||||
var hereAt = KeysAt(mine);
|
||||
var thereAt = KeysAt(theirs);
|
||||
var shared = photos.Where(p => p.Class is PhotoClass.Same or PhotoClass.Converted).Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
|
||||
for (var i = 0; i < photos.Count; i++)
|
||||
{
|
||||
var p = photos[i];
|
||||
if (p.Class is not (PhotoClass.Same or PhotoClass.Converted) || p.Here!.CapturedAt is not { } hereTime || p.There!.CapturedAt is not { } thereTime) continue;
|
||||
var ms = Millisecond(hereTime);
|
||||
if (ms != Millisecond(thereTime) || !SubSecond(ms)) continue;
|
||||
if (!hereAt.TryGetValue(ms, out var onHere) || !thereAt.TryGetValue(ms, out var onThere)) continue;
|
||||
if (onHere.Count == 2 && onThere.Count == 2 && onHere.SetEquals(onThere) && onHere.All(shared.Contains)) photos[i] = p with { Class = PhotoClass.Versions };
|
||||
}
|
||||
|
||||
static Dictionary<long, HashSet<string>> KeysAt(List<Holding> side)
|
||||
{
|
||||
var at = new Dictionary<long, HashSet<string>>();
|
||||
foreach (var h in side)
|
||||
{
|
||||
if (h.Ms is not { } ms) continue;
|
||||
if (!at.TryGetValue(ms, out var keys)) at[ms] = keys = new HashSet<string>(StringComparer.Ordinal);
|
||||
keys.Add(h.Key);
|
||||
}
|
||||
return at;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Capture order, then key and class: the same for any order of the inputs.</summary>
|
||||
private static int Order(ComparedPhoto a, ComparedPhoto b)
|
||||
{
|
||||
var byTime = ((a.Here ?? a.There)!.CapturedAt ?? DateTime.MaxValue).CompareTo((b.Here ?? b.There)!.CapturedAt ?? DateTime.MaxValue);
|
||||
if (byTime != 0) return byTime;
|
||||
var byKey = string.CompareOrdinal(a.Key, b.Key);
|
||||
return byKey != 0 ? byKey : a.Class.CompareTo(b.Class);
|
||||
}
|
||||
|
||||
private static PhotoClassTotal[] Totals(List<ComparedPhoto> photos) =>
|
||||
[
|
||||
.. Enum.GetValues<PhotoClass>().Select(c =>
|
||||
{
|
||||
var of = photos.Where(p => p.Class == c).ToList();
|
||||
return new PhotoClassTotal(c, of.Count, of.Sum(p => p.Here?.Size ?? 0), of.Sum(p => p.There?.Size ?? 0));
|
||||
}),
|
||||
];
|
||||
|
||||
/// <summary>10. The counts and ratios of design §3.2 (Versions counted in Shared).</summary>
|
||||
private static CopyScore Score(List<ComparedPhoto> photos, int localPhotos, int otherPhotos)
|
||||
{
|
||||
int Of(PhotoClass c) => photos.Count(p => p.Class == c);
|
||||
var versions = Of(PhotoClass.Versions);
|
||||
var shared = Of(PhotoClass.Same) + Of(PhotoClass.Converted) + versions;
|
||||
var unhashed = Of(PhotoClass.SameUnhashed);
|
||||
var (deletedHere, deletedThere) = (Of(PhotoClass.DeletedHere), Of(PhotoClass.DeletedThere));
|
||||
var removed = deletedHere + deletedThere;
|
||||
var smaller = Math.Min(localPhotos, otherPhotos);
|
||||
var union = localPhotos + otherPhotos - (shared + unhashed);
|
||||
var containment = smaller == 0 ? 0 : (int)Math.Min(1000, 1000L * (shared + unhashed + removed) / smaller);
|
||||
var overlap = union <= 0 ? 0 : (int)Math.Min(1000, 1000L * (shared + unhashed) / union);
|
||||
return new CopyScore(shared, unhashed, removed, Of(PhotoClass.OnlyHere), Of(PhotoClass.OnlyThere), Of(PhotoClass.Differs), deletedHere, deletedThere,
|
||||
versions, localPhotos, otherPhotos, containment, overlap, 0);
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,18 @@ public sealed class SyncTombstones
|
||||
/// <summary>No photo removed on either side.</summary>
|
||||
public static SyncTombstones None { get; } = new([], null);
|
||||
|
||||
/// <summary>
|
||||
/// The tombstones of two copies both given as the manifest carries them (<see cref="ToDto"/>): a local pair compared
|
||||
/// with each other (owner review 6, #73), <paramref name="here"/> standing for "this PC".
|
||||
/// </summary>
|
||||
public static SyncTombstones FromDtos(IEnumerable<RemovedPhotoDto> here, IEnumerable<RemovedPhotoDto>? there)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(here);
|
||||
return new SyncTombstones(here.Where(r => r is not null).Select(r => new FrameRemoval(Guid.Empty, r.Sha256, r.Replacement,
|
||||
string.Equals(r.Reason, Wire(RemovalReason.Replaced), StringComparison.OrdinalIgnoreCase) ? RemovalReason.Replaced : RemovalReason.Deleted, r.At)),
|
||||
there?.Where(r => r is not null));
|
||||
}
|
||||
|
||||
/// <summary>Whether either side removed or replaced anything.</summary>
|
||||
public bool IsEmpty => _deletedLocally.Count == 0 && _deletedRemotely.Count == 0 && _canonical.Count == 0;
|
||||
|
||||
|
||||
Reference in new issue
Block a user