Repository navigation
feat(rust): add LiveSession and zero-copy HostCtx primitives - #202
Merged
Merged
Conversation
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`.
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.
- 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`).
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 single-thread,
#![deny(unsafe_code)]LiveSessionand fast zero-copyHostCtxprimitives so high-frequency UI/app/game embedders can call directly into a live VM without JS trampoline shims, while leaving durableSession(Send, snapshot-capable) andVm: Senduntouched.Public API
Runtime::live_session(&self, code, options) -> Result<LiveSession, Diagnostic>andLiveSession(!Send + !Sync):enter<R>(&mut self, f: impl FnOnce(&mut HostCtx<'_>) -> R) -> Result<R, Diagnostic>— enters the live VM directly with no'staticbound and no JSPromise.trywrapper; resets per-entrystart,CpuMeter,slice,stack_base, and fuel; drains ready microtasks/jobs; runs pending/idle GC and heap-limit checks; preserves fatal stickiness.unroot(&mut self, roots: &[Root])— O(1) Rust-only free-list unpinning.set_data/with_data/with_data_mut— typed single-thread host state stored in thread-local storage keyed by unique non-zerolive_id.heap_bytes(&mut self) -> usize— live reachable heap measurement viacrate::heap::measure.gc_step(&mut self)/collect_garbage(&mut self)— bounded incremental step and fullIdle -> Mark -> SweepWeak -> Sweep -> Trim -> Idlecollection.eval_compiled(&mut self, module)/eval_module(&mut self, source, name)/is_fatal(&self).Root& single-threadHostCtxextensions:Root((live_id, slot, generation), generation starts at1, skips0on wrap) withHostCtx::root,get_root, andunroot.HostCtx::local_fn— non-Sendsingle-thread closures (Rc<LocalFn>) stored inthread_local! LIVE_STORES, excluded fromhosted()cloning, and automatically reclaimed from bothLIVE_STORESandvm.host.functions(via free list) when GC sweeps their JS function objects.HostCtx::set_data/with_data/with_data_mut.HostCtxprimitives (works in bothSessionandLiveSession):is_frozen(&self, v)— O(1)FROZENflag check onObj.object_id(&self, v) -> Option<u64>— ABA-safe monotonic object identity (lazily allocated, zero bytes added toObj, forgotten on GC sweep).new_bytes(&mut self, bytes: &[u8])— directUint8Arrayallocation with zero JS call.get_global/set_global— directglobal_map/ compiledglobalsaccess with lazy built-in/host resolution and GC barriers.for_each_own— direct own-property walk skipping symbol keys (<= SYM_LAST), zero-allocation fast path for plain objects, full getter/index-order general path.is_fatal(&self)— cleanly distinguishes fatal VM termination from JSthrow undefined.format_val(&self, v)— safe, non-JS-invoking human-readable formatting.Invariants & Layout
Session(src/session.rs) and snapshot serialization remain untouched.VmremainsSend(compile-time asserted);Vm::liveandVm::object_idsare boxed cold fields appended at the end ofVm, keepingvm::layout::stack_is_nearandvm::layout::kind_is_smallunchanged with zero overhead for non-live runs.gc_shade_value) onHostCtx::rootandHostCtx::set_global, doomed-slot rejection (gc_is_doomed) acrossSweepWeakand unsweptSweepranges, and TLSRefCelldrop safety (all reclaimed closures and dropped stores drop outsideRefCellborrows viatry_with).Verification
cargo fmt --all --check— passedcargo clippy -p psychoscript --all-targets -- -D warnings— passedcargo clippy -p psychoscript --lib --target wasm32-unknown-unknown -- -D warnings— passedcargo clippy -p psychoscript --no-default-features --lib --target wasm32-unknown-unknown -- -D warnings— passedcargo test -p psychoscript --lib vm::layout::stack_is_near— passed (stack_is_near+kind_is_small)cargo test -p psychoscript --test live_session— 12/12 passed (normal &PSYCHOSCRIPT_GC_STRESS=1)cargo test -p psychoscript --test session --test modules --test gc --test snapshot --test host— all passed (session: 23,modules: 9,gc: 10,snapshot: 25,host: 30)