Skip to content
2 changes: 1 addition & 1 deletion rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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 @@ -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.
Expand Down
78 changes: 62 additions & 16 deletions rust/crates/psychoscript/src/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64>,
/// 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.
Expand All @@ -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,
}
}

Expand All @@ -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(),
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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();
}
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/psychoscript/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/psychoscript/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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<str> = Arc::from(code);
vm.code = code.clone();
vm.program = setup.program_lines.map(|lines| program_range(&code, lines));
Expand Down
32 changes: 32 additions & 0 deletions rust/crates/psychoscript/src/runtime.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<Mutex<Kept>>,
heap_bytes: Arc<AtomicU64>,
#[cfg(feature = "gc-stats")]
stats: Arc<Mutex<crate::HeapStats>>,
}
Expand All @@ -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<u64> {
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)]
Expand Down Expand Up @@ -199,6 +221,7 @@ pub(crate) struct Setup {
pub translate: Translate,
pub program_lines: Option<(u32, u32)>,
pub locale: Option<Arc<dyn crate::locale::LocaleProvider>>,
pub measure_heap: bool,
}

impl Setup {
Expand Down Expand Up @@ -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).
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/psychoscript/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
75 changes: 75 additions & 0 deletions rust/crates/psychoscript/tests/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
);
}
Loading