Notes/Snapshots.md (5834B)
1# Snapshots in Shared Games
2
3Snapshots are a move-log compaction and replay acceleration mechanism. Instead
4of reconstructing a game by replaying every move from an empty grid, a client can
5start from a stored grid snapshot and replay only the moves not included in that
6snapshot.
7
8The current scalar `upToLamport` model is not safe for shared games. It assumes
9there is one global move sequence:
10
11```text
12Snapshot(upToLamport: 42)
13```
14
15Replay then skips every move whose Lamport is `<= 42`. That is only correct if
16all devices assign Lamports from a single globally ordered stream. In a shared
17or offline-capable game, two devices can independently create moves with the
18same or overlapping Lamport values. A snapshot from device A at Lamport 42 may
19not include device B's move at Lamport 41. If replay treats B's move as covered,
20that move can disappear from the reconstructed grid.
21
22## Proposed Model
23
24Use per-replica move clocks and snapshot coverage vectors.
25
26Each move should identify the replica that produced it and that replica's local
27sequence number:
28
29```text
30Move(replicaID: "device-a", sequence: 12)
31Move(replicaID: "device-b", sequence: 7)
32```
33
34A snapshot should store the grid plus the highest included sequence for each
35replica:
36
37```text
38Snapshot(
39 grid: ...,
40 coverage: [
41 "device-a": 12,
42 "device-b": 7
43 ]
44)
45```
46
47Replay can then skip a move only when the selected snapshot explicitly covers
48that move:
49
50```swift
51let coveredSequence = snapshot.coverage[move.replicaID] ?? 0
52let isCovered = move.sequence <= coveredSequence
53```
54
55This prevents one device's snapshot from accidentally hiding another device's
56move. A move is skipped only if the snapshot proves that the move was folded
57into the snapshot grid.
58
59## Replay and Conflict Ordering
60
61Snapshot coverage answers one question: which moves are included in this
62snapshot?
63
64Conflict ordering answers a separate question: when multiple moves affect the
65same square, which move wins?
66
67Those should not be represented by the same scalar value. Replay should:
68
691. Choose a snapshot.
702. Start from the snapshot grid.
713. Apply only moves not covered by that snapshot.
724. Use a deterministic conflict ordering for same-cell writes.
73
74The conflict ordering can be last-writer-wins with a stable tie-breaker, for
75example `(createdAt, replicaID, sequence)` or another explicit ordering chosen
76for product semantics. The important part is that coverage remains per-replica.
77
78The shipped tie-break (`GridStateMerger.shouldReplace`) is
79`(updatedAt, authorID, deviceID)`: per-cell last-writer-wins on the writer's
80wall-clock `updatedAt`, then lex-min `authorID`, then lex-min `deviceID`.
81
82### Accepted trade-off: cross-device wall-clock skew
83
84The merge, the completion seal (`merge(notAfter: completedAt)`), the pause-push
85diff window, and presence all compare raw device wall clocks across users —
86there is no logical clock and no server-time normalisation on apply. A device
87whose clock runs fast therefore wins every cell conflict regardless of real
88typing order, and its legitimate pre-win letters can be dropped by the
89completion seal when their future-dated `updatedAt` reads as past the latch.
90
91This is accepted as-is rather than mitigated, because the realistic incidence is
92low. iOS defaults to "Set Automatically" (NTP / cellular network time), which
93holds devices within sub-second of true time; quartz drift on a merely-offline
94device is seconds per week. Sub-second skew almost never inverts a merge outcome,
95since that requires two writers to the *same* cell within a real-time gap smaller
96than the skew, and the losing letter in such a tie is usually plausible anyway —
97it is a coin-flip on a shared cell, not silent destruction of unique work. The
98one regime where skew actually bites is a user who has turned off automatic time
99or set the clock manually (minutes to days off); that is self-inflicted
100misconfiguration, and since `CKShare` participants are invited friends, a
101malicious far-future clock is griefing by someone you chose to play with, not a
102cheating-for-advantage vector — there is nothing zero-sum to win in a cooperative
103solve.
104
105If field reports ever surface a "my answer disappeared" trace to a wrong clock,
106the cheap mitigation is to clamp each inbound cell's `updatedAt` to
107`record.modificationDate + ε` on apply, bounding every writer's skew by
108CloudKit's server clock (which all devices share). It is deliberately not built
109speculatively: it adds a permanent "inbound timestamps are rewritten on apply"
110behaviour to reason about, for an edge no user is known to hit.
111
112## Pruning
113
114Pruning old moves is the risky part. With multiple replicas, snapshots can be
115incomparable:
116
117```text
118Snapshot A covers device-a: 20, device-b: 5
119Snapshot B covers device-a: 10, device-b: 30
120```
121
122Neither snapshot fully replaces the other. If moves are deleted merely because
123they are covered by some snapshot, a later replay from a different snapshot may
124miss required moves.
125
126The conservative implementation path is:
127
1281. Add per-replica coverage to snapshots.
1292. Use snapshots only as replay accelerators.
1303. Do not prune moves initially.
1314. Add pruning later only for moves covered by a retained canonical snapshot.
132
133A newer snapshot can safely replace a canonical snapshot when its coverage
134dominates the previous one: for every known replica, the newer snapshot covers at
135least as high a sequence number. Until that rule exists and is tested, retaining
136the move log is safer than compacting it incorrectly.
137
138## Practical Recommendation
139
140For now, disable snapshot pruning for shared games. It is also reasonable to
141disable shared-game snapshot creation entirely until the snapshot format records
142per-replica coverage. The cost is a larger move log and slower replay for very
143long games; the benefit is avoiding data loss or disappearing squares.