oficina / docs Public

Docs native engine: record transaction updates only while a command runs

Review finding 2 (Fable, #145). The update observer was subscribed for
the editor's lifetime, so every applied update, the opening state
included, was encoded again and kept until the next command. The
authority runs commands only for undo and redo, so it held a second copy
of the opening state plus every update of the session, and every fresh
sandbox re-encoded the whole document on import.

The subscription now exists only for the duration of `command`.
Measured with host/examples/session_memory.rs (open, then 3,000 peer
updates applied one by one): linear memory at open 11.4 -> 9.5 MiB for
the 200-page edited document, 1.8 -> 1.5 MiB at 20 pages. Host gains a
hidden `memory_bytes` for that measurement. New test: applies between
commands leave the next command's update (and an undo's) minimal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 20448f64c8c51a77e11eb1a471343247dd7f5b80 parent 3070a2a
4 files changed, +49 −6
  • native/crdt/src/lib.rs +8 −6
  • native/crdt/tests/minimal_updates.rs +19 −0
  • native/host/examples/session_memory.rs +19 −0
  • native/host/src/lib.rs +3 −0
diff --git a/native/crdt/src/lib.rs b/native/crdt/src/lib.rs
index 2b2bc38..a60ab92 100644
--- a/native/crdt/src/lib.rs
+++ b/native/crdt/src/lib.rs
@@ -19,8 +19,9 @@ pub struct Editor {
undo: UndoManager,
/// The v1 update of every transaction committed while a command runs,
/// exactly what Yjs emits as `doc.on('update')`.
+ /// Subscribed only while a command runs: applying a peer's update or a
+ /// whole state must neither encode it again nor keep a copy.
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.
@@ -47,10 +48,6 @@ impl Editor {
timestamp: Arc::new(|| 1),
});
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");
let presented = Arc::new(Mutex::new(Presented::default()));
let touched = presented.clone();
let root_branch = projection::fragment_ptr(&root);
@@ -70,7 +67,7 @@ impl Editor {
}
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}
+ Self {doc, undo, transactions, 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) }
@@ -189,7 +186,12 @@ impl Editor {
/// state-vector diff, which carries the document's whole delete set.
pub fn command(&mut self, request: &Value) -> Result<Vec<u8>, &'static str> {
self.transactions.lock().map_err(|_| "invalid_command")?.clear();
+ let sink = self.transactions.clone();
+ let subscription = self.doc.observe_update_v1(move |_, event| {
+ if let Ok(mut sink) = sink.lock() { sink.push(event.update.clone()); }
+ }).map_err(|_| "invalid_command")?;
let result = self.execute(request);
+ drop(subscription);
let updates = std::mem::take(&mut *self.transactions.lock().map_err(|_| "invalid_command")?);
result?;
match updates.len() {
diff --git a/native/crdt/tests/minimal_updates.rs b/native/crdt/tests/minimal_updates.rs
index 1fbf6ea..674cced 100644
--- a/native/crdt/tests/minimal_updates.rs
+++ b/native/crdt/tests/minimal_updates.rs
@@ -107,3 +107,22 @@ fn a_command_that_changes_nothing_sends_an_empty_update() {
let update = editor.command(&json!({"op":"display_edit","at":3,"length":0,"text":""})).unwrap();
assert_eq!(update, Update::new().encode_v1());
}
+
+#[test]
+fn applying_updates_records_nothing_for_the_next_command() {
+ // Audit review finding 2: only a command's own transactions are kept;
+ // a peer's update or a whole state applied in between is neither encoded
+ // again nor carried by the next command's update.
+ let base = generate(3, 100, 4);
+ let mut editor = Editor::new("large-document", 80);
+ editor.apply(&base).unwrap();
+ let mut peer = open(&base, 81);
+ for _ in 0..20 {
+ let remote = peer.command(&json!({"op":"display_edit","at":7,"length":0,"text":"peer"})).unwrap();
+ editor.apply(&remote).unwrap();
+ }
+ let update = editor.command(&json!({"op":"display_edit","at":3,"length":0,"text":"x"})).unwrap();
+ assert!(update.len() <= 32, "{} bytes", update.len());
+ let undo = editor.command(&json!({"op":"undo"})).unwrap();
+ assert!(undo.len() <= 32, "undo carries only its own change: {} bytes", undo.len());
+}
diff --git a/native/host/examples/session_memory.rs b/native/host/examples/session_memory.rs
new file mode 100644
index 0000000..d730fe3
--- /dev/null
+++ b/native/host/examples/session_memory.rs
@@ -0,0 +1,19 @@
+//! WASM memory of an authority through a long session: open a document, then
+//! apply `n` peer updates one by one, as DocsModel.refresh does.
+//! cargo run --release --example session_memory -- doc.bin 2000
+use docs_native_host::Host;
+use serde_json::json;
+fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let bytes = std::fs::read(&args[1]).unwrap();
+ let n: usize = args.get(2).map(|v| v.parse().unwrap()).unwrap_or(2000);
+ let open = |client: u64| { let mut h = Host::new().unwrap(); h.call(&serde_json::to_vec(&json!({"op":"open","guid":"m","client":client})).unwrap()).unwrap(); let mut e = vec![255]; e.extend(&bytes); h.call(&e).unwrap(); h };
+ let mut authority = open(11);
+ let mut peer = open(12);
+ let opened = authority.memory_bytes();
+ for i in 0..n {
+ let update = peer.call(&serde_json::to_vec(&json!({"op":"display_edit","at":5 + (i % 50),"length":0,"text":"remote typing "})).unwrap()).unwrap().to_vec();
+ let mut e = vec![255]; e.extend(update); authority.call(&e).unwrap();
+ }
+ println!("opened {:.1} MiB, after {n} peer updates {:.1} MiB (doc {} KB)", opened as f64 / 1048576.0, authority.memory_bytes() as f64 / 1048576.0, bytes.len() / 1024);
+}
diff --git a/native/host/src/lib.rs b/native/host/src/lib.rs
index faf41f1..262fc3c 100644
--- a/native/host/src/lib.rs
+++ b/native/host/src/lib.rs
@@ -69,6 +69,9 @@ impl Host {
let memory = instance.get_memory(&store, "memory").ok_or("invalid_module")?;
Ok(Self {store, instance, memory, output: Vec::new(), failed: false, ceiling: MAX_FUEL})
}
+ /// The instance's linear memory, in bytes (it never shrinks).
+ #[doc(hidden)]
+ pub fn memory_bytes(&self) -> usize { self.memory.data(&self.store).len() }
/// Tests only: a lower ceiling, to show that running out of fuel is a
/// clean failure that discards the instance.
#[doc(hidden)]