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

@@ -372,12 +372,57 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
var frame = await _db.Frames.GetAsync(copy.DropFrameId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.CopyPhoto, copy.FileName, n, journal.Copies.Count)).ConfigureAwait(false);
var result = await FileAsync(frame, copy.Sha256, planned: copy.Sha256 is { Length: > 0 }).ConfigureAwait(false);
// A version kept beside the kept sequence's own (a Union keep-both, or another photo after all) is left out of
// Main as it is filed, before the journal says so: a resumed run files it again (a duplicate) and asks again.
if (copy is { Action: PhotoAction.FetchVersion, Sha256: { Length: > 0 } version } && journal.Replaces.All(r => r.Key != copy.Key))
await LeaveOutOfMainAsync(version).ConfigureAwait(false);
journal.Committed[copy.DropFrameId] = result.FrameId;
Save();
context.Log(Loc.L("Archive.Log.MergeCopied", copy.FileName));
}
}
/// <summary>
/// Leaves the second version <paramref name="sha"/> just filed in the kept sequence out of Main at once (owner Q3), not
/// only at the Details stage: a merge abandoned before that stage (its details changed meanwhile, a stale stage, a
/// cancel) would otherwise leave both versions in Main for good, and a new plan, which reads both as the kept
/// sequence's own photos, leaves neither out. Written under the kept sequence's lease at the settings version read
/// just before (asked again when an edit lands in between); when that was the version the plan read, the Details
/// stage then writes at the version this write made (the plan's payload leaves the version out as well). Settings
/// that are not a project of this Chronos are left as they are, as the plan leaves them. Not cancelled halfway: a
/// filed version is never left in Main by a cancel.
/// </summary>
private async Task LeaveOutOfMainAsync(string sha)
{
var ct = CancellationToken.None;
for (var attempt = 1; ; attempt++)
{
var keep = await _db.Sequences.GetAsync(journal.KeepId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
var basis = CopyPayload.Portable(SyncPayload.Of(keep), await SequencePayloadWriter.PhotosAsync(_db, journal.KeepId, null, ct).ConfigureAwait(false));
SyncPayload excluded;
try
{
excluded = CopyPayload.ExcludeVersions(basis, [sha.ToLowerInvariant()]);
}
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException)
{
return;
}
if (excluded.SameAs(basis)) return;
try
{
var updated = await new SequencePayloadWriter(_db, owner.Archives).ApplyAsync(journal.KeepId, excluded, keep.SettingsVersion, ct)
.ConfigureAwait(false);
if (journal.KeepSettingsVersion == keep.SettingsVersion) journal.KeepSettingsVersion = updated.SettingsVersion;
return;
}
catch (SyncConflictChangedException) when (attempt < 3)
{
// Edited between the read and the lease: read again.
}
}
}
/// <summary>
/// Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the
/// kept sequence. <paramref name="planned"/>: the plan knew the photo's content (else a tombstone of the kept sequence
@@ -598,7 +643,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
var keepRemoved = (await _db.FrameRemovals.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false))
.Select(r => r.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var failed = new List<(Guid FrameId, string Sha256)>();
var failed = new List<(Guid FrameId, string Sha256, bool Unhashed)>();
foreach (var frame in dropFrames)
{
_ct.ThrowIfCancellationRequested();
@@ -625,13 +670,14 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
{
// Compared by size and time only, and another photo after all: filed in the kept sequence as a second version.
var filed = await FileAsync(frame, sha, planned: false).ConfigureAwait(false);
await LeaveOutOfMainAsync(sha).ConfigureAwait(false);
journal.SecondVersions.Add(frame.Id);
journal.Verified[frame.Id] = new MergeVerified(sha, filed.FrameId);
held.TryAdd(sha, filed.FrameId);
Save();
continue;
}
failed.Add((frame.Id, sha));
failed.Add((frame.Id, sha, frame.Sha256 is not { Length: > 0 }));
}
if (failed.Count > 0)
{
@@ -639,7 +685,16 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
// sequence's index rows prove nothing: its files were hashed again above and did not hold it.
var others = await new CopySides(_db).HeldElsewhereAsync([.. failed.Select(f => f.Sha256)], [journal.DropId, journal.KeepId], _ct)
.ConfigureAwait(false);
var lost = failed.Where(f => !others.Contains(f.Sha256)).Select(f => f.Sha256).Distinct(StringComparer.Ordinal).Count();
var lostFrames = failed.Where(f => !others.Contains(f.Sha256)).ToList();
if (lostFrames.Any(f => f.Unhashed && keepRemoved.Contains(f.Sha256)))
{
// Content the kept sequence deleted, which the plan never compared by content (unhashed, matched by size
// and time): a last copy the plan did not list. Retrying this journal would fail the same way: it goes,
// and the new plan lists it.
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));
// Held by a third sequence now: asked again before the trash, which that sequence may not wait for.
+14 -3
View File
@@ -124,10 +124,10 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
var here = await _sides.LocalAsync(keep, ct).ConfigureAwait(false);
var there = await _sides.LocalAsync(drop, ct).ConfigureAwait(false);
var comparison = CopyComparer.Compare(here, there);
if (online && await HashOnlyThereAsync(comparison, there, dropPaths, ct).ConfigureAwait(false) is { } hashed)
if (online && await HashUnhashedThereAsync(comparison, there, dropPaths, here.Removed.Count > 0, ct).ConfigureAwait(false) is { } hashed)
{
// Compared by content now: a photo the kept sequence deleted reads Deleted here (a last copy when nothing else
// holds it), never a copy the kept sequence's tombstone refuses.
// holds it), never a copy the kept sequence's tombstone refuses nor a photo the verify cannot find held.
there = hashed;
comparison = CopyComparer.Compare(here, there);
}
@@ -288,11 +288,22 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
/// <summary>
/// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none.
/// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted.
/// When the kept sequence has tombstones (<paramref name="keepDeleted"/>), also every unhashed frame of the other that
/// the comparison matched by size and time with a photo of the kept one (<see cref="PhotoClass.SameUnhashed"/>, each
/// frame of that size and instant): one of them may be content the kept sequence deleted (a burst of one size in one
/// whole second), which nothing would copy, list or find held, so the merge would fail at its verify on every retry.
/// </summary>
private async Task<CopySideInput?> HashOnlyThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, CancellationToken ct)
private async Task<CopySideInput?> HashUnhashedThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, bool keepDeleted,
CancellationToken ct)
{
var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal))
.Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
if (keepDeleted)
{
foreach (var photo in comparison.Photos)
if (photo is { Class: PhotoClass.SameUnhashed, There: { Sha256: null or { Length: 0 }, CapturedAt: not null } theirs })
keys.Add(CopyComparer.UnhashedKey(theirs.Size, theirs.CapturedAt, theirs.FrameId));
}
if (keys.Count == 0) return null;
var photos = new List<CopyPhotoInput>(there.Photos.Count);
var changed = false;
+23 -4
View File
@@ -199,14 +199,20 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
}
/// <summary>
/// A 404 for the remote side (design §6.3): nothing when <paramref name="localId"/> is null (an observation-only link);
/// else 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.
/// 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
/// (<see cref="SettleUnlinkedGoneAsync"/>).
/// </summary>
public async Task MarkRemoteGoneAsync(string server, Guid remoteId, Guid? localId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(server);
if (localId is not { } local) return;
if (localId is not { } local)
{
await SettleUnlinkedGoneAsync(server, remoteId, ct).ConfigureAwait(false);
return;
}
var refreshes = GoneRefreshes.GetOrCreateValue(db.Database);
var counted = refreshes.TryGetValue((server, remoteId), out var last) && last == refreshId;
await _db.InTransactionAsync(async session =>
@@ -231,6 +237,19 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
refreshes[(server, remoteId)] = refreshId;
}
/// <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.
/// </summary>
public Task SettleUnlinkedGoneAsync(string server, Guid remoteId, 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);
}
/// <summary>The server answered for the remote again: hits back to 0, no gone time.</summary>
public Task ClearRemoteGoneAsync(string server, Guid remoteId, CancellationToken ct)
{
+8 -6
View File
@@ -985,10 +985,11 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary>
/// The session key the first original of a download without a local copy goes under: the server sequence's own
/// (<see cref="SyncService.SessionKey"/>), which groups the download in the local sequence an earlier download of it made,
/// unless that sequence has been unlinked or kept apart from it, or linked to another sequence of this server since (it
/// has a pair or a link for this server). The user chose to keep such a sequence separate: the 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.
/// (<see cref="SyncService.SessionKey"/>), which groups the download in the local sequence an earlier download of it made
/// (refilled and linked again: a link a 404 forgot, a pair asked about again), unless the user separated that sequence
/// from it: their pair is Kept apart (kept apart, or unlinked), or it is linked to another sequence of this server. Such
/// 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)
{
@@ -996,8 +997,9 @@ internal sealed class SyncTransfers(SyncService sync)
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.Kind == CopyKind.LocalServer && string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == holder)
|| await sync.Links.FindByLocalAsync(remote.Server, holder, ct).ConfigureAwait(false) is not null;
.Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart } && string.Equals(c.Server, remote.Server, StringComparison.Ordinal)
&& c.LocalId == holder && c.RemoteId == remoteId)
|| 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;
}