fix(copies): close the owner review 6 verification findings

A merge could still trash photos it never verified, resume against a
pair the user had answered meanwhile, and take different unhashed
photos for copies; the dialog and the lists worded several facts
wrongly or lost them on refresh.

- Merge: a retry resumes only while the pair is still the job's;
  Verify requires the other archive online and its folder in place,
  stops on an unreadable photo, files a differing unhashed photo as a
  second version and must cover every frame before Trash; the plan
  hashes unmatched unhashed photos first, lists "Deleted in the other"
  and names the relinked servers; second versions stay discoverable
  (CopySides.VersionsAsync).
- Integrate: a retry after a failure before the journal runs again.
- Sync: a sequence back after a 404 stays Linked while its link holds;
  a local cull no longer asks for attention.
- Block lines of both planners name the right sequence, archive,
  server and space through one formatter.
- Compare dialog: one Details row per setting with worded values,
  Projects headings, Choose focuses the kept-sequence radios, the
  photo selection reaches rows outside the viewport, the Replace
  confirmation lists the losers per side, plan lines read as queued.
- Matches and Library: counts first and grouped, integrating shown as
  a share, local matches name the other archive, the Library keeps its
  match and "deleted on server" statuses across a refresh.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 15:02:39 +01:00
1 parent d10577b175
commit b34b6b6fe0
41 files changed
+1046 -193

No files matched your search

