Docs native engine: a command's update carries only its own change
Editor::command returned encode_state_as_update_v1(&before), a
state-vector diff, which always includes the document's whole delete
set: 685 B per typed character at 10 edited pages, 3.6 KB at 50, 11.8 KB
at 200, against the browser's 15 B (audit finding 7). Every outbox file,
POST, server log row and peer GET carried it.
The editor now records the v1 update of every transaction committed while
a command runs (observe_update_v1, exactly Yjs's doc.on('update')) and
returns that update; a command of several transactions (join_range,
paste, rules, batch normalisation) returns their merge, through the same
merge_updates the outbox already sends. A command that changes nothing
returns the empty update. The wire format is unchanged.
Tests: tests/minimal_updates.rs (a keystroke in a document edited by 20
clients is <= 32 B with no delete set; a 3-unit deletion carries exactly
3 units; every command kind incl. multi-transaction commands, undo/redo
and batch, applied alone and in order to peers with gc on and off,
matches the authority). New wire gate in check-native.sh:
update_wire_probe + check-update-wire.mjs replay each command's update in
Yjs (gc on/off) against the authority's snapshot, check a keystroke
carries no delete set and is the size of the browser's own update
(17 B vs 18 B here), and have the native engine apply the browser's
per-transaction updates. tests/support builds large edited documents
(the shape of fixtures/generate-large-doc.mjs) for the engine tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+490
−5
native/crdt/src/bin/update_wire_probe.rs+106 −0native/crdt/src/lib.rs+30 −5native/crdt/tests/minimal_updates.rs+109 −0native/crdt/tests/support/mod.rs+174 −0native/scripts/check-native.sh+3 −0native/scripts/check-update-wire.mjs+68 −0
diff --git a/native/crdt/src/bin/update_wire_probe.rs b/native/crdt/src/bin/update_wire_probe.rs| new file mode 100644 |
| index 0000000..50d7a9d |
| --- /dev/null |
| +++ b/native/crdt/src/bin/update_wire_probe.rs |
| @@ -0,0 +1,106 @@ |
| +//! Wire fixtures for transaction-scoped updates (native realtime audit, |
| +//! finding 7). Phase one writes an edited base document, then one update per |
| +//! command (each only what that command inserted and deleted) with the |
| +//! authority's snapshot after it; native/scripts/check-update-wire.mjs replays |
| +//! them in Yjs and writes the browser's own per-transaction updates back. |
| +//! Phase two (`--browser DIR`) applies those to the native engine. |
| +use docs_native_crdt::Editor; |
| +use serde_json::{json, Value}; |
| +use std::path::Path; |
| + |
| +fn plain(value: &Value) -> String { |
| + if let Some(runs) = value["runs"].as_array() { return runs.iter().filter_map(|run| run["insert"].as_str()).collect(); } |
| + value["children"].as_array().map(|children| children.iter().map(plain).collect()).unwrap_or_default() |
| +} |
| +fn length(value: &Value) -> u32 { |
| + // Display length: text, one per inline atom, two per rule, one per block end. |
| + fn walk(value: &Value) -> u32 { |
| + match value["type"].as_str().unwrap_or("") { |
| + "text" => plain(value).encode_utf16().count() as u32, |
| + "hard_break" | "image" => 1, |
| + "horizontal_rule" => 2, |
| + tag => value["children"].as_array().map(|c| c.iter().map(walk).sum()).unwrap_or(0) + u32::from(["paragraph","heading","code_block"].contains(&tag)), |
| + } |
| + } |
| + value["children"].as_array().unwrap().iter().map(walk).sum() |
| +} |
| +fn edited_base() -> Editor { |
| + // Three writers type and delete concurrently, so the base carries the |
| + // tombstones (a delete set) a state-vector diff would have resent. |
| + let mut writers: Vec<Editor> = (0..3).map(|i| Editor::new("update-wire", 9_100 + i)).collect(); |
| + let first = writers[0].command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap(); |
| + for writer in &writers[1..] { writer.apply(&first).unwrap(); } |
| + let mut seed: u64 = 7; |
| + let mut next = |n: u32| { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); ((seed >> 33) as u32) % n.max(1) }; |
| + for round in 0..60 { |
| + let mut updates = Vec::new(); |
| + for (index, writer) in writers.iter_mut().enumerate() { |
| + let total = length(&writer.projection()); |
| + let at = next(total); |
| + let command = if round % 4 == 3 && total > 6 { json!({"op":"display_edit","at":at.min(total - 4),"length":2,"text":""}) } |
| + else if round % 7 == 6 { json!({"op":"display_edit","at":at,"length":0,"text":"\n"}) } |
| + else { json!({"op":"display_edit","at":at,"length":0,"text":format!("w{index}r{round} ")}) }; |
| + if let Ok(update) = writer.command(&command) { updates.push((index, update)); } |
| + } |
| + for (index, writer) in writers.iter().enumerate() { |
| + for (from, update) in &updates { if *from != index { writer.apply(update).unwrap(); } } |
| + } |
| + } |
| + let base = Editor::new("update-wire", 9_000); |
| + base.apply(&writers[0].snapshot()).unwrap(); |
| + base |
| +} |
| +fn main() { |
| + let arguments: Vec<String> = std::env::args().collect(); |
| + if arguments.get(1).map(String::as_str) == Some("--browser") { |
| + let directory = Path::new(&arguments[2]); |
| + let editor = Editor::new("update-wire", 9_500); |
| + editor.apply(&std::fs::read(directory.join("base.bin")).unwrap()).unwrap(); |
| + let mut index = 0; |
| + while let Ok(update) = std::fs::read(directory.join(format!("browser-{index}.bin"))) { |
| + editor.apply(&update).unwrap(); |
| + index += 1; |
| + } |
| + assert!(index > 0, "no browser updates"); |
| + let expected = std::fs::read_to_string(directory.join("browser-text.txt")).unwrap(); |
| + assert_eq!(plain(&editor.projection()), expected, "native applies the browser's per-transaction updates"); |
| + println!("Native applied {index} browser transaction updates."); |
| + return; |
| + } |
| + let directory = Path::new(&arguments[1]); |
| + std::fs::create_dir_all(directory).unwrap(); |
| + let mut authority = edited_base(); |
| + 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":[ |
| + {"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), |
| + ]; |
| + 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()})); |
| + } |
| + 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/src/lib.rs b/native/crdt/src/lib.rs| index 351d83a..fa77f8b 100644 |
| --- a/native/crdt/src/lib.rs |
| +++ b/native/crdt/src/lib.rs |
| @@ -9,7 +9,7 @@ mod paste; |
| mod lists; |
| mod input_rules; |
| use serde_json::{json, Value}; |
| -use std::{cell::RefCell, collections::HashSet, sync::Arc}; |
| +use std::{cell::RefCell, collections::HashSet, sync::{Arc, Mutex}}; |
| use yrs::{Doc, OffsetKind, Options, ReadTxn, StateVector, Transact, UndoManager, Update}; |
| use yrs::updates::decoder::{Decode, Decoder, DecoderV1}; |
| use yrs::updates::encoder::Encode; |
| @@ -17,6 +17,10 @@ use yrs::updates::encoder::Encode; |
| pub struct Editor { |
| doc: Doc, |
| undo: UndoManager, |
| + /// The v1 update of every transaction committed while a command runs, |
| + /// exactly what Yjs emits as `doc.on('update')`. |
| + transactions: Arc<Mutex<Vec<Vec<u8>>>>, |
| + _updates: yrs::Subscription, |
| } |
| impl Editor { |
| pub fn new(guid: &str, client_id: u64) -> Self { |
| @@ -30,7 +34,12 @@ impl Editor { |
| capture_transaction: None, |
| timestamp: Arc::new(|| 1), |
| }); |
| - Self {doc, undo} |
| + let transactions = Arc::new(Mutex::new(Vec::new())); |
| + let sink = transactions.clone(); |
| + let _updates = doc.observe_update_v1(move |_, event| { |
| + if let Ok(mut sink) = sink.lock() { sink.push(event.update.clone()); } |
| + }).expect("no transaction is open while the editor is created"); |
| + Self {doc, undo, transactions, _updates} |
| } |
| pub fn apply(&self, bytes: &[u8]) -> Result<(), &'static str> { self.apply_origin(bytes, false) } |
| pub fn apply_local(&self, bytes: &[u8]) -> Result<(), &'static str> { self.apply_origin(bytes, true) } |
| @@ -50,8 +59,24 @@ impl Editor { |
| } |
| pub fn anchor(&self, at: u32) -> Result<Value, &'static str> { display::anchor(&self.doc, at) } |
| pub fn resolve(&self, anchor: &Value) -> Result<u32, &'static str> { display::resolve(&self.doc, anchor) } |
| + /// Runs one command and returns its update: only what its own |
| + /// transactions inserted and deleted, as the browser sends. Never a |
| + /// state-vector diff, which carries the document's whole delete set. |
| pub fn command(&mut self, request: &Value) -> Result<Vec<u8>, &'static str> { |
| - let before = self.doc.transact().state_vector(); |
| + self.transactions.lock().map_err(|_| "invalid_command")?.clear(); |
| + let result = self.execute(request); |
| + let updates = std::mem::take(&mut *self.transactions.lock().map_err(|_| "invalid_command")?); |
| + result?; |
| + match updates.len() { |
| + 0 => Ok(Update::new().encode_v1()), |
| + 1 => Ok(updates.into_iter().next().unwrap_or_default()), |
| + _ => { |
| + let decoded = updates.iter().map(|bytes| Update::decode_v1(bytes).map_err(|_| "invalid_update")).collect::<Result<Vec<_>, _>>()?; |
| + Ok(Update::merge_updates(decoded).encode_v1()) |
| + }, |
| + } |
| + } |
| + fn execute(&mut self, request: &Value) -> Result<(), &'static str> { |
| match request.get("op").and_then(Value::as_str).ok_or("invalid_command")? { |
| "batch" => { |
| let commands = request["commands"].as_array().filter(|v| v.len() <= 1000).ok_or("invalid_command")?; |
| @@ -59,7 +84,7 @@ impl Editor { |
| let mut affected = HashSet::new(); |
| for command in commands { |
| let target = lists::normalization_target(&self.doc, command); |
| - self.command(command)?; |
| + self.execute(command)?; |
| if let Some(id) = target.and_then(|t| lists::normalized_identity(&self.doc, t)) { affected.insert(id); } |
| } |
| lists::normalize(&self.doc, &mut affected); |
| @@ -74,7 +99,7 @@ impl Editor { |
| "block" | "split" | "hard_break" | "join_range" => structure::execute(&self.doc, request)?, |
| _ => operations::execute(&self.doc, request)?, |
| } |
| - Ok(self.doc.transact().encode_state_as_update_v1(&before)) |
| + Ok(()) |
| } |
| } |
diff --git a/native/crdt/tests/minimal_updates.rs b/native/crdt/tests/minimal_updates.rs| new file mode 100644 |
| index 0000000..1fbf6ea |
| --- /dev/null |
| +++ b/native/crdt/tests/minimal_updates.rs |
| @@ -0,0 +1,109 @@ |
| +//! Finding 7 of the native realtime audit: a command's update carries only |
| +//! what its own transactions inserted and deleted (as Yjs's doc.on('update') |
| +//! does), never the document's whole delete set. |
| +mod support; |
| +use docs_native_crdt::Editor; |
| +use serde_json::{json, Value}; |
| +use support::{generate, oracle, plain}; |
| +use yrs::updates::decoder::Decode; |
| +use yrs::updates::encoder::Encode; |
| +use yrs::Update; |
| + |
| +fn open(bytes: &[u8], client: u64) -> Editor { |
| + let editor = Editor::new("large-document", client); |
| + editor.apply(bytes).unwrap(); |
| + editor |
| +} |
| +fn deleted_units(update: &[u8]) -> u32 { |
| + let update = Update::decode_v1(update).unwrap(); |
| + update.delete_set().iter().map(|(_, ranges)| ranges.iter().map(|r| r.end - r.start).sum::<u32>()).sum() |
| +} |
| +fn middle_of_text(projection: &Value) -> u32 { |
| + let (ranges, _) = oracle(projection); |
| + let text = ranges.iter().filter(|r| !r.atomic && r.length > 8).nth(ranges.len() / 3).unwrap(); |
| + text.start + text.length / 2 |
| +} |
| + |
| +#[test] |
| +fn keystroke_update_is_independent_of_the_documents_history() { |
| + let edited = generate(10, 600, 1); |
| + let mut editor = open(&edited, 41); |
| + let at = middle_of_text(&editor.projection()); |
| + // What the engine used to send: a state-vector diff carries every deletion. |
| + let before = { use yrs::{ReadTxn, Transact}; let doc = yrs::Doc::new(); doc.transact_mut().apply_update(Update::decode_v1(&edited).unwrap()).unwrap(); let sv = doc.transact().state_vector(); sv }; |
| + let update = editor.command(&json!({"op":"display_edit","at":at,"length":0,"text":"x"})).unwrap(); |
| + assert!(update.len() <= 32, "one character, {} bytes", update.len()); |
| + assert_eq!(deleted_units(&update), 0); |
| + let legacy = { use yrs::{ReadTxn, Transact}; let doc = yrs::Doc::new(); doc.transact_mut().apply_update(Update::decode_v1(&editor.snapshot()).unwrap()).unwrap(); let bytes = doc.transact().encode_state_as_update_v1(&before); bytes }; |
| + assert!(legacy.len() > 10 * update.len(), "the history really is large: {} vs {}", legacy.len(), update.len()); |
| + |
| + let deletion = editor.command(&json!({"op":"display_edit","at":at,"length":3,"text":""})).unwrap(); |
| + assert_eq!(deleted_units(&deletion), 3, "only the three deleted units"); |
| + assert!(deletion.len() <= 32, "a three-unit deletion, {} bytes", deletion.len()); |
| +} |
| + |
| +#[test] |
| +fn every_command_kind_converges_through_its_own_update_alone() { |
| + // Each step's update is applied, alone and in order, to a peer which |
| + // started from the same document: with gc on and off it must match the |
| + // authority exactly. This covers multi-transaction commands (join_range, |
| + // paste, rules, batch normalization) and undo/redo. |
| + let edited = generate(4, 240, 2); |
| + let mut authority = open(&edited, 51); |
| + let peer_gc = open(&edited, 52); |
| + let peer = { let mut options = yrs::Options::with_guid_and_client_id("large-document".into(), 53); options.skip_gc = true; options.offset_kind = yrs::OffsetKind::Utf16; let doc = yrs::Doc::with_options(options); use yrs::Transact; doc.transact_mut().apply_update(Update::decode_v1(&edited).unwrap()).unwrap(); doc }; |
| + let mut client = 60; |
| + let mut step = |authority: &mut Editor, command: Value, from_source: bool| { |
| + let update = if from_source { |
| + client += 1; |
| + let mut source = open(&authority.snapshot(), client); |
| + let update = source.command(&command).unwrap_or_else(|e| panic!("{command}: {e}")); |
| + authority.apply_local(&update).unwrap(); |
| + update |
| + } else { authority.command(&command).unwrap_or_else(|e| panic!("{command}: {e}")) }; |
| + peer_gc.apply(&update).unwrap(); |
| + { use yrs::Transact; peer.transact_mut().apply_update(Update::decode_v1(&update).unwrap()).unwrap(); } |
| + let expected = authority.projection()["children"].clone(); |
| + assert_eq!(peer_gc.projection()["children"], expected, "{command}"); |
| + let reread = open(&{ use yrs::{ReadTxn, StateVector, Transact}; let bytes = peer.transact().encode_state_as_update_v1(&StateVector::default()); bytes }, 99); |
| + assert_eq!(reread.projection()["children"], expected, "{command} (no gc)"); |
| + update |
| + }; |
| + let at = middle_of_text(&authority.projection()); |
| + step(&mut authority, json!({"op":"display_edit","at":at,"length":0,"text":"typed"}), true); |
| + step(&mut authority, json!({"op":"display_edit","at":at,"length":2,"text":"Q"}), true); |
| + step(&mut authority, json!({"op":"display_edit","at":at,"length":0,"text":"one\ntwo\u{2028}three"}), true); |
| + // A cross-paragraph replacement (join_range runs several transactions). |
| + step(&mut authority, json!({"op":"display_edit","at":at - 20,"length":900,"text":"joined"}), true); |
| + step(&mut authority, json!({"op":"display_paste","at":10,"length":4,"blocks":[ |
| + {"type":"heading","attrs":{"level":"3"},"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); |
| + let (_, length) = oracle(&authority.projection()); |
| + step(&mut authority, json!({"op":"display_edit","at":length - 1,"length":0,"text":"\n-"}), true); |
| + let p = authority.projection(); |
| + let (_, length) = oracle(&p); |
| + step(&mut authority, json!({"op":"display_autoformat","at":length - 2,"length":1,"kind":"bullet_list","level":0}), true); |
| + let p = authority.projection(); |
| + let (_, length) = oracle(&p); |
| + step(&mut authority, json!({"op":"display_revert_rule","at":length - 1,"kind":"bullet_list","prior_type":"paragraph","prior_attrs":{},"text":"- "}), true); |
| + step(&mut authority, json!({"op":"undo"}), false); |
| + step(&mut authority, json!({"op":"undo"}), false); |
| + step(&mut authority, json!({"op":"redo"}), false); |
| + let p = authority.projection(); |
| + let first = p["children"][1]["id"].clone(); |
| + let second = p["children"][2]["id"].clone(); |
| + step(&mut authority, json!({"op":"batch","commands":[ |
| + {"op":"block","node":first,"type":"bullet_list"}, |
| + {"op":"block","node":second,"type":"bullet_list"} |
| + ]}), true); |
| + step(&mut authority, json!({"op":"undo"}), false); |
| + assert!(!plain(&authority.projection()).is_empty()); |
| +} |
| + |
| +#[test] |
| +fn a_command_that_changes_nothing_sends_an_empty_update() { |
| + let mut editor = open(&generate(2, 50, 3), 70); |
| + let update = editor.command(&json!({"op":"display_edit","at":3,"length":0,"text":""})).unwrap(); |
| + assert_eq!(update, Update::new().encode_v1()); |
| +} |
diff --git a/native/crdt/tests/support/mod.rs b/native/crdt/tests/support/mod.rs| new file mode 100644 |
| index 0000000..4a4c39b |
| --- /dev/null |
| +++ b/native/crdt/tests/support/mod.rs |
| @@ -0,0 +1,174 @@ |
| +//! Large, realistically edited documents for the engine tests, built with |
| +//! yrs directly (the same shape as fixtures/generate-large-doc.mjs): a page is |
| +//! five ~560-character paragraphs with bold and italic runs, a level-2 |
| +//! heading every second page and a five-item bullet list every fifth. `edits` |
| +//! then applies that many small concurrent edits from twenty clients, synced |
| +//! in rounds, so the document carries real tombstones and fragmentation. |
| +#![allow(dead_code)] |
| +use serde_json::Value; |
| +use yrs::types::xml::{XmlDeltaPrelim, XmlIn}; |
| +use yrs::types::Delta; |
| +use yrs::{Any, Doc, In, OffsetKind, Options, ReadTxn, StateVector, Text, Transact, Update, XmlElementPrelim, XmlFragment, XmlOut, XmlTextRef}; |
| +use yrs::updates::decoder::Decode; |
| + |
| +pub struct Random(u64); |
| +impl Random { |
| + pub fn new(seed: u64) -> Self { Random(seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407)) } |
| + pub 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 |
| + } |
| + pub 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","are","or","from","at","which","but","have","an","they","you","were","there","would","their","we","been","has","when","who","will","more","if","out","so","up","what","about","than","into","them","can","only","other","time","new","some","could","these","two","may","first","then","any","like","now","over","such","our","even","most","made","after","also","many","before","must","well","back","through","years","much","where","your","way","down","should","because","each","just","those","people","how","too","little","state","good","very","make","world","still","own","work","long","here","both","between","life","being","under","never","day","same","another","know","while","last","might","great","old","year","come","since","against","right","used","take","three","naïve","café","😀"]; |
| +fn sentence(random: &mut Random) -> String { |
| + let n = 8 + random.below(14) as usize; |
| + let mut words: Vec<String> = (0..n).map(|_| WORDS[random.below(WORDS.len() as u64) as usize].to_owned()).collect(); |
| + let first: String = words[0].chars().take(1).flat_map(char::to_uppercase).chain(words[0].chars().skip(1)).collect(); |
| + words[0] = first; |
| + words.join(" ") + "." |
| +} |
| +fn paragraph_text(random: &mut Random) -> String { |
| + let mut text = String::new(); |
| + while text.chars().count() < 560 { if !text.is_empty() { text.push(' '); } text += &sentence(random); } |
| + text |
| +} |
| +fn run(text: &str, mark: Option<&str>) -> Delta<In> { |
| + let attrs = mark.map(|m| Box::new([(m.into(), Any::Map(Default::default()))].into_iter().collect())); |
| + Delta::Inserted(In::Any(Any::from(text)), attrs) |
| +} |
| +fn text(delta: Vec<Delta<In>>) -> XmlIn { XmlIn::Text(XmlDeltaPrelim { attributes: Default::default(), delta }) } |
| +fn rich_paragraph(random: &mut Random) -> XmlElementPrelim { |
| + let words = paragraph_text(random); |
| + let chars: Vec<char> = words.chars().collect(); |
| + if random.below(10) < 3 { return XmlElementPrelim::new("paragraph", [text(vec![run(&words, None)])]); } |
| + let len = chars.len(); |
| + let a = random.below((len - 80) as u64) as usize; let b = a + 10 + random.below(30) as usize; |
| + let c = (b + 20 + random.below(40) as usize).min(len - 1); let d = (c + 5 + random.below(20) as usize).min(len); |
| + let slice = |from: usize, to: usize| chars[from..to].iter().collect::<String>(); |
| + let mut delta = Vec::new(); |
| + for (from, to, mark) in [(0, a, None), (a, b, Some("strong")), (b, c, None), (c, d, Some("em")), (d, len, None)] { |
| + if to > from { delta.push(run(&slice(from, to), mark)); } |
| + } |
| + XmlElementPrelim::new("paragraph", [text(delta)]) |
| +} |
| +fn options(client: u64) -> Options { |
| + let mut options = Options::with_guid_and_client_id("large-document".into(), client); |
| + options.offset_kind = OffsetKind::Utf16; |
| + options |
| +} |
| +fn texts<T: ReadTxn>(fragment: &impl XmlFragment, txn: &T, out: &mut Vec<XmlTextRef>) { |
| + for child in fragment.children(txn) { |
| + match child { |
| + XmlOut::Text(t) => out.push(t), |
| + XmlOut::Element(e) => texts(&e, txn, out), |
| + XmlOut::Fragment(f) => texts(&f, txn, out), |
| + } |
| + } |
| +} |
| +/// A Yjs v1 update holding the whole document. |
| +pub fn generate(pages: usize, edits: usize, seed: u64) -> Vec<u8> { |
| + let mut random = Random::new(seed); |
| + let author = Doc::with_options(options(7_000)); |
| + let root = author.get_or_insert_xml_fragment("prosemirror"); |
| + { |
| + let mut txn = author.transact_mut(); |
| + let mut index = 0; |
| + for page in 0..pages { |
| + if page % 2 == 0 { |
| + let mut heading = XmlElementPrelim::new("heading", [text(vec![run(&format!("Section {}: {}", page / 2 + 1, sentence(&mut random).chars().take(40).collect::<String>()), None)])]); |
| + heading.attributes.insert("level".into(), "2".into()); |
| + root.insert(&mut txn, index, heading); index += 1; |
| + } |
| + for _ in 0..5 { root.insert(&mut txn, index, rich_paragraph(&mut random)); index += 1; } |
| + if page % 5 == 4 { |
| + let items: Vec<XmlIn> = (0..5).map(|_| XmlIn::Element(XmlElementPrelim::new("list_item", [XmlIn::Element(XmlElementPrelim::new("paragraph", [text(vec![run(&sentence(&mut random), None)])]))]))).collect(); |
| + root.insert(&mut txn, index, XmlElementPrelim::new("bullet_list", items)); index += 1; |
| + } |
| + } |
| + } |
| + let base = author.transact().encode_state_as_update_v1(&StateVector::default()); |
| + if edits == 0 { return base; } |
| + let clients: Vec<Doc> = (0..20).map(|i| { |
| + let doc = Doc::with_options(options(7_001 + i)); |
| + doc.transact_mut().apply_update(Update::decode_v1(&base).unwrap()).unwrap(); |
| + doc |
| + }).collect(); |
| + let mut done = 0; |
| + while done < edits { |
| + let mut round = Vec::new(); |
| + for doc in &clients { |
| + if done == edits { break; } |
| + let before = doc.transact().state_vector(); |
| + { |
| + let fragment = doc.get_or_insert_xml_fragment("prosemirror"); |
| + let mut all = Vec::new(); |
| + texts(&fragment, &doc.transact(), &mut all); |
| + let mut txn = doc.transact_mut(); |
| + let target = &all[random.below(all.len() as u64) as usize]; |
| + let content: String = target.diff(&txn, |_| ()).iter().map(|d| d.insert.clone().to_string(&txn)).collect(); |
| + let units: Vec<u16> = content.encode_utf16().collect(); |
| + let at = random.below(units.len() as u64 + 1) as u32; |
| + let boundary = |at: u32| at as usize >= units.len() || !(0xDC00..0xE000).contains(&units[at as usize]); |
| + if !boundary(at) { continue; } |
| + if random.below(3) == 0 && units.len() > 4 { |
| + let mut length = 1 + random.below(4) as u32; |
| + while at + length > units.len() as u32 || !boundary(at + length) { if length == 0 { break; } length -= 1; } |
| + if length > 0 { target.remove_range(&mut txn, at, length); } |
| + } else { |
| + let insert: String = (0..1 + random.below(8)).map(|_| (b'a' + random.below(26) as u8) as char).collect(); |
| + target.insert(&mut txn, at, &insert); |
| + } |
| + } |
| + round.push(doc.transact().encode_state_as_update_v1(&before)); |
| + done += 1; |
| + } |
| + for doc in &clients { |
| + let mut txn = doc.transact_mut(); |
| + for update in &round { txn.apply_update(Update::decode_v1(update).unwrap()).unwrap(); } |
| + } |
| + } |
| + let merged = Doc::with_options(options(6_999)); |
| + merged.transact_mut().apply_update(Update::decode_v1(&base).unwrap()).unwrap(); |
| + merged.transact_mut().apply_update(Update::decode_v1(&clients[0].transact().encode_state_as_update_v1(&StateVector::default())).unwrap()).unwrap(); |
| + let bytes = merged.transact().encode_state_as_update_v1(&StateVector::default()); |
| + bytes |
| +} |
| + |
| +pub fn plain(value: &Value) -> String { |
| + if let Some(runs) = value["runs"].as_array() { return runs.iter().filter_map(|run| run["insert"].as_str()).collect(); } |
| + value["children"].as_array().map(|children| children.iter().map(plain).collect()).unwrap_or_default() |
| +} |
| + |
| +/// The display mapping as it was defined before the engine stopped building a |
| +/// projection for it (display.rs at 8e54d3a): the oracle the fast walk must match. |
| +pub struct Span { pub node: String, pub start: u32, pub length: u32, pub atomic: bool } |
| +pub fn spans(value: &Value, offset: &mut u32, output: &mut Vec<Span>) { |
| + let tag = value["type"].as_str().unwrap_or(""); |
| + if tag == "text" { |
| + let length = 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); |
| + output.push(Span { node: value["id"].as_str().unwrap_or("").to_owned(), start: *offset, length, atomic: false }); |
| + *offset += length; return; |
| + } |
| + if ["hard_break", "image", "horizontal_rule"].contains(&tag) { |
| + output.push(Span { node: value["id"].as_str().unwrap_or("").to_owned(), start: *offset, length: 1, atomic: true }); |
| + *offset += if tag == "horizontal_rule" { 2 } else { 1 }; return; |
| + } |
| + let start = *offset; |
| + if let Some(children) = value["children"].as_array() { for child in children { spans(child, offset, output); } } |
| + if ["paragraph", "heading", "code_block"].contains(&tag) { |
| + if *offset == start { output.push(Span { node: value["id"].as_str().unwrap_or("").to_owned(), start, length: 0, atomic: false }); } |
| + *offset += 1; |
| + } |
| +} |
| +pub fn oracle(projection: &Value) -> (Vec<Span>, u32) { |
| + let mut offset = 0; let mut ranges = Vec::new(); |
| + for child in projection["children"].as_array().unwrap() { spans(child, &mut offset, &mut ranges); } |
| + (ranges, offset) |
| +} |
| +pub fn oracle_locate(ranges: &[Span], at: u32, length: u32) -> Option<(String, u32)> { |
| + let end = at.checked_add(length)?; |
| + ranges.iter().find(|r| !r.atomic && at >= r.start && end <= r.start + r.length) |
| + .or_else(|| ranges.iter().find(|r| r.atomic && at >= r.start && end <= r.start + r.length)) |
| + .map(|r| (r.node.clone(), at - r.start)) |
| +} |
diff --git a/native/scripts/check-native.sh b/native/scripts/check-native.sh| index 3518ba3..f527f6f 100755 |
| --- a/native/scripts/check-native.sh |
| +++ b/native/scripts/check-native.sh |
| @@ -44,6 +44,9 @@ 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" |
| +"$CARGO" run --locked --quiet --manifest-path native/crdt/Cargo.toml --bin update_wire_probe -- "$native_check_dir/update" |
| +node native/scripts/check-update-wire.mjs "$native_check_dir/update" |
| +"$CARGO" run --locked --quiet --manifest-path native/crdt/Cargo.toml --bin update_wire_probe -- --browser "$native_check_dir/update" |
| if [ "$core_only" = 0 ]; then |
| native/scripts/build-crdt.sh |
| swift test --package-path native/apple |
diff --git a/native/scripts/check-update-wire.mjs b/native/scripts/check-update-wire.mjs| new file mode 100644 |
| index 0000000..b420015 |
| --- /dev/null |
| +++ b/native/scripts/check-update-wire.mjs |
| @@ -0,0 +1,68 @@ |
| +// Native realtime audit finding 7: the native engine sends transaction-scoped |
| +// updates, as the browser does. Replays update_wire_probe's per-command |
| +// updates in Yjs (gc on and off), each alone and in order, against the |
| +// authority's snapshot after it; checks that a keystroke carries no delete |
| +// set and is the size of the browser's own update for the same keystroke; |
| +// then writes browser per-transaction updates for the native side to apply. |
| +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-update-wire.mjs OUTPUT_DIRECTORY') |
| +const read = name => fs.readFileSync(path.join(directory, name)) |
| +const manifest = JSON.parse(read('manifest.json')) |
| +const deleted = update => { |
| + let units = 0 |
| + for (const ranges of Y.decodeUpdate(update).ds.clients.values()) for (const r of ranges) units += r.len |
| + return units |
| +} |
| +let comparisons = 0 |
| +for (const gc of [true, false]) { |
| + 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}`) |
| + comparisons++ |
| + snapshot.destroy() |
| + } |
| + doc.destroy() |
| +} |
| +const base = new Y.Doc() |
| +Y.applyUpdate(base, read('base.bin')) |
| +const typed = new Y.Doc() |
| +Y.applyUpdate(typed, read('base.bin')); Y.applyUpdate(typed, read('1.bin')) |
| +// What the engine used to send for the same keystroke: a state-vector diff. |
| +const legacy = Y.encodeStateAsUpdate(typed, Y.encodeStateVector(base)).length |
| +const baseDeletes = deleted(Y.encodeStateAsUpdate(base)) |
| +assert.ok(baseDeletes > 20, `the base document carries a delete set (${baseDeletes} units)`) |
| +const keystroke = read('1.bin'), deletion = read('2.bin') |
| +assert.equal(deleted(keystroke), 0, 'a typed character carries no deletions') |
| +assert.equal(deleted(deletion), 3, 'a three-unit deletion carries exactly those three units') |
| +// The browser's own update for typing one character into the same document. |
| +const browser = new Y.Doc() |
| +Y.applyUpdate(browser, read('base.bin')) |
| +const updates = [] |
| +browser.on('update', update => updates.push(update)) |
| +const firstText = (fragment) => { |
| + for (const child of fragment.toArray()) { |
| + if (child instanceof Y.XmlText && child.length > 4) return child |
| + if (child instanceof Y.XmlElement) { const found = firstText(child); if (found) return found } |
| + } |
| +} |
| +const text = firstText(browser.getXmlFragment('prosemirror')) |
| +text.insert(2, 'x') |
| +assert.equal(updates.length, 1) |
| +assert.ok(keystroke.length <= updates[0].length + 8, `native keystroke ${keystroke.length} B vs browser ${updates[0].length} B`) |
| +// Browser transactions for native to apply: an insertion, a deletion and a mark. |
| +text.delete(1, 2) |
| +text.format(0, 2, { strong: {} }) |
| +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).`) |