From cc5763abc2f11b4e53916726a969555f99f5c1bc Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Sun, 29 Nov 2026 01:22:19 +0100 Subject: [PATCH 1/3] feat(rust): make source size limit configurable via Limits::max_source_bytes --- rust/README.md | 1 + rust/crates/psychoscript/src/compiler.rs | 12 +-- rust/crates/psychoscript/src/diagnostic.rs | 13 +++ rust/crates/psychoscript/src/lib.rs | 1 + rust/crates/psychoscript/src/run.rs | 23 ++++- rust/crates/psychoscript/src/runtime.rs | 11 ++- rust/crates/psychoscript/src/snapshot.rs | 12 ++- .../crates/psychoscript/tests/source_limit.rs | 92 +++++++++++++++++++ 8 files changed, 144 insertions(+), 21 deletions(-) create mode 100644 rust/crates/psychoscript/tests/source_limit.rs diff --git a/rust/README.md b/rust/README.md index 181bf8a4..ee8df95d 100644 --- a/rust/README.md +++ b/rust/README.md @@ -66,6 +66,7 @@ Only Rust has: - The interpreter slice: [`Limits::slice_ms`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs), the longest stretch between awaits of the host; past it, `SliceExceeded`. - The function marker: [`TranslateFunctions::Mark`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs), giving `HostValue::FunctionMarker` and `Data::FunctionMarker`. - A value depth limit: [`Limits::max_value_depth`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs), at most [`MAX_VALUE_DEPTH_LIMIT`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/convert.rs). +- A configurable source size limit: [`Limits::max_source_bytes`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs), defaulting to [`DEFAULT_MAX_SOURCE_BYTES`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/compiler.rs) (256 KiB). - Located host errors: [`HostError::located`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs) (`HostValue::Located`), caught as a standard error at the call, with the host error's own fields. - The program's own lines: [`Runtime::program_lines`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs); an error raised in the host's code around them (a prelude), or by a host function called from there, is located at the nearest frame of the program, as is [`Call::location`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/host_function.rs). - 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. diff --git a/rust/crates/psychoscript/src/compiler.rs b/rust/crates/psychoscript/src/compiler.rs index 4723001e..65344197 100644 --- a/rust/crates/psychoscript/src/compiler.rs +++ b/rust/crates/psychoscript/src/compiler.rs @@ -35,8 +35,9 @@ type R = Result; /// Deepest syntactic nesting a program may have; it bounds the recursion of analysis and compilation. const MAX_NESTING: u32 = 2_000; -/// Largest program accepted, which bounds the parser's own recursion. -const MAX_SOURCE_BYTES: usize = 256 * 1024; +/// The largest program accepted when [`Limits::max_source_bytes`](crate::Limits::max_source_bytes) is `None` +/// (256 KiB); `run::compile` refuses a larger one, which bounds the parser's own recursion. +pub const DEFAULT_MAX_SOURCE_BYTES: usize = 256 * 1024; pub fn compile(source: &str, atoms: &mut Strings) -> R { compile_as(source, atoms, false) @@ -84,13 +85,6 @@ fn compile_in( atoms: &mut Strings, internal: bool, ) -> R { - if source.len() > MAX_SOURCE_BYTES { - return Err(CompileError { - kind: DiagnosticKind::ParseError, - message: format!("Program is larger than {MAX_SOURCE_BYTES} bytes."), - offset: None, - }); - } if source.trim().is_empty() { return Err(CompileError { kind: DiagnosticKind::ParseError, diff --git a/rust/crates/psychoscript/src/diagnostic.rs b/rust/crates/psychoscript/src/diagnostic.rs index 376ccf6c..eb9cb457 100644 --- a/rust/crates/psychoscript/src/diagnostic.rs +++ b/rust/crates/psychoscript/src/diagnostic.rs @@ -15,6 +15,12 @@ pub struct Limits { /// [`MAX_VALUE_DEPTH_LIMIT`](crate::MAX_VALUE_DEPTH_LIMIT), as the copies recurse on the native stack once a /// level. A value nested deeper fails with a `TypeError` (a `RangeError` for the result and `JSON.stringify`). pub max_value_depth: Option, + /// The most bytes of source code [`Runtime::compile`](crate::Runtime::compile) and + /// [`Runtime::execute`](crate::Runtime::execute) accept; `None` (the default) is + /// [`DEFAULT_MAX_SOURCE_BYTES`](crate::DEFAULT_MAX_SOURCE_BYTES) (256 KiB). It bounds what compiling can cost: + /// the parser recurses once a level of syntax, a source nests no deeper than it has bytes, and the stack for it is + /// made to fit. In a debug build 256 KiB of `[` takes 1 GiB and 1 s to refuse, and 1 MiB of it 4 GiB and 4 s. + pub max_source_bytes: Option, /// What `timeout_ms` and `slice_ms` count; [`Clock::Wall`] by default. pub clock: Clock, /// The longest a run may compute without awaiting the host: from its start or resume, or from when a host call it @@ -26,6 +32,13 @@ pub struct Limits { pub slice_ms: Option, } +impl Limits { + pub(crate) fn source_limit(&self) -> usize { + self.max_source_bytes + .unwrap_or(crate::DEFAULT_MAX_SOURCE_BYTES) + } +} + /// What a run's `timeout_ms` and `slice_ms` count. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Clock { diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index b2c9e5ce..319c0ae7 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -52,6 +52,7 @@ mod time; mod value; mod vm; +pub use compiler::DEFAULT_MAX_SOURCE_BYTES; pub use convert::MAX_VALUE_DEPTH_LIMIT; pub use data::Data; pub use diagnostic::{Clock, Diagnostic, DiagnosticKind, Interrupted, Limits}; diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index b05e46a0..99fb7c0c 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -82,9 +82,10 @@ impl<'a> From<&'a Compiled> for Code<'a> { } /// Parses and compiles a program, or the diagnostic a run of it would fail with before running anything. -pub fn compile_program(code: &str) -> Result { +pub fn compile_program(code: &str, max_source_bytes: usize) -> Result { let mut atoms = Strings::fresh(); - let program = compile(code, &mut atoms).map_err(|e| compile_diagnostic(code, e))?; + let program = + compile(code, &mut atoms, max_source_bytes).map_err(|e| compile_diagnostic(code, e))?; Ok(Compiled(Arc::new(CompiledProgram { code: Arc::from(code), program, @@ -113,7 +114,18 @@ pub fn execute(rt: &Runtime, code: Code<'_>, options: &ProgramOptions) -> Outcom /// more native stack for deep syntax, so only compiling moves. On `wasm32`, where spawning a helper thread is /// unsupported, programs exceeding `RUN_STACK_BUDGET` return an error instead of attempting to spawn or overflowing /// the wasm stack. -pub fn compile(code: &str, atoms: &mut Strings) -> Result { +pub fn compile( + code: &str, + atoms: &mut Strings, + max_source_bytes: usize, +) -> Result { + if code.len() > max_source_bytes { + return Err(CompileError { + kind: DiagnosticKind::ParseError, + message: format!("Program is larger than {max_source_bytes} bytes."), + offset: None, + }); + } // A program nests no deeper than it has bytes, so a short one needs no scan to know it fits. let fits = |levels: usize| levels.saturating_mul(COMPILE_STACK_PER_LEVEL) <= RUN_STACK_BUDGET; let need = match fits(code.len()) { @@ -186,7 +198,7 @@ pub fn start( Code::Compiled(c) => (c.0.code.clone(), c.0.program.clone(), c.0.atoms.clone()), Code::Source(code) => { let mut atoms = Strings::fresh(); - match compile(code, &mut atoms) { + match compile(code, &mut atoms, rt.setup().limits.source_limit()) { Ok(p) => (Arc::from(code), p, atoms), Err(e) => return Err(Box::new(failed(compile_diagnostic(code, e)))), } @@ -231,7 +243,8 @@ pub fn start_for_resume( ) -> Result { let code = restored.code; let mut atoms = Strings::fresh(); - let mut program = compile(&code, &mut atoms).map_err(|_| { + // The run that saved the state accepted its source: it compiles again whatever its size. + let mut program = compile(&code, &mut atoms, code.len()).map_err(|_| { crate::snapshot::SnapshotError::new( "Source main does not compile in this build, so it can't resume.", ) diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 9c01e716..de951d00 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -245,8 +245,9 @@ impl Runtime { /// /// # Panics /// - /// When `timeout_ms` or `max_heap_bytes` is `Some(0)`, or `max_value_depth` is `Some(0)` or more than - /// [`MAX_VALUE_DEPTH_LIMIT`](crate::MAX_VALUE_DEPTH_LIMIT), which the reference refuses with a `RangeError`. + /// When `timeout_ms`, `max_heap_bytes` or `max_source_bytes` is `Some(0)`, or `max_value_depth` is `Some(0)` or + /// more than [`MAX_VALUE_DEPTH_LIMIT`](crate::MAX_VALUE_DEPTH_LIMIT), which the reference refuses with a + /// `RangeError`. pub fn limits(mut self, limits: Limits) -> Self { assert!( limits.timeout_ms != Some(0), @@ -263,6 +264,10 @@ impl Runtime { "maxValueDepth must be an integer from 1 to {}.", crate::MAX_VALUE_DEPTH_LIMIT ); + assert!( + limits.max_source_bytes != Some(0), + "maxSourceBytes must be a safe integer greater than or equal to 1." + ); self.setup.limits = limits; self } @@ -314,7 +319,7 @@ impl Runtime { /// without doing it again; or the diagnostic a run of it would fail with first (an empty program, a syntax /// error). Unsupported syntax still fails where it runs, as from source. A compiled program runs in any runtime. pub fn compile(&self, code: &str) -> Result { - crate::run::compile_program(code) + crate::run::compile_program(code, self.setup.limits.source_limit()) } /// A program continuing a suspended run, from its state. It keeps the limits it was saved with, and its globals diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index 5774e339..4c8f9583 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -436,8 +436,10 @@ 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::run::compile(c.code, &mut crate::strings::Strings::fresh()) - .map_err(|e| Refusal::Other(e.message))?; + // The run accepted its source when it started: it compiles again whatever its size. + let fresh = &mut crate::strings::Strings::fresh(); + let program = + crate::run::compile(c.code, fresh, c.code.len()).map_err(|e| Refusal::Other(e.message))?; let limits = *vm.limits; let metadata = vm.host.run.metadata(); let mut header = json!({ @@ -992,8 +994,8 @@ fn hex_bytes(s: &str) -> R> { /// Each object of a fresh run's base, encoded, to see which ones the run changed. fn baseline(vm: &Vm, code: &str) -> R> { let mut atoms = crate::strings::Strings::fresh(); - let program = - crate::run::compile(code, &mut atoms).map_err(|e| SnapshotError::new(e.message))?; + let program = crate::run::compile(code, &mut atoms, code.len()) + .map_err(|e| SnapshotError::new(e.message))?; let h = &vm.host; let host = host::RunHost::new( h.globals.clone(), @@ -2234,6 +2236,8 @@ pub fn header(snapshot: &Snapshot) -> R { .ok_or_else(|| invalid("the value depth is out of range."))?, ), }, + // Not saved: it bounds the source a run starts from, and a state brings its own. + max_source_bytes: None, }, active_ms: field(budget, "activeMs")?.as_u64().unwrap_or(0), }) diff --git a/rust/crates/psychoscript/tests/source_limit.rs b/rust/crates/psychoscript/tests/source_limit.rs new file mode 100644 index 00000000..9164dd4f --- /dev/null +++ b/rust/crates/psychoscript/tests/source_limit.rs @@ -0,0 +1,92 @@ +//! `Limits::max_source_bytes`: defaults to `DEFAULT_MAX_SOURCE_BYTES` (256 KiB) and survives suspend/resume. + +use std::sync::mpsc; + +use psychoscript::{ + DEFAULT_MAX_SOURCE_BYTES, DiagnosticKind, HostFunction, HostValue, Limits, ProgramOptions, + RunOutcome, Runtime, from_bytes, to_bytes, +}; +use serde_json::json; + +fn padded(bytes: usize, tail: &str) -> String { + format!( + "// {}\n{tail}", + "a".repeat(bytes.saturating_sub(tail.len() + 4)) + ) +} + +#[test] +fn source_size_bound_defaults_to_256kib_and_is_configurable() { + let over_default = padded(DEFAULT_MAX_SOURCE_BYTES + 1, "return 42"); + let err = Runtime::make().compile(&over_default).unwrap_err(); + assert_eq!(err.kind, DiagnosticKind::ParseError); + assert!( + err.message_lossy() + .contains(&DEFAULT_MAX_SOURCE_BYTES.to_string()) + ); + + let one_mib = 1 << 20; + let rt = Runtime::make().limits(Limits { + max_source_bytes: Some(one_mib), + ..Limits::default() + }); + let at_1m = padded(one_mib, "return 99"); + assert_eq!(at_1m.len(), one_mib); + let compiled = rt.compile(&at_1m).expect("1 MiB fits under 1 MiB limit"); + assert_eq!(rt.execute(&compiled).json().unwrap(), json!(99)); + assert_eq!(rt.execute(at_1m.as_str()).json().unwrap(), json!(99)); + assert_eq!( + rt.compile(&padded(one_mib + 1, "return 99")) + .unwrap_err() + .kind, + DiagnosticKind::ParseError + ); +} + +#[test] +fn large_program_survives_suspend_and_resume() { + let (started, ready) = mpsc::channel(); + let rt1 = Runtime::make() + .limits(Limits { + max_source_bytes: Some(1 << 20), + ..Limits::default() + }) + .globals(move |_| { + let started = started.clone(); + [( + "wait", + HostFunction::new_async(move |_, _| { + let _ = started.send(()); + std::future::pending() + }) + .idempotent(), + )] + }); + let code = padded(300 * 1024, "await wait(); return 7"); + let program = rt1.program(code.as_str(), &ProgramOptions::new()); + let suspender = program.suspender(); + let state = std::thread::scope(|s| { + let h = s.spawn(move || { + ready.recv().unwrap(); + suspender.suspend(None).unwrap() + }); + let _ = program.run_resumable().unwrap(); + let RunOutcome::Suspended(suspended) = h.join().unwrap() else { + panic!("expected suspended") + }; + suspended.state + }); + let state = from_bytes(&to_bytes(&state)).unwrap(); + + // Resumes on a default-limit runtime: the limit bounds the source a run starts from, not a saved state's. + let rt2 = Runtime::make().globals(|_| { + [( + "wait", + HostFunction::new_async(|_, _| async { Ok(HostValue::Undefined) }).idempotent(), + )] + }); + let RunOutcome::Done(outcome) = rt2.resume(&state).unwrap().run_resumable().unwrap() else { + panic!("expected done") + }; + assert_eq!(outcome.json().unwrap(), json!(7)); +} From 4edc1cc8514716e02bbd1b4c9d21f749c9773515 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 19:25:43 +0100 Subject: [PATCH 2/3] fix(rust): name max_source_bytes in its panic, and give its cost after #177 --- rust/crates/psychoscript/src/diagnostic.rs | 6 +++--- rust/crates/psychoscript/src/runtime.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/rust/crates/psychoscript/src/diagnostic.rs b/rust/crates/psychoscript/src/diagnostic.rs index eb9cb457..c0f8a77c 100644 --- a/rust/crates/psychoscript/src/diagnostic.rs +++ b/rust/crates/psychoscript/src/diagnostic.rs @@ -17,9 +17,9 @@ pub struct Limits { pub max_value_depth: Option, /// The most bytes of source code [`Runtime::compile`](crate::Runtime::compile) and /// [`Runtime::execute`](crate::Runtime::execute) accept; `None` (the default) is - /// [`DEFAULT_MAX_SOURCE_BYTES`](crate::DEFAULT_MAX_SOURCE_BYTES) (256 KiB). It bounds what compiling can cost: - /// the parser recurses once a level of syntax, a source nests no deeper than it has bytes, and the stack for it is - /// made to fit. In a debug build 256 KiB of `[` takes 1 GiB and 1 s to refuse, and 1 MiB of it 4 GiB and 4 s. + /// [`DEFAULT_MAX_SOURCE_BYTES`](crate::DEFAULT_MAX_SOURCE_BYTES) (256 KiB). What compiling costs grows with it: + /// a source nested past `MAX_COMPILE_LEVELS` is refused before it is parsed, which for 1 MiB of `[` takes 16 ms + /// and 48 MiB in a release build. pub max_source_bytes: Option, /// What `timeout_ms` and `slice_ms` count; [`Clock::Wall`] by default. pub clock: Clock, diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 528c54d9..51f3ed2a 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -281,7 +281,7 @@ impl Runtime { ); assert!( limits.max_source_bytes != Some(0), - "maxSourceBytes must be a safe integer greater than or equal to 1." + "max_source_bytes must be at least 1." ); self.setup.limits = limits; self From 2e4e373be9ef3ac95f0916fe61b739024f33a241 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 19:28:43 +0100 Subject: [PATCH 3/3] docs(rust): DEFAULT_MAX_SOURCE_BYTES no longer claims to bound the parser --- rust/crates/psychoscript/src/compiler.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/crates/psychoscript/src/compiler.rs b/rust/crates/psychoscript/src/compiler.rs index 65344197..bb3eb3c9 100644 --- a/rust/crates/psychoscript/src/compiler.rs +++ b/rust/crates/psychoscript/src/compiler.rs @@ -36,7 +36,7 @@ type R = Result; /// Deepest syntactic nesting a program may have; it bounds the recursion of analysis and compilation. const MAX_NESTING: u32 = 2_000; /// The largest program accepted when [`Limits::max_source_bytes`](crate::Limits::max_source_bytes) is `None` -/// (256 KiB); `run::compile` refuses a larger one, which bounds the parser's own recursion. +/// (256 KiB); `run::compile` refuses a larger one. pub const DEFAULT_MAX_SOURCE_BYTES: usize = 256 * 1024; pub fn compile(source: &str, atoms: &mut Strings) -> R {