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

@@ -694,6 +694,14 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
ForgetJournal();
throw new StaleCopyPlanException();
}
if (lostFrames.Any(f => !f.Unhashed && !journal.Copies.Any(c => c.DropFrameId == f.FrameId)))
{
// A hashed photo the plan did not copy (held by a third sequence when planned, by nothing now): a last
// copy the plan did not list. Retrying this journal would fail the same way: it goes, and the new plan
// lists it. Only a photo the plan copied and the kept sequence does not hold is a failed copy.
ForgetJournal();
throw new StaleCopyPlanException();
}
var lost = lostFrames.Select(f => f.Sha256).Distinct(StringComparer.Ordinal).Count();
if (lost > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.VerifyFailed", lost));
journal.Settled.AddRange(failed.Select(f => f.FrameId));
+30 -9
View File
@@ -202,7 +202,7 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
/// A 404 for the remote side (design §6.3): the pair's row (made when the link had none) counts one hit per
/// <paramref name="refreshId"/>, and a hit after the first only once <see cref="GoneRecheck"/> has passed since it, and
/// every Candidate row naming that remote is deleted. With <paramref name="localId"/> null (an observation-only link: no
/// local copy is linked to it) no row counts the hit; the Candidate and Kept apart rows naming that remote go
/// local copy is linked to it) the Candidate rows naming that remote go and its Kept apart rows count the hit the same way
/// (<see cref="SettleUnlinkedGoneAsync"/>).
/// </summary>
public async Task MarkRemoteGoneAsync(string server, Guid remoteId, Guid? localId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
@@ -210,7 +210,7 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
ArgumentException.ThrowIfNullOrWhiteSpace(server);
if (localId is not { } local)
{
await SettleUnlinkedGoneAsync(server, remoteId, ct).ConfigureAwait(false);
await SettleUnlinkedGoneAsync(server, remoteId, refreshId, at, ct).ConfigureAwait(false);
return;
}
var refreshes = GoneRefreshes.GetOrCreateValue(db.Database);
@@ -238,16 +238,37 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
}
/// <summary>
/// A server sequence no local copy is linked to answered 404 (design §6.3; owner Q8): the unanswered (Candidate) and
/// Kept apart rows naming it go, so a local sequence matched only with it reads as local only again (Upload all local
/// sends it, the Library stops saying "copy found") rather than as a match whose server side is gone. Linked, Integrated
/// and Integrating rows are left to their link's own 404. Listed again, the server sequence is found anew.
/// A server sequence no local copy is linked to answered 404 (design §6.3; owner Q1, Q8): the unanswered (Candidate) rows
/// naming it go, so a local sequence matched only with it reads as local only again (Upload all local sends it, the
/// Library stops saying "copy found"); listed again, it is found anew. Its Kept apart rows are the user's answer and stay:
/// each counts the hit as a linked pair does (one per <paramref name="refreshId"/>, a second only once
/// <see cref="GoneRecheck"/> has passed since the first), so a server sequence answering 404 for a moment (moved to the
/// server's trash and restored, access withdrawn briefly) keeps the answer and a listing clears the count; only a
/// confirmed deletion (<see cref="FoundCopy.RemoteGone"/>) lets Upload all local send the local sequence
/// (<see cref="UploadAllRule"/>). Linked, Integrated and Integrating rows are left to their link's own 404.
/// </summary>
public Task SettleUnlinkedGoneAsync(string server, Guid remoteId, CancellationToken ct)
public async Task SettleUnlinkedGoneAsync(string server, Guid remoteId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(server);
return _db.ExecuteAsync($"DELETE FROM found_copies WHERE kind = 0 AND server = $1 AND remote_id = $2 AND {Effective} IN (0, 1)",
[server, remoteId], ct);
var refreshes = GoneRefreshes.GetOrCreateValue(db.Database);
var counted = refreshes.TryGetValue((server, remoteId), out var last) && last == refreshId;
await _db.InTransactionAsync(async session =>
{
var inner = new DbAccess(session);
await inner.ExecuteAsync($"DELETE FROM found_copies WHERE kind = 0 AND server = $1 AND remote_id = $2 AND {Effective} = 0",
[server, remoteId], ct).ConfigureAwait(false);
if (counted) return 0;
var apart = await inner.ListAsync($"{Select} WHERE kind = 0 AND server = $1 AND remote_id = $2 AND {Effective} = 1", [server, remoteId], Map, ct)
.ConfigureAwait(false);
foreach (var row in apart.Where(r => r.RemoteGoneHits == 0 || r.RemoteGoneAt is not { } first || at - first >= GoneRecheck))
{
await inner.ExecuteAsync(
"UPDATE found_copies SET remote_gone_hits = remote_gone_hits + 1, remote_gone_at = COALESCE(remote_gone_at, $2), updated_at = $3 WHERE id = $1",
[row.Id, at, _time.GetUtcNow()], ct).ConfigureAwait(false);
}
return 0;
}, ct).ConfigureAwait(false);
refreshes[(server, remoteId)] = refreshId;
}
/// <summary>The server answered for the remote again: hits back to 0, no gone time.</summary>
+4 -1
View File
@@ -55,7 +55,10 @@ public static class UploadAllRule
foreach (var entry in localOnly)
{
if (entry.Local is not { } local) continue;
var pairs = bySequence.GetValueOrDefault(local.Id) ?? [];
// A Kept apart answer about a server sequence confirmed deleted there (two 404s apart) holds nothing back: that
// sequence is no copy of anything any more, and the local one is this PC's only.
var pairs = (bySequence.GetValueOrDefault(local.Id) ?? []).Where(p => p is not { Kind: CopyKind.LocalServer, State: CopyState.KeptApart, RemoteGone: true })
.ToList();
UploadSkip? why =
busy.Contains(local.Id) || pairs.Any(p => p.State == CopyState.Integrating) ? UploadSkip.Busy
: pairs.Any(p => p.Kind == CopyKind.LocalServer && p.RemoteGoneHits >= 1) ? UploadSkip.DeletedOnServer
+16 -6
View File
@@ -643,13 +643,15 @@ public sealed class SyncService
// Title, tags, rating and notes the user decided as this PC's (the plan had a line there and the final payload
// keeps this PC's value) are never taken over from a server edit made since: no analysis moves them, and they
// keep no history. The pair goes back to Linked and the sync shows the conflict. Settings paths are absorbed.
var lined = CopyPayload.Moved(plannedLocal, plannedRemote);
var notLocal = CopyPayload.Moved(plannedLocal, finalPortable);
var metadata = absorbed.Where(p => p.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal)).ToList();
if (metadata.Count > 0)
{
var lined = CopyPayload.Moved(plannedLocal, plannedRemote);
var notLocal = CopyPayload.Moved(plannedLocal, finalPortable);
if (metadata.Any(p => lined.Contains(p) && !notLocal.Contains(p))) throw DetailsChanged();
}
if (metadata.Any(p => lined.Contains(p) && !notLocal.Contains(p))) throw DetailsChanged();
// A line the user decided as the server's whose server value is now this PC's planned one: this PC's own
// value sent there since the plan (a background push), not a newer edit. Absorbing it would reverse the
// user's choice on both sides.
var sinceLocal = CopyPayload.Moved(plannedLocal, freshRemote);
if (absorbed.Any(p => lined.Contains(p) && notLocal.Contains(p) && !sinceLocal.Any(q => Overlaps(p, q)))) throw DetailsChanged();
final = CopyPayload.Merge(final, freshRemote, absorbed.ToDictionary(p => p, _ => CopySide.Other, StringComparer.Ordinal),
[.. absorbed.Select(p => new DetailLine(p, null, null))]);
}
@@ -710,6 +712,10 @@ public sealed class SyncService
return result;
static SyncConflictChangedException DetailsChanged() => new(Loc.L("Errors.Copies.DetailsChanged"));
static bool Overlaps(string path, string other) =>
string.Equals(path, other, StringComparison.Ordinal)
|| other.StartsWith(path + ".", StringComparison.Ordinal) || path.StartsWith(other + ".", StringComparison.Ordinal);
}
private const int AgreeAttempts = 3;
@@ -981,6 +987,10 @@ public sealed class SyncService
var localChanged = link.BaseLocalSettings != local.SettingsVersion;
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
if (!localChanged && !remoteChanged) return (link, local);
// A pair being integrated has its details settled once, line by line, by its Integrate job: a push or pull now would
// be absorbed there as a newer edit and reverse the user's choice (owner Q4).
if (await Copies.FindRemoteAsync(local.Id, link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false) is { State: CopyState.Integrating })
return (link, local);
// Frames inserted here since the copy was listed moved its positions without a new settings version.
if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is { } current && current.SettingsVersion == local.SettingsVersion)
local = current;
+51 -12
View File
@@ -81,6 +81,9 @@ internal sealed class SyncTransfers(SyncService sync)
// is filed into the new sequence once there is one).
var heldElsewhere = new List<Frame>();
var sessionKey = remoteId is null ? await SessionKeyAsync(context, remote, local).ConfigureAwait(false) : null;
// Server sequences this PC knows already (listed, linked, or paired with this one): one the key files the first
// original into was not made by this upload, and its details are compared as a new link's, never overwritten.
var knownRemotes = remoteId is null ? await KnownRemotesAsync(remote, local.Id, ct).ConfigureAwait(false) : [];
while (remoteId is null && pending.TryDequeue(out var first))
{
var sent = await UploadFrameAsync(context, remote, null, sessionKey, paths.FromRelative(first.RelativePath), first, tombstones,
@@ -90,6 +93,7 @@ internal sealed class SyncTransfers(SyncService sync)
else if (sent.SequenceId != Guid.Empty)
{
remoteId = sent.SequenceId;
if (knownRemotes.Contains(sent.SequenceId)) created = false;
await context.CheckpointAsync(sent.SequenceId.ToString(), progress.Done + 1, frames.Count).ConfigureAwait(false);
await sync.LinkAsync(remote.Server, sent.SequenceId, local, ct).ConfigureAwait(false);
}
@@ -501,6 +505,21 @@ internal sealed class SyncTransfers(SyncService sync)
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
// Without a local copy, the first original goes under the server sequence's key (DownloadKeyAsync). A local copy that
// key already names, which this PC compared with the server sequence (a link a 404 forgot, a pair asked about again),
// is that copy: linked first, filled as a linked copy (its tombstones honoured), and compared as a new link, so its own
// details are never overwritten by the server's (owner Q3, Q4, Q6).
string? key = null;
if (local is null)
{
(key, var joins) = await DownloadKeyAsync(context, remote, remoteId, archive.Id).ConfigureAwait(false);
if (joins is { } holderId && await db.Sequences.GetAsync(holderId, ct).ConfigureAwait(false) is { } holder)
{
await sync.LinkAsync(remote.Server, remoteId, holder, ct).ConfigureAwait(false);
local = holder;
}
}
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
var (have, restore, photos, missing) = local is null ? ([], [], new FramePhotos([]), []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
@@ -538,7 +557,6 @@ internal sealed class SyncTransfers(SyncService sync)
if (local is null && wanted.Count > 0)
{
// The first original creates the local sequence (grouped by the server id); the others join it.
var key = await DownloadKeyAsync(context, remote, remoteId, archive.Id).ConfigureAwait(false);
var (staged, sha) = await FetchOriginalAsync(remote, wanted[0], staging, ct).ConfigureAwait(false);
var first = await CommitAsync(key, archive.Id, null, wanted[0], staged, sha, captured, ct).ConfigureAwait(false);
local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
@@ -970,16 +988,19 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary>
/// The session key the first original of an upload without a target goes under: this sequence's own
/// (<see cref="SyncService.SessionKey"/>), unless the user kept it apart from (or unlinked it from) a sequence of this
/// server. The server files that key into the sequence an earlier upload made, which the user chose to keep separate;
/// such an upload makes a new sequence instead, under a key of this job (the same on a retry).
/// (<see cref="SyncService.SessionKey"/>), unless it has a pair with a sequence of this server that the user has not
/// linked (kept apart, unlinked, or asked about again). The server files that key into the sequence an earlier upload
/// made, which the user separated; such an upload makes a new sequence instead, under a key of this job (the same on a
/// retry).
/// </summary>
private async Task<string> SessionKeyAsync(JobContext context, ISyncRemote remote, Sequence local)
{
var own = SyncService.SessionKey(local.Id);
// Kept apart, unlinked, or asked about again (Candidate: unlinked then Ask again, a Keep apart undone): the user has
// not linked the two, so the upload never joins one through the key and links it unasked (owner Q1).
var apart = (await sync.Copies.ListByLocalAsync(local.Id, context.Cancellation).ConfigureAwait(false))
.Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart } && string.Equals(c.Server, remote.Server, StringComparison.Ordinal)
&& c.LocalId == local.Id);
.Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart or CopyState.Candidate }
&& string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == local.Id);
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
}
@@ -991,16 +1012,34 @@ internal sealed class SyncTransfers(SyncService sync)
/// a download makes a new local sequence instead, under a key of this job (the same on a retry), and never fills or
/// overwrites the other.
/// </summary>
private async Task<string> DownloadKeyAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid archiveId)
/// <returns>
/// The key, and the holder it joins when that holder is a copy this PC already compared with the server sequence (a pair
/// of the two exists: Candidate, Linked or Integrated): the download then fills it as a linked copy, honouring its
/// tombstones, and compares its details as a new link's. Null when the key makes a new sequence or joins one a run of
/// this download made and stopped before linking.
/// </returns>
private async Task<(string Key, Guid? Joins)> DownloadKeyAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid archiveId)
{
var ct = context.Cancellation;
var own = SyncService.SessionKey(remoteId);
if (await sync.Database.Sequences.FindBySessionKeyAsync(archiveId, own, ct).ConfigureAwait(false) is not { } holder) return own;
var apart = (await sync.Copies.ListByLocalAsync(holder, ct).ConfigureAwait(false))
.Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart } && string.Equals(c.Server, remote.Server, StringComparison.Ordinal)
&& c.LocalId == holder && c.RemoteId == remoteId)
if (await sync.Database.Sequences.FindBySessionKeyAsync(archiveId, own, ct).ConfigureAwait(false) is not { } holder) return (own, null);
var pairs = (await sync.Copies.ListByLocalAsync(holder, ct).ConfigureAwait(false))
.Where(c => c.Kind == CopyKind.LocalServer && string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == holder
&& c.RemoteId == remoteId)
.ToList();
var apart = pairs.Any(c => c.State == CopyState.KeptApart)
|| await sync.Links.FindByLocalAsync(remote.Server, holder, ct).ConfigureAwait(false) is { } link && link.RemoteId != remoteId;
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
if (apart) return (string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}"), null);
return (own, pairs.Count > 0 ? holder : null);
}
/// <summary>The server sequences of <paramref name="remote"/> this PC knows of: listed or linked, or paired with <paramref name="localId"/>.</summary>
private async Task<HashSet<Guid>> KnownRemotesAsync(ISyncRemote remote, Guid localId, CancellationToken ct)
{
var known = (await sync.Links.ListAsync(remote.Server, ct).ConfigureAwait(false)).Select(l => l.RemoteId).ToHashSet();
foreach (var pair in await sync.Copies.ListByLocalAsync(localId, ct).ConfigureAwait(false))
if (pair is { Kind: CopyKind.LocalServer, RemoteId: { } id } && string.Equals(pair.Server, remote.Server, StringComparison.Ordinal)) known.Add(id);
return known;
}
private static async Task<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)