diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index f390e9d3..3412ca3b 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -231,6 +231,18 @@ match. A 1.1 server works as before, without Integrate; a 1.2 server adds the ph
of duplicating every photo into a new local sequence.
- A match whose server sequence was deleted, with no local copy linked to it, goes: *Upload all local* sends the
local sequence again and the Library stops reading it as a copy found.
+ - A merge whose photo held by a third sequence is held nowhere by the time of its verify asks for a new comparison,
+ which lists it as a last copy, instead of failing with "did not match after copying" on every retry.
+ - A background sync no longer pushes or pulls the details of a pair being integrated, and the Integrate stops
+ instead of taking this PC's own value over a line the user decided as the server's.
+ - A *Keep apart* answer survives a server sequence answering 404 for a moment: it is counted as a linked pair's 404
+ is, so the pair is neither asked again nor linked by itself; only a confirmed deletion lets *Upload all local*
+ send the local sequence.
+ - Download originals into the local copy of a pair asked about again keeps the photos deleted there deleted and
+ compares its details instead of overwriting them with the server's.
+ - An upload of a sequence asked about again makes a new server sequence instead of joining, re-linking and
+ overwriting the one an earlier upload made; one that joins a server sequence this PC already knows compares its
+ details instead of overwriting them.
## [1.1.1] — 2026-11-16
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index de50fa3f..b73a1384 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -1023,3 +1023,8 @@ One line per decision: date · decision · alternative · reason.
| 2026-11-18 | A merge plan whose kept sequence has tombstones also hashes in memory the other's unhashed frames matched by size and time (every frame of that size and instant); a verify that finds unhashed content the kept sequence deleted, held nowhere and not listed, drops the journal and fails as a stale plan (#73) | Hash them always | Only a tombstone makes such a frame a last copy nothing lists; the rest the verify files as a second version, and an adopted folder is not hashed twice for nothing |
| 2026-11-18 | Supersedes the 2026-11-18 download-key row: Download originals goes under a key of the job only when the holder of the server sequence's own key is Kept apart from that server sequence (kept apart or unlinked) or linked to another sequence of that server; a Candidate, Linked or Integrated pair, a pair with another server sequence, or a link a 404 forgot keeps the own key, so the download refills and links its own local copy (#73) | Any pair or link for that server | A link a 404 forgot left a Candidate pair, and the download duplicated every photo into a new local sequence |
| 2026-11-18 | A 404 for a server sequence no local copy is linked to (an observation-only link) deletes the Candidate and Kept apart pairs naming it (`FoundCopyStore.SettleUnlinkedGoneAsync`); Linked, Integrated and Integrating pairs are left to their link's 404 (#73) | Count the hit on those pairs (read as deleted on the server) | Neither is a copy of anything the server still has: Upload all local must send the local sequence, and a server sequence listed again is found anew |
+| 2026-11-18 | A merge verify that finds a hashed photo of the other the plan did not copy (held by a third sequence when planned) held by nothing now drops the journal and fails as a stale plan; "did not match after copying" stays, with the journal kept, for a photo the plan copied that the kept sequence does not hold (#73) | Keep the journal and let a retry ask the third sequence again | A third copy gone never comes back: every retry failed the same way, and the new plan lists the photo as a last copy |
+| 2026-11-18 | A comparison settles no details (push, pull or conflict) of a pair whose found-copy row reads Integrating; the Integrate's Details stage also refuses (details changed, photos kept) a line the user decided as the server's whose server value is now this PC's planned one, instead of absorbing it (#73) | Count the Integrate's ids in the transfers an event refresh skips | The planner's own Busy check reads that set, and the photos must still be compared; only the settling reversed the user's line-by-line choice (owner Q4) |
+| 2026-11-18 | Supersedes the 2026-11-18 unlinked-404 row: a 404 for a server sequence no local copy is linked to deletes only its Candidate pairs; each Kept apart pair naming it counts the hit as a linked pair does (once per refresh, a second only after `GoneRecheck`), a listing clears the count, and Upload all local sends the local sequence only once the pair reads deleted on the server (two hits) (#73) | Count observation links in the sweep test | A single 404 (trash and restore, access withdrawn for a moment) erased the Keep apart answer, and the pair was asked again or linked by itself (owner Q1) |
+| 2026-11-18 | Download originals whose server-sequence key names a local copy paired with that server sequence (Candidate, Linked or Integrated, no link) links that copy first and fills it as a linked copy (its tombstones honoured), then compares it as a new link instead of taking the server's details; a holder with no pair (a run that stopped before linking) is joined as before (#73) | Use a key of the job for a Candidate holder too | The round-9 rule refills the local copy a 404 or Ask again left without a link; treated as new it got photos deleted here back and lost its details (owner Q3, Q4, Q6) |
+| 2026-11-18 | An upload without a target goes under a key of the job when its local sequence has a Candidate or Kept apart pair with that server, and one whose first original joins a server sequence this PC already knows (listed, linked or paired) compares it as a new link instead of sending all its details (#73) | Keep the own key for a Candidate pair | The own key filed the photos into the sequence an earlier upload made, linked it unasked and overwrote edits made there (owner Q1, Q4) |
diff --git a/src/Chronos.Data/Archiving/Jobs/MergeJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/MergeJobHandler.cs
index 9777bb3c..20e47f80 100644
--- a/src/Chronos.Data/Archiving/Jobs/MergeJobHandler.cs
+++ b/src/Chronos.Data/Archiving/Jobs/MergeJobHandler.cs
@@ -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));
diff --git a/src/Chronos.Data/Copies/FoundCopyStore.cs b/src/Chronos.Data/Copies/FoundCopyStore.cs
index 9f8de8fb..b8f8c500 100644
--- a/src/Chronos.Data/Copies/FoundCopyStore.cs
+++ b/src/Chronos.Data/Copies/FoundCopyStore.cs
@@ -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
/// , and a hit after the first only once has passed since it, and
/// every Candidate row naming that remote is deleted. With 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
/// ().
///
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
}
///
- /// 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 , a second only once
+ /// 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 () lets Upload all local send the local sequence
+ /// (). Linked, Integrated and Integrating rows are left to their link's own 404.
///
- 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;
}
/// The server answered for the remote again: hits back to 0, no gone time.
diff --git a/src/Chronos.Data/Copies/UploadAllRule.cs b/src/Chronos.Data/Copies/UploadAllRule.cs
index b611a0b2..11522c57 100644
--- a/src/Chronos.Data/Copies/UploadAllRule.cs
+++ b/src/Chronos.Data/Copies/UploadAllRule.cs
@@ -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
diff --git a/src/Chronos.Data/Sync/SyncService.cs b/src/Chronos.Data/Sync/SyncService.cs
index cb69b5f2..37d678e8 100644
--- a/src/Chronos.Data/Sync/SyncService.cs
+++ b/src/Chronos.Data/Sync/SyncService.cs
@@ -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;
diff --git a/src/Chronos.Data/Sync/SyncTransfers.cs b/src/Chronos.Data/Sync/SyncTransfers.cs
index 3e444dc9..155bd0b0 100644
--- a/src/Chronos.Data/Sync/SyncTransfers.cs
+++ b/src/Chronos.Data/Sync/SyncTransfers.cs
@@ -81,6 +81,9 @@ internal sealed class SyncTransfers(SyncService sync)
// is filed into the new sequence once there is one).
var heldElsewhere = new List();
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)
///
/// The session key the first original of an upload without a target goes under: this sequence's own
- /// (), 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).
+ /// (), 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).
///
private async Task 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.
///
- private async Task DownloadKeyAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid archiveId)
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ /// The server sequences of this PC knows of: listed or linked, or paired with .
+ private async Task> 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 ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
diff --git a/tests/Chronos.Data.Tests/Archiving/SequenceMergerTests.cs b/tests/Chronos.Data.Tests/Archiving/SequenceMergerTests.cs
index 6c53c309..cc4e8b38 100644
--- a/tests/Chronos.Data.Tests/Archiving/SequenceMergerTests.cs
+++ b/tests/Chronos.Data.Tests/Archiving/SequenceMergerTests.cs
@@ -1093,6 +1093,43 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
Assert.Contains(again.LastCopies, l => l.Key == Sha(5, 30_250));
}
+ [Test]
+ public async Task APhotoHeldByAThirdSequenceThatIsGoneByTheVerifyMakesTheRetryPlanAgain()
+ {
+ var fx = await FixtureAsync();
+ var keep = await SequenceAsync(fx, "keep", [(1, 0, "IMG_0001.JPG"), (4, 30_250, "IMG_0004.JPG")]);
+ var drop = await SequenceAsync(fx, "drop", [(1, 0, "IMG_0001.JPG"), (5, 30_250, "IMG_0004.JPG")]);
+ // A third sequence holds the other's losing version: not a last copy when planned.
+ var third = await SequenceAsync(fx, "third", [(5, 30_250, "IMG_0004.JPG")]);
+ var copy = await PairAsync(fx, keep.Id, drop.Id);
+ var merger = Merger(fx);
+ var (engine, handler) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
+ await engine.StartAsync(Ct);
+ var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.ThisPcWins), NoContext, Ct);
+ Assert.Empty(plan.LastCopies);
+ handler.BeforeStage = async stage =>
+ {
+ if (stage == MergeStage.Verify) await fx.Db.Sequences.DeleteAsync(third.Id, Ct);
+ };
+
+ var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
+ var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
+
+ // A last copy the plan did not list, not a failed copy: the journal goes and nothing goes to the trash.
+ Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
+ Assert.Contains(Sha(5, 30_250), await HashesAsync(fx, drop.Id));
+ Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)), "the next run plans again");
+
+ // The Retry asks for a new comparison instead of the same verify error, and the new plan lists the photo.
+ handler.BeforeStage = null;
+ await engine.ResumeAsync(job.Id, Ct);
+ failed = await fx.WaitForAsync(job.Id, JobState.Failed);
+ Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
+ Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
+ var again = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.ThisPcWins), NoContext, Ct);
+ Assert.Contains(again.LastCopies, l => l.Key == Sha(5, 30_250));
+ }
+
[Test]
public async Task APhotoAddedToTheOtherOrDeletedFromTheKeptOneMeanwhileKeepsTheOtherOutOfTheTrash()
{
diff --git a/tests/Chronos.Data.Tests/Copies/FoundCopyStoreTests.cs b/tests/Chronos.Data.Tests/Copies/FoundCopyStoreTests.cs
index ce73aa7d..4fb8722e 100644
--- a/tests/Chronos.Data.Tests/Copies/FoundCopyStoreTests.cs
+++ b/tests/Chronos.Data.Tests/Copies/FoundCopyStoreTests.cs
@@ -276,7 +276,7 @@ public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(
}
[Test]
- public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsUnlinkedMatches()
+ public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsCandidatesAndCountsOnItsKeptApartAnswers()
{
var (db, _, s) = await SetupAsync(4);
var store = new FoundCopyStore(db);
@@ -289,18 +289,35 @@ public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(
var elsewhere = await store.UpsertFoundAsync(Remote(s[3].Id, Guid.CreateVersion7()), Ct);
// An observation-only link answers 404: no local copy is linked to it.
- await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now, Ct);
+ var first = Guid.NewGuid();
+ await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now, Ct);
+ await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(1), Ct);
- // Its matches nobody linked are gone, so Upload all local reads their local sequences as local only again.
+ // The unanswered match is gone; the Keep apart answer stays and counts the 404 once, not read as deleted yet.
Assert.Null(await store.GetAsync(candidate.Id, Ct));
- Assert.Null(await store.GetAsync(apart.Id, Ct));
+ var row = (await store.GetAsync(apart.Id, Ct))!;
+ Assert.Equal((CopyState.KeptApart, 1, false), (row.State, row.RemoteGoneHits, row.RemoteGone));
Assert.Equal(CopyState.Linked, (await store.GetAsync(linked.Id, Ct))!.State);
Assert.Equal(CopyState.Candidate, (await store.GetAsync(elsewhere.Id, Ct))!.State);
- var left = await store.ListAsync(Ct);
var entries = s[..2].Select(q => new SyncEntry(q, null, SyncStatus.LocalOnly)).ToList();
- var (upload, skipped) = UploadAllRule.Select(entries, left, new HashSet(), new HashSet());
+ var (upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet(), new HashSet());
+ Assert.Equal(s[0].Id, upload.Single().Local!.Id);
+ Assert.Equal((s[1].Id, UploadSkip.DeletedOnServer), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
+
+ // A second 404 within the re-check is the same moment; one after it confirms the deletion.
+ await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddMinutes(5), Ct);
+ Assert.Equal(1, (await store.GetAsync(apart.Id, Ct))!.RemoteGoneHits);
+ await store.MarkRemoteGoneAsync(Nas, remote, null, Guid.NewGuid(), TestData.Now.AddHours(1), Ct);
+ row = (await store.GetAsync(apart.Id, Ct))!;
+ Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
+ (upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet(), new HashSet());
Assert.Empty(skipped);
Assert.Count(2, upload);
+
+ // Listed again: the count clears and the answer is the user's as before.
+ await store.ClearRemoteGoneAsync(Nas, remote, Ct);
+ row = (await store.GetAsync(apart.Id, Ct))!;
+ Assert.Equal((CopyState.KeptApart, 0), (row.State, row.RemoteGoneHits));
}
[Test]
diff --git a/tests/Chronos.Data.Tests/Copies/IntegrateTests.cs b/tests/Chronos.Data.Tests/Copies/IntegrateTests.cs
index 7a91a8e7..03466f58 100644
--- a/tests/Chronos.Data.Tests/Copies/IntegrateTests.cs
+++ b/tests/Chronos.Data.Tests/Copies/IntegrateTests.cs
@@ -800,6 +800,73 @@ public sealed class IntegrateTests(TestContext context)
Assert.Equal("Comet (night)", remote.Title);
}
+ ///
+ /// A linked pair whose details were agreed, then edited on this PC (Window41, not sent yet), with every detail line
+ /// decided as the server's (Window33): the plan of an Integrate the user confirmed.
+ ///
+ private static async Task<(Sequence Local, FakeSequence Remote, FoundCopy Pair, IntegratePlan Plan)> EditedHereServerChosenAsync(SyncFixture f)
+ {
+ var photos = f.NewPhotos(3);
+ var local = await f.LocalAsync("Comet", photos.Take(2).ToList(), SyncFixture.Window33);
+ var remote = f.Remote.Add("Comet", [photos[0], photos[2]], SyncFixture.Window33);
+ await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
+ await f.Sync.RefreshSequencesAsync(f.Remote, [remote.Id], new SyncPolicy(AutoSyncSettings: false), f.Ct);
+ Assert.Equal(local.SettingsVersion, (await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct))!.BaseLocalSettings);
+ local = await f.EditLocalSettingsAsync(local.Id, SyncFixture.Window41);
+ var pair = (await f.Sync.Copies.FindRemoteAsync(local.Id, f.Server, remote.Id, f.Ct))!;
+ var choices = await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.Union);
+ Assert.NotEmpty(choices.Details);
+ choices = choices with { Details = choices.Details.ToDictionary(d => d.Key, _ => CopySide.Other) };
+ var plan = await Planner(f).PlanAsync(f.Remote, pair, choices, PlanContext(), f.Ct);
+ return (local, remote, pair, plan);
+ }
+
+ [Test]
+ public async Task ABackgroundSyncDuringTheIntegrateLeavesTheDetailsToTheUsersChoice()
+ {
+ await using var f = await FixtureAsync(context);
+ var (engine, handler) = Engine(f);
+ await using var _ = engine;
+ await engine.StartAsync(f.Ct);
+ var (local, remote, _, plan) = await EditedHereServerChosenAsync(f);
+ // The server fires sequenceChanged as the photos land (or the periodic refresh runs): the agent compares the pair.
+ handler.BeforeStage = async stage =>
+ {
+ if (stage == IntegrateStage.Details) await f.Sync.RefreshSequencesAsync(f.Remote, [remote.Id], new SyncPolicy(), f.Ct);
+ };
+
+ var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
+ await f.Archive.WaitForAsync(job.Id, JobState.Done);
+
+ // The server's settings the user kept are on both sides: this PC's edit was not pushed over them meanwhile.
+ Assert.True(SyncRules.SameSettings(SyncFixture.Window33, remote.SettingsJson), remote.SettingsJson);
+ Assert.True(SyncRules.SameSettings(SyncFixture.Window33, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.SettingsJson));
+ }
+
+ [Test]
+ public async Task AServerValueThatIsThisPcsOwnOverALineDecidedAsTheServersStopsTheDetails()
+ {
+ await using var f = await FixtureAsync(context);
+ var (engine, handler) = Engine(f);
+ await using var _ = engine;
+ await engine.StartAsync(f.Ct);
+ var (local, remote, pair, plan) = await EditedHereServerChosenAsync(f);
+ // This PC's planned value reaches the server while the photos travel (a push the job did not make).
+ handler.BeforeStage = stage =>
+ {
+ if (stage == IntegrateStage.Photos) f.Remote.EditSettings(remote.Id, SyncFixture.Window41);
+ return Task.CompletedTask;
+ };
+
+ var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
+ var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
+
+ // Not absorbed as a newer edit, which would reverse the user's choice on both sides: the details stop, the photos stay.
+ Assert.Equal(Loc.L("Errors.Copies.DetailsChanged"), failed.Error);
+ Assert.Equal(CopyState.Linked, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
+ Assert.Equal(3, RemoteHashes(remote).Count);
+ }
+
[Test]
public async Task ACancelledQueuedJobSetsThePairBack()
{
diff --git a/tests/Chronos.Data.Tests/Sync/SyncServiceCopyTests.cs b/tests/Chronos.Data.Tests/Sync/SyncServiceCopyTests.cs
index 3d1535f5..f95be102 100644
--- a/tests/Chronos.Data.Tests/Sync/SyncServiceCopyTests.cs
+++ b/tests/Chronos.Data.Tests/Sync/SyncServiceCopyTests.cs
@@ -203,6 +203,34 @@ public sealed class SyncServiceCopyTests(TestContext context)
Assert.Equal(local.Id, upload.Single().Local!.Id);
}
+ [Test]
+ public async Task AKeptApartServerSequenceAnswering404OnceKeepsTheAnswerAndIsNeverLinkedByItself()
+ {
+ await using var f = await SyncFixture.CreateAsync(context);
+ var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
+ var photos = f.NewPhotos(3);
+ var local = await f.LocalAsync("Comet", photos);
+ var remote = nas.Add("2026-09-28 Canon", photos);
+ remote.FirstCapture = local.FirstCapture;
+ remote.CameraModel = local.CameraModel;
+ await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
+ var pair = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
+ Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.Candidate, CopyState.KeptApart,
+ new CopyAnswer(pair.Fingerprint, pair.Score.Shared, null, false, DateTimeOffset.UtcNow), f.Ct));
+
+ // Moved to the server's trash and restored: one refresh gets a 404, the next lists it again.
+ nas.Sequences.Remove(remote.Id);
+ await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
+ Assert.Equal((CopyState.KeptApart, 1), ((await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.RemoteGoneHits));
+ nas.Sequences[remote.Id] = remote;
+ await f.Sync.RefreshAsync(nas, new SyncPolicy { Linking = CopyLinking.WhenIdentical }, f.Ct);
+
+ // Keep separate is remembered (owner Q1): not asked again, and not linked although the photos are identical.
+ var after = (await f.Sync.Copies.ListByServerAsync(nas.Server, f.Ct)).Single();
+ Assert.Equal((pair.Id, CopyState.KeptApart, 0), (after.Id, after.State, after.RemoteGoneHits));
+ Assert.Null(await f.Sync.LinkOfAsync(nas.Server, local.Id, f.Ct));
+ }
+
[Test]
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
{
diff --git a/tests/Chronos.Data.Tests/Sync/SyncTransferCopyTests.cs b/tests/Chronos.Data.Tests/Sync/SyncTransferCopyTests.cs
index c77d5a0e..212c561a 100644
--- a/tests/Chronos.Data.Tests/Sync/SyncTransferCopyTests.cs
+++ b/tests/Chronos.Data.Tests/Sync/SyncTransferCopyTests.cs
@@ -292,6 +292,108 @@ public sealed class SyncTransferCopyTests(TestContext context)
Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
}
+ [Test]
+ public async Task DownloadingAgainIntoTheOwnLocalCopyOfAPairAskedAgainKeepsItsDeletionsAndDetails()
+ {
+ await using var f = Capable(await SyncFixture.CreateAsync(context));
+ var photos = f.NewPhotos(3);
+ var remote = f.Remote.Add("Comet", photos);
+ var engine = await f.StartEngineAsync();
+ var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
+ await f.Archive.WaitForAsync(job.Id, JobState.Done);
+ var local = Assert.NotNull(Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
+ await WaitIdleAsync(f, local);
+
+ // While linked: one photo deleted here (the server keeps it, owner Q6) and the title edited; then unlinked and
+ // asked about again (Ask again, or a Keep apart undone).
+ var sequence = (await f.Db.Sequences.GetAsync(local, f.Ct))!;
+ var gone = (await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct))[0];
+ var delete = await f.Archive.Service.FrameTrash.PlanDeleteAsync(local, [gone.Id], sequence.FramesVersion, f.Ct);
+ await f.Archive.Service.FrameTrash.DeleteAsync(delete, cancellationToken: f.Ct);
+ await f.Db.Sequences.EditAsync(local, new SequenceEdit { Title = "Mine" }, null, f.Ct);
+ await f.Sync.UnlinkAsync(f.Server, remote.Id, local, f.Ct);
+ var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == remote.Id && c.LocalId == local);
+ Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
+
+ // Download originals of the server sequence: it refills its own local copy, as a linked copy.
+ job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Comet", SyncDownloadMode.Originals, f.Archive.Archive.Id);
+ await f.Archive.WaitForAsync(job.Id, JobState.Done);
+
+ // The photo deleted here stays deleted, and the title is not overwritten by the server's.
+ Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
+ Assert.Count(2, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
+ Assert.Contains(gone.Sha256, (await f.Db.FrameRemovals.ListBySequenceAsync(local, f.Ct)).Select(r => r.Sha256));
+ Assert.Equal("Mine", (await f.Db.Sequences.GetAsync(local, f.Ct))!.Title);
+ Assert.Equal("Comet", remote.Title);
+ Assert.Equal(1, (await f.Db.Sequences.ListAsync(new SequenceQuery(), f.Ct)).Items.Count);
+ }
+
+ [Test]
+ public async Task AnUploadOfASequenceAskedAboutAgainMakesANewServerSequenceAndLeavesTheOtherAlone()
+ {
+ await using var f = Capable(await SyncFixture.CreateAsync(context));
+ var photos = f.NewPhotos(3);
+ var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
+ var engine = await f.StartEngineAsync();
+ var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
+ await f.Archive.WaitForAsync(job.Id, JobState.Done);
+ var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
+ // Unlinked, then asked about again: the pair is a Candidate and nothing links the two.
+ await f.Sync.UnlinkAsync(f.Server, first, local.Id, f.Ct);
+ var pair = (await f.Sync.Copies.ListByServerAsync(f.Server, f.Ct)).Single(c => c.RemoteId == first);
+ Assert.True(await f.Sync.Copies.SetStateAsync(pair.Id, CopyState.KeptApart, CopyState.Candidate, null, f.Ct));
+ // Renamed on the server (the web, another desktop); a new photo here.
+ var server = f.Remote.Sequences[first];
+ server.Title = "Comet NAS";
+ server.SettingsVersion++;
+ server.UpdatedAt = DateTimeOffset.UtcNow;
+ await f.AddLocalAsync(local.Id, photos[2]);
+
+ job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
+ await f.Archive.WaitForAsync(job.Id, JobState.Done);
+
+ // The other is not joined through the key, linked unasked or overwritten: a new server sequence holds every photo.
+ Assert.Equal("Comet NAS", server.Title);
+ Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals([Sha(photos[0]), Sha(photos[1])]));
+ Assert.Equal(CopyState.Candidate, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
+ Assert.Null((await f.Sync.Links.GetAsync(f.Server, first, f.Ct))!.LocalId);
+ var link = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct));
+ Assert.NotEqual(first, link.RemoteId);
+ Assert.True(f.Remote.Sequences[link.RemoteId].Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
+ }
+
+ [Test]
+ public async Task AnUploadThatJoinsAServerSequenceItKnowsAlreadyComparesItsDetailsInsteadOfOverwritingThem()
+ {
+ await using var f = Capable(await SyncFixture.CreateAsync(context));
+ var photos = f.NewPhotos(3);
+ var local = await f.LocalAsync("Comet", [photos[0], photos[1]]);
+ var engine = await f.StartEngineAsync();
+ var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
+ await f.Archive.WaitForAsync(job.Id, JobState.Done);
+ var first = Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId;
+ // The link and its pair were forgotten (a sweep of 404s: the server served another archive for a while); the
+ // server sequence is listed again, as an observation.
+ var observed = Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, first, f.Ct)) with { LocalId = null };
+ await f.Sync.Links.UpsertAsync(observed, f.Ct);
+ await using (var session = await f.Db.Database.OpenAsync(f.Ct))
+ await session.ExecuteAsync("DELETE FROM found_copies WHERE remote_id = $1", [first], f.Ct);
+ var server = f.Remote.Sequences[first];
+ server.Title = "Comet NAS";
+ server.SettingsVersion++;
+ server.UpdatedAt = DateTimeOffset.UtcNow;
+ await f.AddLocalAsync(local.Id, photos[2]);
+
+ job = await f.Sync.EnqueueUploadAsync(engine, f.Server, (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!);
+ await f.Archive.WaitForAsync(job.Id, JobState.Done);
+
+ // Joined through this sequence's key, not made by this upload: the server's title is not overwritten unseen.
+ Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
+ Assert.True(server.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
+ Assert.Equal("Comet NAS", server.Title);
+ Assert.Equal("Comet", (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Title);
+ }
+
[Test]
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
{