From cf1d29b111f461ed99c972b44e8ca336d0fbdc30 Mon Sep 17 00:00:00 2001 From: Sebastian Herrlinger Date: Thu, 19 Nov 2026 03:20:02 +0100 Subject: [PATCH 1/8] test(codemode): measure the native stack compiling and re-entrant calls need --- .../bench/examples/stack_probe.rs | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 packages/codemode-rust/bench/examples/stack_probe.rs diff --git a/packages/codemode-rust/bench/examples/stack_probe.rs b/packages/codemode-rust/bench/examples/stack_probe.rs new file mode 100644 index 0000000000000..9ab5aad20eb11 --- /dev/null +++ b/packages/codemode-rust/bench/examples/stack_probe.rs @@ -0,0 +1,155 @@ +//! Measures the native stack a program needs, by running it on threads of different stack sizes in child processes +//! and bisecting for the smallest size that does not overflow. +//! +//! `stack_probe` prints, for each construct, the stack bytes per nesting level of compiling it. +//! `stack_probe [run]` compiles (and with `run`, runs) one program and exits 0. + +use psychoscript::{ProgramOptions, Runtime}; + +const CONSTRUCTS: &[&str] = &[ + "parens", + "arrays", + "objects", + "blocks", + "calls", + "arrows", + "functions", + "if-else", + "if", + "unary", + "ternary", + "assign", + "binary", + "members", + "template", + "typeof", + "void", + "await", + "new", + "negate", + "spread", + "destructure", + "pattern", + "optional", + "labels", + "while", +]; + +fn source(construct: &str, n: usize) -> String { + let rep = |s: &str| s.repeat(n); + match construct { + "parens" => format!("return {}1{}", rep("("), rep(")")), + "arrays" => format!("return {}1{}", rep("["), rep("]")), + "objects" => format!("return {}1{}", rep("{a:"), rep("}")), + "blocks" => format!("{}{}return 1", rep("{"), rep("}")), + "calls" => format!("const f = (x) => x; return {}1{}", rep("f("), rep(")")), + "arrows" => format!("return {}1", rep("() => ")), + "functions" => format!("return {}1{}", rep("function () { return "), rep(" }")), + "if-else" => format!("let a = 1; {}{{}} return 1", rep("if (a) {} else ")), + "if" => format!("let a = 1; {}a = 2; return a", rep("if (a) ")), + "unary" => format!("return {}1", rep("!")), + "ternary" => format!("let a = 1; return {}0", rep("a ? 1 : ")), + "assign" => format!("let a; return {}1", rep("a = ")), + "binary" => format!("return 1{}", rep(" + 1")), + "members" => format!( + "const o = {{ a() {{ return o }} }}; return o{}", + rep(".a()") + ), + "template" => format!("return {}1{}", rep("`${"), rep("}`")), + "typeof" => format!("return {}1", rep("typeof ")), + "void" => format!("return {}1", rep("void ")), + "await" => format!("return {}1", rep("await ")), + "new" => format!("function F() {{}} return {}F{}", rep("new "), rep("()")), + "negate" => format!("return {}1", rep("- ")), + "spread" => format!("return {}1{}", rep("[..."), rep("]")), + "destructure" => format!("const {}a{} = 1; return 1", rep("["), rep("]")), + "pattern" => format!("let a; ({}a{} = {{}}); return 1", rep("{a:"), rep("}")), + "optional" => format!("const o = {{}}; return o{}", rep("?.a")), + "labels" => format!( + "{}break a0; return 1", + (0..n).map(|i| format!("a{i}: ")).collect::() + ), + "while" => format!("let a = 0; {}a = 1; return a", rep("while (a) ")), + // Native re-entrancy at run time: each level calls back into the VM through a built-in. + "map" => { + format!("function f(n) {{ return n ? [n].map((x) => f(x - 1))[0] : 0 }} return f({n})") + } + "sort" => format!( + "function f(n) {{ if (n) [2, 1].sort((a, b) => (f(n - 1), a - b)); return 0 }} return f({n})" + ), + "tostring" => format!( + "function f(n) {{ return n ? String({{ toString() {{ return f(n - 1) }} }}) : '0' }} return f({n})" + ), + "replace" => format!( + "function f(n) {{ return n ? 'a'.replace('a', () => f(n - 1)) : '0' }} return f({n})" + ), + other => panic!("unknown construct {other}"), + } +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.len() >= 3 { + let (construct, depth, stack) = + (&args[0], args[1].parse().unwrap(), args[2].parse().unwrap()); + let run = args.get(3).is_some_and(|a| a == "run"); + let code = source(construct, depth); + let ok = std::thread::Builder::new() + .stack_size(stack) + .spawn(move || { + let rt = Runtime::make(); + let program = rt.program(&code, &ProgramOptions::new()); + if run { + let outcome = program.run().expect("not interrupted"); + if let Err(d) = outcome.result { + eprintln!("{:?}", d.message); + return false; + } + } + true + }) + .unwrap() + .join() + .unwrap(); + std::process::exit(if ok { 0 } else { 2 }); + } + let run = args.first().is_some_and(|a| a == "run"); + let constructs: Vec<&str> = if run { + vec!["map", "sort", "tostring", "replace"] + } else { + CONSTRUCTS.to_vec() + }; + let (lo, hi) = match (run, cfg!(debug_assertions)) { + (true, true) => (500, 4500), + (true, false) => (500, 4500), + _ => (200, 600), + }; + for construct in constructs { + let a = smallest(construct, lo, run); + let b = smallest(construct, hi, run); + let per = (b as f64 - a as f64) / (hi - lo) as f64; + println!("{construct:10} {lo}: {a:>9} B {hi}: {b:>9} B per level: {per:>7.0} B"); + } +} + +/// The smallest thread stack, to 1 KiB, that runs the construct at that depth. +fn smallest(construct: &str, depth: usize, run: bool) -> usize { + let exe = std::env::current_exe().unwrap(); + let ok = |stack: usize| { + let mut cmd = std::process::Command::new(&exe); + cmd.args([construct, &depth.to_string(), &stack.to_string()]); + if run { + cmd.arg("run"); + } + cmd.stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + }; + let (mut lo, mut hi) = (16 << 10, 512 << 20); + assert!(ok(hi), "{construct} at {depth} fails even with {hi} bytes"); + while hi - lo > 1024 { + let mid = (lo + hi) / 2; + if ok(mid) { hi = mid } else { lo = mid } + } + hi +} From 3b682d0d9308e6b57f8d6f7bb724178c543479ec Mon Sep 17 00:00:00 2001 From: Sebastian Herrlinger Date: Thu, 19 Nov 2026 03:20:54 +0100 Subject: [PATCH 2/8] refactor(codemode): make a run's state Send --- .../crates/psychoscript/src/builtins/bytes.rs | 18 ++++++++----- .../crates/psychoscript/src/bytecode.rs | 4 +-- .../crates/psychoscript/src/compiler.rs | 4 +-- .../crates/psychoscript/src/convert.rs | 4 +-- .../crates/psychoscript/src/host.rs | 5 ++-- .../crates/psychoscript/src/object.rs | 8 +++--- .../crates/psychoscript/src/ops.rs | 2 +- .../crates/psychoscript/src/program.rs | 6 +++++ .../crates/psychoscript/src/run.rs | 4 +-- .../crates/psychoscript/src/runtime.rs | 2 +- .../crates/psychoscript/src/snapshot.rs | 26 +++++++++++-------- .../crates/psychoscript/src/streaming.rs | 9 +++---- .../crates/psychoscript/src/test262.rs | 4 +-- .../crates/psychoscript/src/vm.rs | 20 +++++++------- 14 files changed, 64 insertions(+), 52 deletions(-) diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/bytes.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/bytes.rs index fa356b61dc653..4e08962a98840 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/bytes.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/bytes.rs @@ -1,7 +1,6 @@ //! Uint8Array, TextEncoder, TextDecoder, atob and btoa. -use std::cell::RefCell; -use std::rc::Rc; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use super::{arg, describe_value, fuel, incompatible}; use crate::native::{FOR_OF_SLOTS, Flow, ForOf, Frame, Input, Step}; @@ -12,7 +11,7 @@ use crate::vm::{Res, Vm}; /// A Uint8Array: a view of `len` bytes at `start` in a buffer that subarrays share. pub struct Bytes { - pub buf: Rc>>, + pub buf: Arc>>, pub start: usize, pub len: usize, /// A Node Buffer: text conversions default to UTF-8. @@ -23,21 +22,26 @@ impl Bytes { pub fn new(data: Vec, buffer: bool) -> Bytes { let len = data.len(); Bytes { - buf: Rc::new(RefCell::new(data)), + buf: Arc::new(Mutex::new(data)), start: 0, len, buffer, } } + /// The shared buffer. Only the run that owns it touches it, so the lock is never contended. + pub fn bytes(&self) -> MutexGuard<'_, Vec> { + self.buf.lock().unwrap_or_else(PoisonError::into_inner) + } + pub fn to_vec(&self) -> Vec { - let b = self.buf.borrow(); + let b = self.bytes(); b[self.start..self.start + self.len].to_vec() } pub fn get(&self, i: usize) -> Option { if i < self.len { - self.buf.borrow().get(self.start + i).copied() + self.bytes().get(self.start + i).copied() } else { None } @@ -45,7 +49,7 @@ impl Bytes { pub fn put(&self, i: usize, v: u8) { if i < self.len - && let Some(slot) = self.buf.borrow_mut().get_mut(self.start + i) + && let Some(slot) = self.bytes().get_mut(self.start + i) { *slot = v; } diff --git a/packages/codemode-rust/crates/psychoscript/src/bytecode.rs b/packages/codemode-rust/crates/psychoscript/src/bytecode.rs index e30709f55cf7f..5de5f01d7e916 100644 --- a/packages/codemode-rust/crates/psychoscript/src/bytecode.rs +++ b/packages/codemode-rust/crates/psychoscript/src/bytecode.rs @@ -1,6 +1,6 @@ //! Bytecode: a compact stack-machine instruction set and compiled function prototypes. -use std::rc::Rc; +use std::sync::Arc; use crate::object::Atom; @@ -305,7 +305,7 @@ pub enum Site { } pub struct Program { - pub protos: Vec>, + pub protos: Vec>, pub consts: Vec, /// Global names referenced by `GetGlobal`, by slot. pub globals: Vec, diff --git a/packages/codemode-rust/crates/psychoscript/src/compiler.rs b/packages/codemode-rust/crates/psychoscript/src/compiler.rs index 1910fc9142d18..cc16c1dc7d5c7 100644 --- a/packages/codemode-rust/crates/psychoscript/src/compiler.rs +++ b/packages/codemode-rust/crates/psychoscript/src/compiler.rs @@ -1,6 +1,6 @@ //! Parses with oxc, resolves bindings with oxc_semantic, rejects syntax outside the subset, and emits bytecode. -use std::rc::Rc; +use std::sync::Arc; use oxc_allocator::Allocator; use oxc_ast::ast::*; @@ -133,7 +133,7 @@ pub fn compile(source: &str, atoms: &mut Strings) -> R { c.compute_captured(); c.compile_program(program)?; Ok(Program { - protos: c.protos.into_iter().map(Rc::new).collect(), + protos: c.protos.into_iter().map(Arc::new).collect(), consts: c.consts, globals: c.globals, templates: c.templates, diff --git a/packages/codemode-rust/crates/psychoscript/src/convert.rs b/packages/codemode-rust/crates/psychoscript/src/convert.rs index 2ee1567189885..43147a1efed8f 100644 --- a/packages/codemode-rust/crates/psychoscript/src/convert.rs +++ b/packages/codemode-rust/crates/psychoscript/src/convert.rs @@ -784,7 +784,7 @@ fn stringify_walk( let buf = fr.get(vm, J_OUT).as_obj(); let text = match buf.map(|b| &mut vm.heap[b as usize].kind) { Some(Kind::Bytes(b)) => { - let mut bytes = std::mem::take(&mut *b.buf.borrow_mut()); + let mut bytes = std::mem::take(&mut *b.bytes()); b.len = 0; bytes.extend_from_slice(out.as_bytes()); // Only whole strings were written to it. @@ -884,7 +884,7 @@ fn flush(vm: &mut Vm, fr: crate::native::Frame, out: &mut String) { } }; if let Kind::Bytes(b) = &mut vm.heap[buf as usize].kind { - b.buf.borrow_mut().extend_from_slice(out.as_bytes()); + b.bytes().extend_from_slice(out.as_bytes()); b.len += out.len(); } out.clear(); diff --git a/packages/codemode-rust/crates/psychoscript/src/host.rs b/packages/codemode-rust/crates/psychoscript/src/host.rs index f5c6ae23f1902..90e5a56bc65b4 100644 --- a/packages/codemode-rust/crates/psychoscript/src/host.rs +++ b/packages/codemode-rust/crates/psychoscript/src/host.rs @@ -1,7 +1,6 @@ //! The VM's side of host work: the run's host globals (see [`crate::host_function`]) and modules, the host calls a run //! has in flight and how they settle. Arguments cross out and results cross in as copies. -use std::rc::Rc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::task::Poll; @@ -274,7 +273,7 @@ impl SuspendWatch for Unwatched { } /// The host globals a run gets, made by the runtime's `globals(run)` when it starts or resumes. -pub type Globals = Rc<[(String, HostValue)]>; +pub type Globals = Arc<[(String, HostValue)]>; /// The host state of one run. pub struct RunHost<'rt> { @@ -411,7 +410,7 @@ impl<'rt> RunHost<'rt> { /// A run with no host globals, for what the snapshot's tables need. pub(crate) fn bare() -> Self { Self::new( - Rc::from([]), + Arc::from([]), &[], Translate::default(), Run::new(None, Data::Null), diff --git a/packages/codemode-rust/crates/psychoscript/src/object.rs b/packages/codemode-rust/crates/psychoscript/src/object.rs index 00aa2cc540dc3..9ade77fa85059 100644 --- a/packages/codemode-rust/crates/psychoscript/src/object.rs +++ b/packages/codemode-rust/crates/psychoscript/src/object.rs @@ -1,6 +1,6 @@ //! Heap objects, property storage and the atom interner. -use std::rc::Rc; +use std::sync::Arc; use rustc_hash::FxHashMap; @@ -162,8 +162,8 @@ pub struct Failure { } pub struct Closure { - pub proto: Rc, - pub upvals: Rc<[u32]>, + pub proto: Arc, + pub upvals: Arc<[u32]>, pub this: Value, } @@ -356,7 +356,7 @@ pub enum Kind { pos: u32, }, ListIter { - items: Rc<[Value]>, + items: Arc<[Value]>, pos: u32, }, /// A path into a host namespace among the globals, the reference's `HostNamespace`. diff --git a/packages/codemode-rust/crates/psychoscript/src/ops.rs b/packages/codemode-rust/crates/psychoscript/src/ops.rs index 49ebf9d7352f4..fd0533e806a0f 100644 --- a/packages/codemode-rust/crates/psychoscript/src/ops.rs +++ b/packages/codemode-rust/crates/psychoscript/src/ops.rs @@ -1687,7 +1687,7 @@ impl<'rt> Vm<'rt> { Value::Obj(id) => { if let Kind::Arguments(_) = self.heap[*id as usize].kind { // Like the reference: the values of its enumerable own keys when iteration starts. - let items: std::rc::Rc<[Value]> = + let items: std::sync::Arc<[Value]> = self.own_entries(*id).into_iter().map(|(_, v)| v).collect(); let it = Kind::ListIter { items, pos: 0 }; return Ok(Value::Obj(self.alloc(Obj::new(Some(proto), it)))); diff --git a/packages/codemode-rust/crates/psychoscript/src/program.rs b/packages/codemode-rust/crates/psychoscript/src/program.rs index 4c375d2d4e234..db01d3db6c6e5 100644 --- a/packages/codemode-rust/crates/psychoscript/src/program.rs +++ b/packages/codemode-rust/crates/psychoscript/src/program.rs @@ -593,3 +593,9 @@ fn roundtrip() -> bool { const ROUNDTRIP_TICKS: u32 = 64; const ROUNDTRIP_MAX: u32 = 1 << 16; + +// A run's state may move to another thread between steps. +const _: () = { + const fn send() {} + send::>() +}; diff --git a/packages/codemode-rust/crates/psychoscript/src/run.rs b/packages/codemode-rust/crates/psychoscript/src/run.rs index 7fa93edc50c44..12a464b5ef612 100644 --- a/packages/codemode-rust/crates/psychoscript/src/run.rs +++ b/packages/codemode-rust/crates/psychoscript/src/run.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use std::panic::AssertUnwindSafe; -use std::rc::Rc; +use std::sync::Arc; use crate::compiler; use crate::convert; @@ -190,7 +190,7 @@ pub fn call_main(vm: &mut Vm) { Some(fp), Kind::Closure(Box::new(Closure { proto, - upvals: Rc::from(Vec::new()), + upvals: Arc::from(Vec::new()), this: Value::Undef, })), ))); diff --git a/packages/codemode-rust/crates/psychoscript/src/runtime.rs b/packages/codemode-rust/crates/psychoscript/src/runtime.rs index 862cee3d0ef46..6ea14614c09e9 100644 --- a/packages/codemode-rust/crates/psychoscript/src/runtime.rs +++ b/packages/codemode-rust/crates/psychoscript/src/runtime.rs @@ -171,7 +171,7 @@ impl Setup { pub(crate) fn globals_for(&self, run: &Run) -> crate::host::Globals { match &self.globals { Some(globals) => globals(run).into(), - None => std::rc::Rc::from([]), + None => std::sync::Arc::from([]), } } } diff --git a/packages/codemode-rust/crates/psychoscript/src/snapshot.rs b/packages/codemode-rust/crates/psychoscript/src/snapshot.rs index 406bb2bc7d9c4..6ec8ba7f61ab7 100644 --- a/packages/codemode-rust/crates/psychoscript/src/snapshot.rs +++ b/packages/codemode-rust/crates/psychoscript/src/snapshot.rs @@ -10,10 +10,9 @@ //! - **Host calls in flight** are saved by kind: an idempotent call as queued, to run again with the same key; a //! started durable call with its data, to wait on again. Any other one in flight refuses the suspend. -use std::cell::RefCell; use std::collections::VecDeque; use std::fmt; -use std::rc::Rc; +use std::sync::Arc; use std::sync::OnceLock; use rustc_hash::FxHashMap; @@ -322,7 +321,7 @@ struct Enc<'v, 'rt> { vm: &'v Vm<'rt>, natives: &'static Natives, protos: FxHashMap, - buffers: Vec>>>, + buffers: Vec>>>, } /// Why a suspend was refused: the calls that block it, or a state that can't be saved. @@ -359,7 +358,7 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { .protos .iter() .enumerate() - .map(|(i, p)| (Rc::as_ptr(p) as usize, i)) + .map(|(i, p)| (Arc::as_ptr(p) as usize, i)) .collect(), buffers: Vec::new(), }; @@ -433,7 +432,7 @@ impl Enc<'_, '_> { "cells": vm.cells[base.cells.min(vm.cells.len())..].iter().map(slot).collect::>(), "changed": changed, "heap": rest, - "buffers": self.buffers.iter().map(|b| J::from(bytes_hex(&b.borrow()))).collect::>(), + "buffers": self.buffers.iter().map(|b| J::from(bytes_hex(&b.lock().unwrap_or_else(std::sync::PoisonError::into_inner)))).collect::>(), "stack": vm.stack.iter().map(slot).collect::>(), "frames": vm.frames.iter().map(|f| self.frame(f)).collect::>>()?, "handlers": vm.handlers_ref().iter().map(handler).collect::>(), @@ -614,7 +613,7 @@ impl Enc<'_, '_> { Kind::RegExp(r) => json!(["re", r.source, r.flags, num(r.last_index)]), Kind::Date(t) => json!(["d", num(*t)]), Kind::Bytes(b) => { - let i = match self.buffers.iter().position(|x| Rc::ptr_eq(x, &b.buf)) { + let i = match self.buffers.iter().position(|x| Arc::ptr_eq(x, &b.buf)) { Some(i) => i, None => { self.buffers.push(b.buf.clone()); @@ -679,9 +678,9 @@ impl Enc<'_, '_> { }) } - fn proto(&self, p: &Rc) -> R { + fn proto(&self, p: &Arc) -> R { self.protos - .get(&(Rc::as_ptr(p) as usize)) + .get(&(Arc::as_ptr(p) as usize)) .copied() .ok_or_else(|| { SnapshotError::new("The run can't be suspended: a function is not this run's code.") @@ -1248,7 +1247,7 @@ struct Dec<'p> { heap_len: usize, bufs_len: usize, protos: usize, - buffers: Vec>>>, + buffers: Vec>>>, _p: std::marker::PhantomData<&'p ()>, } @@ -1741,7 +1740,12 @@ impl Dec<'_> { return Err(invalid("a byte array's buffer is missing.")); }; let (start, len) = (usize_(f(2)?)?, usize_(f(3)?)?); - if start + len > buf.borrow().len() { + if start + len + > buf + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .len() + { return Err(invalid("a byte array's view is out of range.")); } Kind::Bytes(Box::new(crate::builtins::bytes::Bytes { @@ -1956,7 +1960,7 @@ pub fn restore(vm: &mut Vm, snapshot: &Snapshot, program_hash: &str) -> R<()> { let changed = field_list(st, "changed")?; let mut buffers = Vec::new(); for b in field_list(st, "buffers")? { - buffers.push(Rc::new(RefCell::new(hex_bytes(&string(b)?)?))); + buffers.push(Arc::new(std::sync::Mutex::new(hex_bytes(&string(b)?)?))); } let dec = Dec { natives: natives(), diff --git a/packages/codemode-rust/crates/psychoscript/src/streaming.rs b/packages/codemode-rust/crates/psychoscript/src/streaming.rs index 71bbbb7e58826..fb331fd7e1de5 100644 --- a/packages/codemode-rust/crates/psychoscript/src/streaming.rs +++ b/packages/codemode-rust/crates/psychoscript/src/streaming.rs @@ -13,7 +13,6 @@ use std::collections::VecDeque; use std::fmt; use std::future::Future; use std::pin::Pin; -use std::rc::Rc; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::task::{Context, Poll, Waker}; @@ -97,7 +96,7 @@ impl fmt::Debug for StreamingResponse { } /// The getter of a host accessor: an own, read-only, non-enumerable property whose value the host answers live. -pub type Getter = Rc Value>; +pub type Getter = Arc Value + Send + Sync>; /// An object with host accessors, such as a streaming response and its body. Deleting an accessor leaves an /// ordinary object behind. @@ -547,17 +546,17 @@ pub(crate) fn surface(response: &StreamingResponse, epoch: &Epoch) -> Surface { let Some(stream) = response.body.clone() else { return Surface { methods, - body_used: Rc::new(|| Value::Bool(false)), + body_used: Arc::new(|| Value::Bool(false)), body: None, }; }; let body_used = { let (stream, epoch) = (stream.clone(), epoch.clone()); - Rc::new(move || Value::Bool(observed(&stream, &epoch).disturbed)) as Getter + Arc::new(move || Value::Bool(observed(&stream, &epoch).disturbed)) as Getter }; let is_locked = { let (stream, epoch) = (stream.clone(), epoch.clone()); - Rc::new(move || Value::Bool(observed(&stream, &epoch).reader.is_some())) as Getter + Arc::new(move || Value::Bool(observed(&stream, &epoch).reader.is_some())) as Getter }; let cancel = { let (stream, epoch) = (stream.clone(), epoch.clone()); diff --git a/packages/codemode-rust/crates/psychoscript/src/test262.rs b/packages/codemode-rust/crates/psychoscript/src/test262.rs index 5ea8709efb34d..0f79a36a9f877 100644 --- a/packages/codemode-rust/crates/psychoscript/src/test262.rs +++ b/packages/codemode-rust/crates/psychoscript/src/test262.rs @@ -3,7 +3,7 @@ //! `$DONOTEVALUATE` are host functions; `assert` itself is program code the runner prepends. use std::cell::RefCell; -use std::rc::Rc; +use std::sync::Arc; use crate::builtins::arg; use crate::object::{Closure, Kind, Obj}; @@ -84,7 +84,7 @@ fn run_here(code: &str, timeout_ms: u64) -> Run { Some(fp), Kind::Closure(Box::new(Closure { proto, - upvals: Rc::from(Vec::new()), + upvals: Arc::from(Vec::new()), this: Value::Undef, })), ))); diff --git a/packages/codemode-rust/crates/psychoscript/src/vm.rs b/packages/codemode-rust/crates/psychoscript/src/vm.rs index 132bcc0b5ee5d..b916701dac686 100644 --- a/packages/codemode-rust/crates/psychoscript/src/vm.rs +++ b/packages/codemode-rust/crates/psychoscript/src/vm.rs @@ -1,7 +1,7 @@ //! The stack machine: frames, calls, exceptions, suspension and the run loop. use std::collections::VecDeque; -use std::rc::Rc; +use std::sync::Arc; use std::time::Instant; use rustc_hash::FxHashMap; @@ -62,10 +62,10 @@ pub enum Resume { } pub struct Frame { - pub func: Rc, + pub func: Arc, pub pc: usize, pub base: usize, - pub upvals: Rc<[u32]>, + pub upvals: Arc<[u32]>, /// Where this frame's exception handlers start in `Vm::handlers`. pub hbase: u32, /// Arguments beyond the declared parameters, kept for rest parameters and `arguments`. @@ -243,7 +243,7 @@ pub struct Vm<'rt> { templates: Vec, /// Each tagged template site's strings array, once made. template_objs: Vec>, - pub protos: Vec>, + pub protos: Vec>, pub jobs: VecDeque, pub inbox: VecDeque<(Id, crate::host::Settlement)>, pub coroutines: Vec, @@ -289,8 +289,8 @@ pub struct Vm<'rt> { pub(crate) json_walk: u32, json_walks: u32, /// The code of every native frame (see `native.rs`). - pub(crate) native_proto: Rc, - no_upvals: Rc<[u32]>, + pub(crate) native_proto: Arc, + no_upvals: Arc<[u32]>, /// Set by a built-in that pushed a native frame instead of returning its result (`enter_native`). pub(crate) entered: bool, /// Set while a built-in called from bytecode or a convert frame's rerun runs: a conversion that calls the @@ -379,8 +379,8 @@ impl<'rt> Vm<'rt> { resumable_run: false, snapshot_base: crate::snapshot::Base::default(), resumed: false, - native_proto: Rc::new(crate::native::proto()), - no_upvals: Rc::from([]), + native_proto: Arc::new(crate::native::proto()), + no_upvals: Arc::from([]), entered: false, convert_ok: false, convert_req: None, @@ -1140,7 +1140,7 @@ impl<'rt> Vm<'rt> { match self.spare_frames.pop() { // Reuse a retired frame in place; one that ran a native frame keeps the shared code and no upvalues. Some(mut f) => { - if !Rc::ptr_eq(&f.func, &self.native_proto) { + if !Arc::ptr_eq(&f.func, &self.native_proto) { f.func = self.native_proto.clone(); } if !f.upvals.is_empty() { @@ -2499,7 +2499,7 @@ impl<'rt> Vm<'rt> { fn make_closure(&mut self, idx: u32) -> Value { let proto = self.protos[idx as usize].clone(); let f = self.frames.last().expect("frame"); - let upvals: Rc<[u32]> = proto + let upvals: Arc<[u32]> = proto .captures .iter() .map(|c| match c { From 0e3de440073925bd930d32c67d52c607ad3303cb Mon Sep 17 00:00:00 2001 From: Sebastian Herrlinger Date: Thu, 19 Nov 2026 03:22:37 +0100 Subject: [PATCH 3/8] refactor(codemode): size compile threads by a conservative nesting scan, not source size --- .../crates/psychoscript/src/lib.rs | 1 + .../crates/psychoscript/src/nesting.rs | 664 ++++++++++++++++++ .../crates/psychoscript/src/program.rs | 11 +- .../crates/psychoscript/src/run.rs | 82 +-- .../crates/psychoscript/src/snapshot.rs | 4 +- .../crates/psychoscript/tests/api.rs | 72 ++ 6 files changed, 782 insertions(+), 52 deletions(-) create mode 100644 packages/codemode-rust/crates/psychoscript/src/nesting.rs diff --git a/packages/codemode-rust/crates/psychoscript/src/lib.rs b/packages/codemode-rust/crates/psychoscript/src/lib.rs index 992f29b03d211..08dfb66bcd737 100644 --- a/packages/codemode-rust/crates/psychoscript/src/lib.rs +++ b/packages/codemode-rust/crates/psychoscript/src/lib.rs @@ -21,6 +21,7 @@ mod host; mod host_function; mod iteration; mod native; +mod nesting; mod object; mod ops; mod program; diff --git a/packages/codemode-rust/crates/psychoscript/src/nesting.rs b/packages/codemode-rust/crates/psychoscript/src/nesting.rs new file mode 100644 index 0000000000000..a6bf669ef5897 --- /dev/null +++ b/packages/codemode-rust/crates/psychoscript/src/nesting.rs @@ -0,0 +1,664 @@ +//! A cheap upper bound on how deeply a program's syntax nests, read from its bytes without parsing. Parsing and +//! compiling recurse once per level of syntax, and the parser has no guard of its own: a bound that came out too low +//! could overflow the native stack, which aborts the process. So the bound is conservative by construction: wherever +//! the scan cannot tell how the parser reads the source, it takes a reading that can only count more. +//! +//! Within one bracket group, a path through the syntax tree passes at most one node per token of the statement or +//! list item it is in, so the bound adds the tokens of the longest item in each group along the deepest chain of +//! groups. `;`, `,` and line breaks where a statement cannot continue end an item. `else` and `do` chain statements +//! across semicolons, so they count for the whole group. +//! +//! The only doubt in reading JavaScript without parsing it is whether a `/` starts a regular expression or divides. +//! Each `/` is a regex, a division, or either, by the token before it. From a `/` that may be either, the rest of the +//! line is counted raw: every non-blank byte is a token, every opening bracket opens a group, and closing brackets +//! close nothing. No reading of that line can nest deeper than that, and the readings agree again at the line's end, +//! unless the line can start something that spans lines (a template, a block comment, a string continued with a +//! backslash); then, as after source the parser cannot tokenize, everything to the end counts raw. + +/// The bound for `code`: never less than its deepest syntax nesting, close to it for ordinary programs. +pub fn bound(code: &str) -> usize { + let mut scan = Scan { + src: code.as_bytes(), + at: 0, + frames: vec![Frame::new(b'\0', false)], + prev: START, + newline: false, + control: false, + dot: false, + }; + scan.run(); + let mut child = 0; + while let Some(mut frame) = scan.frames.pop() { + frame.child = frame.child.max(child); + child = frame.close(); + } + child +} + +struct Frame { + /// The bracket that opened the group, `$` for a template substitution. + open: u8, + /// Tokens of the current item, and the deepest group nested in it. + tokens: usize, + child: usize, + /// The deepest item closed so far. + best: usize, + /// `else` and `do` seen anywhere in the group. + chained: usize, + /// Parentheses holding an `if`, `for`, `while` or `with` head: a statement follows. + control: bool, +} + +impl Frame { + fn new(open: u8, control: bool) -> Self { + Self { + open, + tokens: 0, + child: 0, + best: 0, + chained: 0, + control, + } + } + + fn end_item(&mut self) { + self.best = self.best.max(self.tokens + self.child); + self.tokens = 0; + self.child = 0; + } + + fn close(&mut self) -> usize { + self.end_item(); + 1 + self.best + self.chained + } +} + +/// How a `/` after a token reads. +#[derive(Clone, Copy, PartialEq)] +enum Slash { + Regex, + Division, + Either, +} + +/// What the previous token tells the scan: how a `/` after it reads, and whether a line break after it may end a +/// statement before a token that starts one. +#[derive(Clone, Copy, PartialEq)] +struct Prev { + slash: Slash, + ends: bool, +} + +/// The start, an operator, an opening bracket, a separator, or a keyword an expression follows. +const START: Prev = Prev { + slash: Slash::Regex, + ends: false, +}; +const OPERATOR: Prev = START; +/// The closing parenthesis of a control head: a statement follows. +const CONTROL_HEAD: Prev = START; +/// A name, literal, `)` or `]`. +const VALUE: Prev = Prev { + slash: Slash::Division, + ends: true, +}; +/// A name a line break may not end, such as `get` before a method name. +const PREFIX: Prev = Prev { + slash: Slash::Division, + ends: false, +}; +/// A `}`, which ends a block (a regex may follow) or an object (a division may). +const BRACE: Prev = Prev { + slash: Slash::Either, + ends: true, +}; +/// A token the scan cannot place: `++`, `--`, a name that may be a keyword, a byte outside ASCII, or the end of a +/// line counted raw. +const EITHER: Prev = Prev { + slash: Slash::Either, + ends: false, +}; + +struct Scan<'a> { + src: &'a [u8], + at: usize, + frames: Vec, + prev: Prev, + /// A line break since the previous token. + newline: bool, + /// The previous token was `if`, `for`, `while` or `with`. + control: bool, + /// The previous token was a `.` of member access: a keyword after it is a property name. + dot: bool, +} + +impl Scan<'_> { + fn run(&mut self) { + if self.src.starts_with(b"#!") { + self.raw(false); + } + while let Some(&b) = self.src.get(self.at) { + match b { + b'\n' | b'\r' => { + self.newline = true; + self.at += 1; + } + 0xe2 if line_separator(self.src, self.at) => { + self.newline = true; + self.at += 3; + } + b' ' | b'\t' | 0x0b | 0x0c => self.at += 1, + b'/' if self.peek(1) == Some(b'/') => self.at = line_end(self.src, self.at), + b'/' if self.peek(1) == Some(b'*') => { + let rest = &self.src[self.at + 2..]; + let len = rest.windows(2).position(|w| w == b"*/"); + let body = &rest[..len.unwrap_or(rest.len())]; + self.newline |= line_end(body, 0) < body.len(); + self.at += 2 + len.map_or(rest.len(), |n| n + 2); + } + // An HTML-like comment in a script, an operator in a module: counted raw, either way. + b'<' if self.src[self.at..].starts_with(b"") + && (self.newline || self.prev == START) => + { + self.raw(false) + } + b'(' | b'[' | b'{' => { + self.token(false); + let control = b == b'(' && self.control; + self.frames.push(Frame::new(b, control)); + self.after(OPERATOR); + self.at += 1; + } + b')' | b']' | b'}' => { + self.at += 1; + self.close(b); + } + b';' | b',' => { + self.top().end_item(); + self.after(OPERATOR); + self.at += 1; + } + b'\'' | b'"' => { + let start = self.at; + self.token(true); + if !self.string(b) { + self.at = start; + return self.raw(true); + } + self.after(VALUE); + } + b'`' => { + self.token(false); + self.at += 1; + self.template(); + } + b'/' => match self.prev.slash { + Slash::Regex => { + let start = self.at; + self.token(false); + if !self.regex() { + self.at = start; + return self.raw(true); + } + self.after(VALUE); + } + Slash::Division => { + self.token(false); + self.after(OPERATOR); + self.at += 1; + } + Slash::Either => self.raw(false), + }, + b'0'..=b'9' => { + self.token(true); + self.number(); + self.after(VALUE); + } + b'.' if self.peek(1).is_some_and(|c| c.is_ascii_digit()) => { + self.token(true); + self.number(); + self.after(VALUE); + } + _ if is_name(b) => self.word(), + b'.' => { + self.token(false); + let spread = self.peek(1) == Some(b'.') + || (self.at > 0 && self.src[self.at - 1] == b'.'); + self.after(OPERATOR); + self.dot = !spread; + self.at += 1; + } + // `++` and `--` may be postfix, after which a `/` divides, or prefix, after which it may not. + b'+' | b'-' => { + self.token(false); + let doubled = self.at > 0 && self.src[self.at - 1] == b; + self.after(if doubled { EITHER } else { OPERATOR }); + self.at += 1; + } + // Outside ASCII a byte may be part of a name or a space; a backslash starts an escaped name. + _ if b >= 0x80 || b == b'\\' => { + self.token(false); + self.after(EITHER); + self.at += 1; + } + // Every other character is an operator or part of one; counting each keeps `!!x` and `~~x` deep. + _ => { + self.token(false); + self.after(OPERATOR); + self.at += 1; + } + } + } + } + + fn peek(&self, n: usize) -> Option { + self.src.get(self.at + n).copied() + } + + fn top(&mut self) -> &mut Frame { + self.frames + .last_mut() + .expect("the program's own frame stays") + } + + /// Counts a token in the current item, first ending the item when a line break before it ends a statement. + fn token(&mut self, starts_statement: bool) { + if self.newline && starts_statement && self.prev.ends { + self.top().end_item(); + } + self.newline = false; + self.top().tokens += 1; + } + + fn after(&mut self, prev: Prev) { + self.prev = prev; + self.control = false; + self.dot = false; + } + + /// Counts from here to the end of the line, or of the source, without telling code from text: every non-blank + /// byte is a token and every opening bracket opens a group that only a later closer outside the raw span closes. + fn raw(&mut self, to_end: bool) { + let line = line_end(self.src, self.at); + let spans_lines = { + let rest = &self.src[self.at..line]; + rest.contains(&b'`') + || rest.windows(2).any(|w| w == b"/*") + || rest.last() == Some(&b'\\') + }; + let end = if to_end || spans_lines { + self.src.len() + } else { + line + }; + self.newline = false; + for i in self.at..end { + let b = self.src[i]; + if b.is_ascii_whitespace() { + continue; + } + self.top().tokens += 1; + if matches!(b, b'(' | b'[' | b'{') { + self.frames.push(Frame::new(b, false)); + } + } + self.at = end; + self.after(EITHER); + } + + fn close(&mut self, b: u8) { + let open = match b { + b')' => b'(', + b']' => b'[', + _ => b'{', + }; + // A closer that does not match is counted, not obeyed: popping on it could only lower the bound. + let top = self.top().open; + if self.frames.len() == 1 || (top != open && !(top == b'$' && b == b'}')) { + self.token(false); + self.after(EITHER); + return; + } + let mut frame = self.frames.pop().expect("checked above"); + let depth = frame.close(); + let parent = self.top(); + parent.child = parent.child.max(depth); + match frame.open { + b'$' => self.template(), + b'{' => self.after(BRACE), + _ if frame.control => self.after(CONTROL_HEAD), + _ => self.after(VALUE), + } + } + + fn word(&mut self) { + let start = self.at; + while self + .src + .get(self.at) + .is_some_and(|&c| is_name(c) || c.is_ascii_digit()) + { + self.at += 1; + } + let word = &self.src[start..self.at]; + let member = self.dot; + // Words that continue the statement before a line break. + let continues = !member + && matches!( + word, + b"in" | b"instanceof" | b"of" | b"else" | b"catch" | b"finally" | b"while" + ); + self.token(!continues); + if matches!(word, b"else" | b"do") { + self.top().chained += 1; + } + let prev = match word { + _ if member => VALUE, + b"this" | b"null" | b"true" | b"false" | b"super" => VALUE, + // Keywords in some places and names in others. + b"await" | b"yield" | b"of" | b"let" => EITHER, + b"get" | b"set" | b"static" | b"async" | b"accessor" => PREFIX, + _ if is_keyword(word) => OPERATOR, + _ => VALUE, + }; + let control = !member + && (matches!(word, b"if" | b"for" | b"while" | b"with") + || (self.control && word == b"await")); + self.after(prev); + self.control = control; + } + + /// Scans a string; false when it does not end on its line. + fn string(&mut self, quote: u8) -> bool { + self.at += 1; + while let Some(&c) = self.src.get(self.at) { + self.at += 1; + match c { + b'\\' if self.src[self.at..].starts_with(b"\r\n") => self.at += 2, + b'\\' => self.at += 1, + b'\n' | b'\r' => return false, + _ if c == quote => return true, + _ => {} + } + } + false + } + + /// Scans template text up to its end or its next substitution, which opens a group. + fn template(&mut self) { + while let Some(&c) = self.src.get(self.at) { + self.at += 1; + match c { + b'\\' => self.at += 1, + b'`' => { + self.after(VALUE); + return; + } + b'$' if self.src.get(self.at) == Some(&b'{') => { + self.at += 1; + self.frames.push(Frame::new(b'$', false)); + self.after(OPERATOR); + return; + } + _ => {} + } + } + } + + /// Scans a regex; false when it does not end on its line. + fn regex(&mut self) -> bool { + self.at += 1; + let mut class = false; + loop { + if self.at >= self.src.len() || matches!(self.src[self.at], b'\n' | b'\r') { + return false; + } + if line_separator(self.src, self.at) { + return false; + } + let c = self.src[self.at]; + self.at += 1; + match c { + b'\\' => { + let next = self.src.get(self.at); + if next.is_none_or(|&n| matches!(n, b'\n' | b'\r')) + || line_separator(self.src, self.at) + { + return false; + } + self.at += 1; + } + b'[' => class = true, + b']' => class = false, + b'/' if !class => break, + _ => {} + } + } + while self.src.get(self.at).is_some_and(|&c| is_name(c)) { + self.at += 1; + } + true + } + + fn number(&mut self) { + let hex = matches!(self.src.get(self.at + 1), Some(b'x' | b'X')); + while let Some(&c) = self.src.get(self.at) { + let exponent_sign = + !hex && matches!(c, b'+' | b'-') && matches!(self.src[self.at - 1], b'e' | b'E'); + if !(c.is_ascii_alphanumeric() || c == b'.' || c == b'_' || exponent_sign) { + return; + } + self.at += 1; + } + } +} + +fn is_name(b: u8) -> bool { + b.is_ascii_alphabetic() || b == b'_' || b == b'$' +} + +/// U+2028 or U+2029, which end a line as `\n` does. +fn line_separator(src: &[u8], at: usize) -> bool { + src[at..].starts_with(&[0xe2, 0x80, 0xa8]) || src[at..].starts_with(&[0xe2, 0x80, 0xa9]) +} + +/// Where the line holding `at` ends. +fn line_end(src: &[u8], at: usize) -> usize { + (at..src.len()) + .find(|&i| matches!(src[i], b'\n' | b'\r') || line_separator(src, i)) + .unwrap_or(src.len()) +} + +/// Words after which an expression, not an operator, comes next. +fn is_keyword(word: &[u8]) -> bool { + matches!( + word, + b"break" + | b"case" + | b"catch" + | b"class" + | b"const" + | b"continue" + | b"debugger" + | b"default" + | b"delete" + | b"do" + | b"else" + | b"export" + | b"extends" + | b"finally" + | b"for" + | b"function" + | b"if" + | b"import" + | b"in" + | b"instanceof" + | b"new" + | b"return" + | b"switch" + | b"throw" + | b"try" + | b"typeof" + | b"var" + | b"void" + | b"while" + | b"with" + ) +} + +#[cfg(test)] +mod tests { + use super::bound; + + #[test] + fn brackets_in_strings_comments_templates_and_regexes_do_not_count() { + assert_eq!(bound("return 1"), bound(r#"return ")))(((" // ((((("#)); + assert_eq!(bound("return 1"), bound("/* ((( */ return 1")); + assert_eq!(bound("return `${1}`"), bound("return `((( ${1} )))`")); + assert_eq!(bound("return 1"), bound(r"return /[)\]]((/g")); + } + + #[test] + fn grows_with_every_nesting_form() { + let forms: &[(&str, &str, &str)] = &[ + ("return ", "(", ")"), + ("return ", "[", "]"), + ("", "{", "}"), + ("return ", "!", ""), + ("return ", "- ", ""), + ("return ", "a ? 1 : ", "0"), + ("let a; return ", "a = ", "1"), + ("return ", "() => ", "1"), + ("return 1", " + 1", ""), + ("return o", ".a()", ""), + ("return ", "`${", "}`"), + ("let a = 1; ", "if (a) ", "a = 2"), + ("let a = 1; ", "if (a)\n", "a = 2"), + ("let a = 1; ", "if (a) a = 1; else ", "a = 2"), + ("let a = 1;\n", "if (a) a = 1\nelse ", "a = 2"), + ("", "do ", "x; while (a)"), + ("", "a: ", "x"), + ("return ", "function () { return ", " }"), + ]; + for (head, open, close) in forms { + let at = |n: usize| bound(&format!("{head}{}1{}", open.repeat(n), close.repeat(n))); + assert!( + at(200) - at(100) >= 100, + "{open:?} grows by {}", + at(200) - at(100) + ); + } + } + + #[test] + fn statements_on_their_own_lines_do_not_add_up() { + let line = + "if (event.type === \"x\") { const s = await tools.git.status(); return { s } }\n"; + let calls = "f(x)\nlet y = 1\nconsole.log(y)\n"; + assert!( + bound(&line.repeat(200)) < 30, + "{}", + bound(&line.repeat(200)) + ); + assert!( + bound(&calls.repeat(200)) < 30, + "{}", + bound(&calls.repeat(200)) + ); + assert!(bound(&"x = 1;".repeat(1000)) < 10); + } + + /// Stack bytes per repetition of each form, measured with `bench/examples/stack_probe.rs` (release, debug). + #[test] + fn covers_the_measured_stack_use() { + let measured: &[(&str, &str, &str, usize, usize)] = &[ + ("return ", "(", ")", 778, 3481), + ("return ", "[", "]", 819, 12574), + ("return ", "{a:", "}", 942, 13189), + ("", "{", "}", 942, 3031), + ("return ", "f(", ")", 1147, 14540), + ("return ", "() => ", "", 1475, 16261), + ("return ", "function () { return ", " }", 2171, 18472), + ("", "if (a) {} else ", "{}", 655, 2212), + ("", "if (a) ", "", 655, 2212), + ("return ", "!", "", 819, 12902), + ("return ", "a ? 1 : ", "0", 860, 11509), + ("return ", "a = ", "", 983, 17858), + ("return 1", " + 1", "", 819, 11509), + ("return o", ".a()", "", 983, 13475), + ("return ", "`${", "}`", 1761, 12247), + ("return ", "typeof ", "", 819, 12902), + ("return ", "void ", "", 819, 12902), + ("return ", "await ", "", 819, 11509), + ("return ", "new ", "()", 819, 11509), + ("return ", "- ", "", 819, 12861), + ("return ", "[...", "]", 860, 12574), + ("const ", "[", "]", 1270, 2294), + ("(", "{a:", "}", 1270, 4915), + ("return o", "?.a", "", 819, 11509), + ("", "while (a) ", "", 655, 3113), + ]; + for (head, open, close, release, debug) in measured { + let at = |n: usize| bound(&format!("{head}{}1{}", open.repeat(n), close.repeat(n))); + let per = (at(600) - at(200)) / 400; + let need = if cfg!(debug_assertions) { + debug + } else { + release + }; + assert!( + per * crate::run::COMPILE_STACK_PER_LEVEL >= *need, + "{open:?}: {per} per level" + ); + } + } + + /// Each source hides a group nested 400 deep from a scan that guessed wrong about a `/`, a line end, or a byte. + #[test] + fn no_reading_of_an_unclear_token_hides_nesting() { + let n = 400; + let d = format!("{}1{}", "(".repeat(n), ")".repeat(n)); + let typeofs = "typeof\u{a0}".repeat(n); + let cases = [ + format!("let a = 1, g = 1; a++ / {d} / g"), + format!("let a = 1, g = 1; a-- /{d}/ g"), + format!("function f(s) {{ if (s) {{}} /}}/.test(s); return {d} }}"), + format!("function f(s) {{ if (s) {{}} /))))/.test(s); return [{d}] }}"), + format!("const o = {{}} / {d} / 2"), + format!("let await = 1, g = 1; await / {d} / g"), + format!("let of = 1, g = 1; of / {d} / g"), + format!("const x = {{}}; x.return / {d} / 2"), + format!("let a = 1; a\u{a0}/ {d} /\u{a0}1"), + format!("return {typeofs}1"), + format!("x = 1 {d}"), + format!("// note\u{2028}{d}"), + format!("/* note */ {d}"), + format!("const s = 'unterminated\n{d}"), + format!("const r = /unterminated\n{d}"), + format!("let a = 1; a++ / `${{1}}\n${{{d}}}` / 1"), + format!("let a = 1; a++ / 1 /* ((( \n */ {d}"), + format!("let a = 1; x = a++ / 'x\\\n{d}'"), + ]; + for case in cases { + let b = bound(&case); + assert!(b >= n, "{} is bounded by {b}", &case[..case.len().min(70)]); + } + } + + #[test] + fn regexes_and_divisions_the_scan_is_sure_of_stay_cheap() { + let plain = bound("const r = /[(]+/g; const q = a / b / c; return r.test(q)"); + assert!(plain < 20, "{plain}"); + let after_block = bound("if (a) { b() }\nconst c = d / e"); + assert!(after_block < 20, "{after_block}"); + } + + #[test] + fn unmatched_closers_do_not_lower_the_bound() { + let deep = format!("return {}1{}", "(".repeat(300), ")".repeat(300)); + assert!(bound(&format!("{deep} ]]]}}}}")) >= bound(&deep)); + assert!(bound(&format!("]]]}}}} {deep}")) >= bound(&deep)); + } +} diff --git a/packages/codemode-rust/crates/psychoscript/src/program.rs b/packages/codemode-rust/crates/psychoscript/src/program.rs index db01d3db6c6e5..d0796de58a15b 100644 --- a/packages/codemode-rust/crates/psychoscript/src/program.rs +++ b/packages/codemode-rust/crates/psychoscript/src/program.rs @@ -226,8 +226,6 @@ pub struct Program<'a> { rt: &'a Runtime, state: State<'a>, shared: Arc, - /// How much of the native stack below the point it is driven from the run may use. - pub(crate) stack_budget: usize, } impl<'a> Program<'a> { @@ -246,12 +244,7 @@ impl<'a> Program<'a> { if let State::Running(r) = &mut state { r.vm.host.shared = shared.clone(); } - Self { - rt, - state, - shared, - stack_budget: run::INLINE_STACK_BUDGET, - } + Self { rt, state, shared } } /// A program continuing a suspended run's state, checked against this runtime. @@ -308,7 +301,7 @@ impl<'a> Program<'a> { }; // Between jobs no native frame of the run is on the stack, so it may continue from wherever it is polled. r.vm.stack_base = &probe as *const u8 as usize; - r.vm.stack_budget = self.stack_budget; + r.vm.stack_budget = run::RUN_STACK_BUDGET; if r.vm.check_time().is_err() { break; } diff --git a/packages/codemode-rust/crates/psychoscript/src/run.rs b/packages/codemode-rust/crates/psychoscript/src/run.rs index 12a464b5ef612..0b0153dc11257 100644 --- a/packages/codemode-rust/crates/psychoscript/src/run.rs +++ b/packages/codemode-rust/crates/psychoscript/src/run.rs @@ -4,9 +4,11 @@ use std::borrow::Cow; use std::panic::AssertUnwindSafe; use std::sync::Arc; -use crate::compiler; +use crate::bytecode::Program; +use crate::compiler::{self, CompileError}; use crate::convert; use crate::host::{self, RunHost}; +use crate::nesting; use crate::object::{Closure, Kind, Obj}; use crate::program::Running; use crate::runtime::{ProgramOptions, Run}; @@ -15,49 +17,47 @@ use crate::value::Value; use crate::vm::Vm; use crate::{Data, Diagnostic, DiagnosticKind, HostString, Outcome, Runtime}; -/// Small programs run on the caller's thread with a modest native-stack budget. Larger ones, whose parse can -/// recurse deeper, run on their own thread with a large stack; the reservation is virtual, only touched pages are -/// committed. -const INLINE_SOURCE_BYTES: usize = 2048; -const INLINE_BRACKET_DEPTH: usize = 64; -pub const INLINE_STACK_BUDGET: usize = 512 << 10; -const STACK_SIZE: usize = 256 << 20; -const THREAD_STACK_BUDGET: usize = 64 << 20; +/// Native stack that parsing and compiling may use per unit of [`nesting::bound`], measured with +/// `bench/examples/stack_probe.rs`, with headroom. The costliest form per unit is a chain of prefix operators: 819 B a +/// level in release builds and 12.9 KB in debug builds. +pub const COMPILE_STACK_PER_LEVEL: usize = if cfg!(debug_assertions) { + 16 << 10 +} else { + 1 << 10 +}; +/// The native stack a run may use from where it is driven, wherever it runs: past it a call fails with a RangeError, so +/// where a program runs never changes what it can do. A run on the caller's thread assumes this much is free there. +pub const RUN_STACK_BUDGET: usize = 512 << 10; +/// Room on a thread beyond what its work is measured to need. +pub(crate) const THREAD_STACK_BASE: usize = 256 << 10; pub fn execute(rt: &Runtime, code: &str, options: &ProgramOptions) -> Outcome { - if code.len() <= INLINE_SOURCE_BYTES && bracket_depth(code) <= INLINE_BRACKET_DEPTH { - let run = AssertUnwindSafe(|| settled(rt.program(code, options).run())); - return std::panic::catch_unwind(run).unwrap_or_else(|_| internal_error()); - } - std::thread::scope(|s| { - let spawned = std::thread::Builder::new() - .stack_size(STACK_SIZE) - .spawn_scoped(s, || { - let mut program = rt.program(code, options); - program.stack_budget = THREAD_STACK_BUDGET; - settled(program.run()) - }); - match spawned { - Ok(handle) => handle.join().unwrap_or_else(|_| internal_error()), - Err(_) => settled(rt.program(code, options).run()), - } - }) + let run = AssertUnwindSafe(|| settled(rt.program(code, options).run())); + std::panic::catch_unwind(run).unwrap_or_else(|_| internal_error()) } -/// The deepest bracket nesting in the source text, a cheap bound on how deep parsing recurses. -fn bracket_depth(code: &str) -> usize { - let (mut depth, mut max) = (0usize, 0usize); - for b in code.bytes() { - match b { - b'(' | b'[' | b'{' => { - depth += 1; - max = max.max(depth); - } - b')' | b']' | b'}' => depth = depth.saturating_sub(1), - _ => {} - } +/// Compiles on the caller's thread when the program's syntax is shallow enough to compile within the run's stack +/// budget, whatever its length; a deeper one compiles on a thread with the stack its nesting needs. Running needs no +/// more native stack for deep syntax, so only compiling moves. +pub fn compile(code: &str, atoms: &mut Strings) -> Result { + let need = nesting::bound(code).saturating_mul(COMPILE_STACK_PER_LEVEL); + if need <= RUN_STACK_BUDGET { + return compiler::compile(code, atoms); } - max + std::thread::scope(|s| { + std::thread::Builder::new() + .stack_size(need.saturating_add(THREAD_STACK_BASE)) + .spawn_scoped(s, || compiler::compile(code, atoms)) + .map_err(|_| CompileError { + kind: DiagnosticKind::ExecutionFailure, + message: + "The program is nested too deeply to compile: no thread with enough stack." + .into(), + offset: None, + })? + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)) + }) } /// The outcome of a run, or for an interrupted one, an `ExecutionFailure` that says so. @@ -92,7 +92,7 @@ pub fn start<'a>( options: &ProgramOptions, ) -> Result>, Box> { let mut atoms = Strings::new(); - let program = match compiler::compile(&code, &mut atoms) { + let program = match compile(&code, &mut atoms) { Ok(p) => p, Err(e) => { let location = e.offset.map(|o| line_col(&code, o)); @@ -139,7 +139,7 @@ pub fn start_for_resume<'a>( ) -> Result, crate::snapshot::SnapshotError> { let code = restored.code; let mut atoms = Strings::new(); - let program = compiler::compile(&code, &mut atoms).map_err(|_| { + let program = compile(&code, &mut atoms).map_err(|_| { crate::snapshot::SnapshotError::new( "Source main does not compile in this build, so it can't resume.", ) diff --git a/packages/codemode-rust/crates/psychoscript/src/snapshot.rs b/packages/codemode-rust/crates/psychoscript/src/snapshot.rs index 6ec8ba7f61ab7..49f7622a6359b 100644 --- a/packages/codemode-rust/crates/psychoscript/src/snapshot.rs +++ b/packages/codemode-rust/crates/psychoscript/src/snapshot.rs @@ -364,7 +364,7 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { }; let state = enc.state(c).map_err(|e| Refusal::Other(e.message))?; let base = vm.snapshot_base; - let program = crate::compiler::compile(c.code, &mut crate::strings::Strings::new()) + let program = crate::run::compile(c.code, &mut crate::strings::Strings::new()) .map_err(|e| Refusal::Other(e.message))?; let limits = vm.limits; let metadata = vm.host.run.metadata(); @@ -907,7 +907,7 @@ fn hex_bytes(s: &str) -> R> { fn baseline(vm: &Vm, code: &str) -> R> { let mut atoms = crate::strings::Strings::new(); let program = - crate::compiler::compile(code, &mut atoms).map_err(|e| SnapshotError::new(e.message))?; + crate::run::compile(code, &mut atoms).map_err(|e| SnapshotError::new(e.message))?; let h = &vm.host; let host = host::RunHost::new(h.globals.clone(), h.modules, h.translate, h.run.clone()); let mut fresh = Vm::new(host, vm.limits, atoms); diff --git a/packages/codemode-rust/crates/psychoscript/tests/api.rs b/packages/codemode-rust/crates/psychoscript/tests/api.rs index 891acffce03e2..be3c760b87920 100644 --- a/packages/codemode-rust/crates/psychoscript/tests/api.rs +++ b/packages/codemode-rust/crates/psychoscript/tests/api.rs @@ -155,6 +155,78 @@ fn deep_input_does_not_overflow() { ); } +#[test] +fn every_deep_form_compiles_without_overflow() { + let rt = Runtime::make(); + let forms = [ + ("return ", "!", "1"), + ("return ", "`${", "1}`"), + ("return ", "() => ", "1"), + ("let a = 1; ", "if (a) a = 1; else ", "a = 2; return a"), + ("let a = 1;\n", "if (a)\n", "a = 2; return a"), + ]; + for (head, form, tail) in forms { + let code = format!("{head}{}{tail}", form.repeat(900)); + let code = code.replace("1}`", &format!("1{}", "}`".repeat(900))); + assert!(run(&rt, &code).result.is_ok(), "{form:?}"); + } +} + +#[test] +fn deep_programs_compile_off_a_small_caller_stack() { + let code = format!("return {}1", "!".repeat(1_500)); + let result = std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(move || { + let rt = Runtime::make(); + let program = rt.program(&code, &ProgramOptions::new()); + program.run().unwrap().json() + }) + .unwrap() + .join() + .unwrap(); + assert_eq!(result.unwrap(), json!(true)); +} + +/// Programs nested far past the limit, some disguised from a cheap scan by `/`s that may be regexes or divisions, end +/// with a diagnostic or an outcome. A native stack overflow would abort this test process instead. +#[test] +fn deliberately_deep_programs_end_cleanly() { + let n = 20_000; + let parens = format!("{}1{}", "(".repeat(n), ")".repeat(n)); + let programs = [ + format!("return {parens}"), + format!("return {}1", "!".repeat(n)), + format!("return {}1", "typeof ".repeat(n)), + format!("return {}1{}", "[".repeat(n), "]".repeat(n)), + format!("return {}1{}", "`${".repeat(n), "}`".repeat(n)), + format!("return {}1", "() => ".repeat(n)), + format!("{}{}return 1", "{".repeat(n), "}".repeat(n)), + format!("let a = 1; {}a = 2", "if (a) a = 1; else ".repeat(n / 2)), + format!("let a = 1, g = 1; a++ / {parens} / g"), + format!("let await = 1, g = 1; await / {parens} / g"), + format!("function f(s) {{ if (s) {{}} /}}/.test(s); return {parens} }}"), + format!("// note\u{2028}{parens}"), + format!("return typeof\u{a0}{}1", "typeof\u{a0}".repeat(n)), + ]; + std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(move || { + let rt = Runtime::make(); + for code in &programs { + let outcome = run(&rt, code); + let ended = match &outcome.result { + Ok(_) => true, + Err(d) => d.kind == DiagnosticKind::ParseError, + }; + assert!(ended, "{}: {:?}", &code[..40], outcome.result); + } + }) + .unwrap() + .join() + .unwrap(); +} + #[test] fn bindings_are_globals_programs_can_shadow() { let mut bindings = serde_json::Map::new(); From 15a0948a0d67ca75ae2f6c9937db79336b69e21e Mon Sep 17 00:00:00 2001 From: Sebastian Herrlinger Date: Thu, 19 Nov 2026 03:24:13 +0100 Subject: [PATCH 4/8] refactor(codemode): runs own their module list and source, so a run outlives its caller's borrow --- .../crates/psychoscript/src/builtins/array.rs | 6 ++--- .../crates/psychoscript/src/builtins/bytes.rs | 4 +-- .../psychoscript/src/builtins/collections.rs | 2 +- .../psychoscript/src/builtins/iterator.rs | 2 +- .../crates/psychoscript/src/builtins/mod.rs | 2 +- .../psychoscript/src/builtins/regexp.rs | 4 +-- .../crates/psychoscript/src/builtins/sets.rs | 2 +- .../crates/psychoscript/src/builtins/web.rs | 6 ++--- .../crates/psychoscript/src/conversion.rs | 2 +- .../crates/psychoscript/src/host.rs | 22 ++++++++-------- .../crates/psychoscript/src/iteration.rs | 2 +- .../crates/psychoscript/src/ops.rs | 2 +- .../crates/psychoscript/src/program.rs | 25 ++++++++----------- .../crates/psychoscript/src/promise.rs | 4 +-- .../crates/psychoscript/src/run.rs | 22 ++++++++-------- .../crates/psychoscript/src/runtime.rs | 5 ++-- .../crates/psychoscript/src/snapshot.rs | 13 +++++++--- .../crates/psychoscript/src/vm.rs | 8 +++--- 18 files changed, 68 insertions(+), 65 deletions(-) diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/array.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/array.rs index 5e4523d4b64e9..ab160d15a2f96 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/array.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/array.rs @@ -85,7 +85,7 @@ fn not_an_array(vm: &mut Vm, this: &Value, callee: Id) -> Value { super::incompatible(vm, &format!("Array.prototype.{name}"), this) } -fn items<'a>(vm: &'a Vm, id: Id) -> &'a [Value] { +fn items(vm: &Vm, id: Id) -> &[Value] { match &vm.heap[id as usize].kind { Kind::Array(items) => items, _ => &[], @@ -181,7 +181,7 @@ fn inherited(vm: &mut Vm, id: Id, i: usize) -> Option { } /// The array's items for a mutating method, after `check_mutable`. -fn items_mut<'a>(vm: &'a mut Vm, id: Id, growth: Option) -> Result<&'a mut Vec, Value> { +fn items_mut(vm: &mut Vm, id: Id, growth: Option) -> Result<&mut Vec, Value> { check_mutable(vm, id, growth)?; array_items(vm, id) } @@ -211,7 +211,7 @@ fn check_mutable(vm: &mut Vm, id: Id, growth: Option) -> Result<(), Value> Ok(()) } -fn array_items<'a>(vm: &'a mut Vm, id: Id) -> Result<&'a mut Vec, Value> { +fn array_items(vm: &mut Vm, id: Id) -> Result<&mut Vec, Value> { if !matches!(vm.heap[id as usize].kind, Kind::Array(_)) { return Err(vm.type_error("not an array")); } diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/bytes.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/bytes.rs index 4e08962a98840..07f30798da33d 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/bytes.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/bytes.rs @@ -124,7 +124,7 @@ fn this_bytes(vm: &mut Vm, this: &Value, name: &str) -> Result { )) } -pub fn bytes_ref<'a>(vm: &'a Vm, id: Id) -> &'a Bytes { +pub fn bytes_ref(vm: &Vm, id: Id) -> &Bytes { match &vm.heap[id as usize].kind { Kind::Bytes(b) => b, _ => unreachable!("checked by this_bytes"), @@ -606,7 +606,7 @@ fn collect_map(vm: &mut Vm, fr: Frame, k: usize) -> Result { fr.call_slots(vm, f, this_arg, [Slot::pack(v), Slot::index(k)]) } -fn values_of<'a>(vm: &'a Vm, s: Slot) -> &'a [Value] { +fn values_of(vm: &Vm, s: Slot) -> &[Value] { match s.obj().map(|o| &vm.heap[o as usize].kind) { Some(Kind::Array(values)) => values, _ => &[], diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/collections.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/collections.rs index 63f70f0873660..0b8d928265c80 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/collections.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/collections.rs @@ -134,7 +134,7 @@ fn map_of(vm: &mut Vm, this: &Value, what: &str) -> Result(vm: &'a mut Vm<'_>, id: Id) -> &'a mut OrderedMap { +fn table(vm: &mut Vm, id: Id) -> &mut OrderedMap { match &mut vm.heap[id as usize].kind { Kind::Map(m) | Kind::Set(m) => m, _ => unreachable!("checked by map_of"), diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/iterator.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/iterator.rs index c170a7a91ad89..7e11ba155ffc5 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/iterator.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/iterator.rs @@ -327,7 +327,7 @@ fn it_drop(vm: &mut Vm, this: Value, args: &[Value], _: Id) -> Res { Ok(primed(vm, iter, next, HelperOp::Drop(n))) } -fn helper_mut<'a>(vm: &'a mut Vm, id: Id) -> &'a mut Helper { +fn helper_mut(vm: &mut Vm, id: Id) -> &mut Helper { match &mut vm.heap[id as usize].kind { Kind::IterHelper(h) => h, _ => unreachable!("checked by this_helper"), diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/mod.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/mod.rs index 89596b7b37e46..a1c64374bebbc 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/mod.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/mod.rs @@ -179,7 +179,7 @@ pub fn arg(args: &[Value], i: usize) -> Value { args.get(i).cloned().unwrap_or_default() } -impl<'rt> Vm<'rt> { +impl Vm { pub fn native_fn(&mut self, name: &'static str, length: u8, f: NativeFn, data: Value) -> Value { let name = self.atoms.intern_static(name); let proto = self.realm.function_proto; diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/regexp.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/regexp.rs index e4583d4fbeef6..be030cb87d089 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/regexp.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/regexp.rs @@ -367,14 +367,14 @@ pub fn as_regexp(vm: &Vm, v: &Value) -> Option { } } -fn data<'a>(vm: &'a Vm, id: Id) -> &'a RegExpData { +fn data(vm: &Vm, id: Id) -> &RegExpData { match &vm.heap[id as usize].kind { Kind::RegExp(r) => r, _ => unreachable!("checked by as_regexp"), } } -fn data_mut<'a>(vm: &'a mut Vm, id: Id) -> &'a mut RegExpData { +fn data_mut(vm: &mut Vm, id: Id) -> &mut RegExpData { match &mut vm.heap[id as usize].kind { Kind::RegExp(r) => r, _ => unreachable!("checked by as_regexp"), diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/sets.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/sets.rs index 65637d4ac7b61..cd95c3b7dea0b 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/sets.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/sets.rs @@ -62,7 +62,7 @@ pub fn setup(vm: &mut Vm) { ); } -fn table<'a>(vm: &'a mut Vm<'_>, id: Id) -> &'a mut OrderedMap { +fn table(vm: &mut Vm, id: Id) -> &mut OrderedMap { match &mut vm.heap[id as usize].kind { Kind::Map(m) | Kind::Set(m) | Kind::WeakMap(m) | Kind::WeakSet(m) => m, _ => unreachable!("checked by the receiver test"), diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/web.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/web.rs index 58d69caa32cbd..a2b44ad141428 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/web.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/web.rs @@ -152,7 +152,7 @@ fn is_runtime_reference(vm: &Vm, v: &Value) -> bool { // ---------- URL ---------- -fn url_data<'a>(vm: &'a Vm, id: Id) -> &'a UrlData { +fn url_data(vm: &Vm, id: Id) -> &UrlData { match &vm.heap[id as usize].kind { Kind::Url(u) => u, _ => unreachable!("checked by the receiver test"), @@ -369,7 +369,7 @@ pub fn url_href(vm: &Vm, id: Id) -> String { // ---------- URLSearchParams ---------- -fn params_mut<'a>(vm: &'a mut Vm, id: Id) -> &'a mut Params { +fn params_mut(vm: &mut Vm, id: Id) -> &mut Params { match &mut vm.heap[id as usize].kind { Kind::SearchParams(p) => p, _ => unreachable!("checked by the receiver test"), @@ -891,7 +891,7 @@ pub fn header_entries(list: &[(String, String)]) -> Vec<(String, String)> { out } -fn headers_mut<'a>(vm: &'a mut Vm, id: Id) -> &'a mut HeaderList { +fn headers_mut(vm: &mut Vm, id: Id) -> &mut HeaderList { match &mut vm.heap[id as usize].kind { Kind::Headers(h) => h, _ => unreachable!("checked by the receiver test"), diff --git a/packages/codemode-rust/crates/psychoscript/src/conversion.rs b/packages/codemode-rust/crates/psychoscript/src/conversion.rs index dde7a8c760879..3b17fc7c0da89 100644 --- a/packages/codemode-rust/crates/psychoscript/src/conversion.rs +++ b/packages/codemode-rust/crates/psychoscript/src/conversion.rs @@ -137,7 +137,7 @@ pub(crate) enum Request { List(Vec, Vec, bool), } -impl Vm<'_> { +impl Vm { /// Whether converting `v` with `hint` calls the program: one of the methods ToPrimitive may call is not native. pub(crate) fn converts_by_call(&mut self, v: &Value, hint: Hint) -> bool { let Value::Obj(id) = v else { return false }; diff --git a/packages/codemode-rust/crates/psychoscript/src/host.rs b/packages/codemode-rust/crates/psychoscript/src/host.rs index 90e5a56bc65b4..3af0c7fcf4e5d 100644 --- a/packages/codemode-rust/crates/psychoscript/src/host.rs +++ b/packages/codemode-rust/crates/psychoscript/src/host.rs @@ -276,16 +276,16 @@ impl SuspendWatch for Unwatched { pub type Globals = Arc<[(String, HostValue)]>; /// The host state of one run. -pub struct RunHost<'rt> { +pub struct RunHost { /// The run's host globals. pub(crate) globals: Globals, /// Module names that load a global, beyond its own name. - pub(crate) modules: &'rt [(String, String)], + pub(crate) modules: Arc<[(String, String)]>, pub(crate) translate: Translate, /// The run as its globals see it: its id and metadata. pub(crate) run: Run, pub(crate) next_call: u64, - pub tasks: Tasks<'rt, Settlement>, + pub tasks: Tasks<'static, Settlement>, pub(crate) functions: Vec, /// Host calls in flight. pub calls: Vec, @@ -361,7 +361,7 @@ pub(crate) struct Meter { pub counted: bool, } -impl<'rt> RunHost<'rt> { +impl RunHost { /// A point where the reference starts the calls queued so far: a new job, or a finished synchronous call. #[inline] pub fn next_epoch(&self) { @@ -371,7 +371,7 @@ impl<'rt> RunHost<'rt> { pub(crate) fn new( globals: Globals, - modules: &'rt [(String, String)], + modules: Arc<[(String, String)]>, translate: Translate, run: Run, ) -> Self { @@ -411,7 +411,7 @@ impl<'rt> RunHost<'rt> { pub(crate) fn bare() -> Self { Self::new( Arc::from([]), - &[], + Arc::from([]), Translate::default(), Run::new(None, Data::Null), ) @@ -511,7 +511,7 @@ impl<'rt> RunHost<'rt> { } } -impl Drop for RunHost<'_> { +impl Drop for RunHost { fn drop(&mut self) { self.cancel_durable(); } @@ -914,10 +914,10 @@ fn block(vm: &mut Vm, work: BoxFuture<'static, HostResult>) -> HostResult { } /// Runs a future for a call, recorded as in flight while it runs. -fn track<'rt>( - vm: &mut Vm<'rt>, +fn track( + vm: &mut Vm, p: Id, - future: BoxFuture<'rt, Settlement>, + future: BoxFuture<'static, Settlement>, in_flight: impl FnOnce() -> InFlight, ) { match vm.host.tasks.spawn(p, future) { @@ -1809,7 +1809,7 @@ fn module(vm: &mut Vm, specifier: &str) -> Res { return Ok(*v); } // A module name the runtime maps to a global. - let modules = vm.host.modules; + let modules = vm.host.modules.clone(); let named = modules .iter() .find(|(m, _)| *m == name) diff --git a/packages/codemode-rust/crates/psychoscript/src/iteration.rs b/packages/codemode-rust/crates/psychoscript/src/iteration.rs index ac715d29f543b..11a68fefd36bb 100644 --- a/packages/codemode-rust/crates/psychoscript/src/iteration.rs +++ b/packages/codemode-rust/crates/psychoscript/src/iteration.rs @@ -70,7 +70,7 @@ pub(crate) const BY_RESUME: usize = 2; /// Its `return` called to close it, as it lacks the `throw` asked for: the promise is rejected after. pub(crate) const BY_CLOSE: usize = 3; -impl Vm<'_> { +impl Vm { /// Whether `it`, kept with `next` in an iterator record, is stepped through a call the VM makes for it: anything /// but a built-in iterator stepped directly and a generator. pub(crate) fn steps_by_call(&self, it: Slot, next: Slot) -> bool { diff --git a/packages/codemode-rust/crates/psychoscript/src/ops.rs b/packages/codemode-rust/crates/psychoscript/src/ops.rs index fd0533e806a0f..45dac4b192b89 100644 --- a/packages/codemode-rust/crates/psychoscript/src/ops.rs +++ b/packages/codemode-rust/crates/psychoscript/src/ops.rs @@ -20,7 +20,7 @@ pub enum Hint { String, } -impl<'rt> Vm<'rt> { +impl Vm { // ---------- property reads ---------- #[inline(never)] diff --git a/packages/codemode-rust/crates/psychoscript/src/program.rs b/packages/codemode-rust/crates/psychoscript/src/program.rs index d0796de58a15b..db241840bc55b 100644 --- a/packages/codemode-rust/crates/psychoscript/src/program.rs +++ b/packages/codemode-rust/crates/psychoscript/src/program.rs @@ -15,16 +15,16 @@ use crate::snapshot::{self, Refusal, Snapshot}; use crate::vm::Vm; use crate::{Interrupted, Outcome, Runtime}; -enum State<'a> { - Running(Box>), +enum State { + Running(Box), /// It ended before running: the program did not compile. Failed(Box), Done, } -pub(crate) struct Running<'a> { - pub vm: Vm<'a>, - pub code: Cow<'a, str>, +pub(crate) struct Running { + pub vm: Vm, + pub code: String, started: bool, timer_armed: bool, /// Active time earlier runs of the same execution used, before a resume. @@ -224,7 +224,7 @@ impl Suspender { /// A program ready to run once. Dropping it interrupts the run and cancels every host call in flight. pub struct Program<'a> { rt: &'a Runtime, - state: State<'a>, + state: State, shared: Arc, } @@ -239,7 +239,7 @@ impl<'a> Program<'a> { Self::with(rt, state) } - fn with(rt: &'a Runtime, mut state: State<'a>) -> Self { + fn with(rt: &'a Runtime, mut state: State) -> Self { let shared = Arc::::default(); if let State::Running(r) = &mut state { r.vm.host.shared = shared.clone(); @@ -534,10 +534,7 @@ fn done_or_suspended(o: RunOutcome) -> Outcome { } /// Rebuilds a suspended run in a fresh VM of this runtime. -fn restore<'a>( - rt: &'a Runtime, - state: &Snapshot, -) -> Result>, snapshot::SnapshotError> { +fn restore(rt: &Runtime, state: &Snapshot) -> Result, snapshot::SnapshotError> { let restored = snapshot::header(state)?; let active_ms = restored.active_ms; let mut started = run::start_for_resume(rt, restored)?; @@ -549,8 +546,8 @@ fn restore<'a>( Ok(r) } -impl<'a> Running<'a> { - pub fn new(vm: Vm<'a>, code: Cow<'a, str>) -> Self { +impl Running { + pub fn new(vm: Vm, code: String) -> Self { Self { vm, code, @@ -590,5 +587,5 @@ const ROUNDTRIP_MAX: u32 = 1 << 16; // A run's state may move to another thread between steps. const _: () = { const fn send() {} - send::>() + send::() }; diff --git a/packages/codemode-rust/crates/psychoscript/src/promise.rs b/packages/codemode-rust/crates/psychoscript/src/promise.rs index a8fda564bbf1f..798673f3f6069 100644 --- a/packages/codemode-rust/crates/psychoscript/src/promise.rs +++ b/packages/codemode-rust/crates/psychoscript/src/promise.rs @@ -123,7 +123,7 @@ pub(crate) fn settle_step(vm: &mut Vm, fr: Frame, input: Input) -> Result Vm<'rt> { +impl Vm { pub fn new_promise(&mut self) -> Id { let proto = self.realm.promise_proto; self.alloc(Obj::new( @@ -528,7 +528,7 @@ fn resolver_reject(vm: &mut Vm, _this: Value, args: &[Value], callee: Id) -> Res // ---------- async generators ---------- -impl<'rt> Vm<'rt> { +impl Vm { /// Creates the async iterator prototypes. Runs while built-ins are set up. pub fn setup_async_iteration(&mut self) { let op = self.realm.object_proto; diff --git a/packages/codemode-rust/crates/psychoscript/src/run.rs b/packages/codemode-rust/crates/psychoscript/src/run.rs index 0b0153dc11257..7ef3156a79f8b 100644 --- a/packages/codemode-rust/crates/psychoscript/src/run.rs +++ b/packages/codemode-rust/crates/psychoscript/src/run.rs @@ -90,7 +90,7 @@ pub fn start<'a>( rt: &'a Runtime, code: Cow<'a, str>, options: &ProgramOptions, -) -> Result>, Box> { +) -> Result, Box> { let mut atoms = Strings::new(); let program = match compile(&code, &mut atoms) { Ok(p) => p, @@ -108,7 +108,7 @@ pub fn start<'a>( let setup = rt.setup(); let run = Run::new(options.run_id.clone(), Data::Null); let globals = setup.globals_for(&run); - let host = RunHost::new(globals, &setup.modules, setup.translate, run); + let host = RunHost::new(globals, setup.modules.clone(), setup.translate, run); let mut vm = Vm::new(host, setup.limits, atoms); vm.setup(); crate::builtins::ensure_globals(&mut vm, &program.globals); @@ -124,19 +124,19 @@ pub fn start<'a>( vm.global_map.insert(a, val); } vm.load(program); - Ok(Box::new(Running::new(vm, code))) + Ok(Box::new(Running::new(vm, code.into_owned()))) } /// A fresh run for a saved program: compiled and set up with the saved limits and no bindings, ready to be filled in. -pub struct Resumed<'a> { - pub running: Box>, +pub struct Resumed { + pub running: Box, pub bytecode: String, } -pub fn start_for_resume<'a>( - rt: &'a Runtime, +pub fn start_for_resume( + rt: &Runtime, restored: crate::snapshot::Restored, -) -> Result, crate::snapshot::SnapshotError> { +) -> Result { let code = restored.code; let mut atoms = Strings::new(); let program = compile(&code, &mut atoms).map_err(|_| { @@ -153,7 +153,7 @@ pub fn start_for_resume<'a>( "This state was saved by a runtime with other host globals; resume it with the same ones.", )); } - let host = RunHost::new(globals, &setup.modules, setup.translate, run); + let host = RunHost::new(globals, setup.modules.clone(), setup.translate, run); let mut vm = Vm::new(host, restored.limits, atoms); vm.setup(); crate::builtins::ensure_globals(&mut vm, &program.globals); @@ -161,7 +161,7 @@ pub fn start_for_resume<'a>( vm.snapshot_base = crate::snapshot::Base::of(&vm); vm.load(program); Ok(Resumed { - running: Box::new(Running::new(vm, Cow::Owned(code))), + running: Box::new(Running::new(vm, code)), bytecode, }) } @@ -206,7 +206,7 @@ pub fn call_main(vm: &mut Vm) { } /// The outcome of a run that ended: host work it left running is interrupted, then the result is copied out. -pub fn finish(r: Running<'_>) -> Outcome { +pub fn finish(r: Running) -> Outcome { let Running { mut vm, code, .. } = r; let code: &str = &code; vm.host.tasks.clear(); diff --git a/packages/codemode-rust/crates/psychoscript/src/runtime.rs b/packages/codemode-rust/crates/psychoscript/src/runtime.rs index 6ea14614c09e9..06246ff1ebaca 100644 --- a/packages/codemode-rust/crates/psychoscript/src/runtime.rs +++ b/packages/codemode-rust/crates/psychoscript/src/runtime.rs @@ -161,7 +161,7 @@ type GlobalsFn = dyn Fn(&Run) -> Vec<(String, HostValue)> + Send + Sync; #[derive(Default)] pub(crate) struct Setup { pub globals: Option>, - pub modules: Vec<(String, String)>, + pub modules: Arc<[(String, String)]>, pub limits: Limits, pub translate: Translate, } @@ -216,7 +216,8 @@ impl Runtime { self.setup.modules = modules .into_iter() .map(|(k, v)| (k.into(), v.into())) - .collect(); + .collect::>() + .into(); self } diff --git a/packages/codemode-rust/crates/psychoscript/src/snapshot.rs b/packages/codemode-rust/crates/psychoscript/src/snapshot.rs index 49f7622a6359b..1f28176dae3fb 100644 --- a/packages/codemode-rust/crates/psychoscript/src/snapshot.rs +++ b/packages/codemode-rust/crates/psychoscript/src/snapshot.rs @@ -317,8 +317,8 @@ pub struct Capture<'c> { pub active_ms: u64, } -struct Enc<'v, 'rt> { - vm: &'v Vm<'rt>, +struct Enc<'v> { + vm: &'v Vm, natives: &'static Natives, protos: FxHashMap, buffers: Vec>>>, @@ -391,7 +391,7 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { )) } -impl Enc<'_, '_> { +impl Enc<'_> { fn state(&mut self, c: &Capture) -> R { let vm = self.vm; let base = vm.snapshot_base; @@ -909,7 +909,12 @@ fn baseline(vm: &Vm, code: &str) -> R> { let program = crate::run::compile(code, &mut atoms).map_err(|e| SnapshotError::new(e.message))?; let h = &vm.host; - let host = host::RunHost::new(h.globals.clone(), h.modules, h.translate, h.run.clone()); + let host = host::RunHost::new( + h.globals.clone(), + h.modules.clone(), + h.translate, + h.run.clone(), + ); let mut fresh = Vm::new(host, vm.limits, atoms); fresh.setup(); crate::builtins::ensure_globals(&mut fresh, &program.globals); diff --git a/packages/codemode-rust/crates/psychoscript/src/vm.rs b/packages/codemode-rust/crates/psychoscript/src/vm.rs index b916701dac686..972394b4ca7b3 100644 --- a/packages/codemode-rust/crates/psychoscript/src/vm.rs +++ b/packages/codemode-rust/crates/psychoscript/src/vm.rs @@ -221,7 +221,7 @@ pub struct Realm { pub std: crate::builtins::StdProtos, } -pub struct Vm<'rt> { +pub struct Vm { pub heap: Vec, pub cells: Vec, pub atoms: Strings, @@ -248,7 +248,7 @@ pub struct Vm<'rt> { pub inbox: VecDeque<(Id, crate::host::Settlement)>, pub coroutines: Vec, pub logs: Vec, - pub host: crate::host::RunHost<'rt>, + pub host: crate::host::RunHost, pub limits: Limits, pub start: Instant, /// Steps left before `budget_out`: the nearer of the reference's fuel and this VM's own check of the clock and of @@ -303,8 +303,8 @@ pub struct Vm<'rt> { pub(crate) replay_meter: Option, } -impl<'rt> Vm<'rt> { - pub fn new(host: crate::host::RunHost<'rt>, limits: Limits, atoms: Strings) -> Self { +impl Vm { + pub fn new(host: crate::host::RunHost, limits: Limits, atoms: Strings) -> Self { let mut atoms = atoms; let names = Names { length: atoms.intern_static("length"), From 34d2637981f6da4d1b7b2c48ebb96a3d0951133f Mon Sep 17 00:00:00 2001 From: Sebastian Herrlinger Date: Thu, 19 Nov 2026 03:29:01 +0100 Subject: [PATCH 5/8] feat(codemode): move long stretches of a run's compute to a worker thread, keeping host code on the executor --- .../codemode-rust/bench/tests/conformance.rs | 62 +++- .../psychoscript/src/builtins/exotic.rs | 9 +- .../crates/psychoscript/src/exec.rs | 39 +- .../crates/psychoscript/src/host.rs | 130 +++++-- .../crates/psychoscript/src/lib.rs | 1 + .../crates/psychoscript/src/offload.rs | 182 +++++++++ .../crates/psychoscript/src/program.rs | 137 +++++-- .../crates/psychoscript/src/vm.rs | 8 + .../crates/psychoscript/tests/offload.rs | 351 ++++++++++++++++++ 9 files changed, 848 insertions(+), 71 deletions(-) create mode 100644 packages/codemode-rust/crates/psychoscript/src/offload.rs create mode 100644 packages/codemode-rust/crates/psychoscript/tests/offload.rs diff --git a/packages/codemode-rust/bench/tests/conformance.rs b/packages/codemode-rust/bench/tests/conformance.rs index 58b2848b133cf..c4fbea016ee47 100644 --- a/packages/codemode-rust/bench/tests/conformance.rs +++ b/packages/codemode-rust/bench/tests/conformance.rs @@ -1,6 +1,7 @@ //! Runs every `conformance/cases/.js` through `psychoscript::Runtime` and compares it with the reference outcome //! in `.json`. Reports every failing case at once. `CONFORMANCE_FILTER=` narrows the run. A case -//! with a `// @platform ""` header is checked only on that OS, where `conformance/generate.ts` records it. +//! with a `// @platform ""` header is checked only on that OS, where `conformance/generate.ts` records it. Every +//! case runs twice: blocking, and as a future, where a long stretch of compute continues on a worker thread. use std::panic::{self, AssertUnwindSafe}; use std::path::Path; @@ -23,7 +24,7 @@ fn runtime(limits: Limits, translate: Translate) -> Runtime { .translate(translate) } -fn check(name: &str, code: &str, expected: &Json) -> Result<(), String> { +fn check(name: &str, code: &str, expected: &Json, future: bool) -> Result<(), String> { let bindings = expected["bindings"] .as_object() .cloned() @@ -46,15 +47,29 @@ fn check(name: &str, code: &str, expected: &Json) -> Result<(), String> { }; let rt = runtime(limits, translate); let options = ProgramOptions::new().bindings(bindings); - let outcome = panic::catch_unwind(AssertUnwindSafe(|| rt.execute_with(code, &options))) - .map_err(|payload| { - let msg = payload - .downcast_ref::() - .cloned() - .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) - .unwrap_or_default(); - format!("{name}: panicked: {msg}") - })?; + let run = || match future { + true => drive(rt.execute_async(code, &options)).unwrap_or_else(|i| psychoscript::Outcome { + result: Err(psychoscript::Diagnostic { + kind: psychoscript::DiagnosticKind::ExecutionFailure, + message: i.to_string().into(), + location: None, + suggestions: Vec::new(), + }), + warnings: Vec::new(), + logs: Vec::new(), + truncated: false, + metadata: psychoscript::Data::Null, + }), + false => rt.execute_with(code, &options), + }; + let outcome = panic::catch_unwind(AssertUnwindSafe(run)).map_err(|payload| { + let msg = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) + .unwrap_or_default(); + format!("{name}: panicked: {msg}") + })?; let mut problems = Vec::new(); match (&outcome.result, expected["ok"].as_bool()) { @@ -146,7 +161,11 @@ fn conformance() { &std::fs::read_to_string(dir.join(format!("{name}.json"))).unwrap(), ) .unwrap(); - check(name, &code, &expected).err() + check(name, &code, &expected, false) + .and_then(|()| { + check(name, &code, &expected, true).map_err(|p| format!("as a future: {p}")) + }) + .err() }) .collect(); panic::set_hook(hook); @@ -161,3 +180,22 @@ fn conformance() { } println!("{} conformance cases passed", names.len()); } + +/// Polls a future to its end on this thread, parking until it is woken. +fn drive(future: F) -> F::Output { + struct Unpark(std::thread::Thread); + impl std::task::Wake for Unpark { + fn wake(self: std::sync::Arc) { + self.0.unpark(); + } + } + let waker = std::task::Waker::from(std::sync::Arc::new(Unpark(std::thread::current()))); + let mut cx = std::task::Context::from_waker(&waker); + let mut future = std::pin::pin!(future); + loop { + if let std::task::Poll::Ready(v) = future.as_mut().poll(&mut cx) { + return v; + } + std::thread::park(); + } +} diff --git a/packages/codemode-rust/crates/psychoscript/src/builtins/exotic.rs b/packages/codemode-rust/crates/psychoscript/src/builtins/exotic.rs index a0f3420675c99..08090a0cf53fd 100644 --- a/packages/codemode-rust/crates/psychoscript/src/builtins/exotic.rs +++ b/packages/codemode-rust/crates/psychoscript/src/builtins/exotic.rs @@ -34,7 +34,14 @@ pub fn get(vm: &mut Vm, id: Id, key: Atom) -> Option { Kind::SearchParams(_) if key == vm.names.size => { Some(Value::Num(web::params_size(vm, id) as f64)) } - Kind::Live(l) => l.getter(key).map(|g| g()), + // A host accessor may run host code (a streaming body's `cancel`), so it runs where the run is driven. + Kind::Live(l) => { + let g = l.getter(key)?; + Some(match crate::offload::home(&vm.host.offload) { + Some(home) => home.run(move || g()).unwrap_or(Value::Undef), + None => g(), + }) + } _ => None, } } diff --git a/packages/codemode-rust/crates/psychoscript/src/exec.rs b/packages/codemode-rust/crates/psychoscript/src/exec.rs index 37db77f4dbe65..fe3daeccdd472 100644 --- a/packages/codemode-rust/crates/psychoscript/src/exec.rs +++ b/packages/codemode-rust/crates/psychoscript/src/exec.rs @@ -1,6 +1,7 @@ //! The small amount of executor a run needs without depending on one: a set of host futures woken individually, //! a thread-parking `block_on`, and one shared timer thread that wakes runs at their deadline. +use crate::offload::Home; use std::collections::BinaryHeap; use std::future::Future; use std::pin::pin; @@ -134,7 +135,12 @@ impl<'a, T> Tasks<'a, T> { } /// Starts a future: it is polled once now, so its work begins at the call. `Ready` means it finished already. - pub fn spawn(&mut self, tag: u32, future: BoxFuture<'a, T>) -> Poll { + /// While the run computes on a worker thread, that poll happens back `home`, where the run is driven. + pub fn spawn(&mut self, tag: u32, future: BoxFuture<'a, T>, home: Option<&Home>) -> Poll + where + 'a: 'static, + T: Send + 'static, + { let index = self.free.pop().unwrap_or_else(|| { self.slots.push(None); self.slots.len() - 1 @@ -143,13 +149,30 @@ impl<'a, T> Tasks<'a, T> { index, shared: self.shared.clone(), })); - let mut slot = Slot { future, waker, tag }; - let mut cx = Context::from_waker(&slot.waker); - if let Poll::Ready(v) = slot.future.as_mut().poll(&mut cx) { - self.free.push(index); - return Poll::Ready(v); - } - self.slots[index] = Some(slot); + let first = |mut future: BoxFuture<'a, T>, waker: &Waker| { + let poll = future.as_mut().poll(&mut Context::from_waker(waker)); + (future, poll) + }; + let started = match home { + None => Some(first(future, &waker)), + Some(home) => { + let waker = waker.clone(); + home.run(move || first(future, &waker)) + } + }; + let future = match started { + Some((_, Poll::Ready(v))) => { + self.free.push(index); + return Poll::Ready(v); + } + Some((future, Poll::Pending)) => future, + // The run is being dropped: the future went with the request. + None => { + self.free.push(index); + return Poll::Pending; + } + }; + self.slots[index] = Some(Slot { future, waker, tag }); self.live += 1; Poll::Pending } diff --git a/packages/codemode-rust/crates/psychoscript/src/host.rs b/packages/codemode-rust/crates/psychoscript/src/host.rs index 3af0c7fcf4e5d..6264823bc7ce0 100644 --- a/packages/codemode-rust/crates/psychoscript/src/host.rs +++ b/packages/codemode-rust/crates/psychoscript/src/host.rs @@ -305,6 +305,9 @@ pub struct RunHost { pub(crate) promise_like: Option, /// Whether a call interrupted the run. pub interrupted: bool, + /// Moving long stretches of compute to a worker thread, for a run driven as a future. Boxed: the VM's hot fields + /// sit after this struct, and a few more bytes here measurably slow its dispatch loop. + pub(crate) offload: Option>, /// Rejected promises nothing handled yet, with their reasons, for the run's warnings. pub unhandled: Vec<(Id, Value)>, pub(crate) modules_loaded: FxHashMap, @@ -393,6 +396,7 @@ impl RunHost { promise_like: None, interrupted: false, unhandled: Vec::new(), + offload: None, modules_loaded: FxHashMap::default(), namespaces: FxHashMap::default(), host_namespaces: FxHashMap::default(), @@ -456,6 +460,11 @@ impl RunHost { } } + /// The run's offload state, made on first use. + pub(crate) fn offload(&mut self) -> &mut crate::offload::Offload { + self.offload.get_or_insert_default() + } + /// Stops durable work still running when the run ends or is interrupted for real; a suspend detaches it first. pub fn cancel_durable(&mut self) { for call in std::mem::take(&mut self.calls) { @@ -723,7 +732,18 @@ pub fn call_namespace(vm: &mut Vm, id: Id, args: &[Value], callee: Value) -> Res return Err(vm.type_error(&message)); }; let resolve = namespace.resolve.clone(); - let f = match resolve(&ns.keys) { + let resolved = match home_of(vm) { + None => resolve(&ns.keys), + Some(home) => { + let keys = ns.keys.clone(); + let Some(resolved) = home.run(move || resolve(&keys)) else { + interrupt(vm); + return Err(Value::Undef); + }; + resolved + } + }; + let f = match resolved { Resolved::Missing(f) => { return Err(failure_value( vm, @@ -826,7 +846,14 @@ fn call_host(vm: &mut Vm, f: &Callee, args: &[Value], target: Target, callee: Va let call_id = vm.host.next_call(); vm.host.enter_sync(call_id, target.label.clone()); let call = vm.host.call(call_id); - let returned = body(host_args, &call); + let returned = match home_of(vm) { + None => body(host_args, &call), + Some(home) => { + let body = body.clone(); + home.run(move || body(host_args, &call)) + .unwrap_or(Returned::Now(Err(HostValue::Interrupt))) + } + }; let returned = match returned { // The run waits for the work: the reference's driver takes over, starting the calls queued so far. Returned::Block(work) => { @@ -876,20 +903,52 @@ fn call_host(vm: &mut Vm, f: &Callee, args: &[Value], target: Target, callee: Va } /// Waits on the thread for work a synchronous call blocks on, while the run's other host calls keep running: what they -/// complete with waits in the inbox. The run's timeout stops the wait; the call then fails as the run times out. +/// complete with waits in the inbox. The run's timeout stops the wait; the call then fails as the run times out. While +/// the run is on its worker, the wait and the other calls' polls happen where the run is driven. fn block(vm: &mut Vm, work: BoxFuture<'static, HostResult>) -> HostResult { let deadline = vm .limits .timeout_ms .map(|ms| vm.start + std::time::Duration::from_millis(ms)); - let mut work = work; + let (settled, done) = match home_of(vm) { + None => wait(&mut vm.host.tasks, work, deadline), + Some(home) => { + let mut tasks = std::mem::take(&mut vm.host.tasks); + let Some((tasks, waited)) = home.run(move || { + let waited = wait(&mut tasks, work, deadline); + (tasks, waited) + }) else { + return Err(HostValue::Interrupt); + }; + vm.host.tasks = tasks; + waited + } + }; + for (p, s) in settled { + vm.host.settled(p); + vm.inbox.push_back((p, s)); + } + match done { + Some(r) => r, + None => { + let _ = vm.check_time(); + Err(HostValue::Undefined) + } + } +} + +/// Polls `work` to its end or the deadline, and the run's other host calls meanwhile: what they complete with, in +/// order, and the work's result, `None` past the deadline. +fn wait( + tasks: &mut crate::exec::Tasks<'static, Settlement>, + mut work: BoxFuture<'static, HostResult>, + deadline: Option, +) -> (Vec<(Id, Settlement)>, Option) { + let mut settled = Vec::new(); let mut armed = false; let done = block_on(std::future::poll_fn(|cx| { - vm.host.tasks.set_parent(Some(cx.waker())); - for (p, s) in vm.host.tasks.poll_ready() { - vm.host.settled(p); - vm.inbox.push_back((p, s)); - } + tasks.set_parent(Some(cx.waker())); + settled.extend(tasks.poll_ready()); if let Poll::Ready(r) = work.as_mut().poll(cx) { return Poll::Ready(Some(r)); } @@ -903,14 +962,13 @@ fn block(vm: &mut Vm, work: BoxFuture<'static, HostResult>) -> HostResult { _ => Poll::Pending, } })); - vm.host.tasks.set_parent(None); - match done { - Some(r) => r, - None => { - let _ = vm.check_time(); - Err(HostValue::Undefined) - } - } + tasks.set_parent(None); + (settled, done) +} + +/// Where host code runs while the run computes on its worker thread; `None` while it runs where it is driven. +fn home_of(vm: &Vm) -> Option { + crate::offload::home(&vm.host.offload).cloned() } /// Runs a future for a call, recorded as in flight while it runs. @@ -920,7 +978,11 @@ fn track( future: BoxFuture<'static, Settlement>, in_flight: impl FnOnce() -> InFlight, ) { - match vm.host.tasks.spawn(p, future) { + match vm + .host + .tasks + .spawn(p, future, crate::offload::home(&vm.host.offload)) + { Poll::Ready(s) => vm.inbox.push_back((p, s)), Poll::Pending => vm.host.calls.push(in_flight()), } @@ -929,6 +991,7 @@ fn track( /// Starts an async or durable call whose promise is `p`, or starts one again on resume. fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: bool) { let call = vm.host.call(r.call); + let home = home_of(vm); let detached = Arc::new(AtomicBool::new(false)); let (label, owner, site) = (r.label.clone(), r.owner.clone(), r.site); let (kind, future): (CallKind, BoxFuture<'static, Settlement>) = match f { @@ -941,7 +1004,14 @@ fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: b true => (CallKind::Idempotent, r.args.clone()), false => (CallKind::Blocking, std::mem::take(&mut r.args)), }; - let work = body(args, call); + let work = match &home { + None => body(args, call), + Some(home) => { + let body = body.clone(); + home.run(move || body(args, call)) + .unwrap_or_else(|| Box::pin(async { Err(HostValue::Interrupt) })) + } + }; ( kind, Box::pin(async move { Settlement::host(work.await, label, owner, site) }), @@ -962,7 +1032,14 @@ fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: b let data = data.clone(); Box::pin(async move { Ok(data) }) } - _ => (d.start)(r.args.clone(), call), + _ => match &home { + None => (d.start)(r.args.clone(), call), + Some(home) => { + let (d, args) = (d.clone(), r.args.clone()); + home.run(move || (d.start)(args, call)) + .unwrap_or_else(|| Box::pin(async { Err(HostValue::Interrupt) })) + } + }, }; let future: BoxFuture<'static, Settlement> = Box::pin(async move { let result = match started.await { @@ -2017,7 +2094,18 @@ pub(crate) fn namespace_keys(vm: &mut Vm, id: Id) -> Result, Val let message = format!("The namespace {} is not available.", vm.atoms.text(ns.root)); return Err(vm.type_error(&message)); }; - (namespace.keys)(&ns.keys).map_err(|thrown| { + let listed = match home_of(vm) { + None => (namespace.keys)(&ns.keys), + Some(home) => { + let keys = ns.keys.clone(); + let Some(listed) = home.run(move || (namespace.keys)(&keys)) else { + interrupt(vm); + return Err(Value::Undef); + }; + listed + } + }; + listed.map_err(|thrown| { let label = vm.ns_label(&ns); thrown_value(vm, &thrown, &label) }) diff --git a/packages/codemode-rust/crates/psychoscript/src/lib.rs b/packages/codemode-rust/crates/psychoscript/src/lib.rs index 08dfb66bcd737..c77ac08b3f72f 100644 --- a/packages/codemode-rust/crates/psychoscript/src/lib.rs +++ b/packages/codemode-rust/crates/psychoscript/src/lib.rs @@ -23,6 +23,7 @@ mod iteration; mod native; mod nesting; mod object; +mod offload; mod ops; mod program; mod promise; diff --git a/packages/codemode-rust/crates/psychoscript/src/offload.rs b/packages/codemode-rust/crates/psychoscript/src/offload.rs new file mode 100644 index 0000000000000..37b35880d2dc0 --- /dev/null +++ b/packages/codemode-rust/crates/psychoscript/src/offload.rs @@ -0,0 +1,182 @@ +//! Moving long stretches of a run's compute off the thread that drives it. A run driven as a future that computes +//! past [`OFFLOAD_AFTER`] without stopping finishes that stretch on a worker thread of its own; the next stretch starts +//! where the run is driven again. Host code stays there: each tool call, extension call, host accessor and first poll +//! of a host future the worker meets is handed back and runs there while the worker waits, so host code runs on the +//! same thread, in the same order, as before. A handed-back call costs a few microseconds, which only stretches already +//! past the budget pay. + +use std::panic::AssertUnwindSafe; +use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::task::{Context, Poll, Waker}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use crate::program::Running; +use crate::run::{RUN_STACK_BUDGET, THREAD_STACK_BASE}; + +/// How long a run may compute on the thread driving it, without stopping, before it moves to a worker thread. +pub const OFFLOAD_AFTER: Duration = Duration::from_millis(1); + +type Job = Box; + +/// A run's side of moving: when the stretch of compute in progress has run long enough to move, whether it stopped to, +/// and where its host code runs while it is away. +#[derive(Default)] +pub struct Offload { + pub at: Option, + pub due: bool, + pub home: Option, +} + +enum ToHome { + /// Host code for the driving thread to run. + Job(Job), + /// The run, back after a stretch of compute. + Back(Box), + /// The interpreter panicked on the worker; the panic continues where the run is driven, as it would have there. + Panicked(Box), +} + +/// Where host code runs while a run with this offload state computes on a worker thread. +pub fn home(offload: &Option>) -> Option<&Home> { + offload.as_ref()?.home.as_ref() +} + +/// The way back to the thread driving a run, for its host code. +#[derive(Clone)] +pub struct Home { + tx: Sender, + waker: Arc>>, +} + +impl Home { + /// Runs `f` on the thread driving the run and waits for its result; `None` when the run is being dropped. + pub fn run(&self, f: impl FnOnce() -> R + Send + 'static) -> Option { + let (reply, answer) = mpsc::sync_channel(1); + self.send(ToHome::Job(Box::new(move || { + let _ = reply.send(f()); + }))) + .ok()?; + answer.recv().ok() + } + + fn send(&self, message: ToHome) -> Result<(), ToHome> { + self.tx.send(message).map_err(|e| e.0)?; + if let Some(w) = self + .waker + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + { + w.wake(); + } + Ok(()) + } +} + +/// A run's worker thread. +pub struct Worker { + to_worker: Option>>, + from_worker: Receiver, + waker: Arc>>, + thread: Option>, +} + +impl Worker { + pub fn spawn() -> std::io::Result { + let (to_worker, runs) = mpsc::channel::>(); + let (tx, from_worker) = mpsc::channel(); + let waker = Arc::new(Mutex::new(None)); + let home = Home { + tx, + waker: waker.clone(), + }; + let thread = std::thread::Builder::new() + .name("psychoscript-run".into()) + .stack_size(RUN_STACK_BUDGET + THREAD_STACK_BASE) + .spawn(move || { + while let Ok(mut r) = runs.recv() { + let message = match std::panic::catch_unwind(AssertUnwindSafe(|| { + compute(&mut r, &home); + })) { + Ok(()) => ToHome::Back(r), + Err(panic) => ToHome::Panicked(panic), + }; + if home.send(message).is_err() { + return; + } + } + })?; + Ok(Self { + to_worker: Some(to_worker), + from_worker, + waker, + thread: Some(thread), + }) + } + + /// Hands the run to the worker for its next stretch of compute. + pub fn compute(&self, r: Box) { + if let Some(tx) = &self.to_worker { + // The worker only stops when this sender is dropped, so it is there to receive. + let _ = tx.send(r); + } + } + + /// Runs the host code the worker hands back, until the run comes back. + pub fn poll(&self, cx: &Context<'_>) -> Poll> { + let mut registered = false; + loop { + match self.from_worker.try_recv() { + Ok(ToHome::Job(job)) => job(), + Ok(ToHome::Back(r)) => return Poll::Ready(r), + Ok(ToHome::Panicked(panic)) => std::panic::resume_unwind(panic), + Err(TryRecvError::Disconnected) => { + unreachable!("the worker only stops once its run is back or abandoned") + } + Err(TryRecvError::Empty) if registered => return Poll::Pending, + // Look again after registering, for a message sent in between. + Err(TryRecvError::Empty) => { + *self.waker.lock().unwrap_or_else(PoisonError::into_inner) = + Some(cx.waker().clone()); + registered = true; + } + } + } + } + + /// Waits for the run to come back, running none of its host code, so it is dropped on the driving thread. The run + /// was asked to stop, which it does at its next safe point. + pub fn reclaim(&self) -> Option> { + loop { + match self.from_worker.recv() { + Ok(ToHome::Job(job)) => drop(job), + Ok(ToHome::Back(r)) => return Some(r), + Ok(ToHome::Panicked(_)) | Err(_) => return None, + } + } + } +} + +impl Drop for Worker { + fn drop(&mut self) { + self.to_worker = None; + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +/// One stretch of compute: until the run ends, waits on the host, or stops at a safe point. +fn compute(r: &mut Running, home: &Home) { + let probe = 0u8; + r.vm.stack_base = &probe as *const u8 as usize; + r.vm.stack_budget = RUN_STACK_BUDGET; + r.vm.host.offload().home = Some(home.clone()); + let _ = r.vm.continue_frames(); + if !r.vm.suspended { + let _ = r.vm.drive(); + } + r.vm.host.offload().home = None; +} diff --git a/packages/codemode-rust/crates/psychoscript/src/program.rs b/packages/codemode-rust/crates/psychoscript/src/program.rs index db241840bc55b..878ab320c8979 100644 --- a/packages/codemode-rust/crates/psychoscript/src/program.rs +++ b/packages/codemode-rust/crates/psychoscript/src/program.rs @@ -9,6 +9,7 @@ use std::task::{Context, Poll, Waker}; use std::time::{Duration, Instant}; use crate::exec; +use crate::offload; use crate::run; use crate::runtime::ProgramOptions; use crate::snapshot::{self, Refusal, Snapshot}; @@ -17,6 +18,8 @@ use crate::{Interrupted, Outcome, Runtime}; enum State { Running(Box), + /// Computing on the program's worker thread. + Away, /// It ended before running: the program did not compile. Failed(Box), Done, @@ -226,6 +229,11 @@ pub struct Program<'a> { rt: &'a Runtime, state: State, shared: Arc, + /// Driven as a future, so a long stretch of compute moves to a worker thread instead of holding the executor's. + offload: bool, + worker: Option, + /// The stretch of compute in progress continues on the worker. + move_away: bool, } impl<'a> Program<'a> { @@ -244,7 +252,14 @@ impl<'a> Program<'a> { if let State::Running(r) = &mut state { r.vm.host.shared = shared.clone(); } - Self { rt, state, shared } + Self { + rt, + state, + shared, + offload: false, + worker: None, + move_away: false, + } } /// A program continuing a suspended run's state, checked against this runtime. @@ -270,7 +285,9 @@ impl<'a> Program<'a> { } /// Runs the program as a future on any executor. Asynchronous host calls run on that executor; a timeout wakes - /// the run from a shared timer thread. Dropping the future interrupts the run and every host call in flight. + /// the run from a shared timer thread. Dropping the future interrupts the run and every host call in flight. A + /// stretch of compute longer than a millisecond continues on a worker thread, so the executor's thread is free + /// meanwhile; every host function, namespace and accessor still runs on the executor. pub async fn run_async(self) -> Result { self.run_resumable_async().await.map(done_or_suspended) } @@ -280,8 +297,9 @@ impl<'a> Program<'a> { exec::block_on(std::future::poll_fn(|cx| self.advance(cx))) } - /// [`Program::run_resumable`] as a future. + /// [`Program::run_resumable`] as a future, which moves long stretches of compute as [`Program::run_async`] does. pub async fn run_resumable_async(mut self) -> Result { + self.offload = true; std::future::poll_fn(|cx| self.advance(cx)).await } @@ -296,38 +314,66 @@ impl<'a> Program<'a> { return Poll::Ready(Ok(outcome)); } loop { + // Back from a stretch of compute on the worker, or still away running its host code. + let computed = matches!(self.state, State::Away); + if computed { + let Some(worker) = &self.worker else { + unreachable!("a run is only away on its worker") + }; + match worker.poll(cx) { + Poll::Ready(r) => self.state = State::Running(r), + Poll::Pending => return Poll::Pending, + } + } let State::Running(r) = &mut self.state else { return Poll::Pending; }; - // Between jobs no native frame of the run is on the stack, so it may continue from wherever it is polled. - r.vm.stack_base = &probe as *const u8 as usize; - r.vm.stack_budget = run::RUN_STACK_BUDGET; - if r.vm.check_time().is_err() { - break; - } - if !r.started { - r.started = true; - r.vm.start = Instant::now() - .checked_sub(r.active_before) - .unwrap_or_else(Instant::now); - if round_trips(&self.shared) { - r.vm.start_roundtrip(r.round_trip_every); + if !computed { + // Between jobs no native frame of the run is on the stack, so it may continue from wherever it is polled. + r.vm.stack_base = &probe as *const u8 as usize; + r.vm.stack_budget = run::RUN_STACK_BUDGET; + if r.vm.check_time().is_err() { + break; } - snapshot::restart_calls(&mut r.vm); - if r.vm.frames.is_empty() && !r.resumed() { - run::call_main(&mut r.vm); + if self.offload { + r.vm.host.offload().at = Some(Instant::now() + offload::OFFLOAD_AFTER); } - } - for (p, s) in r.vm.host.tasks.poll_ready() { - r.vm.host.settled(p); - if let crate::host::Settlement::Interrupted = s { - crate::host::interrupt(&mut r.vm); + if !r.started { + r.started = true; + r.vm.start = Instant::now() + .checked_sub(r.active_before) + .unwrap_or_else(Instant::now); + if round_trips(&self.shared) { + r.vm.start_roundtrip(r.round_trip_every); + } + snapshot::restart_calls(&mut r.vm); + if r.vm.frames.is_empty() && !r.resumed() { + run::call_main(&mut r.vm); + } + } + for (p, s) in r.vm.host.tasks.poll_ready() { + r.vm.host.settled(p); + if let crate::host::Settlement::Interrupted = s { + crate::host::interrupt(&mut r.vm); + } + r.vm.inbox.push_back((p, s)); + } + let away = std::mem::take(&mut self.move_away); + if let Some(worker) = self.worker.as_ref().filter(|_| away) { + r.vm.host.offload().at = None; + let State::Running(r) = std::mem::replace(&mut self.state, State::Away) else { + unreachable!() + }; + worker.compute(r); + continue; + } + let _ = r.vm.continue_frames(); + if !r.vm.suspended { + let _ = r.vm.drive(); + } + if let Some(o) = &mut r.vm.host.offload { + o.at = None; } - r.vm.inbox.push_back((p, s)); - } - let _ = r.vm.continue_frames(); - if !r.vm.suspended { - let _ = r.vm.drive(); } // The run stopped: the reference's driver starts the host calls queued so far. if !r.vm.host.queued.is_empty() { @@ -339,6 +385,25 @@ impl<'a> Program<'a> { if r.vm.outcome.is_some() || r.vm.fatal.is_some() { break; } + // A stop to move only: the stretch continues on the worker, and the next one starts here again. A suspend at + // the same stop goes first. + if r.vm.suspended + && r.vm + .host + .offload + .as_mut() + .is_some_and(|o| std::mem::take(&mut o.due)) + && !self.shared.requested.load(Ordering::Relaxed) + { + r.vm.suspended = false; + r.vm.suspend_wanted = false; + if self.worker.is_none() { + self.worker = offload::Worker::spawn().ok(); + } + self.move_away = self.worker.is_some(); + self.offload = self.move_away; + continue; + } if r.vm.suspended { match self.checkpoint() { Some(done) => return Poll::Ready(Ok(done)), @@ -526,6 +591,20 @@ impl<'a> Program<'a> { } } +impl Drop for Program<'_> { + /// A run away on its worker is asked to stop at its next safe point and comes back, so it ends here, where its + /// host calls are cancelled. + fn drop(&mut self) { + let Some(worker) = self.worker.take() else { + return; + }; + if let State::Away = self.state { + self.shared.requested.store(true, Ordering::Relaxed); + drop(worker.reclaim()); + } + } +} + fn done_or_suspended(o: RunOutcome) -> Outcome { match o { RunOutcome::Done(o) => o, diff --git a/packages/codemode-rust/crates/psychoscript/src/vm.rs b/packages/codemode-rust/crates/psychoscript/src/vm.rs index 972394b4ca7b3..82099967af6fe 100644 --- a/packages/codemode-rust/crates/psychoscript/src/vm.rs +++ b/packages/codemode-rust/crates/psychoscript/src/vm.rs @@ -888,6 +888,14 @@ impl Vm { self.host.meter.fuel = self.roundtrip_every as i32; self.suspend_wanted = true; } + // A long stretch of compute stops to move to a worker thread: see `offload`. + if let Some(o) = &mut self.host.offload + && o.at.is_some_and(|at| std::time::Instant::now() >= at) + { + o.at = None; + o.due = true; + self.suspend_wanted = true; + } if self.host.shared.requested() { self.suspend_wanted = true; } diff --git a/packages/codemode-rust/crates/psychoscript/tests/offload.rs b/packages/codemode-rust/crates/psychoscript/tests/offload.rs new file mode 100644 index 0000000000000..8c48933dc201d --- /dev/null +++ b/packages/codemode-rust/crates/psychoscript/tests/offload.rs @@ -0,0 +1,351 @@ +//! A run driven as a future moves long stretches of compute to a worker thread; host code never runs there. + +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Waker}; +use std::thread::{self, ThreadId}; +use std::time::{Duration, Instant}; + +use psychoscript::{ + Data, DurableFunction, HostFunction, HostString, HostValue, HttpBody, Namespace, + ProgramOptions, Returned, RunOutcome, Runtime, StreamingResponse, +}; +use serde_json::json; + +/// Counts the host code that ran, and how much of it ran off the thread that drives the run. +#[derive(Clone)] +struct Witness { + driver: ThreadId, + ran: Arc, + strays: Arc, +} + +impl Witness { + fn new() -> Self { + Self { + driver: thread::current().id(), + ran: Arc::default(), + strays: Arc::default(), + } + } + + fn check(&self) { + self.ran.fetch_add(1, Ordering::SeqCst); + if thread::current().id() != self.driver { + self.strays.fetch_add(1, Ordering::SeqCst); + } + } +} + +fn first(args: Vec) -> HostValue { + args.into_iter().next().unwrap_or_default() +} + +/// Every kind of host code a program can reach, each noting where it runs: synchronous functions, one blocking the +/// program on work and one leaving work pending, an asynchronous function, a durable one, and a namespace. +fn runtime(w: &Witness) -> Runtime { + let w = w.clone(); + Runtime::make().globals(move |_| { + let (a, b, c, d, e, f) = ( + w.clone(), + w.clone(), + w.clone(), + w.clone(), + w.clone(), + w.clone(), + ); + let (start, wait) = (w.clone(), w.clone()); + let (keys, resolve) = (w.clone(), w.clone()); + vec![ + ( + "sync", + HostValue::from(HostFunction::new(move |args, _| { + a.check(); + Ok::<_, HostValue>(first(args)) + })), + ), + ( + "slow", + HostFunction::new_async(move |args, _| { + let b = b.clone(); + async move { + b.check(); + Ok(later(5, first(args)).await) + } + }) + .into(), + ), + ( + "block", + HostFunction::new(move |args, _| { + c.check(); + let c = c.clone(); + Returned::Block(Box::pin(async move { + c.check(); + Ok(later(5, first(args)).await) + })) + }) + .into(), + ), + ( + "pending", + HostFunction::new(move |args, _| { + d.check(); + let d = d.clone(); + Returned::Pending(Box::pin(async move { + d.check(); + Ok(first(args)) + })) + }) + .into(), + ), + ( + "durable", + DurableFunction::new( + move |_, _| { + let start = start.clone(); + async move { + start.check(); + Ok(Data::Null) + } + }, + move |_, _| { + let wait = wait.clone(); + async move { + wait.check(); + Ok(HostValue::Number(7.0)) + } + }, + |_, _| async {}, + ) + .into(), + ), + ( + "ns", + Namespace::new( + move |_| { + keys.check(); + Ok(vec![HostString::from("f")]) + }, + move |_| { + resolve.check(); + let e = e.clone(); + HostFunction::new(move |args, _| { + e.check(); + Ok::<_, HostValue>(first(args)) + }) + }, + ) + .into(), + ), + ( + "spare", + HostFunction::new(move |_, _| { + f.check(); + Ok::<_, HostValue>(HostValue::Undefined) + }) + .into(), + ), + ] + }) +} + +/// Each host call follows a stretch of compute long enough to move to the worker. +const BUSY_THEN_HOST: &str = " + const spin = (k) => { let n = 0; for (let i = 0; i < k; i++) n += i % 7; return n > 0 } + const a = spin(2e6) && sync(1) + const b = spin(2e6) && await slow(2) + const c = spin(2e6) && block(3) + const d = spin(2e6) && await pending(4) + const e = spin(2e6) && await durable() + const f = spin(2e6) && ns.f(5) + const g = spin(2e6) && Object.keys(ns).length + const h = spin(2e6) && await Promise.all([slow(6), sync(7)]) + return [a, b, c, d, e, f, g, h, spin(1e6)]"; + +#[test] +fn long_compute_leaves_the_executor_while_host_code_stays_on_it() { + let w = Witness::new(); + let rt = runtime(&w); + let options = ProgramOptions::new(); + let expected = json!([1, 2, 3, 4, 7, 5, 1, [6, 7], true]); + let started = Instant::now(); + let blocking = rt.execute(BUSY_THEN_HOST); + let whole = started.elapsed(); + assert_eq!(blocking.json().unwrap(), expected); + let ran_blocking = w.ran.swap(0, Ordering::SeqCst); + + let mut run = Box::pin(rt.execute_async(BUSY_THEN_HOST, &options)); + let started = Instant::now(); + assert!( + run.as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + .is_pending() + ); + assert!( + started.elapsed() < whole / 4, + "the first poll held the executor for {:?} of {whole:?}", + started.elapsed() + ); + let outcome = drive(run).unwrap(); + assert_eq!(outcome.json().unwrap(), expected); + assert_eq!(w.ran.load(Ordering::SeqCst), ran_blocking); + assert_eq!(w.strays.load(Ordering::SeqCst), 0); +} + +/// A future that never ends and notes the thread it is dropped on. +struct Forever(Arc>>); + +impl Future for Forever { + type Output = Result; + + fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll { + Poll::Pending + } +} + +impl Drop for Forever { + fn drop(&mut self) { + *self.0.lock().unwrap() = Some(thread::current().id()); + } +} + +#[test] +fn dropping_a_run_away_on_its_worker_ends_it_here() { + let dropped = Arc::new(Mutex::new(None)); + let seen = dropped.clone(); + let rt = Runtime::make().globals(move |_| { + let seen = seen.clone(); + [( + "never", + HostFunction::new_async(move |_, _| Forever(seen.clone())), + )] + }); + let options = ProgramOptions::new(); + let mut run = Box::pin(rt.execute_async("never(); while (true) {}", &options)); + let waker = Waker::noop(); + assert!( + run.as_mut() + .poll(&mut Context::from_waker(waker)) + .is_pending() + ); + thread::sleep(Duration::from_millis(10)); + assert!( + run.as_mut() + .poll(&mut Context::from_waker(waker)) + .is_pending() + ); + drop(run); + assert_eq!(*dropped.lock().unwrap(), Some(thread::current().id())); +} + +#[test] +fn a_run_away_on_its_worker_suspends_and_resumes() { + let rt = Runtime::make(); + let code = "let n = 0; for (let i = 0; i < 2e9; i++) n++; return n > 0"; + let program = rt.program(code, &ProgramOptions::new()); + let suspender = program.suspender(); + let mut run = Box::pin(program.run_resumable_async()); + assert!( + run.as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + .is_pending() + ); + let asked = thread::spawn(move || suspender.suspend(None)); + let outcome = drive(run).unwrap(); + let answer = asked.join().unwrap().unwrap(); + let (RunOutcome::Suspended(state), RunOutcome::Suspended(_)) = (outcome, answer) else { + panic!("expected a suspended run"); + }; + assert!(rt.resume(&state.state).is_ok()); +} + +/// A body whose `cancel` notes where it ran. +struct Cancelled(Witness); + +impl HttpBody for Cancelled { + fn poll_chunk(&mut self, _: &mut Context<'_>) -> Poll, HostValue>>> { + Poll::Ready(None) + } + + fn cancel(&mut self, _: HostValue) { + self.0.check(); + } +} + +#[test] +fn a_body_cancelled_while_its_run_is_on_a_worker_cancels_on_the_executor() { + let w = Witness::new(); + let body = w.clone(); + let rt = Runtime::make().globals(move |_| { + let body = body.clone(); + [( + "fetch", + HostFunction::new_async(move |_, _| { + let body = Cancelled(body.clone()); + async move { + Ok(HostValue::Response(StreamingResponse::new( + 200, + Some(Box::new(body) as Box), + ))) + } + }), + )] + }); + // A loop long enough to move to the worker, then a cancel queued there, which starts when the program next looks + // at the body after the run has handed calls over: at the `bodyUsed` getter, still on the worker. + let code = "const r = await fetch(); let n = 0 + for (let i = 0; i < 3e6; i++) n += i % 3 + r.body.cancel('stop') + for (let i = 0; i < 1e5; i++) n += i % 3 + return r.bodyUsed && n > 0"; + let outcome = drive(rt.execute_async(code, &ProgramOptions::new())).unwrap(); + assert_eq!(outcome.json().unwrap(), json!(true)); + assert_eq!(w.ran.load(Ordering::SeqCst), 1); + assert_eq!(w.strays.load(Ordering::SeqCst), 0); +} + +/// A value that arrives after `ms` from another thread: an asynchronous host operation without an executor. +fn later(ms: u64, value: T) -> impl Future { + let state = Arc::new(Mutex::new((None, None::))); + let shared = state.clone(); + thread::spawn(move || { + thread::sleep(Duration::from_millis(ms)); + let mut s = shared.lock().unwrap(); + s.0 = Some(value); + if let Some(w) = s.1.take() { + w.wake(); + } + }); + std::future::poll_fn(move |cx| { + let mut s = state.lock().unwrap(); + match s.0.take() { + Some(v) => Poll::Ready(v), + None => { + s.1 = Some(cx.waker().clone()); + Poll::Pending + } + } + }) +} + +/// Polls a future to its end on this thread, parking until it is woken. +fn drive(future: F) -> F::Output { + struct Unpark(thread::Thread); + impl std::task::Wake for Unpark { + fn wake(self: Arc) { + self.0.unpark(); + } + } + let waker = Waker::from(Arc::new(Unpark(thread::current()))); + let mut cx = Context::from_waker(&waker); + let mut future = std::pin::pin!(future); + loop { + if let Poll::Ready(v) = future.as_mut().poll(&mut cx) { + return v; + } + thread::park(); + } +} From 47bf86e198282e01b828ec31077cc358652863e5 Mon Sep 17 00:00:00 2001 From: Sebastian Herrlinger Date: Thu, 19 Nov 2026 03:29:01 +0100 Subject: [PATCH 6/8] test(codemode): bench programs as futures with --async --- packages/codemode-rust/bench/src/main.rs | 35 ++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/packages/codemode-rust/bench/src/main.rs b/packages/codemode-rust/bench/src/main.rs index e327202141227..04dedf152709c 100644 --- a/packages/codemode-rust/bench/src/main.rs +++ b/packages/codemode-rust/bench/src/main.rs @@ -1,6 +1,6 @@ //! Interpreter benchmarks, mirroring the reference `script/bench.ts`: median and fastest wall-clock milliseconds per //! program. Each iteration calls `execute` on the source, with one warm-up run that also checks the program succeeds. -//! Usage: psychoscript-bench [--iterations N] [--filter name] [--json] [--cases DIR] +//! Usage: psychoscript-bench [--iterations N] [--filter name] [--json] [--cases DIR] [--async] //! `--iterations 0` runs only the warm-up, for one-shot measurements such as peak RSS. //! //! `psychoscript-bench --plugin [--runs N] SOURCE...` is the plugin-event benchmark instead: the conformance @@ -41,6 +41,7 @@ fn main() { let mut iterations = 11usize; let mut filter = String::new(); let mut json = false; + let mut future = false; let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../conformance/cases"); let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -53,12 +54,21 @@ fn main() { } "--filter" => filter = args.next().expect("--filter name"), "--json" => json = true, + "--async" => future = true, "--cases" => dir = args.next().expect("--cases DIR").into(), other => panic!("unknown argument {other}"), } } let runtime = runtime(); + let options = psychoscript::ProgramOptions::new(); + // `--async` drives each run as a future, where a long one computes on a worker thread. + let execute = |code: &str| { + if future { + return block_on(runtime.execute_async(code, &options)).expect("not interrupted"); + } + runtime.execute(code) + }; let mut report = Vec::new(); for (slug, name) in CASES { if !(slug.contains(&filter) || name.contains(&filter)) { @@ -67,14 +77,14 @@ fn main() { let path = dir.join(format!("bench-{slug}.js")); let code = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let value = match runtime.execute(&code).result { + let value = match execute(&code).result { Ok(value) => value, Err(d) => panic!("{name} failed: {d:?}"), }; let times: Vec = (0..iterations) .map(|_| { let start = Instant::now(); - let _ = runtime.execute(&code); + let _ = execute(&code); start.elapsed().as_secs_f64() * 1e3 }) .collect(); @@ -135,3 +145,22 @@ fn plugin(mut args: impl Iterator) { ); } } + +/// Polls a future to its end on this thread, parking until it is woken. +fn block_on(future: F) -> F::Output { + struct Unpark(std::thread::Thread); + impl std::task::Wake for Unpark { + fn wake(self: std::sync::Arc) { + self.0.unpark(); + } + } + let waker = std::task::Waker::from(std::sync::Arc::new(Unpark(std::thread::current()))); + let mut cx = std::task::Context::from_waker(&waker); + let mut future = std::pin::pin!(future); + loop { + if let std::task::Poll::Ready(v) = future.as_mut().poll(&mut cx) { + return v; + } + std::thread::park(); + } +} From ba616f357aaa6c905c1518a129f181515d0f1553 Mon Sep 17 00:00:00 2001 From: Sebastian Herrlinger Date: Thu, 19 Nov 2026 03:34:27 +0100 Subject: [PATCH 7/8] docs(codemode): refresh bench results after threading by nesting --- packages/codemode-rust/bench/RESULTS.md | 92 ++++++++++++------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/packages/codemode-rust/bench/RESULTS.md b/packages/codemode-rust/bench/RESULTS.md index ad5e66dbd8502..0d8a1fdaf30ab 100644 --- a/packages/codemode-rust/bench/RESULTS.md +++ b/packages/codemode-rust/bench/RESULTS.md @@ -8,53 +8,53 @@ mins and means are shown for spread, never compared. ## Environment - CPU: Apple M5 Max, 18 cores, 48 GiB RAM, macOS 26.7.1 arm64 -- Reference: anomalyco/opencode 04e3d5b5a0e1503e02428fb544bda51ffe3642c3, `packages/codemode` -- PsychoScript: 04e3d5b5a0e1503e02428fb544bda51ffe3642c3 +- Reference: anomalyco/opencode 47bf86e198282e01b828ec31077cc358652863e5, `packages/codemode` +- PsychoScript: 47bf86e198282e01b828ec31077cc358652863e5 - bun 1.4.4; rustc 1.100.0 (0ef1bc386 2026-11-09); cargo 1.100.0 (3acc79c0c 2026-11-05) ## (a) Per-case wall time, 11 iterations after one warm-up -| Case | Reference median ms | Reference min ms | Rust median ms | Rust min ms | Median speedup | -|---|---:|---:|---:|---:|---:| -| numeric loop | 9.1 | 6.2 | 4.1 | 3.8 | 2.2x | -| closure recursion (fib 22) | 2.0 | 1.9 | 1.4 | 1.4 | 1.4x | -| array callbacks (50k) | 36.8 | 36.2 | 10.1 | 9.9 | 3.6x | -| promise fan-out (5k) | 3.4 | 2.5 | 0.8 | 0.8 | 4.0x | -| tool fan-out (1k) ¹ | 1.8 | 1.6 | 0.4 | 0.4 | 4.0x | -| JSON round-trip | 21.7 | 19.8 | 10.8 | 10.6 | 2.0x | -| generator iteration | 2.2 | 2.2 | 1.1 | 1.1 | 2.0x | -| string building | 7.9 | 6.7 | 2.8 | 2.8 | 2.8x | -| Map/Set ops | 5.9 | 5.5 | 4.3 | 4.2 | 1.4x | +| Case | Reference median ms | Reference min ms | Rust median ms | Rust min ms | Median speedup | +| -------------------------- | ------------------: | ---------------: | -------------: | ----------: | -------------: | +| numeric loop | 9.2 | 6.1 | 3.9 | 3.8 | 2.3x | +| closure recursion (fib 22) | 2.0 | 1.9 | 1.4 | 1.4 | 1.4x | +| array callbacks (50k) | 36.6 | 35.8 | 9.8 | 9.8 | 3.7x | +| promise fan-out (5k) | 3.0 | 2.3 | 0.9 | 0.9 | 3.5x | +| tool fan-out (1k) ¹ | 1.8 | 1.7 | 0.4 | 0.4 | 4.3x | +| JSON round-trip | 21.9 | 20.0 | 10.9 | 10.6 | 2.0x | +| generator iteration | 2.2 | 2.2 | 1.1 | 1.1 | 2.0x | +| string building | 7.8 | 6.8 | 2.8 | 2.7 | 2.8x | +| Map/Set ops | 5.6 | 5.5 | 4.3 | 4.1 | 1.3x | ¹ `tools.echo` is an async host function in a `Host.namespace` on both sides (`conformance/reference.ts` and `conformance/reference.rs`); neither validates its input or output. ## (b) Cold start: process start to the result of `return 1` -| Implementation | Median wall ms (20 runs) | -|---|---:| -| Reference (bun bench/ref/embed.ts) | 66.4 | -| Rust (embed example) | 1.9 | +| Implementation | Median wall ms (20 runs) | +| ---------------------------------- | -----------------------: | +| Reference (bun bench/ref/embed.ts) | 65.8 | +| Rust (embed example) | 1.9 | ## (c) Peak RSS, each case once in a fresh process -| Case | Reference peak RSS MiB | Rust peak RSS MiB | -|---|---:|---:| -| numeric loop | 87.4 | 3.5 | -| closure recursion (fib 22) | 83.5 | 3.5 | -| array callbacks (50k) | 107.8 | 7.8 | -| promise fan-out (5k) | 94.5 | 8.2 | -| tool fan-out (1k) | 91.9 | 5.7 | -| JSON round-trip | 123.7 | 19.9 | -| generator iteration | 84.0 | 3.6 | -| string building | 114.2 | 7.5 | -| Map/Set ops | 102.2 | 10.0 | +| Case | Reference peak RSS MiB | Rust peak RSS MiB | +| -------------------------- | ---------------------: | ----------------: | +| numeric loop | 89.3 | 3.6 | +| closure recursion (fib 22) | 81.3 | 3.6 | +| array callbacks (50k) | 107.9 | 8.0 | +| promise fan-out (5k) | 95.5 | 8.3 | +| tool fan-out (1k) | 90.7 | 5.6 | +| JSON round-trip | 122.2 | 20.1 | +| generator iteration | 83.0 | 3.7 | +| string building | 113.6 | 7.6 | +| Map/Set ops | 102.6 | 10.1 | ## (d) Binary size -| Artifact | Bytes | MiB | -|---|---:|---:| -| Rust embed example, release, stripped | 6135352 | 5.85 | +| Artifact | Bytes | MiB | +| ---------------------------------------- | -------: | ----: | +| Rust embed example, release, stripped | 6318616 | 6.03 | | bun executable (what you ship otherwise) | 88660864 | 84.55 | ## (e) Perturbed variants, 11 iterations after one warm-up @@ -63,17 +63,17 @@ Each program in `bench/variants/` computes the same result as its original, writ identifiers, equivalent constants, function expressions and named functions for callbacks, and other loop forms. A variant / original ratio far from the reference's on one side only points at a shape-specific fast path. -| Case | Reference original median ms | Reference variant median ms | Reference variant / original | Rust original median ms | Rust variant median ms | Rust variant / original | Rust ratio / reference ratio | -|---|---:|---:|---:|---:|---:|---:|---:| -| numeric loop | 9.1 | 6.5 | 0.71 | 4.2 | 4.6 | 1.08 | 1.53x | -| closure recursion (fib 22) | 2.0 | 1.9 | 0.97 | 1.4 | 1.4 | 0.99 | 1.01x | -| array callbacks (50k) | 36.1 | 38.2 | 1.06 | 10.0 | 10.8 | 1.09 | 1.03x | -| promise fan-out (5k) | 3.0 | 2.5 | 0.83 | 0.9 | 1.0 | 1.12 | 1.35x | -| tool fan-out (1k) | 1.9 | 1.4 | 0.73 | 0.4 | 0.5 | 1.17 | 1.60x | -| JSON round-trip | 20.7 | 20.0 | 0.97 | 10.8 | 11.0 | 1.02 | 1.05x | -| generator iteration | 3.2 | 3.1 | 0.96 | 1.1 | 1.1 | 1.03 | 1.07x | -| string building | 7.5 | 7.4 | 0.99 | 2.8 | 3.2 | 1.14 | 1.16x | -| Map/Set ops | 5.5 | 8.5 | 1.55 | 4.3 | 4.6 | 1.06 | 0.68x | +| Case | Reference original median ms | Reference variant median ms | Reference variant / original | Rust original median ms | Rust variant median ms | Rust variant / original | Rust ratio / reference ratio | +| -------------------------- | ---------------------------: | --------------------------: | ---------------------------: | ----------------------: | ---------------------: | ----------------------: | ---------------------------: | +| numeric loop | 9.1 | 6.6 | 0.72 | 4.2 | 4.3 | 1.04 | 1.44x | +| closure recursion (fib 22) | 2.0 | 1.9 | 0.98 | 1.4 | 1.4 | 0.98 | 1.00x | +| array callbacks (50k) | 36.8 | 38.1 | 1.03 | 10.0 | 11.0 | 1.10 | 1.06x | +| promise fan-out (5k) | 3.0 | 2.1 | 0.69 | 0.9 | 1.1 | 1.23 | 1.79x | +| tool fan-out (1k) | 1.7 | 1.4 | 0.78 | 0.5 | 0.5 | 0.84 | 1.09x | +| JSON round-trip | 21.1 | 19.8 | 0.94 | 11.0 | 10.9 | 0.99 | 1.06x | +| generator iteration | 3.1 | 3.0 | 0.97 | 1.1 | 1.1 | 1.02 | 1.06x | +| string building | 7.5 | 7.5 | 0.99 | 2.7 | 3.2 | 1.15 | 1.16x | +| Map/Set ops | 5.4 | 8.1 | 1.50 | 4.3 | 4.7 | 1.10 | 0.74x | ## (f) Plugin event: µs per execute, 2000 runs after 2000 warm-up runs @@ -81,10 +81,10 @@ The conformance reducer (`plugin-reducer-*`) handling `{ type: "command", name: `tools.git.status` host function, through `execute` once per event. `reducer.js` is its command path; `reducer-padded.js` is the whole reducer with eleven more command handlers before the matching one. -| Source | Bytes | Reference median µs | Reference min µs | Reference mean µs | Rust median µs | Rust min µs | Rust mean µs | Median speedup | -|---|---:|---:|---:|---:|---:|---:|---:|---:| -| `bench/plugin/reducer.js` | 226 | 109.4 | 92.7 | 125.2 | 21.4 | 19.8 | 21.7 | 5.1x | -| `bench/plugin/reducer-padded.js` | 2957 | 187.1 | 156.0 | 264.4 | 61.5 | 56.2 | 63.6 | 3.0x | +| Source | Bytes | Reference median µs | Reference min µs | Reference mean µs | Rust median µs | Rust min µs | Rust mean µs | Median speedup | +| -------------------------------- | ----: | ------------------: | ---------------: | ----------------: | -------------: | ----------: | -----------: | -------------: | +| `bench/plugin/reducer.js` | 226 | 112.2 | 92.7 | 128.3 | 21.2 | 19.5 | 21.4 | 5.3x | +| `bench/plugin/reducer-padded.js` | 2957 | 189.7 | 153.9 | 263.1 | 44.8 | 41.5 | 45.2 | 4.2x | ## Commands From 2b150b4654b54db1241cfdf52cac57f1dfd5f852 Mon Sep 17 00:00:00 2001 From: Sebastian Herrlinger Date: Thu, 19 Nov 2026 03:34:51 +0100 Subject: [PATCH 8/8] docs(codemode): describe how runs use threads --- packages/codemode-rust/PR.md | 33 ++++++++++++++++++++++++++++++++ packages/codemode-rust/README.md | 3 ++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/packages/codemode-rust/PR.md b/packages/codemode-rust/PR.md index df868d3ce8524..c3bb546fb44a0 100644 --- a/packages/codemode-rust/PR.md +++ b/packages/codemode-rust/PR.md @@ -66,6 +66,39 @@ recordings and fails on any difference. through the reference's language runtime with the same `tools` namespace. It covers per-case time, cold start, peak RSS, binary size and perturbed variants; the table states the command and machine. +## Threading + +How a run uses threads changes how it runs, never what a program can do or see. + +- **Compiling.** Parsing and compiling recurse once per level of syntax, and the parser has no guard of its own. A + token scan (`nesting::bound`) gives an upper bound on a program's nesting without parsing it. It is conservative + by construction: where it can't tell how the parser reads a `/` (regex or division) or a byte, it counts that + line raw, every opening bracket and no closer, and source it can't tokenize counts raw to the end. A program + compiles on the caller's thread when its bound fits the 512 KB budget, however long it is. A deeper one compiles + on a thread sized to its bound: 1 KiB per unit in release builds and 16 KiB in debug builds, over the measured + worst of 819 B and 12.9 KB (`bench/examples/stack_probe.rs`). Every entry point compiles this way: `execute`, + `program`, `execute_async` and `resume`. +- **Running.** Running needs no native stack for deep syntax, and built-in callbacks are VM frames: re-entrant calls + cost no native stack per level. A run therefore stays on the thread that drives it, with the same 512 KB budget + everywhere. Call depth matches the reference exactly: 10,000 levels at one program frame per level, 5,000 at two, + 3,334 at three. +- **Long runs as futures.** In `execute_async`, `run_async` and `run_resumable_async`, a stretch of compute longer than + 1 ms stops at its next safe point (a loop back-edge or a job boundary). It finishes on a worker thread of the run's + own, so the executor's thread is free meanwhile. The next stretch starts on the executor again. Host code never + runs on the worker; each piece is handed back to the executor while the worker waits, so it runs on the same thread + and in the same order as without the worker: + - a host function's call, and the work a synchronous one blocks on; + - starting an async or durable function, and the first poll of its future; + - namespace `resolve` and `keys`; + - accessors such as a streaming body's `cancel`. + + A handed-back call costs a few microseconds, which only stretches already past 1 ms pay. Dropping a run while it is + on its worker brings it back first, so its calls are cancelled on the executor. A suspend works the same either + way. Blocking `execute` and `Program::run` never use a worker: the caller waits either way. +- **Cost.** To move between threads, a run's state is `Send` (`Arc` instead of `Rc`, byte buffers behind an + uncontended `Mutex`). The nine bench programs stay within 0.5% of the single-threaded instruction counts. The 3 KB + plugin event stops paying for a thread: 9% fewer instructions. + ## Known differences - A saved state resumes only in the implementation and build that saved it: the snapshot formats differ, and diff --git a/packages/codemode-rust/README.md b/packages/codemode-rust/README.md index 94d571e654972..42b466960a917 100644 --- a/packages/codemode-rust/README.md +++ b/packages/codemode-rust/README.md @@ -59,7 +59,8 @@ The API is the Rust form of the reference's `Language` namespace: | `Json` a host passes or keeps (bindings, `run.metadata`, a durable function's data) | `Data`, which keeps unpaired surrogates; it converts from and to `serde_json::Value` | Host work is a `Future` instead of an Effect: `Runtime::execute` drives a run on the calling thread, and -`execute_async` and `Program::run_async` run on any executor. Values cross the boundary as copies (`HostValue`); a +`execute_async` and `Program::run_async` run on any executor. As a future, a stretch of compute longer than 1 ms continues on a worker +thread of the run's own while every host call still runs on the executor; see `PR.md`'s Threading. Values cross the boundary as copies (`HostValue`); a string crosses as a `HostString`, which keeps a string with an unpaired surrogate exactly, so a host sees and returns what the program had. Every string the API hands over that can hold program text is one: values, object keys, error names and messages, RegExp sources, namespace paths, the result (`Data`), logs, diagnostics and failures, bindings,