oficina / docs Public

Docs native engine: compile the CRDT module once per process

Every new sandbox (a fresh source after a peer change, each send merger,
each replica commit, each recovery) recompiled the wasm module: 6.6-7.3 ms
per docs_host_new whatever the document size (audit finding 9). The
Engine and Module are now built once in a OnceLock and each host only
instantiates them. Each host keeps its own store, linear memory, limits
and fuel, so the instance is still the isolation unit; the module is
immutable. New test: hosts on several threads share the module but no
state.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 8bb6258bcde9c1603637ce1caaa75069e62c6c5d parent 8e54d3a
2 files changed, +41 −6
  • native/host/src/lib.rs +16 −6
  • native/host/tests/sandbox.rs +25 −0
diff --git a/native/host/src/lib.rs b/native/host/src/lib.rs
index 00cea6c..0a425bf 100644
--- a/native/host/src/lib.rs
+++ b/native/host/src/lib.rs
@@ -1,5 +1,6 @@
//! Apple process boundary: only the safe WASM interpreter sees remote updates.
use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::sync::OnceLock;
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;
@@ -11,20 +12,29 @@ pub struct Host {
output: Vec<u8>,
failed: bool,
}
-impl Host {
- pub fn new() -> Result<Self, &'static str> {
+/// The module is immutable, so it is validated and compiled once per process
+/// (about 7 ms) and every host only instantiates it. Each host still has its
+/// own store, linear memory and fuel: the instance remains the isolation unit.
+static COMPILED: OnceLock<Option<(Engine, Module)>> = OnceLock::new();
+fn compiled() -> Result<&'static (Engine, Module), &'static str> {
+ COMPILED.get_or_init(|| {
let mut config = Config::default();
config.consume_fuel(true);
let engine = Engine::new(&config);
- let module = Module::new(&engine, WASM).map_err(|_| "invalid_module")?;
+ Module::new(&engine, WASM).ok().map(|module| (engine, module))
+ }).as_ref().ok_or("invalid_module")
+}
+impl Host {
+ pub fn new() -> Result<Self, &'static str> {
+ let (engine, module) = compiled()?;
// 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 linker = Linker::new(engine);
let limits = StoreLimitsBuilder::new().memory_size(64 * 1024 * 1024).instances(1).memories(1).tables(1).build();
- let mut store = Store::new(&engine, limits);
+ let mut store = Store::new(engine, limits);
store.limiter(|limits| limits);
store.set_fuel(FUEL).map_err(|_| "fuel")?;
- let instance = linker.instantiate(&mut store, &module).map_err(|_| "invalid_module")?.start(&mut store).map_err(|_| "module_trap")?;
+ 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})
}
diff --git a/native/host/tests/sandbox.rs b/native/host/tests/sandbox.rs
index 4cb7706..f7079fd 100644
--- a/native/host/tests/sandbox.rs
+++ b/native/host/tests/sandbox.rs
@@ -60,3 +60,28 @@ 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 hosts_share_the_compiled_module_but_never_state() {
+ // The module is compiled once per process; every host is still its own
+ // instance, memory and fuel budget, on any thread.
+ let mut first = Host::new().unwrap();
+ first.call(br#"{"op":"open","guid":"shared","client":11}"#).unwrap();
+ first.call(br#"{"op":"insert_element","at":0,"type":"paragraph"}"#).unwrap();
+ let mut second = Host::new().unwrap();
+ assert!(second.call(br#"{"op":"project"}"#).is_err(), "a new host starts with no editor");
+ let threads: Vec<_> = (0..4u32).map(|n| std::thread::spawn(move || {
+ for round in 0..3u32 {
+ let mut host = Host::new().unwrap();
+ host.call(format!(r#"{{"op":"open","guid":"thread","client":{}}}"#, 100 + n * 10 + round).as_bytes()).unwrap();
+ host.call(br#"{"op":"insert_element","at":0,"type":"paragraph"}"#).unwrap();
+ host.call(format!(r#"{{"op":"display_edit","at":0,"length":0,"text":"t{n}"}}"#).as_bytes()).unwrap();
+ let p: serde_json::Value = serde_json::from_slice(host.call(br#"{"op":"project"}"#).unwrap()).unwrap();
+ assert_eq!(p["children"].as_array().unwrap().len(), 1);
+ assert_eq!(p["children"][0]["children"][0]["runs"][0]["insert"], format!("t{n}"));
+ }
+ })).collect();
+ for thread in threads { thread.join().unwrap(); }
+ let p: serde_json::Value = serde_json::from_slice(first.call(br#"{"op":"project"}"#).unwrap()).unwrap();
+ assert_eq!(p["children"].as_array().unwrap().len(), 1);
+}