oficina / docs Public

Native realtime phase 1: fuel, echo, throttle, small fixes open

On branch perf/native-realtime-phase1

Phase 1 ("small, low-risk") of the native realtime fixes from the audit (native-levelup/docs-realtime-audit.md, probes on perf/native-realtime-audit). Not merged, deployed or released.

In this branch

  1. Finding 1, fuel (critical). native/host/src/lib.rs: the per-call budget is no longer a fixed 40M. It is 40M + 128 per byte of the instance's linear memory + 1,024 per request byte, sized from measured costs of documents of 1–400 pages with 2–3x headroom. Memory (64 MiB) and requests (8 MiB) are capped, so the host stays bounded: at most ~17G fuel (~20 s of interpretation on an M1 Max, and only for an instance already holding 64 MiB); a one-page document's calls get ~200M (~0.25 s). Out of fuel is still a trap that discards the instance. New host tests: the budget is bounded, running out is a clean failure that poisons the instance, and (in check-native.sh, release) a generated 200-page document with 10,000 edits opens and types through the host. It failed at open on the old budget. New mutation case for the ceiling. This touches native/host only (not native/crdt); the engine branch should rebase over it.
  2. Finding 5, echo download. The POST's Docs-Seq reaches the open document and is adopted by the web's noteOwnSeq rule: only when it is exactly sequence + 1, and only when the replica holds every outbox entry the POST carried, because another window may have written some. The server announces before it answers, so an event for the next row while this document's POST is in flight is held until the answer. The hold lasts at most 1 s, and a failed POST releases it at once.
  3. Finding 6, throttle. Update POSTs for a document are ≥ 250 ms apart, like the web. The first send after a pause goes at once. The per-keystroke durable outbox write is unchanged. Save, close and background send at once.
  4. Finding 10/13/14/15 (low). - The chunked response reader is a kit change: rastrillo/native branch perf/chunked-response-reader. It is pushed, not merged, and Docs' pin is unchanged until it lands. - iPhone closes the stream on .background and reopens it on .active, with no error. - Metadata is re-read and decrypted only when this account wrote it since, and observed state is assigned only on change.
  5. Kill harness. TestNativeKillServer now sends the session cookie. With cookies[0] (now rastrillo_attempt) the native process had no session and the script stopped before the kill. Plain and --random runs pass.

Not here: engine work (owned by perf/native-realtime-engine) and rendering work (deferred to the UI redesign).

Before/after numbers from the audit probes follow in a reply.

Before/after, measured with the audit's probes (perf/native-realtime-audit d23f3ca cherry-picked onto main 8e54d3a for before and onto this branch at d12b584 for after; nothing of the probes is in this branch). Release builds, M1 Max, other sessions on the machine, so treat timings as ±15%. Request counts are exact.

Typing, end to end (run-e2e.py … testEndToEndLocalTyping KEYS=40 CADENCE_MS=125 NOWAIT=1, the production DocsModel with a sealed store against the real server):

| Doc | POSTs (per s), before → after | Echo GETs ?since, before → after | CPU per key, before → after | | --- | --- | --- | --- | | p1 | 40 (5.8/s) → 22 (3.0/s) | 40 → 0 | 83 → 41 ms | | p10 | 40 (5.7/s) → 21 (2.9/s) | 28 → 0 | 211 → 153 ms | | p20 | 40 (5.6/s) → 21 (2.9/s) | 10 → 0 | 238 → 186 ms |

So, while typing:

  • Requests. Total requests per second went from 11.6 to 3.0 at p1 (target: at most 4).
  • Acknowledgement. The outbox now drains up to ~0.5 s after the last key, against 40–290 ms before. That is the throttle's wait plus the POST, as on the web. Every key is in the sealed outbox before anything is sent, as before.

Remote changes, p10 (testEndToEndRemoteUpdates, 30 peer updates and a burst of 10): unchanged. A peer's change is visible after a median of 257 → 268 ms. The client made 24 → 23 GETs for the 30 peer POSTs, and 4 → 4 for the burst. Peer changes are never held back by the echo rule.

Open and type (/tmp probe: the same call sequence CRDTReplica makes for open, then three keystrokes, run against each branch's own native/host):

| Doc | Before (40M fixed) | After | | --- | --- | --- | | p1–p20, p10h | OK | OK (same timings) | | p20h, p30, p30h | opens, first key fails (display_edit out of fuel) | OK | | p40, p50 | open fails (project) | OK | | p50h, p100h, p200, p200h, p400h | open fails (import) | OK | | p600, p800 (unedited) | – | OK |

After the change:

  • Interpreter time per key is 159 ms (p20h), 382 ms (p50h), 1.6 s (p200h) and 3.5 s (p400h). That is finding 2, the engine branch's work.
  • The memory cap (64 MiB) was not reached at 800 unedited pages; p400h uses 34 MiB.
  • End to end, p50h: before, it does not open. After, it opens in 618 ms and 16 keys type with no error and no echo GETs, but the model catches up 2.5 s after the last key.

Response reads (testEndToEndFetchCost, full-log GET, median of 5; after is built against rastrillo/native perf/chunked-response-reader via OFICINA_NATIVE_PACKAGE_PATH):

| Doc | responseDetails before | after | URLSession.data | | --- | --- | --- | --- | | p10 (36 KB) | 2.8 ms | 0.8 ms | 0.8 ms | | p50 (180 KB) | 13.3 ms | 1.1 ms | 1.0 ms | | p200 (718 KB) | 42.5 ms | 1.7 ms | 1.6 ms |

Metadata reads: 3.6 → 0.6 per key (RealtimeSyncTests.testTypingDoesNotRereadMetadataForEveryOutboxChange, with the throttle on in both cases). The remaining reads are one per POST (send) and one per flush (ensureMetadataEntry), still on the main actor. Caching those would hide a locked or damaged store, which OfflineDurabilityTests relies on seeing, so I left them.

Kill harness: on main, test-offline-kill.py fails before the kill: OfflineKillTests.swift:25 "open failed", then "typing assertions failed before kill". On this branch it passes the plain run and two --random seeds.

iPhone background stream: covered by RealtimeSyncTests.testBackgroundClosesTheStreamAndForegroundCatchesUp (no open stream while suspended, catch-up on resume, no error). It is not measured on a device. DocsKit builds for the iOS Simulator.

Local gates at 9ef6941:

  • native/scripts/check-native.sh green, including the 200-page long-document check and the browser↔native wire fixtures. swift test: 141 tests, 0 failures, including WorkspaceInitTests and SignedInLaunchTests.
  • check-mutations.py: every case caught, the new fuel-ceiling case included.
  • .amadan/ci.d/10-gate (go1.26.5) passes.

Whole-branch review of perf/native-realtime-phase1 at 9ef6941 (8e54d3a..9ef6941) — reviewer: Claude Fable (claude-fable-5-2), read-only via git show/git diff; nothing built or run by me, so every finding below is from reading (the server, the web's live-updates.mjs, and the kit's OutboxDrainer at the pinned a18c32b were read alongside).

Verdict: APPROVE AFTER FIXES

Findings 1 and 2 should be fixed before merge (both small). 3 needs a decision, not necessarily code. The rest are low.

Findings

1. Medium — the held announcement's 1 s cap does not work. DocsModel.swift:485-495 with :525-530. When the timer fires it calls releaseHeldRemote → refresh(sqid, remoteSequence: held), and refresh re-enters the same hold branch, because sequence + 1 == held still and postingUpdates still contains the key. It holds again with a fresh 1 s timer, and so on until the POST resolves. Scenario: this client's POST stalls on a bad connection (the stream is a separate connection and still delivers); a peer writes row S+1; that one change is not shown until the POST times out at the transport's request timeout, not after 1 s. No loss (a second peer row arrives as S+2 and is fetched at once; POST failure releases), but the stated bound and "peer changes are never held back" are not true, and no test covers the timeout path (testAHeldEventIsFetchedWhenTheOwnSaveFails covers failure only). Fix: the timeout path must bypass the hold (a parameter to refresh), plus a test with a POST that never answers.

2. Medium — the echo rule trusts sequence, and sequence is not always this document's. The model is reused across documents (DocsWorkspace.swift:57, DocsJumpControls.swift:124, iOS beginDocument :183-187), and sequence is assigned only at DocsModel.swift:287, :503, :519. - (a) New in this branch: open publishes self.replica at :285 and sets sequence only after the await at :287. A sent arriving in that suspension (the drainer is already sending this lane's replayed entries, which are in held) compares against the previous document's sequence. If it matches by coincidence, Task { replica.setSequence(assigned) } raises the replica's durable sequence (it is a max) past rows this replica never fetched, and that is what gets persisted. Narrow, but it is the one path I found where a remote row can be skipped. Fix: read persistentState().sequence before assigning self.replica, or have sent ignore results until open has finished. - (b) Pre-existing, not caused by this branch, but the same root: newDraft (:182-206) and discardAll never reset sequence. On iPhone: open a document at seq 500, tap New. The draft keeps sequence == 500, so after it attaches, refresh's remoteSequence > sequence guard ignores every announcement until row 501 and then asks ?since=500. A collaborator's first 500 rows never arrive in that session. Not reproduced, read only. sequence = 0 in newDraft/discardAll closes it; worth doing here since finding 5's safety rests on this variable.

