Skip to content

Share durable sync operations between folder agent and CFAPI - #487

Draft
cre4ture wants to merge 84 commits into
mainfrom
feat/durable-shared-sync
Draft

cre4ture wants to merge 84 commits into
mainfrom
feat/durable-shared-sync

Conversation

@cre4ture

@cre4ture cre4ture commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

Interrupted sync and large remote trees need progress that survives restart and continues without another remote change. This PR shares a durable SQLite operation lifecycle between folder-agent materialization and CFAPI synchronization.

  • The shared journal provides indexed readiness, dependency ordering, retries, resource leases, immutable intents, checkpoints, guarded observation publication, conflict proofs and graph-safe terminal retention. Scoped folder-agent reconciliation preserves implicit-parent prerequisites and newer local mutations or conflict reviews.
  • CFAPI uses bounded placeholder batches, durable local delete/rename intents, accepted-upload recovery and deadline-driven workers. One typed namespace queue compiles effects independently: refused effects retain visible diagnostics and reservations while healthy siblings progress. Dependencies refer to actual issued occurrences. Diagnostic publication and repair use atomic observation CAS. Namespace operations require physical source proofs, protected native handles and FETCH exclusion. File deletion, confirmed empty-directory deletion and cold/empty file moves have receipt-based recovery and atomic baseline/fence completion. Cross-directory moves use atomic EA-owned stages and nonreplacing publication. Placement occurrence tokens distinguish repeated moves at the same revision.
  • Clean resident-file deletion verifies complete on-disk/validated ranges and hashes the protected original object against its frozen source-revision fingerprint. Same-parent, case-only and cross-directory resident moves preserve verified bytes, inode, pin state and hidden AlwaysFull policy when frozen source and target fingerprints and sizes match. A single owning parent-capability set supports existing target directories, including source ancestors and the sync root. Durable EA-owned directory anchors guard overlapping target-parent handle transitions, followed by strong restoration and held nonrecursive cleanup before atomic completion. Source, ancestry and FETCH protection remain held through publication. A moved anchor and its descendants remain protected from upload inference. Unknown, dirty, partial or replaced sources remain protected.
  • Hydration binds callbacks to provider, object, revision, path and physical root/file identity. Full/ranged SDK downloads pin object ID and version through HEAD, retries, fallback, resume and cache keys. Server object-ID directory deletion requires the expected revision and rejects live descendants under the store lock. Both lockfiles address RUSTSEC-2026-0592.

This remains a draft. Remaining work includes narrowing host-ancestor guards so unrelated file operations progress, changed-content policy, directory/parent effects with issued dependencies, remaining conflict choices, production planner cutover, removal of the old CFAPI executor and real existing-root reconciliation tests. No legacy execution switch is planned.

Validation

  • Shared core: all 209 Windows and 207 Linux tests pass, with strict lint. Post-main-merge Windows core tests pass again (7.46 seconds); the local MSVC link uses temporary /DEBUG:NONE after hitting LNK1140. Earlier Linux folder-agent scenarios pass.
  • Native CFAPI: the full 397-test run passed 396 tests (926.28 seconds); its only failure was an obsolete fixture expecting root-target moves to be unsupported. After a test-only correction to use a real identity-size limit, all 13 issuance/isolation tests pass (47.03 seconds). All new topology cases passed in the full run, including pin/AlwaysFull and multichunk preservation, exact redirect counterproofs, all 16 positive-receipt and six ambiguous-interruption cases, FETCH/reader/writer retry, occurrence history and observation CAS. Hashing no longer holds the global baseline mutex. Final strict adapter all-target lint, formatting, diff checks and independent production review pass. Core and adapter sources and dependency manifests are unchanged by the latest main merge.
  • Earlier SDK validation: all 303 tests pass on Windows and Linux. The 41 SQLite/Turso object-ID tests pass. Full locked system-workspace metadata resolution passes on Windows and Linux.
  • On the previous published head 26370c6, 38 checks pass and eight are skipped. The iOS gallery UI check passed after one failed-jobs rerun without source changes. The new head requires fresh CI; Claude review remains blocked by its account quota until 12:00 UTC. Both older conflict-choice threads remain pending the complete choice paths.
  • Final workspace and system checks will be recorded after cutover.

Context Refresh

  • Run just context-refresh and update docs/agent-context.md after the production cutover; implementation documentation is maintained in docs/durable-sync-work.md throughout.

