| 1 | //! Three editors run every command kind against each other (Claude Fable's |
| 2 | //! adversarial harness from the review on #145): each command's update is |
| 3 | //! checked against shadow Yjs documents that see only those updates (gc on |
| 4 | //! and off: state vector, delete set and projection), deliveries arrive in |
| 5 | //! random order and sometimes twice, and projection deltas are replayed |
| 6 | //! against the whole projection. A failed command is treated as CRDTReplica |
| 7 | //! treats it: the writer is rebuilt from its last good state. |
| 8 | mod support; |
| 9 | use docs_native_crdt::Editor; |
| 10 | use serde_json::{json, Value}; |
| 11 | use support::{generate, legacy_projection, oracle, Random}; |
| 12 | use yrs::updates::decoder::Decode; |
| 13 | use yrs::{Doc, ReadTxn, StateVector, Transact, Update}; |
| 14 | |
| 15 | fn open(bytes: &[u8], client: u64) -> Editor { let e = Editor::new("large-document", client); e.apply(bytes).unwrap(); e } |
| 16 | fn shadow_doc(bytes: &[u8], client: u64, skip_gc: bool) -> Doc { |
| 17 | let mut o = yrs::Options::with_guid_and_client_id("large-document".into(), client); |
| 18 | o.offset_kind = yrs::OffsetKind::Utf16; o.skip_gc = skip_gc; |
| 19 | let d = Doc::with_options(o); |
| 20 | d.transact_mut().apply_update(Update::decode_v1(bytes).unwrap()).unwrap(); d |
| 21 | } |
| 22 | fn state(d: &Doc) -> Vec<u8> { d.transact().encode_state_as_update_v1(&StateVector::default()) } |
| 23 | fn collect(v: &Value, ty: &[&str], out: &mut Vec<Value>) { |
| 24 | if ty.contains(&v["type"].as_str().unwrap_or("")) { out.push(v["id"].clone()); } |
| 25 | for c in v["children"].as_array().into_iter().flatten() { collect(c, ty, out); } |
| 26 | } |
| 27 | fn replay(children: &mut Vec<Value>, delta: &Value) { |
| 28 | assert_eq!(delta["base"].as_u64().unwrap() as usize, children.len()); |
| 29 | let mut next = Vec::new(); let mut at = 0; |
| 30 | for op in delta["ops"].as_array().unwrap() { |
| 31 | if let Some(n) = op["keep"].as_u64() { next.extend_from_slice(&children[at..at + n as usize]); at += n as usize; } |
| 32 | else if let Some(n) = op["remove"].as_u64() { at += n as usize; } |
| 33 | else { next.extend(op["insert"].as_array().unwrap().iter().cloned()); } |
| 34 | } |
| 35 | assert_eq!(at, children.len()); assert_eq!(next.len(), delta["count"].as_u64().unwrap() as usize); |
| 36 | *children = next; |
| 37 | } |
| 38 | fn ds(u: &Update) -> std::collections::BTreeMap<u64, String> { u.delete_set().iter().map(|(c, r)| (*c, format!("{:?}", r))).collect() } |
| 39 | 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() } } |
| 40 | |
| 41 | fn run(seed: u64, steps: usize, in_order: bool) -> (usize, usize, std::collections::BTreeMap<String,(usize,usize)>) { |
| 42 | let base = generate(2, 80, seed); |
| 43 | let n = 3; |
| 44 | let mut editors: Vec<Editor> = (0..n).map(|i| open(&base, 1000 + i as u64)).collect(); |
| 45 | let shadows: Vec<Doc> = (0..n).map(|i| shadow_doc(&base, 2000 + i as u64, false)).collect(); |
| 46 | let nogc: Vec<Doc> = (0..n).map(|i| shadow_doc(&base, 3000 + i as u64, true)).collect(); |
| 47 | let mut inbox: Vec<Vec<Vec<u8>>> = vec![Vec::new(); n]; |
| 48 | let mut r = Random::new(seed * 77 + 5); |
| 49 | let mut children: Vec<Vec<Value>> = editors.iter().map(|e| e.projection()["children"].as_array().unwrap().clone()).collect(); |
| 50 | let mut partial = 0; let mut next_client = 5000u64; |
| 51 | let mut stats = std::collections::BTreeMap::<String,(usize,usize)>::new(); |
| 52 | let mut multi = 0; |
| 53 | for step in 0..steps { |
| 54 | let i = r.below(n as u64) as usize; |
| 55 | let before = editors[i].snapshot(); |
| 56 | let p = legacy_projection(&before); |
| 57 | let (_, total) = oracle(&p); |
| 58 | let at = r.below(total as u64 + 1) as u32; |
| 59 | let mut texts = vec![]; collect(&p, &["text"], &mut texts); |
| 60 | let mut blocks = vec![]; collect(&p, &["paragraph","heading","code_block","list_item","bullet_list","ordered_list","blockquote"], &mut blocks); |
| 61 | let mut leaves = vec![]; collect(&p, &["paragraph","heading"], &mut leaves); |
| 62 | let types = ["paragraph","heading","bullet_list","ordered_list","blockquote","code_block"]; |
| 63 | let command = match r.below(22) { |
| 64 | 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])}), |
| 65 | 3 | 4 => json!({"op":"display_edit","at":at,"length":r.below(4),"text":""}), |
| 66 | 5 => json!({"op":"display_edit","at":at,"length":r.below(700),"text":(["","Z","q\nr"][r.below(3) as usize])}), |
| 67 | 6 => json!({"op":"display_paste","at":at,"length":r.below(30),"blocks":[ |
| 68 | {"type":"paragraph","children":[{"type":"text","runs":[{"insert":"pasted","marks":{"em":{}}}]},{"type":"hard_break"},{"type":"text","runs":[{"insert":"more","marks":{}}]}]}, |
| 69 | {"type":"horizontal_rule"}, |
| 70 | {"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":{}}]}]}]}]}]}]}]}), |
| 71 | 7 | 8 => json!({"op":"undo"}), |
| 72 | 9 => json!({"op":"redo"}), |
| 73 | 10 | 11 => json!({"op":"block","node":pick(&mut r,&leaves),"type":types[r.below(6) as usize],"level":1 + r.below(3)}), |
| 74 | 12 => json!({"op":"attribute","node":pick(&mut r,&blocks),"name":"align","value":(["center","right"][r.below(2) as usize])}), |
| 75 | 13 | 14 => json!({"op":"format","node":pick(&mut r,&texts),"at":r.below(20),"length":1 + r.below(30),"marks":{"strong":{}}}), |
| 76 | 15 => json!({"op":"list_indent","node":pick(&mut r,&leaves),"delta":if r.below(2)==0 {1} else {-1}}), |
| 77 | 16 => json!({"op":"split","node":pick(&mut r,&texts),"at":r.below(40)}), |
| 78 | 17 => json!({"op":"hard_break","node":pick(&mut r,&texts),"at":r.below(40)}), |
| 79 | 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}), |
| 80 | 19 => json!({"op":"display_exit_list","at":at}), |
| 81 | 20 => json!({"op":"batch","commands":[ |
| 82 | {"op":"block","node":pick(&mut r,&leaves),"type":types[r.below(6) as usize],"level":2}, |
| 83 | {"op":"block","node":pick(&mut r,&leaves),"type":types[r.below(6) as usize],"level":2}, |
| 84 | {"op":"display_edit","at":at,"length":r.below(3),"text":"B"}]}), |
| 85 | _ => json!({"op":"display_edit","at":at,"length":r.below(60),"text":"\n"}), |
| 86 | }; |
| 87 | let op = command["op"].as_str().unwrap().to_owned(); |
| 88 | match editors[i].command(&command) { |
| 89 | Ok(update) => { |
| 90 | stats.entry(op).or_default().0 += 1; |
| 91 | let u = Update::decode_v1(&update).unwrap(); |
| 92 | let _ = u; |
| 93 | shadows[i].transact_mut().apply_update(Update::decode_v1(&update).unwrap()).unwrap(); |
| 94 | nogc[i].transact_mut().apply_update(Update::decode_v1(&update).unwrap()).unwrap(); |
| 95 | for j in 0..n { if j != i { inbox[j].push(update.clone()); } } |
| 96 | if update.len() > 2 { multi += 1; } |
| 97 | }, |
| 98 | Err(_) => { |
| 99 | stats.entry(op).or_default().1 += 1; |
| 100 | if editors[i].snapshot() != before { |
| 101 | partial += 1; |
| 102 | // as Swift does: rebuild the writer from its last good state |
| 103 | next_client += 1; |
| 104 | editors[i] = open(&state(&shadows[i]), next_client); |
| 105 | children[i] = editors[i].projection()["children"].as_array().unwrap().clone(); |
| 106 | } |
| 107 | }, |
| 108 | } |
| 109 | // deliver some messages, in random order, sometimes duplicated |
| 110 | for j in 0..n { |
| 111 | let k = r.below(4) as usize; |
| 112 | for _ in 0..k { |
| 113 | if inbox[j].is_empty() { break; } |
| 114 | let idx = if in_order { 0 } else { r.below(inbox[j].len() as u64) as usize }; |
| 115 | let m = if !in_order && r.below(10) == 0 { inbox[j][idx].clone() } else { inbox[j].remove(idx) }; |
| 116 | editors[j].apply(&m).unwrap(); |
| 117 | shadows[j].transact_mut().apply_update(Update::decode_v1(&m).unwrap()).unwrap(); |
| 118 | nogc[j].transact_mut().apply_update(Update::decode_v1(&m).unwrap()).unwrap(); |
| 119 | } |
| 120 | } |
| 121 | for j in 0..n { |
| 122 | let eu = Update::decode_v1(&editors[j].snapshot()).unwrap(); let su = Update::decode_v1(&state(&shadows[j])).unwrap(); |
| 123 | assert_eq!(eu.state_vector(), su.state_vector(), "seed {seed} step {step} e{j}: state vectors {command}"); |
| 124 | assert_eq!(ds(&eu), ds(&su), "seed {seed} step {step} e{j}: delete sets {command}"); |
| 125 | let truth = legacy_projection(&editors[j].snapshot()); |
| 126 | let sh = legacy_projection(&state(&shadows[j])); |
| 127 | assert_eq!(truth, sh, "seed {seed} step {step} editor {j}: shadow (own updates only) differs after {command}"); |
| 128 | let ng = legacy_projection(&state(&nogc[j])); |
| 129 | assert_eq!(truth, ng, "seed {seed} step {step} editor {j}: nogc shadow differs after {command}"); |
| 130 | if r.below(3) != 0 { |
| 131 | let d = editors[j].projection_delta(); |
| 132 | replay(&mut children[j], &d); |
| 133 | assert_eq!(Value::Array(children[j].clone()), truth["children"], "seed {seed} step {step} editor {j}: delta differs after {command}"); |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | for j in 0..n { for m in std::mem::take(&mut inbox[j]) { editors[j].apply(&m).unwrap(); } } |
| 138 | let first = legacy_projection(&editors[0].snapshot()); |
| 139 | for j in 1..n { assert_eq!(first, legacy_projection(&editors[j].snapshot()), "seed {seed}: editors diverged at the end"); } |
| 140 | (partial, multi, stats) |
| 141 | } |
| 142 | |
| 143 | /// Seeds and steps: a bounded run in the gate, more with |
| 144 | /// DOCS_FUZZ_SEEDS=1..200 (or one seed, DOCS_FUZZ_SEEDS=39) locally. |
| 145 | fn seeds() -> std::ops::RangeInclusive<u64> { |
| 146 | match std::env::var("DOCS_FUZZ_SEEDS") { |
| 147 | Ok(v) => match v.split_once("..") { Some((a, b)) => a.parse().unwrap()..=b.parse().unwrap(), None => { let s = v.parse().unwrap(); s..=s } }, |
| 148 | Err(_) => 1..=6, |
| 149 | } |
| 150 | } |
| 151 | fn fuzz(in_order: bool) { |
| 152 | let mut total = std::collections::BTreeMap::<String,(usize,usize)>::new(); |
| 153 | let mut partial = 0; |
| 154 | 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; } } |
| 155 | eprintln!("partial-mutation-on-error: {partial}; ok/err per op: {total:?}"); |
| 156 | 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:?}"); } |
| 157 | } |
| 158 | // The vendored yrs fixes it needed are on main (0819fa1, #147): an |
| 159 | // undo-kept item under a collected parent, and an undo's re-insertion into a |
| 160 | // parent a peer deleted. Seeds 1..6 in the gate; DOCS_FUZZ_SEEDS=1..500 |
| 161 | // locally. |
| 162 | #[test] |
| 163 | fn three_editors_converge_with_shuffled_duplicated_delivery() { fuzz(false) } |
| 164 | #[test] |
| 165 | fn three_editors_converge_with_causal_delivery() { fuzz(true) } |
| 166 | |