oficina / docs Public

Native realtime: engine (CRDT/WASM layer and replica persistence) open

On branch perf/native-realtime-engine

Engine half of the native realtime fixes from the audit (oficina/native-levelup/docs-realtime-audit.md, probes on perf/native-realtime-audit d23f3ca). Phase 1 (fuel, echo skip, 250 ms throttle, response reader, iPhone stream) is on perf/native-realtime-phase1, by another session; nothing here does those. Rendering is out of scope.

Not for merge yet. Work in progress, pushed as it lands:

  • [x] 9 (engine part): compile the wasm module once per process (8bb6258). Hosts still get their own store, memory and fuel.
  • [x] 7: a command's update carries only what its own transactions changed, like the browser's doc.on('update') (f9a17cd). New wire gate update_wire_probe + check-update-wire.mjs in check-native.sh (Yjs replay gc on/off, keystroke has no delete set, browser per-transaction updates applied natively).
  • [ ] 2: display offsets mapped without a projection; no snapshot or projection per command/apply; incremental projection deltas to Swift.
  • [ ] 8: incremental replica persistence (append, compact occasionally), keeping the outbox/sealed-store guarantees.

Before/after numbers, tests and CI will be posted here per step.

Heads-up from phase 1 (perf/native-realtime-phase1, #146), so this branch can rebase over it:

  • native/host/src/lib.rs. The fixed FUEL is replaced by fuel_budget(memory, request): 40M + 128 per byte of linear memory + 1,024 per request byte. It is capped by the 64 MiB memory limit and 8 MiB MAX_BYTES, at about 17G. Housekeeping calls (alloc, free, output) run on the 40M floor. The failed poisoning is unchanged.
  • native/host/tests/sandbox.rs. Three new tests: - the budget is bounded; - out of fuel is a clean failure that poisons the instance; - an ignored long_edited_document_opens_and_types, which check-native.sh runs in release on a generated 200-page document with 10,000 edits (fixtures/generate-large-doc.mjs).

That last test drives the same call sequence CRDTReplica makes today: open/255/clients/snapshot/project, then per key display_edit/snapshot/254/project/snapshot/anchor/resolve. If the engine changes that sequence, update the test to match.

  • check-mutations.py. One new host case, for the fuel ceiling.

I did not touch native/crdt or CRDTReplica.swift. The Swift changes are in DocsModel, DocsOfflineAccount, DocsPersistence (it tracks the IDs of outbox entries the replica holds) and DocsWorkspace.

Engine scope is in, at 69d8ae9 (8 commits). Not merged, deployed or released. Hub CI passed at c78bda6.

Commits

  • 8bb6258: 9. The wasm module is compiled once per process. Each host still has its own store, memory and fuel.
  • f9a17cd: 7. A command's update is only what its own transactions changed (the same as doc.on('update')). New wire gate: update_wire_probe + check-update-wire.mjs.
  • 3f54c32: 2, Rust half. Display offsets map by walking the yrs tree using stored text lengths. Nodes are looked up by identity. project_delta re-projects only the top-level blocks a transaction touched. A text's embeds now render as U+FFFC, so a display offset equals a yrs offset. Documents without embeds project byte for byte as before (tested against the old code).
  • 23d8d97 + 712746f: 2, Swift half. command and apply no longer project or snapshot. lastGood is now a base plus the updates since. Source reuse tracks an authority version instead of comparing snapshots byte for byte. Presentations patch the cached projection with deltas.
  • be40e24 + c78bda6: 8. The replica is stored as a base plus appended segments (replica-log/). Every 32 segments are compacted into the base. Headless sends append too. Discard removes segments before the base. Orphaned segments are never read. One unreadable segment drops the whole replica, as a corrupt base already did. Memory for unstored changes is bounded.

Before → after. Audit probes, release build, production fuel, same machine. Rows marked \* used fuel raised for diagnosis; their "before" values are the audit's figures.

| | p1 | p10 | p10h | p20 | p50\ | p200\ | p200h\ | |---|---:|---:|---:|---:|---:|---:|---:| | command(display_edit) ms | 5.35 → 0.76 | 43.4 → 1.09 | 47.8 → 1.25 | 88.4 → 1.55 | 213 → 2.97 | 886 → 9.6 | – → 9.9 | | presentation (reused source) ms | 7.11 → 2.26 | 61.1 → 3.28 | 63.6 → 3.57 | 120.8 → 4.05 | 297 → 5.24 | 1,263 → 16.1 | – → 16.4 | | remote apply ms | 2.9 → 0.21 | 18.9 → 0.22 | 22.1 → 0.26 | 37.2 → 0.23 | 91 → 0.24 | 375 → 0.26 | – → 0.31 | | presentation after a remote change ms | 16.3 → 3.5 | 72.8 → 9.1 | 86.5 → 17.3 | 143 → 14.7 | 321 → 31 | 1,604 → 117 | – → 262 | | bytes per typed character | 21 → 14–21 | 21 → 14–19 | 685 → 14–21* | 22 → 16–22 | 3,585 (p50h) → 22 | | 11,817 → 22 | | replica persist (sealed disk) ms | 16 → 1.85 | 55 → 1.81 | 70 → 1.82 | 100 → 1.79 | 237 → 1.85 | 900 → 1.97 | 1,300 → 2.00 | | new host ms | 6.9 → 0.04 | | | | | | |

For context, a whole-state persist is still needed for the first write and costs 11–321 ms (p1–p200h). Compaction runs every 32 appends and costs 10–385 ms (p1–p200h).

End to end: production DocsModel against the real server, 8 keys/s, the same fixture binary.

  • Peer change visible (median): p10 264 → 41 ms, p20 500 → 64 ms. A burst of 10 changes shows in 678 → 148 ms at p10 and 1,564 → 199 ms at p20.
  • CPU per typed key: p10 203 → 41 ms, p20 244 → 62 ms. The model now catches up 29–40 ms after the last key, against 159–349 ms before.
  • Key → server ack: 75–78 → 10–12 ms.

Tests and gates

  • Native gate (check-native.sh, full macOS run): green. swift test: 140 tests, 0 failures.
  • New Rust tests: - minimal updates: every command kind, peers with gc on and off; - display mapping against the old projection-based mapping, at every position; - projection deltas over 160 mixed steps; - host isolation with the shared module.
  • New Swift tests: - CRDTIncrementalTests; - ReplicaSegmentTests: crash at every operation of an append and the compaction after it, orphaned segments, corrupt segment, memory bound.
  • OfflineDurabilityTests now checks I1a against base plus segments.
  • Go gate (.amadan/ci.d/10-gate, go1.26.5): green. Two cmd/docs tests fail on macOS only because the default TMPDIR makes the unix socket path too long; with TMPDIR=/tmp they pass.

Remaining

  • Phase 1 overlap. A trial merge with perf/native-realtime-phase1 conflicts in three files: - native/host/src/lib.rs: fuel and the module cache, both in Host::new/call; - native/host/tests/sandbox.rs; - DocsPersistence.reopen: their held set against the segment loop.

DocsOfflineAccount merges cleanly. I'll rebase onto main once phase 1 lands. p50 and larger still need phase 1's fuel to open.

  • Rendering is now the bottleneck. The engine keeps up, so every keystroke is published. At p20 that means 41 whole-document renders at about 29 ms each on the main thread, which is findings 3 and 4 (UI). The deltas would allow rendering per block.
  • Large documents, possible next engine steps: - A presentation after a remote change still opens a fresh source from the whole state: 117 ms at p200 and 262 ms at p200h. A standby sandbox kept in sync would remove that. - At p200 a keystroke still walks the top level (about 10 ms for display_edit and 16 ms for a presentation). A per-block length index would make it O(log n).

Review of perf/native-realtime-engine at 69d8ae9 (whole branch against main 8e54d3a), by Claude Fable (model claude-fable-5-2), review-only session.

Verdict: APPROVE AFTER FIXES

The branch's own logic held up: I could not make minimal updates, delta projections or the segment store lose or diverge data. Fix finding 2 before merge. Finding 1 is the serious one, but it is already on main, so it can be its own change as long as it lands before the natives ship.

What I ran

  • Native gate: native/scripts/check-native.sh (Rust 1.98.0) in my own detached worktree at 69d8ae9: green, 141 Swift tests, 4 skipped, 0 failures.
  • Fuzz (temporary, not committed): three editors run random commands and exchange only the per-command updates. After every step I checked: - each editor against a plain yrs doc that received only those updates (projection, state vector, delete set), with gc on and off; - project_delta replayed onto the previous projection against a fresh projection; - convergence of all three at the end.

Commands: display_edit (insert, delete, cross-block), display_paste with nested lists, undo, redo, block, attribute, format, list_indent, split, hard_break, display_autoformat, batch. display_exit_list never succeeded, so it is not covered. 40 seeds of 150 steps per pass.

  • Result: with unpatched yrs the fuzz dies on finding 1. With a three-line yrs patch, 15 passes were green (2 with random order and duplicates, 13 in causal order) and one failed (finding 9).
  • Both review worktrees are removed. Harness, minimal repro and the yrs patch are in /tmp/fable-review-145/ on this machine.

Findings

1. HIGH, already on main, not a regression: vendored yrs leaves an undo-kept item under a garbage-collected parent. native/vendor/yrs-0.23.5/src/block.rs:1375 (Item::gc skips kept children even when the parent is being collected), with block.rs:415 (keep(false) clears the flag up the parent chain while a sibling is still kept) and undo.rs:508 (clear_item).

  • Repro (fable_keep.rs, deterministic on main 8e54d3a): delete a word; type a character in the same paragraph; undo; type anything (this clears the redo stack); a peer deletes that paragraph. The next Editor::snapshot panics at slice.rs:212, "Could not get parent branch info for item". The kept item's parent pointer dangles.
  • Silent variant (seen in the fuzz on this branch, native build): no panic, but the 18 KB snapshot cannot be integrated by a fresh doc. It projects as empty while the editor shows 23 blocks.
  • In the WASM build: the same sequence through CRDTReplica came back correct in my one run. It is reading freed memory that happened to be intact, so I would not rely on it.
  • Why it matters here: every compaction (lastGood base), every new source and every stored base is a snapshot. A bad one becomes the local replica, and the stored sequence stops the server from ever correcting it. The branch is no worse than main (main snapshots after every command), and its base-plus-updates recovery heals the panic variant.
  • Fix: collect the children of a collected parent whatever their keep flag, as Yjs Item.gc does. /tmp/fable-review-145/yrs-gc.patch does this and is what the passes above ran with. Add the repro as a test.

2. MEDIUM: the update sink records every transaction and only command empties it. native/crdt/src/lib.rs:52, :155.

  • observe_update_v1 fires for 254/255 applies too. The authority only runs command for undo and redo, so it keeps a second copy of the whole opening state plus every update of the session in WASM memory. Sources keep the opening copy until their first command.
  • Every fresh(update:) also re-encodes the whole document just to fill the sink, which costs fuel and time on open and on every new source.
  • Failure: a large document or a long session gets closer to the 64 MiB and fuel limits, then traps and recovers in a loop.
  • This is from reading the code; I did not measure it.
  • Fix: record only while command is executing, or clear in apply_origin.

3. LOW to MEDIUM: a missing segment is silent. DocsReplicaCache.swift:61 (else { continue }), :66.

  • Segments carry no chain or count. BlobStore removes a corrupt file itself before throwing .corrupt.
  • Failure: the remove(key) in the catch at :66 fails (locked device, I/O error). The next load then succeeds without that segment, while a later segment's sequence says the state is complete. Whatever the segment held (peer changes, or acknowledged local edits) is never fetched again.
  • The same hole appears if a power loss drops one file; the store only promises to survive a process kill.
  • Fix: give each segment its predecessor's name or a running index, and treat a gap like an unreadable segment.

4. LOW: a whole state stored as a segment does not trigger compaction. DocsPersistence.swift:84.

  • After the 4 MB overflow (needsWhole), commit appends the whole state as a segment but compactIfNeeded is told appended: 0.
  • Up to 31 whole-state segments can sit on disk and be replayed at open. Pass the whole state's size.

5. LOW: CRDTReplica.persisted drops "the first n" updates. CRDTReplica.swift:111.

  • Correct only while persist() never overlaps itself. That holds today because DocsModel.persistReplica is the only caller and goes through CoalescedRunner.
  • Two overlapping captures would drop updates that were never stored. Use absolute offsets.

6. LOW: command still lets {"op":"apply"} through. CRDTReplica.swift:250.

  • The engine applies it and returns nothing, so lastGood, the source state and unpersisted miss it. No caller sends it today. Reject it alongside project.

7. LOW: lastGood.data is base plus up to 256 KiB of tail in one 255 envelope.

  • A document whose snapshot is within that margin of the 8 MiB limit can no longer build a fresh sandbox until it compacts.

8. Test gaps.

  • check-update-wire.mjs replays 8 steps into one Yjs peer, in order, and compares toString and the state vector. It has no shuffled or duplicated delivery, no delete-set comparison, and no format, attribute, list_indent, split or autoformat.
  • The delta test is one sequence (seeds 22 and 9, 160 steps) with no nested-list, format or remote structural edits.
  • The fuzz in /tmp/fable-review-145/fable_adversarial.rs covers these on the yrs side and could be adopted once finding 1 is fixed.

9. Unexplained, seen once.

  • One in-order pass (yrs patch applied) failed at seed 39, step 22: after an undo, the editor's delete set differed from that of the peer given only the update.
  • It did not recur in 12 further full in-order passes or 150 runs of that seed, and I did not capture which side had more.
  • My guess is leftover memory unsafety from finding 1, but I have not shown that. It is worth one more look once finding 1 is properly fixed.

Your seven questions

  1. Minimal updates: sound. The update is yrs's own transaction update (new structs since before_state plus the transaction's delete set), merged across a command's transactions. Every command kind above converged through its own update alone, with gc on and off, out of order and duplicated. A failed command can leave its writer changed with no update (23 of about 6,000 steps). CRDTReplica.command rebuilds the writer on every error path, so nothing diverges, but that rebuild is now load-bearing.
  2. Delta projection: no mismatch found. A block's projection depends only on its own subtree. changed_parent_types reaches the top-level ancestor, and new or re-created blocks are inserted because their identity is new. List numbering is not in the projection. The patched projection matched a fresh one after every checked step.
  3. Position mapping: equivalent by reading (locate, resolve, the fallback). The branch's own test checks every position, including surrogate pairs, atoms, empty blocks and the end of the document. I did not add to it.
  4. Persistence. - Crash points in append, compaction and discard are safe by reading, and the branch's crash test covers them. - "No local edit without its outbox entry" holds: an append needs commandsApplied == commandsDurable, re-checked with no suspension before the write. - Dropping the stored replica loses nothing. Unsent edits are in the outbox. Sent ones are appended by the send path before they are marked sent. - Two windows are better off than before, since each appends and compaction removes only what it merged. - Two processes compacting the same key could lose a segment, but I found no second process on this store. - Beyond 4 MB the record is dropped and the next persist stores the whole state. - See findings 3 to 5.
  5. Concurrency: fine. wasmi 0.32.3's Engine and Module are Send + Sync, and each host has its own store, memory and fuel. Sandboxes never leave the actor. DocsReplicaCache still does file and sealing work on the main actor, but less per persist than before.
  6. U+FFFC: no real document affected. y-prosemirror only puts strings and formats in an XmlText. Inline nodes are sibling elements.
  7. Rebase on phase 1. - Conflicts: Host::new and call (fuel against the shared module), sandbox.rs, and reopen (the held set against the segment loop). - Phase 1's long-document test: long_edited_document_opens_and_types must follow the new call sequence: no snapshot or project per key, project_delta, and a 255 envelope carrying base plus tail. - Echo skip: it adopts the server sequence without applying anything. That is safe only because the send path appends the sent update to the log in the same main-actor turn as posted, before .sent. Keep that order through the rebase, and add a test: crash between enqueue and persist, reopen, send, adopt the sequence, reopen. - Empty segments: echo skip will also produce segments with no update. The engine accepts them.

