oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1//! Fuzz for the undo-kept GC bug (oficina/docs #145, finding 1; see
2//! gc_undo_kept.rs), after Claude Fable's review harness: three editors run
3//! random commands, undo and redo included, and exchange only each command's
4//! update, delivered late, out of order and sometimes twice. After every step
5//! each editor is checked against plain yrs documents that received only
6//! those updates (gc on and off), and its snapshot must integrate whole into a
7//! fresh document and show exactly what the editor shows. At the end all
8//! three converge.
9//!
10//! The gate runs a bounded set of seeds. For a long run:
11//! GC_UNDO_KEPT_SEEDS=1-400 GC_UNDO_KEPT_STEPS=150 cargo test --release \
12//! --manifest-path native/crdt/Cargo.toml --test gc_undo_kept_fuzz
13//! GC_UNDO_KEPT_TRACE=1 prints each command.
14use docs_native_crdt::{projection_of, Editor};
15use serde_json::{json, Value};
16use std::collections::BTreeMap;
17use yrs::updates::decoder::Decode;
18use yrs::{Doc, ReadTxn, StateVector, Transact, Update};
19
20const GUID: &str = "gc-undo-kept";
21
22struct Random(u64);
23impl Random {
24 fn new(seed: u64) -> Self { Random(seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407)) }
25 fn next(&mut self) -> u64 {
26 self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
27 let mut x = self.0; x ^= x >> 33; x = x.wrapping_mul(0xff51afd7ed558ccd); x ^= x >> 33; x
28 }
29 fn below(&mut self, n: u64) -> u64 { if n == 0 { 0 } else { self.next() % n } }
30}
31
32const WORDS: &[&str] = &["the","of","and","to","in","is","that","for","it","as","was","with","be","by","on","not","this","naïve","café","😀"];
33
34/// A few pages: paragraphs, headings and a list, written by one client and
35/// then edited by three more, so the base carries tombstones.
36fn generate(seed: u64) -> Vec<u8> {
37 let mut random = Random::new(seed);
38 let mut author = Editor::new(GUID, 7_000);
39 author.command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap();
40 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();
41 author.command(&json!({"op":"display_edit","at":0,"length":0,"text":paragraphs.join("\n")})).unwrap();
42 let mut leaves = vec![]; collect(&author.projection(), &["paragraph"], &mut leaves);
43 for (i, node) in leaves.iter().enumerate() {
44 match i % 6 {
45 0 => { author.command(&json!({"op":"block","node":node,"type":"heading","level":2})).unwrap(); },
46 3 | 4 => { author.command(&json!({"op":"block","node":node,"type":"bullet_list","level":1})).ok(); },
47 _ => {},
48 }
49 }
50 let base = author.snapshot();
51 let mut editors: Vec<Editor> = (0..3).map(|i| { let e = Editor::new(GUID, 7_001 + i); e.apply(&base).unwrap(); e }).collect();
52 for round in 0..10 {
53 let mut updates = vec![];
54 for editor in editors.iter_mut() {
55 let total = display_length(&editor.projection());
56 let at = random.below(total as u64 + 1);
57 let command = if random.below(3) == 0 { json!({"op":"display_edit","at":at,"length":1 + random.below(4),"text":""}) }
58 else { json!({"op":"display_edit","at":at,"length":0,"text":format!("e{round}")}) };
59 if let Ok(update) = editor.command(&command) { updates.push(update); }
60 }
61 for editor in &editors { for update in &updates { editor.apply(update).unwrap(); } }
62 }
63 let merged = Editor::new(GUID, 6_999);
64 merged.apply(&base).unwrap();
65 merged.apply(&editors[0].snapshot()).unwrap();
66 merged.snapshot()
67}
68
69fn display_length(projection: &Value) -> u32 {
70 fn walk(value: &Value, offset: &mut u32) {
71 let tag = value["type"].as_str().unwrap_or("");
72 if tag == "text" {
73 *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);
74 return;
75 }
76 if ["hard_break", "image"].contains(&tag) { *offset += 1; return; }
77 if tag == "horizontal_rule" { *offset += 2; return; }
78 for child in value["children"].as_array().into_iter().flatten() { walk(child, offset); }
79 if ["paragraph", "heading", "code_block"].contains(&tag) { *offset += 1; }
80 }
81 let mut offset = 0;
82 for child in projection["children"].as_array().unwrap() { walk(child, &mut offset); }
83 offset
84}
85
86fn collect(value: &Value, types: &[&str], out: &mut Vec<Value>) {
87 if types.contains(&value["type"].as_str().unwrap_or("")) { out.push(value["id"].clone()); }
88 for child in value["children"].as_array().into_iter().flatten() { collect(child, types, out); }
89}
90fn pick(random: &mut Random, values: &[Value]) -> Value {
91 if values.is_empty() { Value::Null } else { values[random.below(values.len() as u64) as usize].clone() }
92}
93
94fn open(bytes: &[u8], client: u64) -> Editor { let e = Editor::new(GUID, client); e.apply(bytes).unwrap(); e }
95fn plain_doc(bytes: &[u8], client: u64, skip_gc: bool) -> Doc {
96 let mut options = yrs::Options::with_guid_and_client_id(GUID.into(), client);
97 options.offset_kind = yrs::OffsetKind::Utf16;
98 options.skip_gc = skip_gc;
99 let doc = Doc::with_options(options);
100 doc.transact_mut().apply_update(Update::decode_v1(bytes).unwrap()).unwrap();
101 doc
102}
103fn state(doc: &Doc) -> Vec<u8> { doc.transact().encode_state_as_update_v1(&StateVector::default()) }
104fn apply(doc: &Doc, bytes: &[u8]) { doc.transact_mut().apply_update(Update::decode_v1(bytes).unwrap()).unwrap(); }
105fn deletes(update: &Update) -> BTreeMap<u64, String> { update.delete_set().iter().map(|(c, r)| (*c, format!("{r:?}"))).collect() }
106/// What a fresh document shows after integrating these bytes, and whether it
107/// integrated all of them.
108fn reread(bytes: &[u8]) -> (Value, bool) { let fresh = open(bytes, 1); (fresh.projection()["children"].clone(), fresh.is_whole()) }
109
110fn run(seed: u64, steps: usize, in_order: bool) -> BTreeMap<String, (usize, usize)> {
111 let trace = std::env::var("GC_UNDO_KEPT_TRACE").is_ok();
112 let base = generate(seed);
113 let n = 3;
114 let mut editors: Vec<Editor> = (0..n).map(|i| open(&base, 1000 + i as u64)).collect();
115 let gc: Vec<Doc> = (0..n).map(|i| plain_doc(&base, 2000 + i as u64, false)).collect();
116 let nogc: Vec<Doc> = (0..n).map(|i| plain_doc(&base, 3000 + i as u64, true)).collect();
117 let mut inbox: Vec<Vec<Vec<u8>>> = vec![Vec::new(); n];
118 let mut random = Random::new(seed * 77 + 5);
119 let mut next_client = 5000u64;
120 let mut stats = BTreeMap::<String, (usize, usize)>::new();
121 let types = ["paragraph", "heading", "bullet_list", "ordered_list", "blockquote", "code_block"];
122 for step in 0..steps {
123 let i = random.below(n as u64) as usize;
124 let before = editors[i].snapshot();
125 let projection = editors[i].projection();
126 let at = random.below(display_length(&projection) as u64 + 1) as u32;
127 let mut texts = vec![]; collect(&projection, &["text"], &mut texts);
128 let mut blocks = vec![]; collect(&projection, &["paragraph","heading","code_block","list_item","bullet_list","ordered_list","blockquote"], &mut blocks);
129 let mut leaves = vec![]; collect(&projection, &["paragraph","heading"], &mut leaves);
130 let command = match random.below(22) {
131 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])}),
132 3 | 4 => json!({"op":"display_edit","at":at,"length":random.below(4),"text":""}),
133 5 => json!({"op":"display_edit","at":at,"length":random.below(700),"text":(["","Z","q\nr"][random.below(3) as usize])}),
134 6 => json!({"op":"display_paste","at":at,"length":random.below(30),"blocks":[
135 {"type":"paragraph","children":[{"type":"text","runs":[{"insert":"pasted","marks":{"em":{}}}]},{"type":"hard_break"},{"type":"text","runs":[{"insert":"more","marks":{}}]}]},
136 {"type":"horizontal_rule"},
137 {"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":{}}]}]}]}]}]}]}]}),
138 7 | 8 => json!({"op":"undo"}),
139 9 => json!({"op":"redo"}),
140 10 | 11 => json!({"op":"block","node":pick(&mut random,&leaves),"type":types[random.below(6) as usize],"level":1 + random.below(3)}),
141 12 => json!({"op":"attribute","node":pick(&mut random,&blocks),"name":"align","value":(["center","right"][random.below(2) as usize])}),
142 13 | 14 => json!({"op":"format","node":pick(&mut random,&texts),"at":random.below(20),"length":1 + random.below(30),"marks":{"strong":{}}}),
143 15 => json!({"op":"list_indent","node":pick(&mut random,&leaves),"delta":if random.below(2) == 0 {1} else {-1}}),
144 16 => json!({"op":"split","node":pick(&mut random,&texts),"at":random.below(40)}),
145 17 => json!({"op":"hard_break","node":pick(&mut random,&texts),"at":random.below(40)}),
146 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}),
147 19 => json!({"op":"display_exit_list","at":at}),
148 20 => json!({"op":"batch","commands":[
149 {"op":"block","node":pick(&mut random,&leaves),"type":types[random.below(6) as usize],"level":2},
150 {"op":"block","node":pick(&mut random,&leaves),"type":types[random.below(6) as usize],"level":2},
151 {"op":"display_edit","at":at,"length":random.below(3),"text":"B"}]}),
152 _ => json!({"op":"display_edit","at":at,"length":random.below(60),"text":"\n"}),
153 };
154 if trace { eprintln!("seed {seed} #{step} e{i} {command}"); }
155 let op = command["op"].as_str().unwrap().to_owned();
156 match editors[i].command(&command) {
157 Ok(update) => {
158 if trace { eprintln!("UPDATE {}", Update::decode_v1(&update).unwrap()); }
159 stats.entry(op).or_default().0 += 1;
160 apply(&gc[i], &update); apply(&nogc[i], &update);
161 for j in 0..n { if j != i { inbox[j].push(update.clone()); } }
162 },
163 Err(_) => {
164 stats.entry(op).or_default().1 += 1;
165 // As CRDTReplica does: a failed command's writer is rebuilt
166 // from the last good state under a new client.
167 if editors[i].snapshot() != before { next_client += 1; editors[i] = open(&state(&gc[i]), next_client); }
168 },
169 }
170 for j in 0..n {
171 for _ in 0..random.below(4) {
172 if inbox[j].is_empty() { break; }
173 let at = if in_order { 0 } else { random.below(inbox[j].len() as u64) as usize };
174 let message = if !in_order && random.below(10) == 0 { inbox[j][at].clone() } else { inbox[j].remove(at) };
175 editors[j].apply(&message).unwrap();
176 apply(&gc[j], &message); apply(&nogc[j], &message);
177 }
178 }
179 for j in 0..n {
180 let context = format!("seed {seed} step {step} editor {j} (in order: {in_order}) after {command}");
181 let snapshot = editors[j].snapshot();
182 let (reread_snapshot, whole) = reread(&snapshot);
183 let shown = editors[j].projection()["children"].clone();
184 // The bug's two faces: a snapshot that does not integrate whole,
185 // or that shows something other than the editor.
186 assert_eq!(whole, editors[j].is_whole(), "{context}: snapshot parks what the editor integrated");
187 assert_eq!(reread_snapshot, shown, "{context}: snapshot differs from what the editor shows");
188 let (ours, theirs) = (Update::decode_v1(&snapshot).unwrap(), Update::decode_v1(&state(&gc[j])).unwrap());
189 assert_eq!(ours.state_vector(), theirs.state_vector(), "{context}: state vectors");
190 let (a, b) = (deletes(&ours), deletes(&theirs));
191 for client in a.keys().chain(b.keys()).filter(|c| a.get(c) != b.get(c)) {
192 eprintln!("{context}: client {client} deletes\n editor {:?}\n plain {:?}", a.get(client), b.get(client));
193 }
194 assert_eq!(deletes(&ours), deletes(&theirs), "{context}: delete sets");
195 assert_eq!(reread(&state(&gc[j])).0, shown, "{context}: plain yrs (gc on) differs");
196 assert_eq!(reread(&state(&nogc[j])).0, shown, "{context}: plain yrs (gc off) differs");
197 // Each plain peer's own display, as it integrated the updates
198 // one by one, not only a fresh integration of its state.
199 assert_eq!(projection_of(&gc[j])["children"], shown, "{context}: plain yrs (gc on) shows otherwise");
200 assert_eq!(projection_of(&nogc[j])["children"], shown, "{context}: plain yrs (gc off) shows otherwise");
201 }
202 }
203 for j in 0..n { for message in std::mem::take(&mut inbox[j]) { editors[j].apply(&message).unwrap(); } }
204 let first = reread(&editors[0].snapshot());
205 assert!(first.1, "seed {seed}: final state not whole");
206 for j in 1..n { assert_eq!(first, reread(&editors[j].snapshot()), "seed {seed}: editors diverged at the end"); }
207 stats
208}
209
210/// The gate's seeds: 1 to 6, plus seeds that catch a yrs patch reverted
211/// (PATCHES.md): 53 the redo delete (causal), 60 the same (shuffled), 98 the
212/// redo origins (causal). insert_into_deleted_parent.rs covers each directly.
213fn seeds(in_order: bool) -> Vec<u64> {
214 match std::env::var("GC_UNDO_KEPT_SEEDS") {
215 Ok(range) => { let (a, b) = range.split_once('-').unwrap_or((&range, &range)); (a.parse().unwrap()..=b.parse().unwrap()).collect() },
216 Err(_) => (1..=6).chain(if in_order { vec![53, 98] } else { vec![60] }).collect(),
217 }
218}
219fn steps() -> usize { std::env::var("GC_UNDO_KEPT_STEPS").map(|s| s.parse().unwrap()).unwrap_or(120) }
220
221fn fuzz(in_order: bool) {
222 let mut total = BTreeMap::<String, (usize, usize)>::new();
223 for seed in seeds(in_order) {
224 for (op, (ok, err)) in run(seed, steps(), in_order) { let entry = total.entry(op).or_default(); entry.0 += ok; entry.1 += err; }
225 }
226 eprintln!("in order {in_order}, seeds {:?}, {} steps: ok/refused per command {total:?}", seeds(in_order), steps());
227}
228
229#[test]
230fn three_editors_with_undo_in_causal_order() { fuzz(true); }
231
232#[test]
233fn three_editors_with_undo_shuffled_and_duplicated() { fuzz(false); }
234