Skip to content

feat(rust): persistent Session and zero-copy HostCtx API - #157

Merged
kommander merged 10 commits into
devfrom
feat/rust-persistent-session
Dec 3, 2026
Merged

kommander merged 10 commits into
devfrom
feat/rust-persistent-session

Conversation

@Hona

@Hona Hona commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds a hardened persistent Session and zero-copy HostFunction::direct / HostCtx API for low-latency Rust embedders (e.g., UI loops and plugin hosts) that call into a live VM repeatedly without marshalling values through HostValue.

This PR builds on and refines the persistent-session work from draft PR #139, keeping the diff tightly scoped to the Session / HostCtx / HostFunction::direct surface (no Cargo.toml ICU feature changes, WeakMap, ThreadClock, or multi-module eval_module) while incorporating GC, safety, and leak hardening from adversarial review and production embedding.

Key Changes

  • Persistent Session (src/session.rs, src/runtime.rs, src/lib.rs):
    • Runtime::session / Runtime::session_with keep a live VM across repeated synchronous calls (exports, export_fn, global, global_by_key, set_global, global_fn, call_fn, call_fn_with_this, call_val).
    • Session::start pairs CpuMeter::enter()/leave() across top-level init, uses an RAII guard to clean up SESSION_STORES on error/panic, clears init-time vm.slice before returning, and rejects incomplete/suspended top-level initialization.
    • Session is thread-affine (!Send + !Sync), enabling safe thread-local callbacks (HostCtx::new_local_fn) and typed per-session user_data (set_user_data, with_user_data, with_user_data_mut, get_user_data) accessed via SESSION_STORES.try_with and dropped outside the RefCell borrow guard.
  • Generation-tagged handles, rooted session_exports, bounds-checked HostCtx, & incremental GC write barriers (src/vm.rs, src/collector.rs, src/strings.rs, src/reach.rs, src/heap.rs, src/session.rs):
    • Session::exports is rooted on Vm::session_exports (outside vm.pinned); user PinSlot generations start at 1 (skipping 0 on wrap) so unpin_slot(0) is always a safe no-op and ABA reuse is rejected.
    • Added Vm::gc_shade and Vm::gc_shade_atom (guarding NO_ATOM) write barriers on Vm::call_direct, alloc_pin, set_global, and host object/array mutators so WHITE values cannot be swept during incremental Phase::Mark.
    • All HostCtx heap/string/atom reads use bounds- and liveness-checked Heap::live_slot / live_slot_mut and Strings::get_opt / text_opt, returning None/false/"" on stale Vals instead of panicking.
    • Top-level Session::call_val (run_depth == 1 && gc.owns_suspend()) runs gc_point() on backward jumps so single-call transient allocation loops collect instead of OOMing; gc_collect_full checks busy, finishes any in-progress cycle before running a complete Idle -> Mark -> Sweep -> Idle pass, and clamps HeapMeter::objects after trailing chunk truncation.
  • Separate rooted keys vs. dynamic property writes (src/session.rs):
    • HostCtx::key interns and permanently roots fixed keys in Vm::host_atoms.
    • HostCtx::obj_set_str interns without rooting in Vm::host_atoms so dynamic keys are reclaimed by GC (intern_key is crate-private so unrooted keys cannot escape as public Keys).
  • GC-reclaimed direct & local host functions + Namespace parity (src/host_function.rs, src/host.rs, src/collector.rs, src/snapshot.rs, src/vm.rs):
    • HostFunction::direct (Body::Direct) dispatches zero-copy across call_op (all arg counts, with host_span() + native_spent()), host_native (no double native_depth increment), and call_host (so Namespace methods can be HostFunction::direct without panicking).
    • DirectArgs::this() normalizes Value::Uninit to Val::UNDEFINED.
    • RunHost::functions uses Vec<Option<FnEntry>> + free_functions (with snapshot serialization updated for None holes); new_local_fn slots are generation-tagged, validate ctx.vm.session_id + generation, are blocked from hosted() cloning, and are reclaimed automatically during GC sweep.
  • Zero-copy HostCtx invariants & inspection (src/session.rs):
    • Strict Val::as_u32 / as_i32 / as_i64 finite integer range checks; exact Kind::Bytes(b) => b.elem.name() in type_name; carrier-decoded key_name -> Cow<'_, str>.
    • obj_set / obj_push_new / new_object_with / array_push enforce frozen/non-extensible/non-writable guards, reset flags on accessor/pending-stack overwrite, deduplicate keys, cap array length at u32::MAX, synchronize array indices, and charge heap_meter.
    • obj_for_each / obj_for_each_key skip symbol keys (<= SYM_LAST) and accessors; array_for_each handles both dense arrays (with holes) and sparse arrays (skipping ACCESSOR props).
  • Non-destructive microtask draining, safe unhandled rejections, and recoverable slice watchdog (src/session.rs, src/vm.rs):
    • Session::drain_jobs_budget(max_jobs) -> Result<bool, Diagnostic> and Session::drain_jobs() (4096-job budget) check fatal at entry and suspended per job, and only clear remaining jobs on fatal VM errors.
    • Session::take_unhandled_rejections inspects heap state directly without executing user JS toString() / [Symbol.toPrimitive] / getters; Session::format_error preserves Failure::kind and host suggestions.
    • Session::arm_slice only clears recoverable SliceExceeded fatals (never wiping out OOM/memory limits), paired with disarm_slice, stack truncation on tick() error in push_closure_frame, and coroutine cleanup on fatal unwind in handle_throw.
    • Keeps #![deny(unsafe_code)] intact.

Verification

  • cargo fmt --check — pass
  • cargo clippy -p psychoscript --all-targets -- -D warnings — pass (0 warnings)
  • cargo clippy -p psychoscript --lib --target wasm32-unknown-unknown -- -D warnings — pass (0 warnings)
  • cargo test -p psychoscript --test session — 18/18 passed
  • PSYCHOSCRIPT_GC_STRESS=1 cargo test -p psychoscript --test session — 18/18 passed
  • cargo test -p psychoscript --test gc — 4/4 passed
  • cargo test -p psychoscript --test heap — 11/11 passed
  • cargo test -p psychoscript --test host — 25/25 passed
  • cargo test -p psychoscript --test snapshot — 22/22 passed

Review changes: Session is now a run kept between calls on the existing program driver (limits per call, failures stick, async host calls settle, GC at the existing safe points, the value crosses as a run's result) and saves/restores through the existing snapshot (Session::save, Runtime::restore_session); HostFunction::direct goes through the normal sync host-call path, and HostCtx reads, writes and calls as the program does with call-scoped Val<'a>; pins, keys, user data, local functions, drain_jobs, arm_slice/disarm_slice and the VM/collector changes are dropped.

Copilot AI balanced review requested due to automatic review settings December 2, 2026 02:00

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@Hona
Hona force-pushed the feat/rust-persistent-session branch from 880f23f to d3d3303 Compare December 2, 2026 15:28
…ns on the host call path

Review changes for #157: the session drives its calls with the program driver (jobs, async host calls, GC at the
existing safe points, limits per call), its failures stick, its value crosses as a run's result, and it saves and
restores through the snapshot machinery. HostFunction::direct goes through call_host with the sync call's
accounting; HostCtx reads, writes and calls as the program does, and its values can't outlive the call.
@kommander
kommander merged commit aa0e6b8 into dev Dec 3, 2026
2 checks passed
@kommander
kommander deleted the feat/rust-persistent-session branch December 3, 2026 00:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants