Skip to main content

harn_vm/vm/
state.rs

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