oficina / docs Public

Docs native engine: stronger convergence gates (review finding 8)

- Update wire gate: 19 command updates instead of 8, now with format,
  attribute, split, list_indent, autoformat and its reversal, two
  concurrent sources and undos after them. Yjs replays them in order
  (gc on and off) and compares state vector and delete set
  (Y.equalSnapshots), not only the text; and three more peers per gc
  mode take every update in their own shuffled order, a fifth of them
  twice, and must converge on the authority's final state.
- The projection delta test runs over several seeds (4 in the gate,
  DOCS_DELTA_SEEDS=1..100 locally: green), and tolerates a peer
  position inside an emoji.
- tests/convergence_fuzz.rs: Claude Fable's three-editor adversarial
  harness from the review (every command kind, shadow Yjs documents
  fed only the updates with gc on and off, delete sets, shuffled and
  duplicated delivery, deltas). Ignored until two fixes to the vendored
  yrs land, which this branch does not make: finding 1 (its own
  branch), and undo re-insertion into a deleted parent (Item::redo,
  create_item and BlockIter::insert_contents ignore integrate's "delete
  me"; seeds 76 and 113 show delete sets that differ while projections
  agree). With both patched locally, seeds 1..200 pass in both modes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev c4300c674912266c171cd5dba1796ecde89fae18 parent 6f95eb9
4 files changed, +276 −32
  • native/crdt/src/bin/update_wire_probe.rs +57 −23
  • native/crdt/tests/convergence_fuzz.rs +172 −0
  • native/crdt/tests/projection_delta.rs +18 −5
  • native/scripts/check-update-wire.mjs +29 −4
