Docs native: the host's fuel budget grows with the document
One fixed budget of 40M fuel per call refused real documents: a projection costs about 1M fuel per page, so typing failed from about 20 edited pages and opening from about 40 (audit finding 1). The budget is now a 40M floor plus 128 fuel per byte of the instance's linear memory and 1,024 per request byte, measured on documents of 1-400 pages with 2-3x headroom. Memory (64 MiB) and requests (8 MiB) are capped, so it is still bounded: at most ~17G fuel (~20 s on an M1 Max), and about 200M for a one-page document. Running out stays a trap that discards the instance. The native gate now generates a 200-page document with 10,000 edits and opens and types in it through the host (it failed at open on the old budget), and a mutation shows the fuel ceiling is enforced.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+229
−6
fixtures/generate-large-doc.mjs+108 −0native/BUILDING.md+3 −1native/host/src/lib.rs+46 −5native/host/tests/sandbox.rs+65 −0native/scripts/check-mutations.py+1 −0native/scripts/check-native.sh+6 −0
diff --git a/fixtures/generate-large-doc.mjs b/fixtures/generate-large-doc.mjs| new file mode 100644 |
| index 0000000..559e2fa |
| --- /dev/null |
| +++ b/fixtures/generate-large-doc.mjs |
| @@ -0,0 +1,108 @@ |
| +// fixtures/generate-large-doc.mjs <pages> <out.bin> [edits] — a long, |
| +// realistic document for the native realtime audit and for the native |
| +// gate's long-document check (native/scripts/check-native.sh, which opens |
| +// and types in a 200-page edited one through the bounded host). A "page" is about 3,000 characters |
| +// (~500 words): five paragraphs, a heading every second page, a bold and |
| +// an italic run in most paragraphs, and a five-item bullet list every |
| +// fifth page. Seeded, so every run produces the same bytes. |
| +// |
| +// [edits] (default 0) then applies that many small edits from twenty |
| +// other clients (insert 1-8 characters, or delete 1-4, at random places), |
| +// so the update carries the fragmentation and tombstones a document that |
| +// has been typed into for a while has. A document built in one |
| +// transaction is the best case for every encoder; this is closer to the |
| +// one people actually open. |
| +import * as Y from 'yjs' |
| +import { prosemirrorToYXmlFragment } from 'y-prosemirror' |
| +import { writeFileSync } from 'node:fs' |
| +import { schema } from './schema.mjs' |
| + |
| +const [pagesArg = '50', out = '/tmp/docs-large.bin', editsArg = '0'] = process.argv.slice(2) |
| +const pages = Number(pagesArg) |
| +const edits = Number(editsArg) |
| + |
| +let state = 12345 |
| +const rand = () => { |
| + state = (state + 0x6d2b79f5) >>> 0 |
| + let t = state |
| + t = Math.imul(t ^ (t >>> 15), t | 1) |
| + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) |
| + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 |
| +} |
| +const WORDS = 'the of and to in is that for it as was with be by on not he this are or his from at which but have an they you were her she there would their we him been has when who will no more if out so up said what its about than into them can only other time new some could these two may first then do any like my now over such our man me even most made after also did many off 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 see own men work long here get both between life being under never day same another know while last us might great old year come since against go came right used take three'.split(' ') |
| +const sentence = () => { |
| + const n = 8 + Math.floor(rand() * 14) |
| + const words = Array.from({ length: n }, () => WORDS[Math.floor(rand() * WORDS.length)]) |
| + words[0] = words[0][0].toUpperCase() + words[0].slice(1) |
| + return words.join(' ') + '.' |
| +} |
| +const paragraphText = () => { |
| + let text = '' |
| + while (text.length < 560) text += (text ? ' ' : '') + sentence() |
| + return text |
| +} |
| +const { paragraph, heading, bullet_list, list_item, doc: docType } = schema.nodes |
| +const strong = schema.marks.strong, em = schema.marks.em |
| +function richParagraph() { |
| + const text = paragraphText() |
| + if (rand() < 0.3) return paragraph.create(null, schema.text(text)) |
| + const a = Math.floor(rand() * (text.length - 80)), b = a + 10 + Math.floor(rand() * 30) |
| + const c = Math.min(text.length - 1, b + 20 + Math.floor(rand() * 40)), d = Math.min(text.length, c + 5 + Math.floor(rand() * 20)) |
| + const spans = [[0, a], [a, b, strong], [b, c], [c, d, em], [d, text.length]] |
| + const parts = spans.filter(([from, to]) => to > from).map(([from, to, mark]) => schema.text(text.slice(from, to), mark ? [mark.create()] : undefined)) |
| + return paragraph.create(null, parts) |
| +} |
| +const blocks = [] |
| +for (let page = 0; page < pages; page++) { |
| + if (page % 2 === 0) blocks.push(heading.create({ level: 2 }, schema.text(`Section ${page / 2 + 1}: ${sentence().slice(0, 40)}`))) |
| + for (let i = 0; i < 5; i++) blocks.push(richParagraph()) |
| + if (page % 5 === 4) { |
| + blocks.push(bullet_list.create(null, Array.from({ length: 5 }, () => list_item.create(null, paragraph.create(null, schema.text(sentence())))))) |
| + } |
| +} |
| +const pm = docType.create(null, blocks) |
| +pm.check() |
| +const ydoc = new Y.Doc() |
| +ydoc.clientID = 1 |
| +prosemirrorToYXmlFragment(pm, ydoc.getXmlFragment('prosemirror')) |
| + |
| +if (edits > 0) { |
| + // Collect every XmlText once; edits land inside existing text, as typing does. |
| + const texts = [] |
| + const walk = (node) => { |
| + for (const child of node.toArray()) { |
| + if (child instanceof Y.XmlText) texts.push(child) |
| + else if (child instanceof Y.XmlElement) walk(child) |
| + } |
| + } |
| + walk(ydoc.getXmlFragment('prosemirror')) |
| + const peers = Array.from({ length: 20 }, (_, i) => { const d = new Y.Doc(); d.clientID = 100 + i; return d }) |
| + // Each peer edits its own replica and the change is merged back, so the |
| + // structs carry twenty client IDs, as a shared document's would. |
| + for (let i = 0; i < edits; i++) { |
| + const text = texts[Math.floor(rand() * texts.length)] |
| + const len = text.length |
| + const peer = peers[i % peers.length] |
| + const before = Y.encodeStateVector(ydoc) |
| + Y.applyUpdate(peer, Y.encodeStateAsUpdate(ydoc, Y.encodeStateVector(peer))) |
| + // Find the same XmlText in the peer by path. |
| + const path = [] |
| + let node = text |
| + while (node.parent && node.parent !== ydoc.getXmlFragment('prosemirror')) { path.unshift(node.parent.toArray().indexOf(node)); node = node.parent } |
| + path.unshift(ydoc.getXmlFragment('prosemirror').toArray().indexOf(node)) |
| + let target = peer.getXmlFragment('prosemirror') |
| + for (const index of path) target = target.toArray()[index] |
| + if (rand() < 0.7 || len < 8) { |
| + const at = Math.floor(rand() * (len + 1)) |
| + target.insert(at, WORDS[Math.floor(rand() * WORDS.length)].slice(0, 1 + Math.floor(rand() * 8))) |
| + } else { |
| + const at = Math.floor(rand() * (len - 4)) |
| + target.delete(at, 1 + Math.floor(rand() * 4)) |
| + } |
| + Y.applyUpdate(ydoc, Y.encodeStateAsUpdate(peer, before)) |
| + } |
| +} |
| +const update = Y.encodeStateAsUpdate(ydoc) |
| +writeFileSync(out, update) |
| +const chars = ydoc.getXmlFragment('prosemirror').toArray().reduce((n, b) => n + b.toString().replace(/<[^>]*>/g, '').length, 0) |
| +console.log(JSON.stringify({ pages, edits, blocks: blocks.length, chars, bytes: update.length })) |
diff --git a/native/BUILDING.md b/native/BUILDING.md| index b7faf88..de5bd2e 100644 |
| --- a/native/BUILDING.md |
| +++ b/native/BUILDING.md |
| @@ -14,7 +14,9 @@ Run the native gate from the repository root: |
| native/scripts/check-native.sh |
| ``` |
| -It builds the CRDT WASM, runs Rust editor and bounded-host tests, checks native |
| +It builds the CRDT WASM, runs Rust editor and bounded-host tests (including |
| +opening and typing in a generated 200-page edited document on the host's |
| +production fuel budget; see `fuel_budget` in `host/src/lib.rs`), checks native |
| and browser updates in both directions (including every list-rule reversal delta |
| and its authoritative snapshot), prepares the Apple XCFramework, and |
| runs Swift adapter/actor tests. `--core-only` runs the Rust and wire checks on |
diff --git a/native/host/src/lib.rs b/native/host/src/lib.rs| index 00cea6c..5d1ae4a 100644 |
| --- a/native/host/src/lib.rs |
| +++ b/native/host/src/lib.rs |
| @@ -2,7 +2,37 @@ |
| use std::panic::{catch_unwind, AssertUnwindSafe}; |
| use wasmi::{Config, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder}; |
| const MAX_BYTES: usize = 8 * 1024 * 1024 + 1; |
| -const FUEL: u64 = 40_000_000; |
| +const MAX_MEMORY: usize = 64 * 1024 * 1024; |
| +/// Fuel bounds every call, so no input (a crafted update, an engine bug) can |
| +/// keep the interpreter running for ever: a call that runs out traps, and the |
| +/// instance is discarded like any other failure. One fixed budget of 40M |
| +/// refused real documents, though. A call's honest work grows with the |
| +/// document (a projection costs about 1M fuel per page), so 40M stopped |
| +/// typing at about 20 edited pages and opening at about 40. |
| +/// |
| +/// So the budget grows with what the call can legitimately touch: a floor, |
| +/// plus an allowance per byte of the instance's linear memory (which holds |
| +/// the document, its history and the undo stack; it never shrinks) and per |
| +/// byte of the request (an import is decoded byte by byte). Measured on |
| +/// edited documents of 1-400 pages, the costliest calls needed at most |
| +/// 38 fuel per memory byte (`display_edit`) and 491 per request byte |
| +/// (importing a heavily fragmented snapshot), so both allowances carry 2-3x |
| +/// headroom on top of the other term. Memory is capped at `MAX_MEMORY` and |
| +/// requests at `MAX_BYTES`, so the budget is still bounded: at most |
| +/// `MAX_FUEL`, about 17G, or some 20 s of interpretation on an M1 Max, and |
| +/// only for an instance already holding 64 MiB. A one-page document's calls |
| +/// get about 200M (a quarter of a second). |
| +const BASE_FUEL: u64 = 40_000_000; |
| +const FUEL_PER_MEMORY_BYTE: u64 = 128; |
| +const FUEL_PER_REQUEST_BYTE: u64 = 1_024; |
| +pub const MAX_FUEL: u64 = BASE_FUEL + FUEL_PER_MEMORY_BYTE * MAX_MEMORY as u64 + FUEL_PER_REQUEST_BYTE * MAX_BYTES as u64; |
| +/// The fuel one call may spend, given the instance's memory once the request |
| +/// is written into it and the request's length. |
| +pub fn fuel_budget(memory: usize, request: usize) -> u64 { |
| + let memory = memory.min(MAX_MEMORY) as u64; |
| + let request = request.min(MAX_BYTES) as u64; |
| + BASE_FUEL + FUEL_PER_MEMORY_BYTE * memory + FUEL_PER_REQUEST_BYTE * request |
| +} |
| const WASM: &[u8] = include_bytes!("../../crdt/target/wasm32-unknown-unknown/release/docs_native_crdt.wasm"); |
| pub struct Host { |
| store: Store<StoreLimits>, |
| @@ -10,6 +40,7 @@ pub struct Host { |
| memory: Memory, |
| output: Vec<u8>, |
| failed: bool, |
| + ceiling: u64, |
| } |
| impl Host { |
| pub fn new() -> Result<Self, &'static str> { |
| @@ -20,26 +51,36 @@ impl Host { |
| // No imports are supplied: CRDT must remain independent of host JS, |
| // filesystem, entropy and clock functions. Identity is an input. |
| let linker = Linker::new(&engine); |
| - let limits = StoreLimitsBuilder::new().memory_size(64 * 1024 * 1024).instances(1).memories(1).tables(1).build(); |
| + let limits = StoreLimitsBuilder::new().memory_size(MAX_MEMORY).instances(1).memories(1).tables(1).build(); |
| let mut store = Store::new(&engine, limits); |
| store.limiter(|limits| limits); |
| - store.set_fuel(FUEL).map_err(|_| "fuel")?; |
| + store.set_fuel(BASE_FUEL).map_err(|_| "fuel")?; |
| let instance = linker.instantiate(&mut store, &module).map_err(|_| "invalid_module")?.start(&mut store).map_err(|_| "module_trap")?; |
| let memory = instance.get_memory(&store, "memory").ok_or("invalid_module")?; |
| - Ok(Self {store, instance, memory, output: Vec::new(), failed: false}) |
| + Ok(Self {store, instance, memory, output: Vec::new(), failed: false, ceiling: MAX_FUEL}) |
| } |
| + /// Tests only: a lower ceiling, to show that running out of fuel is a |
| + /// clean failure that discards the instance. |
| + #[doc(hidden)] |
| + pub fn limit_fuel_for_tests(&mut self, ceiling: u64) { self.ceiling = ceiling; } |
| pub fn call(&mut self, request: &[u8]) -> Result<&[u8], &'static str> { |
| if self.failed || request.len() > MAX_BYTES { return Err("replica_unavailable"); } |
| // Any failed mutation can have partially modified the WASM state. Once |
| // failed, discard the replica; never let callers continue using it. |
| self.failed = true; |
| - self.store.set_fuel(FUEL).map_err(|_| "fuel")?; |
| + self.store.set_fuel(BASE_FUEL).map_err(|_| "fuel")?; |
| let alloc = self.instance.get_typed_func::<u32, u32>(&self.store, "docs_editor_alloc").map_err(|_| "invalid_abi")?; |
| let ptr = alloc.call(&mut self.store, request.len() as u32).map_err(|_| "module_trap")?; |
| if ptr == 0 { return Err("allocation"); } |
| self.memory.write(&mut self.store, ptr as usize, request).map_err(|_| "invalid_memory")?; |
| + // Measured after the write, so an import's own bytes count as memory too. |
| + let budget = fuel_budget(self.memory.data(&self.store).len(), request.len()).min(self.ceiling); |
| + self.store.set_fuel(budget).map_err(|_| "fuel")?; |
| let call = self.instance.get_typed_func::<(u32,u32), i32>(&self.store, "docs_editor_call").map_err(|_| "invalid_abi")?; |
| let status = call.call(&mut self.store, (ptr, request.len() as u32)).map_err(|_| "module_trap")?; |
| + // Freeing and reading the output get their own small budget, so a |
| + // call that finished just inside its budget is not failed by them. |
| + self.store.set_fuel(BASE_FUEL).map_err(|_| "fuel")?; |
| let free = self.instance.get_typed_func::<(u32,u32), ()>(&self.store, "docs_editor_free").map_err(|_| "invalid_abi")?; |
| free.call(&mut self.store, (ptr, request.len() as u32)).map_err(|_| "module_trap")?; |
| if status != 0 { |
diff --git a/native/host/tests/sandbox.rs b/native/host/tests/sandbox.rs| index 4cb7706..1103337 100644 |
| --- a/native/host/tests/sandbox.rs |
| +++ b/native/host/tests/sandbox.rs |
| @@ -60,3 +60,68 @@ fn native_boundary_rejects_client_ids_that_v1_decoder_would_truncate() { |
| let mut host = Host::new().unwrap(); |
| assert!(host.call(br#"{"op":"open","guid":"generation","client":6088656600138213}"#).is_err()); |
| } |
| + |
| +#[test] |
| +fn fuel_budget_grows_with_the_instance_but_stays_bounded() { |
| + use docs_native_host::{fuel_budget, MAX_FUEL}; |
| + // A small call keeps the old floor; a bigger instance or request earns more. |
| + assert_eq!(fuel_budget(0, 0), 40_000_000); |
| + assert!(fuel_budget(16 << 20, 0) > fuel_budget(1 << 20, 0)); |
| + assert!(fuel_budget(1 << 20, 1 << 20) > fuel_budget(1 << 20, 0)); |
| + // Memory and requests are capped, so the budget is too, whatever is asked. |
| + assert_eq!(fuel_budget(usize::MAX, usize::MAX), MAX_FUEL); |
| + assert!(MAX_FUEL < 20_000_000_000, "the ceiling is what bounds a runaway call: {MAX_FUEL}"); |
| +} |
| + |
| +#[test] |
| +fn running_out_of_fuel_is_a_clean_failure_that_discards_the_instance() { |
| + let mut host = Host::new().unwrap(); |
| + host.call(br#"{"op":"open","guid":"fuel","client":321}"#).unwrap(); |
| + for at in 0..40 { host.call(format!(r#"{{"op":"insert_element","at":{at},"type":"paragraph"}}"#).as_bytes()).unwrap(); } |
| + let text = "fuel ".repeat(600); |
| + host.call(&serde_json::to_vec(&json!({"op":"display_edit","at":0,"length":0,"text":text})).unwrap()).unwrap(); |
| + // The same call succeeds with its budget, so only fuel can fail it below. |
| + assert!(host.call(br#"{"op":"project"}"#).is_ok()); |
| + host.limit_fuel_for_tests(100_000); |
| + assert_eq!(host.call(br#"{"op":"project"}"#).err(), Some("module_trap")); |
| + assert!(host.call(br#"{"op":"snapshot"}"#).is_err(), "an instance that ran out must not be reused"); |
| +} |
| + |
| +/// The native gate's long-document check: a 200-page document with 10,000 |
| +/// edits from twenty clients (fixtures/generate-large-doc.mjs) opens and takes |
| +/// typing through the calls CRDTReplica makes, on the production budget. The |
| +/// old fixed 40M budget failed this at the first keystroke and could not open |
| +/// it at all. check-native.sh generates the document and runs this. |
| +#[test] |
| +#[ignore = "needs DOCS_LARGE_DOCUMENT; native/scripts/check-native.sh runs it"] |
| +fn long_edited_document_opens_and_types() { |
| + let path = std::env::var("DOCS_LARGE_DOCUMENT").expect("DOCS_LARGE_DOCUMENT names the generated document"); |
| + let document = std::fs::read(path).unwrap(); |
| + assert!(document.len() > 800_000, "expected the 200-page edited document"); |
| + // Open (CRDTReplica.open): the authority imports the state, then snapshots and projects. |
| + let mut authority = Host::new().unwrap(); |
| + authority.call(br#"{"op":"open","guid":"long","client":3088656600}"#).unwrap(); |
| + let mut imported = vec![255]; imported.extend(&document); authority.call(&imported).unwrap(); |
| + authority.call(br#"{"op":"clients"}"#).unwrap(); |
| + let snapshot = authority.call(br#"{"op":"snapshot"}"#).unwrap().to_vec(); |
| + let projection: serde_json::Value = serde_json::from_slice(authority.call(br#"{"op":"project"}"#).unwrap()).unwrap(); |
| + assert!(projection["children"].as_array().unwrap().len() > 1000); |
| + // Presentation: a fresh source sandbox from the snapshot. |
| + let mut source = Host::new().unwrap(); |
| + source.call(br#"{"op":"open","guid":"long","client":4088656600}"#).unwrap(); |
| + let mut imported = vec![255]; imported.extend(&snapshot); source.call(&imported).unwrap(); |
| + source.call(br#"{"op":"clients"}"#).unwrap(); |
| + // Typing (CRDTReplica.command, then presentation) deep in the document. |
| + let at = 300_000u32; |
| + for (i, ch) in "Typed".chars().enumerate() { |
| + let at = at + i as u32; |
| + let update = source.call(&serde_json::to_vec(&json!({"op":"display_edit","at":at,"length":0,"text":ch.to_string()})).unwrap()).unwrap().to_vec(); |
| + source.call(br#"{"op":"snapshot"}"#).unwrap(); |
| + let mut applied = vec![254]; applied.extend(update); authority.call(&applied).unwrap(); |
| + authority.call(br#"{"op":"project"}"#).unwrap(); |
| + authority.call(br#"{"op":"snapshot"}"#).unwrap(); |
| + let anchor: serde_json::Value = serde_json::from_slice(source.call(&serde_json::to_vec(&json!({"op":"anchor","at":at + 1})).unwrap()).unwrap()).unwrap(); |
| + let resolved = authority.call(&serde_json::to_vec(&json!({"op":"resolve","anchor":anchor})).unwrap()).unwrap(); |
| + assert_eq!(resolved, (at + 1).to_string().as_bytes()); |
| + } |
| +} |
diff --git a/native/scripts/check-mutations.py b/native/scripts/check-mutations.py| index 10fc46e..97bddb5 100644 |
| --- a/native/scripts/check-mutations.py |
| +++ b/native/scripts/check-mutations.py |
| @@ -21,6 +21,7 @@ cases = [ |
| ('crdt/src/structure.rs', 'Any::from(suffix)), diff.attributes', 'Any::from(suffix)), None', 'paragraph_split_keeps_prefix_identity_and_suffix_marks'), |
| ('crdt/src/structure.rs', 'copy.attributes.insert("level".into(), number(&request["level"])?.clamp(1,6).to_string());', 'copy.attributes.insert("level".into(), "1".into());', 'changing_block_preserves_existing_inline_formatting'), |
| ('host/src/lib.rs', 'if self.failed || request.len() > MAX_BYTES', 'if request.len() > MAX_BYTES', 'failed_replica_cannot_be_reused'), |
| + ('host/src/lib.rs', 'request.len()).min(self.ceiling)', 'request.len())', 'running_out_of_fuel_is_a_clean_failure_that_discards_the_instance'), |
| ] |
| for relative, old, new, test in cases: |
| path = root / relative |
diff --git a/native/scripts/check-native.sh b/native/scripts/check-native.sh| index 699b191..3518ba3 100755 |
| --- a/native/scripts/check-native.sh |
| +++ b/native/scripts/check-native.sh |
| @@ -33,6 +33,12 @@ fi |
| npm ci --prefix fixtures --ignore-scripts --no-audit --no-fund |
| native_check_dir=$(mktemp -d "${TMPDIR:-/tmp}/docs-native-check.XXXXXX") |
| trap 'rm -rf "$native_check_dir"' EXIT HUP INT TERM |
| +# Long documents: a 200-page document with 10,000 edits from twenty clients |
| +# opens and takes typing through the bounded host on its production fuel |
| +# budget (the old fixed budget refused it). Release: the interpreter is slow |
| +# in a debug build. |
| +node fixtures/generate-large-doc.mjs 200 "$native_check_dir/long.bin" 10000 |
| +DOCS_LARGE_DOCUMENT="$native_check_dir/long.bin" "$CARGO" test --locked --release --manifest-path native/host/Cargo.toml --test sandbox -- --ignored |
| "$CARGO" run --locked --quiet --manifest-path native/crdt/Cargo.toml --bin wire_fixture -- "$native_check_dir/native.bin" |
| node fixtures/native-wire.mjs "$native_check_dir/native.bin" "$native_check_dir/browser.bin" |
| "$CARGO" run --locked --quiet --manifest-path native/crdt/Cargo.toml --bin wire_fixture -- "$native_check_dir/native.bin" "$native_check_dir/browser.bin" |