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:
@@ -95,6 +95,14 @@ struct WorkoutDocument: Codable, Sendable, Equatable, Identifiable {
|
||||
/// watch and the phone from both writing the same workout to Health.
|
||||
var metrics: WorkoutMetrics?
|
||||
|
||||
/// Per-log deletion tombstones — `logID → when deleted`. Authored only by the phone
|
||||
/// (`WorkoutLogListView.deleteLog`, the sole log-removal site). They disambiguate an
|
||||
/// absent log during the per-log merge: without them, a log the watch still carries
|
||||
/// (having missed a phone-side delete) is indistinguishable from one the watch just
|
||||
/// added. `nil`/absent in files written before the merge shipped; pruned after a grace
|
||||
/// period. See `WorkoutMergePlanner`.
|
||||
var deletedLogIDs: [String: Date]? = nil
|
||||
|
||||
// Bumped 1→2 when `metrics` was added: the captured HR/calorie data is
|
||||
// irreplaceable, so the forward-gate must quarantine these files on older apps
|
||||
// rather than let them strip `metrics` on rewrite.
|
||||
@@ -107,7 +115,11 @@ struct WorkoutDocument: Codable, Sendable, Equatable, Identifiable {
|
||||
// into `Int` fails, and one rewriting the file would strip `setEntries` —
|
||||
// the recorded actuals are irreplaceable (same rationale as the v2 `metrics`
|
||||
// bump), so older apps must quarantine.
|
||||
static let currentSchemaVersion = 4
|
||||
// Bumped 4→5 when per-log `updatedAt` began being written and `deletedLogIDs`
|
||||
// was added for the per-log merge: an older app rewriting the file would strip
|
||||
// the deletion tombstones and resurrect a deleted exercise (irreplaceable
|
||||
// intent, same rationale as v2/v4), so older apps must quarantine.
|
||||
static let currentSchemaVersion = 5
|
||||
|
||||
var relativePath: String { Self.relativePath(id: id, start: start) }
|
||||
|
||||
@@ -127,7 +139,7 @@ extension WorkoutDocument {
|
||||
/// source of the status-from-logs rule — every screen that mutates logs calls it,
|
||||
/// so an ended workout (remaining exercises skipped) stays finished no matter which
|
||||
/// screen the next edit comes from.
|
||||
mutating func recomputeStatusFromLogs() {
|
||||
mutating func recomputeStatusFromLogs(now: Date = Date()) {
|
||||
let statuses: [WorkoutStatus] = logs.map { WorkoutStatus(rawValue: $0.status) ?? .notStarted }
|
||||
let isResolved: (WorkoutStatus) -> Bool = { $0 == .completed || $0 == .skipped }
|
||||
|
||||
@@ -138,10 +150,11 @@ extension WorkoutDocument {
|
||||
// Only stamp the finish time on the *transition* into completed. A workout
|
||||
// that was already completed (with an `end`) keeps that original end, so
|
||||
// editing a finished workout — which re-runs this recompute with all logs
|
||||
// still resolved — doesn't jump its end forward to now.
|
||||
// still resolved — doesn't jump its end forward to now. `now` is injectable
|
||||
// so the pure merge planner can recompute deterministically.
|
||||
let wasCompletedWithEnd = status == WorkoutStatus.completed.rawValue && end != nil
|
||||
status = WorkoutStatus.completed.rawValue
|
||||
if !wasCompletedWithEnd { end = Date() }
|
||||
if !wasCompletedWithEnd { end = now }
|
||||
} else if anyStarted {
|
||||
status = WorkoutStatus.inProgress.rawValue
|
||||
end = nil
|
||||
@@ -220,6 +233,12 @@ extension WorkoutLogDocument {
|
||||
)
|
||||
}
|
||||
|
||||
/// Stamp the per-log modification time for a content-only edit — one that changes a
|
||||
/// log's fields (order, notes, machine settings, an adjusted entry) without flipping its
|
||||
/// status. Status flips stamp `updatedAt` inside `transition(to:)`; this is the hook the
|
||||
/// other edit sites call so the merge can order every kind of per-log change.
|
||||
mutating func touch(_ now: Date = Date()) { updatedAt = now }
|
||||
|
||||
/// Move to a new status, keeping the started/completed timestamps consistent.
|
||||
/// Every screen that flips a log's status (phone and watch) goes through here,
|
||||
/// so the timestamps can't drift per-call-site. Completion is derived from
|
||||
@@ -227,6 +246,10 @@ extension WorkoutLogDocument {
|
||||
/// there's no separate flag to keep in sync.
|
||||
mutating func transition(to newStatus: WorkoutStatus) {
|
||||
status = newStatus.rawValue
|
||||
// Stamp the per-log modification time on every status flip — the merge orders
|
||||
// concurrent edits by it. Content-only edits (order, notes, machine settings,
|
||||
// adjusted entries) stamp `updatedAt` at their own call sites.
|
||||
updatedAt = Date()
|
||||
switch newStatus {
|
||||
case .notStarted:
|
||||
// A full reset — the run never happened, so recorded actuals go too.
|
||||
|
||||
@@ -144,6 +144,11 @@ final class Workout {
|
||||
var metricSourceRaw: String?
|
||||
var metricRecordedAt: Date?
|
||||
|
||||
/// Mirrors the document's per-log deletion tombstones (`logID → when deleted`), so the
|
||||
/// phone re-derives them into any `WorkoutDocument` it rebuilds and the merge stays
|
||||
/// deletion-safe across cache round-trips. Phone-authored; see `WorkoutMergePlanner`.
|
||||
var deletedLogIDs: [String: Date]?
|
||||
|
||||
@Relationship(deleteRule: .cascade, inverse: \WorkoutLog.workout)
|
||||
var logs: [WorkoutLog] = []
|
||||
|
||||
|
||||
@@ -49,7 +49,8 @@ extension WorkoutDocument {
|
||||
splitName: workout.splitName, start: workout.start, end: workout.end,
|
||||
status: workout.statusRaw, createdAt: workout.createdAt, updatedAt: workout.updatedAt,
|
||||
logs: workout.logsArray.map(WorkoutLogDocument.init(from:)),
|
||||
metrics: workout.metrics)
|
||||
metrics: workout.metrics,
|
||||
deletedLogIDs: workout.deletedLogIDs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +146,7 @@ enum CacheMapper {
|
||||
workout.updatedAt = doc.updatedAt
|
||||
workout.jsonRelativePath = relativePath
|
||||
workout.metrics = doc.metrics
|
||||
workout.deletedLogIDs = doc.deletedLogIDs
|
||||
|
||||
let existing = Dictionary(workout.logs.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })
|
||||
var keep = Set<String>()
|
||||
|
||||
Reference in New Issue
Block a user