diff --git a/rust/README.md b/rust/README.md index b0cca7c6..75fd8989 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: [`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. 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/collector.rs b/rust/crates/psychoscript/src/collector.rs index ed24cd17..079ba9f5 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1622,7 +1622,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 409f96d6..f675ca66 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,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 limit. + /// 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); @@ -142,7 +156,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 +165,57 @@ impl Vm { self.pop(); } - /// The run ended: what it leaves reachable, its value among it, is measured once more. + /// 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.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 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); + self.host.run.set_heap_bytes(bytes); let Some(m) = self.heap_meter.as_deref_mut() else { return; }; 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/program.rs b/rust/crates/psychoscript/src/program.rs index 9ca51fb9..d99f8341 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -439,6 +439,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/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 27ce63ed..2fe93056 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::data::Kept; @@ -57,12 +58,15 @@ impl Outcome { } } +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, metadata: Arc>, + heap_bytes: Arc, #[cfg(feature = "gc-stats")] stats: Arc>, } @@ -72,11 +76,29 @@ impl Run { Self { id: Arc::new(id.map(std::sync::OnceLock::from).unwrap_or_default()), metadata: Arc::new(Mutex::new(Kept(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 (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, + 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)] @@ -199,6 +221,7 @@ pub(crate) struct Setup { pub translate: Translate, pub program_lines: Option<(u32, u32)>, pub locale: Option>, + pub measure_heap: bool, } impl Setup { @@ -298,6 +321,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 b6b92c91..94a05e47 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -4940,6 +4940,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 dfc79d31..a4da3153 100644 --- a/rust/crates/psychoscript/tests/heap.rs +++ b/rust/crates/psychoscript/tests/heap.rs @@ -239,3 +239,78 @@ 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] + ); + + // `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:?}" + ); + } + + // 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(); + 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"); + 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:?}"); + } + } +} + +#[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..8fd89dc2 100644 --- a/rust/crates/psychoscript/tests/snapshot.rs +++ b/rust/crates/psychoscript/tests/snapshot.rs @@ -1077,3 +1077,84 @@ 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() { + 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])); +} + +#[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}" + ); +}