Rebased onto main 80d4989 (phase 1). Branch is now 59be82d, force-pushed; hub CI passed.

Conflicts resolved, phase 1's behaviour kept:

  • native/host/src/lib.rs: the module cache now sits under phase 1's fuel allowance. Host::new instantiates the cached module with BASE_FUEL, MAX_MEMORY and ceiling; call is phase 1's unchanged.
  • sandbox.rs: both sets of tests kept (pinned allowance, out-of-fuel, the 200-page check, shared module).
  • DocsPersistence.reopen: the segment loop plus phase 1's held.insert.
  • DocsOfflineAccount.send: my append-or-whole-state block, then phase 1's pacing hold. Order unchanged: the sent update is stored before the dispositions mark entries sent.
  • DocsModel.refresh: phase 1's refused-update backoff, around try await replica.apply (now Void). Publish then persist, as before.

Folded into the commits that need them:

  • RealtimeSyncTests uses the new command return.
  • check-mutations.py: the resolve mutation follows the new code (found = Some(start + local.min(length))).

Gates on 59be82d:

  • check-native.sh --mutations: green. That covers the 200-page edited open-and-type check, the wire, rule and update-wire fixtures, all 15 mutations caught, and swift test: 165 tests (13 skipped, env-gated), 0 failures.
  • Go gate: green with TMPDIR=/tmp.