diff --git a/native/crdt/src/bin/update_wire_probe.rs b/native/crdt/src/bin/update_wire_probe.rs
index 50d7a9d..e760d02 100644
--- a/native/crdt/src/bin/update_wire_probe.rs
+++ b/native/crdt/src/bin/update_wire_probe.rs
@@ -73,33 +73,67 @@ fn main() {
std::fs::write(directory.join("base.bin"), authority.snapshot()).unwrap();
let total = length(&authority.projection());
let middle = total / 2;
- let mut steps: Vec<(Value, bool)> = vec![
- (json!({"op":"display_edit","at":middle,"length":0,"text":"x"}), true),
- (json!({"op":"display_edit","at":middle,"length":3,"text":""}), true),
- (json!({"op":"display_edit","at":middle,"length":0,"text":"line\nsplit\u{2028}break"}), true),
- (json!({"op":"display_edit","at":middle.saturating_sub(30),"length":60,"text":"joined"}), true),
- (json!({"op":"display_paste","at":5,"length":2,"blocks":[
+ // Each step: a command built from the authority's current projection,
+ // run on a fresh source (a new client, as each presentation makes) or,
+ // for undo and redo, on the authority. `Concurrent` runs two sources
+ // from the same state, so their updates are concurrent.
+ enum Step { Source(Value), Authority(Value), Concurrent(Value, Value) }
+ fn find(value: &Value, test: &dyn Fn(&Value) -> bool) -> Option<Value> {
+ if test(value) { return Some(value.clone()); }
+ value["children"].as_array().into_iter().flatten().find_map(|child| find(child, test))
+ }
+ let in_list = |p: &Value| find(p, &|v| v["type"] == "list_item").and_then(|item| find(&item, &|v| v["type"] == "paragraph")).map(|v| v["id"].clone());
+ let builders: Vec<Box<dyn Fn(&Value, u32) -> Step>> = vec![
+ Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":0,"text":"x"}))),
+ Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":3,"text":""}))),
+ Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":0,"text":"line\nsplit\u{2028}break"}))),
+ Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle.saturating_sub(30),"length":60,"text":"joined"}))),
+ Box::new(|_, _| Step::Source(json!({"op":"display_paste","at":5,"length":2,"blocks":[
{"type":"heading","attrs":{"level":"2"},"children":[{"type":"text","runs":[{"insert":"Pasted","marks":{"strong":{}}}]}]},
{"type":"bullet_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"Item","marks":{}}]}]}]}]}
- ]}), true),
- (json!({"op":"undo"}), false),
- (json!({"op":"redo"}), false),
+ ]}))),
+ Box::new(|_, _| Step::Authority(json!({"op":"undo"}))),
+ Box::new(|_, _| Step::Authority(json!({"op":"redo"}))),
+ Box::new(|p, _| Step::Source(json!({"op":"batch","commands":[{"op":"block","node":p["children"][0]["id"],"type":"ordered_list"}]}))),
+ Box::new(|p, _| Step::Source(json!({"op":"format","node":find(p, &|v| v["type"] == "text" && plain(v).encode_utf16().count() > 8).unwrap()["id"],"at":2,"length":5,"marks":{"em":{}}}))),
+ Box::new(|p, _| Step::Source(json!({"op":"attribute","node":find(p, &|v| v["type"] == "paragraph").unwrap()["id"],"name":"align","value":"center"}))),
+ Box::new(|p, _| Step::Source(json!({"op":"split","node":find(p, &|v| v["type"] == "text" && plain(v).encode_utf16().count() > 8).unwrap()["id"],"at":3}))),
+ Box::new(move |p, _| Step::Source(json!({"op":"list_indent","node":in_list(p).unwrap(),"delta":-1}))),
+ Box::new(|_, total| Step::Source(json!({"op":"display_edit","at":total - 1,"length":0,"text":"\n-"}))),
+ Box::new(|_, total| Step::Source(json!({"op":"display_autoformat","at":total - 2,"length":1,"kind":"bullet_list","level":0}))),
+ Box::new(|_, total| Step::Source(json!({"op":"display_revert_rule","at":total - 1,"kind":"bullet_list","prior_type":"paragraph","prior_attrs":{},"text":"- "}))),
+ Box::new(move |_, _| Step::Concurrent(json!({"op":"display_edit","at":middle,"length":0,"text":"left"}), json!({"op":"display_edit","at":middle,"length":4,"text":"right"}))),
+ Box::new(|_, _| Step::Authority(json!({"op":"undo"}))),
+ Box::new(|_, _| Step::Authority(json!({"op":"undo"}))),
];
- let p = authority.projection();
- let first = p["children"][0]["id"].clone();
- steps.push((json!({"op":"batch","commands":[{"op":"block","node":first,"type":"ordered_list"}]}), true));
let mut manifest = Vec::new();
- for (index, (command, from_source)) in steps.iter().enumerate() {
- let update = if *from_source {
- let mut source = Editor::new("update-wire", 9_200 + index as u64);
- source.apply(&authority.snapshot()).unwrap();
- let update = source.command(command).unwrap_or_else(|e| panic!("{command}: {e}"));
- authority.apply_local(&update).unwrap();
- update
- } else { authority.command(command).unwrap() };
- std::fs::write(directory.join(format!("{}.bin", index + 1)), &update).unwrap();
- std::fs::write(directory.join(format!("{}.snapshot", index + 1)), authority.snapshot()).unwrap();
- manifest.push(json!({"command": command["op"], "bytes": update.len()}));
+ let mut index = 0;
+ for (number, build) in builders.iter().enumerate() {
+ let projection = authority.projection();
+ let step = build(&projection, length(&projection));
+ let commands: Vec<(Value, bool)> = match step {
+ Step::Source(c) => vec![(c, true)],
+ Step::Authority(c) => vec![(c, false)],
+ Step::Concurrent(a, b) => vec![(a, true), (b, true)],
+ };
+ let snapshot = authority.snapshot();
+ let mut updates = Vec::new();
+ for (offset, (command, from_source)) in commands.iter().enumerate() {
+ let update = if *from_source {
+ // Concurrent sources both start from the state before either.
+ let mut source = Editor::new("update-wire", 9_200 + (number * 2 + offset) as u64);
+ source.apply(&snapshot).unwrap();
+ source.command(command).unwrap_or_else(|e| panic!("{command}: {e}"))
+ } else { authority.command(command).unwrap() };
+ updates.push((command.clone(), update));
+ }
+ for (command, update) in updates {
+ if command["op"] != "undo" && command["op"] != "redo" { authority.apply_local(&update).unwrap(); }
+ index += 1;
+ std::fs::write(directory.join(format!("{index}.bin")), &update).unwrap();
+ std::fs::write(directory.join(format!("{index}.snapshot")), authority.snapshot()).unwrap();
+ manifest.push(json!({"command": command["op"], "bytes": update.len()}));
+ }
}
std::fs::write(directory.join("manifest.json"), Value::Array(manifest).to_string()).unwrap();
std::fs::write(directory.join("keystroke-at.txt"), middle.to_string()).unwrap();
diff --git a/native/crdt/tests/convergence_fuzz.rs b/native/crdt/tests/convergence_fuzz.rs
new file mode 100644
index 0000000..d2e5155
--- /dev/null
+++ b/native/crdt/tests/convergence_fuzz.rs
@@ -0,0 +1,172 @@
+//! Three editors run every command kind against each other (Claude Fable's
+//! adversarial harness from the review on #145): each command's update is
+//! checked against shadow Yjs documents that see only those updates (gc on
+//! and off: state vector, delete set and projection), deliveries arrive in
+//! random order and sometimes twice, and projection deltas are replayed
+//! against the whole projection. A failed command is treated as CRDTReplica
+//! treats it: the writer is rebuilt from its last good state.
+mod support;
+use docs_native_crdt::Editor;
+use serde_json::{json, Value};
+use support::{generate, legacy_projection, oracle, Random};
+use yrs::updates::decoder::Decode;
+use yrs::{Doc, ReadTxn, StateVector, Transact, Update};
+
+fn open(bytes: &[u8], client: u64) -> Editor { let e = Editor::new("large-document", client); e.apply(bytes).unwrap(); e }
+fn shadow_doc(bytes: &[u8], client: u64, skip_gc: bool) -> Doc {
+ let mut o = yrs::Options::with_guid_and_client_id("large-document".into(), client);
+ o.offset_kind = yrs::OffsetKind::Utf16; o.skip_gc = skip_gc;
+ let d = Doc::with_options(o);
+ d.transact_mut().apply_update(Update::decode_v1(bytes).unwrap()).unwrap(); d
+}
+fn state(d: &Doc) -> Vec<u8> { d.transact().encode_state_as_update_v1(&StateVector::default()) }
+fn collect(v: &Value, ty: &[&str], out: &mut Vec<Value>) {
+ if ty.contains(&v["type"].as_str().unwrap_or("")) { out.push(v["id"].clone()); }
+ for c in v["children"].as_array().into_iter().flatten() { collect(c, ty, out); }
+}
+fn replay(children: &mut Vec<Value>, delta: &Value) {
+ assert_eq!(delta["base"].as_u64().unwrap() as usize, children.len());
+ let mut next = Vec::new(); let mut at = 0;
+ for op in delta["ops"].as_array().unwrap() {
+ if let Some(n) = op["keep"].as_u64() { next.extend_from_slice(&children[at..at + n as usize]); at += n as usize; }
+ else if let Some(n) = op["remove"].as_u64() { at += n as usize; }
+ else { next.extend(op["insert"].as_array().unwrap().iter().cloned()); }
+ }
+ assert_eq!(at, children.len()); assert_eq!(next.len(), delta["count"].as_u64().unwrap() as usize);
+ *children = next;
+}
+fn ds(u: &Update) -> std::collections::BTreeMap<u64, String> { u.delete_set().iter().map(|(c, r)| (*c, format!("{:?}", r))).collect() }
+fn pick(r: &mut Random, v: &[Value]) -> Value { if v.is_empty() { Value::Null } else { v[r.below(v.len() as u64) as usize].clone() } }
+
+fn run(seed: u64, steps: usize, in_order: bool) -> (usize, usize, std::collections::BTreeMap<String,(usize,usize)>) {
+ let base = generate(2, 80, seed);
+ let n = 3;
+ let mut editors: Vec<Editor> = (0..n).map(|i| open(&base, 1000 + i as u64)).collect();
+ let shadows: Vec<Doc> = (0..n).map(|i| shadow_doc(&base, 2000 + i as u64, false)).collect();
+ let nogc: Vec<Doc> = (0..n).map(|i| shadow_doc(&base, 3000 + i as u64, true)).collect();
+ let mut inbox: Vec<Vec<Vec<u8>>> = vec![Vec::new(); n];
+ let mut r = Random::new(seed * 77 + 5);
+ let mut children: Vec<Vec<Value>> = editors.iter().map(|e| e.projection()["children"].as_array().unwrap().clone()).collect();
+ let mut partial = 0; let mut next_client = 5000u64;
+ let mut stats = std::collections::BTreeMap::<String,(usize,usize)>::new();
+ let mut multi = 0;
+ for step in 0..steps {
+ let i = r.below(n as u64) as usize;
+ let before = editors[i].snapshot();
+ let p = legacy_projection(&before);
+ let (_, total) = oracle(&p);
+ let at = r.below(total as u64 + 1) as u32;
+ let mut texts = vec![]; collect(&p, &["text"], &mut texts);
+ let mut blocks = vec![]; collect(&p, &["paragraph","heading","code_block","list_item","bullet_list","ordered_list","blockquote"], &mut blocks);
+ let mut leaves = vec![]; collect(&p, &["paragraph","heading"], &mut leaves);
+ let types = ["paragraph","heading","bullet_list","ordered_list","blockquote","code_block"];
+ let command = match r.below(22) {
+ 0 | 1 | 2 => json!({"op":"display_edit","at":at,"length":0,"text":(["x","héllo","😀"," a\nb","\n","\n\n- "][r.below(6) as usize])}),
+ 3 | 4 => json!({"op":"display_edit","at":at,"length":r.below(4),"text":""}),
+ 5 => json!({"op":"display_edit","at":at,"length":r.below(700),"text":(["","Z","q\nr"][r.below(3) as usize])}),
+ 6 => json!({"op":"display_paste","at":at,"length":r.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 r,&leaves),"type":types[r.below(6) as usize],"level":1 + r.below(3)}),
+ 12 => json!({"op":"attribute","node":pick(&mut r,&blocks),"name":"align","value":(["center","right"][r.below(2) as usize])}),
+ 13 | 14 => json!({"op":"format","node":pick(&mut r,&texts),"at":r.below(20),"length":1 + r.below(30),"marks":{"strong":{}}}),
+ 15 => json!({"op":"list_indent","node":pick(&mut r,&leaves),"delta":if r.below(2)==0 {1} else {-1}}),
+ 16 => json!({"op":"split","node":pick(&mut r,&texts),"at":r.below(40)}),
+ 17 => json!({"op":"hard_break","node":pick(&mut r,&texts),"at":r.below(40)}),
+ 18 => json!({"op":"display_autoformat","at":at,"length":r.below(3),"kind":(["bullet_list","heading","blockquote","ordered_list"][r.below(4) as usize]),"level":1}),
+ 19 => json!({"op":"display_exit_list","at":at}),
+ 20 => json!({"op":"batch","commands":[
+ {"op":"block","node":pick(&mut r,&leaves),"type":types[r.below(6) as usize],"level":2},
+ {"op":"block","node":pick(&mut r,&leaves),"type":types[r.below(6) as usize],"level":2},
+ {"op":"display_edit","at":at,"length":r.below(3),"text":"B"}]}),
+ _ => json!({"op":"display_edit","at":at,"length":r.below(60),"text":"\n"}),
+ };
+ let op = command["op"].as_str().unwrap().to_owned();
+ match editors[i].command(&command) {
+ Ok(update) => {
+ stats.entry(op).or_default().0 += 1;
+ let u = Update::decode_v1(&update).unwrap();
+ let _ = u;
+ shadows[i].transact_mut().apply_update(Update::decode_v1(&update).unwrap()).unwrap();
+ nogc[i].transact_mut().apply_update(Update::decode_v1(&update).unwrap()).unwrap();
+ for j in 0..n { if j != i { inbox[j].push(update.clone()); } }
+ if update.len() > 2 { multi += 1; }
+ },
+ Err(_) => {
+ stats.entry(op).or_default().1 += 1;
+ if editors[i].snapshot() != before {
+ partial += 1;
+ // as Swift does: rebuild the writer from its last good state
+ next_client += 1;
+ editors[i] = open(&state(&shadows[i]), next_client);
+ children[i] = editors[i].projection()["children"].as_array().unwrap().clone();
+ }
+ },
+ }
+ // deliver some messages, in random order, sometimes duplicated
+ for j in 0..n {
+ let k = r.below(4) as usize;
+ for _ in 0..k {
+ if inbox[j].is_empty() { break; }
+ let idx = if in_order { 0 } else { r.below(inbox[j].len() as u64) as usize };
+ let m = if !in_order && r.below(10) == 0 { inbox[j][idx].clone() } else { inbox[j].remove(idx) };
+ editors[j].apply(&m).unwrap();
+ shadows[j].transact_mut().apply_update(Update::decode_v1(&m).unwrap()).unwrap();
+ nogc[j].transact_mut().apply_update(Update::decode_v1(&m).unwrap()).unwrap();
+ }
+ }
+ for j in 0..n {
+ let eu = Update::decode_v1(&editors[j].snapshot()).unwrap(); let su = Update::decode_v1(&state(&shadows[j])).unwrap();
+ assert_eq!(eu.state_vector(), su.state_vector(), "seed {seed} step {step} e{j}: state vectors {command}");
+ assert_eq!(ds(&eu), ds(&su), "seed {seed} step {step} e{j}: delete sets {command}");
+ let truth = legacy_projection(&editors[j].snapshot());
+ let sh = legacy_projection(&state(&shadows[j]));
+ assert_eq!(truth, sh, "seed {seed} step {step} editor {j}: shadow (own updates only) differs after {command}");
+ let ng = legacy_projection(&state(&nogc[j]));
+ assert_eq!(truth, ng, "seed {seed} step {step} editor {j}: nogc shadow differs after {command}");
+ if r.below(3) != 0 {
+ let d = editors[j].projection_delta();
+ replay(&mut children[j], &d);
+ assert_eq!(Value::Array(children[j].clone()), truth["children"], "seed {seed} step {step} editor {j}: delta differs after {command}");
+ }
+ }
+ }
+ for j in 0..n { for m in std::mem::take(&mut inbox[j]) { editors[j].apply(&m).unwrap(); } }
+ let first = legacy_projection(&editors[0].snapshot());
+ for j in 1..n { assert_eq!(first, legacy_projection(&editors[j].snapshot()), "seed {seed}: editors diverged at the end"); }
+ (partial, multi, stats)
+}
+
+/// Seeds and steps: a bounded run in the gate, more with
+/// DOCS_FUZZ_SEEDS=1..200 (or one seed, DOCS_FUZZ_SEEDS=39) locally.
+fn seeds() -> std::ops::RangeInclusive<u64> {
+ match std::env::var("DOCS_FUZZ_SEEDS") {
+ Ok(v) => match v.split_once("..") { Some((a, b)) => a.parse().unwrap()..=b.parse().unwrap(), None => { let s = v.parse().unwrap(); s..=s } },
+ Err(_) => 1..=6,
+ }
+}
+fn fuzz(in_order: bool) {
+ let mut total = std::collections::BTreeMap::<String,(usize,usize)>::new();
+ let mut partial = 0;
+ for seed in seeds() { let (p, _m, s) = run(seed, 150, in_order); partial += p; for (k,(a,b)) in s { let e = total.entry(k).or_default(); e.0 += a; e.1 += b; } }
+ eprintln!("partial-mutation-on-error: {partial}; ok/err per op: {total:?}");
+ for op in ["display_edit", "display_paste", "undo", "format", "block", "split"] { assert!(total.get(op).is_some_and(|(ok, _)| *ok > 0), "{op} never succeeded: {total:?}"); }
+}
+// Ignored until two fixes to the vendored yrs land (they are not this
+// branch's to make): an undo-kept item under a collected parent (review
+// finding 1, its own branch), and Item::redo / create_item /
+// BlockIter::insert_contents ignoring `integrate`'s "delete me" for an item
+// put into a deleted parent, so an undo's re-insertion into a paragraph a
+// peer deleted is live in the editor and deleted at every peer (seeds 76 and
+// 113: delete sets differ, projections agree). With both patched, seeds
+// 1..200 pass in both modes. Run: cargo test --test convergence_fuzz -- --ignored
+const NEEDS: &str = "needs the vendored-yrs fixes described above";
+#[test]
+#[ignore = "needs the vendored-yrs fixes described above"]
+fn three_editors_converge_with_shuffled_duplicated_delivery() { let _ = NEEDS; fuzz(false) }
+#[test]
+#[ignore = "needs the vendored-yrs fixes described above"]
+fn three_editors_converge_with_causal_delivery() { fuzz(true) }
diff --git a/native/crdt/tests/projection_delta.rs b/native/crdt/tests/projection_delta.rs
index a302859..95c8a82 100644
--- a/native/crdt/tests/projection_delta.rs
+++ b/native/crdt/tests/projection_delta.rs
@@ -45,14 +45,24 @@ fn typing_reprojects_only_the_block_typed_in() {
assert_eq!(unchanged["ops"], json!([{"keep": unchanged["count"]}]));
}
+/// Seeds: a bounded run in the gate; DOCS_DELTA_SEEDS=1..100 locally.
+fn seeds() -> std::ops::RangeInclusive<u64> {
+ match std::env::var("DOCS_DELTA_SEEDS") {
+ Ok(v) => match v.split_once("..") { Some((a, b)) => a.parse().unwrap()..=b.parse().unwrap(), None => { let s = v.parse().unwrap(); s..=s } },
+ Err(_) => 1..=4,
+ }
+}
#[test]
fn deltas_replay_to_the_whole_projection_through_every_kind_of_change() {
- let base = generate(6, 400, 22);
+ for seed in seeds() { deltas_replay(seed); }
+}
+fn deltas_replay(seed: u64) {
+ let base = generate(6, 400, 20 + seed);
let mut authority = open(&base, 601);
let peers: Vec<Editor> = (0..3).map(|i| open(&base, 610 + i)).collect();
let mut peers = peers;
let mut children = authority.projection()["children"].as_array().unwrap().clone();
- let mut random = Random::new(9);
+ let mut random = Random::new(seed * 7 + 2);
let mut applied = std::collections::HashMap::<String, usize>::new();
for step in 0..160 {
let p = json!({"children": children.clone()});
@@ -81,16 +91,19 @@ fn deltas_replay_to_the_whole_projection_through_every_kind_of_change() {
let (peer_ranges, _) = oracle(&peer_p);
let peer_texts: Vec<_> = peer_ranges.iter().filter(|r| !r.atomic && r.length > 0).collect();
let peer_span = peer_texts[random.below(peer_texts.len() as u64) as usize];
- let remote = peer.command(&json!({"op":"display_edit","at":peer_span.start + 1,"length":if step % 4 == 0 { 1 } else { 0 },"text":"p"})).unwrap();
+ // A position inside an emoji is refused; the peer then edits at the
+ // text's start, which is always a boundary.
+ let remote = peer.command(&json!({"op":"display_edit","at":peer_span.start + 1,"length":if step % 4 == 0 { 1 } else { 0 },"text":"p"}))
+ .or_else(|_| peer.command(&json!({"op":"display_edit","at":peer_span.start,"length":0,"text":"p"}))).unwrap();
authority.apply(&remote).unwrap();
if let Ok(update) = local { for peer in &peers { peer.apply(&update).unwrap(); } }
for other in peers.iter().enumerate().filter(|(i, _)| *i != step % 3).map(|(_, p)| p) { other.apply(&remote).unwrap(); }
if step % 5 != 4 {
replay(&mut children, &authority.projection_delta());
- assert_eq!(Value::Array(children.clone()), truth(&authority), "step {step}: {command}");
+ assert_eq!(Value::Array(children.clone()), truth(&authority), "seed {seed} step {step}: {command}");
}
}
- for op in ["display_edit", "display_paste", "undo", "redo", "block", "attribute"] { assert!(applied.get(op).copied().unwrap_or(0) >= 5, "{op} ran: {applied:?}"); }
+ for op in ["display_edit", "display_paste", "undo", "redo", "block", "attribute"] { assert!(applied.get(op).copied().unwrap_or(0) >= 3, "seed {seed}: {op} ran: {applied:?}"); }
let delta = authority.projection_delta();
assert_eq!(delta["canUndo"], authority.projection()["canUndo"]);
}
diff --git a/native/scripts/check-update-wire.mjs b/native/scripts/check-update-wire.mjs
index b420015..b7d3c41 100644
--- a/native/scripts/check-update-wire.mjs
+++ b/native/scripts/check-update-wire.mjs
@@ -17,20 +17,45 @@ const deleted = update => {
for (const ranges of Y.decodeUpdate(update).ds.clients.values()) for (const r of ranges) units += r.len
return units
}
+// Same deletions, same items: the state vector and the delete set together
+// (Y.snapshot), not only the rendered text.
+const same = (a, b) => Y.equalSnapshots(Y.snapshot(a), Y.snapshot(b))
+let seed = 7
+const random = n => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed % n }
let comparisons = 0
for (const gc of [true, false]) {
+ // In order: after each command's update alone, the peer equals the authority.
const doc = new Y.Doc({ gc })
Y.applyUpdate(doc, read('base.bin'))
for (let step = 1; step <= manifest.length; step++) {
Y.applyUpdate(doc, read(step + '.bin'))
const snapshot = new Y.Doc({ gc })
Y.applyUpdate(snapshot, read(step + '.snapshot'))
- assert.equal(doc.getXmlFragment('prosemirror').toString(), snapshot.getXmlFragment('prosemirror').toString(), `gc=${gc}, step=${step} (${manifest[step - 1].command})`)
- assert.deepEqual(Y.encodeStateVector(doc), Y.encodeStateVector(snapshot), `state vector, gc=${gc}, step=${step}`)
+ const label = `gc=${gc}, step=${step} (${manifest[step - 1].command})`
+ assert.equal(doc.getXmlFragment('prosemirror').toString(), snapshot.getXmlFragment('prosemirror').toString(), label)
+ assert.ok(same(doc, snapshot), `state vector and delete set, ${label}`)
comparisons++
snapshot.destroy()
}
- doc.destroy()
+ // Out of order and duplicated: three more peers each get every update in
+ // their own shuffled order, a fifth of them twice, and must converge on
+ // the authority's final state.
+ const final = new Y.Doc({ gc })
+ Y.applyUpdate(final, read(manifest.length + '.snapshot'))
+ for (let peer = 0; peer < 3; peer++) {
+ const updates = manifest.map((_, i) => read((i + 1) + '.bin'))
+ for (let i = 0; i < manifest.length; i++) if (random(5) === 0) updates.push(updates[i])
+ for (let i = updates.length - 1; i > 0; i--) { const j = random(i + 1); [updates[i], updates[j]] = [updates[j], updates[i]] }
+ const shuffled = new Y.Doc({ gc })
+ Y.applyUpdate(shuffled, read('base.bin'))
+ for (const update of updates) Y.applyUpdate(shuffled, update)
+ assert.equal(shuffled.getXmlFragment('prosemirror').toString(), final.getXmlFragment('prosemirror').toString(), `shuffled peer ${peer}, gc=${gc}`)
+ assert.ok(same(shuffled, final), `shuffled peer ${peer}, gc=${gc}: state vector and delete set`)
+ comparisons++
+ shuffled.destroy()
+ }
+ assert.ok(same(doc, final))
+ doc.destroy(); final.destroy()
}
const base = new Y.Doc()
Y.applyUpdate(base, read('base.bin'))
@@ -65,4 +90,4 @@ browser.transact(() => { text.insert(0, 'browser ') })
updates.forEach((update, index) => fs.writeFileSync(path.join(directory, `browser-${index}.bin`), update))
const plain = node => node instanceof Y.XmlText ? node.toDelta().map(d => typeof d.insert === 'string' ? d.insert : '').join('') : node.toArray().map(plain).join('')
fs.writeFileSync(path.join(directory, 'browser-text.txt'), plain(browser.getXmlFragment('prosemirror')))
-console.log(`Update wire replay passed ${comparisons} per-command comparisons; keystroke ${keystroke.length} B (browser ${updates[0].length} B, a state-vector diff would be ${legacy} B).`)
+console.log(`Update wire replay passed ${comparisons} comparisons (${manifest.length} commands in order, and shuffled with duplicates, gc on and off); keystroke ${keystroke.length} B (browser ${updates[0].length} B, a state-vector diff would be ${legacy} B).`)