3. Medium (decision) — fuel: bounded and off the main thread, but the bound per user action is several times "~20 s". native/host/src/lib.rs:25-35, :69-76. - Thread: every docs_host_call is inside actor CRDTReplica (CRDTReplica.swift:15, the only call site). Nothing runs on the main actor, so this cannot beachball as 0.1.7 did. The main actor only awaits. A long call does block that replica's actor, so typing, publish and close for that document queue behind it. - The budget is per call. One keystroke is up to 5 calls (CRDTReplica.command: edit, snapshot, apply, project, snapshot), fresh is 3, apply is 3. Worst case per keystroke is therefore ~5x the ceiling, and the figure is M1 Max only; an iPhone will be slower. The description should say so. - Can a peer or server buy fuel? Yes, linearly, and it stays capped. The request term gives ~1.07G fuel per MiB: a writer is limited to 1 MiB per POST by the server (handlers.go:39), a hostile server to 8 MiB per GET (8.6G, about 10 s). The memory term is persistent: content that inflates linear memory raises the allowance of every later call up to 8.2G. Both are bounded by MAX_FUEL, so the sandbox's guarantee (no unbounded run, trap discards the instance) holds on every entry point: instantiate/start, alloc, free and output reads get BASE_FUEL, the call gets budget, all via set_fuel (no carry-over). - What changed in kind: a failing remote update used to cost ~50 ms and now can cost seconds, and it is retried without limit. After a trap, apply rebuilds from lastGood (CRDTReplica.swift:139-147), sequence does not advance, and the next stream event fetches and applies the same bytes again (DocsModel.swift:497-508). A document with one poisoned row burns up to 3 budgets per announcement, and the editor stalls behind each. Suggest remembering a failed (since, Docs-Seq) and backing off, as a follow-up if not here. - Tests: the out-of-fuel test is meaningful (trap, poisoned instance) and the 200-page check is the real regression test. The new mutation case only mutates the test hook (.min(self.ceiling)), which is fine but proves nothing about the production bound; MAX_FUEL < 20G is the only pin on that. Nothing exercises an 8 MiB request, whose alloc now has only BASE_FUEL (unchanged from main, noted only). I think this is acceptable for phase 1 given the engine branch attacks the cost itself, but Paul should know the worst case is "a document that takes a minute per key on a background thread", not "20 s".

