| 1 | # Live push: a collaborator's typing in about one round trip |
| 2 | |
| 3 | Status: revision 3, 2026-11-26. |
| 4 | - Revision 1 (4ce1a1b) was reviewed by Claude Fable 5.2 on oficina/docs #172: |
| 5 | APPROVE AFTER FIXES, 18 findings. Revision 2 answers all of them; the table |
| 6 | at the end maps each finding to where it is answered. |
| 7 | - Fable re-reviewed revision 2 (9319c64): APPROVE AFTER FIXES, ready to |
| 8 | become a plan, no further round. Revision 3 (this) applies those eight |
| 9 | fixes (second table at the end). |
| 10 | - Paul's rulings on revision 1's questions are below. The warm handle and |
| 11 | push were prototyped to measure them (§4.2); figures are labelled |
| 12 | **measured** or **projected** throughout. |
| 13 | |
| 14 | **Paul's rulings, 2026-11-26 (binding):** |
| 15 | 1. The 50 ms floor between uploads: **yes**. |
| 16 | 2. Visible web tabs stay live: **yes** (§3.6 sets the bound). |
| 17 | 3. Keep the 250 ms window on cellular and other expensive paths: **yes** |
| 18 | (also on Low Data Mode, §3.8). |
| 19 | 4. A timing check through the real edge with his own session: **yes** |
| 20 | (§10; the snippet is `native/benchmarks/live-push/edge-timing.js`). |
| 21 | |
| 22 | Prototype (measurement only, never to merge): branch `proto/live-push`, the |
| 23 | warm handle and the push stream behind `DOCS_PROTO_WARM` / `DOCS_PROTO_PUSH` |
| 24 | (`internal/docs/proto_live_push.go`) and the probe's push and shared-document |
| 25 | modes. |
| 26 | |
| 27 | Branch: `spec/live-push` (this spec, and the measurement harness under |
| 28 | `native/benchmarks/live-push/`, `internal/docs/live_push_probe_test.go` and |
| 29 | `native/apple/Tests/DocsKitTests/LivePushLatencyTests.swift`; every probe skips |
| 30 | unless its environment variable is set). Nothing here changes what the apps |
| 31 | or the server do. |
| 32 | |
| 33 | Background: `2026-09-01-live-sync-design.md` (SSE announces a seq, the |
| 34 | client fetches `?since=`), the realtime audit |
| 35 | (`oficina/native-levelup/docs-realtime-audit.md`) and its phase 1 (main |
| 36 | 80d4989, discussion #146: echo skip, held announcements, 250 ms native |
| 37 | upload pacing like the web's). |
| 38 | |
| 39 | ## Why |
| 40 | |
| 41 | Paul, 2026-11-26, Docs native 0.1.12: typing locally is instant, but "the lag |
| 42 | is when I have two versions of the doc open and I'm looking at the other one |
| 43 | catching up". He estimates it at up to 500 ms and wants it imperceptible. He |
| 44 | asked whether we need a WebSocket, and whether making it faster would "risk |
| 45 | essentially DDOS'ing ourselves for essentially nothing", given each Oficina |
| 46 | instance is self-contained. |
| 47 | |
| 48 | Answers, in short: |
| 49 | |
| 50 | - **The lag is the protocol, not rendering.** Today, at a 50 ms round trip, |
| 51 | a keystroke shows on the other copy in 274–330 ms at the median and |
| 52 | 439–497 ms at p95, on every web/native combination (§1.1). About 120–140 ms |
| 53 | of that is the sender waiting for its 250 ms upload window, and one whole |
| 54 | round trip is the receiver fetching what the stream already told it exists. |
| 55 | Applying and drawing take the web ~5–10 ms and the native app 10–45 ms. |
| 56 | - **No WebSocket.** The existing SSE stream can carry the bytes. A socket |
| 57 | buys no latency here (both are one trip each way on the edge's HTTP/2 |
| 58 | connection) and costs a dependency, a handshake path and a second |
| 59 | reconnect policy (§3.6). |
| 60 | - **Not a DDoS.** Pushing bytes removes the receiver's fetch per change |
| 61 | (one request per watcher per change). Sending when nothing is in flight |
| 62 | instead of every 250 ms raises uploads from ~3.5/s to ~6/s per active |
| 63 | typist at normal speed (one per keystroke), self-limited to one in flight. |
| 64 | Requests for a typist and one watcher stay about the same and fall for |
| 65 | every extra watcher (§4). With a warm replayed handle per active |
| 66 | document, the prototype measured **less server CPU than today**: 20 |
| 67 | against 42 ms/s for one typist, and 249 against 529 for twenty. A shared |
| 68 | document with five typists and five watchers costs about the same as |
| 69 | today (§4.2). The new costs are local WAL writes (~25 KB per commit, |
| 70 | ~60 KB/s more per typist; replicated bytes should not grow, §4.3) and |
| 71 | warm-handle memory (2.7 MB per active 20-page document). |
| 72 | |
| 73 | ## 1. Measurements |
| 74 | |
| 75 | Machine: Apple M1 Max, macOS 27.0, shared with other sessions (load average |
| 76 | 10–970 during the runs, so CPU timings are ±20%; the network-shaped numbers |
| 77 | are much less sensitive to it). Server: the real authenticated app on loopback |
| 78 | (`TestLivePushProbeServer`), HTTP/1.1, optionally behind a loopback proxy that |
| 79 | holds every chunk RTT/2 in each direction. Typing: "Q"s at a human cadence, |
| 80 | 60 ms + an exponential (mean 150 ms, ~6 keys/s), with a 0.7–1.5 s pause every |
| 81 | 30–60 keys. Documents from `fixtures/generate-large-doc.mjs` (p20 = 20 pages, |
| 82 | 72 KB of Yjs) unless stated. |
| 83 | |
| 84 | **Production path.** From this Mac (Paul's network) to `docs.oficina.works`: |
| 85 | TCP connect to the CARLOS edge 37–62 ms, a warm request on a reused HTTP/2 |
| 86 | connection 45–56 ms to first byte. The edge speaks **HTTP/2** to clients and |
| 87 | HTTP/1.1 to the instance. Its reverse proxy flushes `text/event-stream` |
| 88 | immediately (Go's `httputil.ReverseProxy` does for that type) and its |
| 89 | compression layer excludes it (`carlos/platform internal/edge/compress.go`), |
| 90 | so the edge should not buffer the stream. That could not be confirmed end to |
| 91 | end without Paul's session (every stream needs one); the 20/50/100 ms rows |
| 92 | below stand in for it, and 50 ms is the closest to Paul's path. |
| 93 | |
| 94 | ### 1.1 What a person sees (real clients) |
| 95 | |
| 96 | Keydown on copy A to the character on copy B: the browser's DOM updated |
| 97 | (MutationObserver; paint follows at the next frame, ≤ 16.7 ms), or the native |
| 98 | app's publication rendered and reconciled into the text view's storage. |
| 99 | Native ↔ native is two XCTest processes, i.e. two apps with their own main |
| 100 | threads, as two devices are. Production `DocsModel` and sealed store; real |
| 101 | web editor in headless Chrome; 120 keys each. |
| 102 | |
| 103 | Measured in the quietest windows available (1-minute load average 20–230; |
| 104 | an earlier run at load ~850 was 1.5–2.5× slower on the native side and is not |
| 105 | used). p50 / p95 ms, 120 keys each: |
| 106 | |
| 107 | | Document, RTT | web → web | native → native | native → web | web → native | |
| 108 | |---|---|---|---|---| |
| 109 | | 20 pages, 0 ms | 190 / 319 | 231 / 396 | 218 / 421 | 224 / 334 | |
| 110 | | 20 pages, 50 ms | **279 / 439** | **296 / 484** | **274 / 446** | **330 / 497** | |
| 111 | | 1 page, 50 ms | 292 / 437 | 289 / 460 | 283 / 463 | 274 / 392 | |
| 112 | |
| 113 | So Paul's "heading toward 500 ms" is today's p95 at his distance, on every |
| 114 | combination. The same runs split with the server's log |
| 115 | (`breakdown.py`; medians, 20 pages, 50 ms): |
| 116 | |
| 117 | | | wait to send | server | stream event → GET reaches server | GET | GET answered → shown | |
| 118 | |---|---|---|---|---|---| |
| 119 | | web → web | 138 | 8 | 54 | 1 | 32 | |
| 120 | | native → native | 120 | 8 | 55 | 1 | 50 | |
| 121 | | native → web | 123 | 10 | 57 | 1 | 29 | |
| 122 | | web → native | 139 | 9 | 56 | 1 | 71 | |
| 123 | |
| 124 | (Plus the 25 ms one-way trip up, which "wait to send" excludes.) The last |
| 125 | column is the 25 ms trip down plus the receiver's work: the web applies and |
| 126 | draws in ~5–10 ms; the native app needs 25–45 ms at 20 pages and ~10 ms at |
| 127 | one page, almost all of it `replica.presentation` with a fresh source, which |
| 128 | re-decodes the whole document (audit finding 2; the per-block drawing after |
| 129 | it is 1–3 ms, S1a). Pushing the bytes removes the middle two columns; sending |
| 130 | at once removes most of the first. |
| 131 | |
| 132 | ### 1.2 Where the time goes (protocol) |
| 133 | |
| 134 | Simulated clients that follow the web's and the native app's exact rules |
| 135 | (`live_push_probe_test.go`): `web250` is `save-queue.mjs` (a key starts a |
| 136 | 250 ms timer, not reset); `native250` is `DocsOfflineAccount.pace` (the first |
| 137 | send after a pause goes at once, POST starts ≥ 250 ms apart); `idleN` sends |
| 138 | when nothing is in flight and N ms have passed since the last send, and |
| 139 | coalesces otherwise. "Fetched" is today: the watcher's `?since=` fetch |
| 140 | completes. "Announced" is when the watcher's stream delivered the seq, which is |
| 141 | when pushed bytes would arrive: a stand-in in revision 1, confirmed by the |
| 142 | prototype's direct measurement (§4.2: 56 ms against the stand-in's 64 at |
| 143 | 50 ms). Add receiver apply + draw (§1.1) to both. |
| 144 | 200 keys per row, p20; median / p95 in ms. |
| 145 | |
| 146 | | RTT | Policy | Sender wait | POST answered | Send → announced | Announced → fetched | **Key → fetched (today's path)** | **Key → announced (push)** | Uploads/s | |
| 147 | |---|---|---|---|---|---|---|---|---| |
| 148 | | 0 | web250 | 171 / 255 | 7 / 27 | 8 / 25 | 1 / 4 | **178 / 270** | 178 / 268 | 2.7 | |
| 149 | | 0 | native250 | 118 / 232 | 6 / 10 | 7 / 10 | 0 / 2 | **127 / 243** | 127 / 242 | 3.6 | |
| 150 | | 0 | idle0 | 0 / 0 | 8 / 21 | 8 / 22 | 1 / 4 | 8 / 24 | **8 / 22** | 6.1 | |
| 151 | | 0 | idle50 | 0 / 0 | 9 / 20 | 9 / 22 | 1 / 5 | 10 / 24 | **9 / 22** | 6.1 | |
| 152 | | 20 | web250 | 157 / 252 | 29 / 33 | 29 / 33 | 23 / 27 | **211 / 308** | 188 / 283 | 3.0 | |
| 153 | | 20 | native250 | 117 / 231 | 30 / 42 | 30 / 42 | 24 / 30 | **171 / 284** | 149 / 260 | 3.6 | |
| 154 | | 20 | idle0 | 0 / 0 | 33 / 50 | 33 / 49 | 24 / 32 | 57 / 77 | **33 / 49** | 6.1 | |
| 155 | | 20 | idle50 | 0 / 0 | 32 / 45 | 32 / 46 | 25 / 33 | 57 / 76 | **32 / 46** | 6.1 | |
| 156 | | 50 | web250 | 108 / 253 | 63 / 81 | 63 / 81 | 56 / 75 | **237 / 390** | 173 / 327 | 3.8 | |
| 157 | | 50 | native250 | 117 / 232 | 62 / 79 | 62 / 79 | 54 / 66 | **235 / 352** | 177 / 297 | 3.6 | |
| 158 | | 50 | idle0 | 0 / 3 | 63 / 88 | 63 / 88 | 54 / 67 | 117 / 152 | **63 / 99** | 6.0 | |
| 159 | | 50 | idle50 | 0 / 0 | 64 / 80 | 64 / 80 | 55 / 66 | 119 / 140 | **64 / 82** | 6.1 | |
| 160 | | 50 | idle100 | 0 / 69 | 64 / 79 | 64 / 80 | 55 / 66 | 127 / 199 | 70 / 137 | 6.0 | |
| 161 | | 100 | web250 | 91 / 252 | 111 / 129 | 111 / 129 | 104 / 115 | **313 / 476** | 207 / 369 | 3.9 | |
| 162 | | 100 | native250 | 125 / 237 | 112 / 130 | 112 / 128 | 105 / 113 | **344 / 458** | 239 / 351 | 3.6 | |
| 163 | | 100 | idle0 | 7 / 98 | 112 / 127 | 112 / 127 | 105 / 115 | 228 / 322 | **122 / 217** | 5.7 | |
| 164 | | 100 | idle50 | 4 / 84 | 111 / 126 | 111 / 126 | 105 / 114 | 229 / 304 | **122 / 200** | 5.7 | |
| 165 | |
| 166 | How much each change buys (medians, today's native policy as the base): |
| 167 | |
| 168 | | RTT | Today (native250, fetch) | Push only (keep pacing) | Pacing cut only (idle50, fetch) | Both (idle50, push) | |
| 169 | |---|---|---|---|---| |
| 170 | | 20 ms | 171 | 149 (−22) | 57 (−114) | **32 (−139)** | |
| 171 | | 50 ms | 235 | 177 (−58) | 119 (−116) | **64 (−171)** | |
| 172 | | 100 ms | 344 | 239 (−105) | 229 (−115) | **122 (−222)** | |
| 173 | |
| 174 | The pacing window is the larger cost at every round trip up to ~100 ms; the |
| 175 | fetch is one round trip, so it grows with distance. Neither alone gets under |
| 176 | ~100 ms at Paul's distance; both together give about one round trip plus |
| 177 | ~12 ms at the median. The receiver's own work adds 1–25 ms (§1.1). |
| 178 | |
| 179 | ### 1.3 Causes, ranked |
| 180 | |
| 181 | 1. **Upload pacing (120–170 ms median, up to 250).** Both platforms hold a |
| 182 | key for up to 250 ms. The web's timer starts at the first key and is not |
| 183 | reset, so an isolated key always waits the full 250 ms. The native app |
| 184 | sends the first key after a pause at once but holds every key typed |
| 185 | within 250 ms of the last POST's start. |
| 186 | 2. **The receiver fetches what it was told about (one full round trip).** |
| 187 | The stream carries only a seq; bytes come from `GET ?since=`. At 50 ms |
| 188 | that is 54–56 ms; at 100 ms, 105. |
| 189 | 3. **Every POST replays the whole document on the server** (`Store.ApplyUpdate` |
| 190 | → `replay`: a fresh WASM instance, the newest snapshot and up to 255 tail |
| 191 | rows applied, then the update). 1.6 ms at 1 page, 10.8 ms median and 77 ms |
| 192 | p95 at 20 pages (`TestLivePushProbeApplyCost`), 13–14 ms of server CPU and |
| 193 | ~8 MB of allocation per POST in the full app at 20 pages. It is in every |
| 194 | change's path, and with the garbage it makes it is about a third of the |
| 195 | server's CPU (§4). |
| 196 | 4. **The web sender downloads most of its own changes back.** The server |
| 197 | broadcasts before it answers the POST, so the sender's stream event usually |
| 198 | arrives before the POST's `Docs-Seq`, and `noteOwnSeq` comes too late: |
| 199 | at 20–100 ms round trip, 77–93 of ~100–130 POSTs per 200 keys were fetched |
| 200 | back (`web250` rows). Phase 1 gave the native app a hold for this |
| 201 | (`heldRemoteSequence`), the web has none. It costs requests, not latency. |
| 202 | 5. **Not causes:** the edge (flushes SSE, h2, no compression of the stream), |
| 203 | Nagle (Go and URLSession set `TCP_NODELAY`), the heartbeat (15 s), native |
| 204 | drawing after S1a (1–3 ms per peer change, pageless; paged waits for S1b). |
| 205 | 6. **Two windows of one document in one app do not exist on the Mac.** |
| 206 | `DocsWindows.reserve` brings the existing window forward for the same |
| 207 | account and document, so Paul's two copies are two devices, two apps or |
| 208 | app + browser, which all go through the server. No in-process fan-out is |
| 209 | needed (§3.8). |
| 210 | 7. **A web copy nobody touches stops updating after two minutes.** |
| 211 | `live-updates.mjs` closes a visible tab's stream after `IDLE_MS` (2 min) |
| 212 | with no local activity and no stream event, and reopens only on |
| 213 | activity. So Paul stops typing for two minutes, types again, and the |
| 214 | copy he is watching stays stale until he moves the mouse over it. The |
| 215 | same happens after every deploy or restart (`hub.drain` closes every |
| 216 | stream) and at the server's 5 min TTL. Native reconnects at once. |
| 217 | |
| 218 | ## 2. Targets |
| 219 | |
| 220 | Measured against these by the release step (§9.3), never by shared CI: |
| 221 | |
| 222 | - **p50 ≤ RTT + 30 ms, p95 ≤ RTT + 80 ms**, key on A to character drawn on |
| 223 | B, at a normal typing cadence, for a web receiver at any size and a native |
| 224 | receiver up to ~5 pages. At Paul's ~50 ms that is ≤ 80 ms median. |
| 225 | - A native receiver at 20 pages: p50 ≤ RTT + 60 ms, until its fresh-source |
| 226 | presentation (25–45 ms, audit finding 2) is made incremental, which is |
| 227 | engine work outside this spec. |
| 228 | - **Measured** in the prototype at 50 ms (protocol only, bytes in the |
| 229 | watcher's hand): 56 / 67 ms, and 58 / 66 ms with five typists and five |
| 230 | watchers in one document (§4.2). **Projected** with the receivers' own |
| 231 | work: ~65 ms median for a web receiver and ~80–100 ms for a native one |
| 232 | at 20 pages, from 274–330 ms today (§1.1). |
| 233 | - No more requests per change than today, and server CPU per active typist |
| 234 | within today's ±20% (§4.2 says how close the prototype comes). |
| 235 | |
| 236 | ## 3. Design |
| 237 | |
| 238 | ### 3.1 The stream carries the bytes |
| 239 | |
| 240 | A client that understands push asks for it: |
| 241 | `GET /d/{sqid}/stream?push=1&since=N`. `hello` and `bye` are sent only on a |
| 242 | `push=1` stream; a stream without `push=1` is exactly today's. |
| 243 | |
| 244 | **Frames:** |
| 245 | |
| 246 | ``` |
| 247 | event: hello |
| 248 | data: <stream id> <the log's current seq> <log epoch> |
| 249 | |
| 250 | id: 43.<tag> |
| 251 | event: push |
| 252 | data: 43 <base64 of row 43's bytes> |
| 253 | |
| 254 | id: 44.<tag> |
| 255 | event: own |
| 256 | data: 44 <the client's counter from Docs-Stream> |
| 257 | |
| 258 | event: update |
| 259 | data: 45 |
| 260 | |
| 261 | event: resync |
| 262 | data: <the log's current seq> |
| 263 | |
| 264 | event: bye |
| 265 | data: <reason: ttl | lease | drain> |
| 266 | ``` |
| 267 | |
| 268 | The `<tag>` is the row's digest (16 hex digits of SHA-256 over its seq and |
| 269 | bytes; branch review #175, finding 3, below). |
| 270 | |
| 271 | - `push` carries a row this client did not post. `own` marks one it did |
| 272 | (§3.4); no bytes. `update` is today's seq-only event. The server sends it |
| 273 | instead of `push` for a row over **32 KiB**, a row it cannot open, or a |
| 274 | client more than **256 rows / 512 KiB** behind. The client then fetches |
| 275 | `?since=` as today. `update` frames never carry `id:`, because their bytes |
| 276 | were not delivered. |
| 277 | - **As built:** |
| 278 | - The far-behind case is decided from the rows' count and stored lengths |
| 279 | before any row is read, and a row too large to push is never loaded or |
| 280 | cached. |
| 281 | - The first row a flush cannot push ends it with one `update <current>`, |
| 282 | since the client's fetch brings that row and everything after it. |
| 283 | - **Reading.** The stream reads rows with the same query and |
| 284 | `openContentUpdate` as `updatesGet` (`seq > sent ORDER BY seq`, log rows |
| 285 | only, never a snapshot). Seq is `MAX+1` inside the single-writer |
| 286 | transaction, so the committed log is gapless when read. No ring buffer is |
| 287 | needed and no reordering. The hub stays a one-slot "something happened" |
| 288 | notification. Each stream keeps `sent`: it reads everything after `sent` |
| 289 | and writes all the frames with one write and one flush. After an `update` |
| 290 | frame, `sent` moves to that seq. |
| 291 | - **Where it starts.** `Last-Event-ID` (sent by `EventSource` on its own |
| 292 | reconnects) wins over `since`. Rows after the start arrive as frames, so |
| 293 | the connect-time GET goes away. With neither, the stream starts at the |
| 294 | current seq and still sends today's connect-time `update <current>` right |
| 295 | after `hello` (`stream.go` calls it load-bearing: it heals a cursor that |
| 296 | failed to advance). `hello` always comes first. |
| 297 | - **A rewound log** (the database restored from a backup, a team |
| 298 | re-provisioned, a later version restore). The client resyncs from 0 (the |
| 299 | web's resync controller; native's catch-up from the start) when any of |
| 300 | these holds: |
| 301 | - `hello`'s seq is below its cursor; |
| 302 | - `hello`'s **log epoch** differs from the one it holds; |
| 303 | - the stream sends **`resync`** (the server's own check, below). |
| 304 | - **The server checks the cursor itself** (branch review #175, findings 3 |
| 305 | and 5), because the epoch misses the likeliest restore. A Litestream |
| 306 | point-in-time restore is from after the last start, and a volume |
| 307 | snapshot carries the file beside the database. So: |
| 308 | - push and own frames carry `id: <seq>.<tag>`; |
| 309 | - fetch responses carry `Docs-Seq-Tag` for the row their `Docs-Seq` names; |
| 310 | - a resume names its cursor's tag (`Last-Event-ID: <seq>.<tag>`, which |
| 311 | `EventSource` sends by itself, or `since=<seq>` with a `Docs-Seq-Tag` |
| 312 | request header). Never in the query string: access logs keep URLs, and |
| 313 | the tag is an unkeyed digest of the row's plaintext, so on a sealed |
| 314 | instance a log reader could confirm a guess at a small row (branch |
| 315 | review #175, approval note 6); |
| 316 | - the stream answers `resync` and ends when the row it holds at that seq |
| 317 | has another tag or is missing, and when the cursor is ahead of the log; |
| 318 | - a cursor without a tag is checked by seq and epoch only. |
| 319 | |
| 320 | The seq alone misses a restore that new commits have already passed: a |
| 321 | log restored to 90, twenty new commits, and a client at 100 sees 110 and |
| 322 | skips the new 91–100. Litestream's loss window makes that possible. |
| 323 | The log epoch is a random value stored in the instance database. It is |
| 324 | rotated by any operation that rewinds a log, and at startup when the |
| 325 | database is not where the last start left it. |
| 326 | - **As built in slice 1b** (`logepoch.go`): a boot counter, kept in the |
| 327 | database and in a file beside it (`<db>.log-epoch`), compared and |
| 328 | bumped at every start. The spec first said "a clean-shutdown marker |
| 329 | written at the end of a clean drain". That would rotate the epoch at |
| 330 | every deploy that overlaps generations (`CARLOS_SWAP=overlap`), where |
| 331 | the new process starts before the old one has drained. |
| 332 | - A move to another box (no file beside the database) and a restore from |
| 333 | a copy older than the last start rotate it, so every open client |
| 334 | resyncs once. |
| 335 | - An ordinary deploy, overlapped or not, and a process crash (which loses |
| 336 | no committed row) do not. |
| 337 | - Not caught: a restore from a copy taken after the last start, onto the |
| 338 | same disk. The seq check still catches a log that is behind, and a |
| 339 | restore runbook can delete the file. |
| 340 | - Clients learn the epoch from `hello`. Fetch responses carry it too |
| 341 | (`Docs-Log-Epoch`), so a non-push client can check it on its next |
| 342 | fetch. |
| 343 | - **Base64 on the stream** costs ~33% on 15–30 bytes per keystroke: noise. |
| 344 | An oversized update still goes by fetch. |
| 345 | |
| 346 | ### 3.2 Client rules for frames (web and native alike) |
| 347 | |
| 348 | - One fetch in flight. Frames that arrive while it is in flight are queued. |
| 349 | When it lands, the queue is checked against the new cursor: drop |
| 350 | everything ≤ cursor, apply cursor + 1 in order, and if the next frame is |
| 351 | still ahead, make one more fetch. |
| 352 | - `push` with seq = cursor + 1: apply it, cursor = seq. Seq ≤ cursor: drop. |
| 353 | Seq > cursor + 1: a gap, so fetch. |
| 354 | - `own` with seq = cursor + 1 and a counter this client sent on **this |
| 355 | stream** (§3.4): cursor = seq, nothing to apply. Anything else: treat as |
| 356 | `update` (fetch). |
| 357 | - `update`: fetch, as today. |
| 358 | - On a push stream the cursor moves only by frames and fetches. The POST's |
| 359 | `Docs-Seq` is not used there (`noteOwnSeq` and the native ≤ 1 s hold stay |
| 360 | for non-push streams, i.e. old servers). |
| 361 | |
| 362 | ### 3.3 Sending: when nothing is in flight |
| 363 | |
| 364 | > Send when nothing is on the wire and at least **50 ms** have passed since |
| 365 | > the last send started. While a send is on the wire, coalesce everything |
| 366 | > typed into the next one, which goes when the answer arrives (and the 50 ms |
| 367 | > have passed). |
| 368 | |
| 369 | - **Only after `hello`, per connection.** A client uses this rule only |
| 370 | while its current stream for the document has said `hello`. Otherwise it |
| 371 | keeps today's 250 ms window. "Has said `hello`" belongs to one |
| 372 | connection and resets on every reopen. So a server restarted with |
| 373 | `DOCS_LIVE_PUSH` off sends clients back to 250 ms and to `Docs-Seq` on |
| 374 | their next stream. A POST in flight across a reopen carries the old |
| 375 | stream id; it arrives on the new stream as `push` and is applied as |
| 376 | nothing. |
| 377 | Sending at once to a server without push is §4.1's "send at once, fetch" |
| 378 | row: ~1.8× the CPU and more fetches. One native build talks to every |
| 379 | team's instance, including lagged ones, so this is not only a rollback |
| 380 | case. |
| 381 | - **On an expensive or constrained path** (`NWPath.isExpensive` or |
| 382 | `isConstrained`; on the web, `navigator.connection.saveData` or a |
| 383 | `cellular` type where reported), keep 250 ms (Paul, ruling 3). |
| 384 | - Rate: **uploads/s ≤ min(keys/s, 1 / (RTT + server time), 20)**. Measured |
| 385 | at ~6 keys/s: |
| 386 | |
| 387 | | RTT | Today, web | Today, native | Send when idle (50 ms floor) | A 12 keys/s burst | |
| 388 | |---|---|---|---|---| |
| 389 | | 20 ms | 3.0 | 3.6 | 6.1 | ≤ 12 | |
| 390 | | 50 ms | 3.8 | 3.6 | 6.1 | ≤ 12 (1/RTT ≈ 15) | |
| 391 | | 100 ms | 3.9 | 3.6 | 5.7 | ≤ ~8.5 (1/RTT) | |
| 392 | |
| 393 | A 50 or 100 ms floor gives the same rate as none at typing speed. It |
| 394 | only caps key-repeat and bursts on a LAN (≤ 20/s). |
| 395 | - Durability is unchanged: every keystroke reaches the outbox (native) or |
| 396 | the queue (web) first. Save, close, blur and background still send at |
| 397 | once. |
| 398 | - Native: `DocsOfflineAccount.sendInterval` becomes 50 ms when the open |
| 399 | model's stream has said `hello`, and `pace` no longer holds the drainer |
| 400 | after a POST that leaves the lane non-empty. Web: `save-queue.mjs` gains |
| 401 | the leading edge (`schedule(0)` when nothing is in flight and the floor |
| 402 | has passed), switched on by `live-updates.mjs` on `hello`. |
| 403 | |
| 404 | ### 3.4 Own updates: `own`, checkable |
| 405 | |
| 406 | A client must be able to check an `own` frame. Adopting one wrongly skips |
| 407 | an update for good, silently: seq N is exactly next, so no gap ever shows, |
| 408 | and later updates that depend on it park invisibly. That would come from |
| 409 | ordinary bugs (a stale id after a reconnect, the native drainer's "holds |
| 410 | every entry" check being wrong once, two tabs) more than from forgery. |
| 411 | |
| 412 | - `hello` gives the stream a random id (16 bytes, base64url). The server |
| 413 | binds it to the session that opened the stream. A `Docs-Stream` header |
| 414 | from a different session is ignored, as if absent. |
| 415 | - A POST may carry `Docs-Stream: <stream id>.<counter>`. The counter is the |
| 416 | client's, one per POST on that stream. |
| 417 | - `Store.ApplyUpdate` records `(doc, seq) → (stream id, counter, |
| 418 | SHA-256 of the bytes)` **inside the transaction, before commit**, in the |
| 419 | hub's small per-document registry (the last 64). A stream that reads row |
| 420 | N therefore always finds the entry (rows become visible only at commit). |
| 421 | It writes `own` only when the stream id matches **and** the row's bytes |
| 422 | hash to the recorded hash. A seq reused after a rolled-back transaction |
| 423 | can never match. |
| 424 | - The client adopts `own N c` only for a counter `c` it sent on this stream |
| 425 | and only at cursor + 1 (§3.2). Anything else is a fetch. |
| 426 | - Native: the drainer is per account, the stream per open document. The |
| 427 | model registers its stream id with `DocsOfflineAccount` for its lane. The |
| 428 | drainer sends the header only when the open model holds every entry in |
| 429 | the batch (the check `DocsModel.sent` makes today) and keeps the counter. |
| 430 | Otherwise there is no header, and the model gets the bytes and applies |
| 431 | them as nothing. |
| 432 | |
| 433 | ### 3.5 The server keeps a warm handle per active document |
| 434 | |
| 435 | Today `Store.ApplyUpdate` replays the whole document for every POST. The |
| 436 | rules for keeping the replayed `core.Handle` between POSTs: |
| 437 | |
| 438 | 1. **Taken under a per-document lock.** POSTs to one document already |
| 439 | serialise on the single SQLite writer. |
| 440 | 2. **Applied before the transaction**, as today's replayed handle is. |
| 441 | - **Any error from `Apply` drops the handle.** A rejection |
| 442 | (`RejectedError`) answers 400 as today, but it is not clean. yrs |
| 443 | integrates an update's structs one at a time, so an update whose later |
| 444 | struct is refused (`InvalidParent`, `ERR_APPLY`) leaves the earlier ones |
| 445 | in the store, and the core's transaction commits them. A kept handle |
| 446 | would carry that content into the next snapshot with no row holding it |
| 447 | (branch review #174, finding 1). |
| 448 | - `ErrUpdateLogFull`, a trap or `RecoveredError`: also replay cold |
| 449 | **inside the same POST**, then carry on as today. The cache never fails |
| 450 | a POST that a replay would take. |
| 451 | - A request cancelled mid-Apply drops the handle quietly and is not |
| 452 | retried. |
| 453 | - An "applied, not committed" flag set before `Apply` closes the handle |
| 454 | on every way out short of a commit, a panic included. |
| 455 | - Making the core apply into a scratch transaction it can roll back would |
| 456 | make a refused update change nothing. That is a core change with its |
| 457 | own ABI test, not part of this spec. |
| 458 | 3. **Committed, or dropped.** Any failure after a successful `Apply` drops |
| 459 | the handle: the in-transaction permission check refusing (a writer |
| 460 | revoked mid-request), a cancelled context, a database error, the team |
| 461 | guard. The handle's seq advances only after commit. If `MAX(seq)` inside |
| 462 | the transaction is not the handle's seq, the row is still inserted |
| 463 | (today's behaviour with a stale replay) and the handle is dropped. |
| 464 | 4. **Re-seeded at the snapshot cadence.** When the handle is 256 rows past |
| 465 | its snapshot, the POST does this, in order: |
| 466 | 1. write the snapshot from the warm state at the handle's seq (D3's |
| 467 | placement, unchanged); |
| 468 | 2. `Apply` the update to the same handle; |
| 469 | 3. commit; |
| 470 | 4. drop the handle. |
| 471 | |
| 472 | The next POST replays from that snapshot. A failed snapshot write |
| 473 | (outside team mode: logged, not fatal, as today) keeps the handle, and |
| 474 | rule 2 is the backstop at 4,096. A warm handle therefore never retains more |
| 475 | than ~257 updates, far from `core.MaxRetainedUpdates` (4,096). Without |
| 476 | this, one typist reaches the cap in ~11 minutes and the POST answers 400, |
| 477 | which `save-queue.mjs` treats as final. |
| 478 | 5. **Memory, measured** (`TestLivePushProbeWarmMemory`, RSS per warm |
| 479 | handle): 1.8 MB at 1 page, 2.7 MB at 20 pages, 16.5 MB at 200 edited |
| 480 | pages. Cap: **128 MB of warm handles per process** (from the handle's |
| 481 | linear-memory size) and 64 handles, LRU. A single handle larger than |
| 482 | the byte cap is not kept; that document takes the cold path every time. |
| 483 | 6. **Dropped** on delete, restore, any change to the document's grants, |
| 484 | team or sealing state (no sealed plaintext stays resident after access |
| 485 | changes), after 60 s without a POST, and at shutdown (`hub.drain` closes |
| 486 | them). As built in slice 1a: |
| 487 | - grants, revoke, visibility, delete, drain and close drop it; |
| 488 | - sealing is activated offline with the app stopped; |
| 489 | - **team roster changes** arrive from outside and drop nothing, and nor |
| 490 | does a grant changed by a second process during a deploy overlap. That |
| 491 | is retention for at most 60 s, not access: permission is checked on |
| 492 | every POST and inside the transaction. Dropping on a roster refresh is |
| 493 | a candidate for slice 1b, which touches the team guard anyway. |
| 494 | - **There is no version restore yet.** When there is, it must drop the |
| 495 | handle: a restore that rewrites rows could leave `MAX(seq)` where it |
| 496 | was, which rule 3 cannot see. |
| 497 | 7. **Swept by POSTs and by the stream's heartbeat.** `stream.go` has no |
| 498 | timer outside a live connection. Each POST sweeps the cache, and so does |
| 499 | every open stream's 15 s heartbeat, which is a timer inside a live |
| 500 | connection. A document whose last writer stopped while a tab still |
| 501 | watches it is therefore dropped within ~75 s. With no stream and no |
| 502 | POST, the instance hibernates within 15 minutes and the memory goes with |
| 503 | it. |
| 504 | 8. **Two processes on one database** (a deploy overlap) stay correct, |
| 505 | because validity is checked inside the transaction. |
| 506 | |
| 507 | ### 3.6 Keeping a visible web copy live (Paul, ruling 2) |
| 508 | |
| 509 | This rule is how long a visible, untouched tab may hold its instance awake. |
| 510 | Paul ruled that visible tabs stay live. The bound and the reopen rule: |
| 511 | |
| 512 | - **A visible tab keeps its stream** while it is visible, up to **8 hours** |
| 513 | since the last local activity (**Paul's call, open question 1**: 2 hours |
| 514 | fixes his complaint equally and halves the awake time; nothing in the |
| 515 | design depends on the value). Then it closes, and any activity reopens |
| 516 | it. The clock resets on local activity and on `push`/`own` frames (real |
| 517 | frames mean POSTs are keeping the instance awake anyway), never on |
| 518 | heartbeats. |
| 519 | - **Hibernation** (checked against `carlos/platform internal/activator`): |
| 520 | an instance hibernates when nothing is in flight and 15 minutes have |
| 521 | passed since the last request. An open stream is in flight, so an |
| 522 | untouched visible tab holds its instance for up to 8 h + 15 min, against |
| 523 | 2 min + 15 min today. A tab left open on Friday evening releases it early |
| 524 | on Saturday. A closed lid or a dead connection holds nothing: the client |
| 525 | never reopens, and the server's 5-minute TTL stays the hard bound. The TTL |
| 526 | stays 5 minutes for exactly that reason. |
| 527 | - **Hidden tabs** keep today's 30 s close. A tab that is hidden when its |
| 528 | stream ends stays closed; showing it is activity, which reopens it. |
| 529 | - **Reopen after any end of the stream.** The server has four ends (TTL, |
| 530 | drain, the team lease deadline, and a failed write or authorisation |
| 531 | check), and the network has more. A visible tab inside its 8 h reopens |
| 532 | with `since=<cursor>` after **any** end, `bye` or not. `bye` only chooses |
| 533 | the first delay: |
| 534 | - `ttl` or `lease`: at once; |
| 535 | - `drain`: 1–5 s with jitter, so a whole team does not reconnect in the |
| 536 | same instant to a process that is still starting; |
| 537 | - no `bye` (a failed check, the network, an old server): 1 s. |
| 538 | - **When the reopen fails.** The tab first fetches `?since=<cursor>`, which |
| 539 | shows the status `EventSource` hides: |
| 540 | - 401, 403 or 404: stop and show the access state, as today; |
| 541 | - anything else (a 502 while the instance starts, a network error): |
| 542 | capped exponential backoff with jitter, 1 s doubling to 60 s. |
| 543 | |
| 544 | So a tab never retries a dead instance at a fast rate, and never for |
| 545 | longer than its 8 hours. |
| 546 | - **The same rule on a non-push stream** (an old server, or `DOCS_LIVE_PUSH` |
| 547 | off). There is no `bye`, so the TTL close arrives as an error and the |
| 548 | tab reopens after 1 s. That fixes cause 7 everywhere, not only where push |
| 549 | is on. Only the frames and the 50 ms floor depend on `hello`. |
| 550 | - **The server sends `bye ttl`, `bye lease` and `bye drain`** before those |
| 551 | three closes. Team-mode streams end at the lease deadline; every team |
| 552 | instance runs in team mode, and all of them will after Alta. |
| 553 | |
| 554 | ### 3.7 Receivers |
| 555 | |
| 556 | - **Web** (`live-updates.mjs`): `openStream` adds `?push=1&since=<cursor>`. |
| 557 | `push` frames go to `onUpdates` in order (decode, `prepareRemote`, |
| 558 | `free`, `applyServerLog`), with the queue rules of §3.2; `hello` switches |
| 559 | the save queue's leading edge on (§3.3) and checks the cursor (§3.1). |
| 560 | A diverged document ignores frames as it ignores fetches today. A resync |
| 561 | replaces the subscriber (cursor and stream together). |
| 562 | - **Native** (`DocsModel.listen`): the same events. A `push` frame is |
| 563 | applied with `replica.apply` and published as `refresh` does after its |
| 564 | GET today (publish first, persist debounced), without the GET. A burst of |
| 565 | queued frames is applied as one `apply` of their concatenation, as a |
| 566 | `?since=` response is today. |
| 567 | |
| 568 | ### 3.8 Mobile, background, cellular |
| 569 | |
| 570 | - The iPhone closes the stream in the background (phase 1) and reopens with |
| 571 | `since=`. What it missed arrives as frames, or as one `update` if it is |
| 572 | far behind, with no extra GET. |
| 573 | - A remote change costs the radio one downstream frame instead of a frame, |
| 574 | a request and a response. |
| 575 | - Expensive and constrained paths keep the 250 ms window (§3.3). |
| 576 | |
| 577 | ### 3.9 Why not a WebSocket |
| 578 | |
| 579 | - **Latency:** none to gain. A change takes one trip up (POST) and one down |
| 580 | (stream frame) either way. With HTTP/2 to the edge, the POST rides the |
| 581 | same connection as the stream, with no new handshake. |
| 582 | - **Cost:** |
| 583 | - rastrillo has no WebSocket helper, so a new dependency; |
| 584 | - a hand-written Origin check on the upgrade; |
| 585 | - auth and per-document authorisation on a long-lived socket; |
| 586 | - a second reconnect, heartbeat and idle policy beside the stream's; |
| 587 | - `NativeHTTP` has no socket either. |
| 588 | - **When it pays:** presence (cursors, selections): many small, ephemeral, |
| 589 | two-way messages. |
| 590 | |
| 591 | ### 3.10 Windows in one app |
| 592 | |
| 593 | None today: on the Mac, one account has one window per document |
| 594 | (`DocsWindows.reserve`). Out of scope. |
| 595 | |
| 596 | ## 4. Cost: are we DDoSing ourselves? |
| 597 | |
| 598 | ### 4.1 Today's paths (measured, revision 1) |
| 599 | |
| 600 | Simulated typists against the real server at 20 pages (`run-probe.py`, |
| 601 | loopback, ~6 keys/s each, each typist in its own document with one |
| 602 | watcher). One run of 200 keys per row, on a machine at load 10–970, so |
| 603 | treat these as ±20%: |
| 604 | |
| 605 | | Typists | Policy | Uploads/s | Fetches/s | Server CPU | Allocation | |
| 606 | |---|---|---|---|---|---| |
| 607 | | 1 | today, native (250 ms) | 3.4 | 3.4 | 48 ms/s | 24 MB/s | |
| 608 | | 1 | today, web (250 ms) | 2.9 | 5.1 | 42 ms/s | 20 MB/s | |
| 609 | | 1 | send at once, fetch | 5.5 | 8.9 | 87 ms/s | 46 MB/s | |
| 610 | | 5 | today, native | 15.7 | 15.7 | 211 ms/s | 111 MB/s | |
| 611 | | 5 | send at once, fetch | 26.3 | 33.6 | 382 ms/s | 227 MB/s | |
| 612 | | 20 | today, native | 58.2 | 57.6 | 714 ms/s | 407 MB/s | |
| 613 | | 20 | send at once, fetch | 99.0 | 107.5 | 1,349 ms/s | 842 MB/s | |
| 614 | |
| 615 | CPU profile (5 typists sending at once, 20 pages): |
| 616 | - per-POST replay: 19%; |
| 617 | - garbage collection, mostly the replay's ~8 MB per POST: 14%; |
| 618 | - SQLite with its WAL lock calls: ~25%; |
| 619 | - GETs: 3%; |
| 620 | - the stream's per-write authorisation: 4%. |
| 621 | |
| 622 | ### 4.2 The prototype (measured) |
| 623 | |
| 624 | Branch `proto/live-push` implements the warm handle (§3.5 rules 2–4, lazy |
| 625 | eviction) and the push stream (`hello`, `push`, `own` with the hash check, |
| 626 | `update` fallback). It does not implement session binding, late answers, |
| 627 | `bye` or the byte cap. Probe: 20 pages, **sealed rows**, ~6 keys/s, |
| 628 | 150 keys per run, **three runs each on fresh servers**; median [range]. |
| 629 | "Arrived" is the bytes in the watcher's hand. Add the receiver's apply and |
| 630 | draw (web 5–10 ms, native 25–45 ms at 20 pages). The machine's load average |
| 631 | was 180–850, which is where the wide ranges come from. |
| 632 | |
| 633 | **Server cost, loopback** (CPU ms per second of typing; ms per upload; |
| 634 | allocation): |
| 635 | |
| 636 | | Case | Today (native 250 ms, fetch) | Push, cold replay | **Push + warm handle** | |
| 637 | |---|---|---|---| |
| 638 | | 1 typist | 42 ms/s; 11.5; 22 MB/s | 73; 12.0; 44 MB/s | **20 ms/s; 3.3; 1 MB/s** | |
| 639 | | 5 typists, own documents | 173; 10.3; 103 MB/s | 330; 11.6; 205 MB/s | **75; 2.6; 5 MB/s** | |
| 640 | | 5 typists + 5 watchers, one document | 436; 25.9; 165 MB/s | 678; 23.7; 263 MB/s | **421; 14.7; 12 MB/s** | |
| 641 | | 20 typists, own documents (one run) | 529; 9.3; 343 MB/s (p95 1,014 ms: saturating) | 928; 9.9; 647 MB/s (p95 802 ms) | **249; 2.3; 19 MB/s (p95 11 ms)** | |
| 642 | |
| 643 | **Latency, 50 ms round trip** (key → arrived, p50 / p95 ms): |
| 644 | |
| 645 | | Case | Today, native | Today, web | **Push + warm handle, 50 ms floor** | |
| 646 | |---|---|---|---| |
| 647 | | 1 typist, 1 watcher | 246 / 369 | 271 / 414 | **56 / 67** | |
| 648 | | 5 typists + 5 watchers, one document | 264 / 509 | – | **58 / 66** | |
| 649 | |
| 650 | What this settles: |
| 651 | |
| 652 | - **The warm handle is the prerequisite.** It cuts server CPU per upload |
| 653 | 3.5× (11.5 → 3.3 ms) and allocation ~40×. With it, push and sending at |
| 654 | once cost **less** CPU than today for typists in their own documents: |
| 655 | - 20 against 42 ms/s for one typist; |
| 656 | - 249 against 529 ms/s for twenty, where today's path saturates. |
| 657 | |
| 658 | A shared document costs about the same (421 against 436). Without the |
| 659 | warm handle, push and sending at once cost 1.6–1.9× today. So slice 1a |
| 660 | ships first (§10). |
| 661 | - **In a shared document the cost is the fan-out** (finding 13): ~12 ms of |
| 662 | server CPU per upload with 10 open streams, about 1.2 ms per stream per |
| 663 | frame. That covers the authorisation re-check, the row read, the unseal |
| 664 | and base64, and today's fetch path pays about the same per watcher. |
| 665 | Slice 1b adds a per-document frame cache (each seq read and unsealed |
| 666 | once, for every stream) and measures this case with and without it. If |
| 667 | the authorisation re-check is most of what remains, it moves to at most |
| 668 | once per second per stream, and at once on a grant change. That is a |
| 669 | decision for 1b's review with the numbers, not a default. |
| 670 | - **Push measured:** 0 GETs from watchers, 0 echo fetches, and every own |
| 671 | update arrived as `own`. |
| 672 | - Twenty typists at once in one instance cost ~0.25 of a core with the |
| 673 | design, against ~0.5 today. |
| 674 | |
| 675 | ### 4.3 Requests, the edge, storage |
| 676 | |
| 677 | - **Requests through the edge** (measured, real clients, 120 keys, 50 ms): |
| 678 | - today web → web: 68 POSTs and 126 GETs (the watcher's 68, plus 58 of |
| 679 | the sender's own updates fetched back); |
| 680 | - today native → native: 72 POSTs and 72 GETs; |
| 681 | - push with the 50 ms floor (projected; the prototype measured 0 GETs): |
| 682 | ~115–120 POSTs and no GETs. |
| 683 | |
| 684 | Each extra watcher costs a GET per upload today and nothing with push. |
| 685 | Frames are bytes on a connection that is already open: ~80–100 bytes |
| 686 | per keystroke per watcher. |
| 687 | - **Storage** (measured, sealed rows, `TestLivePushProbeRowSize`): |
| 688 | - a keystroke row costs **~180 bytes** of database (16 bytes of update, |
| 689 | the seal, the row and its indexes, snapshots amortised); |
| 690 | - each commit writes **~25 KB to the local WAL** (about six 4 KB pages: |
| 691 | the row, its index, `documents.updated_at`, the suite feed's revision). |
| 692 | That is local disk and checkpoint work: ~60 KB/s more per active typist |
| 693 | than today. |
| 694 | - **Replicated bytes, measured in slice 1b** (`replica-bytes.py`: |
| 695 | Litestream v0.5.14, the version `carlos/platform` main pins, local file |
| 696 | replica, default 1 s sync; one typist for 60 s at 20 pages, sealed rows, |
| 697 | two runs each): |
| 698 | |
| 699 | | Pacing | Uploads/min | Replica bytes/min | Replica files/min | |
| 700 | |---|---|---|---| |
| 701 | | Today's native (250 ms) | ~210 | 490–610 KB | ~65 | |
| 702 | | Push, 50 ms floor | ~360 | 835–860 KB | ~65 | |
| 703 | |
| 704 | The review expected the replica to get about the same pages whatever |
| 705 | the commit rate (LTX ships each changed page once per sync). Measured, |
| 706 | it grows ~1.5×. The number of files (an S3 PUT each) is the same, about |
| 707 | one per second. Per active typist that is ~+300 KB a minute: ~33 MB an |
| 708 | hour of continuous typing today, ~51 MB with push. |
| 709 | - **No server-side coalescing of commits** in this spec: it would cost |
| 710 | the latency the spec removes, and the cost above is bytes, not |
| 711 | requests. Open question 2 is back for Paul with these numbers. |
| 712 | - The log grows ~3.9 MB per hour of continuous typing (today ~2.3 MB); |
| 713 | compaction remains deferred (docs spec §4.1). |
| 714 | - **Per instance:** see §4.2. Nothing is shared between instances except |
| 715 | the edge, which sees no more requests than today. |
| 716 | |
| 717 | ## 5. Limits and safety rails |
| 718 | |
| 719 | - **Max update over the stream: 32 KiB** (raw). Larger goes as `update` |
| 720 | (fetch). That keeps every native SSE line well under `NativeStreamLines`' |
| 721 | 256 KiB line and 1 MiB event limits. |
| 722 | - **Slow receivers.** A stream never queues: it reads from the log, from |
| 723 | its own cursor, when it can write. A stream more than 256 rows / 512 KiB |
| 724 | behind gets one `update` and catches up by fetch. The write deadline |
| 725 | (30 s) still ends a stalled connection. |
| 726 | - **Late answers, bounded.** Clients keep one upload in flight, so the |
| 727 | server can rate-limit by answering later. A session that has posted more |
| 728 | than 30 updates to a document in the last second has its next answer |
| 729 | delayed: |
| 730 | - before it takes the document lock or the writer, never while holding |
| 731 | either; |
| 732 | - for at most 1 s; |
| 733 | - ended by request cancellation and by `hub.draining()`; |
| 734 | - at most 2 answers per session may be waiting; beyond that, `503` with |
| 735 | `Retry-After: 1`. The web queue retries a 5xx and the native drainer |
| 736 | honours `Retry-After`. Never a 4xx: the web save queue drops any 4xx |
| 737 | batch. |
| 738 | - **Authorisation** is re-checked once per flush (`nativeStreamAllowed`, |
| 739 | the team guard), not per frame. |
| 740 | - **Warm handles:** 128 MB and 64 per process (§3.5). |
| 741 | |
| 742 | ## 6. Security |
| 743 | |
| 744 | - Only a member who may read the document gets bytes. The stream route is |
| 745 | the same reader-scoped route (`getDocumentForUpdates`), every flush |
| 746 | re-checks the session and the document, and a stranger gets the same 404. |
| 747 | A reader's stream receives frames; the reader still cannot post. |
| 748 | - The bytes are the rows `GET ?since=` already serves the same person. |
| 749 | Sealed rows are opened with the same `openContentUpdate`. |
| 750 | - **`own` cannot cause a silent skip** (§3.4): the stream id is bound to the |
| 751 | session that opened it, the entry is matched by the row's bytes, and the |
| 752 | client adopts only a counter it sent on that stream at cursor + 1. A |
| 753 | forged or stale header yields a `push` (bytes applied as nothing) or a |
| 754 | fetch, never an adopted seq the client does not hold. |
| 755 | - `since` and `Last-Event-ID` are parsed like `parseSince` (400 on |
| 756 | garbage). A cursor ahead of the log is caught by `hello` (§3.1). |
| 757 | - A warm handle holds the document's decrypted state in memory for up to |
| 758 | ~75 s after its last write (§3.5 rule 7), and is dropped at once on any |
| 759 | access or sealing change. The process holds the content key anyway. |
| 760 | |
| 761 | ## 7. Compatibility and rollout |
| 762 | |
| 763 | | Client \ Server | Old server, or new server with push switched off | New server | |
| 764 | |---|---|---| |
| 765 | | Old web / old native | today | today: no `push=1`, so seq-only `update` events and no `hello`; POST unchanged; the warm handle and late answers are invisible | |
| 766 | | New web / new native | `push=1` ignored, no `hello`: fetch, and the **250 ms window** stays (§3.3) | push, the 50 ms floor | |
| 767 | |
| 768 | Old native parses any `data:` line as an `Int64`. It never asks for |
| 769 | `push=1`, so it never sees a frame. |
| 770 | |
| 771 | ## 8. Switches |
| 772 | |
| 773 | - `DOCS_WARM_HANDLE` (server): on by default once slice 1a is proven; off |
| 774 | means today's cold replay per POST. |
| 775 | - `DOCS_LIVE_PUSH` (server): off means `push=1` is ignored, so every client |
| 776 | goes back to today's path (fetch, 250 ms window) without a release. |
| 777 | |
| 778 | ## 9. Tests |
| 779 | |
| 780 | ### 9.1 CI, deterministic |
| 781 | |
| 782 | - **Go:** |
| 783 | - one POST yields exactly one flushed `push` frame per watcher, and no |
| 784 | GET; |
| 785 | - `own` reaches only the poster's stream, and only with a matching |
| 786 | session and hash; |
| 787 | - frames come in seq order under concurrent POSTs; |
| 788 | - resume from `since` and from `Last-Event-ID` (which wins); |
| 789 | - `hello` carries the current seq; |
| 790 | - oversized and far-behind rows become `update`, and `sent` moves; |
| 791 | - `bye ttl`, `bye lease` (team mode) and `bye drain` before those closes; |
| 792 | - a push stream without `since` sends the connect-time `update`; |
| 793 | - `hello` carries the log epoch, and the epoch rotates after an unclean |
| 794 | start but not after a clean drain; |
| 795 | - a reader's stream receives frames and its POST is refused; |
| 796 | - access revoked between two frames ends the stream; |
| 797 | - an old (non-push) client sees exactly today's events, checked with the |
| 798 | native line parser's rules. |
| 799 | - **Go, warm handle:** |
| 800 | - more than 4,096 POSTs to one warm document, none refused (finding 1); |
| 801 | - a writer revoked between apply and commit, after which the next |
| 802 | snapshot equals a cold replay (finding 2); |
| 803 | - a property test that warm and cold give the same state for random |
| 804 | update sequences, with injected failures; |
| 805 | - re-seeding at the snapshot cadence; |
| 806 | - the byte and count caps; |
| 807 | - dropping on delete, restore and grant change. |
| 808 | - **JS** (`live-updates.test.mjs`, `save-queue.test.mjs`, fake clocks): |
| 809 | - a key after idle is sent with zero wait; |
| 810 | - keys coalesce while a send is in flight; |
| 811 | - the 250 ms window stays without `hello`; |
| 812 | - uploads ≤ 1.2 × keys; |
| 813 | - the queue rules of §3.2 and `own` adoption; |
| 814 | - the reopen rule (§3.6): after any end, `bye` choosing the delay; a |
| 815 | fetch first; stop on 401/403/404; backoff capped at 60 s; the 8 h clock |
| 816 | reset by activity and frames, not heartbeats; the same on a non-push |
| 817 | stream; |
| 818 | - `hello` resetting per connection, and a POST in flight across a reopen. |
| 819 | - **Swift** (`RealtimeSyncTests`, fake clock): the same as JS, plus `own` |
| 820 | only when the model holds the batch, and the old-server path. |
| 821 | |
| 822 | ### 9.2 CI, timing (relative, never absolute) |
| 823 | |
| 824 | The probe in-process with a 20 ms injected round trip, three runs. In the |
| 825 | same process and the same runs: |
| 826 | - push's server-added p50 (measured minus injected) must be **≤ the fetch |
| 827 | path's**, best of three. Push removes a request, so it must not be |
| 828 | slower. |
| 829 | - uploads must be ≤ 1.2 × keys. |
| 830 | |
| 831 | It fails, and it never skips. |
| 832 | |
| 833 | ### 9.3 Release step |
| 834 | |
| 835 | - `run-clients.sh` with real web and native clients, at 0 and 50 ms, against |
| 836 | the §2 targets. |
| 837 | - Today's path (`DOCS_LIVE_PUSH` off) and push are run **interleaved, three |
| 838 | times each**, in the same session (as `realtime/run-matrix.sh` does). |
| 839 | - The result file, with the load average recorded, is committed beside the |
| 840 | release. |
| 841 | - No load ceiling: this Mac has not met one in any run so far. Interleaving |
| 842 | is what makes a loaded run comparable. |
| 843 | - A run that cannot be completed or recorded, or misses the targets, |
| 844 | **blocks the release**. It is never skipped or passed. |
| 845 | |
| 846 | ## 10. Slices and deploy order |
| 847 | |
| 848 | 0. **Before native work starts:** restore |
| 849 | `RealtimeAuditE2ETests.testEndToEndRemoteUpdates` (n = 0 since S1a: it |
| 850 | observes `projection`, which S1a made `@ObservationIgnored`; observe |
| 851 | `projectionGeneration`). |
| 852 | 1. **1a, server: the warm handle alone**, behind `DOCS_WARM_HANDLE`, with |
| 853 | rules 1–8 of §3.5 and the tests of §9.1. Deploy, then re-run |
| 854 | `load-p1`/`load-p20` and the 5-typist, 5-watcher shared document against |
| 855 | the real implementation. |
| 856 | 2. **1b, server: push**, behind `DOCS_LIVE_PUSH`: |
| 857 | - `hello`/`push`/`own`/`update`/`bye`; |
| 858 | - `Docs-Stream` and the session binding; |
| 859 | - late answers. |
| 860 | |
| 861 | Deploy with the switch on for Paul's team. 1b is done when: |
| 862 | - **Paul's edge check** (`edge-timing.js`) has been run on production, |
| 863 | before slice 2 ships, since edge buffering is unverified; |
| 864 | - the fan-out measurement (5 typists + 5 watchers in one document) has |
| 865 | been re-run on the real implementation **in team mode as well** |
| 866 | (`guard.check()` per flush), before deciding on the frame cache or on |
| 867 | throttling the authorisation re-check; |
| 868 | - **replica bytes per minute of typing** have been measured: LTX files |
| 869 | of a local file replica on CARLOS' Litestream version, 1 s sync, |
| 870 | today's pacing against the 50 ms floor. |
| 871 | 3. **2, web:** the push receiver; `hello` switching on the leading-edge send |
| 872 | (so it cannot go live before the push stream is checked on production); |
| 873 | the visible-tab rule (§3.6). It ships with a server deploy, so it is |
| 874 | ordered after 1b is checked. |
| 875 | 4. **3, native:** the push receiver in `DocsModel.listen`, the 50 ms floor |
| 876 | after `hello`, stream-id registration, `isExpensive`/`isConstrained`. A |
| 877 | native release after 1b is live. Independent of S1b (pagination). |
| 878 | |
| 879 | ## 11. Paul's edge check |
| 880 | |
| 881 | `native/benchmarks/live-push/edge-timing.js`, pasted into the browser |
| 882 | console on a scratch document. It works against today's server and a push |
| 883 | server alike. **Run it now for a baseline**: it answers the open question |
| 884 | (does the edge buffer the stream?) on today's server, because today's |
| 885 | server already announces each upload on the stream. Run it again after |
| 886 | slice 1b, when it also reports the `own` frame. |
| 887 | |
| 888 | Instructions for Paul: |
| 889 | 1. Sign in to Docs in Safari or Chrome. Create a document named |
| 890 | "Edge timing (scratch)" and open it. |
| 891 | 2. Open the console: Safari, Develop → Show JavaScript Console (turn on |
| 892 | Settings → Advanced → Show features for web developers if Develop is |
| 893 | missing); Chrome, View → Developer → JavaScript Console (Chrome may ask |
| 894 | you to type `allow pasting` first). |
| 895 | 3. Paste the whole file and press Return. It takes about ten seconds and |
| 896 | prints `DOCS EDGE TIMING { … }`. Copy that and send it back. |
| 897 | 4. Delete the scratch document. The script added three empty updates (two |
| 898 | bytes each, no visible change) to its history. |
| 899 | |
| 900 | The snippet only makes same-origin requests from that page. It sends no |
| 901 | data anywhere else and changes nothing visible. |
| 902 | |
| 903 | ## 12. Open questions for Paul |
| 904 | |
| 905 | 1. **The bound for an untouched visible tab (§3.6).** The spec uses 8 hours |
| 906 | (a working day) as the default. 2 hours fixes the lag complaint equally |
| 907 | and halves how long an instance stays awake. Unbounded is also possible. |
| 908 | His call. |
| 909 | 2. **Litestream traffic (§4.3, measured in 1b):** sending at once |
| 910 | replicates ~1.5× the bytes of today's pacing (835–860 against 490–610 KB |
| 911 | per minute of one person typing; ~51 against ~33 MB an hour), with the |
| 912 | same number of files (S3 PUTs). Fine as it is (recommended), or should |
| 913 | the server coalesce one session's commits over a short window, at the |
| 914 | cost of up to that window in latency? |
| 915 | |
| 916 | ## Review findings (Claude Fable 5.2, #172) and where they are answered |
| 917 | |
| 918 | | # | Finding | Answer | |
| 919 | |---|---|---| |
| 920 | | 1 | Warm handle reaches `MaxRetainedUpdates`; the web drops the save | §3.5 rules 2 and 4 (re-seed at the cadence, cold replay in the same POST); test in §9.1 | |
| 921 | | 2 | Applied but not committed poisons the handle | §3.5 rule 3; test in §9.1 | |
| 922 | | 3 | `own` can silently skip; the registry race | §3.4 (counter, session binding, hash, recorded inside the transaction), §3.2, §6; `own` wins on push streams | |
| 923 | | 4 | `bye` alone does not fix the 2-minute close | §1.3 cause 7, §3.6 (Paul's ruling, the 8 h bound, `bye` on drain with jitter), question 1 | |
| 924 | | 5 | Frames during a fallback fetch | §3.2 (queue and re-check), §3.1 (`sent` moves after `update`) | |
| 925 | | 6 | Cursor ahead of the log; `Last-Event-ID` | §3.1 (`hello` carries the seq; `Last-Event-ID` wins; no `id:` on `update`) | |
| 926 | | 7 | New client on an old server | §3.3 (the floor only after `hello`), §7 | |
| 927 | | 8 | Warm-handle memory and eviction | §3.5 rules 5–8 (measured, byte cap, drops, lazy sweep) | |
| 928 | | 9 | Projections, worst case not run | §4.2 (prototype: warm handle and push, 5 typists and 5 watchers in one document, three runs), labels throughout, §10 slice 1a re-run, §10 edge check as a condition | |
| 929 | | 10 | The latency gate would flake | §9 (deterministic CI, relative timing, release step) | |
| 930 | | 11 | Late answers need bounds | §5 | |
| 931 | | 12 | Split slice 1, switches | §8, §10 (1a, 1b, the web's leading edge gated on `hello`) | |
| 932 | | 13 | W watchers, W reads and unseals | measured in §4.2 (shared document); the cache decision follows from it | |
| 933 | | 14 | Real per-row storage | §4.3 (~180 B per sealed row; ~25 KB of WAL per commit), question 2 | |
| 934 | | 15 | Low Data Mode | §3.3, §3.8 (`isConstrained`) | |
| 935 | | 16 | Two processes on one database | §3.5 rule 8; old-process streams get `bye` on drain (§3.6) | |
| 936 | | 17 | More stream tests | §9.1 | |
| 937 | | 18 | Restore the native e2e probe | §10 slice 0 | |
| 938 | |
| 939 | ## Notes on the measurements |
| 940 | |
| 941 | - Revision 2's prototype measurements: branch `proto/live-push`, |
| 942 | `native/benchmarks/live-push/proto-table.py`, and the probe tests |
| 943 | `TestLivePushProbeWarmMemory` and `TestLivePushProbeRowSize` there. The |
| 944 | raw summaries are in `native/benchmarks/live-push/results-2026-11-26/proto/`. |
| 945 | |
| 946 | - The harness: `native/benchmarks/live-push/` (`gen-typing.mjs`, |
| 947 | `run-probe.py`, `run-clients.sh`, `browser-probe.mjs`, `breakdown.py`, |
| 948 | `server-costs.py`, `join.py`), `internal/docs/live_push_probe_test.go` and |
| 949 | `native/apple/Tests/DocsKitTests/LivePushLatencyTests.swift`. Every probe |
| 950 | skips unless its environment variable is set. The native probe needs the |
| 951 | release test build with `-DDOCS_PROBES -DDEBUG` (`ReplicaDirtyLogTests` |
| 952 | uses a `#if DEBUG` hook; no other `#if DEBUG` exists in DocsKit). |
| 953 | - Headless Chrome has no display link here, so "DOM updated" is the web |
| 954 | figure; paint is at most one frame later. The native watcher timestamps the |
| 955 | publication (when per-block drawing starts) and does not lay out pages |
| 956 | (S1b's subject). |
| 957 | - The machine was shared and heavily loaded (load average 10–970); every |
| 958 | CPU figure is ±20% and the end-to-end runs used the quietest windows. |
| 959 | - Not measured: the CARLOS edge end to end (needs a session), iPhone |
| 960 | hardware, documents over 20 pages. |
| 961 | - Aside: `RealtimeAuditE2ETests.testEndToEndRemoteUpdates` no longer sees |
| 962 | any publication (it observes `projection`, which S1a made |
| 963 | `@ObservationIgnored`), so it reports n=0; it should observe |
| 964 | `projectionGeneration`. |
| 965 | |
| 966 | ## Re-review findings (Claude Fable 5.2 on 9319c64, #172) and where they are answered |
| 967 | |
| 968 | | # | Finding | Answer | |
| 969 | |---|---|---| |
| 970 | | 1 | Team streams end at the lease deadline with no `bye`; reopen policy | `bye lease`; a visible tab reopens after any end, `bye` only chooses the delay; fetch first, stop on 401/403/404, backoff capped at 60 s (§3.1, §3.6, §9.1) | |
| 971 | | 2 | Visible-tab rule on a non-push stream; `hello` per connection | §3.6 (the same rule, TTL close as error, 1 s reopen), §3.3 (`hello` per connection, the in-flight POST across a reopen), §9.1 | |
| 972 | | 3 | WAL bytes are not replicated bytes | §4.3 rewritten (local WAL cost; the review's LTX reasoning attributed; CARLOS pins v0.5.14 on main), no coalescing, replica-bytes measurement in 1b's done list (§10), question 2 withdrawn pending it | |
| 973 | | 4 | Eviction swept only by POSTs; a handle over the cap; the plaintext sentence | §3.5 rules 5 and 7 (heartbeat sweep, ~75 s; one handle over the cap is not kept), §6 sentence fixed | |
| 974 | | 5 | Re-seed order | §3.5 rule 4: snapshot, `Apply`, commit, drop; a failed snapshot keeps the handle | |
| 975 | | 6 | Gate details | §9.2 (push ≤ fetch path's server-added p50, best of three), §9.3 (interleaved A/B, no load ceiling, a run that cannot be recorded blocks the release) | |
| 976 | | 7 | Connect-time `update`; restored log | §3.1 (connect-time `update` kept without `since`; log epoch in `hello` and `Docs-Log-Epoch`, rotated on any start without a clean-shutdown marker) | |
| 977 | | 8 | 1b fan-out re-run in team mode | §10, 1b's done list | |
| 978 | |