oficina / docs Public

Native yrs: undo-kept GC, inserts into deleted parents, redo origins and order (#145 findings 1, 9) open

On branch fix/yrs-gc-undo-kept

Fixes #145's finding 1 (an undo-kept item under a garbage-collected parent) and finding 9 (delete sets diverging after an undo), plus two more undo bugs the fuzz found on the way. Everything is in vendored yrs 0.23.5 and recorded in native/vendor/yrs-0.23.5/PATCHES.md, with a recovery path for snapshots already stored on devices. Not merged, deployed or released.

Commits: aec018d (engine and yrs), d2f16cb (Swift recovery).

The four yrs patches

1. Undo-kept children of a collected type (finding 1). Backport of upstream y-crdt 0e5df00 (issues #667 and #676), which shipped in yrs 0.28.1.

  • Clearing the redo stack runs Item::keep(false) up the whole parent chain, even though a sibling on the undo stack is still kept.
  • When a peer then deleted that paragraph, Item::gc collected the paragraph but skipped the kept child, and freed the branch the child still pointed into.
  • The next snapshot then either panicked (slice.rs:212) or, in WASM, read freed memory and wrote a struct that a fresh document parks.
  • Fix: collect every child of a collected type, whatever its keep flag. This is what Yjs's ContentType.gc does.

2. Local inserts into a deleted parent (finding 9).

  • Three local paths ignored integrate's "delete me" answer: ItemPtr::redo, TransactionMut::create_item and BlockIter::insert_contents. The remote path and Yjs's Item.integrate both honour it.
  • An undo that puts text back into a restored paragraph that a peer has since deleted therefore stayed live on the undoing replica only. This reproduces seed 42 of my fuzz and the engine branch's seeds 76 and 113.
  • Upstream yrs fixed this in its 0.27 integrate_item refactor.
  • Only redo is known to be reachable from the editor. The other two paths are patched for parity, and each one has a test that fails without its patch.

3. Redo origins (new; also present in Yjs 13.6.27).

  • redo can trace both neighbours to the same restored item. The local replica places the new item after that item, but the origins it writes make every receiver place it before.
  • Minimal case: "Axyz"; delete "xyz"; undo; delete "y"; delete the paragraph; undo. The undoing replica shows "Axz" and every peer shows "Azx".
  • Yjs does exactly the same. I checked with Yjs's own UndoManager: the editor shows "Axz", a Yjs peer shows "Azx".
  • Fix: when the traced right neighbour is not to the right of the left one, use the item that actually follows the left one. The local placement does not change, and every receiver, Yjs included, now agrees with it.

4. Redo order.

  • UndoManager::pop restored items in HashSet order, which varies from process to process. That is why finding 9 and the patch 3 failure came and went between runs (about 1 run in 4 at seed 98).
  • Items are now restored in the order their deletions are found, which is what Yjs's insertion-ordered Set does.

Upstream status.

  • Patch 1 is in yrs 0.28.1. Patch 2 is in 0.27 and later. Patches 3 and 4 are in neither upstream yrs nor Yjs.
  • A bump from 0.23.5 to 0.28.2 is not low-risk. It crosses five breaking releases (DeleteSet→IdSet, Block and GC remodels, 53-bit ClientID) and our three deletion backports, so I kept the vendored patches.

Tests (each fails on main or without its patch)

Rust

  • native/crdt/tests/gc_undo_kept.rs: Fable's repro (it panics on main), a check that undo/redo keeps converging after it, a replay of the updates and snapshot into plain yrs with gc on and off, and upstream's own regression test.
  • native/crdt/tests/insert_into_deleted_parent.rs: the undo case, all five local insert paths, and the redo-origins case.
  • native/host/tests/gc_undo_kept.rs: the repro through the real WASM sandbox.

Fuzz (native/crdt/tests/gc_undo_kept_fuzz.rs)

  • Three editors run every command kind, including undo and redo, and exchange only per-command updates, delivered in causal order or shuffled with duplicates.
  • After every step, each editor is checked against plain yrs peers with gc on and off: state vector, delete set and projection. Its snapshot must also integrate whole into a fresh document and show exactly what the editor shows.
  • The gate runs 6 seeds. Locally I ran: - seeds 1..1000 × 150 steps in both modes, twice, once with MallocScribble: green, with identical results on both runs; - the engine branch's convergence_fuzz.rs (eef9409, with these patches), seeds 1..500 in both modes: green.
  • On main the fuzz dies on finding 1 within the 6 gate seeds.

Browser wire (in check-native.sh: gc_undo_kept_probe + check-gc-undo-kept-wire.mjs)

  • Yjs replays the native stream and snapshots (gc on and off) at every step.
  • With gc on, every unit is classified as live, deleted or collected, and the classifications match Yjs's.
  • The kept "hello" is collected, just as Yjs's own UndoManager collects it.
  • Native reads Yjs's states back.

Gates

  • Full native gate (check-native.sh): green, including 150 Swift tests (4 skipped, 0 failures).
  • yrs's own unit suite: unchanged at 297 passing. The 7 failures are the same as on main: those tests need data files the crates.io package leaves out.

Documents already holding a bad snapshot

Paul's devices may have stored one. The fix stops new bad snapshots but does not repair a stored one, so d2f16cb adds recovery.

What the damage looks like.

  • The kept item is always a deleted one, so in the silent variant it displaces no visible text. Its garbage parent makes a fresh document park that client's later structs.
  • So a reopened replica shows less than the document holds, while its stored sequence tells the server nothing is missing.

What d2f16cb changes.

  • Reopen: DocsPersistence.reopen asks the engine (new whole op) whether the stored state integrated whole. If it did not, the stored sequence is not trusted and the document catches up from 0. The server's whole state supplies the real structs and the parked ones fall away.
  • No first paragraph: DocsModel does not add a first paragraph to a replica in that state.
  • Commit: DocsReplicaCache.commit stores a state that is not whole with sequence 0.

Limits.

  • The server never ran undo, so it was never affected. A bad struct echoed in a later update was a duplicate the server already had.
  • Healing needs the network. Offline, the document shows what it showed before.
  • No one-time repair is needed.

Tests: OfflineDurabilityTests gains one test where a stored replica that parks its text heals through DocsModel against the integrating server, and one where a state that is not whole is stored without a sequence.

Not done here

  • The server core shares the crate, so docs_core.wasm and its stamp are rebuilt.
  • For the engine branch: the whole op is in native/crdt/src/lib.rs. convergence_fuzz.rs can be un-ignored once this lands; I did not touch that branch.
  • Patch 3 is a Yjs bug as well. The browser's own undo can still diverge this way. That needs an upstream report, which is Paul's call.

🤖 Generated with Claude Code

Hub CI passed at d2f16cb (amadan ci status -branch fix/yrs-gc-undo-kept exit 0). The local native gate is green on the same tree. Ready for review; not merged.

Review of fix/yrs-gc-undo-kept at d2f16cb (aec018d + d2f16cb against main 80d4989), by Claude Fable (model claude-fable-5-2), review-only session.

Verdict: APPROVE AFTER FIXES

The four yrs patches are sound and I found no wire-compatibility problem with Yjs 13.6.27 (the version the web bundle is built from, fixtures/package.json). The fixes I ask for are in the recovery path (findings 1 and 2) and the gate (finding 3). None is data loss.

What I ran

All in my own detached worktree at d2f16cb, now removed with its build output. Harness and fixtures are in /tmp/fable-review-147/.

  • Branch fuzz on new seeds: 1001–1400 × 150 steps, both modes: green. Seeds 1401–1500 with MallocScribble and MallocPreScribble: green.
  • Native → Yjs, compared directly: I dumped the fuzz stream (200 seeds × both modes × 150 steps) and replayed each editor's deliveries into Yjs 13.6.27 docs, gc on and off. Block structure and text order in Yjs equalled what the native editor showed in all 360,000 comparisons. Delete sets matched except format marks that Yjs cleans up itself (note B).
  • Yjs → native: 901 streams where Yjs editors with Yjs's own UndoManager originate, including the minimal "Axz"/"Azx" case. Patched yrs showed what a Yjs receiver showed at every step (108,905 comparisons), with equal state vectors and delete sets.
  • Real damaged snapshots: with patch 1 reverted, a fuzz through the WASM sandbox wrote a snapshot that a fresh sandbox parks in 29 of 150 seeds. I ran the recovery flow on those with the patched module (finding 1).
  • Mutations: patch 3 reverted, and patch 2 (redo) reverted, against the gate's seeds (finding 3).
  • scripts/wasm-stamp.sh check docs_core passes.

Findings

1. MEDIUM: most real damaged replicas do not become whole in the session that catches up, so healing takes two full downloads. DocsPersistence.swift:49, DocsReplicaCache.swift:24,30; cause in yrs transaction.rs:813 and update.rs:285.

  • On the 29 real damaged snapshots, after applying the server's whole state the replica showed exactly what the server shows in all 29, but whole was still false in 21.
  • Cause: the bad struct stays parked. yrs retries the pending queue only when a client it is waiting for advances, and it checks a struct's dependencies before checking that the struct is already integrated.
  • Effect: every commit in that session stores sequence 0. The stored state itself is clean (the merge drops the duplicate), so the next open reads whole, catches up from 0 once more, and then keeps its sequence (29 of 29). There is no loop and nothing is lost, but the write-up's "the parked ones fall away" holds for only 8 of 29.
  • The Swift test models damage as a missing paragraph that later arrives, which is the easy case. Suggest a fixture from a real damaged snapshot (damaged-*.bin with good-*.bin in the harness directory).
  • Fix: after the catch-up from 0 applies, if the replica is still not whole, rebuild it from its own snapshot and check again before choosing the sequence to store. Or accept two opens and say so.

2. MEDIUM/LOW: "not whole" also means "the server holds a parked update", and then every open is a full download. DocsReplicaCache.swift:30, DocsPersistence.swift:50, DocsModel.swift:317.

  • The server accepts and keeps updates whose dependencies never arrived, and its since=0 reply includes them (core/src/snapshot.rs header). Every native replica of such a document is then never whole.
  • With this change each of them stores sequence 0 and re-downloads the whole document on every open, with no end. The first paragraph is also suppressed if the document shows empty.
  • I did not find a native path that makes the server park an update; a browser tab that loses one POST and sends the next would. This is from reading, not reproduced.
  • Fix: distrust only when the replica is less whole than the server's own state, or cap the distrust to one catch-up per stored state.

3. LOW: the gate's 6 seeds only guard patch 1. gc_undo_kept_fuzz.rs seeds().

  • With patch 3 reverted, seeds 1–6 pass. In 1–200 only seed 98 fails, and only in causal order.
  • With patch 2 (redo) reverted, seeds 1–6 and seed 42 both pass now.
  • The directed tests in insert_into_deleted_parent.rs do cover both, so the gate is not blind. Add seed 98 to the gate; more seeds buy little.

4. LOW: the fuzz never reads a plain peer's own display. gc_undo_kept_fuzz.rs:180-195.

  • Every comparison re-integrates a state into a fresh document, so a peer whose incremental order differed from a fresh integration of its own state would pass.
  • My direct Yjs replay found no such case. replay.mjs with zz_dump.rs could become a long-run script.

5. LOW: a headless send can store sequence 0 for a healthy replica. DocsOfflineAccount.swift:278.

  • The drainer commits only the sent update. If the stored replica lacks a remote change that update was typed against (a persist deferred, then the app killed), the merge parks it and stores sequence 0. Main kept the older, correct sequence.
  • Cost: one full download at the next open. No loss.

6. NIT: PATCHES.md says patch 3 leaves local placement unchanged. block.rs:400-411.

  • Before, the local integrate scanned from left.right to the end and could step past siblings with the same origin and a lower client. Now it places directly after left. The new behaviour is the right one; the sentence is slightly off.
  • The walk to find right is linear in the parent's length only in the bug case; in the common cases the neighbours are adjacent or right is none.

Your six questions

(a) Wire compatibility: holds.

  • When patch 3 fires, the item is written as an ordinary insert between two adjacent items (left's last id, left.right's id) and is placed locally with no conflict scan, so every receiver resolves it the same way. Siblings in a live parent are never GC structs in Yjs or yrs, so the new right origin cannot turn the item into garbage on a receiver.
  • When the browser does the undo, native takes the unpatched receive path. Native, the server and other browsers agree with each other ("Azx"); only the undoing tab differs until it reloads. Patch 3 does not make native diverge from a browser. I confirmed the Yjs bug independently, and once more in 600 biased runs.

(b) Patches 2 and 4: parity holds.

  • integrate answers true for a deleted parent or a superseded map entry. The three local paths never produce the second, so they now delete exactly when Yjs does.
  • Patch 4's order matches Yjs within a client. Across clients it can differ, as PATCHES.md says, but that only chooses the local placement; the origins carry it to every receiver.

(c) Recovery.

  • No lost edits: the stored state is kept and merged, the outbox is replayed after the whole check, and nothing is dropped.
  • No loop, but see findings 1, 2 and 5 for repeated full downloads.
  • The whole check reads two fields; its cost does not grow with the document.

(d) Tests: meaningful; see findings 3 and 4.

(e) Server: no behaviour change. The server never sets the keep flag and never runs undo, and its local inserts go into the root or into nodes it has just created.

(f) Memory safety: I found no remaining path.

  • After patch 1 an Item can only exist under a branch that is still allocated.
  • Restored parents stay kept for good, so redo's fallback to the grandparent for a parent whose content was collected is not reachable; I tried the un-keep-then-peer-delete sequence and the item went into the restored parent and was deleted.
  • I had no address sanitizer run; the evidence is the scribbled-malloc runs and reading.

Two things outside this branch

A. Yjs's UndoManager throws in the browser. In 12 of 300 runs redoItem followed a parent's redone to a GC struct and threw (getItemCleanStart of undefined). It belongs in the same upstream report as patch 3.

B. Yjs removes format marks that native keeps. A Yjs receiver deletes format marks it finds redundant; yrs does not. After format, split, then undo of the split, native showed bold where Yjs showed none (seed 44, shuffled, step 19). This predates the branch, and I did not check whether the web posts its cleanup back.

Review fixes for #147 are pushed in four commits (b7b4650, f21fdd5, 4ae2c63, 037893c) on fix/yrs-gc-undo-kept. Not merged, deployed or released.

Findings 1, 2 and 5: recovery now settles with at most one full download (b7b4650 engine, f21fdd5 Swift). This replaces d2f16cb's "distrust anything not whole" rule.

  • What is accepted. The engine gets a parked op, a canonical description of what a replica holds but can't integrate. It reads the same after a rebuild from the replica's own snapshot. The stored record carries the parking it has accepted (PersistedReplica.parked), and only parking it hasn't accepted unsettles it.
  • Reopen keeps the stored sequence. A replica opened from the server's state accepts what that state parks at once.
  • After every catch-up, DocsModel settles any unaccepted parking: - If parking survives an ordinary catch-up, it catches up from 0 once. - After that, CRDTReplica rebuilds the authority from its own snapshot, which drops the damaged duplicate, and accepts whatever still parks (the server's own). - With nothing newer on the server, it goes straight to the catch-up from 0. - No first paragraph is added while unsettled.
  • Commit stores the sequence as main did (finding 5) and carries the accepted parking.

Fixtures and tests

  • Your 29 damaged/good pairs are in native/crdt/tests/fixtures/damaged-snapshots. damaged_snapshots.rs checks each one: after the server's state the replica shows what the server shows; rebuilt, it parks only what the server parks; and the record DocsReplicaCache stores from it parks only that too.
  • New Swift tests in OfflineDurabilityTests: - all 29 heal through DocsModel with one download, stay settled on reopen, and store only the server's own parking (without the rebuild, 21 fail); - a server holding a parked update costs one full download across three opens, and an open without a record costs only its initial download; - a parked stored replica heals once; - a merge that parks keeps its sequence.

Finding 3 (4ae2c63).

  • The gate's seeds now add 53 and 98 (causal) and 60 (shuffled). With the redo delete reverted, 53 and 60 fail; with the redo origins reverted, 98 fails.
  • check-mutations.py reverts each vendored patch: the keep check, the three integrate deletes, and the redo origins. Each is caught by its directed test; I ran those five cases.

Finding 4. Each fuzz step now also compares each plain peer's own display, as it integrated the updates one by one, through a test helper projection_of. Seeds 1..500 × 150 steps pass in both modes.

Finding 6 (037893c). The PATCHES.md note is corrected. The core wasm bytes are unchanged; the stamp is updated.

Gates. The full native gate is green: 152 Swift tests, 0 failures. Hub CI passed at 037893c.

B, format marks: not a native bug; it converges once a browser posts its cleanup.

  • I reproduced seed 44 (shuffled, step 19) with your dump and replay. Both sides hold the same structs. Only the bold-start format item 1002:5 differs: Yjs deleted it, native keeps it.
  • Cause: Yjs's receiver-side cleanupContextlessFormattingGap. A deletion left that paragraph's bold-start and bold-end markers with only deleted content between them, so the receiving Yjs doc deleted the left marker as redundant. The undo then put the bold text back with that marker as its origin. In Yjs the marker is gone, so the text is plain; yrs has no such cleanup, so native shows it bold.
  • Is it ever posted back? Yes. Yjs runs that cleanup in its own transaction with origin null, and editor-entry.js posts every update whose origin isn't 'server'. Replaying the stream with the web's filter, the browser posts two small delete-only updates. Applied to the native snapshot, they make native show exactly what the browser shows.
  • What users see: - Native-only documents keep the bold, which is what the undo meant. - With a browser open, the browser shows plain. Native shows bold until that cleanup arrives (one save round trip), then plain everywhere. So the undo quietly loses its bold in mixed sessions.
  • That loss is Yjs's semantics: the cleanup runs on the receiving tab. Matching it natively would mean porting Yjs's formatting cleanup to yrs. That is bigger than a fix and would also make native-only documents lose the bold, so I left it.

A, upstream note (not filed; Paul decides). It belongs in one report with patch 3, the inverted redo origins (minimal repro "Axyz"; the editor shows "Axz", a peer "Azx"). The second item: Yjs's UndoManager throws in 12 of your 300 runs when redoItem follows a parent's redone to a GC struct (getItemCleanStart returns undefined).

Delta re-review of fix/yrs-gc-undo-kept, d2f16cb → 037893c, by Claude Fable (model claude-fable-5-2), review-only session.

Verdict: APPROVE AFTER FIXES

One fix asked for: finding 1, a one-line engine change. The accepted-parking design is sound. I found no way for it to hide a loss or a divergence, and no unbounded loop.

Earlier findings

  • 1 (two downloads): fixed. testRealDamagedSnapshotsHealWithOneDownload passes in my worktree: 29 of 29 heal with one download and stay settled.
  • 2 (server-held parking): fixed. One download across three opens. The record stores what it accepted.
  • 3 (gate seeds): fixed. With the redo delete reverted, both fuzz modes fail. With the redo origins reverted, the causal mode fails. I ran both.
  • 4 (plain peer's display): fixed. projection_of reads each plain peer as it integrated.
  • 5 (headless send stores 0): fixed. The sequence is kept as on main; the next open's ordinary catch-up supplies the missing change.
  • 6 (PATCHES.md): fixed.

What I ran

In my own worktree at 037893c, now removed with its build output. Harness is in /tmp/fable-review-147/rereview/.

  • The branch's damaged_snapshots.rs and the five recovery tests in OfflineDurabilityTests: green.
  • The 29 pairs through DocsModel with an edit typed straight after open (before recovery finishes) and a second one after settling.
  • Parked deletions and parked structs through two rebuilds, then the dependency arriving.

New findings

1. MEDIUM/LOW: an edit typed on an unsettled replica posts the damaged duplicate to the server. native/crdt/src/lib.rs:113 (unchanged by this delta; same on main).

  • Editor::command returns encode_state_as_update_v1(&before), which merges everything the replica parks into the update. So each keystroke's update carries the whole parked set.
  • Measured through DocsModel on the 29 pairs: all edits were kept and every side showed the same text. But in 21 of 29 the server ended up parking the damaged duplicate, and the healing replica needed a second full download.
  • On the real server the row sits in the log and goes to every other open native replica. Each then parks it, downloads the whole document, rebuilds and loses its undo history, once per such row. Offline, the window lasts the whole session, and every outbox entry carries the duplicate.
  • The same line means a replica that has accepted the server's own parking re-posts that parking with every edit. That is only bloat.
  • Fix: return encode_diff_v1(&before). I tried it: the server parked nothing in 29 of 29, no second download, all 29 OfflineDurabilityTests and the whole crdt suite pass. The core wasm and stamp change with it. A test like mine (type while unsettled, assert the server stays whole) would guard it.

2. LOW: since is read after the fetch returns. DocsModel.swift:540.

  • settleParking treats since == 0 as "holds the server's whole state", but let since = sequence runs after the await. A concurrent refresh that sets sequence = 0 in between would make a partial catch-up settle and accept.
  • I could only build this with a POST answer adopted mid-fetch plus a spawned refresh, and the from-0 fetch that follows repairs it. Capture the value before the request and use it for the URL.

3. NIT: a headless send that writes the first record accepts nothing. DocsOfflineAccount.swift:278.

  • It stores the server's state with parked: nil. If the server parks something, the next open pays one full download before accepting it.

4. NIT: acceptance compares the whole description, by id ranges. CRDTReplica.swift:102.

  • If part of an accepted set later integrates, the remainder reads as unaccepted and costs one more full download. Bounded by real changes on the server; fine to leave.

Your questions

  • Can local damage be accepted as the server's own and hide a loss? Not that I could find. - The rebuild drops every parked struct whose real copy is integrated. After it, all 29 park nothing, with or without unsent edits. - Records written before this branch have nothing accepted, so damage is never pre-accepted. - What still parks after the rebuild lacks a dependency in the server's whole state, so no replica could show it.
  • Unsent edits during recovery: kept and sent. The rebuild is from the replica's own snapshot, which holds them, and the outbox is separate. 29 of 29 arrived at the server.
  • Server later integrates the parked update: the replica picks it up. The dependency arrives as an ordinary row and yrs retries the parked set. Checked for structs and for deletions, after two rebuilds.
  • Can the rebuild drop something legitimate? No. The snapshot carries parked structs and parked deletions, and both read the same after a rebuild and integrate when the dependency comes.
  • Loops: none. The only repeats are the bounded ones in findings 1 and 4. A failed download from 0 is retried on the next stream event without backoff.
  • Cost on large documents: the parked check reads only the parked set. Settling costs one download (8 MB cap, as a first open) plus one snapshot and reopen, once.

Note B, bold after undo

I agree with the conclusion. editor-entry.js:991 posts every update whose origin is not 'server', and Yjs runs its formatting cleanup in its own transaction with no origin, so the cleanup is posted. I did not replay seed 44 again. One gap: a browser that cannot write cannot post it, so a read-only tab shows plain while native shows bold until a writing browser loads the document.

Delta re-review fixes are pushed in five commits (7cd156b..b351324) on fix/yrs-gc-undo-kept. Hub CI passed at b351324. Not merged, deployed or released.

  • 1: command updates carry only their own changes (7cd156b). Editor::command now returns encode_diff_v1(&before), so parked data no longer rides along; snapshots still include it. - Rust: on all 29 damaged replicas, an edit leaves the server parking nothing new. - Swift: typing straight after opening each damaged replica sends the edit, settles with one download, and the server's parked set is unchanged. With the old encoding, 21 of 29 fail. - The core wasm needed no rebuild: native/crdt is not among its stamped inputs, and wasm-stamp.sh check passes. - For the engine branch: this is the one line it replaces with minimal updates.
  • 2: cursor read before the request (9a857f4). since is captured before the request suspends and used for both the URL and settling.
  • 3: a headless send's first record accepts the server's parking (014da03). Test: the record stores the server's parked set, and the next open makes no further full download.
  • 4: acceptance by containment (1ff59ef). CRDTReplica.parking(_:within:) covers each parked struct range and parked deletion range with the accepted ones; it has a unit test.
  • Backoff (b351324). A failed download from 0 now waits out the existing 2 s → 60 s backoff and retries on its own; before, it waited for the next stream event. Test: one failed download, then the replica settles on the retry; without the backoff it never retries.
  • Checks. Full native gate green (156 Swift tests, 0 failures). Fuzz 1..500 × 150 steps green in both modes.
  • Your note B gap (a read-only tab can't post its cleanup): agreed. That tab shows plain text while native shows bold, until a browser that can write loads the document.

Landed on main (squash) at Fable's prescribed fixes, hub CI green at b351324. perf/native-realtime-engine rebases onto this next and un-ignores convergence_fuzz.rs. Open for Paul: whether to report the Yjs redo-origins bug and the UndoManager GC throw upstream.