From e24937e99629fb8ba29f10eb4c99e221856e11b4 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Sat, 28 Nov 2026 22:40:30 +0100 Subject: [PATCH 1/3] feat(rust): cloneable Runtime, 'static Program, and Runtime::offload(false) --- rust/README.md | 4 +- rust/crates/psychoscript/src/program.rs | 40 +++++++------ rust/crates/psychoscript/src/runtime.rs | 58 ++++++++++++++----- rust/crates/psychoscript/tests/hostile.rs | 2 +- rust/crates/psychoscript/tests/offload.rs | 39 +++++++++++++ rust/crates/psychoscript/tests/snapshot.rs | 4 +- rust/crates/psychoscript/tests/streaming.rs | 2 +- rust/crates/psychoscript/tests/value_depth.rs | 2 +- 8 files changed, 112 insertions(+), 39 deletions(-) diff --git a/rust/README.md b/rust/README.md index 181bf8a4..a5432621 100644 --- a/rust/README.md +++ b/rust/README.md @@ -71,6 +71,7 @@ Only Rust has: - Always-on typed arrays: `ArrayBuffer`, `Uint16Array`, `Uint32Array`, `Int32Array`, `Float32Array`, `Float64Array`, as [`HostValue::TypedArray`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs): lent without a copy to sync host functions, copied for async and durable ones. - Lazy built-in groups: [`LAZY`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/builtins/mod.rs) sets up `RegExp`, `Date`, the typed arrays and the other groups only when a program uses them. - Optional `locale` feature (`default = ["locale"]`): disable it with `default-features = false` to drop ICU4X's compiled CLDR tables (~5 MB) in lean embedded or `wasm32` builds. With `locale` off, `locales` and `options` are ignored: `Date.prototype.toLocale*String` returns UTC ISO-8601 strings (`YYYY-MM-DDTHH:mm:ss.sssZ`, date slice, or time slice, or `"Invalid Date"`), `Number`/`BigInt.prototype.toLocaleString` use decimal `toString`, and `String.prototype.localeCompare` compares NFC-normalized UTF-16 code units. +- Owned runs that stay on the calling thread: [`Runtime`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs) clones cheaply, [`Program`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/program.rs) holds a clone so it is `'static`, and `Runtime::offload(false)` keeps a run driven as a future on the thread that polls it, without starting a worker thread, so CPU time counts there. Only TypeScript has: @@ -159,7 +160,8 @@ Known differences: ## Design - **Threading:** a run stays on the thread that drives it; as a future, compute past 1 ms moves to a worker of the - run's own while host code is always handed back to the executor, in the same order. On wasm32, without threads, the + run's own (unless `Runtime::offload(false)` keeps it on the calling thread) while host code is always handed back to + the executor, in the same order. On wasm32, without threads, the run yields to its executor there instead, and a thread can't wait: a synchronous run waiting on host work that isn't ready, or a sync host function's `Returned::Block` work, ends in an `ExecutionFailure` saying so. - **Memory:** an incremental, non-moving mark-sweep collector (`collector.rs`) frees what a run can no longer reach, diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index 5826c841..390fef11 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -224,30 +224,32 @@ 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, +/// A program ready to run once. Holds a clone of its [`Runtime`], so it is `'static`. Dropping it interrupts the run +/// and cancels every host call in flight. +pub struct Program { + rt: 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. + /// Driven as a future with offloading enabled, 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> { +impl Program { /// Compiles the program and sets up its globals; nothing runs yet. - pub(crate) fn new(rt: &'a Runtime, code: Code<'_>, options: &ProgramOptions) -> Self { + pub(crate) fn new(rt: &Runtime, code: Code<'_>, options: &ProgramOptions) -> Self { let started = run::start(rt, code, options); let state = match started { Ok(r) => State::Running(r), Err(outcome) => State::Failed(outcome), }; - Self::with(rt, state) + Self::with(rt.clone(), state) } - fn with(rt: &'a Runtime, mut state: State) -> Self { + fn with(rt: Runtime, mut state: State) -> Self { let shared = Arc::::default(); if let State::Running(r) = &mut state { r.vm.host.shared = shared.clone(); @@ -263,12 +265,9 @@ impl<'a> Program<'a> { } /// A program continuing a suspended run's state, checked against this runtime. - pub(crate) fn resume( - rt: &'a Runtime, - state: &Snapshot, - ) -> Result { + pub(crate) fn resume(rt: &Runtime, state: &Snapshot) -> Result { let running = restore(rt, state)?; - Ok(Self::with(rt, State::Running(running))) + Ok(Self::with(rt.clone(), State::Running(running))) } /// What suspends this run from another thread. @@ -314,9 +313,10 @@ impl<'a> Program<'a> { Ok(outcome) } - /// [`Program::run_resumable`] as a future, which moves long stretches of compute as [`Program::run_async`] does. + /// [`Program::run_resumable`] as a future, which moves long stretches of compute as [`Program::run_async`] does + /// unless [`Runtime::offload`] was set to `false`. pub async fn run_resumable_async(mut self) -> Result { - self.offload = true; + self.offload = self.rt.setup().offload; std::future::poll_fn(|cx| self.advance(cx)).await } @@ -634,7 +634,7 @@ impl<'a> Program<'a> { let saved = r.vm.heap.len().saturating_sub(r.vm.snapshot_base.heap); let skip = (saved / 800 + bytes.len() / 400_000) as u32; let state = snapshot::from_bytes(&bytes).ok()?; - match restore(self.rt, &state) { + match restore(&self.rt, &state) { Ok(mut fresh) => { fresh.vm.host.shared = self.shared.clone(); // A round trip is not a pause: the run's clock keeps its start, which the header would @@ -678,7 +678,7 @@ impl<'a> Program<'a> { } } -impl Drop for Program<'_> { +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) { @@ -750,8 +750,10 @@ 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. +// A run and its state are owned and may move to another thread between steps. const _: () = { const fn send() {} - send::() + const fn owned() {} + send::(); + owned::(); }; diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 9c01e716..c45a502b 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -177,13 +177,27 @@ impl ProgramOptions { type GlobalsFn = dyn Fn(&Run) -> Vec<(String, HostValue)> + Send + Sync; /// What a runtime shares with every run it starts. -#[derive(Default)] +#[derive(Clone)] pub(crate) struct Setup { - pub globals: Option>, + pub globals: Option>, pub modules: Arc<[(String, String)]>, pub limits: Limits, pub translate: Translate, pub program_lines: Option<(u32, u32)>, + pub offload: bool, +} + +impl Default for Setup { + fn default() -> Self { + Self { + globals: None, + modules: Arc::from([]), + limits: Limits::default(), + translate: Translate::default(), + program_lines: None, + offload: true, + } + } } impl Setup { @@ -196,10 +210,11 @@ impl Setup { } } -/// A reusable confined runtime over host globals: each run of a program is independent. -#[derive(Default)] +/// A reusable confined runtime over host globals: each run of a program is independent. Cheap to clone, and shared +/// across threads. +#[derive(Clone, Default)] pub struct Runtime { - setup: Setup, + setup: Arc, } impl Runtime { @@ -219,7 +234,7 @@ impl Runtime { K: Into, V: Into, { - self.setup.globals = Some(Box::new(move |run| { + Arc::make_mut(&mut self.setup).globals = Some(Arc::new(move |run| { globals(run) .into_iter() .map(|(k, v)| (k.into(), v.into())) @@ -233,7 +248,7 @@ impl Runtime { mut self, modules: impl IntoIterator, ) -> Self { - self.setup.modules = modules + Arc::make_mut(&mut self.setup).modules = modules .into_iter() .map(|(k, v)| (k.into(), v.into())) .collect::>() @@ -263,13 +278,13 @@ impl Runtime { "maxValueDepth must be an integer from 1 to {}.", crate::MAX_VALUE_DEPTH_LIMIT ); - self.setup.limits = limits; + Arc::make_mut(&mut self.setup).limits = limits; self } /// How host calls' arguments carry functions and promises; see [`Translate`]. pub fn translate(mut self, translate: Translate) -> Self { - self.setup.translate = translate; + Arc::make_mut(&mut self.setup).translate = translate; self } @@ -279,7 +294,16 @@ impl Runtime { /// as the call was made), when there is one; so is [`Call::location`](crate::Call::location). Without it every /// line is the program's. pub fn program_lines(mut self, first: u32, last: u32) -> Self { - self.setup.program_lines = Some((first, last)); + Arc::make_mut(&mut self.setup).program_lines = Some((first, last)); + self + } + + /// Whether a run driven as a future ([`Runtime::execute_async`], [`Program::run_async`], + /// [`Program::run_resumable_async`]) moves stretches of compute past 1 ms to a worker thread (`true` by default; + /// on wasm32, yields to its executor). Set to `false` to keep the run on the thread that polls it, so its CPU time + /// counts on that thread and no worker thread is started. + pub fn offload(mut self, offload: bool) -> Self { + Arc::make_mut(&mut self.setup).offload = offload; self } @@ -305,8 +329,8 @@ impl Runtime { } /// A program, from its source or [compiled](Runtime::compile), ready to run once; nothing runs until - /// [`Program::run`] or [`Program::run_async`]. - pub fn program<'c>(&self, code: impl Into>, options: &ProgramOptions) -> Program<'_> { + /// [`Program::run`] or [`Program::run_async`]. Holds a clone of this runtime, so it is `'static`. + pub fn program<'c>(&self, code: impl Into>, options: &ProgramOptions) -> Program { Program::new(self, code.into(), options) } @@ -321,12 +345,12 @@ impl Runtime { /// are made again for the run with its saved id and metadata. Fails with a [`SnapshotError`] when the state was /// saved by another build, with other host globals, from a source that no longer compiles the same, or is /// malformed or changed since it was saved. - pub fn resume(&self, state: &Snapshot) -> Result, SnapshotError> { + pub fn resume(&self, state: &Snapshot) -> Result { Program::resume(self, state) } /// [`Runtime::resume`] from [`to_bytes`](crate::to_bytes). - pub fn resume_bytes(&self, bytes: &[u8]) -> Result, SnapshotError> { + pub fn resume_bytes(&self, bytes: &[u8]) -> Result { let state = from_bytes(bytes)?; Program::resume(self, &state) } @@ -335,3 +359,9 @@ impl Runtime { &self.setup } } + +// A runtime is shared across threads and cheap to clone. +const _: () = { + const fn shared() {} + shared::() +}; diff --git a/rust/crates/psychoscript/tests/hostile.rs b/rust/crates/psychoscript/tests/hostile.rs index a2073a06..697bdbfc 100644 --- a/rust/crates/psychoscript/tests/hostile.rs +++ b/rust/crates/psychoscript/tests/hostile.rs @@ -1183,7 +1183,7 @@ fn malformed_states_are_refused_or_resume_without_panicking() { fn resumes<'r>( rt: &'r Runtime, label: &str, - resume: impl FnOnce(&'r Runtime) -> Result, psychoscript::SnapshotError>, + resume: impl FnOnce(&'r Runtime) -> Result, ) -> Vec<(String, String)> { guarded(label, || { if let Ok(program) = resume(rt) { diff --git a/rust/crates/psychoscript/tests/offload.rs b/rust/crates/psychoscript/tests/offload.rs index 8c48933d..8e636f07 100644 --- a/rust/crates/psychoscript/tests/offload.rs +++ b/rust/crates/psychoscript/tests/offload.rs @@ -331,6 +331,45 @@ fn later(ms: u64, value: T) -> impl Future { }) } +#[test] +fn runtime_clones_and_program_is_static() { + let rt = Runtime::make().globals(|_| { + [( + "bump", + HostFunction::new(|args, _| HostValue::from(args[0].as_f64().unwrap_or(0.0) + 1.0)), + )] + }); + let program = rt + .clone() + .offload(false) + .program("return bump(41)", &ProgramOptions::new()); + drop(rt); + let future: Pin + Send + 'static>> = + Box::pin(program.run_resumable_async()); + let RunOutcome::Done(outcome) = drive(future).unwrap() else { + panic!("expected a completed run"); + }; + assert_eq!(outcome.json().unwrap(), json!(42)); +} + +#[test] +fn offload_false_keeps_compute_on_the_calling_thread() { + use psychoscript::thread_clock::ThreadClock; + + // Without offloading, a fixed compute loop finishes in the single poll on this thread's CPU clock. + let rt = Runtime::make().offload(false); + let work = "let n = 0; for (let i = 0; i < 6e5; i++) n += i % 3; return n"; + let mut run = Box::pin(rt.program(work, &ProgramOptions::new()).run_async()); + let clock = ThreadClock::current(); + let before = clock.now(); + let Poll::Ready(Ok(outcome)) = run.as_mut().poll(&mut Context::from_waker(Waker::noop())) + else { + panic!("expected single-poll completion without offloading"); + }; + assert_eq!(outcome.json().unwrap(), json!(600_000)); + assert!(clock.now() > before); +} + /// Polls a future to its end on this thread, parking until it is woken. fn drive(future: F) -> F::Output { struct Unpark(thread::Thread); diff --git a/rust/crates/psychoscript/tests/snapshot.rs b/rust/crates/psychoscript/tests/snapshot.rs index c8430c1e..1011d399 100644 --- a/rust/crates/psychoscript/tests/snapshot.rs +++ b/rust/crates/psychoscript/tests/snapshot.rs @@ -165,8 +165,8 @@ fn options(run_id: &str) -> ProgramOptions { } /// Runs `program` on this thread while `during` runs on another with its suspender. -fn background<'a, T: Send>( - program: Program<'a>, +fn background( + program: Program, during: impl FnOnce(Suspender) -> T + Send, ) -> (RunOutcome, T) { let suspender = program.suspender(); diff --git a/rust/crates/psychoscript/tests/streaming.rs b/rust/crates/psychoscript/tests/streaming.rs index 32f2cbf4..610a735e 100644 --- a/rust/crates/psychoscript/tests/streaming.rs +++ b/rust/crates/psychoscript/tests/streaming.rs @@ -305,7 +305,7 @@ impl Waiting { /// Runs `program` on this thread while `during` runs on another with its suspender. fn background( - program: Program<'_>, + program: Program, during: impl FnOnce(Suspender) -> T + Send, ) -> (RunOutcome, T) { let suspender = program.suspender(); diff --git a/rust/crates/psychoscript/tests/value_depth.rs b/rust/crates/psychoscript/tests/value_depth.rs index 51bd1bcc..0366c0aa 100644 --- a/rust/crates/psychoscript/tests/value_depth.rs +++ b/rust/crates/psychoscript/tests/value_depth.rs @@ -151,7 +151,7 @@ fn resumed_argument(depth: usize) -> HostValue { } /// Suspends `program` once `ready` says its call has started. -fn suspend(program: psychoscript::Program<'_>, ready: mpsc::Receiver<()>) -> Snapshot { +fn suspend(program: psychoscript::Program, ready: mpsc::Receiver<()>) -> Snapshot { let suspender = program.suspender(); let outcome = std::thread::scope(|s| { s.spawn(move || { From c81f954b35c0746b67d0775fc81b00a61fef05fe Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 19:28:18 +0100 Subject: [PATCH 2/3] fix(rust): keep wasm32's cooperative yield under offload(false), and say native compute holds the polling thread --- rust/crates/psychoscript/src/program.rs | 2 +- rust/crates/psychoscript/src/runtime.rs | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index e69a861a..95be60b4 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -328,7 +328,7 @@ impl Program { /// [`Program::run_resumable`] as a future, which moves long stretches of compute as [`Program::run_async`] does /// unless [`Runtime::offload`] was set to `false`. pub async fn run_resumable_async(mut self) -> Result { - self.offload = self.rt.setup().offload; + self.offload = cfg!(target_arch = "wasm32") || self.rt.setup().offload; std::future::poll_fn(|cx| self.advance(cx)).await } diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index c76e3b0d..52528220 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -316,8 +316,9 @@ impl Runtime { /// Whether a run driven as a future ([`Runtime::execute_async`], [`Program::run_async`], /// [`Program::run_resumable_async`]) moves stretches of compute past 1 ms to a worker thread (`true` by default; - /// on wasm32, yields to its executor). Set to `false` to keep the run on the thread that polls it, so its CPU time - /// counts on that thread and no worker thread is started. + /// on wasm32, which yields to its executor instead, either way). Set to `false` to keep the run on the thread that + /// polls it, so its CPU time counts on that thread and no worker thread is started. + /// With `false`, a stretch of compute holds the polling thread until the next host wait or [`Limits::slice_ms`]. pub fn offload(mut self, offload: bool) -> Self { Arc::make_mut(&mut self.setup).offload = offload; self From 50c38d4dc8c252e2465796397d626f6e45c0f5cc Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 19:34:21 +0100 Subject: [PATCH 3/3] docs(rust): run_async keeps compute on the polling thread with offload(false) --- rust/crates/psychoscript/src/program.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index 95be60b4..e1e65993 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -297,8 +297,9 @@ impl Program { /// 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. 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. + /// stretch of compute longer than a millisecond continues on a worker thread, unless [`Runtime::offload`] is + /// `false`, 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) }