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:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user