28 Commits
Author SHA1 Message Date
Alby96andClaude Opus 5.5 aad8ae46dd fix(copies): close the eighth verification round of owner review 6
- A merge's Renders stage never deletes what sits at a journaled render
  target: a file or folder it did not copy there (a render of the kept
  sequence made after a failed run), or a path another render of the kept
  sequence names, makes the copy take a new free name instead.
- A merge's Verify stage records the hash it read for each kept frame the
  index had none for, the Details stage leaves the versions the verify filed
  out of Main, and Two versions also lists a whole-second instant holding two
  frames of one size and other content (owner Q3).
- The Integrate journal keeps the losers the plan listed as last copies; a
  loser that became the only copy while the job ran is never trashed: the
  journal goes and the job fails as a stale plan.
- Download originals of a server sequence whose earlier download was
  unlinked or kept apart makes a new local sequence under a key of the job,
  instead of filling the old one, re-linking it and overwriting its details.
- An upload never links again from its checkpoint a server sequence the user
  kept apart since the attempt that made it.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:38:18 +01:00
Alby96andClaude Opus 5.5 123ceba845 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>
2026-11-18 10:45:11 +01:00
Alby96andClaude Opus 5.5 c3273b7da5 test: serialise setup registry scratch keys and refresh the copy plan baselines
The setup tests running in parallel shared HKCU\Software\Chronos.Tests and each
removed it once it looked empty; one test's cleanup could race another's key
creation and fail ReplacingTheLegacyUploaderMovesItsSignInEntryAndKeepsItTurnedOff
in a whole-suite run. ScratchRegistry now creates each scratch key and removes
the parent under one lock.

The Plan and Blocked compare captures now count both server projects coming
to this PC (Vertical and Slow pan, as the Projects part lists them); the old
baselines still showed one.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:48:17 +01:00
Alby96andClaude Opus 5.5 b0b7c45896 fix(i18n): translate the reworded copy prompt into every culture
The merge confirmation now names the number to type ({1}) before the sequence; all 36 cultures follow that order instead of showing the number in brackets after the title. The session-keys tooltip already matched its shortened English text and is re-imported unchanged; the import tool also normalises key order in the touched files.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:17:15 +01:00
Alby96andClaude Opus 5.5 7c9d91c59f docs: bring the owner review 6 documentation in step with the fixes
The docs commit 59235e7c predates the third to sixth verification rounds.
The brief now says how Integrate decides who may trash a server photo (per
sequence, owner or admin with Delete; otherwise the server's version stays
out of its Main), that the Details stage stops on a server change, how a
merge re-plans, keeps its links undoable and names its classes, the
Two versions... list of owner Q3, the three-button rows and twins with a
sibling only, with an amendment row per round. DESIGN, ARCHITECTURE,
DECISIONS, CHANGELOG, STATUS 8.7 and the request doc follow; the Windows
captures are no longer listed as open.

The glossaries gain the match terms in every language, read from the
shipped strings. Hindi merging reads मर्ज, apart from मिलान (match);
Croatian names the matching sequence podudarna sekvenca; Finnish no
longer puts kohteen right after a count.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:10:58 +01:00
Alby96andClaude Opus 5.5 38764972ad fix(copies): close the sixth verification round of owner review 6
A merge that finds the other changed drops its journal so the retry plans
again. Unlink and Keep apart name the local side and leave a link that now
joins another sequence alone; Link only and the Integrate job refuse to
touch a link or a pair another integration holds. A sweep of 404s asks the
server once. To trash... trashes from the kept sequence after a swap and
every trash re-checks for new last copies. The Compare dialog and Settings
choices fit in every language, Details segments say which value they take,
twins need their sibling at the other home, and a linked row keeps three
buttons. Captures updated for the dialog and Settings scenes.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:58:58 +01:00
Alby96andClaude Opus 5.5 bf7701d279 fix(copies): close the fifth verification round of owner review 6
The metered hold now records the jobs it paused in the index and forgets
any job the user pauses, resumes, retries or cancels, so it never resumes
a pause of the user's and still resumes its own after a restart.

Drop... reports why its dry run is blocked instead of asking first, and
dropping the version Main uses lets Main use the version that stays,
with its hero and keyframes. That version reads "In Main".

Merges:
- A re-plan no longer hashes the other's photos again.
- A resumed merge verifies photos flagged damaged while it waited.
- A merge is blocked while the other's folder holds photos the index
  has not read; this is checked again under the lease before the trash.
- Choose each offers Keep both, Kept and Other, and blocks until every
  differing photo is chosen.
- Classes are named by role.

The Compare dialog:
- Its headings stay over their columns.
- The Projects part scrolls.
- Every confirmation line carries its own prefix, and a merge's facts
  carry none.
- A server card in a match offers Compare... alone.

The Italian strings follow the glossary.

Finding 9 (a local drop counting 0 photos) is not reproduced; a test now
keeps the count at 2.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:51:23 +01:00
Alby96andClaude Opus 5.5 2c06e7ac2b fix(copies): close the fourth verification round of owner review 6
The fourth verification round of the matches work found 18 defects in
the merge, Integrate and Matches surfaces. This commit fixes them:

- An Integrate job now carries the planning account's id, so its re-plan
  decides ownership the way the dialog did.
- A merge skips only a project the kept sequence holds a real copy of
  (name, offset head and history content) and re-points its renders to
  that copy.
- A merge runs its trash checks before the Links stage and records an
  undo, so an abandoned merge gives the other sequence back its link,
  session keys and pairs.
- The metered hold adopts automatic transfers that were paused before a
  restart.
- Apply in the Compare dialog re-plans when the plan is pending or stale.
- The Library's Two versions... lists the second versions a Union merge
  leaves, each with Drop... (dry run, confirmation, verified partner).
  A merge job's Open shows that list.
- The merge's typed confirmation is the invariant count, and the prompt
  names it in all 38 languages.
- Italian text uses Principale and Gemello. The Main project is named
  through WorkspaceText in the Projects part and in the twin tooltip.
- The session keys tooltip is split into two keys, and To trash... and
  Delete on server... say why they are disabled.
- The capture restores the editor account before the Matches scenes.
- Upload again follows SyncHost.CanSendSync (Upload with Edit).
- Matches rows trim archive names in the middle on a rebalanced grid;
  the Projects part rows trim, with the full text in the tooltip.
- The sample project targets use ProjectTransplant.FreeName.

DECISIONS, CHANGELOG, STATUS 8.7, the request doc and the 16 changed
capture baselines are updated.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:20:30 +01:00
Alby96andClaude Opus 5.5 3c99badcfe fix(copies): close the third verification round and add the match baselines
Integrate trashes a server photo only for the sequence's owner or an admin, a
Details stage stops instead of overwriting a server change the user had kept
this PC's value against, a merge retried after a stop plans again when work
reached the other sequence, detection keeps pairs answered while it ran, and a
sync row whose match the server deleted offers Keep here, Upload again and To
trash. The Integrate and merge logs say in the UI language why a version was
kept.

The edit-picker-twins capture scene showed no Twin chip, since a capture has no
workspace: it now lists sample workspace projects of the sample matches. The
screenshot baselines gain the 38 Matches screens and take the Matches chip,
the three Settings > Server rows, the longer priority list and 1.2.0.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:01:37 +01:00
Alby96andClaude Opus 5.5 3e6110d329 chore(i18n): owner review 6 strings in all languages
Translate the match, integrate and merge strings of owner review 6 into
the 36 other cultures, with the extra plural forms each language needs,
so i18n check reports no untranslated strings.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:32:18 +01:00
Alby96andClaude Opus 5.5 59235e7c25 docs: owner review 6 request, brief amendments and decisions for matches (v1.2.0)
Owner review 6 asks Chronos to recognise the same time-lapse on a server
and on this PC, show the differences and let the user keep the two apart
or integrate and sync them. The request file keeps the owner's words, the
reading R1-R8, the eight answers and the delivery plan; the brief now
describes matches, the Compare dialog, Integrate, the merge of two local
sequences, the automatic photos of integrated pairs, the photo lookup and
uploads into a target, and amends 14.5 so other projects cross only through
Integrate or a merge. DECISIONS records the design choices and those taken
while building it; the changelog, status, architecture and design notes
follow, and the version moves to 1.2.0.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:24:53 +01:00
Alby96andClaude Opus 5.5 9657c1711d fix(copies): close the owner review 6 second verification findings
Upload again now deletes the gone pair row once the new sequence is linked, so
the pair stops reading "deleted on server" or "kept here". A linked upload the
server refuses into its sequence (403 for an account without Edit that does not
own it) falls back to ordinary uploads instead of failing; an Integrate that
would add photos to such a sequence is blocked in its plan (NoAddRight).
Automatic photo transfers pause on a metered connection whatever the option
says. Integrate trashes server photos only against the manifest version that
checked the winner, and a merge is blocked while the other sequence holds a
damaged photo nothing else holds (DamagedPhotos), so nothing unverified reaches
the trash.

The plan and the confirmations now say what really happens: replaced versions
are no longer counted as kept, a merge lists the kept sequence's replaced
photos, plan lines use the text colour, an integrated pair that left photos out
says new photos move by hand, and a merging pair reads "merging" with its
progress. The Compare dialog gets per-side tooltips, class sizes for both
sides, policy-aware class tooltips, column headings and readable file names;
the sync table shows "deleted there" with Review and warns on skipped rows; the
Edit picker names the server, the Library card shows the match status second,
a deleted server sequence is named instead of "0 photos", and the match
tooltips stop calling a sequence a copy. The capture scenes use the server
name, the link names and consistent sample sizes.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:08:49 +01:00
Alby96andClaude Opus 5.5 b34b6b6fe0 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>
2026-11-17 15:02:39 +01:00
Alby96andClaude Opus 5.5 d10577b175 fix(copies): close the owner review 6 gaps with tests
Photos not sent: automatic photos of an integrated pair that failed three
times in a row are now told with an error toast that shows the row, and the
row reads "not sent" with the last reason. The matches-found and linked toasts
of background detections run from their Windows notification too.

Maintenance now clears a merge's or an integration's journal whose job is done,
cancelled, or deleted without a cancel and untouched for the history's days.

Tests pin the matches jobs in the priority queue, the owner's defaults (ask
always, union, copy across), the dialog starting from the settings, Choose
each preselecting nothing, no automatic photos for a pair whose server copy
is gone, the repair of a corrupt local frame by an Integrate, and the owner's
whole scenario end to end against a real in-process server.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:03:23 +01:00
Alby96andClaude Opus 5.5 fe752a0a21 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>
2026-11-17 13:12:00 +01:00
Alby96andClaude Opus 5.5 96b5b4078b feat(copies): engine composition, automatic photos, metered hold and App wiring (owner review 6, P5)
CopyEngine puts the planners together behind ICopyEngine so the App can find,
compare, integrate, merge, link, unlink and keep pairs apart. It also moves
photos that one side deleted to the other side's trash. Each trash step
re-reads both sides when applied, and nothing moves if any photo was restored
since the dry run. The sync agent now queues the new photos of pairs that were
integrated with automatic photos, both ways, at background priority. Failures
back off, and three in a row are reported so the pair can show "not sent". On
a metered connection, integrations are held like other server transfers.
AppServices builds the engine and registers the Integrate and Merge handlers.
A CopyWatch looks for local copies after start and after jobs that change
photos. Merges wait for workspace work that has not been sent home.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:03:56 +01:00
Alby96andClaude Opus 5.5 461dfcf4a3 feat(copies): integrate local and server, filtered transfers, project transplant (owner review 6, P3)
A local sequence and its server twin can now be integrated into one linked
pair by a resumable job instead of by hand. The planner runs the dry run of
design 5c: photo steps per policy (the wins policies decide only the Different
class; Only here and Only there always move), left out and AutoPhotos, last
copies, the one portable payload, projects copied across under free names,
space, rights and every block, and a fingerprint the job checks again.

