oficina / docs Public

Docs native engine: map display positions by walking the tree, and project only touched blocks

Audit finding 2 (Rust half). One keystroke built the whole JSON
projection about eight times inside the interpreter, only to turn a
UTF-16 offset into a node; 2.15 s per key at 200 pages.

- display.rs maps offsets by walking the yrs tree with each text's
  stored UTF-16 length (no JSON, no string copies), stopping at the
  span it needs. locate, display_edit's length check, resolve and
  join_range's leaf blocks all use it.
- projection::find / structure::parent look a node up by its identity
  and check it upwards (live, a child of a live parent, up to the root)
  instead of a depth-first search serialising every node's id.
  Children are read with one pass over the item list, not get(i) each.
- The projection renders an embed in a text as one U+FFFC (and pads or
  trims content Yjs editors never put in a text), so a display offset
  is a yrs offset. Documents without embeds project byte for byte as
  before (tested against the old code).
- projection_delta ("project_delta"): after a projection, the editor
  records which top-level blocks any transaction touched
  (changed_parent_types, read before gc) and reports edits to the
  previous list of blocks: keep n, remove n, insert re-projected blocks.

Tests: display_mapping.rs checks the walk against the old
projection-based mapping at every position (locate with four lengths,
anchor and resolve) on edited documents and on every node kind, that
typing anywhere edits exactly that display position, the embed case,
and that projections are unchanged. projection_delta.rs replays deltas
through 160 steps of local commands, peers' concurrent updates, undo,
redo, paste, block and attribute changes and compares with the whole
projection each time.

host/examples/realtime.rs measures it through the production
interpreter. Per keystroke (display_edit + authority apply + two
anchors + presentation): p1 1.6 ms, p10 3.5 ms, p20 3.5 ms (was 13,
105 and 212 ms); with fuel raised for diagnosis p50 7.9 ms, p200 23 ms
(was 510 and 2,150 ms). Swift still asks for whole projections and
snapshots; the next commit stops that.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev dfa43a62387ac417bdf3acdaff95a5b21ef4b1a6 parent e416221
10 files changed, +649 −73
  • native/crdt/src/display.rs +97 −32
  • native/crdt/src/lib.rs +94 −4
  • native/crdt/src/operations.rs +1 −1
  • native/crdt/src/projection.rs +92 −17
  • native/crdt/src/structure.rs +7 −18
  • native/crdt/tests/display_mapping.rs +145 −0
  • native/crdt/tests/projection_delta.rs +107 −0
  • native/crdt/tests/support/mod.rs +29 −0
  • native/host/examples/realtime.rs +76 −0
  • native/scripts/check-mutations.py +1 −1
