Merge watch workout pushes per log instead of whole-document

ingestFromWatch arbitrated by whole-document updatedAt, so concurrent edits
to the same workout on both devices (phone edits exercise A while the watch
completes exercise B) lost one side wholesale — the newer snapshot replaced
the other (H1).

Reconcile per log instead. WorkoutMergePlanner (pure, deterministic) unions
logs by id, resolves each by newest per-log updatedAt, and applies
phone-authored deletion tombstones so an absent log is never ambiguous
between "deleted on the phone" and "just added on the watch". Edits to
different exercises now commute — delivery order and offline gaps stop
mattering. A stale/duplicate push merges back to exactly the cached doc, so
ingest re-pushes authoritative state rather than writing.

The per-log updatedAt scaffolding shipped (unused) in schema v4; it's now
stamped by transition(to:) on status flips and a new touch() at the
content-only edit sites (order, notes, machine settings, adjusted entries,
new logs) on both phone and watch. deletedLogIDs is new: additive on the
wire and cache, phone-authored (deleteLog), pruned after a 30-day grace.
Because an older build rewriting a file would strip the tombstones and
resurrect a deleted exercise, WorkoutDocument schema bumps 4->5 (forward
gate quarantines old builds) and the cache bumps 5->6.

recomputeStatusFromLogs takes an injectable now: so the merge recomputes
status/end deterministically. WorkoutMergePlannerTests pins the decision
table (commute, per-log newer-wins, legacy-nil, watch-add, tombstone
honored/resurrect/union/prune, status recompute, no-op re-push);
WorkoutDocumentMapperTests gains the deletedLogIDs round-trip.
This commit is contained in:
2026-07-09 08:35:16 -04:00
parent 04523c875a
commit 8c8f22850e
16 changed files with 350 additions and 37 deletions
+16 -24
View File
@@ -307,35 +307,27 @@ final class SyncEngine {
onCacheChanged?()
return
}
// `updatedAt` intake gate: the watch mixes `sendMessage` with a queued
// `transferUserInfo` fallback, which are unordered a failed-then-queued
// older edit can arrive after a newer one. Accept only what's strictly
// newer than the cache; the cache mirrors every accepted write
// immediately, so it's always at least as new as any pending slot.
// Strictly older means the watch is behind re-push authoritative state
// so it corrects. Equal is the duplicate/echo case ignore silently.
//
// KNOWN LIMIT (deliberate, revisit if users report vanished sets): this
// gate arbitrates *timestamps*, not *content*. A doc edited on a stale
// watch snapshot carries a fresh stamp and replaces the whole workout
// concurrent edits inside one push round-trip (or a disconnection) lose
// one side wholesale. The watch-side absorb (WorkoutLogListView's
// onChange re-seed) narrows the stale window to one push latency; the
// durable fix is per-log merge: give WorkoutLogDocument its own optional
// `updatedAt` (same additive pattern as startedAt/completedAt), merge
// incoming docs log-by-log (newer log wins per id) instead of replacing,
// and carry log add/remove as explicit intents so an absent log is never
// ambiguous between "deleted" and "not seen yet". That makes edits to
// different logs commute, so delivery order and offline gaps stop
// mattering entirely.
// Per-log merge (H1's durable fix). The watch mixes `sendMessage` with a queued
// `transferUserInfo` fallback, which are unordered, and either device can edit the
// same workout at once. Rather than arbitrate by whole-document `updatedAt` which
// loses one side's edit wholesale reconcile the incoming doc against the cache
// log-by-log (`WorkoutMergePlanner`): newer per-log stamp wins, deletion tombstones
// resolve absent logs, so edits to different exercises commute regardless of delivery
// order. When the merge changes nothing (a stale or duplicate push), re-push
// authoritative state so the watch corrects; otherwise persist the merged document
// (which echoes back to the watch via `onCacheChanged`).
if let cached = CacheMapper.fetchWorkout(id: doc.id, in: context) {
if doc.updatedAt < cached.updatedAt {
let cachedDoc = WorkoutDocument(from: cached)
let merged = WorkoutMergePlanner.merge(incoming: doc, cached: cachedDoc)
guard merged != cachedDoc else {
onCacheChanged?()
return
}
if doc.updatedAt == cached.updatedAt { return }
await save(workout: merged)
} else {
// First time we've seen this workout nothing to merge against.
await save(workout: doc)
}
await save(workout: doc)
}
// MARK: - Public CRUD (mirror-first: cache now, file via the write queue)