Comment thread crates/adapter-windows-cfapi/src/cli.rs Resolved
Comment on lines +362 to +368
pub(super) fn local_intents(&self) -> Result<Vec<LocalMutation>> {
self.store
.work(LOCAL_SCOPE)?
.into_iter()
.map(|work| serde_json::from_value(work.payload).map_err(Into::into))
.collect()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A conflict local intent is permanent and wedges its paths forever.

local_intents() reads store.work(LOCAL_SCOPE), which selects state IN ('pending','running','conflict'). Nothing in the tree ever moves a row out of conflict:

  • WorkStore::complete_conflict is never called anywhere in the repo (dead code).
  • store.cancel is only used by cancel_missing_uploads (UPLOAD_SCOPE).
  • enqueue_intent/enqueue_deletes go through write_plan(.., replace=false), whose upsert only re-arms when payload/dependencies/resource differ or the row is cancelled — re-detecting the same mutation leaves the row in conflict.

Concrete failure: user renames a placeholder, apply_mutation returns Conflict("rename destination identity changed at {to}") (e.g. the destination was replaced between detection and execution). From then on, for the lifetime of the journal file:

  • protected_paths() permanently contains from and to, so try_walk puts them in handled_renames and skips handle_entry for them — no upload, no hydrate/dehydrate, ever.
  • handle_deleted_entries permanently skips those paths, so a later genuine local delete is never propagated.
  • protected_object_ids()/protected_snapshot_ids() permanently protect that object id in reconcile_remote_object_state_with_protected_ids, and schedule() permanently drops every materialization action under those paths.
  • enqueue_deletes sets depends_on on child object ids, and refresh_ready treats a non-complete parent as unsatisfied, so one conflicted child delete blocks every ancestor directory delete indefinitely.
  • status().conflicts > 0 forever, so publish_work_status pins the tray to "Sync needs attention".

The journal is also never pruned on this path, so a restart doesn't clear it. There needs to be a path out of conflict (call complete_conflict, cancel, or re-arm on re-detection) before this is shipped.

@claude

claude Bot commented Dec 1, 2026

Copy link
Copy Markdown

Deep review pass (second reviewer)

Did a focused second pass over the ~14k lines of new non-test code. No correctness or security defects found that I could confirm. One low-severity robustness nit posted inline on sync_work/store.rs.

What I verified in detail, and why each held up:

Durable journal (sync_work/store*)

  • Lease/ownership invariants: claim → checkpoint/renew → finish all gate on (scope, key, generation, token, resource) and a matching sync_work_resources row, so a superseded or expired owner cannot acknowledge, checkpoint, or steal another key's resource. open_for_executor recovery resets running rows and rebuilds the ready index inside one immediate transaction.
  • sync_work_ready maintenance: refresh_ready/refresh_dependents/postpone_resource are called on every state transition, and finish_in_transaction deletes the resource row before recomputing available_at so no stale lease leaks into the deadline.
  • bump_envelope history eviction terminates (each iteration pops regardless of pattern match, and keys/bytes stay in sync with the deque). envelope_changed_keys fails closed to a full reclassification on epoch gaps, bulk invalidation, or any external data_version change; unknown_rows re-reads active membership freshly and retries on a stamp change, so the schema cache can't retain a retired reservation.
  • prune correctly excludes rows that are still desired, resource-leased, or a prerequisite of an active dependent — so the directory-delete dependency chains built in enqueue_deletes can't be orphaned by retention.
  • FK cascade on sync_work_ready/_desired/_dependencies works because PRAGMA foreign_keys=ON is set per connection in open. Fresh DBs reach schema 5 via migrate (the CREATE TABLE IF NOT EXISTS omits folded_resource/conflict_nonce, which the migration adds).
  • Lock ordering is consistent everywhere I checked (connection → envelope_epochs; baseline → store; monitor → refresh_gate in both the work thread and the refresh thread), so no deadlock between the new workers.

Server delete guard

  • directory_descendant_upper_bound is exact: '/'(0x2F)→'0'(0x30) is the true byte successor, and key TEXT PRIMARY KEY is BINARY-collated in both the SQLite and Turso schemas, so key > 'a/b/' AND key < 'a/b0' covers precisely the descendants and nothing else, wildcards included. The check runs under the same lock_store guard as the tombstone. recursive gaining object_id.is_none() only opens a path that previously returned 400, so no prior behavior is weakened. The tombstone_object_with_companions sidecar (<key>.xmp) is itself a descendant, so the 409 fires before it could be touched.

Download pinning / hydration authority

  • ObjectReadSource::validate enforces id+version together and rejects snapshot combinations; the server's get_object_response genuinely honors object_id via describe_history_object, so the pinning isn't a no-op. Staged paths hash (key, id, version) with length prefixes, and ResumableDownloadFileState compares by full equality including the new object_id, so a resumed partial can't be mixed across objects.
  • hydration_authority::validate re-derives identity from the held handle, not the runtime map; the dos[..2] drive-letter slicing is UTF-8-safe because byte 1 is checked to be ASCII ':'.
  • FetchAdmission is retained through failure publication (submit_fetch_or_retain returns the work item rather than dropping it), and fail_fetch_work unregisters cancellation — the removed inline execute_transfer_data_failure is now reported exactly once by execute_fetch_work.

Path/prefix handling

  • checked_relative_path, validated_resolution_path, and payload::path_valid all reject .. (via the trailing-dot rule), absolute and drive-qualified paths. Case folding is applied symmetrically to both the stored folded_resource column and the query parameters, and gate()/canonical_key() normalize /→\\ so the one call site that joins a forward-slash path still maps to the same mutex.
  • Conflict review tokens are bound to (scope, work, proof); request_reviewed_resolution re-validates that the caller's path matches the reviewed intent, so a token for one conflict can't be redirected at another path.

Incremental baseline selection (load_local_baseline_selection) does include every path the planner later reads — exact paths and parents via read_resources, and subtree members via destructive, which covers exactly the jobs whose payload.subtree is populated.

🤖 Generated with Claude Code

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant