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
@@ -85,7 +85,8 @@ struct WorkoutDocumentMapperTests {
MachineSetting(name: "Back Rest", value: "45°")],
startedAt: Self.startedAt),
],
metrics: fullMetrics()
metrics: fullMetrics(),
deletedLogIDs: ["LOG-DELETED": Self.completedAt]
)
CacheMapper.upsertWorkout(original, relativePath: original.relativePath, into: context)
@@ -120,6 +121,7 @@ struct WorkoutDocumentMapperTests {
#expect(rebuilt.metrics == fullMetrics())
#expect(rebuilt.metrics?.hrZoneSeconds == [10, 20, 30, 40, 50])
#expect(rebuilt.metrics?.healthKitWorkoutUUID == "HK-UUID-123")
#expect(rebuilt.deletedLogIDs == ["LOG-DELETED": Self.completedAt]) // merge tombstones survive
}
/// A workout with no metrics yet (the common in-progress / just-started case) must