fix(copies): close the seventh verification round of owner review 6

- A merge plan hashes the kept sequence's unhashed frames that match a hashed
  photo of the other by size and time: the same content is no longer a false
  last copy, and another content is copied in as a second version instead of
  going to the trash with the other sequence.
- The Replace stage trashes a losing version of the kept sequence only while
  another sequence still holds it or the plan listed it as a last copy;
  otherwise the journal goes and the job fails as a stale plan.
- A details conflict at the merge's or the Integrate's Details stage drops
  the journal, so a retry plans again instead of failing the same way.
- The Integrate's Projects stage keeps a project for good only for a
  permanent refusal; a server out of reach fails the job with the journal
  kept, and the retry finishes the same copy.
- A pair read as deleted on the server is cleared when the server lists it
  again or a link to that sequence is made.
- An upload of a sequence kept apart from a server sequence goes under a
  session key of the job, making a new server sequence; a link made over a
  kept-apart pair moves it to Linked.

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 10:45:11 +01:00
1 parent c3273b7da5
commit 123ceba845
13 files changed
+418 -13

No files matched your search

@@ -227,6 +227,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
Replaces = [.. plan.Photos.Where(p => p.Action == PhotoAction.TrashHere && p.FrameId is not null && winners.GetValueOrDefault(p.Key) is { Length: > 0 })
.Select(p => new MergeReplace(p.Key, p.FrameId!.Value, p.FileName, winners[p.Key]!))],
Absent = [.. plan.LastCopies.Where(l => l.Side == CopySide.Other).Select(l => l.Key.ToLowerInvariant())],
LastHere = [.. plan.LastCopies.Where(l => l.Side == CopySide.ThisPc).Select(l => l.Key.ToLowerInvariant())],
Renders = [.. plan.Renders],
Payload = plan.Payload,
Projects = [.. plan.Projects],
@@ -720,6 +721,13 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
Keep(replace, Loc.L("Archive.Log.KeptReason.NotInPlace"));
continue;
}
if (!await HeldOrListedAsync(loser).ConfigureAwait(false))
{
// Held by another sequence when planned, by nothing now: a last copy the plan did not list. Planned
// again, it is listed.
ForgetJournal();
throw new StaleCopyPlanException();
}
try
{
var plan = await owner.Archives.FrameTrash.PlanDeleteAsync(journal.KeepId, [replace.KeepFrameId], null, _ct, journal.JobId).ConfigureAwait(false);
@@ -747,6 +755,22 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
context.Log(Loc.L("Archive.Log.CopyKept", replace.FileName, why));
}
/// <summary>
/// Whether the losing version <paramref name="loser"/> may go to the trash: a last copy the plan listed, or held by
/// another usable frame of the kept sequence or by another sequence of this index now (the one that held it when
/// planned may have been flagged or deleted while the photos were copied). An unhashed loser was never compared by
/// content and is not asked.
/// </summary>
private async Task<bool> HeldOrListedAsync(Frame loser)
{
if (loser.Sha256 is not { Length: > 0 } recorded) return true;
var sha = recorded.ToLowerInvariant();
if (journal.LastHere.Contains(sha)) return true;
foreach (var frame in await _db.Frames.FindBySha256Async(sha, _ct).ConfigureAwait(false))
if (frame.SequenceId == journal.KeepId && frame.Id != loser.Id && (frame.Flags & CopySides.UnusableFlags) == 0) return true;
return (await new CopySides(_db).HeldElsewhereAsync([sha], [journal.KeepId, journal.DropId], _ct).ConfigureAwait(false)).Contains(sha);
}
/// <summary>Whether a usable frame of the kept sequence holds <paramref name="sha"/>, hashed again.</summary>
private async Task<bool> WinnerInPlaceAsync(string sha)
{
@@ -764,7 +788,17 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
{
if (journal.Payload is null || journal.DetailsDone) return;
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Details)).ConfigureAwait(false);
await new SequencePayloadWriter(_db, owner.Archives).ApplyAsync(journal.KeepId, journal.Payload, journal.KeepSettingsVersion, _ct).ConfigureAwait(false);
try
{
await new SequencePayloadWriter(_db, owner.Archives).ApplyAsync(journal.KeepId, journal.Payload, journal.KeepSettingsVersion, _ct).ConfigureAwait(false);
}
catch (SyncConflictChangedException)
{
// The kept sequence's settings version never goes back: retrying this journal would fail the same way, so it
// goes and the next run plans again.
ForgetJournal();
throw;
}
journal.DetailsDone = true;
Save();
}
@@ -77,6 +77,12 @@ internal sealed class MergeJournal
/// <summary>Raw SHA-256 of drop originals the plan leaves out of the kept sequence (last copies, losers, tombstoned in keep, converted).</summary>
public List<string> Absent { get; set; } = [];
/// <summary>
/// Raw SHA-256 of the kept sequence's losing versions the plan listed as last copies (the user confirmed them): any other
/// loser goes to the trash only while another sequence still holds it.
/// </summary>
public List<string> LastHere { get; set; } = [];
public List<RenderStep> Renders { get; set; } = [];
public SyncPayload? Payload { get; set; }
+40 -1
View File
@@ -131,6 +131,10 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
there = hashed;
comparison = CopyComparer.Compare(here, there);
}
// The kept sequence's unhashed frames matched by size and time with a hashed photo of the other, hashed now (in
// memory): the same content is held (never a last copy); another content is a second photo the merge copies in.
var freshHere = online ? await HashUnhashedHereAsync(comparison, keepPaths, ct).ConfigureAwait(false) : new Dictionary<Guid, string>();
var keepTombstones = here.Removed.Select(r => r.Sha256).ToHashSet(StringComparer.OrdinalIgnoreCase);
var steps = new List<PhotoStep>();
var excluded = new List<string>();
var unchosen = 0;
@@ -142,6 +146,15 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
// Every photo only the other holds is copied: it goes to the trash, nothing it alone holds stays behind.
steps.Add(Step(photo.Key, PhotoAction.Fetch, photo.There!));
break;
case PhotoClass.SameUnhashed when photo is { Here: { } mine, There.Sha256: { Length: > 0 } theirs }
&& freshHere.TryGetValue(mine.FrameId, out var fresh)
&& !string.Equals(fresh, theirs, StringComparison.OrdinalIgnoreCase)
&& !keepTombstones.Contains(theirs):
// Another photo after all (design §5d step 4): the other's version is copied into the kept one as a
// second version, whatever the policy (nothing chose between the two), and left out of its projects.
steps.Add(Step(photo.Key, PhotoAction.FetchVersion, photo.There!));
excluded.Add(theirs.ToLowerInvariant());
break;
case PhotoClass.Differs:
// Under Choose each a photo nobody chose blocks: its other version would go to the trash unasked (Leave,
// which a merge does not offer, keeps the kept sequence's version as Kept does).
@@ -168,6 +181,7 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
var losers = steps.Where(s => s.Action == PhotoAction.TrashHere).Select(s => s.FrameId!.Value).ToHashSet();
var keepHolds = here.Photos.Where(p => !p.Unusable && p.Sha256 is { Length: > 0 } && !losers.Contains(p.FrameId))
.Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
keepHolds.UnionWith(freshHere.Values);
// Photos of the other a verify flagged Corrupt (changed since import, or damaged) or Missing whose file is there: the
// comparison leaves them out, so nothing would copy or hash-verify them before their folder goes to the trash. One
// whose content now nothing else holds (an edited photo's only copy) blocks the merge until it is resolved.
@@ -305,6 +319,31 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
return changed ? there with { Photos = photos } : null;
}
/// <summary>
/// The SHA-256 of each unhashed frame of the kept sequence that the comparison matched by size and time only
/// (<see cref="PhotoClass.SameUnhashed"/>) with a hashed photo of the other, read now (in memory), by frame. Without it a
/// photo of the other read as held by the kept sequence would be listed as a last copy when the content is the same,
/// and go to the trash with the other when it is not. A file that cannot be read is left out.
/// </summary>
private async Task<Dictionary<Guid, string>> HashUnhashedHereAsync(CopyComparisonResult comparison, ArchivePaths keepPaths, CancellationToken ct)
{
var result = new Dictionary<Guid, string>();
foreach (var photo in comparison.Photos)
{
if (photo is not { Class: PhotoClass.SameUnhashed, Here: { Sha256: null or { Length: 0 } } mine, There.Sha256: { Length: > 0 } }) continue;
if (await _db.Frames.GetAsync(mine.FrameId, ct).ConfigureAwait(false) is not { } frame) continue;
try
{
result[frame.Id] = await HashAsync(frame.Id, keepPaths.FromRelative(frame.RelativePath), ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Unreadable now: compared as before (the other's photo is listed as a last copy).
}
}
return result;
}
/// <summary>
/// Whether the other sequence holds a frame flagged unusable (Corrupt, or Missing by an earlier verify although its file
/// is back) whose file is there and whose content, hashed now (in memory), neither the kept sequence
@@ -336,7 +375,7 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
}
/// <summary>
/// The SHA-256 (lower-case) of the other's file <paramref name="path"/> of frame <paramref name="frameId"/>: the one read
/// The SHA-256 (lower-case) of the file <paramref name="path"/> of frame <paramref name="frameId"/>: the one read
/// before while the file keeps its size and last write time (<see cref="_hashes"/>), else read now.
/// </summary>
private async Task<string> HashAsync(Guid frameId, string path, CancellationToken ct)
+4 -2
View File
@@ -162,7 +162,7 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
/// <summary>
/// The row of a link (evidence Link, state Linked) when it has none; the link's row otherwise kept (moved to Linked when it
/// was a Candidate). Any other Linked or Integrated row of the same server sequence, or of the same local sequence and
/// was a Candidate or Kept apart). Any other Linked or Integrated row of the same server sequence, or of the same local sequence and
/// server, is demoted to Candidate (a link re-pointed to another copy: sync_links holds one link per side and server); the
/// local copy's rows with another server sequence that answered 404 are deleted (Upload again).
/// </summary>
@@ -181,8 +181,10 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
row = LinkRow(server, remoteId, localId, now);
await InsertAsync(inner, row, now, ct).ConfigureAwait(false);
}
else if (row.State == CopyState.Candidate)
else if (row.State is CopyState.Candidate or CopyState.KeptApart)
{
// A Kept apart answer never stays on a pair that is linked: the store and the link would disagree (Matches
// would offer no Unlink for a pair that syncs).
await inner.ExecuteAsync("UPDATE found_copies SET state = 2, previous_state = NULL, job_id = NULL, auto_photos = $2, updated_at = $3 WHERE id = $1",
[row.Id, false, now], ct).ConfigureAwait(false);
}
+40 -6
View File
@@ -261,6 +261,13 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
/// <summary>The journal no longer holds: it goes, and <see cref="StaleCopyPlanException"/> is thrown.</summary>
[System.Diagnostics.CodeAnalysis.DoesNotReturn]
private void Stale()
{
Forget();
throw new StaleCopyPlanException();
}
/// <summary>The journal no longer holds: it goes, so the next run plans again.</summary>
private void Forget()
{
try
{
@@ -270,7 +277,6 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
{
Log.Warning("sync", $"The stale journal of Integrate {journal.JobId} was not removed", ex);
}
throw new StaleCopyPlanException();
}
/// <summary>Before a stage that trashes or writes: the pair is still this job's and the link still joins its two sides.</summary>
@@ -449,6 +455,14 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
{
throw await GoneAsync(ex).ConfigureAwait(false);
}
catch (SyncConflictChangedException)
{
// A detail changed on one side since the plan, and that edit never goes back: retrying this journal's
// payloads would fail the same way. It goes, and a retry plans again against both sides as they are now
// (the photos moved so far are found the same there).
Forget();
throw;
}
journal.PayloadRemote = true;
journal.PayloadLocal = true;
journal.FinalPayloadSha = IntegratePlanner.PayloadHash(journal.Payload);
@@ -470,9 +484,14 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
_ct.ThrowIfCancellationRequested();
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Projects, step.TargetName, n, journal.Projects.Count)).ConfigureAwait(false);
var (from, to) = step.From == CopySide.ThisPc ? ((IProjectHome?)localHome, serverHome) : (serverHome, localHome);
if (from is null || to is null)
{
// The server keeps no projects for this PC (none planned there either): kept where it is, for good.
Failed(step, Loc.L("Errors.Copies.ProjectsUnreachable", journal.ServerName ?? journal.Server));
continue;
}
try
{
if (from is null || to is null) throw new HomeUnavailableException(Loc.L("Errors.Copies.ProjectsUnreachable", journal.ServerName ?? journal.Server));
if ((await from.ListAsync(_ct).ConfigureAwait(false)).FirstOrDefault(p => p.Id == step.SourceProjectId) is not { } source)
{
// Deleted at its home since the plan: nothing to copy.
@@ -490,15 +509,30 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
Save();
context.Log(Loc.L("Archive.Log.CopyProject", step.SourceName, step.TargetName));
}
catch (Exception ex) when (ex is not OperationCanceledException)
catch (Exception ex) when (IsRefusal(ex))
{
journal.ProjectsFailed.Add(step.SourceProjectId);
Save();
context.Log(Loc.L("Archive.Log.CopyProjectKept", step.SourceName, ex.Message));
Failed(step, ex.Message);
}
// Anything else (the server out of reach for a moment, a busy database) fails the job with the journal and
// the copy's own step kept: a retry finishes that copy instead of planning it again as a foreign project.
}
}
/// <summary>
/// A refusal that a retry would meet again: a project or version the home refuses or cannot read, a record of another
/// format, a request the server refuses for good. A home out of reach, a network error or a server answer that may
/// change (busy, unavailable) is not.
/// </summary>
private static bool IsRefusal(Exception ex) =>
ex is TransplantFormatException or InvalidDataException or ProjectException or ChronosApiException { IsTransient: false };
private void Failed(ProjectStep step, string why)
{
journal.ProjectsFailed.Add(step.SourceProjectId);
Save();
context.Log(Loc.L("Archive.Log.CopyProjectKept", step.SourceName, why));
}
// ---- done ----
private async Task FinishAsync()
+9 -2
View File
@@ -469,6 +469,8 @@ public sealed class SyncService
?? new SyncLink { Server = server, RemoteId = remoteId, Title = local.DisplayTitle, RemoteUpdatedAt = DateTimeOffset.UtcNow };
if (link.LocalId != local.Id) link = Unlinked(link) with { LocalId = local.Id };
await _links.UpsertAsync(link, cancellationToken).ConfigureAwait(false);
// Linked to that very server sequence, which answered for it: no pair of it reads "deleted on server" any more.
await Copies.ClearRemoteGoneAsync(server, remoteId, cancellationToken).ConfigureAwait(false);
await Copies.EnsureLinkedAsync(server, remoteId, local.Id, cancellationToken).ConfigureAwait(false);
return link;
}
@@ -498,6 +500,7 @@ public sealed class SyncService
{
var linked = Unlinked(Observe(link, remote.Server, dto)) with { LocalId = local.Id };
await ReconcileSafelyAsync(remote, linked, dto, local, locals, policy, cancellationToken).ConfigureAwait(false);
await Copies.ClearRemoteGoneAsync(remote.Server, dto.Id, cancellationToken).ConfigureAwait(false);
await Copies.EnsureLinkedAsync(remote.Server, dto.Id, local.Id, cancellationToken).ConfigureAwait(false);
}
catch
@@ -793,7 +796,8 @@ public sealed class SyncService
}
/// <summary>
/// Pairs one 404 marked (design §6.3): a remote listed again is cleared at once and asked about again; one still unlisted
/// Pairs a 404 marked (design §6.3): a remote listed again is cleared at once and asked about again, also one that read
/// "deleted on server" (restored there, or served again); one marked once and still unlisted
/// is asked for once more, no sooner than <see cref="GoneRecheck"/> after it was marked, and a second 404 there makes the
/// pair read "deleted on server". A refresh's first 404 forgot the link (the pair is asked about again); a job's 404
/// kept it (the pair stays Linked or Integrated).
@@ -804,12 +808,15 @@ public sealed class SyncService
var now = DateTimeOffset.UtcNow;
foreach (var pair in await Copies.ListByServerAsync(remote.Server, cancellationToken).ConfigureAwait(false))
{
if (pair is not { RemoteGoneHits: 1, RemoteId: { } remoteId }) continue;
if (pair is not { RemoteGoneHits: >= 1, RemoteId: { } remoteId }) continue;
if (listed.Contains(remoteId))
{
// Listed again (restored from the server's trash, or the server serves its archive again): whatever the
// count, the server answers for it, so the pair no longer reads "deleted on server".
await BackAsync(pair, remoteId).ConfigureAwait(false);
continue;
}
if (pair.RemoteGoneHits > 1) continue;
// A sweep of 404s (the server serves something else now) confirms no earlier hit either.
if (!confirm || (pair.RemoteGoneAt is { } at && now - at < GoneRecheck)) continue;
try
+17 -1
View File
@@ -80,9 +80,10 @@ internal sealed class SyncTransfers(SyncService sync)
// server has filed one, which creates the sequence (an original it already holds elsewhere creates nothing, and
// 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;
while (remoteId is null && pending.TryDequeue(out var first))
{
var sent = await UploadFrameAsync(context, remote, null, SyncService.SessionKey(local.Id), paths.FromRelative(first.RelativePath), first, tombstones,
var sent = await UploadFrameAsync(context, remote, null, sessionKey, paths.FromRelative(first.RelativePath), first, tombstones,
hashes, ct).ConfigureAwait(false);
if (sent is null) skipped++;
else if (sent.SequenceId == Guid.Empty && sent.FrameId != Guid.Empty) heldElsewhere.Add(first);
@@ -962,6 +963,21 @@ internal sealed class SyncTransfers(SyncService sync)
return (null, true);
}
/// <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).
/// </summary>
private async Task<string> SessionKeyAsync(JobContext context, ISyncRemote remote, Sequence local)
{
var own = SyncService.SessionKey(local.Id);
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);
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
}
private static async Task<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
{
try