@@ -45,6 +45,8 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
private IWorkspaceGuard Workspace => workspace;
private SequenceMerger Merger => merger;
/// <summary>Called before each stage runs (tests: a crash, a change made between stages).</summary>
internal Func<MergeStage, Task>? BeforeStage { get; set; }
@@ -58,7 +60,9 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
var keepPaths = new ArchivePaths(keepArchive.RootPath);
try
{
var journal = MergeJournal.Read(keepPaths, job.Id) ?? await StartAsync(context, parameters, keepRow, keepPaths).ConfigureAwait(false);
var journal = MergeJournal.Read(keepPaths, job.Id);
if (journal is null) journal = await StartAsync(context, parameters, keepRow, keepPaths).ConfigureAwait(false);
else await ResumeAsync(job, parameters, keepPaths, ct).ConfigureAwait(false);
var staging = MergeJournal.StagingFor(keepPaths, job.Id);
if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true);
await new Run(this, context, journal, keepArchive, keepPaths).RunAsync().ConfigureAwait(false);
@@ -101,6 +105,28 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
await new FoundCopyStore(db).ReleaseAsync(parameters.CopyId, job.Id, null, keepJob: false, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// A resumed run (a pause, a crash, or a retry after a failure) goes on only while the pair is still this job's: it reads
/// Integrating with this job (a failure keeps both; a Keep apart, an Ask again or another merge since clears them), or
/// it is gone with the other sequence (the trash stage ran before the journal said so). Otherwise the journal is stale:
/// it and its staging go and nothing more is applied; the pair, no longer this job's, is left as it is.
/// </summary>
private async Task ResumeAsync(Job job, MergeJobParameters parameters, ArchivePaths keepPaths, CancellationToken ct)
{
var copy = await new FoundCopyStore(db).GetAsync(parameters.CopyId, ct).ConfigureAwait(false);
if (copy is { State: CopyState.Integrating } && copy.JobId == job.Id) return;
if (copy is null && await db.Sequences.GetAsync(parameters.DropId, ct).ConfigureAwait(false) is null) return;
try
{
MergeJournal.Delete(keepPaths, job.Id);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"The stale journal of merge {job.Id} was not removed", ex);
}
throw new StaleCopyPlanException();
}
/// <summary>The first run: plans again, refuses a plan that moved or is blocked, and journals it.</summary>
private async Task<MergeJournal> StartAsync(JobContext context, MergeJobParameters parameters, Sequence keepRow, ArchivePaths keepPaths)
{
@@ -196,6 +222,31 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
private InvalidOperationException Changed(string title) => new(Loc.L("Errors.Copies.Changed", title));
/// <summary>Drops this run's journal and staging: what it planned no longer holds.</summary>
private void ForgetJournal()
{
try
{
MergeJournal.Delete(keepPaths, journal.JobId);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"The stale journal of merge {journal.JobId} was not removed", ex);
}
}
/// <summary>
/// The other sequence's files are where the index says, on a volume that answers: a verify or a trash never reads an
/// absent drive or a moved folder as "nothing there to lose".
/// </summary>
private void EnsureDropReadable(Sequence drop)
{
if (ArchiveVolume.Probe(_dropPaths) != ArchiveAvailability.Online)
throw new InvalidOperationException(Loc.L("Errors.Copies.ArchiveOffline", _dropTitle));
if (drop.Folder.Length > 0 && !SequenceFolders.Holds(_dropPaths.Sequence(drop.Folder), drop.Id))
throw new InvalidOperationException(Loc.L("Errors.Copies.FolderMoved", _dropTitle));
}
private async Task EnsureDropUnchangedAsync(int expected)
{
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false);
@@ -215,15 +266,19 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
await EnsureDropUnchangedAsync(journal.DropFramesVersion).ConfigureAwait(false);
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).ConfigureAwait(false);
var result = await FileAsync(frame, copy.Sha256, planned: copy.Sha256 is { Length: > 0 }).ConfigureAwait(false);
journal.Committed[copy.DropFrameId] = result.FrameId;
Save();
context.Log(Loc.L("Archive.Log.MergeCopied", copy.FileName));
}
}
/// <summary>Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the kept sequence.</summary>
private async Task<IngestResult> FileAsync(Frame frame, string? expected)
/// <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
/// may refuse it although the plan listed no last copy: the plan is stale, never this job's to retry).
/// </summary>
private async Task<IngestResult> FileAsync(Frame frame, string? expected, bool planned)
{
Directory.CreateDirectory(_staging);
var staged = Path.Combine(_staging, frame.Id.ToString("N") + Path.GetExtension(frame.FileName));
@@ -251,9 +306,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
}
catch (PhotoRemovedException)
{
// Deleted from the kept sequence since the plan: it would be a last copy the plan did not list.
File.Delete(staged);
throw Changed(_keepTitle);
if (planned) throw Changed(_keepTitle); // deleted from the kept sequence since the plan: a last copy the plan did not list
// A photo the plan could not compare by content (unhashed) that the kept sequence deleted: a last copy the
// plan did not list. Retrying this journal would fail the same way: it goes, and the user plans again.
ForgetJournal();
throw new StaleCopyPlanException();
}
if (File.Exists(staged)) File.Delete(staged);
return result;
@@ -365,6 +423,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
{
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
if (drop.FramesVersion != journal.DropFramesVersion) throw Changed(_dropTitle);
EnsureDropReadable(drop);
var keepFrames = await ProcessingFrames.ListAsync(_db, journal.KeepId, _ct).ConfigureAwait(false);
var dropFrames = (await ProcessingFrames.ListAsync(_db, journal.DropId, _ct).ConfigureAwait(false))
.Where(f => (f.Flags & CopySides.UnusableFlags) == 0).ToList();
@@ -380,18 +439,18 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
if (await HashAsync(keepPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false) is { } sha) held.TryAdd(sha, frame.Id);
}
var failed = new List<string>();
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)>();
foreach (var frame in dropFrames)
{
_ct.ThrowIfCancellationRequested();
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Verify, frame.FileName, ++done, total)).ConfigureAwait(false);
if (journal.Verified.ContainsKey(frame.Id)) continue;
var sha = await HashAsync(_dropPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false);
if (sha is null)
{
// Nothing on disk: nothing of it can be lost.
continue;
}
if (journal.Verified.ContainsKey(frame.Id) || journal.Settled.Contains(frame.Id)) continue;
// A usable frame (not flagged Missing) whose file is absent stops the merge (design §5d step 4): it is not
// "nothing to lose" until a verify says so.
var sha = await HashAsync(_dropPaths.FromRelative(frame.RelativePath)).ConfigureAwait(false)
?? throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
if (frame.Sha256 is { Length: > 0 } recorded && !string.Equals(recorded, sha, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
if (held.TryGetValue(sha, out var keepFrame))
@@ -399,26 +458,33 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
journal.Verified[frame.Id] = new MergeVerified(sha, keepFrame);
continue;
}
if (frame.Sha256 is not { Length: > 0 })
if (journal.Absent.Contains(sha))
{
// A last copy the plan listed (or left out by the user's choice).
journal.Settled.Add(frame.Id);
continue;
}
if (frame.Sha256 is not { Length: > 0 } && !keepRemoved.Contains(sha))
{
// 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).ConfigureAwait(false);
var filed = await FileAsync(frame, sha, planned: false).ConfigureAwait(false);
journal.SecondVersions.Add(frame.Id);
journal.Verified[frame.Id] = new MergeVerified(sha, filed.FrameId);
held.TryAdd(sha, filed.FrameId);
Save();
continue;
}
if (journal.Absent.Contains(sha)) continue;
failed.Add(sha);
failed.Add((frame.Id, sha));
}
if (failed.Count > 0)
{
// A photo held by another sequence of the index is not lost with the other; any other is. The kept
// 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, [journal.DropId, journal.KeepId], _ct).ConfigureAwait(false);
var lost = failed.Count(s => !others.Contains(s));
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();
if (lost > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.VerifyFailed", lost));
journal.Settled.AddRange(failed.Select(f => f.FrameId));
}
journal.VerifiedDropFramesVersion = drop.FramesVersion;
Save();
@@ -598,8 +664,16 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
}
if (!journal.LinksMoved)
{
var moved = await new FoundCopyStore(_db).MoveToKeptAsync(journal.DropId, journal.KeepId, keepArchive.Id, journal.SessionKeys, journal.CopyId, _ct)
.ConfigureAwait(false);
MoveResult moved;
try
{
moved = await new FoundCopyStore(_db).MoveToKeptAsync(journal.DropId, journal.KeepId, keepArchive.Id, journal.SessionKeys, journal.CopyId, _ct)
.ConfigureAwait(false);
}
catch (CopyLinkTakenException ex) when (ex.Server is { } key)
{
throw CopyLinkTakenException.BothLinked(key, owner.Merger.ServerName(key));
}
foreach (var key in moved.SkippedKeys) context.Log(key);
journal.LinksMoved = true;
Save();
@@ -617,6 +691,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
throw new InvalidOperationException(Loc.L("Errors.Copies.Unsent", _dropTitle));
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
EnsureDropReadable(drop);
await using (await owner.Archives.Writer.LockAsync(keepPaths, journal.KeepId, _ct).ConfigureAwait(false))
{
await EnsureVerifiedHeldAsync().ConfigureAwait(false);
@@ -636,9 +711,18 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
context.Log(Loc.L("Archive.Log.MergeTrashed", _dropTitle));
}
/// <summary>Every photo the verify found in the kept sequence is still there and usable (read under its lease).</summary>
/// <summary>
/// Every usable photo of the other was verified (held by the kept sequence, or a last copy the plan listed, or held by
/// a third sequence), and every photo the verify found in the kept sequence is still there and usable (read under its lease).
/// </summary>
private async Task EnsureVerifiedHeldAsync()
{
// Every usable photo of the other was verified in this journal: a verify cut short (an absent drive, a moved
// folder) never lets the rest through unread.
var dropFrames = await ProcessingFrames.ListAsync(_db, journal.DropId, _ct).ConfigureAwait(false);
if (dropFrames.Any(f => (f.Flags & CopySides.UnusableFlags) == 0 && !journal.Verified.ContainsKey(f.Id) && !journal.Settled.Contains(f.Id)))
throw Changed(_dropTitle);
var frames = await ProcessingFrames.ListAsync(_db, journal.KeepId, _ct).ConfigureAwait(false);
var byId = frames.Where(f => (f.Flags & CopySides.UnusableFlags) == 0).ToDictionary(f => f.Id);
var hashes = byId.Values.Select(f => f.Sha256).OfType<string>().Select(s => s.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);