4. Low — a stream can start while the iPhone is in the background. suspendLiveUpdates (DocsModel.swift:539-542) cancels the current stream only. An open that completes after backgrounding (:302) or a draft attaching (reloadMetadata :127-129) starts one anyway. Harmless (it errors on suspension and .active finds streamTask != nil, which is then a dead-or-retrying loop rather than a fresh one). A suspended flag checked at both sites would make it exact.

5. Low — the batch is reserved before the wait. DocsOfflineAccount.swift:253 paces after beginSend and after the merge, so keys typed during the 250 ms wait miss that POST and wait for the next (hence ~0.5 s acknowledgement), the entries show as in flight meanwhile (compaction is refused, correctly), and Save after sendNow can still wait up to 250 ms for the second batch because the woken send has just stamped lastUpdatePost. Durability is unaffected: the outbox write is before all of it. Also, pacing blocks the single drainer, so another document's lane waits behind it. Acceptable; noting it because "Save sends at once" is true only of the first batch.

6. Low — a discard during the wait is still sent. DocsOfflineAccount.swift:253-257: send does not re-check replicaCache.generation(key) after pace. Same race as a discard during a POST on main, widened by up to 250 ms. One guard after pace closes the added part.

7. Nits. held keeps the IDs of compacted-away entries for the session (DocsPersistence.swift:78-79); the four new private properties on the @Observable DocsModel (:45-51) are not read by any body but could be @ObservationIgnored to keep it that way.

Checked and found sound

  • Echo skip vs convergence. Server seq is per document, gapless, MAX+1 in the write transaction, never reused, and every accepted POST inserts a row (store.go ApplyUpdate); the header is set and the hub broadcasts before the 204 (handlers.go:1077-1080). With a truthful sequence, assigned == sequence + 1 means no other row lies between. Peer row before ours: not adopted, fetched. Ours then peer: the S+2 event is not held and fetches since S. Lost response and retry: duplicate row, idempotent. Two windows: neither adopts the other's entries, and a cross-window compaction is adopted by neither; every held error is on the safe side (fetch). Reconnect and server restart: the connect-time event (stream.go:175-181) fetches. One batch is in flight per account (OutboxDrainer), so postingUpdates and the single pacing slot are safe. An out-of-order setSequence Task can only lower-bound, since the actor takes the max.
  • Durability. Per-keystroke outbox write unchanged and precedes any send; kill during the wait leaves the entries on disk; ordering is the drainer's, unchanged. Status is derived from the outbox, so "Saved" cannot show while entries wait; it only arrives later.
  • iOS / SwiftUI. All new calls are in .onChange/.task, none in init/body; the new account state is @ObservationIgnored. Cancelling the stream raises no error (:470, :508).
  • Metadata cache. Only reloadMetadata is cached. Every writer goes through saveMetadata/removeMetadata on the shared account, a failed or nil read does not record the revision, and that path already swallowed errors with try?, so nothing that was visible is hidden. The reads in send (:214) and ensureMetadataEntry (:194) are still live, as described.
  • Kill harness. Picks the session cookie by name; fine.