Headline numbers. Phase 1 main (80d4989) → this branch, release builds, production fuel (phase 1's allowance), same machine run back to back. The load average was about 27, so absolute values are higher than in the audit.

| | p10 | p20 | p50 | p200 | p200h | |---|---:|---:|---:|---:|---:| | command(display_edit) ms | 55.8 → 1.16 | 105.9 → 1.53 | 269.9 → 2.79 | 1,008 → 9.3 | 958 → 9.4 | | presentation (reused source) ms | 77.9 → 3.88 | 149.4 → 3.99 | 374.1 → 4.92 | 1,260 → 15.6 | 1,289 → 16.1 | | engine per key (sum) ms | 134 → 5.0 | 255 → 5.5 | 644 → 7.7 | 2,268 → 25 | 2,247 → 25.5 | | bytes per typed char | 21 → 21 (p10h 685 → 21) | 22 → 22 | 22 → 22 | 20 → 22 | 11,817 → 22 | | remote apply ms | 18.1 → 0.24 | 36.1 → 0.22 | 87.9 → 0.24 | 351.6 → 0.24 | 389 → 0.31 | | presentation after a remote change ms | 70.7 → 9.0 | 134.2 → 14.3 | 315.9 → 30.7 | 1,269 → 111 | 1,464 → 253 | | replica persist (sealed disk) ms | 50.6 → 1.9 | 93.5 → 1.9 | 223 → 1.8 | 840 → 1.8 | 1,086 → 1.9 | | peer change visible, end to end, median ms | 241 → 43 | 489 → 64 | 1,224 → 209 | 5,106 → 863 | | | burst of 10 peer changes visible ms | 658 → 137 | 1,535 → 235 | 3,605 → 523 | 15,058 → 1,916 | |

The bytes-per-character figures come from the probe's display_edit, which carries the typing marks; a bare character is 14–16 B.

The end-to-end numbers use the production DocsModel and the real server. At p50 and p200 the remaining time is mostly two things: the whole-document render plus reconcile on the main thread (42 ms at p50, 176 ms at p200; findings 3 and 4), and the fresh source sandbox built after each remote change (31 ms and 111 ms).

Fable's findings 2–8. Fixes go in as separate commits on top of this; I'll post them here. I'm leaving native/vendor alone (finding 1).

Review fixes are in at eef9409, as separate commits on top of the rebase. Hub CI passed. Locally:

  • check-native.sh --mutations: green. That covers the 200-page check, the strengthened wire gate, 15/15 mutations caught, and swift test (169 tests, 0 failures).
  • Go gate: green.

| Finding | Commit | What changed | |---|---|---| | 2 | 4aeff84 | The update observer exists only while command runs. Applies are no longer encoded again or kept. Linear memory at open drops from 11.4 to 9.5 MiB for the 200-page edited document and from 1.8 to 1.5 MiB at 20 pages (host/examples/session_memory.rs: open, then 3,000 peer updates). Test: applies between commands leave the next command's update, and an undo's, minimal. | | 4–7 | 3fe715a | 4: a whole state stored as a segment counts toward compaction. 5: persisted marks updates by position, not "first n"; a test covers overlapping captures in both orders and a stale capture. 6: command refuses apply. 7: sandboxes import the base, then the tail in envelopes of at most 4 MB. | | 3 | 03b0865 | Segments are numbered from the base's new segmentsFrom. The number is in the name and in the sealed bytes (DRL2). A gap is treated like corruption: the replica is dropped, and the outbox and server restore it. Compaction moves segmentsFrom past what it merged, so leftovers are skipped. Tests: a missing middle segment, and interrupted-compaction leftovers. | | 8 | 0399353 | Wire gate: 19 commands instead of 8 (format, attribute, split, listindent, autoformat and revert, two concurrent sources, undos). They replay in order with Y.equalSnapshots, gc on and off, and three peers per mode get shuffled, duplicated delivery. The delta test covers 4 seeds in the gate; 1..100 locally are green. Your harness is now `tests/convergencefuzz.rs, ignored until the yrs fixes below. | | Rebase notes | 26835dc | The 200-page check now uses the new call sequence: displayedit, 254, two anchors, projectdelta` with one block, a peer change, a source from base plus tail, and compaction. | | Rebase notes | eef9409 | Echo-skip test: crash with the edit only in the outbox, reopen, send with the stream open (the sequence is adopted, no catch-up), reopen offline. The edit is there and the stored sequence is the adopted row. |

Finding 9 is reproducible and is not finding 1. With the fix/yrs-gc-undo-kept vendor diff applied locally, the fuzz still fails on 2 of 150 seeds, deterministically: seed 76 (causal delivery) and seed 113 (shuffled delivery).

  • What fails: after an undo, the editor's delete set lacks two units that every peer has. Projections agree.
  • Cause: the undo re-inserts content into a paragraph a peer has deleted. Item::integrate returns "delete me" for an item whose parent is deleted. The remote path (update.rs:309) honours that. The local paths ignore it: Item::redo (block.rs:409), TransactionMut::create_item (transaction.rs:900) and BlockIter::insert_contents (block_iter.rs:492). So in the editor the item is live inside a deleted parent, while each peer marks it deleted. Yjs's own integrate deletes it in both paths.
  • Not caused by this branch: a state-vector diff would carry the editor's delete set, which lacks the units too, and peers would still mark the item deleted.
  • Fix, applied locally only: delete the block after pushing it when integrate returns true, at all three sites. With that plus the finding 1 diff, seeds 1..200 pass in both modes (150 steps each).
  • Where it is: the combined local patch is /tmp/fable-review-145/redo-into-deleted-parent.patch and /tmp/rt-engine/yrs-integrate-delete.patch. I have not touched native/vendor on this branch; this belongs with the yrs fix. Once it lands I'll rebase, un-ignore the fuzz, and run it across many seeds.

Also seen: phase 1's RealtimeSyncTests.testANewDraftAfterADocumentStartsFromItsOwnCursor failed about once in six runs. It shows "bc" instead of "abc", so one of three quick peer rows is never shown. It fails the same way on main 80d4989 without this branch, so it is pre-existing. It passed in the final gate run.

Phase 1's flaky testANewDraftAfterADocumentStartsFromItsOwnCursor: a bug in the test's fixture server, not in the app. The fix is 0527f4c, a test-only commit; hub CI passed.

  • What the logs show: I ran the test in a loop with logging (8 of 25 runs failed under load). In each failure, the catch-up GET /updates?since=1 returned 18 bytes, which is row 2 only, with Docs-Seq: 3. The client sets its cursor to the header, as the protocol says, so it never asks for row 3: "bc" instead of "abc".
  • Why the header was wrong: SequencedServer (an actor) read document.sequence for the header after awaiting the merge of the rows. The actor is reentrant, so the next peer's commit landed in between.
  • The draft is not involved. The assertion that fails (line 294) runs before the draft is created, so this is not a lost first keystroke.
  • Users cannot hit this. The real server takes Docs-Seq from the rows it is sending, never from a second read (handlers.go updatesGet, which documents exactly this loss). So production cannot claim a row it did not send.
  • The fix: both fixture servers now take the header from the rows they actually send, or from the sequence read before a snapshot is awaited. That is SequencedServer in RealtimeSyncTests and IntegratingServer in OfflineDurabilityTests, which had the same pattern. A POST now answers with the sequence its own commit assigned.
  • Result: 0 failures in 80 runs. swift test: 160 tests, 0 failures.
  • For main: the commit only touches test fixtures, so it can be cherry-picked onto main on its own.

Findings 1 and 9 are fixed on branch fix/yrs-gc-undo-kept (discussion #147). It contains four vendored-yrs patches, a recovery path for stored snapshots that do not integrate whole, and the fuzz/wire tests. The whole engine op is new in native/crdt/src/lib.rs. With these patches, convergence_fuzz.rs at eef9409 passes seeds 1..500 in both modes, so it can be un-ignored once #147 lands. Seeds 76 and 113 needed only the redo half of the integrate fix. A further bug (redo origins, also present in Yjs 13.6.27) showed up at seed 98 of my fuzz; details are in #147.

Rebased onto main 0819fa1 (the yrs fixes and #147). Branch head is now d5e047a, force-pushed; hub CI passed.

How the conflicts were resolved

  • Editor::command: I kept this branch's per-command transaction updates and dropped main's encode_diff_v1 line. A transaction's update is written from the block store, so nothing the replica parks rides on a command. damaged_snapshots.rs passes, including an_edit_on_a_damaged_replica_does_not_carry_what_it_parks. Main's is_whole, parked, projection_of and the dispatch ops are kept.
  • Parking API: main's API is ported to the new CRDTReplica (isWhole, parked, accept, hasUnacceptedParking, parking(within:), settleAfterCatchingUpFromStart). The rebuild resets the delta base and moves the version, so sources refresh.
  • refresh: main's backoff and settleParking are kept, then publish, then persist.
  • Headless send: when there is no base, the first record accepts the server's parking, as on main. When there is a base, the send appends a segment.
  • Reopen: parking is checked after the base and the segments are loaded.
  • Gate and mutations: main's gc_undo_kept wire gate and its five vendor mutations sit alongside this branch's update-wire gate.

New commit d5e047a: #147's self-healing replicas on segment storage

  • On main, every persist wrote the whole merged state, so healing rewrote the base for free. Here a persist appends a segment, which cannot replace a damaged base.
  • So the replica now counts settlements: a rebuild after catching up from the start, or a catch-up that integrated what an unsettled replica parked. The next persist then calls DocsReplicaCache.replace. That folds the stored base, every segment and the healed state into a new base carrying the accepted parking. Folding the damaged base in drops the duplicate, as main's commit merge did. The I1a check runs again with no suspension before the write.
  • Compaction now keeps the base's accepted parking; before, it dropped it.
  • Result: testRealDamagedSnapshotsHealWithOneDownload passes for all 29 fixtures, with one download each and a clean base on its own. Every other #147 test passes too. There is a new segment test for parking through compaction and replace.

Convergence fuzz: un-ignored. Seeds 1..500 pass in both delivery modes (150 steps each, about 150,000 commands). Seeds 76 and 113 pass; finding 9 is gone with main's yrs fixes. The gate runs seeds 1..6.

Gates on d5e047a

  • check-native.sh --mutations: green. That includes the 200-page check, the update-wire, rule and gcundokept wire gates, the convergence fuzz and main's undo fuzz, and all 20 of 20 mutations caught.
  • swift test: 169 tests, 0 failures.
  • Go gate: green.

Headline numbers. Main 0819fa1 → this branch, release, production fuel, run back to back.

| | p10 | p20 | p50 | p200 | p200h | |---|---:|---:|---:|---:|---:| | command(display_edit) ms | 42.9 → 1.06 | 85.3 → 1.48 | 212.3 → 2.76 | 873 → 8.9 | 954 → 9.1 | | presentation (reused source) ms | 59.5 → 3.77 | 118.4 → 3.92 | 293.4 → 4.83 | 1,214 → 14.9 | 1,282 → 15.9 | | bytes per typed character | 21 → 21 | 22 → 22 | 22 → 22 | 22 → 22 | 11,817 → 22 | | remote apply ms | 18.0 → 0.22 | 35.6 → 0.20 | 87.2 → 0.22 | 351 → 0.22 | 392 → 0.27 | | presentation after a remote change ms | 70.0 → 7.4 | 131.7 → 10.9 | 317 → 21.3 | 1,266 → 76.5 | 1,458 → 199 | | replica persist per keystroke (sealed disk) ms | 51 → 2.3 | 93 → 2.2 | 223 → 2.2 | 843 → 2.2 | 1,091 → 2.2 | | peer change visible, end to end, median ms | 253 → 42 | 475 → 62 | 1,223 → 126 | 5,091 → 811 | | | burst of 10 visible ms | 674 → 150 | 1,546 → 235 | 3,645 → 623 | 15,315 → 2,135 | |

Ready for the delta review.

Final delta review of perf/native-realtime-engine at d5e047a against main 0819fa1, by Claude Fable (model claude-fable-5-2), review-only session.

Verdict: APPROVE

Nothing blocks the merge. I could not make the branch lose, duplicate or diverge data, including with a kill at every store operation of the new replace. The five findings below are all LOW or NIT and can follow the merge.

What I ran

All in my own detached worktrees at d5e047a, now removed with their build output. Temporary tests are in /tmp/fable-review-145c/; nothing was committed.

  • check-native.sh --mutations (Rust 1.98.0): green. swift test: 169 tests, 4 skipped, 0 failures. 20 of 20 mutations caught.
  • Convergence fuzz on new seeds: 501..620 × 150 steps, both delivery modes: green.
  • The 29 damaged pairs through the branch flow: - Kill at every store operation of the healing persist (FableReplaceReviewTests.swift): damaged base, a local edit in a segment and the outbox, catch-up from the start, rebuild, a second edit in the outbox only, then a crash before operation 0, 1, 2 … of persist. 290 boundaries across the 29 pairs. Every reopen showed exactly the uncrashed text. 203 reopened still unsettled and healed on the second pass; 87 had the new base, with only the server's parking and sequence 5. - Through DocsModel: type straight after open, settle, type again, stop, then reopen offline as a new process. 29 of 29: one download, both edits on the server and in the stored replica, the base alone parks nothing unaccepted, and the offline reopen is settled. - A source made before the rebuild: its command's update leaves the server's parked set unchanged and both sides show the same text, 29 of 29. - My #147 re-review harness (zz_rereview.rs) on this engine: the server parks the damage in 0 of 29.
  • Concurrent writers: an append from the same cache and one from a second cache on the same store, both made while replace and a compaction were suspended in their merges. Nothing was lost; sequence and parking were right.
  • Mutations by hand: two in the engine, three vendored-yrs reverts against the convergence gate, and five in the Swift heal path (results in findings 1 and 2).

Your four questions

(1) Fixes for my findings 2–8: all hold.

  • 2: the update observer exists only inside Editor::command. 254/255 applies are neither re-encoded nor kept.
  • 3: segments are numbered from the base's segmentsFrom, with the number in the name and in the sealed bytes; a gap drops the replica. A lost last segment cannot be seen, and does not need to be: it equals a crash before that append. Every earlier segment's sequence is below the server sequence of anything the lost one held, so the next catch-up fetches it again, and unsent edits are in the outbox.
  • 4–7: as described. persisted marks by position and epoch; command refuses apply; the tail imports in pieces of at most 4 MB.
  • 8: the wire gate and the multi-seed delta test ran green in the gate.

(2) Conflict resolution with #147: sound.

  • Parked structs cannot ride on a command's update. The update is yrs's TransactionMut::encode_update (write_blocks_from(before_state) plus the transaction's delete set), read from the block store. Only encode_state_as_update and encode_diff merge the pending set. No command path calls apply_update, so a command never retries the parked set either.
  • Rebuild: settleAfterCatchingUpFromStart clears the cached projection and moves the version, so no source is reused. An old source can still write (tested above).
  • refresh: backoff, settleParking, publish, persist, in that order. Publishing before persisting is safe: the server holds the rows, and the sequence is stored with the state.
  • Headless send: with a base it appends the sent update in the same main-actor turn as posted; without one it stores the server's state with the server's parking. Both are as on main.
  • Reopen: parking is checked after the base and the segments, and before the outbox replay.

(3) d5e047a, replace: crash-safe, and it cannot drop a local edit.

  • Kill at every step: the base is one atomic write. Before it, the old base and segments stand and the next open heals again (one more download). After it, leftover segments are below segmentsFrom and skipped. BlobStore.list is sorted and removal goes in ascending order, so leftovers are always the top of the range and the next segment number stays right.
  • Concurrent appends and other windows: a segment appended during the merge is numbered at or after the new segmentsFrom and is kept. A concurrent base write is detected by the re-read and retried. Two windows share one cache per account.
  • Unsent and unacked edits: the new base is the union of the old base, every segment and the candidate, so nothing stored can leave it. The I1a check runs with no suspension before the write (DocsReplicaCache.swift:211).
  • Compaction keeps the base's accepted parking.

(4) Gate seeds 1..6: adequate.

  • They guard the branch's own logic. Returning only a command's last transaction fails at seed 1 step 9; not recording touched blocks fails at seed 1 step 0; reverting the keep-flag patch fails at seed 3.
  • They do not guard the redo patches: with the redo delete reverted, 1..6 pass and 76 (causal) and 113 (shuffled) fail; with the redo origins reverted, 1..6 pass. gc_undo_kept_fuzz's gate seeds and the directed tests cover those, so the gate as a whole is not blind.

Findings

1. LOW, test gap: the new replace path has no crash or concurrency test, and its I1a re-check is unguarded. DocsReplicaCache.swift:191-217.

  • Removing guard valid() else { return .refused } at :211 passes all 169 tests.
  • The code is right. FableReplaceReviewTests.swift in /tmp/fable-review-145c/ has the crash-boundary and append-during-replace tests and can be adopted. A replace-path variant of testWriterBetweenCommandAndEnqueueCannotPersistTheCommand would cover the guard.

2. LOW, gate: add seeds 76 (causal) and 113 (shuffled), and mutation cases for the new engine code. convergence_fuzz.rs:148, check-mutations.py.

  • The two seeds cost about 7 s each in the debug gate and make this fuzz guard the redo delete on its own.
  • check-mutations.py has no case for the transaction merge in Editor::command or for the touched set. Both are caught today (see question 4); a case each would keep it so.

3. NIT: a settlement stored through commit does not update the base's parking. DocsPersistence.swift:96.

  • This is from reading; I did not reproduce it.
  • When the persistence believes there is no base (hasBase false) but a headless send has written one, a settled capture goes to commit, which appends it as a segment. persisted then marks the settlement stored.
  • Cost: one more full download at a later open. Nothing is lost.
  • Fix: call cache.replace whenever changes.replace != nil; it already falls back to commit when no base is stored.

4. NIT: a failed segment removal after the new base is written fails the whole persist. DocsReplicaCache.swift:216, DocsModel.swift:165.

  • The throw reaches persistReplica, which pauses input with "cannot save on device" and schedules no retry, although the base was stored. A corrupt segment found during the fold does the same.
  • Compaction already treats this as upkeep (try?). The removals in fold could be the same: leftovers below segmentsFrom are skipped on load and removed by the next fold.

5. NIT: nextSegment prefers its in-memory number to the base's segmentsFrom. DocsReplicaCache.swift:107-109.

  • With one cache per store, which is what the app has, this is correct.
  • A second cache with a stale number, and no segments on disk, would write a segment below segmentsFrom, and load would skip it silently. From reading; only DocsPersistence's default cache in tests can make one. Worth a comment on the single-cache assumption.

Two surviving mutants that are not findings

Dropping version &+= 1 or presented = nil from the rebuild passes every test, but both are equivalent in practice. The catch-up apply before every settlement already moves the version, and a rebuilt sandbox reports a delta base of 0, which Swift rejects and replaces with a whole projection.

Landed on main (squash) after Fable's APPROVE at d5e047a and green hub CI. The five low notes are tasks on this branch. Next: a Docs native release (0.1.10) from main.