From 2d7ad26924f1249ef9d80568066a6e06a5d71937 Mon Sep 17 00:00:00 2001 From: Daniel Peter Date: Fri, 27 Nov 2026 19:43:00 +0100 Subject: [PATCH] fix(rust): count each live string allocation and heap BigInt toward max_heap_bytes --- .../psychoscript/src/builtins/bigint.rs | 15 ++++++++++ rust/crates/psychoscript/src/heap.rs | 22 +++++++------- rust/crates/psychoscript/tests/heap.rs | 29 +++++++++++++++++++ 3 files changed, 55 insertions(+), 11 deletions(-) diff --git a/rust/crates/psychoscript/src/builtins/bigint.rs b/rust/crates/psychoscript/src/builtins/bigint.rs index 82eb9df..c261c0d 100644 --- a/rust/crates/psychoscript/src/builtins/bigint.rs +++ b/rust/crates/psychoscript/src/builtins/bigint.rs @@ -100,6 +100,14 @@ impl BigNum { BigRef::Large(n) => n.clone(), } } + + /// The bytes this heap integer holds (16 for inline 128-bit `Small`, rounded-up bit length for `Large`). + pub(crate) fn byte_len(&self) -> u64 { + match self { + BigNum::Small(_) => 16, + BigNum::Large(n) => n.bits().div_ceil(8), + } + } } /// A BigInt's integer, read without copying it. @@ -203,7 +211,14 @@ impl Vm { self.gc_shade_big(id); return Value::Big(id); } + let extra = match n.get() { + BigRef::Small(_) => 0, + BigRef::Large(b) => b.bits().div_ceil(8), + }; let id = self.alloc(Obj::new(None, Kind::BigInt(n))); + if extra > 0 { + self.charge_heap(extra); + } self.bigints.add(h, id); Value::Big(id) } diff --git a/rust/crates/psychoscript/src/heap.rs b/rust/crates/psychoscript/src/heap.rs index 6c55afc..cb33339 100644 --- a/rust/crates/psychoscript/src/heap.rs +++ b/rust/crates/psychoscript/src/heap.rs @@ -9,8 +9,12 @@ //! - A typed array's storage: one per byte, once for every view and `ArrayBuffer` that shares it. //! - What the fresh runtime made (built-ins, host globals, and the lazy groups of built-ins it sets up later) counts //! nothing, though the objects the program stored on it do. -//! - A string value: `STRING_BYTES` plus two per UTF-16 code unit, once per distinct text. Property keys count as part -//! of their property, an error's `stack` text as part of the error, and a built-in's own texts nothing. +//! - A string value: `STRING_BYTES` plus two per UTF-16 code unit, once per distinct live string allocation (`StrId`). +//! Shared references to the same string count once, while separately allocated identical strings each count their own +//! buffer. Property keys count as part of their property, an error's `stack` text as part of the error, and a +//! built-in's own texts nothing. +//! - A heap `BigInt` (`BigNum::Small` or `BigNum::Large`): `BIGINT_BYTES` plus its byte length (16 bytes for `Small`, +//! `bits().div_ceil(8)` for `Large`), once per distinct interned value; inline `BigInt`s in `Value` count nothing. //! //! Measuring walks the reachable heap (`reach.rs`), so it is paced by allocation: the run counts roughly what it //! allocated since the last measurement (objects and strings made, what concatenations copy, array contents, elements @@ -19,8 +23,6 @@ //! still live) and when the run ends. Over the limit, the run stops with `MemoryLimitExceeded`. When the //! measurements between the first and the last fall differs from the reference's; what each one finds is the same. -use rustc_hash::FxHashSet; - use crate::DiagnosticKind; use std::sync::Arc; @@ -35,6 +37,7 @@ pub(crate) const PROPERTY_BYTES: u64 = 32; pub(crate) const ELEMENT_BYTES: u64 = 16; pub(crate) const ENTRY_BYTES: u64 = 32; pub(crate) const STRING_BYTES: u64 = 16; +pub(crate) const BIGINT_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; @@ -174,7 +177,6 @@ pub(crate) fn measure(vm: &Vm) -> u64 { objects: vec![false; vm.heap.len()], cells: vec![false; vm.cells.len()], strings: vec![false; vm.atoms.bufs.len()], - texts: FxHashSet::default(), work: Vec::new(), bytes: 0, }; @@ -241,8 +243,9 @@ fn object_bytes(vm: &Vm, o: &Obj) -> u64 { let own = OBJECT_BYTES + PROPERTY_BYTES * props as u64; match &o.kind { // An accessor's own object is part of its property; a buffer's storage counts as its bytes. - // A BigInt counts nothing, as the reference counts its primitives. - Kind::Accessor(_) | Kind::Storage(_) | Kind::BigInt(_) => 0, + Kind::Accessor(_) | Kind::Storage(_) => 0, + // Heap BigInts are interned, so each distinct value counts once (inline BigInts never reach here). + Kind::BigInt(n) => BIGINT_BYTES + n.byte_len(), // The program's body, which the reference runs with no function object. Kind::Closure(c) if vm.protos.first().is_some_and(|p| Arc::ptr_eq(p, &c.proto)) => 0, Kind::Array(items) | Kind::Arguments(items) => own + ELEMENT_BYTES * items.len() as u64, @@ -259,7 +262,6 @@ struct Walk<'v> { objects: Vec, cells: Vec, strings: Vec, - texts: FxHashSet<(&'v str, Option<&'v [u16]>)>, work: Vec, bytes: u64, } @@ -304,8 +306,6 @@ impl Walk<'_> { } self.strings[i] = true; let r = self.vm.atoms.sref(s); - if self.texts.insert((r.s, r.units)) { - self.bytes += STRING_BYTES + 2 * r.len16() as u64; - } + self.bytes += STRING_BYTES + 2 * r.len16() as u64; } } diff --git a/rust/crates/psychoscript/tests/heap.rs b/rust/crates/psychoscript/tests/heap.rs index dfc79d3..0e157db 100644 --- a/rust/crates/psychoscript/tests/heap.rs +++ b/rust/crates/psychoscript/tests/heap.rs @@ -239,3 +239,32 @@ fn finished_async_functions_dont_pile_up() { assert_eq!(result, Ok(json!(100000)), "{code}"); } } + +#[test] +fn duplicate_fresh_strings_count_each_allocation() { + // Separately allocated identical strings each hold their own buffer in the string arena and must not bypass + // `max_heap_bytes` (whereas shared references to the same string still count once, tested above). + let rt = capped(2 * 1024 * 1024); + let code = "const a = []; for (let i = 0; i < 10_000; i++) a.push('x'.repeat(10_000)); return a.length"; + assert_eq!(kind(&rt, code), DiagnosticKind::MemoryLimitExceeded); +} + +#[test] +fn large_bigints_count_toward_the_heap_limit() { + // Distinct large BigInts (~125 KB each) must trip `max_heap_bytes`. + let rt = capped(2 * 1024 * 1024); + let over = "const base = 1n << 1_000_000n; const a = []; for (let i = 0; i < 100; i++) a.push(base + BigInt(i)); return a.length"; + assert_eq!(kind(&rt, over), DiagnosticKind::MemoryLimitExceeded); + + // Shared references to the same interned BigInt count once. + let shared = + "const big = 1n << 1_000_000n; const a = new Array(1000).fill(big); return a.length"; + assert_eq!( + capped(256 * 1024).execute(shared).result.unwrap(), + json!(1000) + ); + + // Unreachable large BigInts are collected and do not trip the limit. + let churn = "let x = 0n; const base = 1n << 500_000n; for (let i = 0; i < 200; i++) x = base + BigInt(i); return x > 0n"; + assert_eq!(rt.execute(churn).result.unwrap(), json!(true)); +}