From 845bfe7b44cd447bfff2f58fbd762cac333ba3f5 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:38:47 +1000 Subject: [PATCH 1/2] feat(rust): add LiveSession and zero-copy HostCtx primitives Adds a single-thread, `#![deny(unsafe_code)]` `LiveSession` alongside zero-copy `HostCtx` inspection and mutation primitives so UI/game/app embedders can drive high-frequency Rust-to-JS calls without JS trampoline overhead while leaving durable `Session` and `Vm: Send` untouched. - `Runtime::live_session` & `LiveSession`: direct `enter` closures (no `'static` bound, no JS `Promise.try` wrapper) with per-entry limit resets, microtask draining, idle/incremental/full GC (`gc_step`, `collect_garbage`), live `heap_bytes()`, `eval_compiled`/`eval_module`, `unroot`, and typed thread-local host state (`set_data`/`with_data`). - GC-safe `Root` (`(live_id, slot, generation)` with SATB write barrier and post-mark doomed-slot rejection) and GC-reclaimed single-thread `HostCtx::local_fn` closures stored in `thread_local! LIVE_STORES`. - Zero-copy `HostCtx` primitives usable in both `Session` and `LiveSession`: `is_frozen`, ABA-safe `object_id`, `new_bytes`, `get_global`, `set_global`, `for_each_own`, `is_fatal`, `format_val`. --- rust/crates/psychoscript/src/collector.rs | 148 ++- rust/crates/psychoscript/src/host.rs | 37 +- rust/crates/psychoscript/src/lib.rs | 2 + rust/crates/psychoscript/src/live_session.rs | 649 +++++++++++++ rust/crates/psychoscript/src/program.rs | 19 + rust/crates/psychoscript/src/reach.rs | 3 + rust/crates/psychoscript/src/run.rs | 2 +- rust/crates/psychoscript/src/runtime.rs | 11 + rust/crates/psychoscript/src/session.rs | 371 +++++++- rust/crates/psychoscript/src/snapshot.rs | 3 +- rust/crates/psychoscript/src/vm.rs | 77 ++ .../crates/psychoscript/tests/live_session.rs | 897 ++++++++++++++++++ 12 files changed, 2210 insertions(+), 9 deletions(-) create mode 100644 rust/crates/psychoscript/src/live_session.rs create mode 100644 rust/crates/psychoscript/tests/live_session.rs diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index 1e9be79d..fbb4cfcd 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1401,6 +1401,109 @@ impl Vm { } } + /// Whether `v` refers to a heap object or string that is already freed or doomed to be swept + /// by the current GC cycle (white in `SweepWeak`, or white ahead of the sweep cursor in + /// `Sweep`). Live slots behind the sweep cursor (already reset to `WHITE`) or allocated past + /// the sweep end are NOT doomed. + pub(crate) fn gc_is_doomed(&self, v: Value) -> bool { + match v { + Value::Big(id) if !crate::builtins::bigint::on_heap(id) => false, + Value::Obj(id) | Value::Big(id) => { + let i = id as usize; + if i >= self.heap.len() { + return true; + } + let Some(&c) = self.heap.marks.color.get(i) else { + return false; + }; + if c == FREE { + return true; + } + if c != WHITE { + return false; + } + match self.gc.phase { + Phase::Idle => false, + Phase::Mark => !self.heap.marking && i >= self.snapshot_base.heap, + Phase::Sweep => i >= self.gc.obj_sweep.0 && i < self.gc.obj_sweep.1, + } + } + Value::Str(s) => { + let i = s as usize; + if i >= self.atoms.bufs.len() { + return true; + } + let Some(&c) = self.atoms.gc.color.get(i) else { + return false; + }; + if c == FREE { + return true; + } + if c != WHITE { + return false; + } + match self.atoms.gc.phase { + Phase::Idle => false, + Phase::Mark => !self.heap.marking && i >= self.snapshot_base.bufs, + Phase::Sweep => i >= self.atoms.gc.sweep.0 && i < self.atoms.gc.sweep.1, + } + } + _ => false, + } + } + + /// Runs one bounded incremental GC step when a cycle is running or due and the VM is not busy. + pub(crate) fn gc_step_bounded(&mut self) { + let busy = self.replay_meter.is_some() + || !self.replay.is_empty() + || self.convert_req.is_some() + || self.json_walk != 0; + if busy { + return; + } + if self.gc.phase == Phase::Idle && !self.gc.requested && self.gc_used() < self.gc.trigger { + return; + } + self.gc.requested = false; + self.gc.debt = self.gc.debt.max(STEP); + self.gc_step(); + if !self.gc.requested && self.gc.owns_suspend { + self.gc.owns_suspend = false; + self.suspend_wanted = false; + } + } + + /// Finishes any in-progress GC cycle and runs one complete + /// `Idle -> Mark -> SweepWeak -> Sweep -> Trim -> Idle` cycle, when the VM is not busy. + pub(crate) fn gc_collect_full(&mut self) { + let busy = self.replay_meter.is_some() + || !self.replay.is_empty() + || self.convert_req.is_some() + || self.json_walk != 0; + if busy { + return; + } + if self.gc.phase != Phase::Idle { + self.gc_finish_cycle(); + } + self.gc_finish_cycle(); + } + + fn gc_finish_cycle(&mut self) { + loop { + self.gc.debt = MAX_WORK; + self.gc_step(); + if self.gc.phase == Phase::Idle { + break; + } + } + self.gc.requested = false; + if self.gc.owns_suspend { + self.gc.owns_suspend = false; + self.suspend_wanted = false; + } + } + /// Whether a step is due, for the host stop. pub(crate) fn gc_pending(&self) -> bool { self.gc.requested @@ -1537,13 +1640,51 @@ impl Vm { self.atoms.gc.atom_sweep.0 = at; let (mut at, end) = self.gc.obj_sweep; let freed_objs = self.gc.free.len(); + let mut reclaimed_locals: Vec<(u64, u32, u32)> = Vec::new(); while at < end && work < budget { work += 1; match self.heap.marks.color[at] { WHITE => { self.heap.marks.color[at] = FREE; - if let Kind::BigInt(n) = &self.heap[at].kind { - self.bigints.forget(at as Id, n); + if let Some(ids) = self.object_ids.get_mut().as_deref_mut() { + ids.forget(at as Id); + } + match &self.heap[at].kind { + Kind::BigInt(n) => { + self.bigints.forget(at as Id, n); + } + Kind::Native { + f, + data: Value::Num(index), + .. + } if std::ptr::fn_addr_eq( + *f, + crate::host::host_native as crate::vm::NativeFn, + ) => + { + let idx = *index as usize; + if *index >= 0.0 + && let Some(entry) = self.host.functions.get_mut(idx) + && entry.reclaimable + { + entry.reclaimable = false; + entry.label = String::new(); + let old = + std::mem::replace(&mut entry.f, crate::host::Callee::Reclaimed); + if let crate::host::Callee::Local { + live_id, + slot, + generation, + } = old + { + if let Some(live) = self.live.as_deref_mut() { + live.fn_free.push(idx); + } + reclaimed_locals.push((live_id, slot, generation)); + } + } + } + _ => {} } *self.heap.slot_mut(at) = Obj::new(None, Kind::Ordinary); self.gc.free.push(at as Id); @@ -1555,6 +1696,9 @@ impl Vm { at += 1; } self.gc.obj_sweep.0 = at; + if !reclaimed_locals.is_empty() { + crate::live_session::reclaim_local_fns(&reclaimed_locals); + } if self.gc.free.len() > freed_objs && !self.lazy_builtins.is_empty() { let color = &self.heap.marks.color; self.lazy_builtins diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index 1f14378b..a177cd79 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -182,11 +182,20 @@ impl Failed { } } -/// What a program function made from the host calls: a host function, or a durable one. +/// What a program function made from the host calls: a host function, a durable one, or a +/// single-thread live-session closure. #[derive(Clone)] pub enum Callee { Fn(HostFunction), Durable(DurableFunction), + /// A single-thread closure registered in a `LiveSession`'s thread-local store. + Local { + live_id: u64, + slot: u32, + generation: u32, + }, + /// A reclaimed `FnEntry` slot awaiting reuse via `LiveRoots::fn_free`. + Reclaimed, } impl Callee { @@ -201,7 +210,7 @@ impl Callee { fn length(&self) -> u8 { match self { Callee::Fn(f) => f.length, - Callee::Durable(_) => 0, + Callee::Durable(_) | Callee::Local { .. } | Callee::Reclaimed => 0, } } } @@ -218,6 +227,8 @@ pub struct FnEntry { /// Whether it is among the globals, even where no path leads (inside an array): such a function never crosses /// back to the host as itself. pub(crate) installed: bool, + /// Whether GC may reclaim this slot when its JS function object is swept (`HostCtx::local_fn`). + pub(crate) reclaimable: bool, } /// A host call in flight, as a suspend sees it. @@ -974,6 +985,7 @@ fn call_host( let concurrent = match f { Callee::Durable(_) => true, Callee::Fn(f) => f.is_async(), + Callee::Local { .. } | Callee::Reclaimed => false, }; let mut back = false; // Program getters in the arguments run first, as program code, before anything else happens for the call: no @@ -1331,6 +1343,9 @@ fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: b Box::pin(async move { Settlement::host(work.await, label, owner, site) }), ) } + Callee::Local { .. } | Callee::Reclaimed => { + unreachable!("local/reclaimed functions are never spawned asynchronously") + } Callee::Durable(d) => { let again = match std::mem::replace(&mut r.start, Start::Call) { Start::Wait(data) => Some(data), @@ -1593,7 +1608,7 @@ fn hosted(vm: &Vm, id: Id) -> Option { } let entry = vm.host.functions.get(*index as usize)?; match &entry.f { - Callee::Fn(f) if !entry.installed => Some(f.clone()), + Callee::Fn(f) if !entry.installed && !entry.reclaimable => Some(f.clone()), _ => None, } } @@ -2492,6 +2507,7 @@ fn shed_properties(vm: &mut Vm, id: Id) { match &mut vm.host.functions[index as usize].f { Callee::Fn(f) => f.properties = Arc::new([]), Callee::Durable(f) => f.properties = Arc::new([]), + Callee::Local { .. } | Callee::Reclaimed => {} } } } @@ -2512,6 +2528,7 @@ fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option Res { +pub(crate) fn host_native(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> Res { let Value::Num(index) = vm.native_data(callee) else { return Ok(Value::Undef); }; let entry = &vm.host.functions[index as usize]; + if let Callee::Local { + live_id, + slot, + generation, + } = entry.f + { + let label = entry.label.clone(); + return crate::live_session::call_local(vm, live_id, slot, generation, this, args, &label); + } + if matches!(entry.f, Callee::Reclaimed) { + return Err(vm.type_error("Local host function has been reclaimed.")); + } if let Callee::Fn(f) = &entry.f && let Body::Lost(message) = &f.body { diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index 9494b619..88087327 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -29,6 +29,7 @@ mod heap; mod host; mod host_function; mod iteration; +mod live_session; pub mod locale; mod native; mod nesting; @@ -66,6 +67,7 @@ pub use host_function::{ Call, CallType, DurableCall, DurableFunction, Failure, HostError, HostFunction, HostResult, HostString, HostValue, Namespace, Resolved, Returned, SnapshotHooks, TypedArray, TypedKind, }; +pub use live_session::{LiveSession, Root}; pub use program::{Program, RunOutcome, RunningCall, SuspendError, Suspended, Suspender}; pub use run::{Code, Compiled, CompiledModule}; pub use runtime::{ diff --git a/rust/crates/psychoscript/src/live_session.rs b/rust/crates/psychoscript/src/live_session.rs new file mode 100644 index 00000000..af1ea119 --- /dev/null +++ b/rust/crates/psychoscript/src/live_session.rs @@ -0,0 +1,649 @@ +//! Single-thread live sessions ([`LiveSession`]): a live VM entered directly from Rust closures +//! with zero JS trampoline overhead, GC-tracked pinned [`Root`] handles, GC-reclaimed single-thread +//! closures ([`HostCtx::local_fn`]), and typed thread-local host state ([`LiveSession::set_data`] / +//! [`HostCtx::with_data`]). +//! +//! Unlike the durable, `Send` [`Session`](crate::Session), a `LiveSession` is `!Send + !Sync` and +//! cannot be snapshotted. Its non-`Send` closures and host data live in a thread-local table keyed +//! by a unique non-zero `live_id`, keeping [`Vm`] itself `Send` and adding zero overhead to normal +//! [`Runtime::execute`](crate::Runtime::execute) or durable [`Session`](crate::Session) runs. + +use std::any::{Any, TypeId}; +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use rustc_hash::FxHashMap; + +use crate::host::{Callee, FnEntry}; +use crate::program::Program; +use crate::time::Instant; +use crate::value::{Id, Value}; +use crate::vm::Vm; +use crate::{ + Args, Code, CompiledModule, Diagnostic, HostCtx, Outcome, ProgramOptions, Runtime, Val, +}; + +static NEXT_LIVE_ID: AtomicU64 = AtomicU64::new(1); + +fn next_live_id() -> u64 { + loop { + let id = NEXT_LIVE_ID.fetch_add(1, Ordering::Relaxed); + if id != 0 { + return id; + } + } +} + +#[inline] +fn next_gen(g: u32) -> u32 { + let n = g.wrapping_add(1); + if n == 0 { 1 } else { n } +} + +// ---------- thread-local store for non-Send closures & typed data ---------- + +pub(crate) type LocalFn = + dyn for<'a> Fn(&mut HostCtx<'a>, Args<'a>) -> Result, Val<'a>> + 'static; + +struct LocalFnSlot { + /// Generation of this slot (starts at 1, skips 0 on wrap). + generation: u32, + func: Option>, +} + +#[derive(Default)] +struct LiveStore { + fns: Vec, + fn_free: Vec, + data: FxHashMap>, +} + +thread_local! { + static LIVE_STORES: RefCell>>> = + RefCell::new(FxHashMap::default()); +} + +fn register_live_store(live_id: u64) { + let store = Rc::new(RefCell::new(LiveStore::default())); + let _ = LIVE_STORES.try_with(|stores| { + stores.borrow_mut().insert(live_id, store); + }); +} + +fn unregister_live_store(live_id: u64) { + let removed = LIVE_STORES + .try_with(|stores| stores.borrow_mut().remove(&live_id)) + .ok() + .flatten(); + // Drop the store (and all captured closures / typed host data) OUTSIDE the TLS RefCell borrow. + drop(removed); +} + +fn get_live_store(live_id: u64) -> Option>> { + LIVE_STORES + .try_with(|stores| stores.borrow().get(&live_id).cloned()) + .ok() + .flatten() +} + +fn insert_local_fn(live_id: u64, func: Rc) -> Option<(u32, u32)> { + let store = get_live_store(live_id)?; + let mut s = store.borrow_mut(); + if let Some(slot) = s.fn_free.pop() { + let entry = &mut s.fns[slot as usize]; + entry.func = Some(func); + return Some((slot, entry.generation)); + } + let slot = u32::try_from(s.fns.len()).ok()?; + s.fns.push(LocalFnSlot { + generation: 1, + func: Some(func), + }); + Some((slot, 1)) +} + +fn lookup_local_fn(live_id: u64, slot: u32, generation: u32) -> Option> { + if generation == 0 { + return None; + } + let store = get_live_store(live_id)?; + let s = store.borrow(); + let entry = s.fns.get(slot as usize)?; + if entry.generation != generation { + return None; + } + entry.func.clone() +} + +/// Releases reclaimed local closures from `LIVE_STORES` after GC sweeps their JS function objects. +/// Drops all freed `Rc` values outside every `RefCell` borrow. +pub(crate) fn reclaim_local_fns(reclaimed: &[(u64, u32, u32)]) { + if reclaimed.is_empty() { + return; + } + let mut to_drop: Vec> = Vec::with_capacity(reclaimed.len()); + for &(live_id, slot, generation) in reclaimed { + let Some(store) = get_live_store(live_id) else { + continue; + }; + let mut s = store.borrow_mut(); + if let Some(entry) = s.fns.get_mut(slot as usize) + && entry.generation == generation + && let Some(func) = entry.func.take() + { + entry.generation = next_gen(entry.generation); + s.fn_free.push(slot); + to_drop.push(func); + } + } + // Dropped outside all RefCell borrows so Drop impls may safely re-enter `LIVE_STORES`. + drop(to_drop); +} + +/// Invokes a single-thread `local_fn` registered in `LIVE_STORES`. +pub(crate) fn call_local( + vm: &mut Vm, + live_id: u64, + slot: u32, + generation: u32, + this: Value, + args: &[Value], + label: &str, +) -> crate::vm::Res { + if !vm.live.as_deref().is_some_and(|l| l.live_id == live_id) { + return Err(vm.type_error("Local host function does not belong to this LiveSession.")); + } + let Some(func) = lookup_local_fn(live_id, slot, generation) else { + return Err(vm.type_error("Local host function has been reclaimed.")); + }; + let call = vm.host.next_call(); + vm.host.enter_sync(call, label.to_owned()); + let span = vm.host_span(); + let mut ctx = HostCtx::new(vm, span); + let r = (func)(&mut ctx, Args::new(this, args)); + let (vm, span) = ctx.into_parts(); + vm.end_host_span(span); + vm.host.leave_sync(); + r.map(|v| v.v).map_err(|e| e.v) +} + +fn store_set_data(live_id: u64, val: T) { + let Some(store) = get_live_store(live_id) else { + return; + }; + let old = store + .borrow_mut() + .data + .insert(TypeId::of::(), Box::new(val)); + // Drop any previous value outside the RefCell borrow. + drop(old); +} + +fn store_with_data(live_id: u64, f: impl FnOnce(&T) -> R) -> Option { + let store = get_live_store(live_id)?; + let borrow = store.borrow(); + let any = borrow.data.get(&TypeId::of::())?; + let val = any.downcast_ref::()?; + Some(f(val)) +} + +fn store_with_data_mut(live_id: u64, f: impl FnOnce(&mut T) -> R) -> Option { + let store = get_live_store(live_id)?; + let mut borrow = store.borrow_mut(); + let any = borrow.data.get_mut(&TypeId::of::())?; + let val = any.downcast_mut::()?; + Some(f(val)) +} + +// ---------- VM-side cold tables (Send, boxed on Vm) ---------- + +/// A pinned handle to a JavaScript value held by a [`LiveSession`]. +/// +/// The referenced value stays alive across garbage collection cycles until unpinned via +/// [`LiveSession::unroot`] or [`HostCtx::unroot`]. Stale roots and roots from another session +/// safely resolve to `None` in [`HostCtx::get_root`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Root { + live_id: u64, + slot: u32, + generation: u32, +} + +struct RootSlot { + /// Non-zero generation of this slot (starts at 1, skips 0 on wrap). + generation: u32, + val: Option, +} + +/// Cold per-`LiveSession` root table stored in `Vm::live: Option>`. +/// Remains `Send` so `Vm: Send` is preserved. +pub(crate) struct LiveRoots { + pub(crate) live_id: u64, + pinned: Vec, + free: Vec, + /// Free indices in `vm.host.functions` reclaimed from GC-swept `local_fn` objects. + pub(crate) fn_free: Vec, +} + +impl LiveRoots { + pub(crate) fn new() -> Self { + let live_id = next_live_id(); + register_live_store(live_id); + Self { + live_id, + pinned: Vec::new(), + free: Vec::new(), + fn_free: Vec::new(), + } + } + + pub(crate) fn values(&self) -> impl Iterator { + self.pinned.iter().filter_map(|s| s.val.as_ref()) + } + + fn insert(&mut self, v: Value) -> Option { + if let Some(slot) = self.free.pop() { + let entry = &mut self.pinned[slot as usize]; + entry.val = Some(v); + return Some(Root { + live_id: self.live_id, + slot, + generation: entry.generation, + }); + } + let slot = u32::try_from(self.pinned.len()).ok()?; + self.pinned.push(RootSlot { + generation: 1, + val: Some(v), + }); + Some(Root { + live_id: self.live_id, + slot, + generation: 1, + }) + } + + fn get(&self, root: Root) -> Option { + if root.live_id != self.live_id || root.generation == 0 { + return None; + } + let entry = self.pinned.get(root.slot as usize)?; + if entry.generation != root.generation { + return None; + } + entry.val + } + + fn remove(&mut self, root: Root) { + if root.live_id != self.live_id || root.generation == 0 { + return; + } + let Some(entry) = self.pinned.get_mut(root.slot as usize) else { + return; + }; + if entry.generation == root.generation && entry.val.is_some() { + entry.val = None; + entry.generation = next_gen(entry.generation); + self.free.push(root.slot); + } + } +} + +impl Drop for LiveRoots { + fn drop(&mut self) { + unregister_live_store(self.live_id); + } +} + +/// ABA-safe monotonic object identity map (`HostCtx::object_id`), allocated lazily in +/// `Vm::object_ids` and cleared per slot as GC sweeps freed objects. +pub(crate) struct ObjIds { + next: u64, + map: FxHashMap, +} + +impl Default for ObjIds { + fn default() -> Self { + Self { + next: 1, + map: FxHashMap::default(), + } + } +} + +impl ObjIds { + pub(crate) fn get_or_assign(&mut self, id: Id) -> u64 { + *self.map.entry(id).or_insert_with(|| { + let assigned = self.next; + let next = assigned.wrapping_add(1); + self.next = if next == 0 { 1 } else { next }; + assigned + }) + } + + #[inline] + pub(crate) fn forget(&mut self, id: Id) { + self.map.remove(&id); + } +} + +// ---------- LiveSession ---------- + +/// A single-thread, non-snapshotable live VM session ([`Runtime::live_session`]) designed for +/// high-frequency Rust-to-JS calls with zero JS trampoline overhead. +/// +/// Unlike [`Session`](crate::Session), `LiveSession` is `!Send + !Sync`, supports direct +/// [`LiveSession::enter`] closures without `'static` bounds, pins values with O(1) [`Root`] handles, +/// registers GC-reclaimed single-thread closures ([`HostCtx::local_fn`]), and stores typed +/// thread-local host state ([`LiveSession::set_data`]). +pub struct LiveSession { + program: Program, + /// Marks `LiveSession` as `!Send + !Sync`. + _not_send: PhantomData>, +} + +impl LiveSession { + pub(crate) fn start( + rt: &Runtime, + code: Code<'_>, + options: &ProgramOptions, + ) -> Result { + let mut program = Program::live_session(rt, code, options); + let outcome = program.drive_session(|_| {}); + match outcome.result { + Ok(_) => Ok(Self { + program, + _not_send: PhantomData, + }), + Err(diag) => Err(diag), + } + } + + fn vm(&self) -> &Vm { + self.program + .session_vm_ref() + .expect("live session always owns a running VM") + } + + fn vm_mut(&mut self) -> &mut Vm { + self.program + .session_vm() + .expect("live session always owns a running VM") + } + + fn live_id(&self) -> u64 { + self.vm() + .live + .as_deref() + .expect("live session always has LiveRoots") + .live_id + } + + /// Runs `f` directly inside the live VM with no `'static` bound and no JS wrapper overhead. + /// + /// Resets per-entry limits (`timeout_ms`, `Clock::ThreadCpu`, `slice_ms`, native stack base), + /// runs `f(&mut ctx)`, drains ready microtasks/jobs, runs pending/idle GC and heap-limit + /// accounting when not fatal, and returns `Ok(r)` or `Err(diag)` if a fatal limit/error + /// occurred (which also sticks for all subsequent entries). + pub fn enter(&mut self, f: impl FnOnce(&mut HostCtx<'_>) -> R) -> Result { + let probe = 0u8; + let vm = self.vm_mut(); + if let Some((kind, message)) = vm.fatal.clone() { + return Err(crate::run::diagnostic(kind, message)); + } + + vm.start = Instant::now(); + vm.start_cpu_meter(); + if let Some(c) = &mut vm.cpu { + c.enter(); + } + vm.slice = None; + vm.slice_restart(); + vm.stack_base = &probe as *const u8 as usize; + vm.stack_budget = crate::run::RUN_STACK_BUDGET; + vm.start_handover_fuel(); + + // Ensures `CpuMeter::leave` runs even if `f` panics. + struct CpuLeave<'v>(&'v mut Vm); + impl Drop for CpuLeave<'_> { + fn drop(&mut self) { + if let Some(c) = &mut self.0.cpu { + c.leave(false); + } + } + } + let guard = CpuLeave(vm); + + let span = guard.0.host_span(); + let result = { + let mut ctx = HostCtx::new(guard.0, span); + let r = f(&mut ctx); + let (vm, span) = ctx.into_parts(); + vm.end_host_span(span); + r + }; + + if guard.0.fatal.is_none() { + guard.0.drain_jobs(); + } + if guard.0.fatal.is_none() { + if guard.0.gc_pending() { + guard.0.gc_point(); + } + guard.0.gc_idle(); + if guard.0.heap_meter.is_some() { + guard.0.heap_point(0); + } + } + #[cfg(feature = "gc-stats")] + guard.0.publish_stats(); + + let fatal = guard.0.fatal.clone(); + drop(guard); + + if let Some((kind, message)) = fatal { + return Err(crate::run::diagnostic(kind, message)); + } + Ok(result) + } + + /// Unpins a slice of [`Root`] handles in O(1) per root without entering JS. + pub fn unroot(&mut self, roots: &[Root]) { + if let Some(live) = self.vm_mut().live.as_deref_mut() { + for &root in roots { + live.remove(root); + } + } + } + + /// Stores a typed single-thread host value associated with this `LiveSession`, replacing any + /// previous value of type `T`. + pub fn set_data(&mut self, val: T) { + store_set_data(self.live_id(), val); + } + + /// Borrows the typed host value `T` stored on this `LiveSession`, if present. + pub fn with_data(&self, f: impl FnOnce(&T) -> R) -> Option { + store_with_data(self.live_id(), f) + } + + /// Mutably borrows the typed host value `T` stored on this `LiveSession`, if present. + pub fn with_data_mut(&mut self, f: impl FnOnce(&mut T) -> R) -> Option { + store_with_data_mut(self.live_id(), f) + } + + /// Measures and returns the live reachable heap bytes of this session in the size model of + /// [`Limits::max_heap_bytes`](crate::Limits::max_heap_bytes). + pub fn heap_bytes(&mut self) -> usize { + let vm = self.vm_mut(); + let bytes = crate::heap::measure(vm); + vm.host.run.set_heap_bytes(bytes); + bytes as usize + } + + /// Runs one bounded incremental GC step when a cycle is running or due and the VM is not busy. + pub fn gc_step(&mut self) { + self.vm_mut().gc_step_bounded(); + } + + /// Finishes any in-progress GC cycle and runs one complete + /// `Idle -> Mark -> SweepWeak -> Sweep -> Trim -> Idle` collection cycle, reclaiming dead JS + /// objects and their associated [`HostCtx::local_fn`] closures. + pub fn collect_garbage(&mut self) { + self.vm_mut().gc_collect_full(); + } + + /// Merges a precompiled [`CompiledModule`] into this session and executes it synchronously. + pub fn eval_compiled(&mut self, module: &CompiledModule) -> Outcome { + self.program + .drive_session(|vm| crate::session::eval_compiled_in_session(vm, module)) + } + + /// Compiles `source` as a synchronous named module (respecting + /// [`Limits::max_source_bytes`](crate::Limits::max_source_bytes)) and executes it in this + /// session. + pub fn eval_module(&mut self, source: &str, name: &str) -> Outcome { + let vm = self.vm_mut(); + if vm.fatal.is_some() { + return self.program.drive_session(|_| {}); + } + let limit = vm.limits.source_limit(); + let metadata = vm.host.run.metadata(); + match crate::run::compile_module(source, name, limit) { + Ok(compiled) => self.eval_compiled(&compiled), + Err(diag) => Outcome { + result: Err(diag), + warnings: Vec::new(), + logs: Vec::new(), + truncated: false, + metadata, + }, + } + } + + /// Whether this session has terminated with a fatal error (such as timeout or memory limit). + pub fn is_fatal(&self) -> bool { + self.vm().fatal.is_some() + } +} + +// ---------- HostCtx live-session methods ---------- + +impl<'a> HostCtx<'a> { + /// Pins `v` in this [`LiveSession`]'s root table so it survives garbage collection across + /// [`LiveSession::enter`] calls. Returns `None` outside a [`LiveSession`] or if `v` is doomed. + pub fn root(&mut self, v: Val<'a>) -> Option { + let vm = self.vm_mut(); + vm.live.as_deref()?; + if vm.gc_is_doomed(v.v) { + return None; + } + // SATB write barrier: keep newly rooted values alive if an incremental mark is active. + if vm.heap.marking { + vm.gc_shade_value(v.v); + } + vm.live.as_deref_mut()?.insert(v.v) + } + + /// Resolves a pinned [`Root`] back to a [`Val`] in O(1). Returns `None` if the root was + /// unrooted, belongs to a different [`LiveSession`], or points to a doomed slot. + pub fn get_root(&self, root: Root) -> Option> { + let vm = self.vm(); + let v = vm.live.as_deref()?.get(root)?; + if vm.gc_is_doomed(v) { + return None; + } + Some(Val::of(v)) + } + + /// Unpins `root` in O(1). Safe no-op for stale roots, foreign roots, or outside a + /// [`LiveSession`]. + pub fn unroot(&mut self, root: Root) { + if let Some(live) = self.vm_mut().live.as_deref_mut() { + live.remove(root); + } + } + + /// Creates a JS function backed by a single-thread Rust closure (no `Send + Sync` required). + /// The closure is automatically reclaimed from thread-local storage when GC sweeps the JS + /// function object. + /// + /// Returns `Err(TypeError)` if called outside a [`LiveSession`]. + pub fn local_fn(&mut self, name: &str, f: F) -> Result, Val<'a>> + where + F: for<'b> Fn(&mut HostCtx<'b>, Args<'b>) -> Result, Val<'b>> + 'static, + { + let Some(live_id) = self.vm().live.as_deref().map(|l| l.live_id) else { + return Err( + self.type_error("HostCtx::local_fn can only be called inside a LiveSession.") + ); + }; + let func: Rc = Rc::new(f); + let Some((slot, generation)) = insert_local_fn(live_id, func) else { + return Err(self.type_error("Failed to register local host function.")); + }; + let vm = self.vm_mut(); + let entry = FnEntry { + f: Callee::Local { + live_id, + slot, + generation, + }, + label: name.to_owned(), + path: None, + owner: None, + installed: false, + reclaimable: true, + }; + let index = match vm.live.as_deref_mut().and_then(|l| l.fn_free.pop()) { + Some(idx) => { + vm.host.functions[idx] = entry; + idx + } + None => { + let idx = vm.host.functions.len(); + vm.host.functions.push(entry); + idx + } + }; + let fn_name = crate::strings::external_text(name.to_owned()); + let made = crate::host::native( + vm, + &fn_name, + 0, + crate::host::host_native, + Value::Num(index as f64), + ); + Ok(Val::of(made)) + } + + /// Stores a typed single-thread host value on the enclosing [`LiveSession`]. No-op outside a + /// [`LiveSession`]. + pub fn set_data(&mut self, val: T) { + if let Some(live_id) = self.vm().live.as_deref().map(|l| l.live_id) { + store_set_data(live_id, val); + } + } + + /// Borrows the typed host value `T` on the enclosing [`LiveSession`], if present. + pub fn with_data(&self, f: impl FnOnce(&T) -> R) -> Option { + let live_id = self.vm().live.as_deref()?.live_id; + store_with_data(live_id, f) + } + + /// Mutably borrows the typed host value `T` on the enclosing [`LiveSession`], if present. + pub fn with_data_mut(&mut self, f: impl FnOnce(&mut T) -> R) -> Option { + let live_id = self.vm().live.as_deref()?.live_id; + store_with_data_mut(live_id, f) + } +} + +// `Vm`, `Session`, and `Program` remain `Send` even with `LiveSession` support. +const _: () = { + const fn is_send() {} + is_send::(); + is_send::(); + is_send::(); +}; diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index 24e0af27..ca4fef65 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -302,6 +302,17 @@ impl Program { program } + /// A single-thread live session's run of `code`, with `Vm::live` initialized before top-level + /// execution so direct host functions called during startup can root values and register local + /// closures immediately. + pub(crate) fn live_session(rt: &Runtime, code: Code<'_>, options: &ProgramOptions) -> Self { + let mut program = Self::session(rt, code, options); + if let State::Running(r) = &mut program.state { + r.vm.live = Some(Box::new(crate::live_session::LiveRoots::new())); + } + program + } + /// A session's run continuing from its saved state, checked against this runtime. pub(crate) fn restore_session( rt: &Runtime, @@ -326,6 +337,14 @@ impl Program { } } + /// Shared reference to a session's VM, unless it failed to compile. + pub(crate) fn session_vm_ref(&self) -> Option<&Vm> { + match &self.state { + State::Running(r) => Some(&r.vm), + _ => None, + } + } + /// Drives a session's run, as [`Program::run`] does, through its top level or a call `start` sets up, with the /// run's limits counting from now; it stays for the next call. Returns how the top level or the call ended. pub(crate) fn drive_session(&mut self, start: impl FnOnce(&mut Vm)) -> Outcome { diff --git a/rust/crates/psychoscript/src/reach.rs b/rust/crates/psychoscript/src/reach.rs index 3b5d3ce6..b24ec20d 100644 --- a/rust/crates/psychoscript/src/reach.rs +++ b/rust/crates/psychoscript/src/reach.rs @@ -36,6 +36,9 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { if let Some(s) = &vm.session { t.vals(s.exports.iter()); } + if let Some(live) = &vm.live { + t.vals(live.values()); + } for (k, v) in &vm.global_map { t.atom(*k); t.val(v); diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index dc5f30fc..4e534eb7 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -547,7 +547,7 @@ fn diagnostic_json(d: &Diagnostic) -> String { } /// A diagnostic whose message is a run's text (see `strings`), which keeps unpaired surrogates. -fn diagnostic(kind: DiagnosticKind, message: String) -> Diagnostic { +pub(crate) fn diagnostic(kind: DiagnosticKind, message: String) -> Diagnostic { Diagnostic { kind, message: HostString::from_run_text(&message), diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 455b28ca..72aed677 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -409,6 +409,17 @@ impl Runtime { crate::Session::start(self, code.into(), options) } + /// Runs `code`'s top level synchronously on the calling thread and keeps the VM alive as a + /// single-thread, non-snapshotable [`LiveSession`](crate::LiveSession). Returns `Err` if + /// compilation or top-level execution fails. + pub fn live_session<'c>( + &self, + code: impl Into>, + options: &ProgramOptions, + ) -> Result { + crate::LiveSession::start(self, code.into(), options) + } + /// A session continuing from the state [`Session::save`](crate::Session::save) gave, here or in another process /// built from the same version; checked as [`Runtime::resume`] checks a suspended run's. pub fn restore_session(&self, state: &Snapshot) -> Result { diff --git a/rust/crates/psychoscript/src/session.rs b/rust/crates/psychoscript/src/session.rs index 7fb9200d..18c1e9f8 100644 --- a/rust/crates/psychoscript/src/session.rs +++ b/rust/crates/psychoscript/src/session.rs @@ -175,7 +175,7 @@ fn call(vm: &mut Vm, name: &str, args: &[Data]) { /// Loads a precompiled module and drives its synchronous entry closure through `Promise.try`, /// matching `call` so results, promises, limits, GC, and error stacks behave identically. -fn eval_compiled_in_session(vm: &mut Vm, module: &CompiledModule) { +pub(crate) fn eval_compiled_in_session(vm: &mut Vm, module: &CompiledModule) { let entry_idx = match vm.load_module(module) { Ok(idx) => idx, Err(e) => { @@ -304,6 +304,10 @@ pub struct Args<'a> { } impl<'a> Args<'a> { + pub(crate) fn new(this: Value, args: &'a [Value]) -> Self { + Self { this, args } + } + pub fn this(&self) -> Val<'a> { Val::of(self.this) } @@ -354,6 +358,24 @@ pub(crate) fn call_direct( } impl<'a> HostCtx<'a> { + pub(crate) fn new(vm: &'a mut Vm, span: Option) -> Self { + Self { vm, span } + } + + pub(crate) fn into_parts(self) -> (&'a mut Vm, Option) { + (self.vm, self.span) + } + + #[inline] + pub(crate) fn vm(&self) -> &Vm { + self.vm + } + + #[inline] + pub(crate) fn vm_mut(&mut self) -> &mut Vm { + self.vm + } + fn key(&mut self, name: &str) -> crate::strings::Atom { match crate::strings::has_mark(name) { false => self.vm.atoms.intern(name), @@ -489,6 +511,9 @@ impl<'a> HostCtx<'a> { this: Val<'a>, args: &[Val<'a>], ) -> Result, Val<'a>> { + if self.vm.fatal.is_some() { + return Err(Val::undefined()); + } let args: Vec = args.iter().map(|v| v.v).collect(); self.vm.end_host_span(self.span.take()); let r = self.vm.call(&f.v, this.v, &args); @@ -541,6 +566,131 @@ impl<'a> HostCtx<'a> { self.eval_compiled(&compiled) } + /// Whether `v` is a frozen object (`Object.freeze`). O(1) flag check; `false` for primitives. + pub fn is_frozen(&self, v: Val<'a>) -> bool { + matches!( + v.v, + Value::Obj(id) if self.vm.heap[id as usize].flags & crate::object::FROZEN != 0 + ) + } + + /// A unique, ABA-safe numeric identity for a live heap object within this VM (valid across + /// GC slot reuse), or `None` for primitives. + pub fn object_id(&self, v: Val<'a>) -> Option { + match v.v { + Value::Obj(id) => self.vm.object_id(id), + _ => None, + } + } + + /// Allocates a new `Uint8Array` populated directly from `bytes` without entering JS. + pub fn new_bytes(&mut self, bytes: &[u8]) -> Val<'a> { + Val::of(crate::builtins::bytes::new_bytes( + self.vm, + bytes.to_vec(), + false, + )) + } + + /// Reads global `name` directly from the VM's global table (lazily initializing built-in or + /// host globals if needed). Returns `Ok(Val::undefined())` if no such global exists. + pub fn get_global(&mut self, name: &str) -> Result, Val<'a>> { + if self.vm.fatal.is_some() { + return Err(Val::undefined()); + } + let key = self.key(name); + if !self.vm.global_map.contains_key(&key) + && (crate::host::has_host_global(self.vm, name) + || !crate::builtins::ensure_global(self.vm, name)) + { + crate::host::define_host_global_by_name(self.vm, name); + } + let val = self + .vm + .global_map + .get(&key) + .copied() + .unwrap_or(Value::Undef); + Ok(Val::of(val)) + } + + /// Sets global `name` to `v` in the VM's global table and updates any existing compiled global + /// slots bound to `name`. + pub fn set_global(&mut self, name: &str, v: Val<'a>) -> Result<(), Val<'a>> { + if self.vm.fatal.is_some() { + return Err(Val::undefined()); + } + let key = self.key(name); + self.vm.gc_shade_atom(key); + if self.vm.heap.marking { + self.vm.gc_shade_value(v.v); + } + self.vm.global_map.insert(key, v.v); + for (i, &gname) in self.vm.global_names.iter().enumerate() { + if gname == key { + self.vm.globals[i] = v.v; + } + } + Ok(()) + } + + /// Walks the own enumerable string properties of `o` in JavaScript key order (skipping symbol + /// keys `<= SYM_LAST`), invoking getters where present and passing `(&str, Val)` to `f`. + /// + /// Takes a zero-allocation fast path for plain objects without accessors or integer keys. + pub fn for_each_own( + &mut self, + o: Val<'a>, + mut f: impl FnMut(&str, Val<'a>) -> Result<(), Val<'a>>, + ) -> Result<(), Val<'a>> { + let Value::Obj(id) = o.v else { + return Ok(()); + }; + let fast = { + let obj = &self.vm.heap[id as usize]; + matches!(obj.kind, Kind::Ordinary | Kind::Error(_)) + && obj.props.items.iter().all(|p| { + p.flags & crate::object::ENUMERABLE == 0 + || p.key <= crate::object::SYM_LAST + || (p.flags & (crate::object::ACCESSOR | crate::object::PENDING_STACK) == 0 + && self.vm.atoms.index(p.key).is_none()) + }) + }; + if fast { + let props = &self.vm.heap[id as usize].props.items; + for p in props.iter() { + if p.flags & crate::object::ENUMERABLE == 0 || p.key <= crate::object::SYM_LAST { + continue; + } + let key = crate::strings::host_text(self.vm.atoms.text(p.key)); + f(&key, Val::of(p.value()))?; + } + return Ok(()); + } + let keys = self.vm.own_keys(id); + for key in keys { + let val = { + let read = self.vm.op_read(&o.v, key).map_err(Val::of)?; + self.read(o, read)? + }; + let name = crate::strings::host_text(self.vm.atoms.text(key)); + f(&name, val)?; + } + Ok(()) + } + + /// Whether the VM has terminated with a fatal error (such as timeout or memory limit), + /// distinguishing fatal termination from a normal JavaScript `throw undefined`. + pub fn is_fatal(&self) -> bool { + self.vm.fatal.is_some() + } + + /// Formats `v` into a human-readable string without invoking any JavaScript code or mutating + /// the VM. Safe on circular objects and deeply nested structures. + pub fn format_val(&self, v: Val<'a>) -> String { + format_val_readonly(self.vm, v.v) + } + /// A new `Error`, to throw: the function's `Err`. pub fn error(&mut self, message: &str) -> Val<'a> { let proto = self.vm.realm.error_proto; @@ -555,6 +705,225 @@ impl<'a> HostCtx<'a> { } } +/// Safe, non-JS-invoking human-readable formatting for [`HostCtx::format_val`]. +fn format_val_readonly(vm: &Vm, v: Value) -> String { + match v { + Value::Undef | Value::Uninit => "undefined".to_owned(), + Value::Null => "null".to_owned(), + Value::Bool(b) => (if b { "true" } else { "false" }).to_owned(), + Value::Num(n) => crate::value::num_to_string(n), + Value::Str(s) => crate::strings::host_text(vm.text(s)).into_owned(), + Value::Sym(s) => crate::ops::symbol_text(s).to_owned(), + Value::Big(id) => format!("{}n", vm.big_text(id)), + Value::Obj(_) => { + let mut out = String::new(); + let mut seen = Vec::new(); + format_readonly_inner(vm, v, &mut out, &mut seen, 0); + out + } + } +} + +const FORMAT_MAX_DEPTH: usize = 16; +const FORMAT_MAX_LEN: usize = 4096; + +fn format_readonly_inner( + vm: &Vm, + v: Value, + out: &mut String, + seen: &mut Vec, + depth: usize, +) { + if out.len() >= FORMAT_MAX_LEN { + return; + } + match v { + Value::Undef | Value::Uninit => out.push_str("undefined"), + Value::Null => out.push_str("null"), + Value::Bool(b) => out.push_str(if b { "true" } else { "false" }), + Value::Num(n) => out.push_str(&crate::value::num_to_string(n)), + Value::Str(s) => { + let text = crate::strings::host_text(vm.text(s)); + out.push('"'); + for ch in text.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c => out.push(c), + } + if out.len() >= FORMAT_MAX_LEN { + out.push_str("..."); + return; + } + } + out.push('"'); + } + Value::Sym(s) => out.push_str(crate::ops::symbol_text(s)), + Value::Big(id) => { + out.push_str(&vm.big_text(id)); + out.push('n'); + } + Value::Obj(id) => { + if depth >= FORMAT_MAX_DEPTH { + out.push_str("..."); + return; + } + if seen.contains(&id) { + out.push_str("[Circular]"); + return; + } + seen.push(id); + let obj = &vm.heap[id as usize]; + match &obj.kind { + Kind::Error(_) => { + let name = + peek_str_prop(vm, id, vm.names.name).unwrap_or_else(|| "Error".to_owned()); + let msg = peek_str_prop(vm, id, vm.names.message).unwrap_or_default(); + if msg.is_empty() { + out.push_str(&name); + } else if name.is_empty() { + out.push_str(&msg); + } else { + out.push_str(&name); + out.push_str(": "); + out.push_str(&msg); + } + } + Kind::Array(items) => { + out.push('['); + for (i, &item) in items.iter().enumerate() { + if i > 0 { + out.push_str(", "); + } + if out.len() >= FORMAT_MAX_LEN { + out.push_str("..."); + break; + } + if !matches!(item, Value::Uninit) { + format_readonly_inner(vm, item, out, seen, depth + 1); + } + } + if obj.flags & crate::object::SPARSE != 0 { + out.push_str(", ..."); + } + out.push(']'); + } + Kind::Closure(c) => { + let n = crate::strings::host_text(vm.atoms.text(c.proto.name)); + if n.is_empty() { + out.push_str("[Function (anonymous)]"); + } else { + out.push_str("[Function: "); + out.push_str(&n); + out.push(']'); + } + } + Kind::Native { name, .. } => { + let n = crate::strings::host_text(vm.atoms.text(*name)); + if n.is_empty() { + out.push_str("[Function (anonymous)]"); + } else { + out.push_str("[Function: "); + out.push_str(&n); + out.push(']'); + } + } + Kind::Bound(_) => out.push_str("[Function (bound)]"), + Kind::Promise(_) => out.push_str("[Promise]"), + Kind::Bytes(b) => { + out.push_str(b.elem.name()); + out.push('('); + out.push_str(&b.len.to_string()); + out.push(')'); + } + Kind::Date(ms) => { + if ms.is_nan() { + out.push_str("Invalid Date"); + } else { + out.push_str("Date("); + out.push_str(&crate::value::num_to_string(*ms)); + out.push(')'); + } + } + Kind::RegExp(r) => { + out.push('/'); + out.push_str(&crate::strings::host_text(&r.source)); + out.push('/'); + out.push_str(&crate::strings::host_text(&r.flags)); + } + Kind::Map(m) => { + out.push_str("Map("); + out.push_str(&m.live.to_string()); + out.push(')'); + } + Kind::Set(m) => { + out.push_str("Set("); + out.push_str(&m.live.to_string()); + out.push(')'); + } + Kind::WeakMap(_) => out.push_str("WeakMap { }"), + Kind::WeakSet(_) => out.push_str("WeakSet { }"), + Kind::Ordinary | Kind::Arguments(_) => { + out.push('{'); + let mut first = true; + for p in obj.props.items.iter() { + if p.flags & crate::object::ENUMERABLE == 0 + || p.key <= crate::object::SYM_LAST + { + continue; + } + if out.len() >= FORMAT_MAX_LEN { + out.push_str(", ..."); + break; + } + if first { + out.push(' '); + first = false; + } else { + out.push_str(", "); + } + out.push_str(&crate::strings::host_text(vm.atoms.text(p.key))); + out.push_str(": "); + if p.flags & crate::object::ACCESSOR != 0 { + out.push_str("[Getter]"); + } else { + format_readonly_inner(vm, p.value(), out, seen, depth + 1); + } + } + if !first { + out.push(' '); + } + out.push('}'); + } + _ => out.push_str("[Object]"), + } + seen.pop(); + } + } +} + +/// Walks `id`'s prototype chain without invoking getters to read a plain string property. +fn peek_str_prop(vm: &Vm, mut id: crate::value::Id, key: crate::strings::Atom) -> Option { + for _ in 0..64 { + let obj = &vm.heap[id as usize]; + if let Some(p) = obj.props.prop(key) { + if p.flags & crate::object::ACCESSOR != 0 { + return None; + } + return match p.value() { + Value::Str(s) => Some(crate::strings::host_text(vm.text(s)).into_owned()), + Value::Undef | Value::Uninit => None, + other => Some(format_val_readonly(vm, other)), + }; + } + id = obj.proto?; + } + None +} + const _: () = { const fn owned() {} owned::(); diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index fcc3a0c2..cfd843af 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -741,7 +741,7 @@ impl Enc<'_> { .map(|f| { let (name, length, own) = match &f.f { Callee::Fn(hf) => (hf.name(), hf.length, hf.own_name), - Callee::Durable(_) => ("", 0, false), + Callee::Durable(_) | Callee::Local { .. } | Callee::Reclaimed => ("", 0, false), }; json!([ f.label, @@ -3102,6 +3102,7 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> { path, owner, installed, + reclaimable: false, }); } vm.host.suggestions.clear(); diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index b301d1be..78a96eb0 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -370,6 +370,11 @@ pub struct Vm { pub(crate) session: Option>, /// Dynamically loaded code chunks (`Array.fromAsync` and named modules), in load order. Saved with the run. pub(crate) loaded_code: Option>, + /// Single-thread live-session state (`live_session.rs`): pinned roots, live session id, and + /// reclaimed host-function slots. `None` for normal runs and durable `Session`s. + pub(crate) live: Option>, + /// ABA-safe monotonic object identities (`HostCtx::object_id`), allocated lazily on first use. + pub(crate) object_ids: std::cell::RefCell>>, } /// Distinct named module sources and exact load order of dynamically appended bytecode chunks. @@ -528,6 +533,8 @@ impl Vm { console: None, session: None, loaded_code: None, + live: None, + object_ids: std::cell::RefCell::new(None), } } @@ -5415,6 +5422,76 @@ impl Vm { self.reference_error(&format!("Cannot access '{n}' before initialization.")) } + /// Returns a unique, ABA-safe numeric identity for live object `id`, or `None` if `id` is + /// already freed or doomed in the current GC cycle. + pub(crate) fn object_id(&self, id: Id) -> Option { + if self.gc_is_doomed(Value::Obj(id)) { + return None; + } + let mut slot = self.object_ids.borrow_mut(); + let ids = slot.get_or_insert_with(|| Box::new(crate::live_session::ObjIds::default())); + Some(ids.get_or_assign(id)) + } + + /// Drains ready microtask jobs and already-settled host inbox results (and launches any queued + /// async host calls) without requiring `self.outcome` to be set. Used by `LiveSession::enter`. + pub(crate) fn drain_jobs(&mut self) { + loop { + if self.fatal.is_some() { + return; + } + if self.suspend_wanted && !self.gc_point() { + return; + } + if self.host.tasks.has_ready() { + let span = self.host_span(); + let ready = self.host.tasks.poll_ready(); + self.end_host_span(span); + for (p, s) in ready { + self.host.settled(p); + if let crate::host::Settlement::Interrupted = s { + crate::host::interrupt(self); + } + self.inbox.push_back((p, s)); + } + } + if let Some(job) = self.jobs.pop_front() { + if self.tick().is_err() { + return; + } + self.handover(); + if self.fatal.is_some() { + return; + } + let _ = self.run_job(job); + continue; + } + if let Some((p, outcome)) = self.inbox.pop_front() { + if self.check_time().is_err() { + return; + } + if self.slice.is_some() { + self.slice_restart(); + } + crate::host::settle(self, p, outcome); + continue; + } + if !self.host.queued.is_empty() { + if self.heap_meter.is_some() { + self.heap_point(0); + if self.fatal.is_some() { + return; + } + } + crate::host::launch(self); + if self.host.tasks.has_ready() || !self.jobs.is_empty() || !self.inbox.is_empty() { + continue; + } + } + return; + } + } + // ---------- driver ---------- /// Runs queued jobs and delivers host results until the program has an outcome. diff --git a/rust/crates/psychoscript/tests/live_session.rs b/rust/crates/psychoscript/tests/live_session.rs new file mode 100644 index 00000000..2f344375 --- /dev/null +++ b/rust/crates/psychoscript/tests/live_session.rs @@ -0,0 +1,897 @@ +//! Integration tests for `LiveSession`, `Root`, `HostCtx::local_fn`, typed thread-local data, +//! and zero-copy `HostCtx` inspection/mutation primitives. + +use std::cell::{Cell, RefCell}; +use std::collections::HashSet; +use std::rc::Rc; +use std::time::Duration; + +use psychoscript::{ + Clock, DiagnosticKind, HostFunction, HostValue, Limits, ProgramOptions, Root, Runtime, Val, +}; + +struct DropGuard(Rc>); + +impl Drop for DropGuard { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } +} + +#[test] +fn enter_borrows_local_stack_and_drains_microtasks() { + let rt = Runtime::make(); + let mut session = rt + .live_session( + r#" + let log = []; + function record(x) { + log.push("sync:" + x); + Promise.resolve(x).then(v => { + log.push("micro1:" + v); + return v * 2; + }).then(v => { + log.push("micro2:" + v); + }); + return x + 1; + } + function getLog() { return log; } + return { record, getLog }; + "#, + &ProgramOptions::new(), + ) + .expect("live session should start"); + + // Capture the functions into globals or via eval_compiled; here let's register via eval_module + // or test via globals set in top-level. Wait: let's also test top-level globals directly! + let mut local_vec: Vec = Vec::new(); + let out = session + .enter(|ctx| { + let f = ctx + .eval_module( + r#" + let seen = []; + return { + trigger(x) { + seen.push("sync:" + x); + Promise.resolve(x) + .then(v => { seen.push("m1:" + v); return v * 10; }) + .then(v => { seen.push("m2:" + v); }); + return x + 1; + }, + drain() { return seen.join(","); } + }; + "#, + "driver.js", + ) + .unwrap(); + let trigger = ctx.get(f, "trigger").unwrap(); + let drain = ctx.get(f, "drain").unwrap(); + let r = ctx.call(trigger, f, &[Val::num(7.0)]).unwrap(); + local_vec.push(format!("returned={}", r.as_f64().unwrap())); + ctx.set_global("__drain", drain).unwrap(); + ctx.set_global("__holder", f).unwrap(); + r.as_f64().unwrap() + }) + .expect("enter should succeed"); + + assert_eq!(out, 8.0); + assert_eq!(local_vec, vec!["returned=8"]); + + // Microtasks queued during the first `enter` must have been drained before `enter` returned! + let drained = session + .enter(|ctx| { + let drain = ctx.get_global("__drain").unwrap(); + let holder = ctx.get_global("__holder").unwrap(); + let res = ctx.call(drain, holder, &[]).unwrap(); + ctx.text(res).unwrap().into_owned() + }) + .expect("second enter should succeed"); + assert_eq!(drained, "sync:7,m1:7,m2:70"); +} + +#[test] +fn timeout_and_thread_cpu_clock_and_fatal_stickiness() { + // 1. Per-entry timeout resets across sleeps between entries (Wall clock). + let rt = Runtime::make().limits(Limits { + timeout_ms: Some(150), + ..Default::default() + }); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + let spin_mod = rt + .compile_module( + r#" + return { + work() { let s = 0; for (let i = 0; i < 5000; i++) s += i; return s; }, + spin() { let n = 0; while (true) n++; } + }; + "#, + "spin.js", + ) + .unwrap(); + + let api_root = session + .enter(|ctx| { + let api = ctx.eval_compiled(&spin_mod).unwrap(); + ctx.root(api).unwrap() + }) + .unwrap(); + + std::thread::sleep(Duration::from_millis(180)); + let sum = session + .enter(|ctx| { + let api = ctx.get_root(api_root).unwrap(); + let work = ctx.get(api, "work").unwrap(); + ctx.call(work, api, &[]).unwrap().as_f64().unwrap() + }) + .expect("per-entry timeout should reset between enter() calls"); + assert_eq!(sum, (4999.0 * 5000.0) / 2.0); + assert!(!session.is_fatal()); + + // 2. Infinite loop triggers TimeoutExceeded and leaves session permanently fatal. + let mut saw_fatal_in_ctx = false; + let err = session + .enter(|ctx| { + let api = ctx.get_root(api_root).unwrap(); + let spin = ctx.get(api, "spin").unwrap(); + let res = ctx.call(spin, api, &[]); + assert!(res.is_err()); + saw_fatal_in_ctx = ctx.is_fatal(); + }) + .unwrap_err(); + assert!(saw_fatal_in_ctx); + assert_eq!(err.kind, DiagnosticKind::TimeoutExceeded); + assert!(session.is_fatal()); + + // Subsequent enter() fails immediately without running closure. + let mut ran_after_fatal = false; + let err2 = session + .enter(|_| { + ran_after_fatal = true; + }) + .unwrap_err(); + assert!(!ran_after_fatal); + assert_eq!(err2.kind, DiagnosticKind::TimeoutExceeded); + assert_eq!(err2.message, err.message); + + // 3. Clock::ThreadCpu also enforces timeout cleanly inside LiveSession::enter. + let rt_cpu = Runtime::make().limits(Limits { + timeout_ms: Some(120), + clock: Clock::ThreadCpu, + ..Default::default() + }); + let mut cpu_session = rt_cpu + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + let cpu_err = cpu_session + .enter(|ctx| { + let m = ctx + .eval_module("return () => { let x = 0; while (true) x++; };", "cpu.js") + .unwrap(); + let _ = ctx.call(m, Val::undefined(), &[]); + }) + .unwrap_err(); + assert_eq!(cpu_err.kind, DiagnosticKind::TimeoutExceeded); + assert!(cpu_session.is_fatal()); +} + +#[test] +fn root_lifecycle_gc_survival_cross_session_and_stale_rejection() { + let rt = Runtime::make(); + let mut s1 = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + let mut s2 = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + // Pin an object, a string, and an array; drop all JS references and churn allocations. + let (obj_root, str_root, arr_root) = s1 + .enter(|ctx| { + let obj = ctx.object(); + let hello = ctx.string("hello-pinned-string"); + ctx.set(obj, "msg", hello).unwrap(); + ctx.set(obj, "num", Val::num(42.0)).unwrap(); + + let arr = ctx.array(&[Val::num(10.0), Val::num(20.0), hello]); + ( + ctx.root(obj).unwrap(), + ctx.root(hello).unwrap(), + ctx.root(arr).unwrap(), + ) + }) + .unwrap(); + + // Allocate lots of transient garbage and force full collections. + s1.enter(|ctx| { + let _ = ctx + .eval_module( + "let tmp = []; for (let i = 0; i < 4000; i++) tmp.push({ k: 'trash_' + i, i }); tmp = null;", + "churn.js", + ) + .unwrap(); + }) + .unwrap(); + s1.collect_garbage(); + s1.gc_step(); + s1.collect_garbage(); + + // Pinned roots survived GC completely intact! + s1.enter(|ctx| { + let obj = ctx.get_root(obj_root).expect("obj root alive"); + assert_eq!(ctx.get(obj, "num").unwrap().as_f64(), Some(42.0)); + let msg = ctx.get(obj, "msg").unwrap(); + assert_eq!(ctx.text(msg).as_deref(), Some("hello-pinned-string")); + + let s = ctx.get_root(str_root).expect("str root alive"); + assert_eq!(ctx.text(s).as_deref(), Some("hello-pinned-string")); + + let arr = ctx.get_root(arr_root).expect("arr root alive"); + assert_eq!(ctx.get_index(arr, 1).unwrap().as_f64(), Some(20.0)); + let item2 = ctx.get_index(arr, 2).unwrap(); + assert_eq!(ctx.text(item2).as_deref(), Some("hello-pinned-string")); + }) + .unwrap(); + + // Cross-session root rejection: s2 rejects s1's roots and cannot unroot them. + let s2_root = s2 + .enter(|ctx| { + assert!(ctx.get_root(obj_root).is_none()); + ctx.unroot(obj_root); + let o = ctx.object(); + ctx.set(o, "session", Val::num(2.0)).unwrap(); + ctx.root(o).unwrap() + }) + .unwrap(); + s2.unroot(&[obj_root, str_root]); + + // s1's roots are still intact, and s1 rejects s2's root. + s1.enter(|ctx| { + assert!(ctx.get_root(obj_root).is_some()); + assert!(ctx.get_root(s2_root).is_none()); + }) + .unwrap(); + + // Unroot via LiveSession::unroot (O(1), no JS call), then reuse the slot and verify stale Root fails. + s1.unroot(&[obj_root]); + let reused_root = s1 + .enter(|ctx| { + assert!(ctx.get_root(obj_root).is_none()); + let fresh = ctx.object(); + ctx.set(fresh, "fresh", Val::bool(true)).unwrap(); + let r2 = ctx.root(fresh).unwrap(); + // Stale handle STILL returns None even after its slot was reused! + assert!(ctx.get_root(obj_root).is_none()); + assert_ne!(obj_root, r2); + assert_eq!( + ctx.get(ctx.get_root(r2).unwrap(), "fresh") + .unwrap() + .as_bool(), + Some(true) + ); + r2 + }) + .unwrap(); + + // Unroot via HostCtx::unroot and double-unroot safety. + s1.enter(|ctx| { + ctx.unroot(reused_root); + ctx.unroot(reused_root); + assert!(ctx.get_root(reused_root).is_none()); + }) + .unwrap(); + s1.unroot(&[str_root, arr_root, obj_root]); +} + +#[test] +fn root_satb_write_barrier_keeps_object_pinned_mid_gc_cycle() { + let rt = Runtime::make(); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + // Allocate enough objects to push GC past threshold, then interleave gc_step with pinning. + let mut pinned: Vec = Vec::new(); + for round in 0..8 { + let r = session + .enter(|ctx| { + let _ = ctx + .eval_module( + "let g = []; for (let i = 0; i < 2000; i++) g.push({ v: i }); g = null;", + "alloc.js", + ) + .unwrap(); + let o = ctx.object(); + let tag = ctx.string(&format!("round-{round}")); + ctx.set(o, "tag", tag).unwrap(); + ctx.root(o).unwrap() + }) + .unwrap(); + pinned.push(r); + session.gc_step(); + } + session.collect_garbage(); + + session + .enter(|ctx| { + for (round, &r) in pinned.iter().enumerate() { + let o = ctx.get_root(r).expect("pinned root must survive SATB"); + let tag = ctx.get(o, "tag").unwrap(); + assert_eq!( + ctx.text(tag).as_deref(), + Some(format!("round-{round}").as_str()) + ); + } + }) + .unwrap(); + session.unroot(&pinned); +} + +#[test] +fn local_fn_non_send_reentrant_and_gc_reclaimed() { + let rt = Runtime::make().globals(|_| { + // A regular host function that takes functions to prove local_fn is excluded from hosted(). + let check_hosted = + HostFunction::new(|args, _| Ok(HostValue::from(args.len() as f64))).takes_functions(); + vec![("checkHosted", HostValue::Function(check_hosted))] + }); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + // 1. Non-Send Rc> captured in local_fn + re-entrant Rust -> JS -> local_fn -> JS! + let calls = Rc::new(Cell::new(0usize)); + let drops = Rc::new(Cell::new(0usize)); + + let result = session + .enter(|ctx| { + let calls_clone = calls.clone(); + let guard = DropGuard(drops.clone()); + let js_helper = ctx + .eval_module("return (n) => n * 3;", "helper.js") + .unwrap(); + let helper_root = ctx.root(js_helper).unwrap(); + + let cb = ctx + .local_fn("reentrantCb", move |ctx, args| { + let _keep = &guard; + calls_clone.set(calls_clone.get() + 1); + let n = args.get(0).as_f64().unwrap_or(0.0); + let helper = ctx.get_root(helper_root).unwrap(); + let tripled = ctx.call(helper, Val::undefined(), &[Val::num(n)])?; + Ok(Val::num(tripled.as_f64().unwrap() + 1.0)) + }) + .unwrap(); + + ctx.set_global("myCb", cb).unwrap(); + + // Passing local_fn to a takes_functions host fn must NOT expose it via hosted(). + let crossed = ctx.eval_module("return checkHosted(myCb);", "cross.js"); + assert!( + crossed.is_err(), + "local_fn must not cross via hosted() cloning" + ); + + // Invoke re-entrantly: Rust -> JS -> local_fn -> JS -> Rust. + let runner = ctx + .eval_module("return () => myCb(10) + myCb(5);", "run.js") + .unwrap(); + let r = ctx.call(runner, Val::undefined(), &[]).unwrap(); + ctx.unroot(helper_root); + r.as_f64().unwrap() + }) + .unwrap(); + + assert_eq!(result, (10.0 * 3.0 + 1.0) + (5.0 * 3.0 + 1.0)); + assert_eq!(calls.get(), 2); + assert_eq!(drops.get(), 0, "cb is still referenced by global myCb"); + + // Still alive across GC while referenced! + session.collect_garbage(); + assert_eq!(drops.get(), 0); + + // Drop JS reference and collect garbage -> closure MUST be automatically reclaimed! + session + .enter(|ctx| { + ctx.set_global("myCb", Val::undefined()).unwrap(); + }) + .unwrap(); + session.collect_garbage(); + assert_eq!( + drops.get(), + 1, + "local_fn closure must be dropped automatically when GC sweeps its JS function" + ); + + // 2. Churn 500 ephemeral local_fns to verify slot reuse and full GC reclamation. + let churn_drops = Rc::new(Cell::new(0usize)); + for i in 0..500usize { + let g = DropGuard(churn_drops.clone()); + session + .enter(|ctx| { + let f = ctx + .local_fn("ephemeral", move |_, args| { + let _keep = &g; + Ok(Val::num(args.get(0).as_f64().unwrap_or(0.0) + i as f64)) + }) + .unwrap(); + let out = ctx.call(f, Val::undefined(), &[Val::num(1.0)]).unwrap(); + assert_eq!(out.as_f64(), Some(i as f64 + 1.0)); + }) + .unwrap(); + if i % 100 == 99 { + session.collect_garbage(); + } + } + session.collect_garbage(); + assert_eq!(churn_drops.get(), 500); + + // 3. Dropping LiveSession drops any still-live local_fns cleanly. + let drop_on_session_drop = Rc::new(Cell::new(0usize)); + { + let mut s_drop = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + let g = DropGuard(drop_on_session_drop.clone()); + s_drop + .enter(|ctx| { + let f = ctx + .local_fn("kept", move |_, _| { + let _keep = &g; + Ok(Val::undefined()) + }) + .unwrap(); + ctx.set_global("kept", f).unwrap(); + }) + .unwrap(); + assert_eq!(drop_on_session_drop.get(), 0); + } + assert_eq!(drop_on_session_drop.get(), 1); +} + +#[test] +fn typed_data_shared_between_session_and_host_ctx() { + struct UiState { + nodes: Rc>>, + frame: u64, + } + + let rt = Runtime::make(); + let mut s1 = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + let mut s2 = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + assert!(s1.with_data::(|s| s.frame).is_none()); + + let shared_nodes = Rc::new(RefCell::new(Vec::new())); + s1.set_data(UiState { + nodes: shared_nodes.clone(), + frame: 1, + }); + s2.set_data(42u32); + + // Independent LiveSessions on the same thread do not conflict on RefCell borrows. + let nested = s1.with_data_mut::(|st1| { + st1.frame += 1; + s2.with_data_mut::(|v2| { + *v2 += 8; + (st1.frame, *v2) + }) + }); + assert_eq!(nested, Some(Some((2, 50)))); + + // Access via HostCtx inside enter() AND inside a local_fn called from JS! + s1.enter(|ctx| { + ctx.set_data("label-text".to_owned()); + let push_node = ctx + .local_fn("pushNode", |ctx, args| { + let text = ctx.text(args.get(0)).unwrap().into_owned(); + let prefix = ctx + .with_data::(|s| s.clone()) + .unwrap_or_default(); + ctx.with_data_mut::(|st| { + st.nodes + .borrow_mut() + .push(format!("{prefix}:{text}:f{}", st.frame)); + }); + Ok(Val::undefined()) + }) + .unwrap(); + ctx.set_global("pushNode", push_node).unwrap(); + let _ = ctx + .eval_module("pushNode('div'); pushNode('span');", "render.js") + .unwrap(); + }) + .unwrap(); + + assert_eq!( + *shared_nodes.borrow(), + vec!["label-text:div:f2", "label-text:span:f2"] + ); + + // Replacing data drops the old value cleanly outside any RefCell borrow. + let data_drops = Rc::new(Cell::new(0usize)); + s1.set_data(DropGuard(data_drops.clone())); + assert_eq!(data_drops.get(), 0); + s1.set_data(DropGuard(data_drops.clone())); + assert_eq!(data_drops.get(), 1); + drop(s1); + assert_eq!(data_drops.get(), 2); +} + +#[test] +fn is_frozen_and_aba_safe_object_id() { + let rt = Runtime::make(); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + // 1. is_frozen & basic object_id behavior. + let (kept_root, kept_id, dead_ids) = session + .enter(|ctx| { + assert!(!ctx.is_frozen(Val::undefined())); + assert!(!ctx.is_frozen(Val::num(1.0))); + assert!(ctx.object_id(Val::undefined()).is_none()); + assert!(ctx.object_id(Val::num(1.0)).is_none()); + let hi = ctx.string("hi"); + assert!(ctx.object_id(hi).is_none()); + + let plain = ctx.object(); + assert!(!ctx.is_frozen(plain)); + + let frozen = ctx + .eval_module("return Object.freeze({ tag: 'button', x: 1 });", "f.js") + .unwrap(); + assert!(ctx.is_frozen(frozen)); + + let id1 = ctx.object_id(frozen).expect("object has id"); + let id1_again = ctx.object_id(frozen).expect("object id is stable"); + assert_eq!(id1, id1_again); + assert_ne!(id1, ctx.object_id(plain).unwrap()); + + // Allocate 200 short-lived objects and record all their object_ids. + let mut dead = HashSet::new(); + for _ in 0..200 { + let tmp = ctx.object(); + assert!(dead.insert(ctx.object_id(tmp).unwrap())); + } + (ctx.root(frozen).unwrap(), id1, dead) + }) + .unwrap(); + + // Sweep all 200 dead objects so their heap slots enter the free list. + session.collect_garbage(); + + // Allocate 400 new objects (reusing those exact freed heap slots!) and verify: + // - kept object STILL has the exact same object_id + // - NONE of the newly allocated objects collide with any dead object_id (ABA-safe!) + session + .enter(|ctx| { + let kept = ctx.get_root(kept_root).unwrap(); + assert!(ctx.is_frozen(kept)); + assert_eq!(ctx.object_id(kept), Some(kept_id)); + + let mut new_ids = HashSet::new(); + for _ in 0..400 { + let fresh = ctx.object(); + let id = ctx.object_id(fresh).unwrap(); + assert!( + !dead_ids.contains(&id), + "ABA collision: reused heap slot returned old object_id {id}" + ); + assert!(new_ids.insert(id)); + } + }) + .unwrap(); + session.unroot(&[kept_root]); +} + +#[test] +fn new_bytes_get_set_global_for_each_own_format_val_and_is_fatal() { + let rt = Runtime::make(); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + session + .enter(|ctx| { + // 1. new_bytes creates a real Uint8Array directly with zero JS call. + let bytes_val = ctx.new_bytes(&[10, 20, 30, 40]); + assert_eq!(ctx.bytes(bytes_val), Some(&[10u8, 20, 30, 40][..])); + ctx.bytes_mut(bytes_val).unwrap()[2] = 99; + ctx.set_global("myBytes", bytes_val).unwrap(); + let check = ctx + .eval_module( + "return (myBytes instanceof Uint8Array) && myBytes.byteLength === 4 && myBytes[2] === 99;", + "bytes.js", + ) + .unwrap(); + assert_eq!(check.as_bool(), Some(true)); + + // 2. get_global lazily resolves built-ins & reads custom globals. + let u8_ctor = ctx.get_global("Uint8Array").unwrap(); + assert_eq!(ctx.type_of(u8_ctor), "function"); + let missing = ctx.get_global("definitelyNotDefined").unwrap(); + assert!(missing.is_undefined()); + let my_bytes = ctx.get_global("myBytes").unwrap(); + assert_eq!(ctx.bytes(my_bytes), Some(&[10u8, 20, 99, 40][..])); + + // 3. for_each_own: plain object (fast path) skipping Symbol.toStringTag & non-enumerable. + let plain = ctx + .eval_module( + r#" + const o = { a: 1, b: "two", [Symbol.toStringTag]: "HiddenSym" }; + Object.defineProperty(o, "secret", { value: 999, enumerable: false }); + return o; + "#, + "own1.js", + ) + .unwrap(); + let mut visited = Vec::new(); + ctx.for_each_own(plain, |k, v| { + visited.push((k.to_owned(), v.as_f64())); + Ok(()) + }) + .unwrap(); + assert_eq!(visited, vec![("a".to_owned(), Some(1.0)), ("b".to_owned(), None)]); + + // for_each_own: integer key order + getters + throwing getter + early abort. + let getter_obj = ctx + .eval_module( + r#" + return { + z: 1, + "2": 20, + "0": 0, + get computed() { return 77; }, + [Symbol.toStringTag]: "SkipMe", + }; + "#, + "own2.js", + ) + .unwrap(); + let mut entries = Vec::new(); + ctx.for_each_own(getter_obj, |k, v| { + entries.push((k.to_owned(), v.as_f64().unwrap())); + Ok(()) + }) + .unwrap(); + assert_eq!( + entries, + vec![ + ("0".to_owned(), 0.0), + ("2".to_owned(), 20.0), + ("z".to_owned(), 1.0), + ("computed".to_owned(), 77.0), + ] + ); + + // Early abort stops iteration. + let mut count = 0; + let stop_err = ctx.for_each_own(plain, |_, _| { + count += 1; + Err(Val::num(123.0)) + }); + assert_eq!(count, 1); + assert_eq!(stop_err.unwrap_err().as_f64(), Some(123.0)); + + // Non-objects are safe no-ops. + ctx.for_each_own(Val::null(), |_, _| panic!("should not visit")) + .unwrap(); + + // 4. is_fatal distinguishes `throw undefined` from fatal VM termination. + let throw_undef = ctx + .eval_module("return () => { throw undefined; };", "throw_undef.js") + .unwrap(); + let err = ctx.call(throw_undef, Val::undefined(), &[]).unwrap_err(); + assert!(err.is_undefined()); + assert!(!ctx.is_fatal(), "throw undefined must NOT set is_fatal()"); + + // 5. format_val formats values safely without invoking JS getters or toString(). + let tricky = ctx + .eval_module( + r#" + let sideEffects = 0; + const err = new TypeError("bad input"); + const nested = { a: { b: [1, 2] }, re: /abc/gi, map: new Map([["k", 1]]) }; + const guarded = { + ok: 1, + get trap() { sideEffects++; return "boom"; }, + toString() { sideEffects++; return "trap"; }, + }; + return { err, nested, guarded, arr: [1, "hi", true], getSideEffects: () => sideEffects }; + "#, + "fmt.js", + ) + .unwrap_or_else(|e| panic!("fmt.js failed: {}", ctx.format_val(e))); + let err_val = ctx.get(tricky, "err").unwrap(); + assert_eq!(ctx.format_val(err_val), "TypeError: bad input"); + let nested_val = ctx.get(tricky, "nested").unwrap(); + let nested_str = ctx.format_val(nested_val); + assert!(nested_str.contains("/abc/gi"), "got: {nested_str}"); + assert!(nested_str.contains("Map(1)"), "got: {nested_str}"); + let guarded_val = ctx.get(tricky, "guarded").unwrap(); + let guarded_str = ctx.format_val(guarded_val); + assert!(guarded_str.contains("[Getter]"), "got: {guarded_str}"); + let arr_val = ctx.get(tricky, "arr").unwrap(); + assert_eq!(ctx.format_val(arr_val), "[1, \"hi\", true]"); + assert_eq!(ctx.format_val(bytes_val), "Uint8Array(4)"); + assert_eq!(ctx.format_val(Val::undefined()), "undefined"); + let plain_str = ctx.string("plain"); + assert_eq!(ctx.format_val(plain_str), "plain"); + + // Confirm format_val invoked ZERO JS code! + let get_se = ctx.get(tricky, "getSideEffects").unwrap(); + assert_eq!(ctx.call(get_se, tricky, &[]).unwrap().as_f64(), Some(0.0)); + }) + .unwrap(); +} + +#[test] +fn primitives_work_in_durable_session_and_live_only_apis_fail_cleanly() { + let rt = Runtime::make().globals(|_| { + let inspect = HostFunction::direct(|ctx, args| { + // Live-only APIs behave cleanly outside LiveSession: + assert!(ctx.root(args.get(0)).is_none()); + assert!(ctx.local_fn("nope", |_, _| Ok(Val::undefined())).is_err()); + assert!(ctx.with_data::(|v| *v).is_none()); + + // Shared primitives work identically in durable Session! + let obj = args.get(0); + assert!(ctx.is_frozen(obj)); + let oid = ctx.object_id(obj).expect("object_id works in Session"); + assert_eq!(ctx.object_id(obj), Some(oid)); + + let mut sum = 0.0; + ctx.for_each_own(obj, |_, v| { + if let Some(n) = v.as_f64() { + sum += n; + } + Ok(()) + })?; + let bytes = ctx.new_bytes(&[1, 2, 3]); + assert_eq!(ctx.bytes(bytes), Some(&[1u8, 2, 3][..])); + assert!(!ctx.is_fatal()); + assert_eq!(ctx.format_val(Val::num(sum)), "6"); + Ok(Val::num(sum)) + }); + vec![("inspect", HostValue::Function(inspect))] + }); + + let (mut durable, started) = rt.session( + "return { run() { return inspect(Object.freeze({ a: 1, b: 2, c: 3 })); } };", + &ProgramOptions::new(), + ); + assert!(started.result.is_ok()); + let out = durable.call("run", &[]); + assert_eq!(out.json().unwrap(), serde_json::json!(6)); +} + +#[test] +fn heap_bytes_shrinks_after_collect_garbage() { + let rt = Runtime::make(); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + // Allocate a large graph pinned via a Root. + let big_root = session + .enter(|ctx| { + let big = ctx + .eval_module( + "const arr = []; for (let i = 0; i < 2000; i++) arr.push({ i, text: 'payload_' + i + '_' + 'x'.repeat(32) }); return arr;", + "big.js", + ) + .unwrap(); + ctx.root(big).unwrap() + }) + .unwrap(); + + let before = session.heap_bytes(); + assert!(before > 100_000, "expected large live heap, got {before}"); + + // Unroot and collect garbage -> live heap bytes must shrink substantially. + session.unroot(&[big_root]); + session.collect_garbage(); + + let after = session.heap_bytes(); + assert!( + after < before / 2, + "expected heap_bytes to shrink after collect_garbage: before={before}, after={after}" + ); +} + +#[test] +fn eval_compiled_multi_module_stacks_in_live_session() { + let rt = Runtime::make(); + let mod_b = rt + .compile_module( + r#" + function explode() { + throw new Error("boom in b"); + } + return { explode }; + "#, + "mod_b.js", + ) + .unwrap(); + let mod_a = rt + .compile_module( + r#" + function invoke() { + return __modB.explode(); + } + return { invoke }; + "#, + "mod_a.js", + ) + .unwrap(); + + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + // Install mod_b via LiveSession::enter + set_global, then load mod_a via eval_compiled. + session + .enter(|ctx| { + let b = ctx.eval_compiled(&mod_b).unwrap(); + ctx.set_global("__modB", b).unwrap(); + }) + .unwrap(); + + let mod_a_runner = rt + .compile_module("return __modA.invoke();", "entry.js") + .unwrap(); + + session + .enter(|ctx| { + let a = ctx.eval_compiled(&mod_a).unwrap(); + ctx.set_global("__modA", a).unwrap(); + }) + .unwrap(); + + let outcome = session.eval_compiled(&mod_a_runner); + let diag = outcome.result.expect_err("expected thrown error"); + let msg = diag.message.to_string_lossy(); + assert!(msg.contains("boom in b"), "msg: {msg}"); + assert!( + msg.contains("mod_b.js"), + "expected mod_b.js frame in: {msg}" + ); + assert!( + msg.contains("mod_a.js"), + "expected mod_a.js frame in: {msg}" + ); + assert!( + msg.contains("entry.js"), + "expected entry.js frame in: {msg}" + ); + // Normal thrown JS error must NOT leave LiveSession fatal! + assert!(!session.is_fatal()); + + // LiveSession::eval_module also works cleanly after a caught/reported module throw. + let ok = session.eval_module("return 21 * 2;", "calc.js"); + assert_eq!(ok.json().unwrap(), serde_json::json!(42)); +} + +#[test] +fn live_session_startup_errors_return_err() { + let rt = Runtime::make(); + let parse_err = rt + .live_session("return {", &ProgramOptions::new()) + .err() + .expect("parse error should return Err"); + assert_eq!(parse_err.kind, DiagnosticKind::ParseError); + + let throw_err = rt + .live_session("throw new Error('startup fail');", &ProgramOptions::new()) + .err() + .expect("top-level throw should return Err"); + assert_eq!(throw_err.kind, DiagnosticKind::ExecutionFailure); + assert!(throw_err.message.to_string_lossy().contains("startup fail")); +} From 08925f5503995a215f36f67cded65da41d957146 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:05:41 +1000 Subject: [PATCH 2/2] fix(rust): address PR #202 review findings for LiveSession & HostCtx - Fix cyclic `Error` stack overflow in `HostCtx::format_val` by threading `seen`, `depth + 1`, and remaining length budget through `peek_str_prop`; bound strings/regexes/keys, close truncated strings cleanly, and fix empty-prefix sparse array formatting (`[...]`). - Add `LiveSession::take_logs()` and `take_unhandled_rejections()`, and drop `vm.session` after startup so top-level return values are not pinned. - Preserve pre-existing `global_map` entries around lazy built-in materialization in `get_global`, `set_global`, and `new_bytes`; track `resolved_globals` so later `load_module` calls never clobber custom globals; reject doomed values in `set_global`. - Re-check own enumerability (`own_slot`) in `HostCtx::for_each_own`'s slow path after getter invocations. - Poison `vm.fatal` on unwind in `CpuLeave::drop`, disable round-trip mode for `LiveSession`, defer `reclaim_local_fns` until after all `gc_sweep` bookkeeping, factor `gc_busy()`, avoid per-call `String` allocations on unwatched `local_fn` calls, take `&self` in `LiveSession::heap_bytes`, bounds-check `is_frozen`, and enforce `max_heap_bytes` on Rust-side `HostCtx::set` mutations. - Add regression tests for all fixes (including `SweepWeak`/`Sweep` doomed-slot rejection and `PSYCHOSCRIPT_ROUNDTRIP=1`). --- rust/crates/psychoscript/src/builtins/mod.rs | 6 + rust/crates/psychoscript/src/collector.rs | 71 ++-- rust/crates/psychoscript/src/heap.rs | 22 ++ rust/crates/psychoscript/src/host.rs | 6 +- rust/crates/psychoscript/src/live_session.rs | 186 +++++++++- rust/crates/psychoscript/src/program.rs | 11 +- rust/crates/psychoscript/src/reach.rs | 5 + rust/crates/psychoscript/src/session.rs | 200 ++++++++--- rust/crates/psychoscript/src/vm.rs | 39 +- .../crates/psychoscript/tests/live_session.rs | 335 ++++++++++++++++-- 10 files changed, 768 insertions(+), 113 deletions(-) diff --git a/rust/crates/psychoscript/src/builtins/mod.rs b/rust/crates/psychoscript/src/builtins/mod.rs index 82823e33..3c9d7fb6 100644 --- a/rust/crates/psychoscript/src/builtins/mod.rs +++ b/rust/crates/psychoscript/src/builtins/mod.rs @@ -208,6 +208,12 @@ pub fn ensure(vm: &mut Vm, bit: u16) { } } +/// Whether `name` triggers any lazy built-in group not yet loaded in `vm`. +pub(crate) fn has_unloaded_global(vm: &Vm, name: &str) -> bool { + LAZY.iter() + .any(|(bit, names, _)| vm.realm.std.loaded & *bit == 0 && names.contains(&name)) +} + /// Installs the lazy groups `name` brings (one defines it, others add to it); false when no group does. pub fn ensure_global(vm: &mut Vm, name: &str) -> bool { let mut found = false; diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index fbb4cfcd..f46d0d40 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1347,15 +1347,19 @@ impl Vm { <= self.heap.base.get().len() + (chunks - 1) * HEAP_CHUNK } + /// Whether a conversion replay or native JSON walk currently holds unrooted values in Rust locals. + #[inline] + fn gc_busy(&self) -> bool { + self.replay_meter.is_some() + || !self.replay.is_empty() + || self.convert_req.is_some() + || self.json_walk != 0 + } + /// A safe point the run reached with `suspend_wanted` set: takes a collection step if one is due. Returns whether /// the collector alone wanted the stop, so the run goes on. pub(crate) fn gc_point(&mut self) -> bool { - // A conversion's replay or a native JSON walk holds values in Rust locals. - let busy = self.replay_meter.is_some() - || !self.replay.is_empty() - || self.convert_req.is_some() - || self.json_walk != 0; - if self.gc.requested && !busy { + if self.gc.requested && !self.gc_busy() { self.gc.requested = false; self.gc_step(); } @@ -1372,11 +1376,7 @@ impl Vm { /// The run stopped to wait for the host: collects now, a whole cycle, if it has made enough since its last one /// (`IDLE_ROOM`) and is small enough for that to be quick (`IDLE_MAX`). pub(crate) fn gc_idle(&mut self) { - let busy = self.replay_meter.is_some() - || !self.replay.is_empty() - || self.convert_req.is_some() - || self.json_walk != 0; - if busy || stress() { + if self.gc_busy() || stress() { return; } let used = self.gc_used(); @@ -1454,11 +1454,7 @@ impl Vm { /// Runs one bounded incremental GC step when a cycle is running or due and the VM is not busy. pub(crate) fn gc_step_bounded(&mut self) { - let busy = self.replay_meter.is_some() - || !self.replay.is_empty() - || self.convert_req.is_some() - || self.json_walk != 0; - if busy { + if self.gc_busy() { return; } if self.gc.phase == Phase::Idle && !self.gc.requested && self.gc_used() < self.gc.trigger { @@ -1476,11 +1472,7 @@ impl Vm { /// Finishes any in-progress GC cycle and runs one complete /// `Idle -> Mark -> SweepWeak -> Sweep -> Trim -> Idle` cycle, when the VM is not busy. pub(crate) fn gc_collect_full(&mut self) { - let busy = self.replay_meter.is_some() - || !self.replay.is_empty() - || self.convert_req.is_some() - || self.json_walk != 0; - if busy { + if self.gc_busy() { return; } if self.gc.phase != Phase::Idle { @@ -1489,6 +1481,26 @@ impl Vm { self.gc_finish_cycle(); } + #[cfg(test)] + pub(crate) fn gc_start_for_test(&mut self) { + if self.gc.phase != Phase::Idle { + self.gc_finish_cycle(); + } + self.gc_start(); + } + + #[cfg(test)] + pub(crate) fn gc_step_one_for_test(&mut self) -> bool { + self.gc.debt = 1; + self.gc_step(); + self.gc.phase == Phase::Idle + } + + #[cfg(test)] + pub(crate) fn gc_in_sweep_past(&self, id: Id) -> bool { + self.gc.phase == Phase::Sweep && (id as usize) < self.gc.obj_sweep.0 + } + fn gc_finish_cycle(&mut self) { loop { self.gc.debt = MAX_WORK; @@ -1626,7 +1638,16 @@ impl Vm { } /// Frees white slots from where the sweep stopped, objects first, then cells, then strings. + /// Drops reclaimed `LiveSession` local closures only after all GC bookkeeping finishes so a + /// panicking user `Drop` impl cannot leave collector invariants half-updated. fn gc_sweep(&mut self, budget: usize) { + let reclaimed_locals = self.gc_sweep_inner(budget); + if !reclaimed_locals.is_empty() { + crate::live_session::reclaim_local_fns(&reclaimed_locals); + } + } + + fn gc_sweep_inner(&mut self, budget: usize) -> Vec<(u64, u32, u32)> { #[cfg(feature = "gc-stats")] self.publish_stats(); let mut work = 0; @@ -1696,9 +1717,6 @@ impl Vm { at += 1; } self.gc.obj_sweep.0 = at; - if !reclaimed_locals.is_empty() { - crate::live_session::reclaim_local_fns(&reclaimed_locals); - } if self.gc.free.len() > freed_objs && !self.lazy_builtins.is_empty() { let color = &self.heap.marks.color; self.lazy_builtins @@ -1728,7 +1746,7 @@ impl Vm { self.gc.live -= self.gc.free_len() + self.gc.cell_free.len() + self.atoms.gc.free.len() - free; if work >= budget { - return; + return reclaimed_locals; } if self.gc.trim.is_none() && self.gc_sparse() { let old = std::mem::take(&mut self.gc.free); @@ -1743,7 +1761,7 @@ impl Vm { })); } if self.gc.trim.is_some() && !self.gc_trim(budget - work) { - return; + return reclaimed_locals; } self.atoms.end_cycle(); self.gc.phase = Phase::Idle; @@ -1753,6 +1771,7 @@ impl Vm { self.gc.live + self.gc.live.max(FLOOR) }; self.gc_poll(); + reclaimed_locals } } diff --git a/rust/crates/psychoscript/src/heap.rs b/rust/crates/psychoscript/src/heap.rs index 3775848d..ec72e686 100644 --- a/rust/crates/psychoscript/src/heap.rs +++ b/rust/crates/psychoscript/src/heap.rs @@ -208,6 +208,28 @@ impl Vm { } } + /// End of a `LiveSession::enter` call: charges arena growth, measures whenever the limit + /// could have been exceeded (including Rust-side `HostCtx::set` mutations), and updates + /// `measure_heap` waits when enabled. + pub(crate) fn heap_enter_end(&mut self) { + if self.fatal.is_some() || self.heap_meter.is_none() { + return; + } + self.heap_charge(0); + let over_estimate = self.heap_meter.as_deref().is_some_and(|m| { + m.due() + || m.limit.is_some_and(|limit| { + m.live + .is_none_or(|live| live.saturating_add(m.debt) > limit) + }) + }); + if over_estimate { + self.heap_measure(); + } else { + self.heap_wait(); + } + } + fn heap_limited(&self) -> bool { self.heap_meter .as_deref() diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index a177cd79..57f896d8 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -1608,7 +1608,7 @@ fn hosted(vm: &Vm, id: Id) -> Option { } let entry = vm.host.functions.get(*index as usize)?; match &entry.f { - Callee::Fn(f) if !entry.installed && !entry.reclaimable => Some(f.clone()), + Callee::Fn(f) if !entry.installed => Some(f.clone()), _ => None, } } @@ -2551,8 +2551,8 @@ pub(crate) fn host_native(vm: &mut Vm, this: Value, args: &[Value], callee: Id) generation, } = entry.f { - let label = entry.label.clone(); - return crate::live_session::call_local(vm, live_id, slot, generation, this, args, &label); + let label = vm.host.shared.watched().then(|| entry.label.clone()); + return crate::live_session::call_local(vm, live_id, slot, generation, this, args, label); } if matches!(entry.f, Callee::Reclaimed) { return Err(vm.type_error("Local host function has been reclaimed.")); diff --git a/rust/crates/psychoscript/src/live_session.rs b/rust/crates/psychoscript/src/live_session.rs index af1ea119..31c5336e 100644 --- a/rust/crates/psychoscript/src/live_session.rs +++ b/rust/crates/psychoscript/src/live_session.rs @@ -150,7 +150,7 @@ pub(crate) fn call_local( generation: u32, this: Value, args: &[Value], - label: &str, + label: Option, ) -> crate::vm::Res { if !vm.live.as_deref().is_some_and(|l| l.live_id == live_id) { return Err(vm.type_error("Local host function does not belong to this LiveSession.")); @@ -158,14 +158,19 @@ pub(crate) fn call_local( let Some(func) = lookup_local_fn(live_id, slot, generation) else { return Err(vm.type_error("Local host function has been reclaimed.")); }; - let call = vm.host.next_call(); - vm.host.enter_sync(call, label.to_owned()); + let watched = label.is_some(); + if let Some(label) = label { + let call = vm.host.next_call(); + vm.host.enter_sync(call, label); + } let span = vm.host_span(); let mut ctx = HostCtx::new(vm, span); let r = (func)(&mut ctx, Args::new(this, args)); let (vm, span) = ctx.into_parts(); vm.end_host_span(span); - vm.host.leave_sync(); + if watched { + vm.host.leave_sync(); + } r.map(|v| v.v).map_err(|e| e.v) } @@ -353,10 +358,18 @@ impl LiveSession { let mut program = Program::live_session(rt, code, options); let outcome = program.drive_session(|_| {}); match outcome.result { - Ok(_) => Ok(Self { - program, - _not_send: PhantomData, - }), + Ok(_) => { + // LiveSession does not expose durable Session::call exports; drop SessionState + // after startup so top-level return values are never pinned and later eval_compiled + // / eval_module calls cross their return values normally. + if let Some(vm) = program.session_vm() { + vm.session = None; + } + Ok(Self { + program, + _not_send: PhantomData, + }) + } Err(diag) => Err(diag), } } @@ -387,6 +400,12 @@ impl LiveSession { /// runs `f(&mut ctx)`, drains ready microtasks/jobs, runs pending/idle GC and heap-limit /// accounting when not fatal, and returns `Ok(r)` or `Err(diag)` if a fatal limit/error /// occurred (which also sticks for all subsequent entries). + /// + /// Garbage collection does not run while `f(&mut ctx)` executes (so unrooted [`Val`] locals + /// on the Rust stack stay valid, bounded by `MAX_OBJECTS` per single entry); collection runs + /// immediately after `f` returns. In long-lived render loops, call [`LiveSession::take_logs`] + /// and [`LiveSession::take_unhandled_rejections`] periodically so buffered logs and rejected + /// promises do not accumulate. pub fn enter(&mut self, f: impl FnOnce(&mut HostCtx<'_>) -> R) -> Result { let probe = 0u8; let vm = self.vm_mut(); @@ -405,13 +424,22 @@ impl LiveSession { vm.stack_budget = crate::run::RUN_STACK_BUDGET; vm.start_handover_fuel(); - // Ensures `CpuMeter::leave` runs even if `f` panics. + // Ensures `CpuMeter::leave` runs even if `f` panics, and poisons the VM on unwind so a + // caught panic cannot leave a half-unwound VM usable. struct CpuLeave<'v>(&'v mut Vm); impl Drop for CpuLeave<'_> { fn drop(&mut self) { if let Some(c) = &mut self.0.cpu { c.leave(false); } + if std::thread::panicking() { + self.0.fatal.get_or_insert_with(|| { + ( + crate::DiagnosticKind::ExecutionFailure, + "The host panicked during a live session call.".into(), + ) + }); + } } } let guard = CpuLeave(vm); @@ -433,9 +461,7 @@ impl LiveSession { guard.0.gc_point(); } guard.0.gc_idle(); - if guard.0.heap_meter.is_some() { - guard.0.heap_point(0); - } + guard.0.heap_enter_end(); } #[cfg(feature = "gc-stats")] guard.0.publish_stats(); @@ -449,6 +475,30 @@ impl LiveSession { Ok(result) } + /// Drains and returns all lines logged via `console.*` since the last call. + /// + /// Call periodically in long-lived render loops to avoid unbounded log buffering. + pub fn take_logs(&mut self) -> Vec { + std::mem::take(&mut self.vm_mut().logs) + .into_iter() + .map(|l| crate::strings::host_text(&l).into_owned()) + .collect() + } + + /// Drains all unhandled promise rejections recorded so far and returns their formatted reasons + /// without invoking JavaScript. + /// + /// Because queued unhandled rejections are GC roots until drained, call periodically in + /// long-lived render loops so rejected promises and their reasons can be collected. + pub fn take_unhandled_rejections(&mut self) -> Vec { + let vm = self.vm_mut(); + let unhandled = std::mem::take(&mut vm.host.unhandled); + unhandled + .into_iter() + .map(|(_, reason)| crate::session::format_val_readonly(vm, reason)) + .collect() + } + /// Unpins a slice of [`Root`] handles in O(1) per root without entering JS. pub fn unroot(&mut self, roots: &[Root]) { if let Some(live) = self.vm_mut().live.as_deref_mut() { @@ -476,8 +526,8 @@ impl LiveSession { /// Measures and returns the live reachable heap bytes of this session in the size model of /// [`Limits::max_heap_bytes`](crate::Limits::max_heap_bytes). - pub fn heap_bytes(&mut self) -> usize { - let vm = self.vm_mut(); + pub fn heap_bytes(&self) -> usize { + let vm = self.vm(); let bytes = crate::heap::measure(vm); vm.host.run.set_heap_bytes(bytes); bytes as usize @@ -647,3 +697,111 @@ const _: () = { is_send::(); is_send::(); }; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{FROZEN, Kind, Obj}; + + #[test] + fn doomed_values_rejected_in_sweep_weak_and_sweep() { + let rt = Runtime::make(); + let mut session = rt + .live_session( + "const wm = new WeakMap(); wm.set({}, 1); return undefined;", + &ProgramOptions::new(), + ) + .unwrap(); + + // Pin a live object and also create an unreferenced (doomed) object directly on the heap. + let (live_id, doomed_id, live_root) = { + let vm = session.vm_mut(); + let live_obj = vm.alloc(Obj::new(None, Kind::Ordinary)); + vm.heap[live_obj as usize].flags |= FROZEN; + let doomed_obj = vm.alloc(Obj::new(None, Kind::Ordinary)); + vm.heap[doomed_obj as usize].flags |= FROZEN; + let live_root = vm + .live + .as_deref_mut() + .unwrap() + .insert(Value::Obj(live_obj)) + .unwrap(); + (live_obj, doomed_obj, live_root) + }; + + // Run GC up to SweepWeak (or Sweep if WeakMap wasn't reached): allocate a WeakMap root so + // marking reaches a weak table and enters SweepWeak (`Phase::Mark && !heap.marking`). + let wm_root = session + .enter(|ctx| { + let wm = ctx + .eval_module( + "const m = new WeakMap(); for (let i = 0; i < 64; i++) m.set({}, i); return m;", + "wm.js", + ) + .unwrap(); + ctx.root(wm).unwrap() + }) + .unwrap(); + + // Advance incremental GC step by step to observe SweepWeak and Sweep phases. + let vm = session.vm_mut(); + // Force a fresh cycle, then allocate enough transient objects after `live_id` so the + // next `Sweep` spans multiple steps (pausing with `live_id < obj_sweep.0 < doomed_2`). + vm.gc_collect_full(); + for _ in 0..4000 { + vm.alloc(Obj::new(None, Kind::Ordinary)); + } + let doomed_2 = vm.alloc(Obj::new(None, Kind::Ordinary)); + vm.heap[doomed_2 as usize].flags |= FROZEN; + + // Start a cycle manually via gc_step_bounded by requesting collection, then step until + // `doomed_2` becomes doomed (in SweepWeak or ahead of obj_sweep cursor in Sweep). + let mut saw_doomed = false; + let mut saw_live_behind_sweep = false; + // Trigger a cycle via allocation or directly starting GC. + vm.gc_start_for_test(); + for _ in 0..10_000 { + if vm.gc_is_doomed(Value::Obj(doomed_2)) { + saw_doomed = true; + // Verify HostCtx rejects doomed_2 for root, get_root, is_frozen, object_id, and set_global. + let mut ctx = HostCtx::new(vm, None); + let doomed_val = Val::of(Value::Obj(doomed_2)); + assert!(ctx.root(doomed_val).is_none()); + assert!(!ctx.is_frozen(doomed_val)); + assert!(ctx.object_id(doomed_val).is_none()); + // Live root must STILL resolve cleanly! + let kept = ctx.get_root(live_root).expect("live root must stay valid"); + assert!(ctx.is_frozen(kept)); + assert!(ctx.object_id(kept).is_some()); + // Also verify a synthetic root pointing to doomed_2 is rejected by get_root! + let synthetic = ctx + .vm_mut() + .live + .as_deref_mut() + .unwrap() + .insert(Value::Obj(doomed_2)) + .unwrap(); + assert!(ctx.get_root(synthetic).is_none()); + ctx.unroot(synthetic); + } + if !vm.gc_is_doomed(Value::Obj(live_id)) && vm.gc_in_sweep_past(live_id) { + saw_live_behind_sweep = true; + let ctx = HostCtx::new(vm, None); + assert!(ctx.get_root(live_root).is_some()); + } + if vm.gc_step_one_for_test() { + break; + } + } + assert!( + saw_doomed, + "expected to observe doomed object during SweepWeak/Sweep" + ); + assert!( + saw_live_behind_sweep, + "expected to observe live object behind sweep cursor" + ); + let _ = doomed_id; + session.unroot(&[live_root, wm_root]); + } +} diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index ca4fef65..cd050266 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -521,7 +521,7 @@ impl Program { c.enter(); } r.vm.slice_start(&r.carried); - if round_trips(&self.shared) { + if round_trips(&self.shared, &r.vm) { r.vm.start_roundtrip(r.round_trip_every); } snapshot::restart_calls(&mut r.vm); @@ -632,7 +632,7 @@ impl Program { if r.vm.host.tasks.has_ready() { continue; } - if round_trips(&self.shared) && !r.vm.host.calls.is_empty() { + if round_trips(&self.shared, &r.vm) && !r.vm.host.calls.is_empty() { // A host stop: save and restore before waiting. r.vm.suspend_wanted = true; r.vm.suspended = true; @@ -923,9 +923,10 @@ impl Running { } } -/// Round-trip mode leaves alone a program that has a `Suspender`: its owner suspends it. -fn round_trips(shared: &Shared) -> bool { - roundtrip() && !shared.watched.load(Ordering::Relaxed) +/// Round-trip mode leaves alone a program that has a `Suspender` (its owner suspends it) and +/// non-snapshotable `LiveSession` runs. +fn round_trips(shared: &Shared, vm: &Vm) -> bool { + roundtrip() && !shared.watched.load(Ordering::Relaxed) && vm.live.is_none() } /// Whether the round-trip test mode is on: every run is saved to bytes and restored into a brand-new VM at every diff --git a/rust/crates/psychoscript/src/reach.rs b/rust/crates/psychoscript/src/reach.rs index b24ec20d..712545e8 100644 --- a/rust/crates/psychoscript/src/reach.rs +++ b/rust/crates/psychoscript/src/reach.rs @@ -46,6 +46,11 @@ pub fn roots_but(vm: &Vm, measuring: bool, visit: &mut impl FnMut(Ref)) { for a in &vm.global_names { t.atom(*a); } + if let Some(resolved) = &vm.resolved_globals { + for a in resolved.iter() { + t.atom(*a); + } + } if !measuring { // Built-in code (`Array.fromAsync`, no positions) and dynamically loaded named modules // (`p.source != 0`): their atoms were made after the permanent ones, so they live by their diff --git a/rust/crates/psychoscript/src/session.rs b/rust/crates/psychoscript/src/session.rs index 18c1e9f8..5a74e912 100644 --- a/rust/crates/psychoscript/src/session.rs +++ b/rust/crates/psychoscript/src/session.rs @@ -460,7 +460,16 @@ impl<'a> HostCtx<'a> { self.vm .check_assignment_at(&o.v, key, &v.v) .map_err(Val::of)?; + let before = match o.v { + Value::Obj(id) if self.vm.heap_meter.is_some() => { + Some((id, self.vm.heap[id as usize].props.len())) + } + _ => None, + }; let setter = self.vm.op_write(&o.v, key, v.v).map_err(Val::of)?; + if let Some((id, before_len)) = before { + self.vm.charge_props(id, before_len); + } self.write(o, setter, v) } @@ -566,16 +575,24 @@ impl<'a> HostCtx<'a> { self.eval_compiled(&compiled) } - /// Whether `v` is a frozen object (`Object.freeze`). O(1) flag check; `false` for primitives. + /// Whether `v` is an object frozen via `Object.freeze`. O(1) `FROZEN` flag check; returns + /// `false` for primitives, doomed/freed slots, and objects made non-extensible without + /// `Object.freeze`. pub fn is_frozen(&self, v: Val<'a>) -> bool { matches!( v.v, - Value::Obj(id) if self.vm.heap[id as usize].flags & crate::object::FROZEN != 0 + Value::Obj(id) + if (id as usize) < self.vm.heap.len() + && !self.vm.gc_is_doomed(v.v) + && self.vm.heap[id as usize].flags & crate::object::FROZEN != 0 ) } - /// A unique, ABA-safe numeric identity for a live heap object within this VM (valid across - /// GC slot reuse), or `None` for primitives. + /// A unique, ABA-safe numeric identity for a live heap object within this VM instance (valid + /// across GC slot reuse), or `None` for primitives or doomed slots. + /// + /// Identities are scoped to the current VM instance and reset across + /// [`Session::save`] / [`Runtime::restore_session`]. pub fn object_id(&self, v: Val<'a>) -> Option { match v.v { Value::Obj(id) => self.vm.object_id(id), @@ -585,6 +602,11 @@ impl<'a> HostCtx<'a> { /// Allocates a new `Uint8Array` populated directly from `bytes` without entering JS. pub fn new_bytes(&mut self, bytes: &[u8]) -> Val<'a> { + if self.vm.realm.std.loaded & crate::builtins::LAZY_BYTES == 0 { + self.vm.preserving_global_map(|vm| { + crate::builtins::ensure(vm, crate::builtins::LAZY_BYTES); + }); + } Val::of(crate::builtins::bytes::new_bytes( self.vm, bytes.to_vec(), @@ -593,17 +615,27 @@ impl<'a> HostCtx<'a> { } /// Reads global `name` directly from the VM's global table (lazily initializing built-in or - /// host globals if needed). Returns `Ok(Val::undefined())` if no such global exists. + /// host globals if needed without clobbering pre-existing custom globals). Returns + /// `Ok(Val::undefined())` if no such global exists. pub fn get_global(&mut self, name: &str) -> Result, Val<'a>> { if self.vm.fatal.is_some() { return Err(Val::undefined()); } let key = self.key(name); - if !self.vm.global_map.contains_key(&key) - && (crate::host::has_host_global(self.vm, name) - || !crate::builtins::ensure_global(self.vm, name)) - { - crate::host::define_host_global_by_name(self.vm, name); + if !crate::strings::has_mark(name) { + if crate::builtins::has_unloaded_global(self.vm, name) { + self.vm.preserving_global_map(|vm| { + crate::builtins::ensure_global(vm, name); + }); + } + let unmapped = !self.vm.global_map.contains_key(&key); + let first_host_override = + crate::host::has_host_global(self.vm, name) && !self.vm.is_global_resolved(key); + if (unmapped || first_host_override) + && crate::host::define_host_global_by_name(self.vm, name) + { + self.vm.mark_global_resolved(key); + } } let val = self .vm @@ -620,12 +652,21 @@ impl<'a> HostCtx<'a> { if self.vm.fatal.is_some() { return Err(Val::undefined()); } + if self.vm.gc_is_doomed(v.v) { + return Ok(()); + } + if !crate::strings::has_mark(name) && crate::builtins::has_unloaded_global(self.vm, name) { + self.vm.preserving_global_map(|vm| { + crate::builtins::ensure_global(vm, name); + }); + } let key = self.key(name); self.vm.gc_shade_atom(key); if self.vm.heap.marking { self.vm.gc_shade_value(v.v); } self.vm.global_map.insert(key, v.v); + self.vm.mark_global_resolved(key); for (i, &gname) in self.vm.global_names.iter().enumerate() { if gname == key { self.vm.globals[i] = v.v; @@ -667,8 +708,12 @@ impl<'a> HostCtx<'a> { } return Ok(()); } + let is_ns = self.vm.is_namespace(id); let keys = self.vm.own_keys(id); for key in keys { + if !is_ns && !self.vm.own_slot(id, key).is_some_and(|s| s.enumerable) { + continue; + } let val = { let read = self.vm.op_read(&o.v, key).map_err(Val::of)?; self.read(o, read)? @@ -705,20 +750,33 @@ impl<'a> HostCtx<'a> { } } -/// Safe, non-JS-invoking human-readable formatting for [`HostCtx::format_val`]. -fn format_val_readonly(vm: &Vm, v: Value) -> String { +/// Safe, non-JS-invoking human-readable formatting for [`HostCtx::format_val`] and +/// [`LiveSession::take_unhandled_rejections`](crate::LiveSession::take_unhandled_rejections). +pub(crate) fn format_val_readonly(vm: &Vm, v: Value) -> String { match v { Value::Undef | Value::Uninit => "undefined".to_owned(), Value::Null => "null".to_owned(), Value::Bool(b) => (if b { "true" } else { "false" }).to_owned(), Value::Num(n) => crate::value::num_to_string(n), - Value::Str(s) => crate::strings::host_text(vm.text(s)).into_owned(), + Value::Str(s) => { + let text = crate::strings::host_text(vm.text(s)); + let mut out = String::new(); + push_bounded(&mut out, &text, FORMAT_MAX_LEN); + out + } Value::Sym(s) => crate::ops::symbol_text(s).to_owned(), - Value::Big(id) => format!("{}n", vm.big_text(id)), + Value::Big(id) => { + let mut out = String::new(); + push_bounded(&mut out, &vm.big_text(id), FORMAT_MAX_LEN); + if out.len() < FORMAT_MAX_LEN { + out.push('n'); + } + out + } Value::Obj(_) => { let mut out = String::new(); let mut seen = Vec::new(); - format_readonly_inner(vm, v, &mut out, &mut seen, 0); + format_readonly_inner(vm, v, &mut out, &mut seen, 0, FORMAT_MAX_LEN); out } } @@ -727,14 +785,33 @@ fn format_val_readonly(vm: &Vm, v: Value) -> String { const FORMAT_MAX_DEPTH: usize = 16; const FORMAT_MAX_LEN: usize = 4096; +/// Appends `s` to `out` up to `max_len` bytes, appending `"..."` if truncated. +fn push_bounded(out: &mut String, s: &str, max_len: usize) { + if out.len() >= max_len { + return; + } + let avail = max_len - out.len(); + if s.len() <= avail { + out.push_str(s); + return; + } + let mut cut = avail; + while cut > 0 && !s.is_char_boundary(cut) { + cut -= 1; + } + out.push_str(&s[..cut]); + out.push_str("..."); +} + fn format_readonly_inner( vm: &Vm, v: Value, out: &mut String, seen: &mut Vec, depth: usize, + max_len: usize, ) { - if out.len() >= FORMAT_MAX_LEN { + if out.len() >= max_len { return; } match v { @@ -754,17 +831,19 @@ fn format_readonly_inner( '\t' => out.push_str("\\t"), c => out.push(c), } - if out.len() >= FORMAT_MAX_LEN { - out.push_str("..."); + if out.len() >= max_len { + out.push_str("...\""); return; } } out.push('"'); } - Value::Sym(s) => out.push_str(crate::ops::symbol_text(s)), + Value::Sym(s) => push_bounded(out, crate::ops::symbol_text(s), max_len), Value::Big(id) => { - out.push_str(&vm.big_text(id)); - out.push('n'); + push_bounded(out, &vm.big_text(id), max_len); + if out.len() < max_len { + out.push('n'); + } } Value::Obj(id) => { if depth >= FORMAT_MAX_DEPTH { @@ -779,17 +858,22 @@ fn format_readonly_inner( let obj = &vm.heap[id as usize]; match &obj.kind { Kind::Error(_) => { - let name = - peek_str_prop(vm, id, vm.names.name).unwrap_or_else(|| "Error".to_owned()); - let msg = peek_str_prop(vm, id, vm.names.message).unwrap_or_default(); + let budget = max_len.saturating_sub(out.len()); + let name = peek_str_prop(vm, id, vm.names.name, seen, depth + 1, budget) + .unwrap_or_else(|| "Error".to_owned()); + let msg_budget = budget.saturating_sub(name.len()); + let msg = peek_str_prop(vm, id, vm.names.message, seen, depth + 1, msg_budget) + .unwrap_or_default(); if msg.is_empty() { - out.push_str(&name); + push_bounded(out, &name, max_len); } else if name.is_empty() { - out.push_str(&msg); + push_bounded(out, &msg, max_len); } else { - out.push_str(&name); - out.push_str(": "); - out.push_str(&msg); + push_bounded(out, &name, max_len); + if out.len() < max_len { + out.push_str(": "); + push_bounded(out, &msg, max_len); + } } } Kind::Array(items) => { @@ -798,16 +882,19 @@ fn format_readonly_inner( if i > 0 { out.push_str(", "); } - if out.len() >= FORMAT_MAX_LEN { + if out.len() >= max_len { out.push_str("..."); break; } if !matches!(item, Value::Uninit) { - format_readonly_inner(vm, item, out, seen, depth + 1); + format_readonly_inner(vm, item, out, seen, depth + 1, max_len); } } if obj.flags & crate::object::SPARSE != 0 { - out.push_str(", ..."); + if !items.is_empty() { + out.push_str(", "); + } + out.push_str("..."); } out.push(']'); } @@ -817,7 +904,7 @@ fn format_readonly_inner( out.push_str("[Function (anonymous)]"); } else { out.push_str("[Function: "); - out.push_str(&n); + push_bounded(out, &n, max_len); out.push(']'); } } @@ -827,7 +914,7 @@ fn format_readonly_inner( out.push_str("[Function (anonymous)]"); } else { out.push_str("[Function: "); - out.push_str(&n); + push_bounded(out, &n, max_len); out.push(']'); } } @@ -850,9 +937,11 @@ fn format_readonly_inner( } Kind::RegExp(r) => { out.push('/'); - out.push_str(&crate::strings::host_text(&r.source)); - out.push('/'); - out.push_str(&crate::strings::host_text(&r.flags)); + push_bounded(out, &crate::strings::host_text(&r.source), max_len); + if out.len() < max_len { + out.push('/'); + push_bounded(out, &crate::strings::host_text(&r.flags), max_len); + } } Kind::Map(m) => { out.push_str("Map("); @@ -875,7 +964,7 @@ fn format_readonly_inner( { continue; } - if out.len() >= FORMAT_MAX_LEN { + if out.len() >= max_len { out.push_str(", ..."); break; } @@ -885,12 +974,19 @@ fn format_readonly_inner( } else { out.push_str(", "); } - out.push_str(&crate::strings::host_text(vm.atoms.text(p.key))); + push_bounded( + out, + &crate::strings::host_text(vm.atoms.text(p.key)), + max_len, + ); + if out.len() >= max_len { + break; + } out.push_str(": "); if p.flags & crate::object::ACCESSOR != 0 { out.push_str("[Getter]"); } else { - format_readonly_inner(vm, p.value(), out, seen, depth + 1); + format_readonly_inner(vm, p.value(), out, seen, depth + 1, max_len); } } if !first { @@ -905,8 +1001,16 @@ fn format_readonly_inner( } } -/// Walks `id`'s prototype chain without invoking getters to read a plain string property. -fn peek_str_prop(vm: &Vm, mut id: crate::value::Id, key: crate::strings::Atom) -> Option { +/// Walks `id`'s prototype chain without invoking getters to read a plain string property, threading +/// `seen`, `depth`, and `max_len` so cyclic `Error` prototypes cannot overflow the stack. +fn peek_str_prop( + vm: &Vm, + mut id: crate::value::Id, + key: crate::strings::Atom, + seen: &mut Vec, + depth: usize, + max_len: usize, +) -> Option { for _ in 0..64 { let obj = &vm.heap[id as usize]; if let Some(p) = obj.props.prop(key) { @@ -914,9 +1018,17 @@ fn peek_str_prop(vm: &Vm, mut id: crate::value::Id, key: crate::strings::Atom) - return None; } return match p.value() { - Value::Str(s) => Some(crate::strings::host_text(vm.text(s)).into_owned()), + Value::Str(s) => { + let mut buf = String::new(); + push_bounded(&mut buf, &crate::strings::host_text(vm.text(s)), max_len); + Some(buf) + } Value::Undef | Value::Uninit => None, - other => Some(format_val_readonly(vm, other)), + other => { + let mut buf = String::new(); + format_readonly_inner(vm, other, &mut buf, seen, depth, max_len); + Some(buf) + } }; } id = obj.proto?; diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index 78a96eb0..1d24257a 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -375,6 +375,9 @@ pub struct Vm { pub(crate) live: Option>, /// ABA-safe monotonic object identities (`HostCtx::object_id`), allocated lazily on first use. pub(crate) object_ids: std::cell::RefCell>>, + /// Globals explicitly resolved or written via `HostCtx::get_global` / `set_global`, so a + /// later `load_module` does not clobber them with a runtime host global. + pub(crate) resolved_globals: Option>>, } /// Distinct named module sources and exact load order of dynamically appended bytecode chunks. @@ -535,6 +538,7 @@ impl Vm { loaded_code: None, live: None, object_ids: std::cell::RefCell::new(None), + resolved_globals: None, } } @@ -681,7 +685,13 @@ impl Vm { let existing = self.atoms.lookup(name); let unmapped = existing.is_none_or(|k| !saved_keys.contains(&k)); let first_host_override = crate::host::has_host_global(self, name) - && existing.is_none_or(|k| !referenced_globals.contains(&k)); + && existing.is_none_or(|k| { + !referenced_globals.contains(&k) + && !self + .resolved_globals + .as_deref() + .is_some_and(|s| s.contains(&k)) + }); if unmapped || first_host_override { crate::host::define_host_global_by_name(self, name); } @@ -5422,6 +5432,33 @@ impl Vm { self.reference_error(&format!("Cannot access '{n}' before initialization.")) } + /// Runs `f` (typically lazy built-in initialization) while preserving every pre-existing + /// `global_map` entry with GC barriers, so sibling built-ins never overwrite custom globals. + pub(crate) fn preserving_global_map(&mut self, f: impl FnOnce(&mut Vm)) { + let saved: Vec<(Atom, Value)> = self.global_map.iter().map(|(&k, &v)| (k, v)).collect(); + f(self); + for (k, v) in saved { + self.gc_shade_atom(k); + if self.heap.marking { + self.gc_shade_value(v); + } + self.global_map.insert(k, v); + } + } + + pub(crate) fn is_global_resolved(&self, key: Atom) -> bool { + self.global_names.contains(&key) + || self + .resolved_globals + .as_deref() + .is_some_and(|s| s.contains(&key)) + } + + pub(crate) fn mark_global_resolved(&mut self, key: Atom) { + self.gc_shade_atom(key); + self.resolved_globals.get_or_insert_default().insert(key); + } + /// Returns a unique, ABA-safe numeric identity for live object `id`, or `None` if `id` is /// already freed or doomed in the current GC cycle. pub(crate) fn object_id(&self, id: Id) -> Option { diff --git a/rust/crates/psychoscript/tests/live_session.rs b/rust/crates/psychoscript/tests/live_session.rs index 2f344375..54d21d40 100644 --- a/rust/crates/psychoscript/tests/live_session.rs +++ b/rust/crates/psychoscript/tests/live_session.rs @@ -22,28 +22,9 @@ impl Drop for DropGuard { fn enter_borrows_local_stack_and_drains_microtasks() { let rt = Runtime::make(); let mut session = rt - .live_session( - r#" - let log = []; - function record(x) { - log.push("sync:" + x); - Promise.resolve(x).then(v => { - log.push("micro1:" + v); - return v * 2; - }).then(v => { - log.push("micro2:" + v); - }); - return x + 1; - } - function getLog() { return log; } - return { record, getLog }; - "#, - &ProgramOptions::new(), - ) + .live_session("undefined;", &ProgramOptions::new()) .expect("live session should start"); - // Capture the functions into globals or via eval_compiled; here let's register via eval_module - // or test via globals set in top-level. Wait: let's also test top-level globals directly! let mut local_vec: Vec = Vec::new(); let out = session .enter(|ctx| { @@ -895,3 +876,317 @@ fn live_session_startup_errors_return_err() { assert_eq!(throw_err.kind, DiagnosticKind::ExecutionFailure); assert!(throw_err.message.to_string_lossy().contains("startup fail")); } + +#[test] +fn format_val_handles_cyclic_error_long_strings_and_empty_sparse_arrays() { + let rt = Runtime::make(); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + session + .enter(|ctx| { + // Cyclic Error: E.prototype.name = e must NOT stack-overflow format_val! + let cyc_err = ctx + .eval_module( + r#" + class E extends Error {} + const e = new E("boom"); + E.prototype.name = e; + return e; + "#, + "cyclic_err.js", + ) + .unwrap(); + let formatted = ctx.format_val(cyc_err); + assert!( + formatted.contains("[Circular]") && formatted.contains("boom"), + "unexpected cyclic error formatting: {formatted}" + ); + + // Cyclic Error via message property as well. + let cyc_msg = ctx + .eval_module( + r#" + class E2 extends Error {} + const e = new E2(); + E2.prototype.message = e; + return e; + "#, + "cyclic_msg.js", + ) + .unwrap(); + let formatted_msg = ctx.format_val(cyc_msg); + assert!( + formatted_msg.contains("[Circular]"), + "unexpected cyclic message formatting: {formatted_msg}" + ); + + // Truncated long string closes quotes cleanly when nested, and bounds top-level strings. + let huge = ctx + .eval_module( + r#" + const s = "a".repeat(10000); + return { s, nested: [s] }; + "#, + "huge_str.js", + ) + .unwrap(); + let s_val = ctx.get(huge, "s").unwrap(); + let top = ctx.format_val(s_val); + assert!( + top.len() <= 4100 && top.ends_with("..."), + "top len={}", + top.len() + ); + + let nested_val = ctx.get(huge, "nested").unwrap(); + let nested = ctx.format_val(nested_val); + assert!(nested.len() <= 4120, "nested len={}", nested.len()); + assert!( + nested.contains("...\""), + "nested should close truncated string: {nested}" + ); + + // Sparse array with empty dense prefix should format as `[...]` rather than `[, ...]`. + let sparse = ctx + .eval_module("const a = []; a[20_000_000] = 1; return a;", "sparse.js") + .unwrap(); + let sparse_fmt = ctx.format_val(sparse); + assert_eq!(sparse_fmt, "[...]"); + }) + .unwrap(); +} + +#[test] +fn globals_preserve_custom_entries_across_lazy_builtins_host_overrides_and_compiled_slots() { + let rt = Runtime::make().globals(|_| { + let custom_console = + HostValue::Object(vec![("tag".into(), HostValue::from("from-runtime-host"))]); + let host_val = HostValue::from("runtime-override"); + vec![("console", custom_console), ("hostThing", host_val)] + }); + let mut s_compiled = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + let reader_mod = rt + .compile_module( + "return () => typeof preboundGlobal === 'undefined' ? 'missing' : preboundGlobal;", + "reader.js", + ) + .unwrap(); + + s_compiled + .enter(|ctx| { + // 1. set_global("Buffer", 1) + new_bytes + get_global("Buffer") === 1 + ctx.set_global("Buffer", Val::num(1.0)).unwrap(); + let b = ctx.new_bytes(&[7, 8, 9]); + assert_eq!(ctx.bytes(b), Some(&[7u8, 8, 9][..])); + let buf = ctx.get_global("Buffer").unwrap(); + assert_eq!(buf.as_f64(), Some(1.0)); + + // 2. set_global("Map", custom) + get_global("Set") preserves custom Map! + let custom_map = ctx.object(); + ctx.set(custom_map, "custom", Val::bool(true)).unwrap(); + ctx.set_global("Map", custom_map).unwrap(); + let set_ctor = ctx.get_global("Set").unwrap(); + assert_eq!(ctx.type_of(set_ctor), "function"); + let map_after = ctx.get_global("Map").unwrap(); + assert_eq!(ctx.get(map_after, "custom").unwrap().as_bool(), Some(true)); + + // 3. get_global("console") resolves runtime host override of base built-in! + let host_console = ctx.get_global("console").unwrap(); + let tag = ctx.get(host_console, "tag").unwrap(); + assert_eq!(ctx.text(tag).as_deref(), Some("from-runtime-host")); + + // 4. set_global("hostThing", ...) is NOT clobbered by a subsequent eval_module! + let custom_host = ctx.string("from-set-global"); + ctx.set_global("hostThing", custom_host).unwrap(); + let seen_in_mod = ctx + .eval_module("return hostThing;", "check_host.js") + .unwrap(); + assert_eq!(ctx.text(seen_in_mod).as_deref(), Some("from-set-global")); + + // 5. set_global updates an ALREADY-COMPILED global slot! + let reader = ctx.eval_compiled(&reader_mod).unwrap(); + let before = ctx.call(reader, Val::undefined(), &[]).unwrap(); + assert_eq!(ctx.text(before).as_deref(), Some("missing")); + let updated = ctx.string("live-updated"); + ctx.set_global("preboundGlobal", updated).unwrap(); + let after = ctx.call(reader, Val::undefined(), &[]).unwrap(); + assert_eq!(ctx.text(after).as_deref(), Some("live-updated")); + }) + .unwrap(); +} + +#[test] +fn for_each_own_rechecks_own_enumerability_after_getter_mutation() { + let rt = Runtime::make(); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + session + .enter(|ctx| { + let obj = ctx + .eval_module( + r#" + const proto = { deletedKey: "FROM_PROTO", hiddenKey: "FROM_PROTO" }; + const o = Object.create(proto); + Object.defineProperty(o, "first", { + enumerable: true, + get() { + delete this.deletedKey; + Object.defineProperty(this, "hiddenKey", { enumerable: false }); + return "firstVal"; + }, + }); + o.deletedKey = "ownDeleted"; + o.hiddenKey = "ownHidden"; + o.kept = "ownKept"; + return o; + "#, + "getter_mut.js", + ) + .unwrap(); + + let mut raw = Vec::new(); + ctx.for_each_own(obj, |k, v| { + raw.push((k.to_owned(), v)); + Ok(()) + }) + .unwrap(); + let visited: Vec<(String, String)> = raw + .into_iter() + .map(|(k, v)| (k, ctx.format_val(v))) + .collect(); + assert_eq!( + visited, + vec![ + ("first".to_owned(), "firstVal".to_owned()), + ("kept".to_owned(), "ownKept".to_owned()), + ] + ); + }) + .unwrap(); +} + +#[test] +fn take_logs_and_take_unhandled_rejections_drain_and_release_gc_roots() { + let rt = Runtime::make(); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + session + .enter(|ctx| { + let _ = ctx + .eval_module( + r#" + console.log("frame", 1); + console.warn("careful"); + const big = []; + for (let i = 0; i < 1500; i++) { + big.push({ i, pad: "payload_" + i + "_" + "z".repeat(32) }); + } + Promise.reject({ label: "unhandled-big", big }); + "#, + "logs_rej.js", + ) + .unwrap(); + }) + .unwrap(); + + // Logs drain cleanly and do not repeat. + let logs = session.take_logs(); + assert_eq!(logs, vec!["frame 1", "[warn] careful"]); + assert!(session.take_logs().is_empty()); + + // While queued in vm.host.unhandled, the rejected payload stays pinned across GC. + session.collect_garbage(); + let before = session.heap_bytes(); + assert!( + before > 80_000, + "expected rejected payload pinned, got {before}" + ); + + // Draining unhandled rejections returns formatted reasons and frees the GC root! + let rejections = session.take_unhandled_rejections(); + assert_eq!(rejections.len(), 1); + assert!( + rejections[0].contains("unhandled-big"), + "unexpected rejection format: {}", + rejections[0] + ); + assert!(session.take_unhandled_rejections().is_empty()); + + session.collect_garbage(); + let after = session.heap_bytes(); + assert!( + after < before / 2, + "expected heap_bytes to drop after draining unhandled rejections: before={before}, after={after}" + ); +} + +#[test] +fn host_panic_inside_enter_poisons_session_cleanly() { + let rt = Runtime::make().limits(Limits { + timeout_ms: Some(500), + clock: Clock::ThreadCpu, + ..Default::default() + }); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + let panic_res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = session.enter(|_ctx| { + panic!("intentional host panic"); + }); + })); + assert!(panic_res.is_err()); + assert!( + session.is_fatal(), + "panic inside enter must poison LiveSession" + ); + + let mut ran = false; + let err = session + .enter(|_| { + ran = true; + }) + .unwrap_err(); + assert!(!ran); + assert_eq!(err.kind, DiagnosticKind::ExecutionFailure); + assert!( + err.message.to_string_lossy().contains("panicked"), + "unexpected fatal msg: {}", + err.message + ); +} + +#[test] +fn max_heap_bytes_enforced_on_rust_ctx_set_loops() { + let rt = Runtime::make().limits(Limits { + max_heap_bytes: Some(256 * 1024), + ..Default::default() + }); + let mut session = rt + .live_session("undefined;", &ProgramOptions::new()) + .unwrap(); + + let err = session + .enter(|ctx| { + let obj = ctx.object(); + ctx.set_global("grower", obj).unwrap(); + for i in 0..15_000 { + let key = format!("prop_{i}"); + if ctx.set(obj, &key, Val::num(i as f64)).is_err() { + break; + } + } + }) + .unwrap_err(); + assert_eq!(err.kind, DiagnosticKind::MemoryLimitExceeded); + assert!(session.is_fatal()); +}