Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Only Rust has:
- A heap cap and live heap size: [`Limits::max_heap_bytes`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs), measured in the size model of [`heap.rs`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/heap.rs); over it, `MemoryLimitExceeded`. [`Run::heap_bytes`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs) returns the last measured reachable bytes of a live run without the `gc-stats` feature. It is measured under `max_heap_bytes`, or without a cap at the run's waits for the host with `Runtime::measure_heap(true)`; otherwise `None`. A run that drops much of its heap without allocating keeps reporting the old size until it allocates again.
- CPU-time budgets: [`Limits::clock`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/diagnostic.rs) `Clock::ThreadCpu` for `timeout_ms` (also [`thread_clock`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/thread_clock.rs) for hosts).
- 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`.
- 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` and every standard typed array besides Uint8Array, 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.
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/psychoscript/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1506,7 +1506,7 @@ mod tests {
/// A VM as a run of `CODE` starts, which a snapshot of it restores into.
fn program_vm() -> (Vm, String) {
let mut atoms = Strings::fresh();
let Ok(program) = crate::run::compile(CODE, &mut atoms) else {
let Ok(program) = crate::run::compile(CODE, &mut atoms, CODE.len()) else {
panic!("compiles");
};
let mut vm = Vm::new(RunHost::bare(), Limits::default(), atoms);
Expand Down
12 changes: 3 additions & 9 deletions rust/crates/psychoscript/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ type R<T> = Result<T, CompileError>;

/// 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.
pub const DEFAULT_MAX_SOURCE_BYTES: usize = 256 * 1024;

pub fn compile(source: &str, atoms: &mut Strings) -> R<Program> {
compile_as(source, atoms, false)
Expand Down Expand Up @@ -84,13 +85,6 @@ fn compile_in(
atoms: &mut Strings,
internal: bool,
) -> R<Program> {
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,
Expand Down
13 changes: 13 additions & 0 deletions rust/crates/psychoscript/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>,
/// 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). 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<usize>,
/// 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
Expand All @@ -26,6 +32,13 @@ pub struct Limits {
pub slice_ms: Option<u64>,
}

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 {
Expand Down
1 change: 1 addition & 0 deletions rust/crates/psychoscript/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,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};
Expand Down
23 changes: 18 additions & 5 deletions rust/crates/psychoscript/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,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<Compiled, Diagnostic> {
pub fn compile_program(code: &str, max_source_bytes: usize) -> Result<Compiled, Diagnostic> {
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,
Expand Down Expand Up @@ -119,7 +120,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<Program, CompileError> {
pub fn compile(
code: &str,
atoms: &mut Strings,
max_source_bytes: usize,
) -> Result<Program, CompileError> {
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()) {
Expand Down Expand Up @@ -199,7 +211,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)))),
}
Expand Down Expand Up @@ -245,7 +257,8 @@ pub fn start_for_resume(
) -> Result<Resumed, crate::snapshot::SnapshotError> {
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.",
)
Expand Down
11 changes: 8 additions & 3 deletions rust/crates/psychoscript/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,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),
Expand All @@ -301,6 +302,10 @@ impl Runtime {
"maxValueDepth must be an integer from 1 to {}.",
crate::MAX_VALUE_DEPTH_LIMIT
);
assert!(
limits.max_source_bytes != Some(0),
"max_source_bytes must be at least 1."
);
self.setup.limits = limits;
self
}
Expand Down Expand Up @@ -369,7 +374,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<Compiled, Diagnostic> {
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
Expand Down
12 changes: 8 additions & 4 deletions rust/crates/psychoscript/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -562,8 +562,10 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result<Snapshot, Refusal> {
};
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;
// Deep metadata is saved flat: as plain JSON, it would pass the nesting limit of the JSON reader in `from_bytes`.
let (metadata, metadata_data) = vm.host.run.update_metadata(|m| {
Expand Down Expand Up @@ -1130,8 +1132,8 @@ fn hex_bytes(s: &str) -> R<Vec<u8>> {
/// Each object of a fresh run's base, encoded, to see which ones the run changed.
fn baseline(vm: &Vm, code: &str) -> R<Vec<J>> {
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(),
Expand Down Expand Up @@ -2536,6 +2538,8 @@ pub fn header(snapshot: &Snapshot) -> R<Restored> {
.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),
})
Expand Down
92 changes: 92 additions & 0 deletions rust/crates/psychoscript/tests/source_limit.rs
Original file line number Diff line number Diff line change
@@ -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));
}