From 3346c0d27ef7bc2f56c712e96224ef9d35280e42 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Sat, 28 Nov 2026 23:01:29 +0100 Subject: [PATCH 1/4] feat(rust): expose Run::heap_bytes without the gc-stats feature --- rust/README.md | 2 +- rust/crates/psychoscript/src/heap.rs | 13 +++++ rust/crates/psychoscript/src/program.rs | 3 ++ rust/crates/psychoscript/src/runtime.rs | 21 +++++++++ rust/crates/psychoscript/src/vm.rs | 1 + rust/crates/psychoscript/tests/heap.rs | 63 +++++++++++++++++++++++++ 6 files changed, 102 insertions(+), 1 deletion(-) diff --git a/rust/README.md b/rust/README.md index 181bf8a4..b54a5d4b 100644 --- a/rust/README.md +++ b/rust/README.md @@ -61,7 +61,7 @@ let mesh = HostFunction::new(|_, _| HostValue::TypedArray(TypedArray::from_f32(& Only Rust has: -- A heap cap: [`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`. +- 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. - 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`. - The function marker: [`TranslateFunctions::Mark`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs), giving `HostValue::FunctionMarker` and `Data::FunctionMarker`. diff --git a/rust/crates/psychoscript/src/heap.rs b/rust/crates/psychoscript/src/heap.rs index 6c55afc5..f6fb8529 100644 --- a/rust/crates/psychoscript/src/heap.rs +++ b/rust/crates/psychoscript/src/heap.rs @@ -143,6 +143,18 @@ impl Vm { self.pop(); } + /// The run stopped to wait for the host: measures once if it hasn't measured yet, so a long-lived idle run + /// reports its reachable bytes through [`Run::heap_bytes`](crate::Run::heap_bytes) without paying on later waits. + pub(crate) fn heap_wait(&mut self) { + if self.heap_meter.is_some() + && self.fatal.is_none() + && self.outcome.is_none() + && self.host.run.heap_bytes().is_none() + { + self.heap_measure(); + } + } + /// The run ended: what it leaves reachable, its value among it, is measured once more. pub(crate) fn heap_final(&mut self) { if self.fatal.is_none() && self.heap_meter.is_some() { @@ -153,6 +165,7 @@ impl Vm { /// Measures the heap; over the limit, the run stops at its next check, which no handler sees. fn heap_measure(&mut self) { let bytes = measure(self); + self.host.run.set_heap_bytes(bytes); let Some(m) = self.heap_meter.as_deref_mut() else { return; }; diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index 5826c841..2b86e80e 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -427,6 +427,9 @@ impl<'a> Program<'a> { } if r.vm.heap_meter.is_some() && r.vm.fatal.is_none() && r.vm.outcome.is_none() { r.vm.heap_point(0); + if !r.vm.suspended { + r.vm.heap_wait(); + } } #[cfg(feature = "gc-stats")] r.vm.publish_stats(); diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 9c01e716..b388cb7f 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -1,6 +1,7 @@ //! The runtime a host makes, the counterpart of the reference's `Runtime.make`: the host globals every run gets, its //! modules, limits and translation, and the outcome of a run. +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use crate::host::RunId; @@ -45,10 +46,13 @@ impl Outcome { /// The run a runtime's globals are made for, the reference's `Run`: its id, and metadata its host functions may keep /// across a suspend. A clone is the same run. +const UNMEASURED: u64 = u64::MAX; + #[derive(Clone)] pub struct Run { pub(crate) id: RunId, metadata: Arc>, + heap_bytes: Arc, #[cfg(feature = "gc-stats")] stats: Arc>, } @@ -58,11 +62,28 @@ impl Run { Self { id: Arc::new(id.map(std::sync::OnceLock::from).unwrap_or_default()), metadata: Arc::new(Mutex::new(metadata)), + heap_bytes: Arc::new(AtomicU64::new(UNMEASURED)), #[cfg(feature = "gc-stats")] stats: Arc::default(), } } + /// The last measured reachable bytes of the run's heap, in the size model of + /// [`Limits::max_heap_bytes`](crate::Limits::max_heap_bytes): updated whenever the heap meter measures (at + /// allocation milestones, on the first wait for the host, as the body returns, and when the run ends). `None` + /// before the first measurement or when the run has no `max_heap_bytes`. + pub fn heap_bytes(&self) -> Option { + match self.heap_bytes.load(Ordering::Relaxed) { + UNMEASURED => None, + bytes => Some(bytes), + } + } + + pub(crate) fn set_heap_bytes(&self, bytes: u64) { + self.heap_bytes + .store(bytes.min(UNMEASURED - 1), Ordering::Relaxed); + } + /// The run's heap as of its last stop for the host (`gc-stats` builds only). #[cfg(feature = "gc-stats")] #[doc(hidden)] diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 1ce06bf3..b7b86c1d 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -1931,6 +1931,7 @@ impl Vm { // The reference measures the heap here when that is due, where its driver takes the calls. if self.heap_meter.is_some() && self.fatal.is_none() && self.replay_meter.is_none() { self.heap_point(0); + self.heap_wait(); // Over the limit, the run ends before the calls start, as there. if self.fatal.is_some() { return; diff --git a/rust/crates/psychoscript/tests/heap.rs b/rust/crates/psychoscript/tests/heap.rs index dfc79d31..70833379 100644 --- a/rust/crates/psychoscript/tests/heap.rs +++ b/rust/crates/psychoscript/tests/heap.rs @@ -239,3 +239,66 @@ fn finished_async_functions_dont_pile_up() { assert_eq!(result, Ok(json!(100000)), "{code}"); } } + +#[test] +fn run_heap_bytes_reports_last_measured_reachable_bytes_without_gc_stats() { + use std::sync::{Mutex, OnceLock}; + + let sample_at_tick = |rt: Runtime, code: &str| { + let samples = Arc::new(Mutex::new(Vec::new())); + let seen = samples.clone(); + let rt = rt.globals(move |run| { + let (run, seen) = (run.clone(), seen.clone()); + [( + "tick", + HostFunction::new_async(move |_, _| { + seen.lock().unwrap().push(run.heap_bytes()); + async { Ok(HostValue::Undefined) } + }), + )] + }); + assert!(rt.execute(code).result.is_ok()); + samples.lock().unwrap().clone() + }; + + assert_eq!( + sample_at_tick(Runtime::make(), "await tick(); return 1"), + [None] + ); + + let samples = sample_at_tick( + capped(4 << 20), + "const small = [1, 2, 3]; await tick(); + const big = new Array(200_000).fill(0); + for (let i = 0; i < 4; i++) new Array(40_000).fill(i); + await tick(); return small.length + big.length", + ); + assert!( + matches!(samples[0], Some(b) if b > 0 && b < 100_000), + "{samples:?}" + ); + assert!( + matches!(samples[1], Some(b) if b >= 200_000 * 16), + "{samples:?}" + ); + + // Exact shared size model (16_064 bytes), both under and over the limit. + for (cap, ok) in [(16_064, true), (16_063, false)] { + let handle = Arc::new(OnceLock::new()); + let keep = handle.clone(); + let rt = capped(cap).globals(move |run| { + let _ = keep.set(run.clone()); + Vec::<(&str, HostValue)>::new() + }); + let outcome = rt.execute("Math.kept = new Array(1000); return 1"); + if ok { + assert_eq!(outcome.json().unwrap(), json!(1)); + } else { + assert_eq!( + outcome.result.unwrap_err().kind, + DiagnosticKind::MemoryLimitExceeded + ); + } + assert_eq!(handle.get().unwrap().heap_bytes(), Some(16_064)); + } +} From 851cbc75915f23e2cf56e403f68fffee7344b763 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 15:55:51 +0000 Subject: [PATCH 2/4] fix(rust): review fixes for Run::heap_bytes Attach Run's doc comment to Run again, assert heap_bytes by its bounds instead of an exact size, and say in the README that it measures only with max_heap_bytes. --- rust/README.md | 2 +- rust/crates/psychoscript/src/runtime.rs | 4 ++-- rust/crates/psychoscript/tests/heap.rs | 8 +++++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/rust/README.md b/rust/README.md index ac860ee1..d3470dde 100644 --- a/rust/README.md +++ b/rust/README.md @@ -63,7 +63,7 @@ let mesh = HostFunction::new(|_, _| HostValue::TypedArray(TypedArray::from_f32(& 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. +- 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 measures only when `max_heap_bytes` is set, and is `None` otherwise. - 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`. - 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. diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index f0b103e5..b9bf3404 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -44,10 +44,10 @@ impl Outcome { } } -/// The run a runtime's globals are made for, the reference's `Run`: its id, and metadata its host functions may keep -/// across a suspend. A clone is the same run. const UNMEASURED: u64 = u64::MAX; +/// The run a runtime's globals are made for, the reference's `Run`: its id, and metadata its host functions may keep +/// across a suspend. A clone is the same run. #[derive(Clone)] pub struct Run { pub(crate) id: RunId, diff --git a/rust/crates/psychoscript/tests/heap.rs b/rust/crates/psychoscript/tests/heap.rs index 70833379..ceaea0f8 100644 --- a/rust/crates/psychoscript/tests/heap.rs +++ b/rust/crates/psychoscript/tests/heap.rs @@ -282,8 +282,8 @@ fn run_heap_bytes_reports_last_measured_reachable_bytes_without_gc_stats() { "{samples:?}" ); - // Exact shared size model (16_064 bytes), both under and over the limit. - for (cap, ok) in [(16_064, true), (16_063, false)] { + // Recorded both under and over the limit. + for (cap, ok) in [(1 << 20, true), (4096, false)] { let handle = Arc::new(OnceLock::new()); let keep = handle.clone(); let rt = capped(cap).globals(move |run| { @@ -291,14 +291,16 @@ fn run_heap_bytes_reports_last_measured_reachable_bytes_without_gc_stats() { Vec::<(&str, HostValue)>::new() }); let outcome = rt.execute("Math.kept = new Array(1000); return 1"); + let bytes = handle.get().unwrap().heap_bytes(); if ok { assert_eq!(outcome.json().unwrap(), json!(1)); + assert!(matches!(bytes, Some(b) if b > 0 && b <= cap), "{bytes:?}"); } else { assert_eq!( outcome.result.unwrap_err().kind, DiagnosticKind::MemoryLimitExceeded ); + assert!(matches!(bytes, Some(b) if b > cap), "{bytes:?}"); } - assert_eq!(handle.get().unwrap().heap_bytes(), Some(16_064)); } } From 69c5612e65940279926d4aa0a8aaa70062491076 Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 16:29:23 +0000 Subject: [PATCH 3/4] feat(rust): Runtime::measure_heap keeps Run::heap_bytes current without a heap limit The heap meter now runs with a limit, with measure_heap, or both: a limit keeps its own schedule and check, and measure_heap measures at the run's waits for the host once it allocated a sixteenth of what it last reached. A limit alone no longer measures at the first wait. --- rust/README.md | 2 +- rust/crates/psychoscript/src/collector.rs | 2 +- rust/crates/psychoscript/src/heap.rs | 73 ++++++++++++++++------ rust/crates/psychoscript/src/run.rs | 4 +- rust/crates/psychoscript/src/runtime.rs | 17 ++++- rust/crates/psychoscript/src/vm.rs | 4 +- rust/crates/psychoscript/tests/heap.rs | 42 ++++++++----- rust/crates/psychoscript/tests/snapshot.rs | 44 +++++++++++++ 8 files changed, 145 insertions(+), 43 deletions(-) diff --git a/rust/README.md b/rust/README.md index d3470dde..7a28fb7f 100644 --- a/rust/README.md +++ b/rust/README.md @@ -63,7 +63,7 @@ let mesh = HostFunction::new(|_, _| HostValue::TypedArray(TypedArray::from_f32(& 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 measures only when `max_heap_bytes` is set, and is `None` otherwise. +- 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`. - 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`. - 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. diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index ca606c66..b2e8f75b 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1618,7 +1618,7 @@ mod tests { let mut vm = Vm::new(RunHost::bare(), limits, Strings::fresh()); vm.setup(); vm.snapshot_base = Base::of(&vm); - vm.start_heap_meter(false); + vm.start_heap_meter(false, false); let base_len = vm.heap.len(); // Repeated transient spikes followed by full GC + truncation stay under the heap cap. diff --git a/rust/crates/psychoscript/src/heap.rs b/rust/crates/psychoscript/src/heap.rs index 0238912f..c7fe4aee 100644 --- a/rust/crates/psychoscript/src/heap.rs +++ b/rust/crates/psychoscript/src/heap.rs @@ -38,9 +38,11 @@ pub(crate) const STRING_BYTES: u64 = 16; /// What a unit of fuel is assumed to allocate, for growth nothing else counts (`push`, a property added). pub(crate) const FUEL_BYTES: u64 = 2; -/// One run's pacing of measurements against its limit. +/// One run's pacing of measurements against its limit, or at its waits for the host when it has none. pub(crate) struct HeapMeter { - pub(crate) limit: u64, + pub(crate) limit: Option, + /// Measures at the run's waits for the host too ([`Runtime::measure_heap`](crate::Runtime::measure_heap)). + waits: bool, /// Roughly what the run allocated since the last measurement. pub(crate) debt: u64, /// The last measurement, or `None` before the first one of a restored run. @@ -52,9 +54,21 @@ pub(crate) struct HeapMeter { impl HeapMeter { fn due(&self) -> bool { + let Some(limit) = self.limit else { + return false; + }; + match self.live { + None => true, + Some(live) => self.debt >= limit.saturating_sub(live).max(limit / 16), + } + } + + /// At a wait for the host: once the run allocated a sixteenth of what it last reached, the pacing of a limit's + /// last stretch. + fn due_at_wait(&self) -> bool { match self.live { None => true, - Some(live) => self.debt >= self.limit.saturating_sub(live).max(self.limit / 16), + Some(live) => self.debt > 0 && self.debt >= live / 16, } } @@ -67,12 +81,14 @@ impl HeapMeter { } impl Vm { - /// Starts pacing measurements once the run is set up, if it has a heap limit; a restored run measures at its - /// first safe point. - pub(crate) fn start_heap_meter(&mut self, restored: bool) { - self.heap_meter = self.limits.max_heap_bytes.map(|limit| { + /// Starts pacing measurements once the run is set up, if it has a heap limit or measures at its waits; a restored + /// run measures at its first safe point under a limit, else at its first wait. + pub(crate) fn start_heap_meter(&mut self, restored: bool, waits: bool) { + let limit = self.limits.max_heap_bytes; + self.heap_meter = (limit.is_some() || waits).then(|| { Box::new(HeapMeter { limit, + waits, debt: 0, live: if restored { None } else { Some(0) }, objects: self.heap.len(), @@ -81,7 +97,7 @@ impl Vm { }); } - /// Runs `setup`, a lazy group's, noting the objects it makes as built-ins when the run has a heap limit. + /// Runs `setup`, a lazy group's, noting the objects it makes as built-ins when the run has a heap meter. pub(crate) fn making_builtins(&mut self, setup: fn(&mut Vm)) { if self.heap_meter.is_none() { return setup(self); @@ -142,7 +158,7 @@ impl Vm { /// `v` among them, as they are as it ends. #[cold] pub(crate) fn heap_body_end(&mut self, v: Value) { - if self.fatal.is_some() { + if self.fatal.is_some() || !self.heap_limited() { return; } self.heap_charge(0); @@ -151,25 +167,41 @@ impl Vm { self.pop(); } - /// The run stopped to wait for the host: measures once if it hasn't measured yet, so a long-lived idle run - /// reports its reachable bytes through [`Run::heap_bytes`](crate::Run::heap_bytes) without paying on later waits. + /// The run stopped to wait for the host: with [`Runtime::measure_heap`](crate::Runtime::measure_heap), measures + /// when it allocated enough since the last measurement, so [`Run::heap_bytes`](crate::Run::heap_bytes) stays + /// current for an idle run. + #[cold] pub(crate) fn heap_wait(&mut self) { - if self.heap_meter.is_some() - && self.fatal.is_none() - && self.outcome.is_none() - && self.host.run.heap_bytes().is_none() + if self.fatal.is_some() + || self.outcome.is_some() + || self.replay_meter.is_some() + || !self.heap_meter.as_deref().is_some_and(|m| m.waits) + { + return; + } + self.heap_charge(0); + if self + .heap_meter + .as_deref() + .is_some_and(HeapMeter::due_at_wait) { self.heap_measure(); } } - /// The run ended: what it leaves reachable, its value among it, is measured once more. + /// The run ended: what it leaves reachable, its value among it, is measured once more against the limit. pub(crate) fn heap_final(&mut self) { - if self.fatal.is_none() && self.heap_meter.is_some() { + if self.fatal.is_none() && self.heap_limited() { self.heap_measure(); } } + fn heap_limited(&self) -> bool { + self.heap_meter + .as_deref() + .is_some_and(|m| m.limit.is_some()) + } + /// Measures the heap; over the limit, the run stops at its next check, which no handler sees. fn heap_measure(&mut self) { let bytes = measure(self); @@ -179,10 +211,13 @@ impl Vm { }; m.live = Some(bytes); m.debt = 0; - if bytes <= m.limit || self.fatal.is_some() { + let Some(limit) = m.limit else { + return; + }; + if bytes <= limit || self.fatal.is_some() { return; } - let message = format!("Execution exceeded its memory limit of {} bytes.", m.limit); + let message = format!("Execution exceeded its memory limit of {limit} bytes."); self.fatal = Some((DiagnosticKind::MemoryLimitExceeded, message)); self.stop_soon(); } diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index 7e8ccb02..466648b7 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -216,7 +216,7 @@ pub fn start( host::install(&mut vm, &program.globals); vm.load_bigints(&mut program); vm.snapshot_base = crate::snapshot::Base::of(&vm); - vm.start_heap_meter(false); + vm.start_heap_meter(false, setup.measure_heap); for (k, v) in &options.bindings { // Host globals of the same name win, as in the reference. if k.as_str().is_some_and(|k| host::has_host_global(&vm, k)) { @@ -267,7 +267,7 @@ pub fn start_for_resume( host::install(&mut vm, &program.globals); vm.load_bigints(&mut program); vm.snapshot_base = crate::snapshot::Base::of(&vm); - vm.start_heap_meter(true); + vm.start_heap_meter(true, setup.measure_heap); let code: Arc = Arc::from(code); vm.code = code.clone(); vm.program = setup.program_lines.map(|lines| program_range(&code, lines)); diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index b9bf3404..07a02bf6 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -69,9 +69,10 @@ impl Run { } /// The last measured reachable bytes of the run's heap, in the size model of - /// [`Limits::max_heap_bytes`](crate::Limits::max_heap_bytes): updated whenever the heap meter measures (at - /// allocation milestones, on the first wait for the host, as the body returns, and when the run ends). `None` - /// before the first measurement or when the run has no `max_heap_bytes`. + /// [`Limits::max_heap_bytes`](crate::Limits::max_heap_bytes): updated whenever the heap meter measures (under the + /// limit at allocation milestones, as the body returns, and when the run ends; with + /// [`Runtime::measure_heap`](crate::Runtime::measure_heap) at waits for the host). `None` before the first + /// measurement, or when the run has neither. pub fn heap_bytes(&self) -> Option { match self.heap_bytes.load(Ordering::Relaxed) { UNMEASURED => None, @@ -206,6 +207,7 @@ pub(crate) struct Setup { pub translate: Translate, pub program_lines: Option<(u32, u32)>, pub locale: Option>, + pub measure_heap: bool, } impl Setup { @@ -305,6 +307,15 @@ impl Runtime { self } + /// Measures each run's reachable heap at its waits for the host, once it has allocated a sixteenth of what it last + /// reached, so [`Run::heap_bytes`] stays current for an idle run without + /// [`Limits::max_heap_bytes`](crate::Limits::max_heap_bytes). Off by default; a limit's own measurements are the + /// same either way. + pub fn measure_heap(mut self, on: bool) -> Self { + self.setup.measure_heap = on; + self + } + /// What formats dates and numbers and compares strings for the locale-sensitive built-ins, instead of the default /// ([`IcuLocale`](crate::locale::IcuLocale) with the `locale` feature, else /// [`FallbackLocale`](crate::locale::FallbackLocale)); see [`LocaleProvider`](crate::locale::LocaleProvider). diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 70d55a3e..16fa0b22 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -1934,7 +1934,6 @@ impl Vm { // The reference measures the heap here when that is due, where its driver takes the calls. if self.heap_meter.is_some() && self.fatal.is_none() && self.replay_meter.is_none() { self.heap_point(0); - self.heap_wait(); // Over the limit, the run ends before the calls start, as there. if self.fatal.is_some() { return; @@ -4871,6 +4870,9 @@ impl Vm { } // Nothing left to run: the reference's driver stops, starting the host calls queued so far. if !self.host.queued.is_empty() { + if self.heap_meter.is_some() { + self.heap_wait(); + } self.handover(); continue; } diff --git a/rust/crates/psychoscript/tests/heap.rs b/rust/crates/psychoscript/tests/heap.rs index ceaea0f8..a4da3153 100644 --- a/rust/crates/psychoscript/tests/heap.rs +++ b/rust/crates/psychoscript/tests/heap.rs @@ -266,23 +266,26 @@ fn run_heap_bytes_reports_last_measured_reachable_bytes_without_gc_stats() { [None] ); - let samples = sample_at_tick( - capped(4 << 20), - "const small = [1, 2, 3]; await tick(); - const big = new Array(200_000).fill(0); - for (let i = 0; i < 4; i++) new Array(40_000).fill(i); - await tick(); return small.length + big.length", - ); - assert!( - matches!(samples[0], Some(b) if b > 0 && b < 100_000), - "{samples:?}" - ); - assert!( - matches!(samples[1], Some(b) if b >= 200_000 * 16), - "{samples:?}" - ); + // `measure_heap` measures at the waits, without a limit or under one too large to be due. + for rt in [Runtime::make(), capped(1 << 40)] { + let samples = sample_at_tick( + rt.measure_heap(true), + "const small = [1, 2, 3]; await tick(); + const big = new Array(200_000).fill(0); + for (let i = 0; i < 4; i++) new Array(40_000).fill(i); + await tick(); return small.length + big.length", + ); + assert!( + matches!(samples[0], Some(b) if b > 0 && b < 100_000), + "{samples:?}" + ); + assert!( + matches!((samples[0], samples[1]), (Some(a), Some(b)) if b > a), + "{samples:?}" + ); + } - // Recorded both under and over the limit. + // A limit alone reports what it measures, both under and over it. for (cap, ok) in [(1 << 20, true), (4096, false)] { let handle = Arc::new(OnceLock::new()); let keep = handle.clone(); @@ -304,3 +307,10 @@ fn run_heap_bytes_reports_last_measured_reachable_bytes_without_gc_stats() { } } } + +#[test] +fn run_heap_bytes_in_the_round_trip_mode() { + support::in_round_trip_mode( + "run_heap_bytes_reports_last_measured_reachable_bytes_without_gc_stats", + ); +} diff --git a/rust/crates/psychoscript/tests/snapshot.rs b/rust/crates/psychoscript/tests/snapshot.rs index c8430c1e..b4eeb3ce 100644 --- a/rust/crates/psychoscript/tests/snapshot.rs +++ b/rust/crates/psychoscript/tests/snapshot.rs @@ -1077,3 +1077,47 @@ fn a_suspend_fails_when_an_encode_hook_fails_and_the_run_goes_on() { ); assert_eq!(done(outcome).result.unwrap(), json!(1)); } + +#[test] +fn a_run_measuring_its_heap_measures_again_at_its_first_wait_once_resumed() { + fn measuring(gate: Option<&Gate>) -> Runtime { + let gate = gate.cloned(); + Runtime::make().measure_heap(true).globals(move |run| { + let run = run.clone(); + let heap = HostFunction::new(move |_, _| { + run.heap_bytes() + .map_or(HostValue::Null, |b| HostValue::Number(b as f64)) + }); + [ + ("step", step(gate.as_ref())), + ("held", held(gate.as_ref())), + ("heap", heap), + ] + }) + } + let code = format!( + r#"const kept = new Array(1000).fill(0) + await step(1) + const before = heap() + await step(1) + {BUSY} + const mid = heap() + await step(1) + return [before > 0, mid, heap() > 0, kept.length]"# + ); + let gate = Gate::default(); + let rt = measuring(Some(&gate)); + let (outcome, _) = background(rt.program(&code, &ProgramOptions::new()), |s| { + gate.entered(2); + suspend_soon(&s, &gate, None) + }); + let state = suspended(outcome).state; + let o = done( + measuring(None) + .resume(&state) + .unwrap() + .run_resumable() + .unwrap(), + ); + assert_eq!(o.result.unwrap(), json!([true, null, true, 1000])); +} From 559f929ca4ea60e58c09ea8d675f6b9f1f63016d Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 17:12:37 +0000 Subject: [PATCH 4/4] fix(rust): record lazy built-ins without a heap meter, for a state that resumes with one A state saved without measure_heap or a limit and resumed with measure_heap counted the lazy groups set up before the suspend as program bytes. --- rust/README.md | 2 +- rust/crates/psychoscript/src/heap.rs | 6 +- rust/crates/psychoscript/tests/snapshot.rs | 67 +++++++++++++++++----- 3 files changed, 55 insertions(+), 20 deletions(-) diff --git a/rust/README.md b/rust/README.md index 7a28fb7f..1238c06f 100644 --- a/rust/README.md +++ b/rust/README.md @@ -63,7 +63,7 @@ let mesh = HostFunction::new(|_, _| HostValue::TypedArray(TypedArray::from_f32(& 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 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`. - 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. diff --git a/rust/crates/psychoscript/src/heap.rs b/rust/crates/psychoscript/src/heap.rs index c7fe4aee..f675ca66 100644 --- a/rust/crates/psychoscript/src/heap.rs +++ b/rust/crates/psychoscript/src/heap.rs @@ -97,11 +97,9 @@ impl Vm { }); } - /// Runs `setup`, a lazy group's, noting the objects it makes as built-ins when the run has a heap meter. + /// Runs `setup`, a lazy group's, noting the objects it makes as built-ins, meter or not: a state saved without one + /// may resume with one. pub(crate) fn making_builtins(&mut self, setup: fn(&mut Vm)) { - if self.heap_meter.is_none() { - return setup(self); - } let len = self.heap.len(); let outer = self.gc.record_made(); setup(self); diff --git a/rust/crates/psychoscript/tests/snapshot.rs b/rust/crates/psychoscript/tests/snapshot.rs index b4eeb3ce..8fd89dc2 100644 --- a/rust/crates/psychoscript/tests/snapshot.rs +++ b/rust/crates/psychoscript/tests/snapshot.rs @@ -1078,23 +1078,26 @@ fn a_suspend_fails_when_an_encode_hook_fails_and_the_run_goes_on() { assert_eq!(done(outcome).result.unwrap(), json!(1)); } +/// A runtime with `step`, `held` and `heap()`, the run's [`Run::heap_bytes`](psychoscript::Run::heap_bytes), measuring +/// it at its waits. +fn measuring(gate: Option<&Gate>) -> Runtime { + let gate = gate.cloned(); + Runtime::make().measure_heap(true).globals(move |run| { + let run = run.clone(); + let heap = HostFunction::new(move |_, _| { + run.heap_bytes() + .map_or(HostValue::Null, |b| HostValue::Number(b as f64)) + }); + [ + ("step", step(gate.as_ref())), + ("held", held(gate.as_ref())), + ("heap", heap), + ] + }) +} + #[test] fn a_run_measuring_its_heap_measures_again_at_its_first_wait_once_resumed() { - fn measuring(gate: Option<&Gate>) -> Runtime { - let gate = gate.cloned(); - Runtime::make().measure_heap(true).globals(move |run| { - let run = run.clone(); - let heap = HostFunction::new(move |_, _| { - run.heap_bytes() - .map_or(HostValue::Null, |b| HostValue::Number(b as f64)) - }); - [ - ("step", step(gate.as_ref())), - ("held", held(gate.as_ref())), - ("heap", heap), - ] - }) - } let code = format!( r#"const kept = new Array(1000).fill(0) await step(1) @@ -1121,3 +1124,37 @@ fn a_run_measuring_its_heap_measures_again_at_its_first_wait_once_resumed() { ); assert_eq!(o.result.unwrap(), json!([true, null, true, 1000])); } + +#[test] +fn a_state_saved_without_measuring_measures_as_a_run_that_measured_throughout() { + // The regular expression literal sets up its lazy group as the run goes; `pad` makes the last wait measure. + let code = format!( + r#"await step(1) + const m = /a+/.exec("caaab")[0] + await step(1) + {BUSY} + const pad = new Array(100000).fill(0) + await step(1) + return [heap(), m, pad.length]"# + ); + let throughout = measuring(None).execute(&code).json().unwrap(); + let gate = Gate::default(); + let rt = measuring(Some(&gate)).measure_heap(false); + let (outcome, _) = background(rt.program(&code, &ProgramOptions::new()), |s| { + gate.entered(2); + suspend_soon(&s, &gate, None) + }); + let state = suspended(outcome).state; + let resumed = done( + measuring(None) + .resume(&state) + .unwrap() + .run_resumable() + .unwrap(), + ); + assert_eq!(resumed.json().unwrap(), throughout); + assert!( + throughout[0].as_u64().is_some_and(|b| b > 0), + "{throughout}" + ); +}