Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions rust/crates/psychoscript/src/builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
193 changes: 178 additions & 15 deletions rust/crates/psychoscript/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand All @@ -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();
Expand All @@ -1401,6 +1401,121 @@ 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) {
if self.gc_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) {
if self.gc_busy() {
return;
}
if self.gc.phase != Phase::Idle {
self.gc_finish_cycle();
}
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;
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
Expand Down Expand Up @@ -1523,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;
Expand All @@ -1537,13 +1661,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);
Expand Down Expand Up @@ -1584,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);
Expand All @@ -1599,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;
Expand All @@ -1609,6 +1771,7 @@ impl Vm {
self.gc.live + self.gc.live.max(FLOOR)
};
self.gc_poll();
reclaimed_locals
}
}

Expand Down
22 changes: 22 additions & 0 deletions rust/crates/psychoscript/src/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
35 changes: 32 additions & 3 deletions rust/crates/psychoscript/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
}
}
}
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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 => {}
}
}
}
Expand All @@ -2512,6 +2528,7 @@ fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option<String
path: place.global.clone(),
owner,
installed: place.installed,
reclaimable: false,
});
let made = native(vm, &name, length, host_native, Value::Num(index as f64));
if constructible
Expand All @@ -2523,11 +2540,23 @@ fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option<String
made
}

fn host_native(vm: &mut Vm, this: Value, args: &[Value], callee: Id) -> 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 = 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."));
}
if let Callee::Fn(f) = &entry.f
&& let Body::Lost(message) = &f.body
{
Expand Down
Loading