Skip to content

feat(rust): add LiveSession and zero-copy HostCtx primitives - #202

Merged
Hona merged 2 commits into
devfrom
feat/rust-live-session
Dec 3, 2026
Merged

Hona merged 2 commits into
devfrom
feat/rust-live-session

Conversation

@Hona

@Hona Hona commented Dec 3, 2026

Copy link
Copy Markdown
Member

Summary

Adds a single-thread, #![deny(unsafe_code)] LiveSession and fast zero-copy HostCtx primitives so high-frequency UI/app/game embedders can call directly into a live VM without JS trampoline shims, while leaving durable Session (Send, snapshot-capable) and Vm: Send untouched.

Public API

  • Runtime::live_session(&self, code, options) -> Result<LiveSession, Diagnostic> and LiveSession (!Send + !Sync):
    • enter<R>(&mut self, f: impl FnOnce(&mut HostCtx<'_>) -> R) -> Result<R, Diagnostic> — enters the live VM directly with no 'static bound and no JS Promise.try wrapper; resets per-entry start, 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-zero live_id.
    • heap_bytes(&mut self) -> usize — live reachable heap measurement via crate::heap::measure.
    • gc_step(&mut self) / collect_garbage(&mut self) — bounded incremental step and full Idle -> Mark -> SweepWeak -> Sweep -> Trim -> Idle collection.
    • eval_compiled(&mut self, module) / eval_module(&mut self, source, name) / is_fatal(&self).
  • GC-safe Root & single-thread HostCtx extensions:
    • Root ((live_id, slot, generation), generation starts at 1, skips 0 on wrap) with HostCtx::root, get_root, and unroot.
    • HostCtx::local_fn — non-Send single-thread closures (Rc<LocalFn>) stored in thread_local! LIVE_STORES, excluded from hosted() cloning, and automatically reclaimed from both LIVE_STORES and vm.host.functions (via free list) when GC sweeps their JS function objects.
    • HostCtx::set_data / with_data / with_data_mut.
  • Zero-copy HostCtx primitives (works in both Session and LiveSession):
    • is_frozen(&self, v) — O(1) FROZEN flag check on Obj.
    • object_id(&self, v) -> Option<u64> — ABA-safe monotonic object identity (lazily allocated, zero bytes added to Obj, forgotten on GC sweep).
    • new_bytes(&mut self, bytes: &[u8]) — direct Uint8Array allocation with zero JS call.
    • get_global / set_global — direct global_map / compiled globals access 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 JS throw undefined.
    • format_val(&self, v) — safe, non-JS-invoking human-readable formatting.

Invariants & Layout

  • Durable Session (src/session.rs) and snapshot serialization remain untouched.
  • Vm remains Send (compile-time asserted); Vm::live and Vm::object_ids are boxed cold fields appended at the end of Vm, keeping vm::layout::stack_is_near and vm::layout::kind_is_small unchanged with zero overhead for non-live runs.
  • GC invariants: SATB write barrier (gc_shade_value) on HostCtx::root and HostCtx::set_global, doomed-slot rejection (gc_is_doomed) across SweepWeak and unswept Sweep ranges, and TLS RefCell drop safety (all reclaimed closures and dropped stores drop outside RefCell borrows via try_with).

Verification

  • cargo fmt --all --check — passed
  • cargo clippy -p psychoscript --all-targets -- -D warnings — passed
  • cargo clippy -p psychoscript --lib --target wasm32-unknown-unknown -- -D warnings — passed
  • cargo clippy -p psychoscript --no-default-features --lib --target wasm32-unknown-unknown -- -D warnings — passed
  • cargo 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)

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`.
Copilot AI balanced review requested due to automatic review settings December 3, 2026 04:39

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.

- 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`).
@Hona
Hona merged commit e79e7ee into dev Dec 3, 2026
2 checks passed
@Hona
Hona deleted the feat/rust-live-session branch December 3, 2026 05:10
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.

2 participants