Repository navigation
feat(rust): persistent Session and zero-copy HostCtx API - #157
Merged
Merged
Conversation
There was a problem hiding this comment.
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.
This was referenced Dec 2, 2026
Hona
force-pushed
the
feat/rust-persistent-session
branch
from
December 2, 2026 15:28
880f23f to
d3d3303
Compare
…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.
…xports, and arg depth limit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a hardened persistent
Sessionand zero-copyHostFunction::direct/HostCtxAPI for low-latency Rust embedders (e.g., UI loops and plugin hosts) that call into a live VM repeatedly without marshalling values throughHostValue.This PR builds on and refines the persistent-session work from draft PR #139, keeping the diff tightly scoped to the
Session/HostCtx/HostFunction::directsurface (noCargo.tomlICU feature changes,WeakMap,ThreadClock, or multi-moduleeval_module) while incorporating GC, safety, and leak hardening from adversarial review and production embedding.Key Changes
Session(src/session.rs,src/runtime.rs,src/lib.rs):Runtime::session/Runtime::session_withkeep 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::startpairsCpuMeter::enter()/leave()across top-level init, uses an RAII guard to clean upSESSION_STORESon error/panic, clears init-timevm.slicebefore returning, and rejects incomplete/suspended top-level initialization.Sessionis thread-affine (!Send + !Sync), enabling safe thread-local callbacks (HostCtx::new_local_fn) and typed per-sessionuser_data(set_user_data,with_user_data,with_user_data_mut,get_user_data) accessed viaSESSION_STORES.try_withand dropped outside theRefCellborrow guard.session_exports, bounds-checkedHostCtx, & incremental GC write barriers (src/vm.rs,src/collector.rs,src/strings.rs,src/reach.rs,src/heap.rs,src/session.rs):Session::exportsis rooted onVm::session_exports(outsidevm.pinned); userPinSlotgenerations start at1(skipping0on wrap) sounpin_slot(0)is always a safe no-op and ABA reuse is rejected.Vm::gc_shadeandVm::gc_shade_atom(guardingNO_ATOM) write barriers onVm::call_direct,alloc_pin,set_global, and host object/array mutators soWHITEvalues cannot be swept during incrementalPhase::Mark.HostCtxheap/string/atom reads use bounds- and liveness-checkedHeap::live_slot/live_slot_mutandStrings::get_opt/text_opt, returningNone/false/""on staleVals instead of panicking.Session::call_val(run_depth == 1 && gc.owns_suspend()) runsgc_point()on backward jumps so single-call transient allocation loops collect instead of OOMing;gc_collect_fullchecksbusy, finishes any in-progress cycle before running a completeIdle -> Mark -> Sweep -> Idlepass, and clampsHeapMeter::objectsafter trailing chunk truncation.src/session.rs):HostCtx::keyinterns and permanently roots fixed keys inVm::host_atoms.HostCtx::obj_set_strinterns without rooting inVm::host_atomsso dynamic keys are reclaimed by GC (intern_keyis crate-private so unrooted keys cannot escape as publicKeys).src/host_function.rs,src/host.rs,src/collector.rs,src/snapshot.rs,src/vm.rs):HostFunction::direct(Body::Direct) dispatches zero-copy acrosscall_op(all arg counts, withhost_span()+native_spent()),host_native(no doublenative_depthincrement), andcall_host(soNamespacemethods can beHostFunction::directwithout panicking).DirectArgs::this()normalizesValue::UninittoVal::UNDEFINED.RunHost::functionsusesVec<Option<FnEntry>>+free_functions(with snapshot serialization updated forNoneholes);new_local_fnslots are generation-tagged, validatectx.vm.session_id+ generation, are blocked fromhosted()cloning, and are reclaimed automatically during GC sweep.HostCtxinvariants & inspection (src/session.rs):Val::as_u32/as_i32/as_i64finite integer range checks; exactKind::Bytes(b) => b.elem.name()intype_name; carrier-decodedkey_name -> Cow<'_, str>.obj_set/obj_push_new/new_object_with/array_pushenforce frozen/non-extensible/non-writable guards, reset flags on accessor/pending-stack overwrite, deduplicate keys, cap array length atu32::MAX, synchronize array indices, and chargeheap_meter.obj_for_each/obj_for_each_keyskip symbol keys (<= SYM_LAST) and accessors;array_for_eachhandles both dense arrays (with holes) and sparse arrays (skippingACCESSORprops).src/session.rs,src/vm.rs):Session::drain_jobs_budget(max_jobs) -> Result<bool, Diagnostic>andSession::drain_jobs()(4096-job budget) checkfatalat entry andsuspendedper job, and only clear remaining jobs on fatal VM errors.Session::take_unhandled_rejectionsinspects heap state directly without executing user JStoString()/[Symbol.toPrimitive]/ getters;Session::format_errorpreservesFailure::kindand hostsuggestions.Session::arm_sliceonly clears recoverableSliceExceededfatals (never wiping out OOM/memory limits), paired withdisarm_slice, stack truncation ontick()error inpush_closure_frame, and coroutine cleanup on fatal unwind inhandle_throw.#![deny(unsafe_code)]intact.Verification
cargo fmt --check— passcargo 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 passedPSYCHOSCRIPT_GC_STRESS=1 cargo test -p psychoscript --test session— 18/18 passedcargo test -p psychoscript --test gc— 4/4 passedcargo test -p psychoscript --test heap— 11/11 passedcargo test -p psychoscript --test host— 25/25 passedcargo test -p psychoscript --test snapshot— 22/22 passedReview changes:
Sessionis 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::directgoes through the normal sync host-call path, andHostCtxreads, writes and calls as the program does with call-scopedVal<'a>; pins, keys, user data, local functions,drain_jobs,arm_slice/disarm_sliceand the VM/collector changes are dropped.