The Integrate job keeps an atomic journal and resumes at each stage: link,
photos both ways through filtered transfers that never create or retarget a
server sequence (a 404 marks the pair remote gone), trash only once the winner
is present (locally through the photo trash inside the job, on the server at
the version its dry run read), the agreed details, then projects through
ProjectTransplant. Refusals are kept and reported; a failure or a cancel sets
the pair back to Linked or its previous state.

Linked uploads now file into their target when the server announces
upload-into. The plan context travels with the job so rights and names give
the same plan on the job side.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:24:18 +01:00
Alby96andClaude Opus 5.5 2a27ef488c merge: P4 merge two local sequences into the kept one
Brings in the owner review 6 parcel P4: SequenceMerger plan and
fingerprint, the journaled merge job (copy, verify, move, trash) and
the sequence payload writer. Merges without conflicts on top of P1b;
build has no warnings, Core, Data and Server suites, the copy-related
App tests, i18n check, xaml-lint and package-guard pass.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:36:00 +01:00
Alby96andClaude Opus 5.5 bfc9747873 merge: P1b detection and sync integration
Brings in the owner review 6 parcel P1b: CopyFinder detection of local
and server copies, CopyReviewBuilder for the compare dialog, and the
SyncService reconcile, re-ask, sweep and agreed-apply integration.
Merges without conflicts.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:35:59 +01:00
Alby96andClaude Opus 5.5 ade908cb6d feat(copies): detection and sync integration (owner review 6, P1b)
A refresh no longer links copies by content behind the user's back. After the
gate is released, CopyFinder looks for copies whose ids differ: the server's
photo lookup (or 1.1's gate and the hints on an older server), session keys,
and an exact comparison by manifest, bounded per refresh and remembered in
copy_probes so nothing is compared twice while neither side moves. What a pair
becomes is the Link matches setting's call: asked by default, linked by itself
only as the setting allows, through a compare-and-set that a Keep apart wins.
Local detection finds copies inside this PC's archives and never links them.

SyncService gives every link its pair, adds Unlink (kept apart, observation
kept), marks pairs whose server sequence answers 404 (once per refresh, twice
reads deleted, never on an address key or in a 404 sweep), keeps deletion
counts current at each comparison, writes an Integrate's agreed details to both
sides by content (ApplyAgreedAsync) and queues uploads at a given priority.
CopyReviewBuilder assembles what the Compare dialog shows.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:25:25 +01:00
Alby96andClaude Opus 5.5 b4070ddfd4 feat(archive): merge two local sequences into the kept one (owner review 6, P4)
SequenceMerger plans the merge of a local pair (kept sequence, photos
copied by policy, last copies, renders, details, projects, session keys,
links, blocks and a fingerprint) and queues the MergeSequences job.
MergeJobHandler applies the confirmed plan through a journal, so every
stage resumes: copy and file the other's photos, move renders, hash-verify
every original of the other in the kept one (or list it as a last copy),
trash the kept one's losing versions, write the details
(SequencePayloadWriter), copy projects, move keys and links, then move the
other to its archive's trash only at the verified frames version. A cancel
drops the journal and returns the pair to its previous state.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:24:32 +01:00
Alby96andClaude Opus 5.5 9912baf78a merge: P6 matches list, compare dialog and app surfaces
Brings in the owner review 6 parcel P6: Server Matches list, compare
dialog, copy settings rows, library and picker twin surfaces. The three
parcels merge without conflicts; build, tests, i18n and xaml-lint pass.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:44:07 +01:00
Alby96andClaude Opus 5.5 3518d0f1bd merge: P2 photo lookup endpoint and uploads into a target
Brings in the owner review 6 parcel P2: the photo lookup endpoint and
the copy path for uploads into an existing sequence, with Server tests.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:44:06 +01:00
Alby96andClaude Opus 5.5 e2a4647281 merge: P1a pure comparison, detection rules, details payload and sides
Brings in the owner review 6 parcel P1a: CopyComparison, CopyRules,
CopyPayload and CopySides with their Data tests.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:44:06 +01:00
Alby96andClaude Opus 5.5 06b826e39d feat(app): matches list, compare dialog, settings rows, library and picker surfaces (owner review 6, P6)
Server > Matches shows the pairs the copy engine found (same sequence on the
server and this PC, or twice here), attention first, with the design 8.1
actions; Keep apart and Unlink toast with Undo. The in-window Compare dialog
walks photos, details, projects and the plan, blocks until details are
chosen, and confirms only what replaces or merges (typed count for a merge).
Sync rows of an unanswered pair read "match found" and offer Compare first;
Upload all local skips suspected copies and says why. Settings > Server gains
Link matches, Integrate photos and Integrate projects. Library cards carry the
match status with Compare..., the sequence picker marks twins, and Jobs opens
Integrate and Merge targets. The sample engine and capture scenes render every
state; tests cover the text rules and the screens.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:29:07 +01:00
Alby96andClaude Opus 5.5 f6f81e2c37 feat(copies): pure comparison, detection rules, details payload and comparison sides
Detection, Integrate and Merge need one comparison of two copies of a time-lapse, so
this adds it: CopyComparer classifies every photo (same, converted, same unhashed,
deleted here/there, differs, two versions, only here/there) with strict Differs and
Versions rules so whole-second capture times and bursts never pair, unusable frames
held as nothing and marked for repair, and the score of design 3.2.
CopyRules ports 1.1's same-originals gate exactly for "Link when half shared" and
holds the Decide table, ask-again thresholds, fingerprints, hints and the probe
sample. CopyPayload compares details in portable form (same photo at another index is
no line) and merges the chosen sides into one payload that must parse as a project.
CopySides reads both sides from the index and a server and answers the last-copy
check across every archive. SyncTombstones gains FromDtos for local pairs.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:58:07 +01:00
Alby96andClaude Opus 5.5 94a56278e2 feat(server): photo lookup endpoint and uploads into a target (owner review 6, P2)
Clients must recognise the same time-lapse filed under another id on the server, and an
integrated pair must get a photo into the server sequence even when another sequence there
already holds it. The server now answers both, authorised and scoped by itself.

- POST /api/v1/photos/lookup (Read right): per probe, the sequences of the served archive
  that hold its hashes in a frame, tombstoned them (deleted or replaced by a conversion),
  match its unhashed photos by size and capture millisecond, or carry its session key; only
  ids and counts, batched raw SQL, 413 too_many beyond 200 probes or 20,000 items, a 4 MB
  body limit so a full request fits.
- Uploads with IntoTarget: sequenceId required, never with Restore, the target must be the
  served archive's and the caller its owner, an admin or an editor. Only a copy in the target
  stands in; a tombstone keeps the photo deleted. Otherwise the server copies an intact file
  of another sequence of the served archive (never another archive of the index) into the
  target: quota and room checked, verified copy, hash compared (a damaged source falls back
  to a normal upload), committed refusing removed photos, used bytes charged only for a new
  frame, frames event published, answered copied.
- server/info announces photo-lookup and upload-into (the desktop's hosted share too).

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:56:30 +01:00
Alby96andClaude Opus 5.5 283d04d9cd feat: found copies foundation (contracts, migration 0012, store, wire, trash and job hooks, keys)
Owner review 6 asks Chronos to recognise the same time-lapse held under different ids on the
server and on this PC, compare the copies, and keep them apart or integrate and sync them. This
lays the shared foundation the later parcels build on, without any UI or detection yet.

- Migration 0012 adds found_copies (local-server and local-local pairs with evidence, scores,
  answer, policy and the 404 record) and copy_probes; every existing link with a local sequence
  becomes a Linked pair, so a server deletion and the per-link policy have a place.
- FoundCopyStore keeps the pairs: upserts that never touch the answer, a compare-and-set of the
  state with an Integrating backstop (a failed or cancelled job reads as the previous state),
  link promotion and demotion, the once-per-refresh 404 count, the merge's links stage
  (session keys, links reset, pairs moved, refused when both are linked on one server), the
  local overlap queries and the probes. SyncLinkStore.RekeyAsync moves pairs and probes with
  the links in the same transaction.
- Contracts for detection, review, plans, the Integrate and MergeSequences jobs (kinds 25/26,
  High level, new detail steps) and the Upload all rule that keeps suspected, kept-apart,
  deleted, busy and server-born sequences here.
- Wire: POST photos/lookup, uploads into a target (IntoTarget/Copied, trailing and optional),
  frames/delete on the client, capabilities photo-lookup and upload-into, cached per remote.
- The trash plans and deletes accept the job that holds the sequence (its own hold is not
  Busy) and a frames version checked under the lease; a Background job never interrupts a
  running one.
- Settings for linking, the photo policy and projects; the en and it keys of design section 9.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:39:04 +01:00
17 changed files with 41 additions and 932 deletions

No files matched your search

-31
View File
@@ -5,8 +5,6 @@ commits follow Conventional Commits (release notes are generated from them by `C
## [Unreleased] ## [Unreleased]
## [1.2.0] — 2026-11-18
Owner review 6 for v1.2.0 (`docs/requests/2026-11-16-owner-review-6.md`; issue #73). Upgrading from 1.1 keeps the Owner review 6 for v1.2.0 (`docs/requests/2026-11-16-owner-review-6.md`; issue #73). Upgrading from 1.1 keeps the
archive, the database and the settings: migration 0012 runs at start and turns every existing link into a linked archive, the database and the settings: migration 0012 runs at start and turns every existing link into a linked
match. A 1.1 server works as before, without Integrate; a 1.2 server adds the photo lookup and uploads into a target. match. A 1.1 server works as before, without Integrate; a 1.2 server adds the photo lookup and uploads into a target.
@@ -225,35 +223,6 @@ match. A 1.1 server works as before, without Integrate; a 1.2 server adds the ph
- Download originals of a server sequence unlinked or kept apart from its earlier download makes a new local - Download originals of a server sequence unlinked or kept apart from its earlier download makes a new local
sequence instead of filling the old one again, re-linking it and overwriting its details. sequence instead of filling the old one again, re-linking it and overwriting its details.
- An upload retried after its pair was kept apart makes a new server sequence instead of linking the old one again. - An upload retried after its pair was kept apart makes a new server sequence instead of linking the old one again.
- A second version a Union merge copies in is left out of Main at once, so a merge that stops before its details
(an edit meanwhile, a cancel) no longer leaves both versions in Main for good.
- A merge whose other sequence is not hashed lists as a last copy a photo matched by size and time whose content the
kept sequence deleted, instead of failing its verify on every retry.
- Download originals of a server sequence whose link a 404 forgot fills and links its own local copy again instead
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.
- A second version a merge's verify files is left out of Main also when the run stopped right after filing it (a
drive dropping out, project.json held, the app closing): the resumed merge leaves it out then.
- A merge whose verify stopped before filing a second version, and whose photo changed before the retry, files the
photo as it is now instead of failing on every retry; one that had filed it leaves it out of Main and asks for a
new comparison.
- *Upload all local* leaves out again a sequence answered *Keep here* after its server copy was deleted, and the
answer stays; only a *Keep apart* given before the deletion lets it send the sequence.
- An upload that joined a server sequence this PC already knew still compares its details when it is resumed or
retried, instead of overwriting the server's title, tags, rating, notes and settings.
## [1.1.1] — 2026-11-16 ## [1.1.1] — 2026-11-16
-13
View File
@@ -1019,16 +1019,3 @@ One line per decision: date · decision · alternative · reason.
| 2026-11-18 | The Integrate journal keeps the losers the plan listed as last copies (`LastHere`, `LastThere`); before each trash step a loser not listed must still be held by another usable copy (the local copy's other frames, another sequence of this index, the server sequence's fresh manifest; for a server loser its other frames or any sequence of this index), else the journal goes and the job fails as a stale plan (#73) | Keep the loser and end Linked | As the merge's Replace stage: nothing goes to a trash as a last copy without being shown | | 2026-11-18 | The Integrate journal keeps the losers the plan listed as last copies (`LastHere`, `LastThere`); before each trash step a loser not listed must still be held by another usable copy (the local copy's other frames, another sequence of this index, the server sequence's fresh manifest; for a server loser its other frames or any sequence of this index), else the journal goes and the job fails as a stale plan (#73) | Keep the loser and end Linked | As the merge's Replace stage: nothing goes to a trash as a last copy without being shown |
| 2026-11-18 | Download originals of a server sequence without a local copy goes under a key of the job (`chronos-sync:<remote:N>:<job:N>`, the same on a retry) when the sequence holding the server sequence's own key has a pair or a link for that server (kept apart, unlinked, asked again, linked elsewhere): a new local sequence, and its details are taken only by it; a holder with neither (a run that stopped before linking) is joined as before (#73) | Refuse the download and ask for Link or Ask again | The download twin of the round-7 upload rule: the shared key filed the photos back into the sequence the user kept separate, re-linked it and overwrote its details | | 2026-11-18 | Download originals of a server sequence without a local copy goes under a key of the job (`chronos-sync:<remote:N>:<job:N>`, the same on a retry) when the sequence holding the server sequence's own key has a pair or a link for that server (kept apart, unlinked, asked again, linked elsewhere): a new local sequence, and its details are taken only by it; a holder with neither (a run that stopped before linking) is joined as before (#73) | Refuse the download and ask for Link or Ask again | The download twin of the round-7 upload rule: the shared key filed the photos back into the sequence the user kept separate, re-linked it and overwrote its details |
| 2026-11-18 | An upload never links again from its checkpoint a server sequence whose pair with the local sequence is Kept apart (unlinked or kept apart since the attempt that made it): the upload goes on as one without a target, under the job's key (#73) | Make Unlink and Keep apart cancel a pending upload | The checkpoint branch never reached the session-key rule, and a retry or a restart moved the Kept apart pair back to Linked | | 2026-11-18 | An upload never links again from its checkpoint a server sequence whose pair with the local sequence is Kept apart (unlinked or kept apart since the attempt that made it): the upload goes on as one without a target, under the job's key (#73) | Make Unlink and Keep apart cancel a pending upload | The checkpoint branch never reached the session-key rule, and a retry or a restart moved the Kept apart pair back to Linked |
| 2026-11-18 | A merge leaves each second version out of Main as it files it (the Copy stage's keep-both and SameUnhashed versions, the Verify stage's), under the kept sequence's lease at the settings version read just before, not cancellable halfway; when that was the plan's version the journal's `KeepSettingsVersion` moves to the one written, so the Details stage still writes the plan's payload (#73) | Have the re-plan exclude a shared version the kept sequence already holds twice | Only the merge knows which version it brought; the re-plan cannot tell it from two versions the user chose to keep in Main |
| 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) |
| 2026-11-18 | A merge's Verify stage journals a second version (`SecondVersions`, and in `VersionShas` the SHA-256 it is filed as) before it files it; a resumed verify that finds such a frame in the kept sequence leaves it out of Main again (a no-op when it already is), and one that reads other bytes for it stops with "changed" (#73) | Save the journal right after filing | The ingest commits the frame before any save can follow: a failed exclusion or a crash in between left the version in Main for good, since a resumed verify read it as the kept sequence's own |
| 2026-11-18 | Supersedes the 2026-11-18 unlinked-404 rows on Upload all local: a Kept apart pair whose server sequence reads deleted on the server holds nothing back only when it was answered before the first 404 (`AnsweredAt < RemoteGoneAt`); a Keep here (answered after the deletion was shown) still skips the local sequence (#73) | A separate Keep here state or marker | Both answers are stored as Kept apart with the gone mark; the answer time already tells them apart, and Keep here's tooltip and design §6.3 promise Upload all local leaves it out |
| 2026-11-18 | An upload's checkpoint names the server sequence its first original reached with `:joined` appended when that was one this PC already knew; a resumed or retried upload sends all its details only when the checkpoint names the target without that mark (a plain id from an older run still means made by this job) (#73) | Look the sequence up again in the known remotes on resume | After the first attempt the link to it exists, so a resume cannot tell a sequence it made from one it joined; only the attempt that sent the first original knows |
| 2026-11-18 | Supersedes the 2026-11-18 `VersionShas` row where a resumed verify reads other bytes for a journalled second version: when the kept sequence does not hold the journalled SHA-256 (nothing was filed) the frame leaves `SecondVersions` and `VersionShas` and is verified as on a first visit, which files the bytes it reads now; when it holds them, they are left out of Main and the merge stops with "changed" and drops its journal, so the next run plans again (#73) | Treat the new bytes as another second version in the same run | A stop that kept the journal failed the same way on every retry once the file changed (an editor saving, a sync tool, an edit before a retry after a failed copy), and a cancel then left a filed version in Main; filing a third version unplanned goes further than the plan the user confirmed, while a new plan compares the new bytes and shows them |
+2 -2
View File
@@ -20,7 +20,7 @@ by its `windows` job once a Windows runner is registered (`WINDOWS_RUNNER`), and
| 8.4 Owner review 4 | Done (request and plan: `docs/requests/2026-11-06-owner-review-4.md`): released as `v0.1.0-rc.14` with owner review 1 phase 6 (the deploy guide `docs/deploy/`), then as `v1.0.0` (#23), the first stable release: R1 work board of every video made or published, the published apart from workspace work (#29); R2 the anonymous usage counts removed, nothing sent by itself (#30); R3 the archive's whole folder structure created inside the chosen archive path, desktop and server (#31); R4 the repository on Gitea in order (earlier work as closed issues #32–#54 in their milestones, the original documentation in `docs/reference/original`, `fe50b877`); R5 licensing set aside and recorded in #24. | | 8.4 Owner review 4 | Done (request and plan: `docs/requests/2026-11-06-owner-review-4.md`): released as `v0.1.0-rc.14` with owner review 1 phase 6 (the deploy guide `docs/deploy/`), then as `v1.0.0` (#23), the first stable release: R1 work board of every video made or published, the published apart from workspace work (#29); R2 the anonymous usage counts removed, nothing sent by itself (#30); R3 the archive's whole folder structure created inside the chosen archive path, desktop and server (#31); R4 the repository on Gitea in order (earlier work as closed issues #32–#54 in their milestones, the original documentation in `docs/reference/original`, `fe50b877`); R5 licensing set aside and recorded in #24. |
| 8.5 Owner review 5 | Done (request, answers and plan: `docs/requests/2026-11-15-owner-review-5.md`; issues #64–#67, milestone v1.1.0), released as `v1.1.0`: one setup for Chronos Desktop and Chronos Uploader with the Uploader's update check (#64); the detail of mass passes (step, photo x of y, sequence n of m, rate, time left) on the desktop, the admin panel and, for the connected server's jobs, the desktop's Server section (#65); separate homes per server keyed by a stable server id, with the 1.0 workspace and cache sorted at the first start and a separate originals archive per server (#66); Chronos Desktop sharing its library on the LAN in place of Chronos Server for Windows, running on in the tray while it shares (#67). One review round, 15 findings fixed; strings in all 38 languages. Not run on the PC: the Windows-only smoke tests, `installer-test.ps1` and the release dry run (CI runs them). Follow-ups: a firewall status row, Change…/Forget on known servers, the LAN beacon announcing the server id, docs/ui DESIGN and mockups for the new screens. | | 8.5 Owner review 5 | Done (request, answers and plan: `docs/requests/2026-11-15-owner-review-5.md`; issues #64–#67, milestone v1.1.0), released as `v1.1.0`: one setup for Chronos Desktop and Chronos Uploader with the Uploader's update check (#64); the detail of mass passes (step, photo x of y, sequence n of m, rate, time left) on the desktop, the admin panel and, for the connected server's jobs, the desktop's Server section (#65); separate homes per server keyed by a stable server id, with the 1.0 workspace and cache sorted at the first start and a separate originals archive per server (#66); Chronos Desktop sharing its library on the LAN in place of Chronos Server for Windows, running on in the tray while it shares (#67). One review round, 15 findings fixed; strings in all 38 languages. Not run on the PC: the Windows-only smoke tests, `installer-test.ps1` and the release dry run (CI runs them). Follow-ups: a firewall status row, Change…/Forget on known servers, the LAN beacon announcing the server id, docs/ui DESIGN and mockups for the new screens. |
| 8.6 Windows test of 1.1.0 | Done (#70, milestone v1.1.1), released as `v1.1.1`: the App and Core.Windows suites run whole on the development PC (5 stale screen tests brought up to date); a hands-on test of a portable 1.1.0 (import, Reorganize, sharing, a client, tray, Exit with clients); fixes: job log times in local time, the Jobs Type column, Forget in Bulgarian, the Reorganize capture. Still to do by the owner: the real 1.0 → 1.1 upgrade on this PC (UAC). | | 8.6 Windows test of 1.1.0 | Done (#70, milestone v1.1.1), released as `v1.1.1`: the App and Core.Windows suites run whole on the development PC (5 stale screen tests brought up to date); a hands-on test of a portable 1.1.0 (import, Reorganize, sharing, a client, tray, Exit with clients); fixes: job log times in local time, the Jobs Type column, Forget in Bulgarian, the Reorganize capture. Still to do by the owner: the real 1.0 → 1.1 upgrade on this PC (UAC). |
| 8.7 Owner review 6 | Done (request, answers and plan: `docs/requests/2026-11-16-owner-review-6.md`; #73, milestone v1.2.0), released as `v1.2.0`: matches, the same time-lapse on a server and on this PC under different ids or twice on this PC, found after each sync refresh (the server's new photo lookup) and after jobs that change photos (migration 0012, `Chronos.Data.Copies`); Server › Matches with Keep apart, Link only, Unlink and the Compare dialog (Photos, Details line by line, Projects, Plan); Integrate of a local and a server sequence (job 25: photos both ways under Union by default, details as one change, projects copied across, losers to the trash only after a hash check) and the merge of two local sequences (job 26: the other to its archive's trash once every photo is verified); new photos of integrated pairs moved by themselves, *deleted there* and *deleted on server* reviewed by the user; Settings › Server › Link matches (Ask always), Integrate photos (Union), Integrate projects (Copy across); Upload all local skips suspected matches. Eight parcels, one review round (correctness, safety, conformance) with every verified finding fixed, a gap round and twelve verification rounds (the last seven on the data engines only, with three-vote confirmation, until one found nothing); the strings in all 38 languages, the match terms in every language's glossary; the Windows captures of the new screens are committed as screenshot baselines (`server-copies-*`, `library-copies-*`, `server-sync-copyfound-*`, `edit-picker-twins-*`); the photos a sequence keeps in two versions are listed with Drop… from the Library (Two versions…) and a merge job's Open. Follow-ups: a field-level merge of an integrated pair's settings (to ask the owner), the Import › Folder… warning, the same two-versions list in Edit, a capture scene of the Two versions… dialog. | | 8.7 Owner review 6 | In progress (request, answers and plan: `docs/requests/2026-11-16-owner-review-6.md`; #73, milestone v1.2.0), implemented on `or6-duplicates`, not released: matches, the same time-lapse on a server and on this PC under different ids or twice on this PC, found after each sync refresh (the server's new photo lookup) and after jobs that change photos (migration 0012, `Chronos.Data.Copies`); Server › Matches with Keep apart, Link only, Unlink and the Compare dialog (Photos, Details line by line, Projects, Plan); Integrate of a local and a server sequence (job 25: photos both ways under Union by default, details as one change, projects copied across, losers to the trash only after a hash check) and the merge of two local sequences (job 26: the other to its archive's trash once every photo is verified); new photos of integrated pairs moved by themselves, *deleted there* and *deleted on server* reviewed by the user; Settings › Server › Link matches (Ask always), Integrate photos (Union), Integrate projects (Copy across); Upload all local skips suspected matches. Eight parcels, one review round (correctness, safety, conformance) with every verified finding fixed, a gap round and six verification rounds; the strings in all 38 languages, the match terms in every language's glossary; the Windows captures of the new screens are committed as screenshot baselines (`server-copies-*`, `library-copies-*`, `server-sync-copyfound-*`, `edit-picker-twins-*`); the photos a sequence keeps in two versions are listed with Drop… from the Library (Two versions…) and a merge job's Open. Still to do: the PostgreSQL tests in CI, the release. Follow-ups: a field-level merge of an integrated pair's settings (to ask the owner), the Import › Folder… warning, the same two-versions list in Edit, a capture scene of the Two versions… dialog. |
| 9 Monetization | Not started: requires explicit approval (§22); the proposal is recorded in issue #24 (owner review 4, R5). | | 9 Monetization | Not started: requires explicit approval (§22); the proposal is recorded in issue #24 (owner review 4, R5). |
## Verification (2026-10-12) ## Verification (2026-10-12)
@@ -69,7 +69,7 @@ src/Chronos.App/bin/Release/net10.0-windows/Chronos.exe --capture out/screenshot
- Job log time (1.1.1): Jobs › expand a job: the log times match the row times (local). - Job log time (1.1.1): Jobs › expand a job: the log times match the row times (local).
- Share this library: Settings › Server › *Share this library*, then Server › This library; connect the Uploader or - Share this library: Settings › Server › *Share this library*, then Server › This library; connect the Uploader or
another PC to the address shown. another PC to the address shown.
- Owner review 6 (v1.2.0): send a folder of photos to a 1.2 server with Chronos Uploader; on the desktop - Owner review 6 (v1.2.0, in progress): send a folder of photos to a 1.2 server with Chronos Uploader; on the desktop
import the same folder plus a few more photos (Import › *Folder…*), give it another title and sign in. After the import the same folder plus a few more photos (Import › *Folder…*), give it another title and sign in. After the
refresh Server › *Matches* lists it as *match found*; *Compare…* shows the photos only here and the differing title; refresh Server › *Matches* lists it as *match found*; *Compare…* shows the photos only here and the differing title;
*Integrate…* opens on Details: *All this PC*, then *Integrate*. The row reads *integrating · x of y*, then *Integrate…* opens on Details: *All this PC*, then *Integrate*. The row reads *integrating · x of y*, then
+2 -2
View File
@@ -67,10 +67,10 @@ local folders and *Upload all local*). The owner answered in Italian; quoted wor
| Phase | Content | State | Commit | | Phase | Content | State | Commit |
|---|---|---|---| |---|---|---|---|
| 1 | `v1.2.0`: R1–R7 (#73); R8 tracking. Parcels: P0 foundation (contracts, migration 0012, store, wire, trash and job hooks, keys), P1a pure comparison and rules, P1b detection and sync integration, P2 server photo lookup and uploads into a target, P3 Integrate, P4 merge of two local sequences, P5 engine composition and automatic photos, P6 the desktop surfaces; then one review round (correctness, safety, conformance) with every verified finding fixed, a gap round and twelve verification rounds (the last seven on the data engines only, each finding confirmed by two of three independent checks, the last three on the latest fixes only, until one found nothing). BRIEF §5, §6.2, §12.2, §12.3, §12.5, §12.7, §12.8, §14.3, §14.4, §14.5, §14.6, §24 and Appendix C amended; DESIGN §4 *Matches*; DECISIONS rows dated 2026-11-16 to 2026-11-18 citing #73 | done: released as `v1.2.0` on 2026-11-18; strings in all 38 languages and their glossaries; the Windows captures committed as baselines; CI green with PostgreSQL 16 and 17 | `283d04d9` … `65b7cdf9` on `or6-duplicates`, squash-merged into `main` | | 1 | `v1.2.0`: R1–R7 (#73); R8 tracking. Parcels: P0 foundation (contracts, migration 0012, store, wire, trash and job hooks, keys), P1a pure comparison and rules, P1b detection and sync integration, P2 server photo lookup and uploads into a target, P3 Integrate, P4 merge of two local sequences, P5 engine composition and automatic photos, P6 the desktop surfaces; then one review round (correctness, safety, conformance) with every verified finding fixed, a gap round and six verification rounds. BRIEF §5, §6.2, §12.2, §12.3, §12.5, §12.7, §12.8, §14.3, §14.4, §14.5, §14.6, §24 and Appendix C amended; DESIGN §4 *Matches*; DECISIONS rows dated 2026-11-16 and 2026-11-17 citing #73 | in progress: implemented on `or6-duplicates`, not released; strings in all 38 languages and their glossaries; the Windows captures committed as baselines; the PostgreSQL tests in CI still to run | `283d04d9` … `38764972`, then the documentation pass |
Follow-ups kept out of 1.2.0: a field-level three-way merge of an integrated pair's settings (settings sync as today, Follow-ups kept out of 1.2.0: a field-level three-way merge of an integrated pair's settings (settings sync as today,
owner Q6; to be asked of the owner), the Import › Folder… warning for photos already on a server, merging two owner Q6; to be asked of the owner), the Import › Folder… warning for photos already on a server, merging two
sequences of one server, the list of second versions with *Drop…* in Edit (the Library has it: *Two versions…*). sequences of one server, the list of second versions with *Drop…* in Edit (the Library has it: *Two versions…*).
Tracking: issue #73, milestone `v1.2.0`, board card; status **done**. Tracking: issue #73, milestone `v1.2.0`, board card; status **in progress**.
@@ -52,12 +52,6 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
/// <summary>Called before each stage runs (tests: a crash, a change made between stages).</summary> /// <summary>Called before each stage runs (tests: a crash, a change made between stages).</summary>
internal Func<MergeStage, Task>? BeforeStage { get; set; } internal Func<MergeStage, Task>? BeforeStage { get; set; }
/// <summary>Called before a second version is left out of Main (tests: a failure between filing it and saving the journal).</summary>
internal Func<string, Task>? BeforeLeaveOutOfMain { get; set; }
/// <summary>Called before the verify files a second version, once the journal names it (tests: its file rewritten meanwhile).</summary>
internal Func<Guid, Task>? BeforeFileVersion { get; set; }
public async Task RunAsync(JobContext context) public async Task RunAsync(JobContext context)
{ {
var job = context.Job; var job = context.Job;
@@ -378,58 +372,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
var frame = await _db.Frames.GetAsync(copy.DropFrameId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle); 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); await context.ReportAsync(Done(), Total, new JobDetail(JobStep.CopyPhoto, copy.FileName, n, journal.Copies.Count)).ConfigureAwait(false);
var result = await FileAsync(frame, copy.Sha256, planned: copy.Sha256 is { Length: > 0 }).ConfigureAwait(false); var result = await FileAsync(frame, copy.Sha256, planned: copy.Sha256 is { Length: > 0 }).ConfigureAwait(false);
// A version kept beside the kept sequence's own (a Union keep-both, or another photo after all) is left out of
// Main as it is filed, before the journal says so: a resumed run files it again (a duplicate) and asks again.
if (copy is { Action: PhotoAction.FetchVersion, Sha256: { Length: > 0 } version } && journal.Replaces.All(r => r.Key != copy.Key))
await LeaveOutOfMainAsync(version).ConfigureAwait(false);
journal.Committed[copy.DropFrameId] = result.FrameId; journal.Committed[copy.DropFrameId] = result.FrameId;
Save(); Save();
context.Log(Loc.L("Archive.Log.MergeCopied", copy.FileName)); context.Log(Loc.L("Archive.Log.MergeCopied", copy.FileName));
} }
} }
/// <summary>
/// Leaves the second version <paramref name="sha"/> just filed in the kept sequence out of Main at once (owner Q3), not
/// only at the Details stage: a merge abandoned before that stage (its details changed meanwhile, a stale stage, a
/// cancel) would otherwise leave both versions in Main for good, and a new plan, which reads both as the kept
/// sequence's own photos, leaves neither out. Written under the kept sequence's lease at the settings version read
/// just before (asked again when an edit lands in between); when that was the version the plan read, the Details
/// stage then writes at the version this write made (the plan's payload leaves the version out as well). Settings
/// that are not a project of this Chronos are left as they are, as the plan leaves them. Not cancelled halfway: a
/// filed version is never left in Main by a cancel.
/// </summary>
private async Task LeaveOutOfMainAsync(string sha)
{
var ct = CancellationToken.None;
if (owner.BeforeLeaveOutOfMain is { } hook) await hook(sha).ConfigureAwait(false);
for (var attempt = 1; ; attempt++)
{
var keep = await _db.Sequences.GetAsync(journal.KeepId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
var basis = CopyPayload.Portable(SyncPayload.Of(keep), await SequencePayloadWriter.PhotosAsync(_db, journal.KeepId, null, ct).ConfigureAwait(false));
SyncPayload excluded;
try
{
excluded = CopyPayload.ExcludeVersions(basis, [sha.ToLowerInvariant()]);
}
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException)
{
return;
}
if (excluded.SameAs(basis)) return;
try
{
var updated = await new SequencePayloadWriter(_db, owner.Archives).ApplyAsync(journal.KeepId, excluded, keep.SettingsVersion, ct)
.ConfigureAwait(false);
if (journal.KeepSettingsVersion == keep.SettingsVersion) journal.KeepSettingsVersion = updated.SettingsVersion;
return;
}
catch (SyncConflictChangedException) when (attempt < 3)
{
// Edited between the read and the lease: read again.
}
}
}
/// <summary> /// <summary>
/// Copies a frame of the other into staging (hash-checked against <paramref name="expected"/>) and files it in the /// 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 /// kept sequence. <paramref name="planned"/>: the plan knew the photo's content (else a tombstone of the kept sequence
@@ -650,7 +598,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
var keepRemoved = (await _db.FrameRemovals.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false)) var keepRemoved = (await _db.FrameRemovals.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false))
.Select(r => r.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal); .Select(r => r.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var failed = new List<(Guid FrameId, string Sha256, bool Unhashed)>(); var failed = new List<(Guid FrameId, string Sha256)>();
foreach (var frame in dropFrames) foreach (var frame in dropFrames)
{ {
_ct.ThrowIfCancellationRequested(); _ct.ThrowIfCancellationRequested();
@@ -662,35 +610,9 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
?? throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName)); ?? throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
if (frame.Sha256 is { Length: > 0 } recorded && !string.Equals(recorded, sha, StringComparison.OrdinalIgnoreCase)) if (frame.Sha256 is { Length: > 0 } recorded && !string.Equals(recorded, sha, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName)); throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
var version = journal.SecondVersions.Contains(frame.Id);
if (version && journal.VersionShas.GetValueOrDefault(frame.Id) is var filedAs
&& !string.Equals(filedAs, sha, StringComparison.OrdinalIgnoreCase))
{
// A run that stopped while filing it as a second version read other bytes: changed since.
if (filedAs is null || !held.ContainsKey(filedAs))
{
// Nothing was filed (the copy failed or read other bytes): visited as for the first time.
journal.SecondVersions.Remove(frame.Id);
journal.VersionShas.Remove(frame.Id);
Save();
version = false;
}
else
{
// The old bytes were filed: left out of Main now (a new plan reads them as the kept sequence's
// own photo), then the merge stops and is planned again, which compares the new bytes.
await LeaveOutOfMainAsync(filedAs).ConfigureAwait(false);
ForgetJournal();
throw new InvalidOperationException(Loc.L("Errors.Copies.ChangedFile", frame.FileName));
}
}
if (held.TryGetValue(sha, out var keepFrame)) if (held.TryGetValue(sha, out var keepFrame))
{ {
// Filed as a second version by a run that stopped before the journal said so: left out of Main again
// (nothing changes when it already is), and still left out at the Details stage.
if (version) await LeaveOutOfMainAsync(sha).ConfigureAwait(false);
journal.Verified[frame.Id] = new MergeVerified(sha, keepFrame); journal.Verified[frame.Id] = new MergeVerified(sha, keepFrame);
if (version) Save();
continue; continue;
} }
if (journal.Absent.Contains(sha)) if (journal.Absent.Contains(sha))
@@ -702,20 +624,14 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
if (frame.Sha256 is not { Length: > 0 } && !keepRemoved.Contains(sha)) 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. // Compared by size and time only, and another photo after all: filed in the kept sequence as a second version.
// The journal says so before it is filed: a run that stops before it is left out of Main (the exclusion
// fails, the app ends) finds it in the kept sequence on resume and leaves it out then.
if (!version) journal.SecondVersions.Add(frame.Id);
journal.VersionShas[frame.Id] = sha.ToLowerInvariant();
Save();
if (owner.BeforeFileVersion is { } fileHook) await fileHook(frame.Id).ConfigureAwait(false);
var filed = await FileAsync(frame, sha, planned: false).ConfigureAwait(false); var filed = await FileAsync(frame, sha, planned: false).ConfigureAwait(false);
await LeaveOutOfMainAsync(sha).ConfigureAwait(false); journal.SecondVersions.Add(frame.Id);
journal.Verified[frame.Id] = new MergeVerified(sha, filed.FrameId); journal.Verified[frame.Id] = new MergeVerified(sha, filed.FrameId);
held.TryAdd(sha, filed.FrameId); held.TryAdd(sha, filed.FrameId);
Save(); Save();
continue; continue;
} }
failed.Add((frame.Id, sha, frame.Sha256 is not { Length: > 0 })); failed.Add((frame.Id, sha));
} }
if (failed.Count > 0) if (failed.Count > 0)
{ {
@@ -723,24 +639,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
// sequence's index rows prove nothing: its files were hashed again above and did not hold it. // sequence's index rows prove nothing: its files were hashed again above and did not hold it.
var others = await new CopySides(_db).HeldElsewhereAsync([.. failed.Select(f => f.Sha256)], [journal.DropId, journal.KeepId], _ct) var others = await new CopySides(_db).HeldElsewhereAsync([.. failed.Select(f => f.Sha256)], [journal.DropId, journal.KeepId], _ct)
.ConfigureAwait(false); .ConfigureAwait(false);
var lostFrames = failed.Where(f => !others.Contains(f.Sha256)).ToList(); var lost = failed.Where(f => !others.Contains(f.Sha256)).Select(f => f.Sha256).Distinct(StringComparer.Ordinal).Count();
if (lostFrames.Any(f => f.Unhashed && keepRemoved.Contains(f.Sha256)))
{
// Content the kept sequence deleted, which the plan never compared by content (unhashed, matched by size
// and time): a last copy the plan did not list. Retrying this journal would fail the same way: it goes,
// and the new plan lists it.
ForgetJournal();
throw new StaleCopyPlanException();
}
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)); if (lost > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.VerifyFailed", lost));
journal.Settled.AddRange(failed.Select(f => f.FrameId)); journal.Settled.AddRange(failed.Select(f => f.FrameId));
// Held by a third sequence now: asked again before the trash, which that sequence may not wait for. // Held by a third sequence now: asked again before the trash, which that sequence may not wait for.
@@ -105,14 +105,6 @@ internal sealed class MergeJournal
/// <summary>Drop frames the verify found to be another photo than keep's (unhashed, same size and time) and filed as a second version.</summary> /// <summary>Drop frames the verify found to be another photo than keep's (unhashed, same size and time) and filed as a second version.</summary>
public List<Guid> SecondVersions { get; set; } = []; public List<Guid> SecondVersions { get; set; } = [];
/// <summary>
/// Drop frame of <see cref="SecondVersions"/> → the SHA-256 it is filed as, written before it is filed: a resumed verify
/// that finds it in the kept sequence leaves it out of Main again. One that reads other bytes starts over for that frame
/// when the kept sequence does not hold the old ones (nothing was filed), else leaves them out of Main and stops, and the
/// merge is planned again.
/// </summary>
public Dictionary<Guid, string> VersionShas { get; set; } = [];
/// <summary>Drop frames the verify found nothing of to lose: last copies the plan listed, or photos a third sequence holds.</summary> /// <summary>Drop frames the verify found nothing of to lose: last copies the plan listed, or photos a third sequence holds.</summary>
public List<Guid> Settled { get; set; } = []; public List<Guid> Settled { get; set; } = [];
+3 -14
View File
@@ -124,10 +124,10 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
var here = await _sides.LocalAsync(keep, ct).ConfigureAwait(false); var here = await _sides.LocalAsync(keep, ct).ConfigureAwait(false);
var there = await _sides.LocalAsync(drop, ct).ConfigureAwait(false); var there = await _sides.LocalAsync(drop, ct).ConfigureAwait(false);
var comparison = CopyComparer.Compare(here, there); var comparison = CopyComparer.Compare(here, there);
if (online && await HashUnhashedThereAsync(comparison, there, dropPaths, here.Removed.Count > 0, ct).ConfigureAwait(false) is { } hashed) if (online && await HashOnlyThereAsync(comparison, there, dropPaths, ct).ConfigureAwait(false) is { } hashed)
{ {
// Compared by content now: a photo the kept sequence deleted reads Deleted here (a last copy when nothing else // Compared by content now: a photo the kept sequence deleted reads Deleted here (a last copy when nothing else
// holds it), never a copy the kept sequence's tombstone refuses nor a photo the verify cannot find held. // holds it), never a copy the kept sequence's tombstone refuses.
there = hashed; there = hashed;
comparison = CopyComparer.Compare(here, there); comparison = CopyComparer.Compare(here, there);
} }
@@ -288,22 +288,11 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
/// <summary> /// <summary>
/// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none. /// The other's unhashed photos only it holds, hashed now (in memory: a dry run writes nothing); null when there are none.
/// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted. /// Matched by size and time only they would be copied blindly, even a photo whose content the kept sequence deleted.
/// When the kept sequence has tombstones (<paramref name="keepDeleted"/>), also every unhashed frame of the other that
/// the comparison matched by size and time with a photo of the kept one (<see cref="PhotoClass.SameUnhashed"/>, each
/// frame of that size and instant): one of them may be content the kept sequence deleted (a burst of one size in one
/// whole second), which nothing would copy, list or find held, so the merge would fail at its verify on every retry.
/// </summary> /// </summary>
private async Task<CopySideInput?> HashUnhashedThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, bool keepDeleted, private async Task<CopySideInput?> HashOnlyThereAsync(CopyComparisonResult comparison, CopySideInput there, ArchivePaths dropPaths, CancellationToken ct)
CancellationToken ct)
{ {
var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal)) var keys = comparison.Photos.Where(p => p.Class == PhotoClass.OnlyThere && p.Key.StartsWith(CopyComparer.UnhashedPrefix, StringComparison.Ordinal))
.Select(p => p.Key).ToHashSet(StringComparer.Ordinal); .Select(p => p.Key).ToHashSet(StringComparer.Ordinal);
if (keepDeleted)
{
foreach (var photo in comparison.Photos)
if (photo is { Class: PhotoClass.SameUnhashed, There: { Sha256: null or { Length: 0 }, CapturedAt: not null } theirs })
keys.Add(CopyComparer.UnhashedKey(theirs.Size, theirs.CapturedAt, theirs.FrameId));
}
if (keys.Count == 0) return null; if (keys.Count == 0) return null;
var photos = new List<CopyPhotoInput>(there.Photos.Count); var photos = new List<CopyPhotoInput>(there.Photos.Count);
var changed = false; var changed = false;
+4 -44
View File
@@ -199,20 +199,14 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
} }
/// <summary> /// <summary>
/// A 404 for the remote side (design §6.3): the pair's row (made when the link had none) counts one hit per /// A 404 for the remote side (design §6.3): nothing when <paramref name="localId"/> is null (an observation-only link);
/// <paramref name="refreshId"/>, and a hit after the first only once <see cref="GoneRecheck"/> has passed since it, and /// else the pair's row (made when the link had none) counts one hit per <paramref name="refreshId"/>, and a hit after the
/// every Candidate row naming that remote is deleted. With <paramref name="localId"/> null (an observation-only link: no /// first only once <see cref="GoneRecheck"/> has passed since it, and every Candidate row naming that remote is deleted.
/// local copy is linked to it) the Candidate rows naming that remote go and its Kept apart rows count the hit the same way
/// (<see cref="SettleUnlinkedGoneAsync"/>).
/// </summary> /// </summary>
public async Task MarkRemoteGoneAsync(string server, Guid remoteId, Guid? localId, Guid refreshId, DateTimeOffset at, CancellationToken ct) public async Task MarkRemoteGoneAsync(string server, Guid remoteId, Guid? localId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
{ {
ArgumentException.ThrowIfNullOrWhiteSpace(server); ArgumentException.ThrowIfNullOrWhiteSpace(server);
if (localId is not { } local) if (localId is not { } local) return;
{
await SettleUnlinkedGoneAsync(server, remoteId, refreshId, at, ct).ConfigureAwait(false);
return;
}
var refreshes = GoneRefreshes.GetOrCreateValue(db.Database); var refreshes = GoneRefreshes.GetOrCreateValue(db.Database);
var counted = refreshes.TryGetValue((server, remoteId), out var last) && last == refreshId; var counted = refreshes.TryGetValue((server, remoteId), out var last) && last == refreshId;
await _db.InTransactionAsync(async session => await _db.InTransactionAsync(async session =>
@@ -237,40 +231,6 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
refreshes[(server, remoteId)] = refreshId; refreshes[(server, remoteId)] = refreshId;
} }
/// <summary>
/// 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 <paramref name="refreshId"/>, a second only once
/// <see cref="GoneRecheck"/> 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 (<see cref="FoundCopy.RemoteGone"/>) lets Upload all local send the local sequence
/// (<see cref="UploadAllRule"/>). Linked, Integrated and Integrating rows are left to their link's own 404.
/// </summary>
public async Task SettleUnlinkedGoneAsync(string server, Guid remoteId, Guid refreshId, DateTimeOffset at, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(server);
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;
}
/// <summary>The server answered for the remote again: hits back to 0, no gone time.</summary> /// <summary>The server answered for the remote again: hits back to 0, no gone time.</summary>
public Task ClearRemoteGoneAsync(string server, Guid remoteId, CancellationToken ct) public Task ClearRemoteGoneAsync(string server, Guid remoteId, CancellationToken ct)
{ {
+1 -8
View File
@@ -55,10 +55,7 @@ public static class UploadAllRule
foreach (var entry in localOnly) foreach (var entry in localOnly)
{ {
if (entry.Local is not { } local) continue; if (entry.Local is not { } local) continue;
// A Kept apart answer given before a server sequence was confirmed deleted there (two 404s apart) holds nothing var pairs = bySequence.GetValueOrDefault(local.Id) ?? [];
// back: that sequence is no copy of anything any more, and the local one is this PC's only. A Keep here, answered
// once the deletion was shown, is the user's answer about the deletion itself: it still skips.
var pairs = (bySequence.GetValueOrDefault(local.Id) ?? []).Where(p => !ApartBeforeDeletion(p)).ToList();
UploadSkip? why = UploadSkip? why =
busy.Contains(local.Id) || pairs.Any(p => p.State == CopyState.Integrating) ? UploadSkip.Busy 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 : pairs.Any(p => p.Kind == CopyKind.LocalServer && p.RemoteGoneHits >= 1) ? UploadSkip.DeletedOnServer
@@ -71,10 +68,6 @@ public static class UploadAllRule
} }
return (upload, skipped); return (upload, skipped);
static bool ApartBeforeDeletion(FoundCopy p) =>
p is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart, RemoteGone: true, AnsweredAt: { } answered, RemoteGoneAt: { } gone }
&& answered < gone;
void Add(Guid id, FoundCopy copy) void Add(Guid id, FoundCopy copy)
{ {
if (!bySequence.TryGetValue(id, out var list)) bySequence[id] = list = []; if (!bySequence.TryGetValue(id, out var list)) bySequence[id] = list = [];
+6 -16
View File
@@ -643,15 +643,13 @@ 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 // 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 // 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. // 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(); var metadata = absorbed.Where(p => p.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal)).ToList();
if (metadata.Any(p => lined.Contains(p) && !notLocal.Contains(p))) throw DetailsChanged(); if (metadata.Count > 0)
// 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 var lined = CopyPayload.Moved(plannedLocal, plannedRemote);
// user's choice on both sides. var notLocal = CopyPayload.Moved(plannedLocal, finalPortable);
var sinceLocal = CopyPayload.Moved(plannedLocal, freshRemote); if (metadata.Any(p => lined.Contains(p) && !notLocal.Contains(p))) throw DetailsChanged();
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), final = CopyPayload.Merge(final, freshRemote, absorbed.ToDictionary(p => p, _ => CopySide.Other, StringComparer.Ordinal),
[.. absorbed.Select(p => new DetailLine(p, null, null))]); [.. absorbed.Select(p => new DetailLine(p, null, null))]);
} }
@@ -712,10 +710,6 @@ public sealed class SyncService
return result; return result;
static SyncConflictChangedException DetailsChanged() => new(Loc.L("Errors.Copies.DetailsChanged")); 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; private const int AgreeAttempts = 3;
@@ -987,10 +981,6 @@ public sealed class SyncService
var localChanged = link.BaseLocalSettings != local.SettingsVersion; var localChanged = link.BaseLocalSettings != local.SettingsVersion;
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion; var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
if (!localChanged && !remoteChanged) return (link, local); 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. // 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) if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is { } current && current.SettingsVersion == local.SettingsVersion)
local = current; local = current;
+19 -69
View File
@@ -37,9 +37,6 @@ internal sealed class SyncTransfers(SyncService sync)
{ {
private const long SpaceReserve = 512L << 20; private const long SpaceReserve = 512L << 20;
/// <summary>The upload checkpoint's suffix for a server sequence the job joined (one this PC already knew), not made.</summary>
private const string JoinedMark = ":joined";
/// <summary>Space a cached proxy is assumed to take before it is downloaded (1920 px JPEG, BRIEF §8.5).</summary> /// <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; private const long ProxyEstimate = 3L << 19;
@@ -84,9 +81,6 @@ internal sealed class SyncTransfers(SyncService sync)
// is filed into the new sequence once there is one). // is filed into the new sequence once there is one).
var heldElsewhere = new List<Frame>(); var heldElsewhere = new List<Frame>();
var sessionKey = remoteId is null ? await SessionKeyAsync(context, remote, local).ConfigureAwait(false) : null; 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)) while (remoteId is null && pending.TryDequeue(out var first))
{ {
var sent = await UploadFrameAsync(context, remote, null, sessionKey, paths.FromRelative(first.RelativePath), first, tombstones, var sent = await UploadFrameAsync(context, remote, null, sessionKey, paths.FromRelative(first.RelativePath), first, tombstones,
@@ -96,10 +90,7 @@ internal sealed class SyncTransfers(SyncService sync)
else if (sent.SequenceId != Guid.Empty) else if (sent.SequenceId != Guid.Empty)
{ {
remoteId = sent.SequenceId; remoteId = sent.SequenceId;
if (knownRemotes.Contains(sent.SequenceId)) created = false; await context.CheckpointAsync(sent.SequenceId.ToString(), progress.Done + 1, frames.Count).ConfigureAwait(false);
// Saved with the target: a resumed or retried attempt reads whether this job made it, never infers it.
await context.CheckpointAsync(sent.SequenceId.ToString() + (created ? string.Empty : JoinedMark), progress.Done + 1, frames.Count)
.ConfigureAwait(false);
await sync.LinkAsync(remote.Server, sent.SequenceId, local, ct).ConfigureAwait(false); await sync.LinkAsync(remote.Server, sent.SequenceId, local, ct).ConfigureAwait(false);
} }
await progress.StepAsync().ConfigureAwait(false); await progress.StepAsync().ConfigureAwait(false);
@@ -510,21 +501,6 @@ internal sealed class SyncTransfers(SyncService sync)
var paths = new ArchivePaths(archive.RootPath); var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths); 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 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 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); var (have, restore, photos, missing) = local is null ? ([], [], new FramePhotos([]), []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
@@ -562,6 +538,7 @@ internal sealed class SyncTransfers(SyncService sync)
if (local is null && wanted.Count > 0) if (local is null && wanted.Count > 0)
{ {
// The first original creates the local sequence (grouped by the server id); the others join it. // 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 (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); 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) local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
@@ -967,15 +944,11 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary> /// <summary>
/// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted /// The server sequence an upload fills and whether this job creates it: the linked one, the one an interrupted
/// attempt created (unless the user kept it apart or unlinked it since), or none yet (the first original creates it). /// attempt created (unless the user kept it apart or unlinked it since), or none yet (the first original creates it).
/// The checkpoint names the server sequence an earlier attempt reached, with <see cref="JoinedMark"/> when that attempt
/// joined one this PC already knew (its details are compared, never sent all over the server's, on every attempt).
/// </summary> /// </summary>
private async Task<(Guid? RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local) private async Task<(Guid? RemoteId, bool Created)> TargetAsync(JobContext context, ISyncRemote remote, Sequence local)
{ {
var ct = context.Cancellation; var ct = context.Cancellation;
var checkpoint = context.Checkpoint ?? string.Empty; Guid? started = Guid.TryParse(context.Checkpoint, out var saved) ? saved : null;
var joined = checkpoint.EndsWith(JoinedMark, StringComparison.Ordinal);
Guid? started = Guid.TryParse(joined ? checkpoint[..^JoinedMark.Length] : checkpoint, out var saved) ? saved : null;
var link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false); var link = await sync.Links.FindByLocalAsync(remote.Server, local.Id, ct).ConfigureAwait(false);
foreach (var candidate in new[] { link?.RemoteId, started }) foreach (var candidate in new[] { link?.RemoteId, started })
{ {
@@ -987,7 +960,7 @@ internal sealed class SyncTransfers(SyncService sync)
if (await ExistsAsync(remote, id, ct).ConfigureAwait(false)) if (await ExistsAsync(remote, id, ct).ConfigureAwait(false))
{ {
if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false); if (link?.RemoteId != id) await sync.LinkAsync(remote.Server, id, local, ct).ConfigureAwait(false);
return (id, id == started && !joined); return (id, id == started);
} }
// Deleted on the server meanwhile: the originals go into a new sequence. // Deleted on the server meanwhile: the originals go into a new sequence.
if (id == link?.RemoteId) await sync.ForgetGoneAsync(remote.Server, id, ct).ConfigureAwait(false); if (id == link?.RemoteId) await sync.ForgetGoneAsync(remote.Server, id, ct).ConfigureAwait(false);
@@ -997,58 +970,35 @@ internal sealed class SyncTransfers(SyncService sync)
/// <summary> /// <summary>
/// The session key the first original of an upload without a target goes under: this sequence's own /// The session key the first original of an upload without a target goes under: this sequence's own
/// (<see cref="SyncService.SessionKey"/>), unless it has a pair with a sequence of this server that the user has not /// (<see cref="SyncService.SessionKey"/>), unless the user kept it apart from (or unlinked it from) a sequence of this
/// linked (kept apart, unlinked, or asked about again). The server files that key into the sequence an earlier upload /// server. The server files that key into the sequence an earlier upload made, which the user chose to keep separate;
/// made, which the user separated; such an upload makes a new sequence instead, under a key of this job (the same on a /// such an upload makes a new sequence instead, under a key of this job (the same on a retry).
/// retry).
/// </summary> /// </summary>
private async Task<string> SessionKeyAsync(JobContext context, ISyncRemote remote, Sequence local) private async Task<string> SessionKeyAsync(JobContext context, ISyncRemote remote, Sequence local)
{ {
var own = SyncService.SessionKey(local.Id); 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)) var apart = (await sync.Copies.ListByLocalAsync(local.Id, context.Cancellation).ConfigureAwait(false))
.Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart or CopyState.Candidate } .Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.KeptApart } && string.Equals(c.Server, remote.Server, StringComparison.Ordinal)
&& string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == local.Id); && c.LocalId == local.Id);
return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own; return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
} }
/// <summary> /// <summary>
/// The session key the first original of a download without a local copy goes under: the server sequence's own /// The session key the first original of a download without a local copy goes under: the server sequence's own
/// (<see cref="SyncService.SessionKey"/>), which groups the download in the local sequence an earlier download of it made /// (<see cref="SyncService.SessionKey"/>), which groups the download in the local sequence an earlier download of it made,
/// (refilled and linked again: a link a 404 forgot, a pair asked about again), unless the user separated that sequence /// unless that sequence has been unlinked or kept apart from it, or linked to another sequence of this server since (it
/// from it: their pair is Kept apart (kept apart, or unlinked), or it is linked to another sequence of this server. Such /// has a pair or a link for this server). The user chose to keep such a sequence separate: the download makes a new
/// a download makes a new local sequence instead, under a key of this job (the same on a retry), and never fills or /// local sequence instead, under a key of this job (the same on a retry), and never fills or overwrites the other.
/// overwrites the other.
/// </summary> /// </summary>
/// <returns> private async Task<string> 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.
/// </returns>
private async Task<(string Key, Guid? Joins)> DownloadKeyAsync(JobContext context, ISyncRemote remote, Guid remoteId, Guid archiveId)
{ {
var ct = context.Cancellation; var ct = context.Cancellation;
var own = SyncService.SessionKey(remoteId); var own = SyncService.SessionKey(remoteId);
if (await sync.Database.Sequences.FindBySessionKeyAsync(archiveId, own, ct).ConfigureAwait(false) is not { } holder) return (own, null); if (await sync.Database.Sequences.FindBySessionKeyAsync(archiveId, own, ct).ConfigureAwait(false) is not { } holder) return own;
var pairs = (await sync.Copies.ListByLocalAsync(holder, ct).ConfigureAwait(false)) var apart = (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 .Any(c => c.Kind == CopyKind.LocalServer && string.Equals(c.Server, remote.Server, StringComparison.Ordinal) && c.LocalId == holder)
&& c.RemoteId == remoteId) || await sync.Links.FindByLocalAsync(remote.Server, holder, ct).ConfigureAwait(false) is not null;
.ToList(); return apart ? string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}") : own;
var apart = pairs.Any(c => c.State == CopyState.KeptApart)
|| await sync.Links.FindByLocalAsync(remote.Server, holder, ct).ConfigureAwait(false) is { } link && link.RemoteId != remoteId;
if (apart) return (string.Create(CultureInfo.InvariantCulture, $"{own}:{context.Job.Id:N}"), null);
return (own, pairs.Count > 0 ? holder : null);
}
/// <summary>The server sequences of <paramref name="remote"/> this PC knows of: listed or linked, or paired with <paramref name="localId"/>.</summary>
private async Task<HashSet<Guid>> 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<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken) private static async Task<bool> ExistsAsync(ISyncRemote remote, Guid id, CancellationToken cancellationToken)
@@ -599,204 +599,6 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0)); AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
} }
[Test]
public async Task AVersionTheVerifyFiledBeforeTheRunStoppedIsLeftOutOfMainOnResume()
{
var fx = await FixtureAsync();
var (mine, theirs) = EqualSizeSeeds(0);
var keep = await SequenceAsync(fx, "keep", [(mine, 0, "IMG_0001.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(theirs, 0, "IMG_0001.JPG")]);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1 OR sequence_id = $2", [keep.Id, drop.Id], Ct);
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);
// Filed at the verify, then the exclusion fails (a drive drops out, project.json is held) before the journal says so.
var failedOnce = false;
handler.BeforeLeaveOutOfMain = _ =>
{
if (failedOnce) return Task.CompletedTask;
failedOnce = true;
throw new IOException("project.json is in use");
};
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.Empty(plan.Photos);
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0), Sha(theirs, 0)]));
await engine.ResumeAsync(job.Id, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
// The resumed verify finds the version in the kept sequence and leaves it out of Main: one photo at that instant.
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
}
[Test]
public async Task AVersionWhoseFileChangedBeforeItWasFiledIsFiledAsItIsOnResume()
{
var fx = await FixtureAsync();
var (mine, theirs) = EqualSizeSeeds(0);
var edited = EqualSizeSeed(0, theirs, mine);
var keep = await SequenceAsync(fx, "keep", [(mine, 0, "IMG_0001.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(theirs, 0, "IMG_0001.JPG")]);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1 OR sequence_id = $2", [keep.Id, drop.Id], Ct);
var path = fx.Paths.FromRelative((await fx.Db.Frames.ListBySequenceAsync(drop.Id)).Single().RelativePath);
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);
// The file is rewritten (an editor saving a rotation) between its hash and its copy: the copy reads other bytes.
var rewritten = false;
handler.BeforeFileVersion = _ =>
{
if (rewritten) return Task.CompletedTask;
rewritten = true;
File.WriteAllBytes(path, Photos.Jpeg(Start, edited));
return Task.CompletedTask;
};
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0)]), "nothing was filed");
await engine.ResumeAsync(job.Id, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
// Nothing was filed: the retry files the photo as it is now, as a second version left out of Main.
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0), Sha(edited, 0)]));
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(edited, 0));
}
[Test]
public async Task AVersionFiledBeforeItsFileChangedIsLeftOutOfMainAndTheMergePlannedAgain()
{
var fx = await FixtureAsync();
var (mine, theirs) = EqualSizeSeeds(0);
var edited = EqualSizeSeed(0, theirs, mine);
var keep = await SequenceAsync(fx, "keep", [(mine, 0, "IMG_0001.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(theirs, 0, "IMG_0001.JPG")]);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1 OR sequence_id = $2", [keep.Id, drop.Id], Ct);
var dropFrame = (await fx.Db.Frames.ListBySequenceAsync(drop.Id)).Single();
var path = fx.Paths.FromRelative(dropFrame.RelativePath);
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);
// Filed at the verify, then the exclusion fails; the file is rewritten before the retry.
var failedOnce = false;
handler.BeforeLeaveOutOfMain = _ =>
{
if (failedOnce) return Task.CompletedTask;
failedOnce = true;
File.WriteAllBytes(path, Photos.Jpeg(Start, edited));
throw new IOException("project.json is in use");
};
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(mine, 0), Sha(theirs, 0)]));
await engine.ResumeAsync(job.Id, Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
// The filed version is left out of Main, the other stays, and the journal goes: the next run plans again.
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.ChangedFile", dropFrame.FileName), failed.Error);
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(mine, 0), Sha(theirs, 0));
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)), "the next run plans again");
}
[Test]
public async Task ASecondVersionCopiedInByAMergeAbandonedBeforeItsDetailsStaysOutOfMain()
{
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")]);
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);
// While the photos are copied the user tags the kept one: its details moved, so the Details stage abandons the merge.
handler.BeforeStage = stage => stage == MergeStage.Details ? fx.Db.Sequences.SetTagsAsync(keep.Id, ["edited"], Ct) : Task.CompletedTask;
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.SequenceEqual([(PhotoAction.FetchVersion, Sha(5, 30_250))], plan.Photos.Select(p => (p.Action, p.Sha256!)));
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.DetailsChanged"), failed.Error);
// The version copied in is already left out of Main.
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(4, 30_250), Sha(5, 30_250));
// Planned again (the kept one holds both versions now) and merged: still one photo in Main at that instant.
handler.BeforeStage = null;
plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.Empty(plan.Photos);
job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
AssertVersions(await new CopySides(fx.Db).VersionsAsync(keep.Id, Ct), Sha(4, 30_250), Sha(5, 30_250));
}
[Test]
public async Task AnUnhashedPhotoMatchedBySizeAndTimeWhoseContentTheKeptOneDeletedIsALastCopy()
{
var fx = await FixtureAsync();
// A whole-second camera shooting a burst of one size: the other holds two photos at one second, not hashed; the kept
// one holds one of them, hashed, and deleted the other.
var (deleted, kept) = EqualSizeSeeds(0);
var keep = await SequenceAsync(fx, "keep", [(kept, 0, "IMG_0002.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(deleted, 0, "IMG_0001.JPG"), (kept, 0, "IMG_0002.JPG")]);
await fx.Db.FrameRemovals.SyncSequenceAsync(keep.Id, [new FrameRemoval(keep.Id, Sha(deleted, 0), null, RemovalReason.Deleted, DateTimeOffset.UtcNow)], Ct);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [drop.Id], Ct);
var copy = await PairAsync(fx, keep.Id, drop.Id);
var merger = Merger(fx);
var (engine, _) = Engine(fx, merger, new FakeProjects(), new FakeWorkspace());
await engine.StartAsync(Ct);
// Compared by content: the deleted photo is a last copy to confirm, nothing to copy.
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.Empty(plan.Photos);
Assert.SequenceEqual([(CopySide.Other, Sha(deleted, 0))], plan.LastCopies.Select(l => (l.Side, l.Key)));
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
Assert.True((await HashesAsync(fx, keep.Id)).SetEquals([Sha(kept, 0)]));
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
}
[Test]
public async Task APhotoTheKeptOneDeletesAfterThePlanMakesTheVerifyAskForANewPlan()
{
var fx = await FixtureAsync();
var (deleted, kept) = EqualSizeSeeds(0);
var keep = await SequenceAsync(fx, "keep", [(kept, 0, "IMG_0002.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(deleted, 0, "IMG_0001.JPG"), (kept, 0, "IMG_0002.JPG")]);
await new DbAccess(fx.Db.Database).ExecuteAsync("UPDATE frames SET sha256 = NULL WHERE sequence_id = $1", [drop.Id], Ct);
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.Union), NoContext, Ct);
Assert.Empty(plan.LastCopies);
// Once planned, the kept one's tombstone for the other photo arrives (a sync of a deletion made elsewhere).
handler.BeforeStage = stage => stage == MergeStage.Verify
? fx.Db.FrameRemovals.SyncSequenceAsync(keep.Id, [new FrameRemoval(keep.Id, Sha(deleted, 0), null, RemovalReason.Deleted, DateTimeOffset.UtcNow)], Ct)
: Task.CompletedTask;
var job = await merger.EnqueueAsync(engine, new FoundCopyStore(fx.Db), plan, keep.DisplayTitle, Ct);
var failed = await fx.WaitForAsync(job.Id, JobState.Failed);
// Not a verify that fails on every retry: the journal goes, and the new plan lists the photo as a last copy.
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.StalePlan"), failed.Error);
Assert.False(File.Exists(MergeJournal.PathFor(fx.Paths, job.Id)));
Assert.NotNull(await fx.Db.Sequences.GetAsync(drop.Id));
plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union), NoContext, Ct);
Assert.SequenceEqual([(CopySide.Other, Sha(deleted, 0))], plan.LastCopies.Select(l => (l.Side, l.Key)));
}
/// <summary>One photo listed in two versions: <paramref name="kept"/> in Main, <paramref name="incoming"/> left out.</summary> /// <summary>One photo listed in two versions: <paramref name="kept"/> in Main, <paramref name="incoming"/> left out.</summary>
private static void AssertVersions(IReadOnlyList<PhotoVersions> listed, string kept, string incoming) private static void AssertVersions(IReadOnlyList<PhotoVersions> listed, string kept, string incoming)
{ {
@@ -819,14 +621,6 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
} }
} }
/// <summary>A seed other than <paramref name="like"/> and <paramref name="not"/> whose photo at <paramref name="ms"/> has the same size as <paramref name="like"/>'s.</summary>
private static int EqualSizeSeed(int ms, int like, params int[] not)
{
var length = Photos.Jpeg(Start.AddMilliseconds(ms), like).Length;
for (var seed = 1; ; seed++)
if (seed != like && !not.Contains(seed) && Photos.Jpeg(Start.AddMilliseconds(ms), seed).Length == length) return seed;
}
[Test] [Test]
public async Task AnUnhashedPhotoOfTheKeptOneWithTheSameContentIsNoLastCopy() public async Task AnUnhashedPhotoOfTheKeptOneWithTheSameContentIsNoLastCopy()
{ {
@@ -1211,43 +1005,6 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
Assert.Contains(again.LastCopies, l => l.Key == Sha(5, 30_250)); 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] [Test]
public async Task APhotoAddedToTheOtherOrDeletedFromTheKeptOneMeanwhileKeepsTheOtherOutOfTheTrash() public async Task APhotoAddedToTheOtherOrDeletedFromTheKeptOneMeanwhileKeepsTheOtherOutOfTheTrash()
{ {
@@ -183,30 +183,6 @@ public sealed class CopyEngineTests(TestContext context)
Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)); Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct));
} }
[Test]
public async Task KeepHereOfASequenceDeletedOnTheServerIsLeftOutOfUploadAllLocal()
{
await using var f = await FixtureAsync(context);
var local = await f.LocalAsync("Comet", f.NewPhotos(2));
var gone = Guid.CreateVersion7();
var pair = await f.Sync.Copies.EnsureLinkedAsync(f.Server, gone, local.Id, f.Ct);
// Deleted on the server: two 404s the re-check apart, read as deleted on server.
var at = DateTimeOffset.UtcNow.AddHours(-2);
await f.Sync.Copies.MarkRemoteGoneAsync(f.Server, gone, local.Id, Guid.NewGuid(), at, f.Ct);
await f.Sync.Copies.MarkRemoteGoneAsync(f.Server, gone, local.Id, Guid.NewGuid(), at.AddHours(1), f.Ct);
using var engine = Engine(f);
await engine.KeepHereAsync(pair.Id, f.Ct);
// Kept here: Upload all local leaves it out, and the answer stays.
var row = (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!;
Assert.Equal((CopyState.KeptApart, true), (row.State, row.RemoteGone));
var entry = new SyncEntry(local, null, SyncStatus.LocalOnly);
var (upload, skipped) = UploadAllRule.Select([entry], await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(upload);
Assert.Equal(local.Id, skipped.Single().Entry.Local!.Id);
}
[Test] [Test]
public async Task LinkIsRefusedWhenTheLocalCopyIsLinkedToAnotherServerSequence() public async Task LinkIsRefusedWhenTheLocalCopyIsLinkedToAnotherServerSequence()
{ {
@@ -275,51 +275,6 @@ public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(
Assert.Equal(1, (await store.GetAsync(row.Id, Ct))!.RemoteGoneHits); Assert.Equal(1, (await store.GetAsync(row.Id, Ct))!.RemoteGoneHits);
} }
[Test]
public async Task A404OfAServerSequenceNoLocalCopyIsLinkedToDeletesItsCandidatesAndCountsOnItsKeptApartAnswers()
{
var (db, _, s) = await SetupAsync(4);
var store = new FoundCopyStore(db);
var remote = Guid.CreateVersion7();
var candidate = await store.UpsertFoundAsync(Remote(s[0].Id, remote), Ct);
var apart = await store.UpsertFoundAsync(Remote(s[1].Id, remote), Ct);
Assert.True(await store.SetStateAsync(apart.Id, CopyState.Candidate, CopyState.KeptApart, Answer(), Ct));
var linked = await store.UpsertFoundAsync(Remote(s[2].Id, remote), Ct);
Assert.True(await store.SetStateAsync(linked.Id, CopyState.Candidate, CopyState.Linked, Answer(), Ct));
var elsewhere = await store.UpsertFoundAsync(Remote(s[3].Id, Guid.CreateVersion7()), Ct);
// After the answers, an observation-only link answers 404: no local copy is linked to it.
var first = Guid.NewGuid();
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(1), Ct);
await store.MarkRemoteGoneAsync(Nas, remote, null, first, TestData.Now.AddMinutes(2), Ct);
// 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));
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 entries = s[..2].Select(q => new SyncEntry(q, null, SyncStatus.LocalOnly)).ToList();
var (upload, skipped) = UploadAllRule.Select(entries, await store.ListAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
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<Guid>(), new HashSet<Guid>());
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] [Test]
public async Task MoveToKeptMovesKeysLinksAndPairsAndIsIdempotent() public async Task MoveToKeptMovesKeysLinksAndPairsAndIsIdempotent()
{ {
@@ -800,73 +800,6 @@ public sealed class IntegrateTests(TestContext context)
Assert.Equal("Comet (night)", remote.Title); Assert.Equal("Comet (night)", remote.Title);
} }
/// <summary>
/// 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.
/// </summary>
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] [Test]
public async Task ACancelledQueuedJobSetsThePairBack() public async Task ACancelledQueuedJobSetsThePairBack()
{ {
@@ -177,60 +177,6 @@ public sealed class SyncServiceCopyTests(TestContext context)
Assert.True(pair.NeedsAttention); Assert.True(pair.NeedsAttention);
} }
[Test]
public async Task AMatchWhoseServerSequenceIsDeletedIsGoneAfterTheRefreshAndUploadAllSendsTheLocalOne()
{
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.Equal((CopyState.Candidate, local.Id), (pair.State, pair.LocalId));
Assert.Null((await f.Sync.Links.GetAsync(nas.Server, remote.Id, f.Ct))!.LocalId);
// Deleted on the server: no longer listed, and a 404 when asked for.
nas.Sequences.Remove(remote.Id);
await f.Sync.RefreshAsync(nas, new SyncPolicy(), f.Ct);
Assert.Null(await f.Sync.Copies.GetAsync(pair.Id, f.Ct));
var entries = (await f.Sync.ListAsync(nas.Server, f.Ct)).Where(e => e.Local?.Id == local.Id).ToList();
var (upload, skipped) = UploadAllRule.Select(entries, await f.Sync.Copies.ListAsync(f.Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(skipped);
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] [Test]
public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain() public async Task ASequenceReadAsDeletedOnTheServerIsClearedWhenItIsListedAgainOrLinkedAgain()
{ {
@@ -263,193 +263,6 @@ public sealed class SyncTransferCopyTests(TestContext context)
Assert.True((await LocalHashesAsync(f, copy)).SetEquals(photos.Select(Sha))); Assert.True((await LocalHashesAsync(f, copy)).SetEquals(photos.Select(Sha)));
} }
[Test]
public async Task DownloadingAgainAServerSequenceWhoseLinkA404ForgotRefillsAndLinksItsOwnLocalCopy()
{
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);
// A refresh's 404 forgot the link (the archive was briefly offline); listed again, the pair is asked about again.
await f.Sync.Links.DeleteAsync(f.Server, remote.Id, 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, pair.State, CopyState.Candidate, null, f.Ct));
// Download originals of the server-only sequence: it goes back into its own local copy, linked again.
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);
Assert.Equal(local, Assert.NotNull(await f.Sync.Links.GetAsync(f.Server, remote.Id, f.Ct)).LocalId);
Assert.Count(3, await f.Db.Frames.ListBySequenceAsync(local, cancellationToken: f.Ct));
Assert.True((await LocalHashesAsync(f, local)).SetEquals(photos.Select(Sha)));
var keys = await f.Db.Sequences.ListSessionKeysAsync(f.Archive.Archive.Id, SyncService.SessionKey(remote.Id) + "%", f.Ct);
Assert.True(keys.All(k => k.SequenceId == local), "no second local sequence holds a key of the server sequence");
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 ARetriedUploadThatJoinedAServerSequenceItKnewStillComparesItsDetails()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
var photos = f.NewPhotos(4);
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; the server sequence is listed again and renamed there.
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]);
await f.AddLocalAsync(local.Id, photos[3]);
// One original unreadable for the first attempt: it fails after joining the known sequence.
var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(photos[3]));
var path = f.Archive.Paths.FromRelative(damaged.RelativePath);
var bytes = await File.ReadAllBytesAsync(path, f.Ct);
var broken = bytes.ToArray();
broken[^3] ^= 0xFF;
await File.WriteAllBytesAsync(path, broken, f.Ct);
var row = new Job
{
Id = Guid.CreateVersion7(),
Kind = JobKind.UploadCommit,
TargetIds = [local.Id],
State = JobState.Running,
NodeId = "t#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
};
await f.Db.Jobs.EnqueueAsync(row, f.Ct);
var jobs = new JobEngine(f.Db, [], new JobEngineOptions { WorkerId = "t" });
var attempt = new JobContext(jobs, row, f.Ct);
await Assert.ThrowsAsync<InvalidDataException>(() => new SyncTransfers(f.Sync).UploadAsync(attempt, f.Remote, local.Id));
Assert.Equal(first, Assert.NotNull(await f.Sync.Links.FindByLocalAsync(f.Server, local.Id, f.Ct)).RemoteId);
// Retried from that attempt's checkpoint, the original readable again.
await File.WriteAllBytesAsync(path, bytes, f.Ct);
var retry = new JobContext(jobs, row with { Checkpoint = attempt.Checkpoint }, f.Ct);
await new SyncTransfers(f.Sync).UploadAsync(retry, f.Remote, local.Id);
// Still joined, not made by this upload: the server's title is not overwritten unseen.
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] [Test]
public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing() public async Task AnAutomaticUploadAfterTheServerCopyIsGoneFailsAndCreatesNothing()
{ {