Skip to main content

harn_vm/vm/
state.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use crate::chunk::{Chunk, ChunkRef, Constant};
6use crate::runtime_limits::RuntimeLimits;
7use crate::value::{
8    ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmEnv, VmError, VmTaskHandle, VmValue,
9};
10use crate::BuiltinId;
11
12use super::debug::DebugHook;
13use super::modules::LoadedModule;
14use super::VmBuiltinMetadata;
15
16/// RAII guard that starts a tracing span on creation and ends it on drop.
17pub(crate) struct ScopeSpan(u64);
18
19impl ScopeSpan {
20    pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
21        Self(crate::tracing::span_start(kind, name))
22    }
23}
24
25impl Drop for ScopeSpan {
26    fn drop(&mut self) {
27        crate::tracing::span_end(self.0);
28    }
29}
30
31#[derive(Clone)]
32pub(crate) struct LocalSlot {
33    pub(crate) value: VmValue,
34    pub(crate) initialized: bool,
35    pub(crate) synced: bool,
36}
37
38impl Drop for LocalSlot {
39    fn drop(&mut self) {
40        // Slot locals hold script values directly (e.g. a `var` bound to a
41        // deeply nested list). When a frame is torn down, the default
42        // recursive drop of such a value would overflow the native stack and
43        // abort the process. For the overwhelmingly common scalar slot this is
44        // a single `matches!` check and then the normal trivial drop; only a
45        // nested container is moved out and torn down iteratively, so hot
46        // frame teardown is unaffected.
47        if crate::value::recursion::is_recursive_container(&self.value) {
48            crate::value::recursion::dismantle(std::mem::replace(&mut self.value, VmValue::Nil));
49        }
50    }
51}
52
53#[derive(Clone)]
54pub(crate) struct InterruptHandler {
55    pub(crate) handle: i64,
56    pub(crate) signals: Vec<String>,
57    pub(crate) once: bool,
58    pub(crate) graceful_timeout_ms: Option<u64>,
59    pub(crate) handler: VmValue,
60}
61
62/// Call frame for function execution.
63pub(crate) struct CallFrame {
64    pub(crate) chunk: ChunkRef,
65    /// VM-local inline-cache set for this frame's chunk. Computed once at
66    /// frame entry so hot opcode dispatch can index cache feedback directly
67    /// instead of hashing the chunk id on every cached opcode.
68    pub(crate) inline_cache_set: usize,
69    pub(crate) ip: usize,
70    pub(crate) stack_base: usize,
71    pub(crate) saved_env: VmEnv,
72    /// Env snapshot captured at call-time, *after* argument binding. Used
73    /// by the debugger's `restartFrame` to rewind this frame to its
74    /// entry state (re-binding args from the original values) without
75    /// re-entering the call site. Cheap to clone because `VmEnv` is
76    /// already cloned into `saved_env` on every call. `None` for
77    /// scratch frames (evaluate, import init) where restart isn't
78    /// meaningful.
79    pub(crate) initial_env: Option<VmEnv>,
80    pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
81    /// Iterator stack depth to restore when this frame unwinds.
82    pub(crate) saved_iterator_depth: usize,
83    /// Function name for stack traces (empty for top-level pipeline).
84    pub(crate) fn_name: String,
85    /// Number of arguments actually passed by the caller (for default arg support).
86    pub(crate) argc: usize,
87    /// Saved VM_SOURCE_DIR to restore when this frame is popped.
88    /// Set when entering a closure that originated from an imported module.
89    pub(crate) saved_source_dir: Option<std::path::PathBuf>,
90    /// Module-local named functions available to symbolic calls within this frame.
91    pub(crate) module_functions: Option<ModuleFunctionRegistry>,
92    /// Shared module-level env for top-level `var` / `let` bindings of
93    /// this frame's originating module. Looked up after `self.env` and
94    /// before `self.globals` by `GetVar` / `SetVar`, giving each module
95    /// its own live static state that persists across calls. See the
96    /// `module_state` field on `VmClosure` for the full rationale.
97    pub(crate) module_state: Option<crate::value::ModuleState>,
98    /// Slot-indexed locals for compiler-resolved names in this frame.
99    pub(crate) local_slots: Vec<LocalSlot>,
100    /// Env scope index that corresponds to compiler local scope depth 0.
101    pub(crate) local_scope_base: usize,
102    /// Current compiler local scope depth, updated by PushScope/PopScope.
103    pub(crate) local_scope_depth: usize,
104}
105
106pub(crate) struct InlineCacheSite {
107    pub(crate) cache_set: usize,
108    pub(crate) slot_count: usize,
109    pub(crate) slot: Option<usize>,
110}
111
112impl CallFrame {
113    #[inline]
114    pub(crate) fn inline_cache_site_for_previous_op(&self) -> InlineCacheSite {
115        let op_offset = self.ip.saturating_sub(1);
116        InlineCacheSite {
117            cache_set: self.inline_cache_set,
118            slot_count: self.chunk.inline_cache_slot_count(),
119            slot: self.chunk.inline_cache_slot(op_offset),
120        }
121    }
122}
123
124/// Exception handler for try/catch.
125pub(crate) struct ExceptionHandler {
126    pub(crate) catch_ip: usize,
127    pub(crate) stack_depth: usize,
128    pub(crate) frame_depth: usize,
129    pub(crate) env_scope_depth: usize,
130    /// When present, this catch only handles errors whose enum_name matches.
131    pub(crate) error_type: Option<crate::value::HarnStr>,
132}
133
134/// A structured-concurrency nursery (`scope { }`). Tasks spawned while this
135/// scope is innermost record their id here; `TaskScopeExit` joins them.
136pub(crate) struct TaskScope {
137    /// Ids of tasks spawned in this scope that have not been explicitly
138    /// `await`ed away. Joined (normal exit) or cancelled (unwind) on close.
139    pub(crate) task_ids: Vec<String>,
140    /// Frame depth at which the scope was opened, for unwind pruning.
141    pub(crate) frame_depth: usize,
142    /// Env scope depth at open, for unwind pruning.
143    pub(crate) env_scope_depth: usize,
144}
145
146/// Iterator state for for-in loops.
147pub(crate) enum IterState {
148    Vec {
149        items: Arc<Vec<VmValue>>,
150        idx: usize,
151    },
152    Dict {
153        entries: Arc<crate::value::DictMap>,
154        keys: Vec<String>,
155        idx: usize,
156    },
157    Channel {
158        receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
159        close: std::sync::Arc<crate::value::VmChannelCloseState>,
160    },
161    Generator {
162        gen: Arc<crate::value::VmGenerator>,
163    },
164    Stream {
165        stream: Arc<crate::value::VmStream>,
166    },
167    /// Step through a lazy range without materializing a Vec.
168    /// Inclusive ranges keep `end` as an actual value so `i64::MAX to i64::MAX`
169    /// still yields one item instead of overflowing a one-past-end sentinel.
170    Range {
171        next: i64,
172        end: i64,
173        inclusive: bool,
174        done: bool,
175    },
176    VmIter {
177        handle: crate::vm::iter::VmIterHandle,
178    },
179}
180
181#[derive(Clone)]
182pub(crate) enum VmBuiltinDispatch {
183    Sync(VmBuiltinFn),
184    Async(VmAsyncBuiltinFn),
185}
186
187#[derive(Clone)]
188pub(crate) struct VmBuiltinEntry {
189    pub(crate) name: Arc<str>,
190    pub(crate) dispatch: VmBuiltinDispatch,
191}
192
193/// The Harn bytecode virtual machine.
194pub struct Vm {
195    pub(crate) stack: Vec<VmValue>,
196    pub(crate) env: VmEnv,
197    pub(crate) output: String,
198    pub(crate) builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
199    pub(crate) async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
200    pub(crate) builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
201    /// Numeric side index for builtins. Name-keyed maps remain authoritative;
202    /// this index is the hot path for direct builtin bytecode and callback refs.
203    pub(crate) builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
204    /// IDs with detected name collisions. Collided names safely fall back to
205    /// the authoritative name-keyed lookup path.
206    pub(crate) builtin_id_collisions: Arc<HashSet<BuiltinId>>,
207    /// Iterator state for for-in loops.
208    pub(crate) iterators: Vec<IterState>,
209    /// Call frame stack.
210    pub(crate) frames: Vec<CallFrame>,
211    /// Exception handler stack.
212    pub(crate) exception_handlers: Vec<ExceptionHandler>,
213    /// Spawned async task handles.
214    pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
215    /// Shared process-local synchronization primitives inherited by child VMs.
216    pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
217    /// Shared process-local cells, maps, and mailboxes inherited by child VMs.
218    pub(crate) shared_state_runtime: Arc<crate::shared_state::VmSharedStateRuntime>,
219    /// Per-isolate inline cache entries. `inline_cache_set_by_chunk` maps a
220    /// compiled chunk identity to an index in this vector at frame entry; the
221    /// dispatch loop uses the frame-local index for per-op reads/writes.
222    pub(crate) inline_cache_sets: Vec<Vec<crate::chunk::InlineCacheEntry>>,
223    pub(crate) inline_cache_set_by_chunk: HashMap<u64, usize>,
224    /// VM-scoped pool registry inherited by child VMs and scoped into Tokio tasks.
225    pub(crate) pool_registry: Arc<crate::stdlib::pool::PoolRegistry>,
226    /// Shared task/channel wait graph for this VM execution tree.
227    pub(crate) wait_for_graph: Arc<crate::wait_for_graph::VmWaitForGraph>,
228    /// Permits acquired by lexical synchronization blocks in this VM.
229    pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
230    /// Locks held by an ancestor VM that is *suspended on this VM's execution*:
231    /// an inline async-builtin child runs while its parent is parked
232    /// mid-instruction still holding these permits. Re-acquiring more permits
233    /// than the primitive can grant is a provably-unresolvable self-deadlock, so
234    /// HARN-ORC-011 fires across the child boundary. Empty for new concurrent
235    /// tasks (`spawn`/`parallel`/triggers), where the parent keeps running and
236    /// blocking can be legitimately resolvable.
237    pub(crate) inherited_held_keys: Arc<Vec<crate::synchronization::VmSyncHeldKey>>,
238    /// Structured-concurrency nursery stack. Each `scope { }` block pushes a
239    /// `TaskScope`; tasks spawned while it is innermost register their id here.
240    /// On normal exit (`TaskScopeExit`) the scope's tasks are joined and the
241    /// first error propagates; on unwind they are cancelled. Modeled on
242    /// `held_sync_guards` (push on enter, prune/cancel on frame/handler exit).
243    pub(crate) task_scopes: Vec<TaskScope>,
244    /// Counter for generating unique task IDs.
245    pub(crate) task_counter: u64,
246    /// Counter for logical runtime-context task groups.
247    pub(crate) runtime_context_counter: u64,
248    /// Logical runtime task context visible through `runtime_context()`.
249    pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
250    /// Active deadline stack: (deadline_instant, frame_depth).
251    pub(crate) deadlines: Vec<(Instant, usize)>,
252    /// Breakpoints, keyed by source-file path so a breakpoint at line N
253    /// in `auto.harn` doesn't also fire when execution hits line N in an
254    /// imported lib. The empty-string key is a wildcard used by callers
255    /// that don't track source paths (legacy `set_breakpoints` API).
256    pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
257    /// Function-name breakpoints. Any closure call whose
258    /// `CompiledFunction.name` matches an entry here raises a stop on
259    /// entry, regardless of the call site's file or line. Lets the IDE
260    /// break on `llm_call` / `host_run_pipeline` / any user pipeline
261    /// function without pinning down a source location first.
262    pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
263    /// Latched on `push_closure_frame` when the callee's name matches
264    /// `function_breakpoints`; consumed by the next step so the stop is
265    /// reported with reason="function breakpoint" and the breakpoint
266    /// name available for the DAP `stopped` event.
267    pub(crate) pending_function_bp: Option<String>,
268    /// Whether the VM is in step mode.
269    pub(crate) step_mode: bool,
270    /// The frame depth at which stepping started (for step-over).
271    pub(crate) step_frame_depth: usize,
272    /// Whether the VM is currently stopped at a debug point.
273    pub(crate) stopped: bool,
274    /// Last source line executed (to detect line changes).
275    pub(crate) last_line: usize,
276    /// Source directory for resolving imports.
277    pub(crate) source_dir: Option<std::path::PathBuf>,
278    /// Modules currently being imported (cycle prevention).
279    pub(crate) imported_paths: Vec<std::path::PathBuf>,
280    /// Imports that hit an in-progress module (an import cycle) and so could
281    /// not bind inline. Drained by `flush_deferred_cyclic_imports` once the
282    /// involved modules finish loading.
283    pub(crate) deferred_cyclic_imports: Vec<super::modules::DeferredCyclicImport>,
284    /// Loaded module cache keyed by canonical or synthetic module path.
285    pub(crate) module_cache: Arc<BTreeMap<std::path::PathBuf, LoadedModule>>,
286    /// Source text keyed by canonical or synthetic module path for debugger retrieval.
287    pub(crate) source_cache: Arc<BTreeMap<std::path::PathBuf, String>>,
288    /// Source file path for error reporting.
289    pub(crate) source_file: Option<String>,
290    /// Source text for error reporting.
291    pub(crate) source_text: Option<String>,
292    /// Line-coverage accumulator. `Some` only while a coverage session is
293    /// active (see [`crate::coverage`]); folded into the global report on drop.
294    pub(crate) coverage: Option<crate::coverage::Coverage>,
295    /// Optional bridge for delegating unknown builtins in bridge mode.
296    pub(crate) bridge: Option<Arc<crate::bridge::HostBridge>>,
297    /// Builtins denied by sandbox mode (`--deny` / `--allow` flags).
298    pub(crate) denied_builtins: Arc<HashSet<String>>,
299    /// Cancellation token for cooperative graceful shutdown (set by parent).
300    pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
301    pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
302    /// Remaining instruction-boundary checks before a requested host
303    /// cancellation is forcefully raised. This gives `is_cancelled()` loops a
304    /// deterministic chance to return cleanly without letting non-cooperative
305    /// CPU-bound code run forever.
306    pub(crate) cancel_grace_instructions_remaining: Option<usize>,
307    /// User-visible interrupt handlers registered through `std/signal`.
308    pub(crate) interrupt_handlers: Vec<InterruptHandler>,
309    pub(crate) next_interrupt_handle: i64,
310    pub(crate) pending_interrupt_signal: Option<String>,
311    pub(crate) interrupted: bool,
312    pub(crate) dispatching_interrupt: bool,
313    pub(crate) interrupt_handler_deadline: Option<Instant>,
314    /// Captured stack trace from the most recent error (fn_name, line, col).
315    pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
316    /// Yield channel sender for generator execution. When set, `Op::Yield`
317    /// sends values through this channel instead of being a no-op.
318    pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
319    /// Project root directory (detected via harn.toml).
320    /// Used as base directory for metadata, store, and checkpoint operations.
321    pub(crate) project_root: Option<std::path::PathBuf>,
322    /// Global constants (e.g. `pi`, `e`). Checked as a fallback in `GetVar`
323    /// after the environment, so user-defined variables can shadow them.
324    pub(crate) globals: Arc<crate::value::DictMap>,
325    /// Optional debugger hook invoked when execution advances to a new source line.
326    pub(crate) debug_hook: Option<parking_lot::Mutex<Box<DebugHook>>>,
327    /// Effective runtime ceilings for this VM execution.
328    pub(crate) runtime_limits: RuntimeLimits,
329}
330
331/// Reusable VM baseline for hosts that need many clean executions with the
332/// same stable builtin/source setup.
333///
334/// The baseline intentionally does not snapshot execution state. Each
335/// instantiation gets fresh stacks, frames, tasks, cancellation fields, sync
336/// primitives, shared cells/maps/mailboxes, and debug state. Builtin tables are
337/// shared through `Arc` until a per-execution rebind needs copy-on-write.
338#[derive(Clone)]
339pub struct VmBaseline {
340    builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
341    async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
342    builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
343    builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
344    builtin_id_collisions: Arc<HashSet<BuiltinId>>,
345    source_dir: Option<std::path::PathBuf>,
346    source_file: Option<String>,
347    source_text: Option<String>,
348    project_root: Option<std::path::PathBuf>,
349    globals: Arc<crate::value::DictMap>,
350    denied_builtins: Arc<HashSet<String>>,
351    runtime_limits: RuntimeLimits,
352}
353
354impl VmBaseline {
355    pub fn from_vm(vm: &Vm) -> Self {
356        Self {
357            builtins: Arc::clone(&vm.builtins),
358            async_builtins: Arc::clone(&vm.async_builtins),
359            builtin_metadata: Arc::clone(&vm.builtin_metadata),
360            builtins_by_id: Arc::clone(&vm.builtins_by_id),
361            builtin_id_collisions: Arc::clone(&vm.builtin_id_collisions),
362            source_dir: vm.source_dir.clone(),
363            source_file: vm.source_file.clone(),
364            source_text: vm.source_text.clone(),
365            project_root: vm.project_root.clone(),
366            globals: Arc::clone(&vm.globals),
367            denied_builtins: Arc::clone(&vm.denied_builtins),
368            runtime_limits: vm.runtime_limits,
369        }
370    }
371
372    pub fn instantiate(&self) -> Vm {
373        let mut source_cache = BTreeMap::new();
374        if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
375            source_cache.insert(std::path::PathBuf::from(file), text.clone());
376        }
377        if let Some(dir) = &self.source_dir {
378            crate::stdlib::set_thread_source_dir(dir);
379        }
380
381        let mut vm = Vm {
382            stack: Vec::with_capacity(256),
383            env: VmEnv::new(),
384            output: String::new(),
385            builtins: Arc::clone(&self.builtins),
386            async_builtins: Arc::clone(&self.async_builtins),
387            builtin_metadata: Arc::clone(&self.builtin_metadata),
388            builtins_by_id: Arc::clone(&self.builtins_by_id),
389            builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
390            iterators: Vec::new(),
391            frames: Vec::new(),
392            exception_handlers: Vec::new(),
393            spawned_tasks: BTreeMap::new(),
394            sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
395            shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
396            inline_cache_sets: Vec::new(),
397            inline_cache_set_by_chunk: HashMap::new(),
398            pool_registry: crate::stdlib::pool::new_pool_registry(),
399            wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
400            held_sync_guards: Vec::new(),
401            inherited_held_keys: Arc::new(Vec::new()),
402            task_scopes: Vec::new(),
403            task_counter: 0,
404            runtime_context_counter: 0,
405            runtime_context: crate::runtime_context::RuntimeContext::root(),
406            deadlines: Vec::new(),
407            breakpoints: BTreeMap::new(),
408            function_breakpoints: std::collections::BTreeSet::new(),
409            pending_function_bp: None,
410            step_mode: false,
411            step_frame_depth: 0,
412            stopped: false,
413            last_line: 0,
414            source_dir: self.source_dir.clone(),
415            imported_paths: Vec::new(),
416            deferred_cyclic_imports: Vec::new(),
417            module_cache: Arc::new(BTreeMap::new()),
418            source_cache: Arc::new(source_cache),
419            source_file: self.source_file.clone(),
420            source_text: self.source_text.clone(),
421            coverage: crate::coverage::for_primary(self.source_file.as_deref()),
422            bridge: None,
423            denied_builtins: Arc::clone(&self.denied_builtins),
424            cancel_token: None,
425            interrupt_signal_token: None,
426            cancel_grace_instructions_remaining: None,
427            interrupt_handlers: Vec::new(),
428            next_interrupt_handle: 1,
429            pending_interrupt_signal: None,
430            interrupted: false,
431            dispatching_interrupt: false,
432            interrupt_handler_deadline: None,
433            error_stack_trace: Vec::new(),
434            yield_sender: None,
435            project_root: self.project_root.clone(),
436            globals: Arc::clone(&self.globals),
437            debug_hook: None,
438            runtime_limits: self.runtime_limits,
439        };
440
441        crate::stdlib::rebind_execution_state_builtins(&mut vm);
442        vm
443    }
444}
445
446impl Vm {
447    pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
448        chunk
449            .local_slots
450            .iter()
451            .map(|_| LocalSlot {
452                value: VmValue::Nil,
453                initialized: false,
454                synced: false,
455            })
456            .collect()
457    }
458
459    pub(crate) fn bind_param_slots(
460        slots: &mut [LocalSlot],
461        func: &crate::chunk::CompiledFunction,
462        args: &[VmValue],
463        synced: bool,
464    ) {
465        Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
466    }
467
468    pub(crate) fn bind_param_slots_args(
469        slots: &mut [LocalSlot],
470        func: &crate::chunk::CompiledFunction,
471        args: &super::CallArgs<'_>,
472        synced: bool,
473    ) {
474        let param_count = func.params.len();
475        for (i, _param) in func.params.iter().enumerate() {
476            if i >= slots.len() {
477                break;
478            }
479            if func.has_rest_param && i == param_count - 1 {
480                let rest_args = args.to_vec_from(i);
481                slots[i].value = VmValue::List(std::sync::Arc::new(rest_args));
482                slots[i].initialized = true;
483                slots[i].synced = synced;
484            } else if let Some(arg) = args.get(i) {
485                slots[i].value = arg.clone();
486                slots[i].initialized = true;
487                slots[i].synced = synced;
488            }
489        }
490    }
491
492    pub(crate) fn visible_variables(&self) -> crate::value::DictMap {
493        let mut vars = self.env.all_variables();
494        let Some(frame) = self.frames.last() else {
495            return vars;
496        };
497        for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
498            if slot.initialized && info.scope_depth <= frame.local_scope_depth {
499                vars.insert(crate::value::intern_key(&info.name), slot.value.clone());
500            }
501        }
502        vars
503    }
504
505    pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
506        let frames = &mut self.frames;
507        let env = &mut self.env;
508        let Some(frame) = frames.last_mut() else {
509            return;
510        };
511        let local_scope_base = frame.local_scope_base;
512        let local_scope_depth = frame.local_scope_depth;
513        for (slot, info) in frame
514            .local_slots
515            .iter_mut()
516            .zip(frame.chunk.local_slots.iter())
517        {
518            if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
519                slot.synced = true;
520                let scope_idx = local_scope_base + info.scope_depth;
521                while env.scopes.len() <= scope_idx {
522                    env.push_scope();
523                }
524                // Slot-backed locals are never boxed captures (those resolve
525                // to `None` in the compiler and are defined straight into the
526                // env as `Cell`s), so syncing a slot always yields a `Value`.
527                Arc::make_mut(&mut env.scopes[scope_idx].vars).insert(
528                    info.name.clone(),
529                    crate::value::Binding::Value {
530                        value: slot.value.clone(),
531                        mutable: info.mutable,
532                    },
533                );
534            }
535        }
536    }
537
538    pub(crate) fn closure_call_env_for_current_frame(
539        &self,
540        closure: &crate::value::VmClosure,
541    ) -> VmEnv {
542        if closure.module_state().is_some() {
543            return closure.env.cloned_for_call();
544        }
545        let call_env = Self::closure_call_env(&self.env, closure);
546        // Same compile-time short-circuit as the env walk in
547        // `closure_call_env`: when the callee body never resolves an
548        // outer name through the env, injecting closure-typed *slot*
549        // locals from the caller's frame is wasted work too.
550        if !closure.func.chunk.references_outer_names {
551            return call_env;
552        }
553        let mut call_env = call_env;
554        let Some(frame) = self.frames.last() else {
555            return call_env;
556        };
557        for (slot, info) in frame
558            .local_slots
559            .iter()
560            .zip(frame.chunk.local_slots.iter())
561            .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
562        {
563            if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
564                let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
565            }
566        }
567        call_env
568    }
569
570    pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
571        let frame = self.frames.last()?;
572        let idx = self.active_local_slot_index(name)?;
573        frame.local_slots.get(idx).map(|slot| slot.value.clone())
574    }
575
576    /// Returns the slot index of an initialized active local with the given
577    /// name, walking from innermost to outermost scope. Used by legacy by-name
578    /// hot paths that still want to mutate the slot value in place without
579    /// paying a defensive `VmValue::clone` first.
580    pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
581        let frame = self.frames.last()?;
582        for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
583            if info.name == name && info.scope_depth <= frame.local_scope_depth {
584                if let Some(slot) = frame.local_slots.get(idx) {
585                    if slot.initialized {
586                        return Some(idx);
587                    }
588                }
589            }
590        }
591        None
592    }
593
594    pub(crate) fn assign_active_local_slot(
595        &mut self,
596        name: &str,
597        value: VmValue,
598        debug: bool,
599    ) -> Result<bool, VmError> {
600        let Some(frame) = self.frames.last_mut() else {
601            return Ok(false);
602        };
603        for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
604            if info.name == name && info.scope_depth <= frame.local_scope_depth {
605                if !debug && !info.mutable {
606                    return Err(VmError::ImmutableAssignment(name.to_string()));
607                }
608                if let Some(slot) = frame.local_slots.get_mut(idx) {
609                    crate::value::recursion::dismantle(std::mem::replace(&mut slot.value, value));
610                    slot.initialized = true;
611                    slot.synced = false;
612                    return Ok(true);
613                }
614            }
615        }
616        Ok(false)
617    }
618
619    pub fn new() -> Self {
620        Self {
621            stack: Vec::with_capacity(256),
622            env: VmEnv::new(),
623            output: String::new(),
624            builtins: Arc::new(BTreeMap::new()),
625            async_builtins: Arc::new(BTreeMap::new()),
626            builtin_metadata: Arc::new(BTreeMap::new()),
627            builtins_by_id: Arc::new(HashMap::new()),
628            builtin_id_collisions: Arc::new(HashSet::new()),
629            iterators: Vec::new(),
630            frames: Vec::new(),
631            exception_handlers: Vec::new(),
632            spawned_tasks: BTreeMap::new(),
633            sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
634            shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
635            inline_cache_sets: Vec::new(),
636            inline_cache_set_by_chunk: HashMap::new(),
637            pool_registry: crate::stdlib::pool::new_pool_registry(),
638            wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
639            held_sync_guards: Vec::new(),
640            inherited_held_keys: Arc::new(Vec::new()),
641            task_scopes: Vec::new(),
642            task_counter: 0,
643            runtime_context_counter: 0,
644            runtime_context: crate::runtime_context::RuntimeContext::root(),
645            deadlines: Vec::new(),
646            breakpoints: BTreeMap::new(),
647            function_breakpoints: std::collections::BTreeSet::new(),
648            pending_function_bp: None,
649            step_mode: false,
650            step_frame_depth: 0,
651            stopped: false,
652            last_line: 0,
653            source_dir: None,
654            imported_paths: Vec::new(),
655            deferred_cyclic_imports: Vec::new(),
656            module_cache: Arc::new(BTreeMap::new()),
657            source_cache: Arc::new(BTreeMap::new()),
658            source_file: None,
659            source_text: None,
660            coverage: crate::coverage::for_primary(None),
661            bridge: None,
662            denied_builtins: Arc::new(HashSet::new()),
663            cancel_token: None,
664            interrupt_signal_token: None,
665            cancel_grace_instructions_remaining: None,
666            interrupt_handlers: Vec::new(),
667            next_interrupt_handle: 1,
668            pending_interrupt_signal: None,
669            interrupted: false,
670            dispatching_interrupt: false,
671            interrupt_handler_deadline: None,
672            error_stack_trace: Vec::new(),
673            yield_sender: None,
674            project_root: None,
675            globals: Arc::new(crate::value::DictMap::new()),
676            debug_hook: None,
677            runtime_limits: RuntimeLimits::default(),
678        }
679    }
680
681    pub fn baseline(&self) -> VmBaseline {
682        VmBaseline::from_vm(self)
683    }
684
685    /// Return the effective runtime limit profile for this VM.
686    pub fn runtime_limits(&self) -> RuntimeLimits {
687        self.runtime_limits
688    }
689
690    /// Return a host/debug report describing the VM's effective runtime limits.
691    pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
692        self.runtime_limits.report()
693    }
694
695    /// Returns true if any debugging affordance is active — DAP hook,
696    /// line breakpoints, or function breakpoints. Call-site code uses
697    /// this to decide whether to capture per-frame restart snapshots
698    /// (`initial_env`, `initial_local_slots`); without a debugger those
699    /// snapshots are dead weight, so skipping them removes two
700    /// allocations from every function call hot path.
701    ///
702    /// All three signals are stable across a function call's lifetime
703    /// (they're set before pipeline execution starts), so the gate is
704    /// consistent between frame creation and any later `restart_frame`
705    /// invocation. The three `is_empty` checks compile to a handful of
706    /// branch-predicted memory probes — cheaper than a single
707    /// `BTreeMap` clone, which is what we're avoiding.
708    #[inline]
709    pub(crate) fn debugger_attached(&self) -> bool {
710        self.debug_hook.is_some()
711            || !self.breakpoints.is_empty()
712            || !self.function_breakpoints.is_empty()
713    }
714
715    /// Set the bridge for delegating unknown builtins in bridge mode.
716    pub fn set_bridge(&mut self, bridge: Arc<crate::bridge::HostBridge>) {
717        self.bridge = Some(bridge);
718    }
719
720    /// Set builtins that are denied in sandbox mode.
721    /// When called, the given builtin names will produce a permission error.
722    pub fn set_denied_builtins(&mut self, denied: HashSet<String>) {
723        self.denied_builtins = Arc::new(denied);
724    }
725
726    /// Set source info for error reporting (file path and source text).
727    pub fn set_source_info(&mut self, file: &str, text: &str) {
728        self.source_file = Some(file.to_string());
729        self.source_text = Some(text.to_string());
730        if let Some(cov) = self.coverage.as_mut() {
731            cov.set_primary_file(file);
732        }
733        Arc::make_mut(&mut self.source_cache)
734            .insert(std::path::PathBuf::from(file), text.to_string());
735    }
736
737    /// Initialize execution (push the initial frame).
738    pub fn start(&mut self, chunk: &Chunk) {
739        // The top-level pipeline frame captures env at start so
740        // restartFrame on the outermost frame rewinds to the
741        // pre-pipeline state — basically "restart session" in
742        // debugger terms. Skipped when no debugger is attached:
743        // the snapshot is dead weight in that case and dominates
744        // call-overhead bench numbers (~5-10%).
745        let debugger = self.debugger_attached();
746        let initial_env = if debugger {
747            Some(self.env.clone())
748        } else {
749            None
750        };
751        let initial_local_slots = if debugger {
752            Some(Self::fresh_local_slots(chunk))
753        } else {
754            None
755        };
756        let chunk = Arc::new(chunk.clone());
757        let local_slots = Self::fresh_local_slots(&chunk);
758        let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
759        self.frames.push(CallFrame {
760            chunk,
761            inline_cache_set,
762            ip: 0,
763            stack_base: self.stack.len(),
764            saved_env: self.env.clone(),
765            initial_env,
766            initial_local_slots,
767            saved_iterator_depth: self.iterators.len(),
768            fn_name: String::new(),
769            argc: 0,
770            saved_source_dir: None,
771            module_functions: None,
772            module_state: None,
773            local_slots,
774            local_scope_base: self.env.scope_depth().saturating_sub(1),
775            local_scope_depth: 0,
776        });
777    }
778
779    /// Create a child VM that shares builtins and env but has fresh execution state.
780    /// Used for parallel/spawn to fork the VM for concurrent tasks.
781    pub(crate) fn child_vm(&self) -> Vm {
782        Vm {
783            stack: Vec::with_capacity(64),
784            env: self.env.clone(),
785            output: String::new(),
786            builtins: Arc::clone(&self.builtins),
787            async_builtins: Arc::clone(&self.async_builtins),
788            builtin_metadata: Arc::clone(&self.builtin_metadata),
789            builtins_by_id: Arc::clone(&self.builtins_by_id),
790            builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
791            iterators: Vec::new(),
792            frames: Vec::new(),
793            exception_handlers: Vec::new(),
794            spawned_tasks: BTreeMap::new(),
795            sync_runtime: self.sync_runtime.clone(),
796            shared_state_runtime: self.shared_state_runtime.clone(),
797            inline_cache_sets: Vec::new(),
798            inline_cache_set_by_chunk: HashMap::new(),
799            pool_registry: self.pool_registry.clone(),
800            wait_for_graph: self.wait_for_graph.clone(),
801            held_sync_guards: Vec::new(),
802            inherited_held_keys: Arc::new(Vec::new()),
803            task_scopes: Vec::new(),
804            task_counter: 0,
805            runtime_context_counter: self.runtime_context_counter,
806            runtime_context: self.runtime_context.clone(),
807            deadlines: self.deadlines.clone(),
808            breakpoints: BTreeMap::new(),
809            function_breakpoints: std::collections::BTreeSet::new(),
810            pending_function_bp: None,
811            step_mode: false,
812            step_frame_depth: 0,
813            stopped: false,
814            last_line: 0,
815            source_dir: self.source_dir.clone(),
816            imported_paths: Vec::new(),
817            deferred_cyclic_imports: Vec::new(),
818            module_cache: Arc::clone(&self.module_cache),
819            source_cache: Arc::clone(&self.source_cache),
820            source_file: self.source_file.clone(),
821            source_text: self.source_text.clone(),
822            coverage: crate::coverage::for_primary(self.source_file.as_deref()),
823            bridge: self.bridge.clone(),
824            denied_builtins: Arc::clone(&self.denied_builtins),
825            cancel_token: self.cancel_token.clone(),
826            interrupt_signal_token: self.interrupt_signal_token.clone(),
827            cancel_grace_instructions_remaining: None,
828            interrupt_handlers: Vec::new(),
829            next_interrupt_handle: 1,
830            pending_interrupt_signal: None,
831            interrupted: self.interrupted,
832            dispatching_interrupt: false,
833            interrupt_handler_deadline: None,
834            error_stack_trace: Vec::new(),
835            yield_sender: None,
836            project_root: self.project_root.clone(),
837            globals: Arc::clone(&self.globals),
838            debug_hook: None,
839            runtime_limits: self.runtime_limits,
840        }
841    }
842
843    /// Create a child VM for external adapters that need to invoke Harn
844    /// closures while sharing the parent's builtins, globals, and module state.
845    pub(crate) fn child_vm_for_host(&self) -> Vm {
846        self.child_vm()
847    }
848
849    /// Request cancellation for every outstanding child task owned by this VM
850    /// and then abort the join handles. This prevents un-awaited spawned tasks
851    /// from outliving their parent execution scope.
852    pub(crate) fn cancel_spawned_tasks(&mut self) {
853        for (_, task) in std::mem::take(&mut self.spawned_tasks) {
854            task.cancel_token
855                .store(true, std::sync::atomic::Ordering::SeqCst);
856            task.handle.abort();
857        }
858    }
859
860    /// Set the source directory for import resolution and introspection.
861    /// Also auto-detects the project root if not already set.
862    pub fn set_source_dir(&mut self, dir: &std::path::Path) {
863        let dir = crate::stdlib::process::normalize_context_path(dir);
864        self.source_dir = Some(dir.clone());
865        crate::stdlib::set_thread_source_dir(&dir);
866        // Auto-detect project root if not explicitly set.
867        if self.project_root.is_none() {
868            self.project_root = crate::stdlib::process::find_project_root(&dir);
869        }
870    }
871
872    /// Explicitly set the project root directory.
873    /// Used by ACP/CLI to override auto-detection.
874    pub fn set_project_root(&mut self, root: &std::path::Path) {
875        self.project_root = Some(root.to_path_buf());
876    }
877
878    /// Get only the explicit or auto-detected project root, without falling
879    /// back to `source_dir`.
880    pub(crate) fn explicit_project_root(&self) -> Option<&std::path::Path> {
881        self.project_root.as_deref()
882    }
883
884    /// Get the project root directory, falling back to source_dir.
885    pub fn project_root(&self) -> Option<&std::path::Path> {
886        self.project_root.as_deref().or(self.source_dir.as_deref())
887    }
888
889    /// Return all registered builtin names (sync + async).
890    pub fn builtin_names(&self) -> Vec<String> {
891        let mut names: Vec<String> = self.builtins.keys().cloned().collect();
892        names.extend(self.async_builtins.keys().cloned());
893        names
894    }
895
896    /// Return discoverable metadata for registered builtins.
897    pub fn builtin_metadata(&self) -> Vec<VmBuiltinMetadata> {
898        self.builtin_metadata.values().cloned().collect()
899    }
900
901    /// Return discoverable metadata for a registered builtin name.
902    pub fn builtin_metadata_for(&self, name: &str) -> Option<&VmBuiltinMetadata> {
903        self.builtin_metadata.get(name)
904    }
905
906    /// Set a global constant (e.g. `pi`, `e`).
907    /// Stored separately from the environment so user-defined variables can shadow them.
908    pub fn set_global(&mut self, name: &str, value: VmValue) {
909        Arc::make_mut(&mut self.globals).insert(crate::value::intern_key(name), value);
910    }
911
912    /// Read a previously-installed global (the value `set_global` /
913    /// `set_harness` recorded). Returns `None` for unknown names.
914    /// Hosts use this to look up runtime-installed capability handles
915    /// (e.g. the `harness` slot) without having to track them
916    /// separately.
917    pub fn global(&self, name: &str) -> Option<&VmValue> {
918        self.globals.get(name)
919    }
920
921    /// Install the script's `Harness` capability handle as the `harness`
922    /// global so the auto-call emitted by `Compiler::compile()` (for
923    /// `fn main(harness: Harness)` entrypoints) can read it. Hosts that
924    /// drive the VM directly (CLI, MCP server, composition runtime) call
925    /// this once before `execute()`.
926    pub fn set_harness(&mut self, harness: crate::harness::Harness) {
927        self.set_global("harness", harness.into_vm_value());
928    }
929
930    /// Get the captured output.
931    pub fn output(&self) -> &str {
932        &self.output
933    }
934
935    /// Drain and return the captured output, leaving the buffer empty.
936    /// Used by the async-builtin dispatch path to forward closure output
937    /// from a child VM back to its parent.
938    pub fn take_output(&mut self) -> String {
939        std::mem::take(&mut self.output)
940    }
941
942    /// Append text to this VM's captured output. Used to forward output
943    /// from child VMs (e.g. closures invoked via `call_closure_pub`)
944    /// back into the parent stream.
945    pub fn append_output(&mut self, text: &str) {
946        self.output.push_str(text);
947    }
948
949    pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
950        self.stack.pop().ok_or(VmError::StackUnderflow)
951    }
952
953    pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
954        self.stack.last().ok_or(VmError::StackUnderflow)
955    }
956
957    pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
958        match c {
959            Constant::String(s) => Ok(s.as_str()),
960            _ => Err(VmError::TypeError("expected string constant".into())),
961        }
962    }
963
964    pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
965        let depth = self.env.scope_depth();
966        self.held_sync_guards
967            .retain(|guard| guard.env_scope_depth < depth);
968        // A `scope { }` torn down without a normal `TaskScopeExit` (break /
969        // continue out of it) leaves a dangling nursery — cancel its tasks.
970        self.cancel_task_scopes_where(|s| s.env_scope_depth >= depth);
971    }
972
973    pub(crate) fn release_sync_guards_after_unwind(
974        &mut self,
975        frame_depth: usize,
976        env_scope_depth: usize,
977    ) {
978        self.held_sync_guards.retain(|guard| {
979            guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
980        });
981        // Cancel nurseries opened above the catch handler (a `throw` unwound
982        // past their `TaskScopeExit`).
983        self.cancel_task_scopes_where(|s| {
984            !(s.frame_depth <= frame_depth && s.env_scope_depth <= env_scope_depth)
985        });
986    }
987
988    pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
989        self.held_sync_guards
990            .retain(|guard| guard.frame_depth != frame_depth);
991        // Cancel any nursery whose `scope {}` block belonged to the frame being
992        // torn down (e.g. a `return` jumped past its `TaskScopeExit`).
993        self.cancel_task_scopes_where(|s| s.frame_depth == frame_depth);
994    }
995
996    pub(crate) fn adopt_sync_permit_for_current_scope(
997        &mut self,
998        permit: crate::value::VmSyncPermitHandle,
999    ) {
1000        if permit.is_released()
1001            || self
1002                .held_sync_guards
1003                .iter()
1004                .any(|guard| guard._permit.same_lease(&permit))
1005        {
1006            return;
1007        }
1008        self.held_sync_guards
1009            .push(crate::synchronization::VmSyncHeldGuard {
1010                _permit: permit,
1011                frame_depth: self.frames.len(),
1012                env_scope_depth: self.env.scope_depth(),
1013            });
1014    }
1015
1016    /// Deregister a task id from every open nursery (it was explicitly
1017    /// `await`ed, so it must not be double-joined or cancelled at scope exit).
1018    pub(crate) fn deregister_task_from_scopes(&mut self, id: &str) {
1019        for scope in &mut self.task_scopes {
1020            scope.task_ids.retain(|t| t != id);
1021        }
1022    }
1023
1024    /// Cancel and remove every task scope matching `doomed`, aborting its bound
1025    /// tasks (used when a `scope {}` is torn down without a normal join).
1026    fn cancel_task_scopes_where<F: Fn(&TaskScope) -> bool>(&mut self, doomed: F) {
1027        let mut i = 0;
1028        while i < self.task_scopes.len() {
1029            if doomed(&self.task_scopes[i]) {
1030                let scope = self.task_scopes.remove(i);
1031                for id in &scope.task_ids {
1032                    if let Some(task) = self.spawned_tasks.remove(id) {
1033                        task.cancel_token
1034                            .store(true, std::sync::atomic::Ordering::SeqCst);
1035                        task.handle.abort();
1036                    }
1037                }
1038            } else {
1039                i += 1;
1040            }
1041        }
1042    }
1043
1044    /// Total live permits this VM already holds for `kind:key`. The held-set is
1045    /// tiny (bounded by lexical nesting and explicit sync acquisitions), so this
1046    /// scan is cheap and only runs on the rare blocking-acquire path.
1047    pub(crate) fn held_permits_for(&self, kind: &str, key: &str) -> u32 {
1048        let own: u32 = self
1049            .held_sync_guards
1050            .iter()
1051            .filter(|guard| {
1052                !guard._permit.is_released()
1053                    && guard._permit.kind() == kind
1054                    && guard._permit.key() == key
1055            })
1056            .map(|guard| guard._permit.permits())
1057            .sum();
1058        let inherited: u32 = self
1059            .inherited_held_keys
1060            .iter()
1061            .filter(|held| held.kind == kind && held.key == key)
1062            .map(|held| held.permits)
1063            .sum();
1064        own + inherited
1065    }
1066
1067    /// Every live sync permit held by this VM *and* its suspended ancestors: the
1068    /// transitive held-set seen by an inline child.
1069    pub(crate) fn combined_held_keys(&self) -> Vec<crate::synchronization::VmSyncHeldKey> {
1070        let mut keys: Vec<crate::synchronization::VmSyncHeldKey> = self
1071            .held_sync_guards
1072            .iter()
1073            .filter_map(|guard| crate::synchronization::VmSyncHeldKey::from_permit(&guard._permit))
1074            .collect();
1075        keys.extend(self.inherited_held_keys.iter().cloned());
1076        keys
1077    }
1078
1079    /// Clone a child VM for an **inline, same-task** execution (an async builtin
1080    /// awaited while this VM is parked, or a user closure that builtin runs and
1081    /// awaits). The child inherits this VM's transitive held-lock keys so a
1082    /// re-acquire of a parent-held lock is caught as a self-deadlock
1083    /// (HARN-ORC-011). Use plain `child_vm()` for new concurrent tasks.
1084    pub(crate) fn child_vm_inline(&self) -> Vm {
1085        let mut child = self.child_vm();
1086        child.inherited_held_keys = Arc::new(self.combined_held_keys());
1087        child
1088    }
1089}
1090
1091impl Drop for Vm {
1092    fn drop(&mut self) {
1093        if let Some(coverage) = self.coverage.take() {
1094            crate::coverage::merge_into_global(coverage);
1095        }
1096        self.cancel_spawned_tasks();
1097    }
1098}
1099
1100impl Default for Vm {
1101    fn default() -> Self {
1102        Self::new()
1103    }
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108
1109    use super::*;
1110
1111    fn baseline_with_stdlib(source: &str) -> VmBaseline {
1112        let mut vm = Vm::new();
1113        crate::register_vm_stdlib(&mut vm);
1114        vm.set_source_info("baseline_test.harn", source);
1115        vm.set_global(
1116            "stable_global",
1117            VmValue::String(arcstr::ArcStr::from("baseline")),
1118        );
1119        vm.baseline()
1120    }
1121
1122    #[test]
1123    fn vm_baseline_instantiates_clean_mutable_execution_state() {
1124        let baseline = baseline_with_stdlib("pipeline main() { __io_println(stable_global) }");
1125
1126        let mut dirty = baseline.instantiate();
1127        dirty.stack.push(VmValue::Int(42));
1128        dirty.output.push_str("dirty");
1129        dirty.task_counter = 9;
1130        dirty.runtime_context_counter = 7;
1131        dirty
1132            .error_stack_trace
1133            .push(("main".to_string(), 1, 1, None));
1134
1135        let clean = baseline.instantiate();
1136        assert!(clean.stack.is_empty());
1137        assert!(clean.output.is_empty());
1138        assert!(clean.frames.is_empty());
1139        assert!(clean.exception_handlers.is_empty());
1140        assert!(clean.spawned_tasks.is_empty());
1141        assert!(clean.held_sync_guards.is_empty());
1142        assert_eq!(clean.task_counter, 0);
1143        assert_eq!(clean.runtime_context_counter, 0);
1144        assert!(clean.deadlines.is_empty());
1145        assert!(clean.cancel_token.is_none());
1146        assert!(clean.interrupt_handlers.is_empty());
1147        assert!(clean.error_stack_trace.is_empty());
1148        assert!(clean.bridge.is_none());
1149        assert!(clean
1150            .globals
1151            .get("stable_global")
1152            .is_some_and(|value| value.display() == "baseline"));
1153    }
1154
1155    #[tokio::test]
1156    async fn inline_child_inherits_held_lock_keys_but_concurrent_child_does_not() {
1157        let mut parent = Vm::new();
1158        let permit = parent
1159            .sync_runtime
1160            .acquire("mutex", "v:test", 1, 1, None, None)
1161            .await
1162            .unwrap()
1163            .unwrap();
1164        parent
1165            .held_sync_guards
1166            .push(crate::synchronization::VmSyncHeldGuard {
1167                _permit: permit,
1168                frame_depth: 0,
1169                env_scope_depth: 0,
1170            });
1171        assert_eq!(parent.held_permits_for("mutex", "v:test"), 1);
1172
1173        // An inline child (async builtin awaited while the parent is parked, or
1174        // a closure the builtin runs inline) inherits the held key, so a
1175        // re-acquire is caught as a cross-context self-deadlock (HARN-ORC-011)
1176        // — even transitively through a further inline child.
1177        let inline = parent.child_vm_inline();
1178        assert_eq!(inline.held_permits_for("mutex", "v:test"), 1);
1179        assert_eq!(
1180            inline.child_vm_inline().held_permits_for("mutex", "v:test"),
1181            1
1182        );
1183
1184        // A new concurrent task (spawn / parallel / trigger) does NOT inherit:
1185        // blocking on a parent-held lock there is legitimately resolvable, so
1186        // flagging it would be a false positive.
1187        let concurrent = parent.child_vm();
1188        assert_eq!(concurrent.held_permits_for("mutex", "v:test"), 0);
1189    }
1190
1191    #[test]
1192    fn vm_reports_effective_runtime_limits() {
1193        let vm = Vm::new();
1194
1195        assert_eq!(vm.runtime_limits(), RuntimeLimits::default());
1196        assert_eq!(
1197            vm.runtime_limit_report().entries.len(),
1198            crate::RUNTIME_LIMIT_DESCRIPTIONS.len()
1199        );
1200        assert_eq!(vm.child_vm().runtime_limits(), vm.runtime_limits());
1201        assert_eq!(
1202            vm.baseline().instantiate().runtime_limits(),
1203            vm.runtime_limits()
1204        );
1205    }
1206
1207    #[tokio::test(flavor = "current_thread")]
1208    async fn vm_baseline_rebinds_shared_state_builtins_per_instance() {
1209        let local = tokio::task::LocalSet::new();
1210        local
1211            .run_until(async {
1212                let source = r#"
1213pipeline main() {
1214  const cell = shared_cell({scope: "task_group", key: "turn", initial: 0})
1215  __io_println(shared_get(cell))
1216  shared_set(cell, shared_get(cell) + 1)
1217}"#;
1218                let chunk = crate::compile_source(source).expect("compile");
1219                let baseline = baseline_with_stdlib(source);
1220
1221                let mut first = baseline.instantiate();
1222                first.execute(&chunk).await.expect("first execute");
1223                assert_eq!(first.output(), "0\n");
1224
1225                let mut second = baseline.instantiate();
1226                second.execute(&chunk).await.expect("second execute");
1227                assert_eq!(
1228                    second.output(),
1229                    "0\n",
1230                    "shared state created by the first VM must not leak into the next baseline instance"
1231                );
1232            })
1233            .await;
1234    }
1235}