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
+81
View File
@@ -0,0 +1,81 @@
//
// WorkoutMergePlanner.swift
// Workouts
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//
import Foundation
/// Pure, deterministic per-log merge of a watch-pushed `WorkoutDocument` against the phone's
/// cached copy the durable fix for H1, where `ingestFromWatch` arbitrated by *whole-document*
/// `updatedAt` and so lost one side's edit whenever the two devices changed the same workout at
/// once. Merging per log makes edits to *different* exercises commute: neither side is clobbered
/// just because its overall stamp is newer, so delivery order and offline gaps stop mattering.
///
/// Log existence is reconciled by id against explicit deletion tombstones (`deletedLogIDs`,
/// phone-authored the watch never deletes a log), so an absent log is never ambiguous between
/// "deleted on the phone" and "just added on the watch". Runs phone-side only (in
/// `SyncEngine.ingestFromWatch`); the merged document then flows through the normal
/// `save(workout:)` path and is echoed authoritatively back to the watch.
enum WorkoutMergePlanner {
/// Deletion tombstones older than this are pruned. A device offline longer than the grace
/// may resurrect a since-deleted log the same bounded risk as the whole-workout stub grace.
static let tombstoneGrace: TimeInterval = 30 * 24 * 60 * 60
/// The instant a log was last changed, for ordering concurrent edits: its own `updatedAt`
/// when present, else the best lifecycle timestamp, else `.distantPast` so a legacy log
/// carrying no stamp always loses to a stamped edit and to any tombstone.
static func modTime(_ log: WorkoutLogDocument) -> Date {
log.updatedAt ?? log.completedAt ?? log.startedAt ?? .distantPast
}
/// Merge `incoming` (from the watch) into `cached` (the phone's current copy). Log content
/// is resolved per id (newer `modTime` wins); deletion tombstones from both sides union and
/// drop a log only when the deletion is at-or-after the log's own edit a strictly-newer
/// edit resurrects the log and clears its stale tombstone. Workout-level scalars come from
/// whichever document is newer overall; status and `end` are recomputed from the merged logs.
static func merge(incoming: WorkoutDocument, cached: WorkoutDocument, now: Date = Date()) -> WorkoutDocument {
// 1. Union deletion tombstones newest stamp per id wins.
var tombstones = cached.deletedLogIDs ?? [:]
for (id, when) in incoming.deletedLogIDs ?? [:] {
tombstones[id] = tombstones[id].map { max($0, when) } ?? when
}
// 2. Per-id log union newer modTime wins; equal stamps keep the cached (phone) copy.
var logsByID: [String: WorkoutLogDocument] = [:]
for log in cached.logs { logsByID[log.id] = log }
for log in incoming.logs {
guard let have = logsByID[log.id] else { logsByID[log.id] = log; continue }
if modTime(log) > modTime(have) { logsByID[log.id] = log }
}
// 3. Apply tombstones: a deletion at-or-after the log's own edit drops it; a strictly
// newer edit resurrects the log and clears the now-stale tombstone.
for (id, deletedAt) in tombstones {
guard let log = logsByID[id] else { continue }
if modTime(log) > deletedAt {
tombstones.removeValue(forKey: id)
} else {
logsByID.removeValue(forKey: id)
}
}
// 4. Prune tombstones past the grace period.
tombstones = tombstones.filter { now.timeIntervalSince($0.value) < tombstoneGrace }
// 5. Base scalars (splitID/name, start, metrics, ) on the newer document overall it
// carries a just-attached metrics summary or a rename then override the reconciled
// parts. Ties prefer the cached copy (the phone is the sole writer). Sort is
// id-tie-broken so the result is deterministic even when two logs share an `order`.
var merged = incoming.updatedAt > cached.updatedAt ? incoming : cached
merged.logs = logsByID.values.sorted {
$0.order != $1.order ? $0.order < $1.order : $0.id < $1.id
}
merged.deletedLogIDs = tombstones.isEmpty ? nil : tombstones
merged.recomputeStatusFromLogs(now: now)
merged.updatedAt = max(incoming.updatedAt, cached.updatedAt)
merged.schemaVersion = WorkoutDocument.currentSchemaVersion
return merged
}
}