diff --git a/native/crdt/src/display.rs b/native/crdt/src/display.rs
index 10f38b7..376dd45 100644
--- a/native/crdt/src/display.rs
+++ b/native/crdt/src/display.rs
@@ -1,35 +1,86 @@
//! Resolve optimistic native UTF-16 display positions against their own source
//! generation, never against an authority which may already include peer edits.
+//!
+//! The display is the projection rendered as text: a text node is its
+//! content, an inline atom (hard break, image) is one position and a rule two,
+//! and a paragraph, heading or code block ends with one. Positions are mapped
+//! by walking the document tree with each text's stored length, not by
+//! building the projection: no JSON and no string copies.
use crate::{operations, projection, structure};
use serde_json::{json, Value};
-use yrs::{Doc, Transact};
-struct Span { node: String, start: u32, length: u32, atomic: bool }
-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;
+use yrs::branch::BranchPtr;
+use yrs::{Doc, ReadTxn, Text, Transact, XmlFragmentRef, XmlOut};
+
+/// Visit the display spans in document order: `visit(node, start, length,
+/// atomic)`, returning true to stop. A text is one span; an inline atom is a
+/// one-position atomic span; an empty paragraph, heading or code block is a
+/// zero-length span of its own.
+fn walk<T: ReadTxn>(fragment: &XmlFragmentRef, txn: &T, offset: &mut u32, visit: &mut dyn FnMut(&XmlOut, u32, u32, bool) -> bool) -> bool {
+ for (_, child) in projection::indexed_children(fragment, txn) {
+ if walk_node(&child, txn, offset, visit) { return true; }
}
- 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;
+ false
+}
+fn walk_node<T: ReadTxn>(node: &XmlOut, txn: &T, offset: &mut u32, visit: &mut dyn FnMut(&XmlOut, u32, u32, bool) -> bool) -> bool {
+ match node {
+ XmlOut::Text(text) => {
+ let length = text.len(txn);
+ if visit(node, *offset, length, false) { return true; }
+ *offset += length;
+ false
+ },
+ XmlOut::Element(element) => {
+ let tag = element.tag();
+ match tag.as_ref() {
+ // An element named "text" projects as a text with no runs.
+ "text" => visit(node, *offset, 0, false),
+ "hard_break" | "image" | "horizontal_rule" => {
+ if visit(node, *offset, 1, true) { return true; }
+ *offset += if tag.as_ref() == "horizontal_rule" { 2 } else { 1 };
+ false
+ },
+ tag => {
+ let start = *offset;
+ if walk(element.as_ref(), txn, offset, visit) { return true; }
+ if ["paragraph", "heading", "code_block"].contains(&tag) {
+ if *offset == start && visit(node, start, 0, false) { return true; }
+ *offset += 1;
+ }
+ false
+ },
+ }
+ },
+ XmlOut::Fragment(fragment) => walk(fragment, txn, offset, visit),
}
}
+fn root(doc: &Doc) -> XmlFragmentRef { doc.get_or_insert_xml_fragment("prosemirror") }
+/// The whole display's length, including the final block's terminator.
+pub(crate) fn display_length<T: ReadTxn>(root: &XmlFragmentRef, txn: &T) -> u32 {
+ let mut offset = 0;
+ walk(root, txn, &mut offset, &mut |_, _, _, _| false);
+ offset
+}
+/// The span containing [at, at + length]: the first text (or empty block)
+/// that does, else the first inline atom that does.
+fn span<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, at: u32, end: u32) -> Option<(XmlOut, u32)> {
+ let mut text = None;
+ let mut atom = None;
+ walk(root, txn, &mut 0, &mut |node, start, length, atomic| {
+ // Spans start in order, so none after this one can contain `at`.
+ if start > at { return true; }
+ if end <= start + length {
+ if !atomic { text = Some((node.clone(), start)); return true; }
+ if atom.is_none() { atom = Some((node.clone(), start)); }
+ }
+ false
+ });
+ text.or(atom)
+}
pub(crate) fn locate(doc: &Doc, at: u32, length: u32) -> Result<(String,u32), &'static str> {
- let root = doc.get_or_insert_xml_fragment("prosemirror");
- let mut offset = 0; let mut ranges = Vec::new();
- for child in projection::children(&root, &doc.transact()) { spans(&child, &mut offset, &mut ranges); }
let end = at.checked_add(length).ok_or("invalid_range")?;
- 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)).ok_or("unsupported_range")
+ let root = root(doc);
+ let txn = doc.transact();
+ span(&root, &txn, at, end).map(|(node, start)| (projection::node_id(&node), at - start)).ok_or("unsupported_range")
}
fn endpoint(doc: &Doc, at: u32) -> Result<(String,u32), &'static str> {
use yrs::{XmlFragment, XmlTextPrelim};
@@ -48,9 +99,8 @@ fn endpoint(doc: &Doc, at: u32) -> Result<(String,u32), &'static str> {
pub fn execute(doc: &Doc, request: &Value) -> Result<(), &'static str> {
let at = request["at"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid_range")?;
let mut length = request["length"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid_range")?;
- let root = doc.get_or_insert_xml_fragment("prosemirror");
- let mut display_length = 0; let mut ranges = Vec::new();
- for child in projection::children(&root, &doc.transact()) { spans(&child, &mut display_length, &mut ranges); }
+ let root = root(doc);
+ let display_length = display_length(&root, &doc.transact());
let end = at.checked_add(length).ok_or("invalid_range")?;
if end > display_length { return Err("invalid_range"); }
// The final native paragraph terminator is presentation, not user content.
@@ -125,16 +175,31 @@ pub fn anchor(doc: &Doc, at: u32) -> Result<Value, &'static str> {
}
}
pub fn resolve(doc: &Doc, anchor: &Value) -> Result<u32, &'static str> {
- let root = doc.get_or_insert_xml_fragment("prosemirror");
+ let root = root(doc);
let txn = doc.transact();
- let mut offset = 0; let mut ranges = Vec::new();
- for child in projection::children(&root, &txn) { spans(&child, &mut offset, &mut ranges); }
let local = if anchor["sticky"].is_null() { anchor["offset"].as_u64().unwrap_or(0) as u32 } else {
let sticky: yrs::StickyIndex = serde_json::from_value(anchor["sticky"].clone()).map_err(|_| "invalid_anchor")?;
sticky.get_offset(&txn).map(|value| value.index).unwrap_or(0)
};
- if let Some(range) = ranges.iter().find(|r| Some(r.node.as_str()) == anchor["node"].as_str()) {
- return Ok(range.start + local.min(range.length));
+ let target: Option<BranchPtr> = anchor["node"].as_str().and_then(projection::nested_id).and_then(|id| yrs::BranchID::get_nested(&txn, &id));
+ if let Some(target) = target {
+ let mut found = None;
+ walk(&root, &txn, &mut 0, &mut |node, start, length, _| {
+ if projection::branch_eq(node.as_ptr(), target) { found = Some(start + local.min(length)); true } else { false }
+ });
+ if let Some(found) = found { return Ok(found); }
+ }
+ Ok((anchor["fallback"].as_u64().unwrap_or(0) as u32).min(display_length(&root, &txn).saturating_sub(1)))
+}
+/// The identities of the leaf blocks (paragraph, heading, code block, rule)
+/// in document order.
+pub(crate) fn leaf_blocks<T: ReadTxn>(fragment: &XmlFragmentRef, txn: &T, ids: &mut Vec<BranchPtr>) {
+ for (_, child) in projection::indexed_children(fragment, txn) {
+ match &child {
+ XmlOut::Element(element) if ["paragraph", "heading", "code_block", "horizontal_rule"].contains(&element.tag().as_ref()) => ids.push(child.as_ptr()),
+ XmlOut::Element(element) => leaf_blocks(element.as_ref(), txn, ids),
+ XmlOut::Fragment(fragment) => leaf_blocks(fragment, txn, ids),
+ XmlOut::Text(_) => {},
+ }
}
- Ok((anchor["fallback"].as_u64().unwrap_or(0) as u32).min(offset.saturating_sub(1)))
}
diff --git a/native/crdt/src/lib.rs b/native/crdt/src/lib.rs
index d714f5a..2b2bc38 100644
--- a/native/crdt/src/lib.rs
+++ b/native/crdt/src/lib.rs
@@ -9,8 +9,8 @@ mod paste;
mod lists;
mod input_rules;
use serde_json::{json, Value};
-use std::{cell::RefCell, collections::HashSet, sync::{Arc, Mutex}};
-use yrs::{Doc, OffsetKind, Options, ReadTxn, StateVector, Transact, UndoManager, Update};
+use std::{cell::RefCell, collections::{HashMap, HashSet}, sync::{Arc, Mutex}};
+use yrs::{BranchID, Doc, OffsetKind, Options, ReadTxn, StateVector, Transact, UndoManager, Update, XmlOut, ID};
use yrs::updates::decoder::{Decode, Decoder, DecoderV1};
use yrs::updates::encoder::Encode;
@@ -21,6 +21,18 @@ pub struct Editor {
/// exactly what Yjs emits as `doc.on('update')`.
transactions: Arc<Mutex<Vec<Vec<u8>>>>,
_updates: yrs::Subscription,
+ /// What the last projection handed out held, and which of its top-level
+ /// blocks any transaction has touched since, so `projection_delta`
+ /// re-projects only those.
+ presented: Arc<Mutex<Presented>>,
+}
+#[derive(Default)]
+struct Presented {
+ blocks: Option<Vec<ID>>,
+ touched: HashSet<ID>,
+}
+fn top_level_id(node: &XmlOut) -> Option<ID> {
+ match node.id() { BranchID::Nested(id) => Some(id), BranchID::Root(_) => None }
}
impl Editor {
pub fn new(guid: &str, client_id: u64) -> Self {
@@ -39,7 +51,26 @@ impl Editor {
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}
+ let presented = Arc::new(Mutex::new(Presented::default()));
+ let touched = presented.clone();
+ let root_branch = projection::fragment_ptr(&root);
+ // changed_parent_types lists every changed branch and all its
+ // ancestors, so the top-level blocks among them are exactly those
+ // whose content, attributes or descendants this transaction changed.
+ // After observers, before garbage collection: every listed branch is
+ // still alive, including one this transaction deleted.
+ doc.observe_after_transaction_with("docs-presented", move |txn| {
+ let mut blocks = Vec::new();
+ for branch in txn.changed_parent_types() {
+ let Ok(node) = XmlOut::try_from(*branch) else { continue };
+ let parent = match &node { XmlOut::Element(e) => yrs::Xml::parent(e), XmlOut::Text(t) => yrs::Xml::parent(t), XmlOut::Fragment(f) => f.parent() };
+ if parent.is_some_and(|parent| projection::branch_eq(parent.as_ptr(), root_branch)) {
+ if let Some(id) = top_level_id(&node) { blocks.push(id); }
+ }
+ }
+ if !blocks.is_empty() { if let Ok(mut touched) = touched.lock() { touched.touched.extend(blocks); } }
+ }).expect("no transaction is open while the editor is created");
+ Self {doc, undo, transactions, _updates, presented}
}
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) }
@@ -88,11 +119,69 @@ impl Editor {
pub fn snapshot(&self) -> Vec<u8> {
self.doc.transact().encode_state_as_update_v1(&StateVector::default())
}
+ /// The whole document. It also becomes the base `projection_delta`
+ /// reports changes against.
pub fn projection(&self) -> Value {
let root = self.doc.get_or_insert_xml_fragment("prosemirror");
let txn = self.doc.transact();
- json!({"children": projection::children(&root, &txn), "canUndo": !self.undo.undo_stack().is_empty(), "canRedo": !self.undo.redo_stack().is_empty()})
+ let mut blocks = Vec::new();
+ let children: Vec<Value> = projection::indexed_children(&root, &txn).map(|(_, node)| {
+ if let Some(id) = top_level_id(&node) { blocks.push(id); }
+ projection::project(&node, &txn)
+ }).collect();
+ if let Ok(mut presented) = self.presented.lock() { presented.blocks = Some(blocks); presented.touched.clear(); }
+ json!({"children": children, "canUndo": !self.undo.undo_stack().is_empty(), "canRedo": !self.undo.redo_stack().is_empty()})
+ }
+ /// What changed since the last projection or delta, as edits to its list
+ /// of top-level blocks: `keep` n unchanged blocks, `remove` n, `insert`
+ /// these freshly projected blocks. Applied in order to the previous
+ /// children (`base` long) they give the current ones (`count` long). Only
+ /// blocks a transaction touched, and new ones, are projected.
+ pub fn projection_delta(&self) -> Value {
+ let root = self.doc.get_or_insert_xml_fragment("prosemirror");
+ let txn = self.doc.transact();
+ let (previous, touched) = match self.presented.lock() {
+ Ok(mut presented) => (presented.blocks.take().unwrap_or_default(), std::mem::take(&mut presented.touched)),
+ Err(_) => (Vec::new(), HashSet::new()),
+ };
+ let position: HashMap<ID, usize> = previous.iter().enumerate().map(|(index, id)| (*id, index)).collect();
+ let mut ops: Vec<Value> = Vec::new();
+ fn count(ops: &mut Vec<Value>, kind: &str, n: usize) {
+ if n == 0 { return; }
+ if let Some(last) = ops.last_mut().filter(|last| last[kind].is_u64()) { last[kind] = json!(last[kind].as_u64().unwrap_or(0) + n as u64); }
+ else { ops.push(json!({kind: n})); }
+ }
+ fn insert(ops: &mut Vec<Value>, node: Value) {
+ match ops.last_mut().and_then(|last| last["insert"].as_array_mut()) {
+ Some(nodes) => nodes.push(node),
+ None => ops.push(json!({"insert": [node]})),
+ }
+ }
+ let mut blocks = Vec::new();
+ let mut base = 0;
+ for (_, node) in projection::indexed_children(&root, &txn) {
+ let id = top_level_id(&node);
+ if let Some(id) = id { blocks.push(id); }
+ let unchanged = id.filter(|id| !touched.contains(id)).and_then(|id| position.get(&id).copied()).filter(|at| *at >= base);
+ match unchanged {
+ Some(at) => {
+ count(&mut ops, "remove", at - base);
+ count(&mut ops, "keep", 1);
+ base = at + 1;
+ },
+ None => insert(&mut ops, projection::project(&node, &txn)),
+ }
+ }
+ count(&mut ops, "remove", previous.len() - base);
+ let count = blocks.len();
+ if let Ok(mut presented) = self.presented.lock() { presented.blocks = Some(blocks); }
+ json!({"base": previous.len(), "count": count, "ops": ops, "canUndo": !self.undo.undo_stack().is_empty(), "canRedo": !self.undo.redo_stack().is_empty()})
}
+ /// The node and local offset a display range maps to (for tests).
+ #[doc(hidden)]
+ pub fn display_locate(&self, at: u32, length: u32) -> Result<(String, u32), &'static str> { display::locate(&self.doc, at, length) }
+ #[doc(hidden)]
+ pub fn display_length(&self) -> u32 { display::display_length(&self.doc.get_or_insert_xml_fragment("prosemirror"), &self.doc.transact()) }
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
@@ -237,6 +326,7 @@ pub fn dispatch(bytes: &[u8]) -> Result<Vec<u8>, &'static str> {
Some("resolve") => serde_json::to_vec(&editor.resolve(&request["anchor"])?).map_err(|_| "invalid_anchor"),
Some("clients") => serde_json::to_vec(&editor.doc.transact().state_vector().iter().map(|(id, _)| *id).collect::<Vec<_>>()).map_err(|_| "invalid_projection"),
Some("project") => serde_json::to_vec(&editor.projection()).map_err(|_| "invalid_projection"),
+ Some("project_delta") => serde_json::to_vec(&editor.projection_delta()).map_err(|_| "invalid_projection"),
_ => editor.command(&request),
}
})
diff --git a/native/crdt/src/operations.rs b/native/crdt/src/operations.rs
index a190b14..247876e 100644
--- a/native/crdt/src/operations.rs
+++ b/native/crdt/src/operations.rs
@@ -48,7 +48,7 @@ pub fn execute(doc: &Doc, request: &Value) -> Result<(), &'static str> {
let end = at.checked_add(length).ok_or("invalid_range")?;
// XmlText GetString includes formatting markup; Text::get_string does
// too for XML. Build raw text from deltas for offset validation.
- let raw: String = text.diff(&txn, |_| ()).iter().map(|r| r.insert.clone().to_string(&txn)).collect();
+ let raw = projection::raw_text(&text, &txn);
if !boundary(&raw, at) || !boundary(&raw, end) { return Err("invalid_range"); }
let marks = attrs(&request["marks"])?;
if op == "format" { text.format(&mut txn, at, length, marks); }
diff --git a/native/crdt/src/projection.rs b/native/crdt/src/projection.rs
index fc837b5..6a06b7d 100644
--- a/native/crdt/src/projection.rs
+++ b/native/crdt/src/projection.rs
@@ -1,18 +1,75 @@
use serde_json::{json, Value};
-use yrs::{ReadTxn, Text, Xml, XmlFragment, XmlFragmentRef, XmlOut};
+use yrs::branch::BranchPtr;
+use yrs::{Any, Array, ArrayRef, BranchID, Out, ReadTxn, Text, Xml, XmlFragment, XmlFragmentRef, XmlOut, XmlTextRef, ID};
pub fn node_id(node: &XmlOut) -> String {
serde_json::to_string(&node.id()).expect("branch identity serializes")
}
+/// A node identity as `node_id` writes it. Anything else (another spelling,
+/// a root) names no node, as when nodes were found by comparing strings.
+pub fn nested_id(id: &str) -> Option<ID> {
+ let parsed: BranchID = serde_json::from_str(id).ok()?;
+ if serde_json::to_string(&parsed).ok()? != id { return None; }
+ match parsed { BranchID::Nested(id) => Some(id), BranchID::Root(_) => None }
+}
+pub fn branch(node: &XmlOut) -> BranchPtr { node.as_ptr() }
+fn xml(value: Out) -> Option<XmlOut> {
+ match value {
+ Out::YXmlElement(element) => Some(XmlOut::Element(element)),
+ Out::YXmlText(text) => Some(XmlOut::Text(text)),
+ Out::YXmlFragment(fragment) => Some(XmlOut::Fragment(fragment)),
+ _ => None,
+ }
+}
+/// The live XML children of a fragment in order, each with the index
+/// `XmlFragment::get` gives it (values that are not XML count, and are
+/// skipped). One pass over the item list, where `get(i)` per child walks the
+/// list from its start every time.
+pub fn indexed_children<'a, T: ReadTxn>(fragment: &XmlFragmentRef, txn: &'a T) -> impl Iterator<Item = (u32, XmlOut)> + 'a {
+ let array: &ArrayRef = fragment.as_ref();
+ array.iter(txn).enumerate().filter_map(|(index, value)| xml(value).map(|node| (index as u32, node)))
+}
+pub fn fragment_of(node: &XmlOut) -> Option<XmlFragmentRef> {
+ match node {
+ XmlOut::Element(element) => Some(AsRef::<XmlFragmentRef>::as_ref(element).clone()),
+ XmlOut::Fragment(fragment) => Some(fragment.clone()),
+ XmlOut::Text(_) => None,
+ }
+}
pub fn children<T: ReadTxn>(root: &XmlFragmentRef, txn: &T) -> Vec<Value> {
- (0..root.len(txn)).filter_map(|i| root.get(txn, i)).map(|node| project(&node, txn)).collect()
+ indexed_children(root, txn).map(|(_, node)| project(&node, txn)).collect()
}
-fn project<T: ReadTxn>(node: &XmlOut, txn: &T) -> Value {
+/// A text's runs, each exactly as long in UTF-16 as the text positions it
+/// covers: the display is then the text's `len` (yrs' UTF-16 content length)
+/// and a display offset is a yrs offset. Strings are themselves; an embed is
+/// one U+FFFC. Content Yjs editors never put in a text (an embedded string or
+/// array, JSON, binary) is shown as U+FFFC padding, or trimmed, so the length
+/// still holds.
+pub fn runs<T: ReadTxn>(text: &XmlTextRef, txn: &T) -> Vec<(String, Option<Box<yrs::types::Attrs>>)> {
+ let length = text.len(txn) as usize;
+ let mut total = 0usize;
+ let mut runs: Vec<(String, Option<Box<yrs::types::Attrs>>)> = text.diff(txn, |_| ()).into_iter().map(|run| {
+ let insert = match run.insert { Out::Any(Any::String(value)) => value.to_string(), _ => "\u{FFFC}".to_owned() };
+ total += insert.encode_utf16().count();
+ (insert, run.attributes)
+ }).collect();
+ if total < length { runs.push(("\u{FFFC}".repeat(length - total), None)); }
+ while total > length {
+ let Some((last, _)) = runs.last_mut() else { break };
+ let Some(ch) = last.pop() else { runs.pop(); continue };
+ total -= ch.len_utf16();
+ if total < length { last.push_str(&"\u{FFFC}".repeat(length - total)); total = length; }
+ if last.is_empty() { runs.pop(); }
+ }
+ runs
+}
+pub fn raw_text<T: ReadTxn>(text: &XmlTextRef, txn: &T) -> String {
+ runs(text, txn).into_iter().map(|(insert, _)| insert).collect()
+}
+pub fn project<T: ReadTxn>(node: &XmlOut, txn: &T) -> Value {
match node {
XmlOut::Text(text) => {
- let runs: Vec<_> = text.diff(txn, |_| ()).iter().map(|run| {
- json!({"insert": run.insert.clone().to_string(txn), "marks": run.attributes})
- }).collect();
+ let runs: Vec<_> = runs(text, txn).into_iter().map(|(insert, marks)| json!({"insert": insert, "marks": marks})).collect();
json!({"id": node_id(node), "type": "text", "runs": runs})
},
XmlOut::Element(element) => {
@@ -23,16 +80,34 @@ fn project<T: ReadTxn>(node: &XmlOut, txn: &T) -> Value {
XmlOut::Fragment(fragment) => json!({"id": node_id(node), "type": "fragment", "children": children(fragment, txn)}),
}
}
+/// A live node reachable from `root` through children, with its parent and
+/// its index there: what a depth-first search comparing every node's
+/// `node_id` used to find, looked up by identity and checked upwards.
+pub fn locate<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, id: &str) -> Option<(XmlOut, XmlFragmentRef, u32)> {
+ let branch = BranchID::get_nested(txn, &nested_id(id)?)?;
+ resolve(root, txn, branch)
+}
+pub fn locate_branch<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, branch: BranchPtr) -> Option<(XmlOut, XmlFragmentRef, u32)> {
+ resolve(root, txn, branch)
+}
+fn resolve<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, branch: BranchPtr) -> Option<(XmlOut, XmlFragmentRef, u32)> {
+ let node = XmlOut::try_from(branch).ok()?;
+ if branch.is_deleted() { return None; }
+ let parent = match &node {
+ XmlOut::Element(element) => element.parent(),
+ XmlOut::Text(text) => text.parent(),
+ XmlOut::Fragment(fragment) => fragment.parent(),
+ }?;
+ let container = fragment_of(&parent)?;
+ // Being some child's parent is not enough: the node must be one of its
+ // live children (not, say, an attribute value), and so must each ancestor.
+ let index = indexed_children(&container, txn).find(|(_, child)| branch_eq(child.as_ptr(), branch)).map(|(index, _)| index)?;
+ let container_branch = parent.as_ptr();
+ if !branch_eq(container_branch, fragment_ptr(root)) { resolve(root, txn, container_branch)?; }
+ Some((node, container, index))
+}
+pub fn branch_eq(a: BranchPtr, b: BranchPtr) -> bool { a == b }
pub fn find<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, id: &str) -> Option<XmlOut> {
- for index in 0..root.len(txn) {
- let node = root.get(txn, index)?;
- if node_id(&node) == id { return Some(node); }
- let nested = match &node {
- XmlOut::Element(el) => find(el.as_ref(), txn, id),
- XmlOut::Fragment(f) => find(f, txn, id),
- _ => None,
- };
- if nested.is_some() { return nested; }
- }
- None
+ locate(root, txn, id).map(|(node, _, _)| node)
}
+pub fn fragment_ptr(fragment: &XmlFragmentRef) -> BranchPtr { BranchPtr::from(AsRef::<yrs::branch::Branch>::as_ref(fragment)) }
diff --git a/native/crdt/src/structure.rs b/native/crdt/src/structure.rs
index 8863906..ac743b9 100644
--- a/native/crdt/src/structure.rs
+++ b/native/crdt/src/structure.rs
@@ -5,13 +5,7 @@ use yrs::types::{AsPrelim, Delta};
use yrs::types::xml::{XmlDeltaPrelim, XmlIn};
pub(crate) fn parent<T: ReadTxn>(root: &XmlFragmentRef, txn: &T, id: &str) -> Option<(XmlFragmentRef, u32)> {
- for index in 0..root.len(txn) {
- let node = root.get(txn, index)?;
- if projection::node_id(&node) == id { return Some((root.clone(), index)); }
- let found = match node { XmlOut::Element(e) => parent(e.as_ref(), txn, id), XmlOut::Fragment(f) => parent(&f, txn, id), _ => None };
- if found.is_some() { return found; }
- }
- None
+ projection::locate(root, txn, id).map(|(_, parent, index)| (parent, index))
}
fn number(value: &Value) -> Result<u32, &'static str> { value.as_u64().and_then(|v| v.try_into().ok()).ok_or("invalid_range") }
fn slice(text: &str, from: u32) -> Result<String, &'static str> {
@@ -19,11 +13,6 @@ fn slice(text: &str, from: u32) -> Result<String, &'static str> {
if from as usize > units.len() { return Err("invalid_range"); }
String::from_utf16(&units[from as usize..]).map_err(|_| "invalid_range")
}
-fn leaf_blocks(value: &serde_json::Value, ids: &mut Vec<String>) {
- if ["paragraph", "heading", "code_block", "horizontal_rule"].contains(&value["type"].as_str().unwrap_or("")) {
- if let Some(id) = value["id"].as_str() { ids.push(id.to_owned()); }
- } else if let Some(children) = value["children"].as_array() { for child in children { leaf_blocks(child, ids); } }
-}
fn clean_empty_containers(root: &XmlFragmentRef, txn: &mut yrs::TransactionMut) {
for index in (0..root.len(txn)).rev() {
if let Some(XmlOut::Element(element)) = root.get(txn,index) {
@@ -89,12 +78,12 @@ pub fn execute(doc: &Doc, request: &Value) -> Result<(), &'static str> {
let end_at = number(&request["end_at"])?;
let (start_parent, start_index) = parent(&root, &txn, &projection::node_id(&XmlOut::Text(start_text.clone()))).ok_or("missing_parent")?;
let (end_parent, end_index) = parent(&root, &txn, &projection::node_id(&XmlOut::Text(end_text.clone()))).ok_or("missing_parent")?;
- let start_block_id = projection::node_id(&XmlOut::Fragment(start_parent.clone()));
- let end_block_id = projection::node_id(&XmlOut::Fragment(end_parent.clone()));
+ let start_block = projection::fragment_ptr(&start_parent);
+ let end_block = projection::fragment_ptr(&end_parent);
let mut blocks = Vec::new();
- for child in projection::children(&root, &txn) { leaf_blocks(&child, &mut blocks); }
- let first = blocks.iter().position(|v| v == &start_block_id).ok_or("missing_node")?;
- let last = blocks.iter().position(|v| v == &end_block_id).ok_or("missing_node")?;
+ crate::display::leaf_blocks(&root, &txn, &mut blocks);
+ let first = blocks.iter().position(|v| *v == start_block).ok_or("missing_node")?;
+ let last = blocks.iter().position(|v| *v == end_block).ok_or("missing_node")?;
if first > last { return Err("invalid_range"); }
let raw: String = start_text.diff(&txn, |_| ()).iter().map(|r| r.insert.clone().to_string(&txn)).collect();
slice(&raw, start_at)?;
@@ -118,7 +107,7 @@ pub fn execute(doc: &Doc, request: &Value) -> Result<(), &'static str> {
if count > 0 { start_parent.remove_range(&mut txn, start_index + 1, count); }
for (offset, child) in trailing.into_iter().enumerate() { start_parent.insert(&mut txn, start_index + 1 + offset as u32, child); }
for block in &blocks[first + 1..=last] {
- let (parent, index) = parent(&root, &txn, block).ok_or("missing_parent")?;
+ let (_, parent, index) = projection::locate_branch(&root, &txn, *block).ok_or("missing_parent")?;
parent.remove(&mut txn, index);
}
clean_empty_containers(&root,&mut txn);
diff --git a/native/crdt/tests/display_mapping.rs b/native/crdt/tests/display_mapping.rs
new file mode 100644
index 0000000..8d3d61b
--- /dev/null
+++ b/native/crdt/tests/display_mapping.rs
@@ -0,0 +1,145 @@
+//! Finding 2 of the native realtime audit: display positions are mapped by
+//! walking the tree, not by building the projection. The walk must agree,
+//! position by position, with the projection-based mapping it replaced
+//! (support::oracle), on edited documents and on every kind of node.
+mod support;
+use docs_native_crdt::Editor;
+use serde_json::{json, Value};
+use support::{generate, oracle, oracle_locate, Random};
+
+fn open(bytes: &[u8], client: u64) -> Editor {
+ let editor = Editor::new("large-document", client);
+ editor.apply(bytes).unwrap();
+ editor
+}
+/// The display text, rendered from the projection the way the apps do.
+fn render(value: &Value, out: &mut Vec<u16>) {
+ match value["type"].as_str().unwrap_or("") {
+ "text" => for run in value["runs"].as_array().into_iter().flatten() { out.extend(run["insert"].as_str().unwrap().encode_utf16()); },
+ "hard_break" => out.push(0x2028),
+ "image" => out.push(0xFFFC),
+ "horizontal_rule" => out.extend([0xFFFC, 10]),
+ tag => {
+ for child in value["children"].as_array().into_iter().flatten() { render(child, out); }
+ if ["paragraph", "heading", "code_block"].contains(&tag) { out.push(10); }
+ },
+ }
+}
+fn display(editor: &Editor) -> Vec<u16> {
+ let mut out = Vec::new();
+ for child in editor.projection()["children"].as_array().unwrap() { render(child, &mut out); }
+ out
+}
+fn check_every_position(editor: &Editor, step: u32) {
+ let projection = editor.projection();
+ let (ranges, total) = oracle(&projection);
+ assert_eq!(editor.display_length(), total);
+ assert_eq!(display(editor).len() as u32, total);
+ let mut at = 0;
+ while at <= total + 1 {
+ for length in [0, 1, 3, 40] {
+ let expected = oracle_locate(&ranges, at, length);
+ let actual = editor.display_locate(at, length).ok();
+ assert_eq!(actual, expected, "locate({at}, {length})");
+ }
+ let anchor = editor.anchor(at).unwrap();
+ let expected = match oracle_locate(&ranges, at, 0) {
+ Some((node, local)) => {
+ let span = ranges.iter().find(|r| r.node == node).unwrap();
+ assert_eq!(anchor["node"], node);
+ span.start + local.min(span.length)
+ },
+ None => at.min(total.saturating_sub(1)),
+ };
+ assert_eq!(editor.resolve(&anchor).unwrap(), expected, "resolve(anchor({at}))");
+ at += step;
+ }
+}
+
+#[test]
+fn walk_matches_the_projection_mapping_on_edited_documents() {
+ for (pages, edits, step) in [(1, 0, 1), (2, 120, 1), (8, 900, 7)] {
+ let editor = open(&generate(pages, edits, 11), 101);
+ check_every_position(&editor, step);
+ }
+}
+
+#[test]
+fn walk_matches_on_every_kind_of_node() {
+ let mut editor = Editor::new("kinds", 201);
+ editor.command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap();
+ editor.command(&json!({"op":"display_paste","at":0,"length":0,"blocks":[
+ {"type":"heading","attrs":{"level":"1"},"children":[{"type":"text","runs":[{"insert":"Title 😀","marks":{"strong":{}}}]}]},
+ {"type":"paragraph","children":[]},
+ {"type":"paragraph","children":[{"type":"text","runs":[{"insert":"before","marks":{}}]},{"type":"hard_break"},{"type":"text","runs":[{"insert":"after","marks":{"em":{}}}]},{"type":"image","attrs":{"src":"https://example.com/a.png"}}]},
+ {"type":"horizontal_rule"},
+ {"type":"code_block","children":[{"type":"text","runs":[{"insert":"let x = 1;\nlet y = 2;","marks":{}}]}]},
+ {"type":"blockquote","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"quoted","marks":{}}]}]}]},
+ {"type":"bullet_list","children":[
+ {"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"one","marks":{}}]}]},
+ {"type":"ordered_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[]}]}]}]},
+ {"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"two","marks":{}}]}]}]}
+ ]},
+ {"type":"image","attrs":{"src":"https://example.com/b.png"}},
+ {"type":"paragraph","children":[{"type":"hard_break"},{"type":"hard_break"}]}
+ ]})).unwrap();
+ check_every_position(&editor, 1);
+ // Empty text nodes, as an edit next to an inline atom leaves them.
+ let length = editor.display_length();
+ for at in (0..length).rev().step_by(3) { let _ = editor.command(&json!({"op":"display_edit","at":at,"length":0,"text":"z"})); }
+ check_every_position(&editor, 1);
+}
+
+#[test]
+fn typing_anywhere_edits_exactly_that_display_position() {
+ let mut editor = open(&generate(6, 600, 12), 301);
+ let mut random = Random::new(5);
+ for round in 0..200 {
+ let before = display(&editor);
+ let total = before.len() as u32;
+ let at = random.below(total as u64) as u32;
+ // Stay inside one text: never across a block end or an atom.
+ let length = if round % 3 == 0 { (1..=3).take_while(|n| at + n < total && !before[(at as usize)..(at + n) as usize].iter().any(|u| [10, 0x2028, 0xFFFC].contains(u))).last().unwrap_or(0) } else { 0 };
+ if at > 0 && (0xDC00..0xE000).contains(&before[at as usize]) { continue; }
+ if (0xDC00..0xE000).contains(&before[(at + length) as usize]) { continue; }
+ let text = ["k", "é", "😀", "two words"][round % 4];
+ editor.command(&json!({"op":"display_edit","at":at,"length":length,"text":text})).unwrap_or_else(|e| panic!("edit {at}+{length}: {e}"));
+ let mut expected = before[..at as usize].to_vec();
+ expected.extend(text.encode_utf16());
+ expected.extend(&before[(at + length) as usize..]);
+ assert_eq!(display(&editor), expected, "round {round}: {at}+{length} {text}");
+ }
+}
+
+#[test]
+fn a_text_holding_an_embed_maps_one_position_per_unit() {
+ // Yjs editors never embed values in a text, but a peer can. The display
+ // shows the embed as one U+FFFC, so display offsets stay yrs offsets.
+ use yrs::{Any, Doc, ReadTxn, StateVector, Text, Transact, XmlElementPrelim, XmlFragment, XmlTextPrelim, XmlOut};
+ let doc = Doc::with_options({ let mut o = yrs::Options::with_guid_and_client_id("embed".into(), 7); o.offset_kind = yrs::OffsetKind::Utf16; o });
+ let root = doc.get_or_insert_xml_fragment("prosemirror");
+ {
+ let mut txn = doc.transact_mut();
+ let paragraph = root.insert(&mut txn, 0, XmlElementPrelim::empty("paragraph"));
+ let text = paragraph.insert(&mut txn, 0, XmlTextPrelim::new("abcd"));
+ text.insert_embed(&mut txn, 2, Any::from(std::collections::HashMap::from([("k".to_owned(), Any::from("v"))])));
+ let _ = XmlOut::Text(text);
+ }
+ let bytes = doc.transact().encode_state_as_update_v1(&StateVector::default());
+ let mut editor = Editor::new("embed", 8);
+ editor.apply(&bytes).unwrap();
+ assert_eq!(display(&editor), "ab\u{FFFC}cd\n".encode_utf16().collect::<Vec<_>>());
+ assert_eq!(editor.display_length(), 6);
+ check_every_position(&editor, 1);
+ editor.command(&json!({"op":"display_edit","at":4,"length":0,"text":"X"})).unwrap();
+ assert_eq!(display(&editor), "ab\u{FFFC}cXd\n".encode_utf16().collect::<Vec<_>>());
+}
+
+#[test]
+fn projection_is_unchanged_for_documents_without_embeds() {
+ for (pages, edits) in [(1, 0), (3, 300), (10, 1200)] {
+ let bytes = generate(pages, edits, 13);
+ let editor = open(&bytes, 401);
+ assert_eq!(editor.projection()["children"], support::legacy_projection(&editor.snapshot())["children"], "{pages} pages, {edits} edits");
+ }
+}
diff --git a/native/crdt/tests/projection_delta.rs b/native/crdt/tests/projection_delta.rs
new file mode 100644
index 0000000..a302859
--- /dev/null
+++ b/native/crdt/tests/projection_delta.rs
@@ -0,0 +1,107 @@
+//! Finding 2(c) of the native realtime audit: after the first projection the
+//! authority reports only the top-level blocks that changed. Replaying the
+//! deltas onto the first projection must give exactly the whole projection
+//! after any mix of local commands, peers' updates, undo and redo.
+mod support;
+use docs_native_crdt::Editor;
+use serde_json::{json, Value};
+use support::{generate, legacy_projection, oracle, Random};
+
+fn open(bytes: &[u8], client: u64) -> Editor {
+ let editor = Editor::new("large-document", client);
+ editor.apply(bytes).unwrap();
+ editor
+}
+fn replay(children: &mut Vec<Value>, delta: &Value) -> usize {
+ assert_eq!(delta["base"].as_u64().unwrap() as usize, children.len());
+ let mut next = Vec::new(); let mut at = 0; let mut projected = 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 { let nodes = op["insert"].as_array().unwrap(); projected += nodes.len(); next.extend(nodes.iter().cloned()); }
+ }
+ assert_eq!(at, children.len(), "every previous block is kept or removed");
+ assert_eq!(next.len(), delta["count"].as_u64().unwrap() as usize);
+ *children = next;
+ projected
+}
+/// The current projection without touching the editor's delta base.
+fn truth(editor: &Editor) -> Value { legacy_projection(&editor.snapshot())["children"].clone() }
+
+#[test]
+fn typing_reprojects_only_the_block_typed_in() {
+ let mut editor = open(&generate(20, 300, 21), 501);
+ let mut children = editor.projection()["children"].as_array().unwrap().clone();
+ let (ranges, _) = oracle(&json!({"children": children}));
+ let at = ranges[ranges.len() / 2].start + 3;
+ for _ in 0..5 {
+ editor.command(&json!({"op":"display_edit","at":at,"length":0,"text":"k"})).unwrap();
+ let delta = editor.projection_delta();
+ assert_eq!(replay(&mut children, &delta), 1, "one block re-projected: {}", delta["ops"]);
+ assert_eq!(delta["ops"].as_array().unwrap().len(), 4, "keep, insert, remove, keep: {}", delta["ops"]);
+ }
+ assert_eq!(Value::Array(children), truth(&editor));
+ let unchanged = editor.projection_delta();
+ assert_eq!(unchanged["ops"], json!([{"keep": unchanged["count"]}]));
+}
+
+#[test]
+fn deltas_replay_to_the_whole_projection_through_every_kind_of_change() {
+ let base = generate(6, 400, 22);
+ 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 applied = std::collections::HashMap::<String, usize>::new();
+ for step in 0..160 {
+ let p = json!({"children": children.clone()});
+ let (ranges, total) = oracle(&p);
+ let texts: Vec<_> = ranges.iter().filter(|r| !r.atomic).collect();
+ let span = texts[random.below(texts.len() as u64) as usize];
+ let at = span.start + random.below(span.length as u64 + 1) as u32;
+ let command = match step % 11 {
+ 0 => json!({"op":"display_edit","at":at,"length":0,"text":"\nnew block"}),
+ 1 => json!({"op":"display_edit","at":at.min(total.saturating_sub(200)),"length":150,"text":"J"}),
+ 2 => json!({"op":"display_paste","at":at,"length":0,"blocks":[
+ {"type":"paragraph","children":[{"type":"text","runs":[{"insert":"pasted","marks":{"em":{}}}]}]},
+ {"type":"horizontal_rule"},
+ {"type":"bullet_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"item","marks":{}}]}]}]}]}]}),
+ 3 => json!({"op":"undo"}),
+ 4 => json!({"op":"redo"}),
+ 5 => json!({"op":"block","node":children[random.below(children.len() as u64) as usize]["id"],"type":"heading","level":2}),
+ 6 => json!({"op":"attribute","node":children[random.below(children.len() as u64) as usize]["id"],"name":"align","value":"center"}),
+ _ => json!({"op":"display_edit","at":at,"length":if step % 3 == 0 { span.length.min(2) } else { 0 },"text":"typed"}),
+ };
+ let local = authority.command(&command);
+ if local.is_ok() { *applied.entry(command["op"].as_str().unwrap().to_owned()).or_default() += 1; }
+ // Peers edit concurrently; their updates arrive in between.
+ let peer = &mut peers[step % 3];
+ let peer_p = peer.projection();
+ 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();
+ 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}");
+ }
+ }
+ for op in ["display_edit", "display_paste", "undo", "redo", "block", "attribute"] { assert!(applied.get(op).copied().unwrap_or(0) >= 5, "{op} ran: {applied:?}"); }
+ let delta = authority.projection_delta();
+ assert_eq!(delta["canUndo"], authority.projection()["canUndo"]);
+}
+
+#[test]
+fn a_full_projection_resets_the_delta_base() {
+ let mut editor = open(&generate(2, 0, 23), 701);
+ let _ = editor.projection();
+ editor.command(&json!({"op":"display_edit","at":5,"length":0,"text":"a"})).unwrap();
+ let mut children = editor.projection()["children"].as_array().unwrap().clone();
+ let delta = editor.projection_delta();
+ assert_eq!(delta["ops"], json!([{"keep": children.len()}]));
+ replay(&mut children, &delta);
+}
diff --git a/native/crdt/tests/support/mod.rs b/native/crdt/tests/support/mod.rs
index 4a4c39b..e312445 100644
--- a/native/crdt/tests/support/mod.rs
+++ b/native/crdt/tests/support/mod.rs
@@ -172,3 +172,32 @@ pub fn oracle_locate(ranges: &[Span], at: u32, length: u32) -> Option<(String, u
.or_else(|| ranges.iter().find(|r| r.atomic && at >= r.start && end <= r.start + r.length))
.map(|r| (r.node.clone(), at - r.start))
}
+
+/// The projection exactly as projection.rs built it at 8e54d3a (children by
+/// index, runs by `to_string`): the oracle for documents without embeds.
+pub fn legacy_projection(bytes: &[u8]) -> Value {
+ use serde_json::json;
+ use yrs::{Xml, XmlFragmentRef};
+ fn node_id(node: &XmlOut) -> String { serde_json::to_string(&node.id()).unwrap() }
+ fn children<T: ReadTxn>(root: &XmlFragmentRef, txn: &T) -> Vec<Value> {
+ (0..root.len(txn)).filter_map(|i| root.get(txn, i)).map(|node| project(&node, txn)).collect()
+ }
+ fn project<T: ReadTxn>(node: &XmlOut, txn: &T) -> Value {
+ match node {
+ XmlOut::Text(text) => {
+ let runs: Vec<_> = text.diff(txn, |_| ()).iter().map(|run| json!({"insert": run.insert.clone().to_string(txn), "marks": run.attributes})).collect();
+ json!({"id": node_id(node), "type": "text", "runs": runs})
+ },
+ XmlOut::Element(element) => {
+ let attrs: serde_json::Map<String, Value> = element.attributes(txn).map(|(key,value)| (key.to_string(), Value::String(value))).collect();
+ json!({"id": node_id(node), "type": element.tag().as_ref(), "attrs": attrs, "children": children(element.as_ref(), txn)})
+ },
+ XmlOut::Fragment(fragment) => json!({"id": node_id(node), "type": "fragment", "children": children(fragment, txn)}),
+ }
+ }
+ let doc = Doc::with_options(options(1));
+ doc.transact_mut().apply_update(Update::decode_v1(bytes).unwrap()).unwrap();
+ let root = doc.get_or_insert_xml_fragment("prosemirror");
+ let txn = doc.transact();
+ json!({"children": children(&root, &txn)})
+}
diff --git a/native/host/examples/realtime.rs b/native/host/examples/realtime.rs
new file mode 100644
index 0000000..7a4658d
--- /dev/null
+++ b/native/host/examples/realtime.rs
@@ -0,0 +1,76 @@
+//! Engine cost per keystroke and per remote change, through the production
+//! interpreter and fuel (native realtime audit, findings 2, 7 and 9).
+//!
+//! cargo run --release --example realtime -- /tmp/rt-audit/docs/p*.bin
+//!
+//! Documents come from fixtures/generate-large-doc.mjs. Each keystroke is
+//! what CRDTReplica does for one typed character: `display_edit` on the
+//! displayed source, the update applied to the authority, the selection's
+//! two anchors resolved, and the authority's presentation (`project_delta`
+//! where the module has it, else the whole projection).
+use docs_native_host::Host;
+use serde_json::{json, Value};
+use std::time::Instant;
+
+fn call(host: &mut Host, request: &Value) -> Result<Vec<u8>, &'static str> { host.call(&serde_json::to_vec(request).unwrap()).map(<[u8]>::to_vec) }
+fn median(mut v: Vec<f64>) -> f64 { v.sort_by(|a, b| a.partial_cmp(b).unwrap()); if v.is_empty() { f64::NAN } else { v[v.len() / 2] } }
+fn open(bytes: &[u8], client: u64) -> Result<Host, &'static str> {
+ let mut host = Host::new()?;
+ call(&mut host, &json!({"op":"open","guid":"bench","client":client}))?;
+ let mut envelope = vec![255]; envelope.extend_from_slice(bytes);
+ host.call(&envelope)?;
+ Ok(host)
+}
+fn text_offset(projection: &Value) -> u32 {
+ // The middle of the document, inside a text run.
+ fn walk(v: &Value, offset: &mut u32, out: &mut Vec<(u32, u32)>) {
+ match v["type"].as_str().unwrap_or("") {
+ "text" => { let n: u32 = v["runs"].as_array().unwrap().iter().map(|r| r["insert"].as_str().unwrap().encode_utf16().count() as u32).sum(); out.push((*offset, n)); *offset += n; },
+ "hard_break" | "image" => *offset += 1,
+ "horizontal_rule" => *offset += 2,
+ tag => { for c in v["children"].as_array().into_iter().flatten() { walk(c, offset, out); } if ["paragraph","heading","code_block"].contains(&tag) { *offset += 1; } },
+ }
+ }
+ let mut offset = 0; let mut texts = Vec::new();
+ for c in projection["children"].as_array().unwrap() { walk(c, &mut offset, &mut texts); }
+ let (start, n) = texts.iter().copied().filter(|(_, n)| *n > 20).nth(texts.len() / 2).unwrap_or(texts[0]);
+ start + n / 2
+}
+fn main() {
+ for path in std::env::args().skip(1) {
+ let name = std::path::Path::new(&path).file_stem().unwrap().to_string_lossy().to_string();
+ let bytes = std::fs::read(&path).unwrap();
+ let t = Instant::now();
+ let (mut authority, mut source) = match (open(&bytes, 11), open(&bytes, 12)) { (Ok(a), Ok(s)) => (a, s), _ => { println!("{name:6} open FAILED (fuel)"); continue; } };
+ let opened = t.elapsed().as_secs_f64() * 1e3 / 2.0;
+ // An unknown op poisons a host, so ask a throwaway one.
+ let delta = open(b"\0\0", 13).ok().and_then(|mut probe| call(&mut probe, &json!({"op":"project_delta"})).ok()).is_some();
+ let projection: Value = match call(&mut authority, &json!({"op":"project"})) { Ok(p) => serde_json::from_slice(&p).unwrap(), Err(e) => { println!("{name:6} project FAILED ({e})"); continue; } };
+ let mut at = text_offset(&projection);
+ let (mut command, mut apply, mut anchors, mut present, mut sizes) = (vec![], vec![], vec![], vec![], vec![]);
+ let mut failed = None;
+ for _ in 0..12 {
+ let t = Instant::now();
+ let update = match call(&mut source, &json!({"op":"display_edit","at":at,"length":0,"text":"x"})) { Ok(u) => u, Err(e) => { failed = Some(e); break; } };
+ command.push(t.elapsed().as_secs_f64() * 1e3); sizes.push(update.len());
+ let t = Instant::now();
+ let mut envelope = vec![254]; envelope.extend(&update);
+ if let Err(e) = authority.call(&envelope) { failed = Some(e); break; }
+ apply.push(t.elapsed().as_secs_f64() * 1e3);
+ let t = Instant::now();
+ for end in [at + 1, at + 1] {
+ let anchor: Value = match call(&mut source, &json!({"op":"anchor","at":end})) { Ok(a) => serde_json::from_slice(&a).unwrap(), Err(e) => { failed = Some(e); break; } };
+ if let Err(e) = call(&mut authority, &json!({"op":"resolve","anchor":anchor})) { failed = Some(e); break; }
+ }
+ anchors.push(t.elapsed().as_secs_f64() * 1e3);
+ let t = Instant::now();
+ let op = if delta { "project_delta" } else { "project" };
+ match call(&mut authority, &json!({"op":op})) { Ok(_) => present.push(t.elapsed().as_secs_f64() * 1e3), Err(e) => { failed = Some(e); break; } }
+ at += 1;
+ }
+ let keystroke: f64 = median(command.clone()) + median(apply.clone()) + median(anchors.clone()) + median(present.clone());
+ println!("{name:6} open {opened:7.1} ms | display_edit {:7.2} | authority apply {:6.2} | 2 anchors {:7.2} | {} {:7.2} | keystroke {keystroke:7.2} ms | update {} B{}",
+ median(command), median(apply), median(anchors), if delta { "delta" } else { "project" }, median(present), sizes.iter().max().unwrap_or(&0),
+ failed.map(|e| format!(" | FAILED: {e}")).unwrap_or_default());
+ }
+}
diff --git a/native/scripts/check-mutations.py b/native/scripts/check-mutations.py
index 28742fc..42884c5 100644
--- a/native/scripts/check-mutations.py
+++ b/native/scripts/check-mutations.py
@@ -13,7 +13,7 @@ cases = [
('crdt/src/lib.rs', 'if local { "native-edit" } else { "remote" }', 'if local { "remote" } else { "remote" }', 'distinct_display_generations_preserve_peer_and_authoritative_undo'),
('crdt/src/display.rs', 'cursor += 1;', 'cursor += 0;', 'optimistic_newline_typeahead_resolves_new_paragraph_in_source'),
('crdt/src/structure.rs', 'start_text.remove_range(&mut txn, start_at, tail);', 'let _ = tail;', 'cross_paragraph_replacement_keeps_prefix_id_and_formatted_suffix'),
- ('crdt/src/display.rs', 'range.start + local.min(range.length)', 'range.start', 'selection_anchor_tracks_peer_insertion_in_utf16'),
+ ('crdt/src/display.rs', 'found = Some(start + local.min(length))', 'found = Some(start)', 'selection_anchor_tracks_peer_insertion_in_utf16'),
('crdt/src/operations.rs', 'text.format(&mut txn, at, length, marks);', 'let _ = marks;', 'utf16_edits_preserve_identity_and_marks'),
('crdt/src/lib.rs', 'HashSet::from(["native-edit".into()])', 'HashSet::from(["native-edit".into(), "remote".into()])', 'concurrent_insertions_and_own_undo_preserve_peer'),
('crdt/src/lib.rs', 'remaining = &remaining[remaining.len() - trailing..];', 'remaining = &[];', 'concatenated_log_applies_every_update'),