fix(copies): address the owner review 6 findings

The review of the found-copies work showed pairs that could stick, jobs that
could act on a pair the user had answered otherwise, and detection gaps:

- forgetting a link on an address-keyed server deletes the pair and Candidate
  rows of that remote and resets the probe, so the sequence is found again
  when it is back; a Linked/Integrated row with no link is asked again
- 404s count only on id-keyed servers, at most once per recheck interval
- probes store the server's newest update time (copy_probes.server_newest,
  migration 0012) instead of comparing with this PC's clock; the lookup
  sample carries hashed photos by size and capture time too, for servers
  that have not hashed their copy
- the older-server gate no longer re-compares unchanged manifests
- a failed Integrate keeps its job id so a retry resumes only an untouched
  pair; cancel and stale plans release the pair (ReleaseAsync)
- automatic photo transfers never create or retarget a sequence
- a first upload files photos the server holds elsewhere into the new
  sequence
- Unlink re-compares before keeping apart; Trash here names only true last
  copies; Drop... trashes one version on both sides after re-checking the
  other
- a merge keeping the pair's other sequence swaps the dialog's columns and
  re-keys Different choices; Upload all reads every pair

Each fix has a regression test where it makes sense.

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 13:12:00 +01:00
1 parent 96b5b4078b
commit fe752a0a21
33 files changed
+957 -123

No files matched your search

