//! 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::{projection_of, 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 { 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 = (0..12).map(|_| (0..6 + random.below(20)).map(|_| WORDS[random.below(WORDS.len() as u64) as usize]).collect::>().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 = (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) { 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 { 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 { 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 { let trace = std::env::var("GC_UNDO_KEPT_TRACE").is_ok(); let base = generate(seed); let n = 3; let mut editors: Vec = (0..n).map(|i| open(&base, 1000 + i as u64)).collect(); let gc: Vec = (0..n).map(|i| plain_doc(&base, 2000 + i as u64, false)).collect(); let nogc: Vec = (0..n).map(|i| plain_doc(&base, 3000 + i as u64, true)).collect(); let mut inbox: Vec>> = vec![Vec::new(); n]; let mut random = Random::new(seed * 77 + 5); let mut next_client = 5000u64; let mut stats = BTreeMap::::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"); // Each plain peer's own display, as it integrated the updates // one by one, not only a fresh integration of its state. assert_eq!(projection_of(&gc[j])["children"], shown, "{context}: plain yrs (gc on) shows otherwise"); assert_eq!(projection_of(&nogc[j])["children"], shown, "{context}: plain yrs (gc off) shows otherwise"); } } 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 } /// The gate's seeds: 1 to 6, plus seeds that catch a yrs patch reverted /// (PATCHES.md): 53 the redo delete (causal), 60 the same (shuffled), 98 the /// redo origins (causal). insert_into_deleted_parent.rs covers each directly. fn seeds(in_order: bool) -> Vec { 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()).collect() }, Err(_) => (1..=6).chain(if in_order { vec![53, 98] } else { vec![60] }).collect(), } } 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::::new(); for seed in seeds(in_order) { 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(in_order), steps()); } #[test] fn three_editors_with_undo_in_causal_order() { fuzz(true); } #[test] fn three_editors_with_undo_shuffled_and_duplicated() { fuzz(false); }