Review fixes pushed: 8816b76, 1a1b74b (on top of 9ef6941).

  1. Hold cap. The 1 s timeout now fetches with the hold bypassed (refresh(…, holding: false)). New test testAStalledSaveHoldsAPeerChangeForAtMostASecond: the POST answers only after 4 s, and the peer's change shows within 1.8 s.
  2. Cursor. - (a) open reads the persisted sequence before the replica is published and sets sequence in the same synchronous step, so the window is gone. There is no deterministic test, because the window was a single await that no longer exists. - (b) newDraft and discardAll set sequence = 0, and clear the hold and backoff state. Writing the test also found that a draft started after stop() never published: newDraft kept the previous document's render generations, so publishCurrent refused every presentation as older. newDraft now resets them, as open already does. - Tests: testANewDraftAfterADocumentStartsFromItsOwnCursor (discardAll, then newDraft) and testANewDraftAfterStopStartsFromItsOwnCursor.
  3. Fuel. - The bound is kept as designed. A remote catch-up whose apply fails is not fetched again from the same cursor until a backoff passes: 2 s, doubling, capped at 60 s. The editor keeps showing the existing "retrying" state, which clears once the rows apply. Test testRowsThatWillNotApplyAreRetriedWithBackoff: 4 announcements cause 1 fetch, then the rows recover after un-poisoning. - The production allowance is pinned exactly in fuel_budget_grows_with_the_instance_but_stays_bounded: representative sizes, memory past the cap, and MAX_FUEL. A new mutation, doubling the per-memory-byte allowance, is caught. - The worst case per keystroke is up to 5 calls, and these are M1 Max figures; an iPhone will be slower. This is noted for Paul. - native/host/src/lib.rs is unchanged.
  4. Background stream. A liveUpdatesSuspended flag is checked where open finishes and where a draft attaches. Test: testAnOpenThatFinishesInTheBackgroundStartsNoStream.
  5. Reserve after the wait. The fix stays inside Docs, because the kit's drainer reserves before it calls send. After a POST, if more of the lane is waiting, send holds the drainer until the next POST is allowed. The drainer then reserves everything typed by then in one batch. - sendNow (Save, close, background) skips the throttle for 1 s. - Test testKeysTypedDuringTheWaitJoinTheNextPost: 6 keys typed ~70 ms apart take 3 POSTs. Without the change they took 4.
  6. Discard during the wait. The generation is re-checked after the wait. Test: testADiscardDuringTheThrottleIsNotSent.
  7. Nits. held drops the IDs of entries that compaction replaced. The new bookkeeping on DocsModel is @ObservationIgnored.

Each new test was seen to fail with its fix removed.

Local runs:

  • check-native.sh passes, including the 200-page check and the wire fixtures; swift test ran 148 tests with 0 failures.
  • The host mutation cases are all caught.
  • test-offline-kill.py passes.

DocsPersistence.reopen is untouched. In native/host, only tests/sandbox.rs changed (+8 lines).

Delta re-review of 9ef6941..1a1b74b (8816b76, 1a1b74b) — reviewer: Claude Fable (claude-fable-5-2), read-only via git show/git diff. I built and ran nothing; this is from reading the diff, the full DocsModel/DocsOfflineAccount/DocsPersistence at 1a1b74b, and the kit's OutboxDrainer/Outbox at the pinned 529f356.

Verdict: APPROVE

All seven earlier findings are fixed as described. I found no regression that should block the merge. Four low notes are at the end; none needs to be done here.

The earlier findings

  1. Hold cap — fixed. DocsModel.swift:515-526, :569-574. The timer clears heldRemoteTask, then releaseHeldRemote(holding: false) reaches the fetch without re-entering the hold. If the fetch brings back this client's own row S+1, the later POST answer is not adopted (assigned != sequence + 1) and the apply is idempotent. If the peer's row was S+1 and ours lands as S+2, it is adopted with nothing between. Both are correct.
  2. Cursor — fixed. - (a) :299-304: the persisted sequence is read before the epoch guard, and sequence, resetRemoteState() and self.replica are set with no suspension between them. Between configurePersistence (:296) and that point, sent returns at its let replica guard, so nothing can be adopted against the previous document's cursor. - (b) newDraft (:208-209) and discardAll (:444) reset the cursor, the hold and backoff state, and the generations. stop() does not reset, but every way back in (open, newDraft) does. - Echo rule: a draft starts at 0 and adopts its first POST only if the server answers seq 1, which is right. A refresh or setSequence Task still in flight across the reset is stopped by the replica === guards or lands on the old replica.
  3. Fuel — fixed as ruled. The backoff is at :506-510, :531-546, :575-583; the pin is in sandbox.rs:74-81 plus the mutation case. The pin is exact: base, both per-byte terms, both caps and MAX_FUEL.
  4. Background stream — fixed. Both start sites check the flag (:136, :320), and resumeLiveUpdates clears it before its guard.
  5. Reserve after the wait — fixed. DocsOfflineAccount.swift:282.
  6. Discard during the wait — fixed. :261. The thrown CancellationError counts as a lane throw in the drainer, but the lane's entries are already gone, so nothing follows from it.
  7. Nits — done. DocsPersistence.swift:79-81 and the @ObservationIgnored properties.