+3 -3
View File
@@ -374,13 +374,13 @@ public sealed class SyncAgent : IAsyncDisposable
if (_photoNotBefore.TryGetValue(local.Id, out var notBefore) && DateTime.UtcNow < notBefore) continue;
if (link.MissingRemote > 0 && !_photoJobs.ContainsKey((local.Id, true)))
{
var job = await _sync.EnqueueUploadAsync(_engine!, Server, local, JobPriority.Background, cancellationToken).ConfigureAwait(false);
var job = await _sync.EnqueueAutomaticUploadAsync(_engine!, Server, local, cancellationToken).ConfigureAwait(false);
_photoJobs[(local.Id, true)] = job.Id;
}
if (link.MissingLocal > 0 && !_photoJobs.ContainsKey((local.Id, false)))
{
var job = await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Originals, local.ArchiveId,
JobPriority.Background, cancellationToken).ConfigureAwait(false);
var job = await _sync.EnqueueAutomaticDownloadAsync(_engine!, Server, link.RemoteId, link.Title, local.ArchiveId, cancellationToken)
.ConfigureAwait(false);
_photoJobs[(local.Id, false)] = job.Id;
}
}
+11 -3
View File
@@ -30,8 +30,16 @@ public enum SyncTransferKind
/// sequence for a download.
/// </summary>
/// <param name="ArchiveId">Archive that receives downloaded originals when the sequence has no local copy yet.</param>
internal sealed record SyncJobParameters(string Server, SyncDownloadMode? Mode = null, Guid? ArchiveId = null, SyncUploadMode? Upload = null)
/// <param name="Automatic">
/// The new photos of a pair integrated with automatic photos (owner review 6, design §7.3): they go only into the two
/// sequences of that pair, never into one the job would create or retarget.
/// </param>
internal sealed record SyncJobParameters(string Server, SyncDownloadMode? Mode = null, Guid? ArchiveId = null, SyncUploadMode? Upload = null,
bool? Automatic = null)
{
[JsonIgnore]
public bool IsAutomatic => Automatic == true;
public static SyncJobParameters? Read(Job job)
{
if (job.Kind is not (JobKind.UploadCommit or JobKind.Download) || job.ParametersJson is not { } json) return null;
@@ -74,7 +82,7 @@ internal sealed class SyncJobHandler(JobKind kind, SyncTransfers transfers, ISyn
switch (parameters.Kind(kind))
{
case SyncTransferKind.Upload:
await transfers.UploadAsync(context, remote, target).ConfigureAwait(false);
await transfers.UploadAsync(context, remote, target, parameters.IsAutomatic).ConfigureAwait(false);
break;
case SyncTransferKind.SendExports:
await transfers.SendExportsAsync(context, remote, target).ConfigureAwait(false);
@@ -86,7 +94,7 @@ internal sealed class SyncJobHandler(JobKind kind, SyncTransfers transfers, ISyn
await transfers.GetExportsAsync(context, remote, target).ConfigureAwait(false);
break;
default:
await transfers.DownloadOriginalsAsync(context, remote, target, parameters.ArchiveId).ConfigureAwait(false);
await transfers.DownloadOriginalsAsync(context, remote, target, parameters.ArchiveId, parameters.IsAutomatic).ConfigureAwait(false);
break;
}
}
+29 -6
View File
@@ -75,7 +75,7 @@ public sealed class SyncService
private const int SweepLinks = 5;
/// <summary>How long a pair marked gone once waits before its remote is asked for again (design §6.3).</summary>
private static readonly TimeSpan GoneRecheck = TimeSpan.FromMinutes(10);
private static readonly TimeSpan GoneRecheck = FoundCopyStore.GoneRecheck;
/// <summary>Recomputes states without sending or taking settings on the user's behalf.</summary>
internal static readonly SyncPolicy CompareOnly = new(AutoSyncSettings: false);
@@ -390,6 +390,21 @@ public sealed class SyncService
public Task<Job> EnqueueUploadAsync(JobEngine engine, string server, Sequence local, JobPriority priority, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server), priority, cancellationToken);
/// <summary>
/// Queues, in the background, the new photos of a pair integrated with automatic photos to its server sequence (owner
/// review 6, design §7.3): the job sends only into the sequence the pair names, and fails rather than create another
/// when that one is gone or the pair changed.
/// </summary>
internal Task<Job> EnqueueAutomaticUploadAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server, Automatic: true), JobPriority.Background,
cancellationToken);
/// <summary>The other way of <see cref="EnqueueAutomaticUploadAsync"/>: the server's new photos into the pair's local sequence only.</summary>
internal Task<Job> EnqueueAutomaticDownloadAsync(JobEngine engine, string server, Guid remoteId, string title, Guid archiveId,
CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.Download, remoteId, title, new SyncJobParameters(server, SyncDownloadMode.Originals, archiveId, Automatic: true),
JobPriority.Background, cancellationToken);
/// <summary>Queues sending the renders of a local copy the server lacks (BRIEF §14.5), unless that is already waiting or running.</summary>
public Task<Job> EnqueueSendExportsAsync(JobEngine engine, string server, Sequence local, CancellationToken cancellationToken = default) =>
EnqueueAsync(engine, JobKind.UploadCommit, local.Id, local.DisplayTitle, new SyncJobParameters(server, Upload: SyncUploadMode.Exports), JobPriority.User,
@@ -879,8 +894,9 @@ public sealed class SyncService
/// <summary>
/// Keeps the deletion counts of a linked pair current at each comparison of its originals (design §6.2): photos one side
/// deleted that the other still holds. A pair scored never before (a plain link an upload or download made) gets the
/// whole detection score once, so a Keep apart after an Unlink is measured against what the two held when it was answered.
/// deleted that the other still holds. A pair scored never before (a plain link an upload or download made), or whose
/// photos moved on either side since its score, gets the whole detection score again, so a Keep apart after an Unlink is
/// measured against what the two hold when it is answered.
/// </summary>
private async Task ScoreLinkedAsync(SyncLink link, Sequence local, SequenceManifest manifest, IReadOnlyDictionary<Guid, DateTime?>? captured,
IReadOnlyCollection<FramePhoto> here, IReadOnlyCollection<FramePhoto> there, SyncTombstones tombstones, CancellationToken cancellationToken)
@@ -888,7 +904,8 @@ public sealed class SyncService
if (await Copies.FindRemoteAsync(local.Id, link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false)
is not { State: CopyState.Linked or CopyState.Integrated } row) return;
CopyScore score;
if (row.Score.LocalPhotos == 0 && row.Score.OtherPhotos == 0)
if ((row.Score.LocalPhotos == 0 && row.Score.OtherPhotos == 0)
|| row.LocalFramesVersion != local.FramesVersion || row.OtherFramesVersion != manifest.FramesVersion)
{
var side = await new CopySides(_db).LocalAsync(local.Id, cancellationToken).ConfigureAwait(false);
score = CopyFinder.Detection(CopyComparer.Compare(side, CopyFinder.ServerSide(manifest, captured)).Score) with { Hints = row.Score.Hints };
@@ -1178,12 +1195,16 @@ public sealed class SyncService
/// <summary>
/// Forgets a link the server answered 404 for. With <paramref name="refreshId"/>, on a server keyed by its id (an address
/// key may name another server tomorrow), the pair counts the 404 first (<see cref="FoundCopyStore.MarkRemoteGoneAsync"/>).
/// key may name another server tomorrow), the pair counts the 404 first (<see cref="FoundCopyStore.MarkRemoteGoneAsync"/>);
/// otherwise the pairs the link joined are settled (<see cref="FoundCopyStore.SettleForgottenAsync"/>), never left Linked
/// with no link behind them.
/// </summary>
private async Task ForgetAsync(SyncLink link, Guid? refreshId, CancellationToken cancellationToken)
{
if (refreshId is { } id && ServerIdentity.IsIdKey(link.Server))
await Copies.MarkRemoteGoneAsync(link.Server, link.RemoteId, link.LocalId, id, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false);
else if (link.LocalId is { } localId)
await Copies.SettleForgottenAsync(link.Server, link.RemoteId, localId, cancellationToken).ConfigureAwait(false);
await _links.DeleteAsync(link.Server, link.RemoteId, cancellationToken).ConfigureAwait(false);
Proxies.Delete(link.Server, link.RemoteId);
Log.Info(LogCategory, $"{link.Title} is no longer on {link.Server}");
@@ -1277,7 +1298,9 @@ public sealed class SyncService
{
var running = TransferKind(job);
var outranked = running == SyncTransferKind.DownloadProxies && job.Priority < priority;
if (running == wanted && !outranked) return job;
// An automatic transfer never creates a sequence: it does not stand for the user's own.
var narrower = SyncJobParameters.Read(job)?.IsAutomatic == true && !parameters.IsAutomatic;
if (running == wanted && !outranked && !narrower) return job;
if (outranked && wanted is SyncTransferKind.DownloadProxies or SyncTransferKind.DownloadOriginals)
await engine.CancelAsync(job.Id, cancellationToken).ConfigureAwait(false);
}
+58 -5
View File
@@ -40,14 +40,21 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary>Space a cached proxy is assumed to take before it is downloaded (1920 px JPEG, BRIEF §8.5).</summary>
private const long ProxyEstimate = 3L << 19;
public async Task UploadAsync(JobContext context, ISyncRemote remote, Guid localId)
/// <param name="automatic">
/// The new photos of a pair integrated with automatic photos: only into the server sequence that pair names, which must
/// still exist; never a new one (<see cref="AutomaticPairAsync"/>).
/// </param>
public async Task UploadAsync(JobContext context, ISyncRemote remote, Guid localId, bool automatic = false)
{
var ct = context.Cancellation;
var db = sync.Database;
var local = await db.Sequences.GetAsync(localId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
var archive = await db.Archives.GetAsync(local.ArchiveId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException(Loc.L("Errors.Sync.NoArchive"));
var paths = new ArchivePaths(archive.RootPath);
var (remoteId, created) = await TargetAsync(context, remote, local).ConfigureAwait(false);
var (remoteId, created) = automatic
? (await AutomaticPairAsync(remote, await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false), local.Id, ct)
.ConfigureAwait(false), false)
: await TargetAsync(context, remote, local).ConfigureAwait(false);
var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var manifest = remoteId is { } known ? await remote.GetManifestAsync(known, ct).ConfigureAwait(false) : null;
@@ -70,12 +77,15 @@ internal sealed class SyncTransfers(SyncService sync)
var hashes = new ConcurrentDictionary<Guid, string>();
// Without a server sequence the originals go out one by one under this sequence's session key until the
// server has filed one, which creates the sequence (an original it already holds elsewhere creates nothing).
// 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>();
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,
hashes, ct).ConfigureAwait(false);
if (sent is null) skipped++;
else if (sent.SequenceId == Guid.Empty && sent.FrameId != Guid.Empty) heldElsewhere.Add(first);
else if (sent.SequenceId != Guid.Empty)
{
remoteId = sent.SequenceId;
@@ -89,6 +99,16 @@ internal sealed class SyncTransfers(SyncService sync)
// A server that files a photo it holds in another sequence into this one (owner review 6): the map's "missing on the
// server" reaches 0 once every original is in the target, not merely somewhere on the server.
var into = (await remote.CapabilitiesAsync(ct).ConfigureAwait(false)).Contains(ServerCapabilities.UploadInto);
if (into)
{
// Counted already (they reached the server before the target existed): filed into it now, nothing stepped again.
foreach (var frame in heldElsewhere)
{
if (await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, tombstones, hashes, ct, into)
.ConfigureAwait(false) is null)
skipped++;
}
}
await Parallel.ForEachAsync(pending, Workers(sync.Options.Uploads, ct), async (frame, token) =>
{
var sent = await UploadFrameAsync(context, remote, target, null, paths.FromRelative(frame.RelativePath), frame, tombstones, hashes, token, into)
@@ -315,10 +335,34 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary>The server sequence of an Integrate answered 404: the pair counts it (design §6.3) and the job fails, nothing more sent.</summary>
private async Task<Exception> GoneAsync(ISyncRemote remote, Guid remoteId, Guid localId, ChronosApiException ex)
{
await sync.Copies.MarkRemoteGoneAsync(remote.Server, remoteId, localId, Guid.NewGuid(), DateTimeOffset.UtcNow, CancellationToken.None).ConfigureAwait(false);
// As a refresh counts it: only on a server keyed by its id, and at most once within FoundCopyStore.GoneRecheck.
if (ServerIdentity.IsIdKey(remote.Server))
await sync.Copies.MarkRemoteGoneAsync(remote.Server, remoteId, localId, Guid.NewGuid(), DateTimeOffset.UtcNow, CancellationToken.None).ConfigureAwait(false);
return new RemoteGoneException(Loc.L("Errors.Copies.RemoteGone"), ex);
}
/// <summary>
/// The server sequence an automatic transfer (owner review 6, design §7.3) may fill or read: the one <paramref name="link"/>
/// joins to <paramref name="localId"/>, while their pair is integrated with automatic photos, not marked gone, and the
/// server still has it (a 404 marks the pair and fails). Anything else fails: such a job never creates or retargets.
/// </summary>
private async Task<Guid> AutomaticPairAsync(ISyncRemote remote, SyncLink? link, Guid localId, CancellationToken ct)
{
if (link is not { RemoteId: var remoteId } || link.LocalId != localId) throw new RemoteGoneException(Loc.L("Errors.Copies.RemoteGone"));
var pair = await sync.Copies.FindRemoteAsync(localId, remote.Server, remoteId, ct).ConfigureAwait(false);
if (pair is { RemoteGoneHits: > 0 }) throw new RemoteGoneException(Loc.L("Errors.Copies.RemoteGone"));
if (pair is not { State: CopyState.Integrated, AutoPhotos: true }) throw new StaleCopyPlanException();
try
{
await remote.GetSequenceAsync(remoteId, ct).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw await GoneAsync(remote, remoteId, localId, ex).ConfigureAwait(false);
}
return remoteId;
}
/// <summary>A photo's key as <see cref="CopyComparer"/> makes it: its canonical SHA-256, else its size and capture time.</summary>
internal static string KeyOf(CopyPhotoInput photo, SyncTombstones tombstones) => KeyOf(photo.Sha256, photo.Size, photo.CapturedAt, photo.FrameId, tombstones);
@@ -433,12 +477,21 @@ internal sealed class SyncTransfers(SyncService sync)
}
}
public async Task DownloadOriginalsAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid? targetArchive)
/// <param name="automatic">
/// The new photos of a pair integrated with automatic photos: only into the local sequence that pair names, which must
/// still exist; never a new one (<see cref="AutomaticPairAsync"/>).
/// </param>
public async Task DownloadOriginalsAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid? targetArchive, bool automatic = false)
{
var ct = context.Cancellation;
var db = sync.Database;
var link = await sync.Links.GetAsync(remote.Server, remoteId, ct).ConfigureAwait(false);
var local = link?.LocalId is { } id ? await db.Sequences.GetAsync(id, ct).ConfigureAwait(false) : null;
if (automatic)
{
if (local is null) throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
await AutomaticPairAsync(remote, link, local.Id, ct).ConfigureAwait(false);
}
var archive = (local?.ArchiveId ?? targetArchive) is { } archiveId ? await db.Archives.GetAsync(archiveId, ct).ConfigureAwait(false) : null;
if (archive is null) throw new InvalidOperationException(Loc.L("Errors.Sync.NoArchive"));
var paths = new ArchivePaths(archive.RootPath);