Skip to content
Closed
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
15 changes: 15 additions & 0 deletions rust/crates/psychoscript/src/builtins/bigint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
}
Expand Down
22 changes: 11 additions & 11 deletions rust/crates/psychoscript/src/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;

Expand All @@ -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;

Expand Down Expand Up @@ -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,
};
Expand Down Expand Up @@ -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,
Expand All @@ -259,7 +262,6 @@ struct Walk<'v> {
objects: Vec<bool>,
cells: Vec<bool>,
strings: Vec<bool>,
texts: FxHashSet<(&'v str, Option<&'v [u16]>)>,
work: Vec<Id>,
bytes: u64,
}
Expand Down Expand Up @@ -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;
}
}
29 changes: 29 additions & 0 deletions rust/crates/psychoscript/tests/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}