oficina / docs Public

Docs native: fix four vendored-yrs undo bugs (#145 findings 1 and 9)

All in native/vendor/yrs-0.23.5, recorded in its PATCHES.md:

- Undo-kept children of a collected type (finding 1; backport of
  y-crdt 0e5df00, released in yrs 0.28.1). Clearing the redo stack
  un-kept a paragraph while a word on the undo stack stayed kept; when a
  peer deleted the paragraph, GC freed its branch and left the word
  pointing into it. The next snapshot panicked, or in WASM read freed
  memory and wrote a struct a fresh document cannot integrate. Children
  of a collected type are now collected whatever their keep flag, as in
  Yjs (ContentType.gc).
- Local inserts into a deleted parent (finding 9). Item::redo,
  TransactionMut::create_item and BlockIter::insert_contents dropped
  integrate's "delete me" for a deleted parent, so an undo into a
  restored paragraph a peer had deleted stayed live here alone. Deleted
  as Yjs's Item.integrate and the remote path do (upstream since 0.27).
- Redo origins. Redo could trace both neighbours to one restored item;
  the item went after it locally but every receiver put it before it.
  Yjs 13.6.27 does the same. Redo now names the item actually after the
  left neighbour as the right one; local placement is unchanged.
- Redo order. Items were restored in HashSet order, which varied from
  process to process; now in the order the deletions are found.

The server core shares the vendored crate: docs_core.wasm and its stamp
are rebuilt. The server never runs undo, so none of this reached it.

Tests: gc_undo_kept.rs (the repro, and upstream's own test),
insert_into_deleted_parent.rs (each fix, each failing without it),
gc_undo_kept_fuzz.rs (three editors with undo, per-command updates
against plain yrs with gc on and off; bounded in the gate), a host test
through the WASM sandbox, and a browser wire check in check-native.sh
(gc_undo_kept_probe + check-gc-undo-kept-wire.mjs: Yjs replays the
native stream and snapshots, collected units match Yjs's, and native
reads Yjs's states back). The engine gets a `whole` op: whether every
struct and deletion it holds is integrated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev aec018db9863b5bdc6130aba9a5b91a6a8b39ff5 parent 80d4989
18 files changed, +883 −17
  • core/Cargo.toml +1 −1
  • internal/core/testdata/docs_core.wasm binary
  • internal/core/testdata/docs_core.wasm.stamp +2 −2
  • native/BUILDING.md +2 −1
  • native/crdt/src/bin/gc_undo_kept_probe.rs +73 −0
  • native/crdt/src/lib.rs +9 −1
  • native/crdt/tests/gc_undo_kept.rs +152 −0
  • native/crdt/tests/gc_undo_kept_fuzz.rs +226 −0
  • native/crdt/tests/insert_into_deleted_parent.rs +154 −0
  • native/host/tests/gc_undo_kept.rs +42 −0
  • native/scripts/check-gc-undo-kept-wire.mjs +106 −0
  • native/scripts/check-native.sh +6 −0
  • native/vendor/yrs-0.23.5/PATCHES.md +47 −3
  • native/vendor/yrs-0.23.5/src/block.rs +34 −2
  • native/vendor/yrs-0.23.5/src/block_iter.rs +7 −1
  • native/vendor/yrs-0.23.5/src/gc.rs +7 −3
  • native/vendor/yrs-0.23.5/src/transaction.rs +7 −1
  • native/vendor/yrs-0.23.5/src/undo.rs +8 −2
diff --git a/core/Cargo.toml b/core/Cargo.toml
index 15587ef..d17192d 100644
--- a/core/Cargo.toml
+++ b/core/Cargo.toml
@@ -31,5 +31,5 @@ wasmparser = "=0.258.0"
# avoid a wasm-bindgen (JS) import on wasm32-unknown-unknown.
[patch.crates-io]
fastrand = { path = "vendor/fastrand-2.5.0" }
-# Shared with the native editor: see its README for the upstream deletion fixes.
+# Shared with the native editor: its patches are listed in native/vendor/yrs-0.23.5/PATCHES.md.
yrs = { path = "../native/vendor/yrs-0.23.5" }
diff --git a/internal/core/testdata/docs_core.wasm b/internal/core/testdata/docs_core.wasm
index b1deebb..a592a10 100755
Binary files a/internal/core/testdata/docs_core.wasm and b/internal/core/testdata/docs_core.wasm differ
diff --git a/internal/core/testdata/docs_core.wasm.stamp b/internal/core/testdata/docs_core.wasm.stamp
index fa62d7a..c6c42f6 100644
--- a/internal/core/testdata/docs_core.wasm.stamp
+++ b/internal/core/testdata/docs_core.wasm.stamp
@@ -1,3 +1,3 @@
# Written by scripts/build-wasm.sh; checked by scripts/wasm-stamp.sh check docs_core.
-inputs c48962fb7dd354989e109e32df2ded0dd48e855ba0b151f4e99b472d1c03dec3
-wasm 733201b2c1ffa64570f20abb04b766d51d0389aa32e5f6ed65fd5074b7120288
+inputs 927a341e996ed5792a621116e535f1e31ed2bae80df310bf5c1a2a61c09ca558
+wasm efc55a06e62779c1863a3887dcb7789adb2615015ab2c65bf1ff964c1ec9cecd
diff --git a/native/BUILDING.md b/native/BUILDING.md
index de5bd2e..b326550 100644
--- a/native/BUILDING.md
+++ b/native/BUILDING.md
@@ -18,7 +18,8 @@ It builds the CRDT WASM, runs Rust editor and bounded-host tests (including
opening and typing in a generated 200-page edited document on the host's
production fuel budget; see `fuel_budget` in `host/src/lib.rs`), checks native
and browser updates in both directions (including every list-rule reversal delta
-and its authoritative snapshot), prepares the Apple XCFramework, and
+and its authoritative snapshot, and the undo-kept garbage-collection repro of
+discussion #145, whose collected units must match Yjs's), prepares the Apple XCFramework, and
runs Swift adapter/actor tests. `--core-only` runs the Rust and wire checks on
Linux. CI invokes this through `.amadan/ci.d/20-native`, alongside the existing
server/web gate. `--mutations` additionally proves representative faulty changes
diff --git a/native/crdt/src/bin/gc_undo_kept_probe.rs b/native/crdt/src/bin/gc_undo_kept_probe.rs
new file mode 100644
index 0000000..bb94981
--- /dev/null
+++ b/native/crdt/src/bin/gc_undo_kept_probe.rs
@@ -0,0 +1,73 @@
+//! Wire fixture for the undo-kept GC fix (oficina/docs #145; tests/gc_undo_kept.rs).
+//! Writes the native update stream of the repro (delete a word, type, undo,
+//! type, a peer deletes the paragraph, then undo and redo) with the editor's
+//! snapshot and projection after each step, for native/scripts/check-gc-undo-kept-wire.mjs
+//! to replay in Yjs. With `--check`, reads the Yjs states that script wrote
+//! back and checks a fresh native editor shows the same as the editor did.
+use docs_native_crdt::Editor;
+use serde_json::{json, Value};
+use std::path::Path;
+
+fn main() {
+ let mut args = std::env::args().skip(1);
+ let directory = args.next().expect("usage: gc_undo_kept_probe DIRECTORY [--check]");
+ let directory = Path::new(&directory);
+ if args.next().as_deref() == Some("--check") { return check(directory); }
+ std::fs::create_dir_all(directory).unwrap();
+ let mut author = Editor::new("gc-undo-kept", 11);
+ author.command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap();
+ author.command(&json!({"op":"display_edit","at":0,"length":0,"text":"aaa\nhello world\nzzz"})).unwrap();
+ let base = author.snapshot();
+ let mut editor = Editor::new("gc-undo-kept", 12);
+ editor.apply(&base).unwrap();
+ let mut peer = Editor::new("gc-undo-kept", 13);
+ peer.apply(&base).unwrap();
+ let mut stream = vec![base];
+ let mut record = |stream: &Vec<Vec<u8>>, editor: &Editor| {
+ let step = stream.len() - 1;
+ std::fs::write(directory.join(format!("{step}.bin")), stream.last().unwrap()).unwrap();
+ std::fs::write(directory.join(format!("{step}.snapshot")), editor.snapshot()).unwrap();
+ std::fs::write(directory.join(format!("{step}.json")), editor.projection()["children"].to_string()).unwrap();
+ };
+ record(&stream, &editor);
+ for command in [
+ json!({"op":"display_edit","at":4,"length":5,"text":""}), // delete "hello"
+ json!({"op":"display_edit","at":6,"length":0,"text":"Q"}),
+ json!({"op":"undo"}),
+ json!({"op":"display_edit","at":0,"length":0,"text":"x"}), // clears the redo stack
+ ] {
+ let update = editor.command(&command).unwrap();
+ peer.apply(&update).unwrap();
+ stream.push(update);
+ record(&stream, &editor);
+ }
+ let remote = peer.command(&json!({"op":"display_edit","at":2,"length":12,"text":""})).unwrap();
+ editor.apply(&remote).unwrap();
+ stream.push(remote);
+ record(&stream, &editor);
+ for op in ["undo", "undo", "undo", "redo", "redo", "redo"] {
+ let update = editor.command(&json!({"op":op})).unwrap();
+ peer.apply(&update).unwrap();
+ stream.push(update);
+ record(&stream, &editor);
+ }
+ assert_eq!(editor.projection()["children"], peer.projection()["children"]);
+ std::fs::write(directory.join("steps"), (stream.len() - 1).to_string()).unwrap();
+}
+
+fn check(directory: &Path) {
+ let steps: usize = std::fs::read_to_string(directory.join("steps")).unwrap().parse().unwrap();
+ let mut checked = 0;
+ for gc in [true, false] {
+ for step in 0..=steps {
+ let state = std::fs::read(directory.join(format!("browser-{gc}-{step}.bin"))).unwrap();
+ let fresh = Editor::new("gc-undo-kept", 99);
+ fresh.apply(&state).unwrap();
+ assert!(fresh.is_whole(), "gc={gc} step={step}: the browser's state does not integrate whole");
+ let expected: Value = serde_json::from_slice(&std::fs::read(directory.join(format!("{step}.json"))).unwrap()).unwrap();
+ assert_eq!(fresh.projection()["children"], expected, "gc={gc} step={step}");
+ checked += 1;
+ }
+ }
+ println!("GC undo-kept wire: {checked} browser states read natively as the editor showed them.");
+}
diff --git a/native/crdt/src/lib.rs b/native/crdt/src/lib.rs
index 351d83a..e4af925 100644
--- a/native/crdt/src/lib.rs
+++ b/native/crdt/src/lib.rs
@@ -1,6 +1,6 @@
//! Native editor CRDT operations. In production this crate runs ONLY inside
//! a fuel/memory-limited WebAssembly interpreter, never as a native decoder.
-//! The server retains its separate ABI; both modules share the reviewed yrs deletion backports.
+//! The server retains its separate ABI; both modules share the vendored yrs and its patches (native/vendor/yrs-0.23.5/PATCHES.md).
mod projection;
mod operations;
mod structure;
@@ -40,6 +40,13 @@ impl Editor {
for update in updates { txn.apply_update(update).map_err(|_| "invalid_update")?; }
Ok(())
}
+ /// Whether every struct and deletion this replica holds is integrated. A
+ /// state that parks some (a dependency it never received) shows less than
+ /// it holds, and its stored sequence must not be trusted (#145).
+ pub fn is_whole(&self) -> bool {
+ let txn = self.doc.transact();
+ txn.store().pending_update().is_none() && txn.store().pending_ds().is_none()
+ }
pub fn snapshot(&self) -> Vec<u8> {
self.doc.transact().encode_state_as_update_v1(&StateVector::default())
}
@@ -161,6 +168,7 @@ pub fn dispatch(bytes: &[u8]) -> Result<Vec<u8>, &'static str> {
editor.apply(&bytes)?; Ok(Vec::new())
},
Some("snapshot") => Ok(editor.snapshot()),
+ Some("whole") => serde_json::to_vec(&editor.is_whole()).map_err(|_| "invalid_projection"),
Some("anchor") => serde_json::to_vec(&editor.anchor(request["at"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid_range")?)?).map_err(|_| "invalid_anchor"),
Some("resolve") => serde_json::to_vec(&editor.resolve(&request["anchor"])?).map_err(|_| "invalid_anchor"),
Some("clients") => serde_json::to_vec(&editor.doc.transact().state_vector().iter().map(|(id, _)| *id).collect::<Vec<_>>()).map_err(|_| "invalid_projection"),
diff --git a/native/crdt/tests/gc_undo_kept.rs b/native/crdt/tests/gc_undo_kept.rs
new file mode 100644
index 0000000..545ebad
--- /dev/null
+++ b/native/crdt/tests/gc_undo_kept.rs
@@ -0,0 +1,152 @@
+//! An undo-kept item under a garbage-collected parent (oficina/docs #145,
+//! finding 1; upstream y-crdt #667 and #676, fixed by 0e5df00 in yrs 0.28.1).
+//!
+//! Clearing the redo stack un-keeps an item and, with it, every parent up the
+//! chain (`Item::keep(false)`), though a sibling the undo stack still holds
+//! stays kept. When a peer then deletes that parent, unpatched yrs collected
+//! the parent but skipped the kept child, freeing the branch the child still
+//! pointed into: the next snapshot panicked ("Could not get parent branch info
+//! for item"), or, reading freed memory, wrote a struct a fresh document
+//! cannot integrate. Yjs collects every child of a collected type whatever its
+//! keep flag (`ContentType.gc`), and so does the patched yrs.
+use docs_native_crdt::Editor;
+use serde_json::{json, Value};
+use yrs::types::ToJson;
+use yrs::updates::decoder::Decode;
+use yrs::{Doc, Map, MapPrelim, MapRef, Options, ReadTxn, StateVector, Transact, UndoManager, Update};
+
+fn reread(snapshot: &[u8]) -> Editor {
+ let fresh = Editor::new("keep", 99);
+ fresh.apply(snapshot).unwrap();
+ fresh
+}
+
+/// Fable's repro: delete a word, type in the same paragraph, undo, type
+/// anything (clearing the redo stack), then a peer deletes that paragraph.
+fn repro() -> (Editor, Editor, Vec<Vec<u8>>) {
+ let mut a = Editor::new("keep", 11);
+ a.command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap();
+ a.command(&json!({"op":"display_edit","at":0,"length":0,"text":"aaa\nhello world\nzzz"})).unwrap();
+ let base = a.snapshot();
+ let mut editor = Editor::new("keep", 12);
+ editor.apply(&base).unwrap();
+ let mut peer = Editor::new("keep", 13);
+ peer.apply(&base).unwrap();
+ // display: "aaa\nhello world\nzzz\n": hello at 4..9
+ let mut sent = vec![base];
+ for command in [
+ json!({"op":"display_edit","at":4,"length":5,"text":""}), // delete "hello" (undo item 1)
+ json!({"op":"display_edit","at":6,"length":0,"text":"Q"}), // type in the same paragraph (undo item 2)
+ json!({"op":"undo"}), // item 2 moves to the redo stack
+ json!({"op":"display_edit","at":0,"length":0,"text":"x"}), // clears the redo stack: un-keeps the paragraph
+ ] {
+ let update = editor.command(&command).unwrap();
+ peer.apply(&update).unwrap();
+ sent.push(update);
+ }
+ // The peer deletes from inside the first paragraph to inside the third:
+ // the middle one, holding the still-kept "hello", goes.
+ let remote = peer.command(&json!({"op":"display_edit","at":2,"length":12,"text":""})).unwrap();
+ editor.apply(&remote).unwrap();
+ sent.push(remote);
+ (editor, peer, sent)
+}
+
+fn children(editor: &Editor) -> Value { editor.projection()["children"].clone() }
+
+#[test]
+fn a_snapshot_after_a_peer_deletes_a_kept_items_paragraph_holds_what_the_editor_shows() {
+ let (editor, peer, _) = repro();
+ assert!(editor.is_whole());
+ let snapshot = editor.snapshot();
+ let fresh = reread(&snapshot);
+ assert!(fresh.is_whole(), "a fresh document parks part of the snapshot");
+ assert_eq!(children(&fresh), children(&editor), "the snapshot does not hold what the editor shows");
+ assert_eq!(children(&editor), children(&peer));
+ assert_eq!(fresh.snapshot(), reread(&fresh.snapshot()).snapshot());
+}
+
+#[test]
+fn undoing_past_the_collected_paragraph_converges_with_the_peer() {
+ let (mut editor, peer, _) = repro();
+ // The collected "hello" cannot come back (Yjs drops it the same way); the
+ // rest of the history undoes, and every step's snapshot stays whole.
+ for _ in 0..8 {
+ let update = editor.command(&json!({"op":"undo"})).unwrap();
+ peer.apply(&update).unwrap();
+ let fresh = reread(&editor.snapshot());
+ assert!(fresh.is_whole());
+ assert_eq!(children(&fresh), children(&editor));
+ assert_eq!(children(&editor), children(&peer));
+ }
+ for _ in 0..8 {
+ let update = editor.command(&json!({"op":"redo"})).unwrap();
+ peer.apply(&update).unwrap();
+ assert_eq!(children(&reread(&editor.snapshot())), children(&editor));
+ assert_eq!(children(&editor), children(&peer));
+ }
+}
+
+#[test]
+fn every_update_and_snapshot_replays_into_plain_yrs_with_gc_on_and_off() {
+ let (editor, _, sent) = repro();
+ for skip_gc in [false, true] {
+ let mut options = Options::with_guid_and_client_id("keep".into(), 50);
+ options.skip_gc = skip_gc;
+ let replayed = Doc::with_options(options.clone());
+ for update in &sent { replayed.transact_mut().apply_update(Update::decode_v1(update).unwrap()).unwrap(); }
+ let from_snapshot = Doc::with_options({ let mut o = options.clone(); o.client_id = 51; o });
+ from_snapshot.transact_mut().apply_update(Update::decode_v1(&editor.snapshot()).unwrap()).unwrap();
+ for doc in [&replayed, &from_snapshot] {
+ let state = doc.transact().encode_state_as_update_v1(&StateVector::default());
+ assert_eq!(children(&reread(&state)), children(&editor), "skip_gc={skip_gc}");
+ assert!(doc.transact().store().pending_update().is_none() && doc.transact().store().pending_ds().is_none());
+ }
+ assert_eq!(replayed.transact().state_vector(), editor_state_vector(&editor));
+ }
+}
+
+fn editor_state_vector(editor: &Editor) -> StateVector {
+ Update::decode_v1(&editor.snapshot()).unwrap().state_vector()
+}
+
+/// Upstream's own regression (y-crdt 0e5df00, `gc_collects_kept_children_of_a_collected_type`),
+/// on yrs 0.23.5's API: a map instead of the editor's XML.
+#[test]
+fn yrs_collects_kept_children_of_a_collected_type() {
+ let d1 = Doc::with_client_id(1);
+ let d2 = Doc::with_client_id(2);
+ let styles1 = d1.get_or_insert_map("styles");
+ let styles2 = d2.get_or_insert_map("styles");
+ styles1.insert(&mut d1.transact_mut(), "p", MapPrelim::from([("kind", "number")]));
+ exchange(&d1, &d2);
+
+ let mut mgr = UndoManager::new(&d2, &styles2);
+ {
+ let mut txn = d2.transact_mut();
+ let p = styles2.get(&txn, "p").unwrap().cast::<MapRef>().unwrap();
+ p.insert(&mut txn, "kind", "bullet");
+ }
+ mgr.undo_blocking();
+ mgr.reset();
+ styles2.insert(&mut d2.transact_mut(), "q", MapPrelim::default()); // clears the redo stack
+
+ styles1.remove(&mut d1.transact_mut(), "p");
+ exchange(&d1, &d2);
+
+ let state = d2.transact().encode_state_as_update_v1(&StateVector::default());
+ let fresh = Doc::with_client_id(3);
+ fresh.transact_mut().apply_update(Update::decode_v1(&state).unwrap()).unwrap();
+ assert!(fresh.transact().store().pending_update().is_none());
+ while mgr.undo_blocking() {}
+ exchange(&d1, &d2);
+ assert_eq!(styles1.to_json(&d1.transact()), styles2.to_json(&d2.transact()));
+}
+
+fn exchange(a: &Doc, b: &Doc) {
+ for (from, to) in [(a, b), (b, a)] {
+ let sv = to.transact().state_vector();
+ let update = from.transact().encode_state_as_update_v1(&sv);
+ to.transact_mut().apply_update(Update::decode_v1(&update).unwrap()).unwrap();
+ }
+}
diff --git a/native/crdt/tests/gc_undo_kept_fuzz.rs b/native/crdt/tests/gc_undo_kept_fuzz.rs
new file mode 100644
index 0000000..84622c8
--- /dev/null
+++ b/native/crdt/tests/gc_undo_kept_fuzz.rs
@@ -0,0 +1,226 @@
+//! Fuzz for the undo-kept GC bug (oficina/docs #145, finding 1; see
+//! gc_undo_kept.rs), after Claude Fable's review harness: three editors run
+//! random commands, undo and redo included, and exchange only each command's
+//! update, delivered late, out of order and sometimes twice. After every step
+//! each editor is checked against plain yrs documents that received only
+//! those updates (gc on and off), and its snapshot must integrate whole into a
+//! fresh document and show exactly what the editor shows. At the end all
+//! three converge.
+//!
+//! The gate runs a bounded set of seeds. For a long run:
+//! GC_UNDO_KEPT_SEEDS=1-400 GC_UNDO_KEPT_STEPS=150 cargo test --release \
+//! --manifest-path native/crdt/Cargo.toml --test gc_undo_kept_fuzz
+//! GC_UNDO_KEPT_TRACE=1 prints each command.
+use docs_native_crdt::Editor;
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+use yrs::updates::decoder::Decode;
+use yrs::{Doc, ReadTxn, StateVector, Transact, Update};
+
+const GUID: &str = "gc-undo-kept";
+
+struct Random(u64);
+impl Random {
+ fn new(seed: u64) -> Self { Random(seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407)) }
+ fn next(&mut self) -> u64 {
+ self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ let mut x = self.0; x ^= x >> 33; x = x.wrapping_mul(0xff51afd7ed558ccd); x ^= x >> 33; x
+ }
+ fn below(&mut self, n: u64) -> u64 { if n == 0 { 0 } else { self.next() % n } }
+}
+
+const WORDS: &[&str] = &["the","of","and","to","in","is","that","for","it","as","was","with","be","by","on","not","this","naïve","café","😀"];
+
+/// A few pages: paragraphs, headings and a list, written by one client and
+/// then edited by three more, so the base carries tombstones.
+fn generate(seed: u64) -> Vec<u8> {
+ let mut random = Random::new(seed);
+ let mut author = Editor::new(GUID, 7_000);
+ author.command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap();
+ let paragraphs: Vec<String> = (0..12).map(|_| (0..6 + random.below(20)).map(|_| WORDS[random.below(WORDS.len() as u64) as usize]).collect::<Vec<_>>().join(" ")).collect();
+ author.command(&json!({"op":"display_edit","at":0,"length":0,"text":paragraphs.join("\n")})).unwrap();
+ let mut leaves = vec![]; collect(&author.projection(), &["paragraph"], &mut leaves);
+ for (i, node) in leaves.iter().enumerate() {
+ match i % 6 {
+ 0 => { author.command(&json!({"op":"block","node":node,"type":"heading","level":2})).unwrap(); },
+ 3 | 4 => { author.command(&json!({"op":"block","node":node,"type":"bullet_list","level":1})).ok(); },
+ _ => {},
+ }
+ }
+ let base = author.snapshot();
+ let mut editors: Vec<Editor> = (0..3).map(|i| { let e = Editor::new(GUID, 7_001 + i); e.apply(&base).unwrap(); e }).collect();
+ for round in 0..10 {
+ let mut updates = vec![];
+ for editor in editors.iter_mut() {
+ let total = display_length(&editor.projection());
+ let at = random.below(total as u64 + 1);
+ let command = if random.below(3) == 0 { json!({"op":"display_edit","at":at,"length":1 + random.below(4),"text":""}) }
+ else { json!({"op":"display_edit","at":at,"length":0,"text":format!("e{round}")}) };
+ if let Ok(update) = editor.command(&command) { updates.push(update); }
+ }
+ for editor in &editors { for update in &updates { editor.apply(update).unwrap(); } }
+ }
+ let merged = Editor::new(GUID, 6_999);
+ merged.apply(&base).unwrap();
+ merged.apply(&editors[0].snapshot()).unwrap();
+ merged.snapshot()
+}
+
+fn display_length(projection: &Value) -> u32 {
+ fn walk(value: &Value, offset: &mut u32) {
+ let tag = value["type"].as_str().unwrap_or("");
+ if tag == "text" {
+ *offset += value["runs"].as_array().map(|runs| runs.iter().map(|r| r["insert"].as_str().unwrap_or("").encode_utf16().count() as u32).sum()).unwrap_or(0);
+ return;
+ }
+ if ["hard_break", "image"].contains(&tag) { *offset += 1; return; }
+ if tag == "horizontal_rule" { *offset += 2; return; }
+ for child in value["children"].as_array().into_iter().flatten() { walk(child, offset); }
+ if ["paragraph", "heading", "code_block"].contains(&tag) { *offset += 1; }
+ }
+ let mut offset = 0;
+ for child in projection["children"].as_array().unwrap() { walk(child, &mut offset); }
+ offset
+}
+
+fn collect(value: &Value, types: &[&str], out: &mut Vec<Value>) {
+ if types.contains(&value["type"].as_str().unwrap_or("")) { out.push(value["id"].clone()); }
+ for child in value["children"].as_array().into_iter().flatten() { collect(child, types, out); }
+}
+fn pick(random: &mut Random, values: &[Value]) -> Value {
+ if values.is_empty() { Value::Null } else { values[random.below(values.len() as u64) as usize].clone() }
+}
+
+fn open(bytes: &[u8], client: u64) -> Editor { let e = Editor::new(GUID, client); e.apply(bytes).unwrap(); e }
+fn plain_doc(bytes: &[u8], client: u64, skip_gc: bool) -> Doc {
+ let mut options = yrs::Options::with_guid_and_client_id(GUID.into(), client);
+ options.offset_kind = yrs::OffsetKind::Utf16;
+ options.skip_gc = skip_gc;
+ let doc = Doc::with_options(options);
+ doc.transact_mut().apply_update(Update::decode_v1(bytes).unwrap()).unwrap();
+ doc
+}
+fn state(doc: &Doc) -> Vec<u8> { doc.transact().encode_state_as_update_v1(&StateVector::default()) }
+fn apply(doc: &Doc, bytes: &[u8]) { doc.transact_mut().apply_update(Update::decode_v1(bytes).unwrap()).unwrap(); }
+fn deletes(update: &Update) -> BTreeMap<u64, String> { update.delete_set().iter().map(|(c, r)| (*c, format!("{r:?}"))).collect() }
+/// What a fresh document shows after integrating these bytes, and whether it
+/// integrated all of them.
+fn reread(bytes: &[u8]) -> (Value, bool) { let fresh = open(bytes, 1); (fresh.projection()["children"].clone(), fresh.is_whole()) }
+
+fn run(seed: u64, steps: usize, in_order: bool) -> BTreeMap<String, (usize, usize)> {
+ let trace = std::env::var("GC_UNDO_KEPT_TRACE").is_ok();
+ let base = generate(seed);
+ let n = 3;
+ let mut editors: Vec<Editor> = (0..n).map(|i| open(&base, 1000 + i as u64)).collect();
+ let gc: Vec<Doc> = (0..n).map(|i| plain_doc(&base, 2000 + i as u64, false)).collect();
+ let nogc: Vec<Doc> = (0..n).map(|i| plain_doc(&base, 3000 + i as u64, true)).collect();
+ let mut inbox: Vec<Vec<Vec<u8>>> = vec![Vec::new(); n];
+ let mut random = Random::new(seed * 77 + 5);
+ let mut next_client = 5000u64;
+ let mut stats = BTreeMap::<String, (usize, usize)>::new();
+ let types = ["paragraph", "heading", "bullet_list", "ordered_list", "blockquote", "code_block"];
+ for step in 0..steps {
+ let i = random.below(n as u64) as usize;
+ let before = editors[i].snapshot();
+ let projection = editors[i].projection();
+ let at = random.below(display_length(&projection) as u64 + 1) as u32;
+ let mut texts = vec![]; collect(&projection, &["text"], &mut texts);
+ let mut blocks = vec![]; collect(&projection, &["paragraph","heading","code_block","list_item","bullet_list","ordered_list","blockquote"], &mut blocks);
+ let mut leaves = vec![]; collect(&projection, &["paragraph","heading"], &mut leaves);
+ let command = match random.below(22) {
+ 0 | 1 | 2 => json!({"op":"display_edit","at":at,"length":0,"text":(["x","héllo","😀"," a\nb","\n","\n\n- "][random.below(6) as usize])}),
+ 3 | 4 => json!({"op":"display_edit","at":at,"length":random.below(4),"text":""}),
+ 5 => json!({"op":"display_edit","at":at,"length":random.below(700),"text":(["","Z","q\nr"][random.below(3) as usize])}),
+ 6 => json!({"op":"display_paste","at":at,"length":random.below(30),"blocks":[
+ {"type":"paragraph","children":[{"type":"text","runs":[{"insert":"pasted","marks":{"em":{}}}]},{"type":"hard_break"},{"type":"text","runs":[{"insert":"more","marks":{}}]}]},
+ {"type":"horizontal_rule"},
+ {"type":"ordered_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"item","marks":{}}]}]},{"type":"bullet_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"nested","marks":{}}]}]}]}]}]}]}]}),
+ 7 | 8 => json!({"op":"undo"}),
+ 9 => json!({"op":"redo"}),
+ 10 | 11 => json!({"op":"block","node":pick(&mut random,&leaves),"type":types[random.below(6) as usize],"level":1 + random.below(3)}),
+ 12 => json!({"op":"attribute","node":pick(&mut random,&blocks),"name":"align","value":(["center","right"][random.below(2) as usize])}),
+ 13 | 14 => json!({"op":"format","node":pick(&mut random,&texts),"at":random.below(20),"length":1 + random.below(30),"marks":{"strong":{}}}),
+ 15 => json!({"op":"list_indent","node":pick(&mut random,&leaves),"delta":if random.below(2) == 0 {1} else {-1}}),
+ 16 => json!({"op":"split","node":pick(&mut random,&texts),"at":random.below(40)}),
+ 17 => json!({"op":"hard_break","node":pick(&mut random,&texts),"at":random.below(40)}),
+ 18 => json!({"op":"display_autoformat","at":at,"length":random.below(3),"kind":(["bullet_list","heading","blockquote","ordered_list"][random.below(4) as usize]),"level":1}),
+ 19 => json!({"op":"display_exit_list","at":at}),
+ 20 => json!({"op":"batch","commands":[
+ {"op":"block","node":pick(&mut random,&leaves),"type":types[random.below(6) as usize],"level":2},
+ {"op":"block","node":pick(&mut random,&leaves),"type":types[random.below(6) as usize],"level":2},
+ {"op":"display_edit","at":at,"length":random.below(3),"text":"B"}]}),
+ _ => json!({"op":"display_edit","at":at,"length":random.below(60),"text":"\n"}),
+ };
+ if trace { eprintln!("seed {seed} #{step} e{i} {command}"); }
+ let op = command["op"].as_str().unwrap().to_owned();
+ match editors[i].command(&command) {
+ Ok(update) => {
+ if trace { eprintln!("UPDATE {}", Update::decode_v1(&update).unwrap()); }
+ stats.entry(op).or_default().0 += 1;
+ apply(&gc[i], &update); apply(&nogc[i], &update);
+ for j in 0..n { if j != i { inbox[j].push(update.clone()); } }
+ },
+ Err(_) => {
+ stats.entry(op).or_default().1 += 1;
+ // As CRDTReplica does: a failed command's writer is rebuilt
+ // from the last good state under a new client.
+ if editors[i].snapshot() != before { next_client += 1; editors[i] = open(&state(&gc[i]), next_client); }
+ },
+ }
+ for j in 0..n {
+ for _ in 0..random.below(4) {
+ if inbox[j].is_empty() { break; }
+ let at = if in_order { 0 } else { random.below(inbox[j].len() as u64) as usize };
+ let message = if !in_order && random.below(10) == 0 { inbox[j][at].clone() } else { inbox[j].remove(at) };
+ editors[j].apply(&message).unwrap();
+ apply(&gc[j], &message); apply(&nogc[j], &message);
+ }
+ }
+ for j in 0..n {
+ let context = format!("seed {seed} step {step} editor {j} (in order: {in_order}) after {command}");
+ let snapshot = editors[j].snapshot();
+ let (reread_snapshot, whole) = reread(&snapshot);
+ let shown = editors[j].projection()["children"].clone();
+ // The bug's two faces: a snapshot that does not integrate whole,
+ // or that shows something other than the editor.
+ assert_eq!(whole, editors[j].is_whole(), "{context}: snapshot parks what the editor integrated");
+ assert_eq!(reread_snapshot, shown, "{context}: snapshot differs from what the editor shows");
+ let (ours, theirs) = (Update::decode_v1(&snapshot).unwrap(), Update::decode_v1(&state(&gc[j])).unwrap());
+ assert_eq!(ours.state_vector(), theirs.state_vector(), "{context}: state vectors");
+ let (a, b) = (deletes(&ours), deletes(&theirs));
+ for client in a.keys().chain(b.keys()).filter(|c| a.get(c) != b.get(c)) {
+ eprintln!("{context}: client {client} deletes\n editor {:?}\n plain {:?}", a.get(client), b.get(client));
+ }
+ assert_eq!(deletes(&ours), deletes(&theirs), "{context}: delete sets");
+ assert_eq!(reread(&state(&gc[j])).0, shown, "{context}: plain yrs (gc on) differs");
+ assert_eq!(reread(&state(&nogc[j])).0, shown, "{context}: plain yrs (gc off) differs");
+ }
+ }
+ for j in 0..n { for message in std::mem::take(&mut inbox[j]) { editors[j].apply(&message).unwrap(); } }
+ let first = reread(&editors[0].snapshot());
+ assert!(first.1, "seed {seed}: final state not whole");
+ for j in 1..n { assert_eq!(first, reread(&editors[j].snapshot()), "seed {seed}: editors diverged at the end"); }
+ stats
+}
+
+fn seeds() -> std::ops::RangeInclusive<u64> {
+ match std::env::var("GC_UNDO_KEPT_SEEDS") {
+ Ok(range) => { let (a, b) = range.split_once('-').unwrap_or((&range, &range)); a.parse().unwrap()..=b.parse().unwrap() },
+ Err(_) => 1..=6,
+ }
+}
+fn steps() -> usize { std::env::var("GC_UNDO_KEPT_STEPS").map(|s| s.parse().unwrap()).unwrap_or(120) }
+
+fn fuzz(in_order: bool) {
+ let mut total = BTreeMap::<String, (usize, usize)>::new();
+ for seed in seeds() {
+ for (op, (ok, err)) in run(seed, steps(), in_order) { let entry = total.entry(op).or_default(); entry.0 += ok; entry.1 += err; }
+ }
+ eprintln!("in order {in_order}, seeds {:?}, {} steps: ok/refused per command {total:?}", seeds(), steps());
+}
+
+#[test]
+fn three_editors_with_undo_in_causal_order() { fuzz(true); }
+
+#[test]
+fn three_editors_with_undo_shuffled_and_duplicated() { fuzz(false); }
diff --git a/native/crdt/tests/insert_into_deleted_parent.rs b/native/crdt/tests/insert_into_deleted_parent.rs
new file mode 100644
index 0000000..edce6dc
--- /dev/null
+++ b/native/crdt/tests/insert_into_deleted_parent.rs
@@ -0,0 +1,154 @@
+//! A local insert into a parent that has since been deleted (oficina/docs
+//! #145, finding 9; found by gc_undo_kept_fuzz.rs at seed 42 and by the engine
+//! branch's convergence fuzz at seeds 76 and 113).
+//!
+//! Yjs's `Item.integrate` deletes an item whose parent is deleted, for every
+//! insert, local or remote; so does yrs's remote path (`Update::integrate`).
+//! yrs 0.23.5's three local paths dropped `integrate`'s "delete me" answer:
+//! `ItemPtr::redo`, `TransactionMut::create_item` (text, element and attribute
+//! inserts) and `BlockIter::insert_contents` (array inserts). The inserting
+//! replica alone kept the item live: invisible under its deleted parent, but
+//! with a delete set no one else had. The editor reaches it through undo:
+//! undoing a deletion re-creates the item in its parent, following a deleted
+//! parent's `redone` chain to its restored copy, which a peer may since have
+//! deleted. Upstream's `integrate_item` (yrs 0.27) deletes for every caller.
+use yrs::types::xml::XmlTextPrelim;
+use yrs::updates::decoder::Decode;
+use yrs::{Array, ArrayPrelim, ArrayRef, Doc, GetString, Map, MapPrelim, Options, ReadTxn, StateVector, Text, Transact, UndoManager, Update, Xml, XmlElementPrelim, XmlElementRef, XmlFragment, XmlOut, XmlTextRef};
+
+fn doc(client: u64) -> Doc { doc_gc(client, false) }
+fn doc_gc(client: u64, skip_gc: bool) -> Doc {
+ let mut options = Options::with_guid_and_client_id("insert-into-deleted-parent".into(), client);
+ options.offset_kind = yrs::OffsetKind::Utf16;
+ options.skip_gc = skip_gc;
+ Doc::with_options(options)
+}
+fn sync(from: &Doc, to: &Doc) {
+ let update = from.transact().encode_state_as_update_v1(&to.transact().state_vector());
+ to.transact_mut_with("remote").apply_update(Update::decode_v1(&update).unwrap()).unwrap();
+}
+fn state(doc: &Doc) -> Update { Update::decode_v1(&doc.transact().encode_state_as_update_v1(&StateVector::default())).unwrap() }
+fn deletes(doc: &Doc) -> String { format!("{:?}", state(doc).delete_set().iter().map(|(c, r)| (*c, format!("{r:?}"))).collect::<std::collections::BTreeMap<_, _>>()) }
+
+#[test]
+fn an_item_undone_into_a_deleted_restored_parent_is_deleted_as_everywhere_else() {
+ let editor = doc(1);
+ let peer = doc(2);
+ let root = editor.get_or_insert_xml_fragment("prosemirror");
+ root.insert(&mut editor.transact_mut_with("remote"), 0, XmlElementPrelim::new("paragraph", [yrs::types::xml::XmlIn::Text(XmlTextPrelim::new("ab cd").into())]));
+ sync(&editor, &peer);
+ let mut undo = UndoManager::with_scope_and_options(&editor, &root, yrs::undo::Options {
+ capture_timeout_millis: 0,
+ tracked_origins: ["local".into()].into(),
+ capture_transaction: None,
+ timestamp: std::sync::Arc::new(|| 1),
+ });
+ let text = || match root.get(&editor.transact(), 0).unwrap() {
+ XmlOut::Element(paragraph) => match paragraph.get(&editor.transact(), 0).unwrap() { XmlOut::Text(text) => text, _ => unreachable!() },
+ _ => unreachable!(),
+ };
+ text().remove_range(&mut editor.transact_mut_with("local"), 2, 1); // delete " "
+ root.remove_range(&mut editor.transact_mut_with("local"), 0, 1); // delete the paragraph
+ assert!(undo.undo_blocking()); // the paragraph comes back as a new one, "abcd"
+ sync(&editor, &peer);
+ // A peer deletes the restored paragraph.
+ let peer_root = peer.get_or_insert_xml_fragment("prosemirror");
+ peer_root.remove_range(&mut peer.transact_mut(), 0, 1);
+ sync(&peer, &editor);
+ // Undo the " ": its parent's restored copy is deleted, so it is too.
+ assert!(undo.undo_blocking());
+ sync(&editor, &peer);
+ assert_eq!(state(&editor).state_vector(), state(&peer).state_vector());
+ assert_eq!(deletes(&editor), deletes(&peer), "the undoing editor disagrees about what is deleted");
+ let fresh = doc(3);
+ fresh.transact_mut().apply_update(state(&editor)).unwrap();
+ assert_eq!(deletes(&fresh), deletes(&editor));
+ assert_eq!(root.get_string(&editor.transact()), "");
+ assert_eq!(peer_root.get_string(&peer.transact()), "");
+}
+
+/// Every local insert path into a type a peer has deleted. With gc off, so the
+/// local references stay valid after the deletion (the editor reaches deleted
+/// types only through undo, above).
+#[test]
+fn local_inserts_into_a_type_a_peer_deleted_are_deleted_as_everywhere_else() {
+ let editor = doc_gc(1, true);
+ let peer = doc_gc(2, true);
+ let root = editor.get_or_insert_xml_fragment("prosemirror");
+ let map = editor.get_or_insert_map("map");
+ {
+ let mut txn = editor.transact_mut();
+ root.insert(&mut txn, 0, XmlElementPrelim::new("paragraph", [yrs::types::xml::XmlIn::Text(XmlTextPrelim::new("ab").into())]));
+ map.insert(&mut txn, "list", ArrayPrelim::from([1, 2]));
+ map.insert(&mut txn, "nested", MapPrelim::from([("k", "v")]));
+ }
+ sync(&editor, &peer);
+ let (paragraph, text): (XmlElementRef, XmlTextRef) = {
+ let txn = editor.transact();
+ let XmlOut::Element(paragraph) = root.get(&txn, 0).unwrap() else { unreachable!() };
+ let XmlOut::Text(text) = paragraph.get(&txn, 0).unwrap() else { unreachable!() };
+ (paragraph, text)
+ };
+ let list: ArrayRef = map.get(&editor.transact(), "list").unwrap().cast().unwrap();
+ let nested: yrs::MapRef = map.get(&editor.transact(), "nested").unwrap().cast().unwrap();
+ let (peer_root, peer_map) = (peer.get_or_insert_xml_fragment("prosemirror"), peer.get_or_insert_map("map"));
+ {
+ let mut txn = peer.transact_mut();
+ peer_root.remove_range(&mut txn, 0, 1);
+ peer_map.remove(&mut txn, "list");
+ peer_map.remove(&mut txn, "nested");
+ }
+ sync(&peer, &editor);
+ {
+ let mut txn = editor.transact_mut();
+ text.insert(&mut txn, 1, "X"); // create_item
+ paragraph.insert(&mut txn, 0, XmlTextPrelim::new("Y")); // create_item via insert_at
+ paragraph.insert_attribute(&mut txn, "align", "center"); // create_item with a key
+ nested.insert(&mut txn, "k2", "v2"); // create_item with a key
+ list.insert_range(&mut txn, 0, [3, 4]); // BlockIter::insert_contents
+ }
+ sync(&editor, &peer);
+ assert_eq!(state(&editor).state_vector(), state(&peer).state_vector());
+ assert_eq!(deletes(&editor), deletes(&peer), "the inserting replica disagrees about what is deleted");
+ let fresh = doc_gc(3, true);
+ fresh.transact_mut().apply_update(state(&editor)).unwrap();
+ assert_eq!(deletes(&fresh), deletes(&editor));
+}
+
+/// Redo origins (found by gc_undo_kept_fuzz.rs at seed 98, reduced). "xyz"
+/// is deleted and undone: it comes back as one item x'y'z', whose `redone` the
+/// original carries. "y'" is deleted, splitting it; then the paragraph. Undoing
+/// that restores A'', x'' and z''. For z'' the left neighbour traces y' (not
+/// restored), then x' to x''; the right neighbour traces the original "xyz",
+/// whose restored copy starts at x', to x'' as well. yrs and Yjs both put z''
+/// right after x'' locally, but the origins they wrote (after the end of the
+/// merged A''x'' block, before x'' inside it) put it before x'' on every
+/// receiver. Unpatched, this replica shows "Axz" and every peer "Azx".
+#[test]
+fn an_undo_whose_neighbours_trace_to_one_item_places_it_as_every_peer_does() {
+ let editor = doc(1);
+ let peer = doc(2);
+ let root = editor.get_or_insert_xml_fragment("prosemirror");
+ root.insert(&mut editor.transact_mut_with("remote"), 0, XmlElementPrelim::new("paragraph", [yrs::types::xml::XmlIn::Text(XmlTextPrelim::new("Axyz").into())]));
+ let mut undo = UndoManager::with_scope_and_options(&editor, &root, yrs::undo::Options {
+ capture_timeout_millis: 0,
+ tracked_origins: ["local".into()].into(),
+ capture_transaction: None,
+ timestamp: std::sync::Arc::new(|| 1),
+ });
+ let text = || match root.get(&editor.transact(), 0).unwrap() {
+ XmlOut::Element(paragraph) => match paragraph.get(&editor.transact(), 0).unwrap() { XmlOut::Text(text) => text, _ => unreachable!() },
+ _ => unreachable!(),
+ };
+ text().remove_range(&mut editor.transact_mut_with("local"), 1, 3); // delete "xyz"
+ assert!(undo.undo_blocking()); // back, as one item x'y'z'
+ text().remove_range(&mut editor.transact_mut_with("local"), 2, 1); // delete "y'"
+ root.remove_range(&mut editor.transact_mut_with("local"), 0, 1); // delete the paragraph
+ assert!(undo.undo_blocking()); // the paragraph back: A'', x'', z''
+ assert_eq!(root.get_string(&editor.transact()), "<paragraph>Axz</paragraph>");
+ sync(&editor, &peer);
+ assert_eq!(peer.get_or_insert_xml_fragment("prosemirror").get_string(&peer.transact()), "<paragraph>Axz</paragraph>", "a peer puts the restored z elsewhere");
+ let fresh = doc(3);
+ fresh.transact_mut().apply_update(state(&editor)).unwrap();
+ assert_eq!(fresh.get_or_insert_xml_fragment("prosemirror").get_string(&fresh.transact()), "<paragraph>Axz</paragraph>");
+}
diff --git a/native/host/tests/gc_undo_kept.rs b/native/host/tests/gc_undo_kept.rs
new file mode 100644
index 0000000..0a23053
--- /dev/null
+++ b/native/host/tests/gc_undo_kept.rs
@@ -0,0 +1,42 @@
+//! The undo-kept GC repro (oficina/docs #145; native/crdt/tests/gc_undo_kept.rs)
+//! through the shipped WASM module and the bounded host, as CRDTReplica runs
+//! it: before the fix the module read freed memory here, so a run could pass by
+//! luck, trap, or write a snapshot a fresh sandbox cannot integrate.
+use docs_native_host::Host;
+use serde_json::{json, Value};
+
+fn open(client: u64, state: &[u8]) -> Host {
+ let mut host = Host::new().unwrap();
+ host.call(&serde_json::to_vec(&json!({"op":"open","guid":"keep","client":client})).unwrap()).unwrap();
+ if !state.is_empty() { host.call(&[&[255u8][..], state].concat()).unwrap(); }
+ host
+}
+fn call(host: &mut Host, command: Value) -> Vec<u8> { host.call(&serde_json::to_vec(&command).unwrap()).unwrap().to_vec() }
+fn project(host: &mut Host) -> Value { serde_json::from_slice::<Value>(&call(host, json!({"op":"project"}))).unwrap()["children"].clone() }
+fn whole(host: &mut Host) -> bool { serde_json::from_slice(&call(host, json!({"op":"whole"}))).unwrap() }
+
+#[test]
+fn a_kept_word_under_a_paragraph_a_peer_deletes_snapshots_whole_in_the_sandbox() {
+ let mut author = open(11, &[]);
+ call(&mut author, json!({"op":"insert_element","at":0,"type":"paragraph"}));
+ call(&mut author, json!({"op":"display_edit","at":0,"length":0,"text":"aaa\nhello world\nzzz"}));
+ let base = call(&mut author, json!({"op":"snapshot"}));
+ let mut editor = open(12, &base);
+ let mut peer = open(13, &base);
+ for command in [
+ json!({"op":"display_edit","at":4,"length":5,"text":""}),
+ json!({"op":"display_edit","at":6,"length":0,"text":"Q"}),
+ json!({"op":"undo"}),
+ json!({"op":"display_edit","at":0,"length":0,"text":"x"}),
+ ] {
+ let update = call(&mut editor, command);
+ peer.call(&[&[255u8][..], &update].concat()).unwrap();
+ }
+ let remote = call(&mut peer, json!({"op":"display_edit","at":2,"length":12,"text":""}));
+ editor.call(&[&[255u8][..], &remote].concat()).unwrap();
+ let snapshot = call(&mut editor, json!({"op":"snapshot"}));
+ let mut fresh = open(99, &snapshot);
+ assert!(whole(&mut fresh), "a fresh sandbox parks part of the snapshot");
+ assert_eq!(project(&mut fresh), project(&mut editor));
+ assert_eq!(project(&mut editor), project(&mut peer));
+}
diff --git a/native/scripts/check-gc-undo-kept-wire.mjs b/native/scripts/check-gc-undo-kept-wire.mjs
new file mode 100644
index 0000000..9207dd7
--- /dev/null
+++ b/native/scripts/check-gc-undo-kept-wire.mjs
@@ -0,0 +1,106 @@
+// Browser replay of gc_undo_kept_probe (oficina/docs #145): the native update
+// stream and snapshots of the undo-kept GC repro, read by Yjs with gc on and
+// off. Each native snapshot must integrate whole, show what the replayed
+// stream shows and, with gc on, hold the same live, deleted and collected
+// units as Yjs; the paragraph's still-kept "hello" must be collected, as Yjs
+// itself does (checked first, with Yjs's own UndoManager). Also checks Yjs
+// deletes a local insert into a type a peer deleted (the vendored integrate
+// patch). Writes the Yjs states back for `gc_undo_kept_probe DIR --check`.
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import path from 'node:path'
+import * as Y from '../../fixtures/node_modules/yjs/dist/yjs.mjs'
+const directory = process.argv[2]
+assert.ok(directory, 'usage: node native/scripts/check-gc-undo-kept-wire.mjs OUTPUT_DIRECTORY')
+const read = (name) => new Uint8Array(fs.readFileSync(path.join(directory, name)))
+const steps = Number(fs.readFileSync(path.join(directory, 'steps'), 'utf8'))
+const body = (doc) => doc.getXmlFragment('prosemirror').toString()
+const whole = (doc) => doc.store.pendingStructs === null && doc.store.pendingDs === null
+
+// Every unit (client:clock) of an update: collected, deleted or live.
+function units (update) {
+ const { structs, ds } = Y.decodeUpdate(update)
+ const out = {}
+ for (const struct of structs) {
+ if (struct instanceof Y.Skip) continue
+ for (let i = 0; i < struct.length; i++) {
+ const id = Y.createID(struct.id.client, struct.id.clock + i)
+ out[`${id.client}:${id.clock}`] = struct instanceof Y.GC ? 'gc' : Y.isDeleted(ds, id) ? 'deleted' : 'live'
+ }
+ }
+ return out
+}
+
+// Yjs's own semantics, the reference: ContentType.gc collects a kept child.
+{
+ const author = new Y.Doc()
+ const text = new Y.XmlText()
+ text.insert(0, 'hello world')
+ const paragraph = new Y.XmlElement('paragraph')
+ paragraph.insert(0, [text])
+ author.getXmlFragment('prosemirror').insert(0, [paragraph])
+ const word = text._start.id
+ const editor = new Y.Doc()
+ Y.applyUpdate(editor, Y.encodeStateAsUpdate(author), 'remote')
+ const undo = new Y.UndoManager(editor.getXmlFragment('prosemirror'), { captureTimeout: 0 })
+ const typed = editor.getXmlFragment('prosemirror').get(0).get(0)
+ typed.delete(0, 5)
+ typed.insert(1, 'Q')
+ undo.undo()
+ typed.insert(0, 'x') // clears the redo stack
+ Y.applyUpdate(author, Y.encodeStateAsUpdate(editor, Y.encodeStateVector(author)), 'remote')
+ author.getXmlFragment('prosemirror').delete(0, 1)
+ Y.applyUpdate(editor, Y.encodeStateAsUpdate(author, Y.encodeStateVector(editor)), 'remote')
+ const structs = editor.store.clients.get(word.client)
+ const hello = structs[Y.findIndexSS(structs, word.clock)]
+ assert.ok(hello instanceof Y.GC, 'Yjs collects the kept "hello" with its paragraph')
+}
+
+// Yjs's own semantics for the vendored integrate patch: an item inserted into
+// a type a peer has deleted is deleted at once (Item.integrate), locally too.
+{
+ const local = new Y.Doc({ gc: false })
+ const text = new Y.XmlText()
+ text.insert(0, 'ab')
+ const paragraph = new Y.XmlElement('paragraph')
+ paragraph.insert(0, [text])
+ local.getXmlFragment('prosemirror').insert(0, [paragraph])
+ const peer = new Y.Doc({ gc: false })
+ Y.applyUpdate(peer, Y.encodeStateAsUpdate(local))
+ peer.getXmlFragment('prosemirror').delete(0, 1)
+ Y.applyUpdate(local, Y.encodeStateAsUpdate(peer, Y.encodeStateVector(local)))
+ text.insert(1, 'X')
+ const inserted = local.store.clients.get(local.clientID).at(-1)
+ assert.ok(inserted.deleted, 'Yjs deletes a local insert into a deleted parent')
+ Y.applyUpdate(peer, Y.encodeStateAsUpdate(local, Y.encodeStateVector(peer)))
+ assert.ok(Y.equalDeleteSets(Y.createDeleteSetFromStructStore(local.store), Y.createDeleteSetFromStructStore(peer.store)))
+}
+
+// The kept word in the native stream: "hello" of "hello world" in the base.
+const base = Y.decodeUpdate(read('0.bin')).structs.find((s) => s.content?.str?.includes('hello world'))
+const hello = Array.from({ length: 5 }, (_, i) => `${base.id.client}:${base.id.clock + base.content.str.indexOf('hello') + i}`)
+
+let comparisons = 0
+for (const gc of [true, false]) {
+ const replay = new Y.Doc({ gc })
+ for (let step = 0; step <= steps; step++) {
+ Y.applyUpdate(replay, read(`${step}.bin`))
+ const snapshot = read(`${step}.snapshot`)
+ const fresh = new Y.Doc({ gc })
+ Y.applyUpdate(fresh, snapshot)
+ assert.ok(whole(fresh), `gc=${gc} step=${step}: Yjs parks part of the native snapshot`)
+ assert.ok(whole(replay), `gc=${gc} step=${step}: Yjs parks part of the native stream`)
+ assert.equal(body(fresh), body(replay), `gc=${gc} step=${step}`)
+ if (gc) {
+ const ours = units(snapshot)
+ assert.deepEqual(ours, units(Y.encodeStateAsUpdate(replay)), `step=${step}: collected/deleted/live units differ from Yjs`)
+ if (step >= 5) assert.deepEqual(hello.map((u) => ours[u]), Array(5).fill('gc'), `step=${step}: the kept "hello" was not collected`)
+ }
+ fs.writeFileSync(path.join(directory, `browser-${gc}-${step}.bin`), Y.encodeStateAsUpdate(replay))
+ fresh.destroy()
+ comparisons++
+ }
+ assert.equal(body(replay), '<paragraph>xaz</paragraph>')
+ replay.destroy()
+}
+console.log(`GC undo-kept wire replay passed ${comparisons} snapshot comparisons, Yjs's two references and the collected kept word.`)
diff --git a/native/scripts/check-native.sh b/native/scripts/check-native.sh
index 3518ba3..1b5a890 100755
--- a/native/scripts/check-native.sh
+++ b/native/scripts/check-native.sh
@@ -44,6 +44,12 @@ node fixtures/native-wire.mjs "$native_check_dir/native.bin" "$native_check_dir/
"$CARGO" run --locked --quiet --manifest-path native/crdt/Cargo.toml --bin wire_fixture -- "$native_check_dir/native.bin" "$native_check_dir/browser.bin"
"$CARGO" run --locked --quiet --manifest-path native/crdt/Cargo.toml --bin rule_wire_probe -- "$native_check_dir/rule"
node native/scripts/check-rule-wire.mjs "$native_check_dir/rule"
+# #145: an undo-kept item under a paragraph a peer deletes is collected with
+# it, as in Yjs. Yjs replays the native stream and snapshots (gc on and off),
+# and the native editor reads Yjs's states back.
+"$CARGO" run --locked --quiet --manifest-path native/crdt/Cargo.toml --bin gc_undo_kept_probe -- "$native_check_dir/gc-undo-kept"
+node native/scripts/check-gc-undo-kept-wire.mjs "$native_check_dir/gc-undo-kept"
+"$CARGO" run --locked --quiet --manifest-path native/crdt/Cargo.toml --bin gc_undo_kept_probe -- "$native_check_dir/gc-undo-kept" --check
if [ "$core_only" = 0 ]; then
native/scripts/build-crdt.sh
swift test --package-path native/apple
diff --git a/native/vendor/yrs-0.23.5/PATCHES.md b/native/vendor/yrs-0.23.5/PATCHES.md
index 85b162b..b71d5ee 100644
--- a/native/vendor/yrs-0.23.5/PATCHES.md
+++ b/native/vendor/yrs-0.23.5/PATCHES.md
@@ -1,14 +1,58 @@
-# Local deletion backports
+# Local patches
Original crates.io yrs 0.23.5 package SHA-256: `197c2b4b298f35c3ba4d549884ac872a961112095b29f173ab45e3d5cf609018`.
-Only `src/transaction.rs` differs from the published Rust source:
+Only `src/transaction.rs`, `src/block.rs`, `src/block_iter.rs`, `src/gc.rs` and `src/undo.rs` differ from the published Rust source. On a yrs bump, check each patch below against the new release: drop it if upstream has it, re-apply it if not, and keep its regression tests either way.
+
+## Deletion backports (`src/transaction.rs`)
- Move the deletion scan outside the initial item-split guard so a range beginning at a garbage-collected block still deletes later live blocks. Adapted from upstream [PR 614](https://github.com/y-crdt/y-crdt/pull/614), commit `97095f2e27e4045002b656cec6347e9f9a989c89`.
- Store an unapplied deletion tail beginning at the known client state, rather than the original range start; this matches current upstream `apply_delete` and preserves deletion when missing inserts arrive later.
- Retain complete deletion ranges for clients whose first insert has not arrived yet, matching the upstream missing-client branch.
-Garbage collection remains enabled. Wire format, client IDs, undo policy, and sandbox limits are unchanged. Regressions live in `native/crdt/tests/rule_delta_convergence.rs`, `native/crdt/tests/delete_tail_review.rs`, and the server core native-rule fixture tests.
+Regressions live in `native/crdt/tests/rule_delta_convergence.rs`, `native/crdt/tests/delete_tail_review.rs`, and the server core native-rule fixture tests.
+
+## Undo-kept children of a collected type (`src/block.rs` `Item::gc`, `src/gc.rs`)
+
+Backport of upstream commit [`0e5df000867d703cbc403feece4312900b954565`](https://github.com/y-crdt/y-crdt/commit/0e5df000867d703cbc403feece4312900b954565) ("fix relation between Item::gc and keep flag", issues [#667](https://github.com/y-crdt/y-crdt/issues/667) and [#676](https://github.com/y-crdt/y-crdt/issues/676)), first released in yrs 0.28.1. oficina/docs discussion #145, finding 1.
+
+- `Item::gc` no longer checks the keep flag. `GCCollector::mark_in_scope` and `mark_all` check it for the top-level candidates instead, and `collect_marked` replaces every marked item.
+- So the children of a collected type are collected whatever their keep flag, as Yjs's `ContentType.gc` does. Before, clearing the redo stack un-kept an item's whole parent chain (`Item::keep(false)`) while a sibling on the undo stack stayed kept; when a peer then deleted that parent, the parent's branch was freed and the kept child still pointed into it. The next snapshot panicked (`slice.rs`, "Could not get parent branch info for item") or, in WASM, read freed memory and wrote a struct a fresh document could not integrate.
+- Drop on a bump to yrs 0.28.1 or later.
+
+Regressions: `native/crdt/tests/gc_undo_kept.rs` (the editor repro and upstream's own test on this API), `native/crdt/tests/gc_undo_kept_fuzz.rs`, and the browser replay `native/crdt/src/bin/gc_undo_kept_probe.rs` with `native/scripts/check-gc-undo-kept-wire.mjs`.
+
+## Local inserts into a deleted parent (`src/block.rs` `ItemPtr::redo`, `src/transaction.rs` `TransactionMut::create_item`, `src/block_iter.rs` `BlockIter::insert_contents`)
+
+Local patch; upstream has the same behaviour since its integration refactor (`0e450204ae`, "refactored transactions and correlated apply update / integrate block logic", yrs 0.27), where `TransactionMut::integrate_item` deletes an item whose parent is deleted for every caller. oficina/docs discussion #145, finding 9.
+
+- `Item::integrate` answers true when the new item's parent is deleted. The remote path (`Update::integrate`) then deletes the item, as Yjs's `Item.integrate` does for every insert, local or remote. The three local paths dropped the answer, so the inserting replica alone kept the item live: invisible under its deleted parent, but with a delete set no peer shared. Each now deletes the item after storing it, as `Update::integrate` does.
+- `ItemPtr::redo` is how the editor reaches it: undo follows a deleted parent's `redone` chain to its restored copy, which a peer may since have deleted. `create_item` (text, element and attribute inserts) and `insert_contents` (array inserts) are patched for parity; the editor's commands address live nodes, so they are not known to be reachable from it.
+- Drop on a bump to yrs 0.27 or later, after checking `integrate_item` still deletes for all three.
+
+Regressions: `native/crdt/tests/insert_into_deleted_parent.rs` (the undo case, and every local insert path into a type a peer deleted; each fails without its patch). `gc_undo_kept_fuzz.rs` found the undo case at seed 42, and the engine branch's `convergence_fuzz.rs` at seeds 76 and 113. `check-gc-undo-kept-wire.mjs` checks Yjs deletes a local insert into a deleted parent.
+
+## Redo origins (`src/block.rs` `ItemPtr::redo`)
+
+Local patch; neither upstream yrs (main, November 2026) nor Yjs 13.6.27 has it. oficina/docs discussion #145, found by `gc_undo_kept_fuzz.rs` at seed 98.
+
+- `redo` finds the restored item's neighbours by following `redone` chains, and both can land on the same restored item: the left neighbour traces to it directly, the right one through an original whose restored copy starts there. Both libraries then integrate the item right after it locally, but write origins (after the end of the merged block that item now ends, before the item inside it) that every receiver resolves to a place before it. Yjs's own `redoItem` and `getMissing` do the same (checked: Yjs's editor shows "Axz", a Yjs peer "Azx").
+- When the traced right neighbour is not to the right of the left one, `redo` now names the item actually after the left one instead. The local placement is unchanged (right after the left neighbour, the original order); the origins now put it there on every receiver, Yjs's included.
+- Keep on a bump unless upstream has changed `redo`'s right-hand trace.
+
+Regression: `native/crdt/tests/insert_into_deleted_parent.rs`, `an_undo_whose_neighbours_trace_to_one_item_places_it_as_every_peer_does` ("Azx" at the peer without the patch).
+
+## Redo order (`src/undo.rs` `UndoManager::pop`)
+
+Local patch. oficina/docs discussion #145.
+
+- `pop` collected the items to restore in a `HashSet<ItemPtr>` and restored them in its iteration order, which depends on the process's random hash keys. Restoration order decides where restored items are placed relative to each other, so the same undo could come out differently from run to run: the redo-origins failure above appeared in about one run in four. Yjs restores in its `Set`'s insertion order, the order the deletions are found.
+- Items are now restored in the order the deletions are found, the `HashSet` kept for membership. yrs's delete set iterates clients in a fixed order (`ClientHasher`); Yjs's is the order the deletions were made, so the order across clients can still differ from Yjs, but it no longer differs between runs.
+- Keep on a bump unless upstream has made the order deterministic.
+
+## Unchanged
+
+Garbage collection remains enabled. Wire format, client IDs, undo policy, and sandbox limits are unchanged.
The registry package omits its license text; `LICENSE` is copied from the exact upstream VCS commit `3996e91df00acdb67334695944bc43f60627103f` recorded in `.cargo_vcs_info.json`. Original attribution is retained.
diff --git a/native/vendor/yrs-0.23.5/src/block.rs b/native/vendor/yrs-0.23.5/src/block.rs
index 511cccc..c58966a 100644
--- a/native/vendor/yrs-0.23.5/src/block.rs
+++ b/native/vendor/yrs-0.23.5/src/block.rs
@@ -390,6 +390,26 @@ impl ItemPtr {
}
}
+ // Local patch (see PATCHES.md, "Redo origins"): tracing `redone` chains
+ // can land `right` on or before `left` (an item restored earlier to the
+ // left; here, `right` = `left`). Integrated locally the item goes right
+ // after `left`, but a receiver resolves those origins elsewhere: `right`
+ // inside `left`'s merged block splits it, so the item lands before it.
+ // Name the item actually after `left` as `right`, so every replica puts
+ // it where this one does.
+ if let (Some(l), Some(r)) = (left, right) {
+ let mut next = l.right;
+ while let Some(n) = next {
+ if n == r {
+ break;
+ }
+ next = n.right;
+ }
+ if next.is_none() {
+ right = l.right;
+ }
+ }
+
let next_clock = txn.store.get_local_state();
let next_id = ID::new(txn.store.client_id, next_clock);
let mut redone_item = Item::new(
@@ -406,9 +426,17 @@ impl ItemPtr {
redone_item.info.set_keep();
let mut block_ptr = ItemPtr::from(&mut redone_item);
- block_ptr.integrate(txn, 0);
+ // Local patch (see PATCHES.md, "Local inserts into a deleted parent"):
+ // integrate answers true when the parent is deleted (a restored parent a
+ // peer has since deleted). Yjs's Item.integrate and every peer receiving
+ // this item delete it then; dropping the answer left it live here alone.
+ // Deleted after it is stored, as Update::integrate does.
+ let should_delete = block_ptr.integrate(txn, 0);
txn.store_mut().blocks.push_block(redone_item);
+ if should_delete {
+ txn.delete(block_ptr);
+ }
Some(block_ptr)
}
@@ -1373,7 +1401,11 @@ impl Item {
}
pub(crate) fn gc(&mut self, collector: &mut GCCollector, parent_gc: bool) {
- if self.is_deleted() && !self.info.is_keep() {
+ // Backport of y-crdt 0e5df00 (see PATCHES.md): the keep flag is checked by
+ // the collector for top-level candidates only. Children of a collected
+ // type go with it whatever their flag, as in Yjs (ContentType.gc); a kept
+ // child left behind would point into its parent's freed branch.
+ if self.is_deleted() {
self.content.gc(collector);
let len = self.len();
if parent_gc {
diff --git a/native/vendor/yrs-0.23.5/src/block_iter.rs b/native/vendor/yrs-0.23.5/src/block_iter.rs
index a0b4e39..ae368da 100644
--- a/native/vendor/yrs-0.23.5/src/block_iter.rs
+++ b/native/vendor/yrs-0.23.5/src/block_iter.rs
@@ -489,9 +489,15 @@ impl BlockIter {
)?;
let mut block_ptr = ItemPtr::from(&mut block);
- block_ptr.integrate(txn, 0);
+ // Local patch (see PATCHES.md, "Local inserts into a deleted parent"):
+ // honour integrate's "delete me" for a parent that is deleted, as Yjs's
+ // Item.integrate and the remote path (Update::integrate) do.
+ let should_delete = block_ptr.integrate(txn, 0);
txn.store_mut().blocks.push_block(block);
+ if should_delete {
+ txn.delete(block_ptr);
+ }
if let Some(remainder) = remainder {
remainder.integrate(txn, inner_ref.unwrap().into())
diff --git a/native/vendor/yrs-0.23.5/src/gc.rs b/native/vendor/yrs-0.23.5/src/gc.rs
index 7844184..4a1ac80 100644
--- a/native/vendor/yrs-0.23.5/src/gc.rs
+++ b/native/vendor/yrs-0.23.5/src/gc.rs
@@ -37,7 +37,9 @@ impl GCCollector {
break;
} else {
if let BlockCell::Block(item) = block {
- item.gc(self, false);
+ if !item.info.is_keep() {
+ item.gc(self, false);
+ }
}
i += 1;
}
@@ -53,7 +55,9 @@ impl GCCollector {
for block in client_blocks.iter_mut() {
if let BlockCell::Block(item) = block {
if item.is_deleted() {
- item.gc(self, false);
+ if !item.info.is_keep() {
+ item.gc(self, false);
+ }
txn.merge_blocks.push(item.id);
}
}
@@ -75,7 +79,7 @@ impl GCCollector {
if let Some(index) = client.find_pivot(clock) {
let block = &mut client[index];
if let BlockCell::Block(item) = block {
- if item.is_deleted() && !item.info.is_keep() {
+ if item.is_deleted() {
let (start, end) = item.clock_range();
let gc = BlockCell::GC(GC::new(start, end));
*block = gc;
diff --git a/native/vendor/yrs-0.23.5/src/transaction.rs b/native/vendor/yrs-0.23.5/src/transaction.rs
index 8e767f2..34f5a16 100644
--- a/native/vendor/yrs-0.23.5/src/transaction.rs
+++ b/native/vendor/yrs-0.23.5/src/transaction.rs
@@ -897,9 +897,15 @@ impl<'doc> TransactionMut<'doc> {
)?;
let mut block_ptr = ItemPtr::from(&mut block);
- block_ptr.integrate(self, 0);
+ // Local patch (see PATCHES.md, "Local inserts into a deleted parent"):
+ // honour integrate's "delete me" for a parent that is deleted, as Yjs's
+ // Item.integrate and the remote path (Update::integrate) do.
+ let should_delete = block_ptr.integrate(self, 0);
self.store_mut().blocks.push_block(block);
+ if should_delete {
+ self.delete(block_ptr);
+ }
if let Some(remainder) = remainder {
remainder.integrate(self, inner_ref.unwrap().into())
diff --git a/native/vendor/yrs-0.23.5/src/undo.rs b/native/vendor/yrs-0.23.5/src/undo.rs
index 50e55aa..c429443 100644
--- a/native/vendor/yrs-0.23.5/src/undo.rs
+++ b/native/vendor/yrs-0.23.5/src/undo.rs
@@ -749,6 +749,10 @@ where
let mut result = None;
while let Some(item) = stack.pop() {
let mut to_redo = HashSet::<ItemPtr>::new();
+ // Local patch (see PATCHES.md, "Redo order"): redo in the order the
+ // deletions are found, as Yjs iterates its Set in insertion order. The
+ // HashSet alone made the order depend on the process's hash keys.
+ let mut redo_order = Vec::<ItemPtr>::new();
let mut to_delete = Vec::<ItemPtr>::new();
let mut change_performed = false;
@@ -775,12 +779,14 @@ where
&& !item.insertions.is_deleted(ptr.id())
// Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.
{
- to_redo.insert(ptr);
+ if to_redo.insert(ptr) {
+ redo_order.push(ptr);
+ }
}
}
}
- for &ptr in to_redo.iter() {
+ for &ptr in redo_order.iter() {
let mut ptr = ptr;
change_performed |= ptr
.redo(txn, &to_redo, &item.insertions, stack, other)