What you asked me to check

  • Can the backoff hide a change, or block a later good update? No. - It applies only while refused.since == sequence. A fetch from that cursor returns the bad rows together with any later ones, so there is no good fetch for it to block. Once the cursor moves, the record is ignored. - Every refused attempt schedules a retry from latestAnnounced, which is recorded before any early return. A retry that fails again reschedules itself, so the chain continues at the 60 s cap. - An announcement that arrives just as the timer is due is harmless: the old task wakes, sees the new deadline and reschedules. - Convergence is better than at 9ef6941. A failed apply used to wait for the next announcement; now it retries after 2 s with none. - The cost is that a transient failure delays a peer's change by up to the current backoff (at most 60 s) instead of until the next announcement. - A retry whose GET fails on the network ends the timer chain. The next stream event, or the connect-time event after a reconnect, fetches again, as before.
  • Does holding the drainer stall the outbox? No. - The hold is at most sendInterval minus the POST's own duration, counted from the POST's start, and only when the lane has more sendable entries. sendNow wakes it. - It comes after posted() and replicaCache.commit, so sequence adoption and the local commit are not delayed. - sessionEnded and drainer.stop() do not wake it, but it ends by its own timer within 250 ms and returns .sent, which is true. - A kill during the hold leaves entries that were sent but not acknowledged, so they are sent again as a duplicate idempotent row. That window existed before and is now up to 250 ms wide while typing. - "Saved" is not delayed. The hold happens only when more entries are waiting, so the lane was not going to show Saved yet. The per-keystroke outbox write is untouched. - A discard during the hold is safe: Outbox.ack skips unknown IDs.
  • SwiftUI. No view file changed. The new state is @ObservationIgnored. The one new observed write is errorKey in the backoff branch, which runs from the stream callback or a timer, never from init or body.

Low notes (follow-up at most)

  1. Low — the sendNow bypass lasts 1 s, not until the drain finishes. DocsOfflineAccount.swift:162, :167. If an offline backlog is more than one 512 KB batch and the POSTs are fast, batches after the first second are paced at 250 ms again. This is on Save and, more to the point, in iPhone background time. It is rare because compaction keeps lanes small. Clearing the bypass when the drain goes idle would be exact.
  2. Nit — the retry timer outlives stop() and suspendLiveUpdates(). DocsModel.swift:575-583. After stop() it wakes once and returns at the detail guard. In the background it fetches at most once per backoff. Cancelling it in both places would be tidier.
  3. Nit — "retrying" and other statuses overwrite each other. :507 assigns "retrying" over any other errorKey on every announcement during the backoff. flush() (:470) clears "retrying" while the rows are still refused, until the next announcement or retry. Cosmetic.
  4. Nit — a few held IDs linger after an open. :561. A sent that arrives during open's awaits returns before persistence.forget, so those IDs stay in held for the session. The error is on the safe side: a fetch, never an adoption.

Known and accepted under the fuel ruling, so not a finding: a row that never applies costs up to three budgets once a minute on the replica's actor for as long as the document is open, and typing queues behind each attempt.

Landed on main (squash) after Fable's APPROVE at 1a1b74b and green hub CI. Fable's four low notes (1 s sendNow bypass, backoff timer not cancelled on stop, errorKey overwrite, held IDs after open) are follow-ups. perf/native-realtime-engine rebases onto this next.