Skip to main content

harn_vm/vm/
execution.rs

1use std::sync::Arc;
2use std::time::{Duration, Instant};
3
4use crate::chunk::{Chunk, ChunkRef, Op};
5use crate::value::{ModuleFunctionRegistry, VmError, VmValue};
6
7use super::{CallFrame, LocalSlot, Vm};
8
9const CANCEL_GRACE_ASYNC_OP: Duration = Duration::from_millis(250);
10
11#[derive(Clone, Copy)]
12enum DeadlineKind {
13    Scope,
14    InterruptHandler,
15}
16
17impl Vm {
18    /// Returns true when no scope-level async machinery is armed. The hot
19    /// interpreter loop uses this to skip both the `pending_scope_interrupt`
20    /// future and the `execute_op_with_scope_interrupts` `tokio::select!`
21    /// wrapper on every dispatch — both are necessary for cancellable /
22    /// deadlined VMs but pure overhead in the common case (benchmarks,
23    /// background script execution, etc.).
24    #[inline]
25    pub(crate) fn scope_interrupts_clean(&self) -> bool {
26        self.cancel_token.is_none()
27            && self.interrupt_signal_token.is_none()
28            && self.pending_interrupt_signal.is_none()
29            && self.interrupt_handler_deadline.is_none()
30            && self.deadlines.is_empty()
31    }
32
33    /// Execute a compiled chunk.
34    ///
35    /// Convenience entry point for callers that hold a borrowed [`Chunk`] and
36    /// run it once (tests, one-shot CLI invocations). It clones the chunk once
37    /// to obtain the owned [`ChunkRef`] the call frame requires. Callers that
38    /// re-run the same compiled chunk (servers, record filters, triggers)
39    /// should hold a [`ChunkRef`] and call [`Vm::execute_arc`] to skip the
40    /// per-execution deep copy of the bytecode + constant pool.
41    pub async fn execute(&mut self, chunk: &Chunk) -> Result<VmValue, VmError> {
42        self.execute_arc(Arc::new(chunk.clone())).await
43    }
44
45    /// Execute a shared compiled chunk without cloning its bytecode.
46    ///
47    /// Threads the existing [`ChunkRef`] straight into the call frame, so
48    /// re-running the same chunk is a refcount bump rather than an
49    /// `O(code + constants)` copy.
50    pub async fn execute_arc(&mut self, chunk: ChunkRef) -> Result<VmValue, VmError> {
51        let registry = self.pool_registry.clone();
52        crate::stdlib::pool::with_pool_registry_scope(registry, async {
53            self.execute_scoped(chunk).await
54        })
55        .await
56    }
57
58    async fn execute_scoped(&mut self, chunk: ChunkRef) -> Result<VmValue, VmError> {
59        let _execution_activity = self
60            .wait_for_graph
61            .register_task(self.runtime_context.task_id.clone());
62        let span_id = crate::tracing::span_start(crate::tracing::SpanKind::Pipeline, "main".into());
63        let result = self.run_chunk(chunk).await;
64        let result = match result {
65            Ok(value) => self.run_pipeline_finish_lifecycle(value).await,
66            Err(error) => {
67                crate::orchestration::clear_pipeline_on_finish();
68                Err(error)
69            }
70        };
71        crate::tracing::span_end(span_id);
72        result
73    }
74
75    /// Run the pipeline-finish lifecycle: `PreFinish`, optional
76    /// `OnUnsettledDetected`, the `on_finish` callback, `PostFinish`. The
77    /// callback (if registered) may transform the return value; everything
78    /// else is advisory.
79    ///
80    /// Tracked: <https://github.com/burin-labs/harn/issues/1854>.
81    async fn run_pipeline_finish_lifecycle(&mut self, value: VmValue) -> Result<VmValue, VmError> {
82        use crate::orchestration::{
83            take_pipeline_on_finish, unsettled_state_snapshot_async, HookEvent,
84        };
85        let _tape_phase =
86            crate::testbench::tape::enter_phase(crate::testbench::tape::TapePhase::RuntimeFinalize);
87
88        let on_finish = take_pipeline_on_finish();
89        let unsettled = unsettled_state_snapshot_async().await;
90
91        let pre_payload = serde_json::json!({
92            "event": HookEvent::PreFinish.as_str(),
93            "return_value": crate::llm::vm_value_to_json(&value),
94            "unsettled": unsettled.to_json(),
95            "has_on_finish": on_finish.is_some(),
96        });
97        self.fire_finish_lifecycle_event(HookEvent::PreFinish, &pre_payload)
98            .await?;
99
100        if !unsettled.is_empty() {
101            let payload = serde_json::json!({
102                "event": HookEvent::OnUnsettledDetected.as_str(),
103                "unsettled": unsettled.to_json(),
104            });
105            self.fire_finish_lifecycle_event(HookEvent::OnUnsettledDetected, &payload)
106                .await?;
107        }
108
109        let final_value = if let Some(closure) = on_finish {
110            let harness_value = crate::harness::Harness::real().into_vm_value();
111            self.call_closure_pub(&closure, &[harness_value, value])
112                .await?
113        } else {
114            value
115        };
116
117        let post_payload = serde_json::json!({
118            "event": HookEvent::PostFinish.as_str(),
119            "return_value": crate::llm::vm_value_to_json(&final_value),
120            "unsettled": unsettled.to_json(),
121        });
122        self.fire_finish_lifecycle_event(HookEvent::PostFinish, &post_payload)
123            .await?;
124
125        Ok(final_value)
126    }
127
128    /// Dispatch a pipeline-finish lifecycle event by invoking matching
129    /// hook closures directly on `self`. The shared `run_lifecycle_hooks`
130    /// path clones a fresh child VM per call and discards its stdout —
131    /// fine for the agent-loop boundaries where hooks are advisory side-
132    /// channels, but the pipeline-finish boundary is the script's last
133    /// chance to print before `vm.output()` is captured, so the closures
134    /// run on `self` to keep their output visible.
135    ///
136    /// Honors the lifecycle control contract (harn#1859):
137    ///   * `PreFinish` rejects `Block` outright — surfaces a runtime
138    ///     error pointing the user at `OnFinish.block_until_settled`.
139    ///     `PostFinish` ignores any control return (advisory only).
140    ///   * `OnUnsettledDetected` honors `Block` to abort the finish
141    ///     lifecycle until the unsettled work clears.
142    ///   * Modify returns are recorded but not consumed at this boundary
143    ///     (the dispatcher already replays subsequent hooks with the
144    ///     post-modify payload via `run_lifecycle_hooks_with_control`).
145    async fn fire_finish_lifecycle_event(
146        &mut self,
147        event: crate::orchestration::HookEvent,
148        payload: &serde_json::Value,
149    ) -> Result<(), VmError> {
150        use crate::orchestration::{HookControl, HookEvent};
151        let invocations = crate::orchestration::matching_vm_lifecycle_hooks(event, payload);
152        if invocations.is_empty() {
153            return Ok(());
154        }
155        let mut current_payload = payload.clone();
156        for invocation in invocations {
157            let arg = crate::stdlib::json_to_vm_value(&current_payload);
158            let closure = invocation.resolve(self).await?;
159            let raw = self.call_closure_pub(&closure, &[arg]).await?;
160            let (action, effects) = crate::orchestration::collect_hook_effects_and_action(
161                event,
162                raw,
163                crate::value::VmValue::Nil,
164            )?;
165            crate::orchestration::inject_hook_effects_into_current_session(effects)?;
166            let control = crate::orchestration::parse_hook_control_for_finish(event, &action)?;
167            match control {
168                HookControl::Allow => {}
169                HookControl::Block { reason } => {
170                    if matches!(event, HookEvent::PreFinish) {
171                        return Err(VmError::Runtime(format!(
172                            "PreFinish hook returned block, which is not a valid control: {reason}. \
173                             To delay pipeline finish until unsettled work clears, use \
174                             OnFinish.block_until_settled (std/lifecycle) or return Modify/Allow \
175                             from PreFinish."
176                        )));
177                    }
178                    if matches!(event, HookEvent::PostFinish) {
179                        // Advisory only; ignore block returns from PostFinish.
180                        continue;
181                    }
182                    // OnUnsettledDetected: block aborts the finish lifecycle.
183                    return Err(VmError::Runtime(format!(
184                        "{} hook blocked pipeline finish: {reason}",
185                        event.as_str()
186                    )));
187                }
188                HookControl::Modify { payload: modified } => {
189                    current_payload = modified;
190                }
191                HookControl::Decision { .. } => {}
192            }
193        }
194        Ok(())
195    }
196
197    /// Convert a VmError into either a handled exception (returning Ok) or a propagated error.
198    pub(crate) fn handle_error(&mut self, error: VmError) -> Result<Option<VmValue>, VmError> {
199        let thrown_value = match &error {
200            VmError::Thrown(v) => v.clone(),
201            other => VmValue::String(arcstr::ArcStr::from(other.to_string())),
202        };
203
204        if let Some(handler) = self.exception_handlers.pop() {
205            if let Some(error_type) = handler.error_type.as_deref() {
206                // Typed catch: only match when the thrown enum's type equals the declared type.
207                let matches = match &thrown_value {
208                    VmValue::EnumVariant(enum_variant) => enum_variant.has_enum_name(error_type),
209                    _ => false,
210                };
211                if !matches {
212                    return self.handle_error(error);
213                }
214            }
215
216            self.release_sync_guards_after_unwind(handler.frame_depth, handler.env_scope_depth);
217
218            while self.frames.len() > handler.frame_depth {
219                if let Some(frame) = self.frames.pop() {
220                    if let Some(ref dir) = frame.saved_source_dir {
221                        crate::stdlib::set_thread_source_dir(dir);
222                    }
223                    self.iterators.truncate(frame.saved_iterator_depth);
224                    self.env = frame.saved_env;
225                }
226            }
227            crate::step_runtime::prune_below_frame(self.frames.len());
228
229            // Drop deadlines that belonged to unwound frames.
230            while self
231                .deadlines
232                .last()
233                .is_some_and(|d| d.1 > handler.frame_depth)
234            {
235                self.deadlines.pop();
236            }
237
238            self.env.truncate_scopes(handler.env_scope_depth);
239
240            self.stack.truncate(handler.stack_depth);
241            self.stack.push(thrown_value);
242
243            if let Some(frame) = self.frames.last_mut() {
244                frame.ip = handler.catch_ip;
245            }
246
247            Ok(None)
248        } else {
249            Err(error)
250        }
251    }
252
253    pub(crate) async fn run_chunk(&mut self, chunk: ChunkRef) -> Result<VmValue, VmError> {
254        self.run_chunk_ref(chunk, 0, None, None, None, None).await
255    }
256
257    pub(crate) async fn run_chunk_ref(
258        &mut self,
259        chunk: ChunkRef,
260        argc: usize,
261        saved_source_dir: Option<std::path::PathBuf>,
262        module_functions: Option<ModuleFunctionRegistry>,
263        module_state: Option<crate::value::ModuleState>,
264        local_slots: Option<Vec<LocalSlot>>,
265    ) -> Result<VmValue, VmError> {
266        let debugger = self.debugger_attached();
267        let local_slots = local_slots.unwrap_or_else(|| Self::fresh_local_slots(&chunk));
268        let initial_env = if debugger {
269            Some(self.env.clone())
270        } else {
271            None
272        };
273        let initial_local_slots = if debugger {
274            Some(local_slots.clone())
275        } else {
276            None
277        };
278        let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
279        self.frames.push(CallFrame {
280            chunk,
281            inline_cache_set,
282            ip: 0,
283            stack_base: self.stack.len(),
284            saved_env: self.env.clone(),
285            initial_env,
286            initial_local_slots,
287            saved_iterator_depth: self.iterators.len(),
288            fn_name: String::new(),
289            argc,
290            saved_source_dir,
291            module_functions,
292            module_state,
293            local_slots,
294            local_scope_base: self.env.scope_depth().saturating_sub(1),
295            local_scope_depth: 0,
296        });
297
298        self.drive_dispatch_loop(0, false).await
299    }
300
301    /// Sub-execution entrypoint used by [`Vm::call_closure`]: runs the
302    /// dispatch loop until the topmost frame pops back to `target_depth`,
303    /// restoring env/iterators/stack on that final pop so the caller's
304    /// state is intact. Distinct from the entrypoint-mode call in
305    /// [`Vm::run_chunk_ref`] (which preserves the script's top-level scope
306    /// for the module-init capture in `modules.rs`).
307    pub(crate) async fn drive_until_frame_depth(
308        &mut self,
309        target_depth: usize,
310    ) -> Result<VmValue, VmError> {
311        self.drive_dispatch_loop(target_depth, true).await
312    }
313
314    /// Dispatch loop body, parameterized on a target frame depth at which
315    /// the loop should return and whether to restore the caller's
316    /// env/iterators/stack on the final pop.
317    ///
318    /// `restore_on_final_pop = false` is the entrypoint mode used by
319    /// `run_chunk_ref` (leaves the script's top-level state in place so the
320    /// caller can capture it — see `modules.rs`).
321    ///
322    /// `restore_on_final_pop = true` is the sub-execution mode used by
323    /// `call_closure`: the closure's frame is pushed onto the caller's
324    /// frame stack and the loop drains it back to `target_depth`, so the
325    /// per-invocation `Box::pin` heap allocation a recursive async
326    /// `call_closure` would require is avoided.
327    async fn drive_dispatch_loop(
328        &mut self,
329        target_depth: usize,
330        restore_on_final_pop: bool,
331    ) -> Result<VmValue, VmError> {
332        let _task_activity = self
333            .wait_for_graph
334            .register_task(self.runtime_context.task_id.clone());
335        loop {
336            // Slow path only: the interrupt-handler future, deadline check,
337            // and host-signal poll inside `pending_scope_interrupt` are all
338            // no-ops when no cancel/interrupt/deadline machinery is armed
339            // (the common case for unsupervised execution), so guard them
340            // with a sync check that avoids the per-iteration future
341            // state-machine allocation.
342            if !self.scope_interrupts_clean() {
343                if let Some(err) = self.pending_scope_interrupt().await {
344                    match self.handle_error(err) {
345                        Ok(None) => continue,
346                        Ok(Some(val)) => return Ok(val),
347                        Err(e) => {
348                            self.unwind_frames_to_depth(target_depth);
349                            return Err(e);
350                        }
351                    }
352                }
353            }
354
355            let frame = match self.frames.last_mut() {
356                Some(f) => f,
357                None => return Ok(self.stack.pop().unwrap_or(VmValue::Nil)),
358            };
359
360            if frame.ip >= frame.chunk.code.len() {
361                let val = self.stack.pop().unwrap_or(VmValue::Nil);
362                let val = self.run_step_post_hooks_for_current_frame(val).await?;
363                self.release_sync_guards_for_frame(self.frames.len());
364                let popped_frame = self.frames.pop().unwrap();
365                if let Some(ref dir) = popped_frame.saved_source_dir {
366                    crate::stdlib::set_thread_source_dir(dir);
367                }
368                let current_depth = self.frames.len();
369                crate::step_runtime::prune_below_frame(current_depth);
370                // Drop any deadlines owned by the popped frame so the
371                // caller doesn't inherit them (an early `return` from
372                // inside `deadline(d) { ... }` would otherwise leave the
373                // deadline live across the function boundary).
374                while self.deadlines.last().is_some_and(|d| d.1 > current_depth) {
375                    self.deadlines.pop();
376                }
377
378                let reached_target = current_depth <= target_depth;
379                if reached_target && !restore_on_final_pop {
380                    // Entrypoint mode: leave env / iterators / stack in place
381                    // so the caller can observe the script's top-level scope.
382                    return Ok(val);
383                }
384                self.iterators.truncate(popped_frame.saved_iterator_depth);
385                self.env = popped_frame.saved_env;
386                self.stack.truncate(popped_frame.stack_base);
387                if reached_target {
388                    return Ok(val);
389                }
390                self.stack.push(val);
391                continue;
392            }
393
394            let op_byte = frame.chunk.code[frame.ip];
395            // Line-coverage hit. `self.coverage` is `None` unless a coverage
396            // session is active, so this is a single predictable branch on the
397            // hot path (and a disjoint-field borrow from `frame`, which holds
398            // `self.frames`). `frame.ip` is still the index of the instruction
399            // we just read, before the increment below.
400            if let Some(coverage) = self.coverage.as_mut() {
401                coverage.record(&frame.chunk, frame.ip);
402            }
403            frame.ip += 1;
404
405            // Sync/async split dispatch: skip the `execute_op` async fn
406            // (a per-iteration `Future` state machine over ~80 match arms)
407            // and the `tokio::select!` deadline/cancel wrapper whenever
408            // the VM has no interrupt machinery armed. Only call/iter/
409            // pipe/parallel/import/yield opcodes still need an `.await`.
410            let op_result: Result<(), VmError> = if self.scope_interrupts_clean() {
411                let op = match Op::from_byte(op_byte) {
412                    Some(op) => op,
413                    None => return Err(VmError::InvalidInstruction(op_byte)),
414                };
415                if let Some(result) = self.execute_op_sync(op) {
416                    result
417                } else {
418                    self.execute_op_async(op).await
419                }
420            } else {
421                match self.execute_op_with_scope_interrupts(op_byte).await {
422                    Ok(Some(val)) => return Ok(val),
423                    Ok(None) => Ok(()),
424                    Err(e) => Err(e),
425                }
426            };
427
428            match op_result {
429                Ok(()) => continue,
430                Err(VmError::Return(val)) => {
431                    let val = self.run_step_post_hooks_for_current_frame(val).await?;
432                    if let Some(popped_frame) = self.frames.pop() {
433                        self.release_sync_guards_for_frame(self.frames.len() + 1);
434                        if let Some(ref dir) = popped_frame.saved_source_dir {
435                            crate::stdlib::set_thread_source_dir(dir);
436                        }
437                        let current_depth = self.frames.len();
438                        self.exception_handlers
439                            .retain(|h| h.frame_depth <= current_depth);
440                        crate::step_runtime::prune_below_frame(current_depth);
441                        while self.deadlines.last().is_some_and(|d| d.1 > current_depth) {
442                            self.deadlines.pop();
443                        }
444
445                        let reached_target = current_depth <= target_depth;
446                        if reached_target && !restore_on_final_pop {
447                            return Ok(val);
448                        }
449                        self.iterators.truncate(popped_frame.saved_iterator_depth);
450                        self.env = popped_frame.saved_env;
451                        self.stack.truncate(popped_frame.stack_base);
452                        if reached_target {
453                            return Ok(val);
454                        }
455                        self.stack.push(val);
456                    } else {
457                        return Ok(val);
458                    }
459                }
460                Err(e) => {
461                    // Capture stack trace before error handling unwinds frames.
462                    if self.error_stack_trace.is_empty() {
463                        self.error_stack_trace = self.capture_stack_trace();
464                    }
465                    // Honor `@step(error_boundary: ...)` if a step-budget
466                    // exhaustion error is propagating out of the step's
467                    // own frame. `continue` swaps the throw for a Nil
468                    // return; `escalate` re-tags the error as a handoff
469                    // escalation and lets the existing exception
470                    // handlers route it.
471                    let e = match self.apply_step_error_boundary(e) {
472                        StepBoundaryOutcome::Returned(val) => {
473                            self.error_stack_trace.clear();
474                            if self.frames.len() <= target_depth {
475                                return Ok(val);
476                            }
477                            self.stack.push(val);
478                            continue;
479                        }
480                        StepBoundaryOutcome::Throw(err) => err,
481                    };
482                    match self.handle_error(e) {
483                        Ok(None) => {
484                            self.error_stack_trace.clear();
485                            continue;
486                        }
487                        Ok(Some(val)) => return Ok(val),
488                        Err(e) => {
489                            self.unwind_frames_to_depth(target_depth);
490                            return Err(self.enrich_error_with_line(e));
491                        }
492                    }
493                }
494            }
495        }
496    }
497
498    /// Pop frames until `self.frames.len() <= target_depth`, restoring env,
499    /// iterators, stack, source-dir thread-locals, and releasing per-frame
500    /// sync guards for each popped frame. Used by [`drive_until_frame_depth`]
501    /// on the error path so a closure sub-execution leaves caller-visible
502    /// state at the same depth it found when an unhandled error propagates
503    /// out.
504    fn unwind_frames_to_depth(&mut self, target_depth: usize) {
505        while self.frames.len() > target_depth {
506            let frame_depth = self.frames.len();
507            if let Some(frame) = self.frames.pop() {
508                self.release_sync_guards_for_frame(frame_depth);
509                if let Some(ref dir) = frame.saved_source_dir {
510                    crate::stdlib::set_thread_source_dir(dir);
511                }
512                self.iterators.truncate(frame.saved_iterator_depth);
513                self.env = frame.saved_env;
514                self.stack.truncate(frame.stack_base);
515            }
516        }
517        let current_depth = self.frames.len();
518        crate::step_runtime::prune_below_frame(current_depth);
519        while self.deadlines.last().is_some_and(|d| d.1 > current_depth) {
520            self.deadlines.pop();
521        }
522    }
523
524    /// Inspect a thrown error against the topmost active step's
525    /// `error_boundary`. Called from the main step loop before
526    /// `handle_error` so that a step's own budget-exhaustion error can be
527    /// short-circuited (`continue`) or annotated (`escalate`) before the
528    /// generic try/catch machinery sees it.
529    pub(crate) fn apply_step_error_boundary(&mut self, error: VmError) -> StepBoundaryOutcome {
530        use crate::step_runtime;
531        if !step_runtime::is_step_budget_exhausted(&error) {
532            return StepBoundaryOutcome::Throw(error);
533        }
534        let Some(step_depth) = step_runtime::active_step_frame_depth() else {
535            return StepBoundaryOutcome::Throw(error);
536        };
537        // The step's frame is the topmost on the call stack iff its
538        // recorded frame_depth equals `frames.len()`. If the throw is
539        // coming from a deeper frame we let it bubble up — the boundary
540        // still applies later when the step's own frame is reached.
541        if step_depth != self.frames.len() {
542            return StepBoundaryOutcome::Throw(error);
543        }
544        let boundary = step_runtime::with_active_step(|step| step.definition.boundary())
545            .unwrap_or(step_runtime::StepErrorBoundary::Fail);
546        match boundary {
547            step_runtime::StepErrorBoundary::Continue => {
548                // Mimic VmError::Return(Nil) for the step's frame: pop
549                // the frame, restore its env/iterators/stack, and feed a
550                // Nil return value back to the caller.
551                if let Some(popped) = self.frames.pop() {
552                    self.release_sync_guards_for_frame(self.frames.len() + 1);
553                    if let Some(ref dir) = popped.saved_source_dir {
554                        crate::stdlib::set_thread_source_dir(dir);
555                    }
556                    let current_depth = self.frames.len();
557                    self.exception_handlers
558                        .retain(|h| h.frame_depth <= current_depth);
559                    step_runtime::pop_and_record(
560                        current_depth + 1,
561                        "skipped",
562                        Some(step_runtime_error_message(&error)),
563                    );
564                    if self.frames.is_empty() {
565                        return StepBoundaryOutcome::Returned(VmValue::Nil);
566                    }
567                    self.iterators.truncate(popped.saved_iterator_depth);
568                    self.env = popped.saved_env;
569                    self.stack.truncate(popped.stack_base);
570                }
571                StepBoundaryOutcome::Returned(VmValue::Nil)
572            }
573            step_runtime::StepErrorBoundary::Escalate => {
574                let identity = step_runtime::with_active_step(|step| {
575                    (
576                        step.definition.name.clone(),
577                        step.definition.function.clone(),
578                    )
579                });
580                step_runtime::pop_and_record(
581                    step_depth,
582                    "escalated",
583                    Some(step_runtime_error_message(&error)),
584                );
585                let (step_name, function) = identity.unzip();
586                StepBoundaryOutcome::Throw(step_runtime::mark_escalated(
587                    error,
588                    step_name.as_deref(),
589                    function.as_deref(),
590                ))
591            }
592            step_runtime::StepErrorBoundary::Fail => {
593                step_runtime::pop_and_record(
594                    step_depth,
595                    "failed",
596                    Some(step_runtime_error_message(&error)),
597                );
598                StepBoundaryOutcome::Throw(error)
599            }
600        }
601    }
602}
603
604fn next_deadline(
605    scope_deadline: Option<Instant>,
606    interrupt_handler_deadline: Option<Instant>,
607) -> (Option<Instant>, Option<DeadlineKind>) {
608    match (scope_deadline, interrupt_handler_deadline) {
609        (Some(scope), Some(interrupt)) if interrupt < scope => {
610            (Some(interrupt), Some(DeadlineKind::InterruptHandler))
611        }
612        (Some(scope), _) => (Some(scope), Some(DeadlineKind::Scope)),
613        (None, Some(interrupt)) => (Some(interrupt), Some(DeadlineKind::InterruptHandler)),
614        (None, None) => (None, None),
615    }
616}
617
618fn step_runtime_error_message(error: &VmError) -> String {
619    match error {
620        VmError::Thrown(VmValue::Dict(dict)) => dict
621            .get("message")
622            .map(|v| v.display())
623            .unwrap_or_else(|| error.to_string()),
624        _ => error.to_string(),
625    }
626}
627
628pub(crate) enum StepBoundaryOutcome {
629    Returned(VmValue),
630    Throw(VmError),
631}
632
633impl crate::vm::Vm {
634    pub(crate) async fn execute_one_cycle(&mut self) -> Result<Option<(VmValue, bool)>, VmError> {
635        if let Some(err) = self.pending_scope_interrupt().await {
636            match self.handle_error(err) {
637                Ok(None) => return Ok(None),
638                Ok(Some(val)) => return Ok(Some((val, false))),
639                Err(e) => return Err(e),
640            }
641        }
642
643        let frame = match self.frames.last_mut() {
644            Some(f) => f,
645            None => {
646                let val = self.stack.pop().unwrap_or(VmValue::Nil);
647                return Ok(Some((val, false)));
648            }
649        };
650
651        if frame.ip >= frame.chunk.code.len() {
652            let val = self.stack.pop().unwrap_or(VmValue::Nil);
653            self.release_sync_guards_for_frame(self.frames.len());
654            let popped_frame = self.frames.pop().unwrap();
655            if self.frames.is_empty() {
656                return Ok(Some((val, false)));
657            }
658            self.iterators.truncate(popped_frame.saved_iterator_depth);
659            self.env = popped_frame.saved_env;
660            self.stack.truncate(popped_frame.stack_base);
661            self.stack.push(val);
662            return Ok(None);
663        }
664
665        let op = frame.chunk.code[frame.ip];
666        frame.ip += 1;
667
668        match self.execute_op_with_scope_interrupts(op).await {
669            Ok(Some(val)) => Ok(Some((val, false))),
670            Ok(None) => Ok(None),
671            Err(VmError::Return(val)) => {
672                if let Some(popped_frame) = self.frames.pop() {
673                    self.release_sync_guards_for_frame(self.frames.len() + 1);
674                    if let Some(ref dir) = popped_frame.saved_source_dir {
675                        crate::stdlib::set_thread_source_dir(dir);
676                    }
677                    let current_depth = self.frames.len();
678                    self.exception_handlers
679                        .retain(|h| h.frame_depth <= current_depth);
680                    if self.frames.is_empty() {
681                        return Ok(Some((val, false)));
682                    }
683                    self.iterators.truncate(popped_frame.saved_iterator_depth);
684                    self.env = popped_frame.saved_env;
685                    self.stack.truncate(popped_frame.stack_base);
686                    self.stack.push(val);
687                    Ok(None)
688                } else {
689                    Ok(Some((val, false)))
690                }
691            }
692            Err(e) => {
693                if self.error_stack_trace.is_empty() {
694                    self.error_stack_trace = self.capture_stack_trace();
695                }
696                match self.handle_error(e) {
697                    Ok(None) => {
698                        self.error_stack_trace.clear();
699                        Ok(None)
700                    }
701                    Ok(Some(val)) => Ok(Some((val, false))),
702                    Err(e) => Err(self.enrich_error_with_line(e)),
703                }
704            }
705        }
706    }
707
708    async fn execute_op_with_scope_interrupts(
709        &mut self,
710        op: u8,
711    ) -> Result<Option<VmValue>, VmError> {
712        enum ScopeInterruptResult {
713            Op(Result<Option<VmValue>, VmError>),
714            Deadline(DeadlineKind),
715            CancelTimedOut,
716        }
717
718        let (deadline, deadline_kind) = next_deadline(
719            self.deadlines.last().map(|(deadline, _)| *deadline),
720            self.interrupt_handler_deadline,
721        );
722        let cancel_token = self.cancel_token.clone();
723
724        if deadline.is_none() && cancel_token.is_none() {
725            return self.execute_op(op).await;
726        }
727
728        let has_deadline = deadline.is_some();
729        let cancel_requested_at_start = cancel_token
730            .as_ref()
731            .is_some_and(|token| token.load(std::sync::atomic::Ordering::SeqCst));
732        let has_cancel = cancel_token.is_some() && !cancel_requested_at_start;
733        let deadline_sleep = async move {
734            if let Some(deadline) = deadline {
735                tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await;
736            } else {
737                std::future::pending::<()>().await;
738            }
739        };
740        let cancel_sleep = async move {
741            if let Some(token) = cancel_token {
742                while !token.load(std::sync::atomic::Ordering::SeqCst) {
743                    tokio::time::sleep(Duration::from_millis(10)).await;
744                }
745            } else {
746                std::future::pending::<()>().await;
747            }
748        };
749
750        let result = {
751            let op_future = self.execute_op(op);
752            tokio::pin!(op_future);
753            tokio::select! {
754                result = &mut op_future => ScopeInterruptResult::Op(result),
755                _ = deadline_sleep, if has_deadline => {
756                    ScopeInterruptResult::Deadline(deadline_kind.unwrap_or(DeadlineKind::Scope))
757                },
758                _ = cancel_sleep, if has_cancel => {
759                    let grace = tokio::time::sleep(CANCEL_GRACE_ASYNC_OP);
760                    tokio::pin!(grace);
761                    tokio::select! {
762                        result = &mut op_future => ScopeInterruptResult::Op(result),
763                        _ = &mut grace => ScopeInterruptResult::CancelTimedOut,
764                    }
765                }
766            }
767        };
768
769        match result {
770            ScopeInterruptResult::Op(result) => result,
771            ScopeInterruptResult::Deadline(DeadlineKind::Scope) => {
772                self.deadlines.pop();
773                self.cancel_spawned_tasks();
774                Err(Self::deadline_exceeded_error())
775            }
776            ScopeInterruptResult::Deadline(DeadlineKind::InterruptHandler) => {
777                Err(Self::interrupt_handler_timeout_error())
778            }
779            ScopeInterruptResult::CancelTimedOut => {
780                self.cancel_spawned_tasks();
781                let signal = self
782                    .take_host_interrupt_signal()
783                    .unwrap_or_else(|| "SIGINT".to_string());
784                if self.has_interrupt_handler_for(&signal) {
785                    self.dispatch_interrupt_handlers(&signal).await?;
786                }
787                Err(Self::cancelled_error())
788            }
789        }
790    }
791
792    pub(crate) fn deadline_exceeded_error() -> VmError {
793        VmError::Thrown(VmValue::String(arcstr::ArcStr::from("Deadline exceeded")))
794    }
795
796    pub(crate) fn cancelled_error() -> VmError {
797        VmError::Thrown(VmValue::String(arcstr::ArcStr::from(
798            "kind:cancelled:VM cancelled by host",
799        )))
800    }
801
802    /// Capture the current call stack as (fn_name, line, col, source_file) tuples.
803    pub(crate) fn capture_stack_trace(&self) -> Vec<(String, usize, usize, Option<String>)> {
804        self.frames
805            .iter()
806            .map(|f| {
807                let idx = if f.ip > 0 { f.ip - 1 } else { 0 };
808                let line = f.chunk.lines.get(idx).copied().unwrap_or(0) as usize;
809                let col = f.chunk.columns.get(idx).copied().unwrap_or(0) as usize;
810                (f.fn_name.clone(), line, col, f.chunk.source_file.clone())
811            })
812            .collect()
813    }
814
815    /// Enrich a VmError with source line information from the captured stack
816    /// trace. Appends ` (line N)` to error variants whose messages don't
817    /// already carry location context.
818    pub(crate) fn enrich_error_with_line(&self, error: VmError) -> VmError {
819        // Determine the line from the captured stack trace (innermost frame).
820        let line = self
821            .error_stack_trace
822            .last()
823            .map(|(_, l, _, _)| *l)
824            .unwrap_or_else(|| self.current_line());
825        if line == 0 {
826            return error;
827        }
828        let suffix = format!(" (line {line})");
829        match error {
830            VmError::Runtime(msg) => VmError::Runtime(format!("{msg}{suffix}")),
831            VmError::TypeError(msg) => VmError::TypeError(format!("{msg}{suffix}")),
832            VmError::DivisionByZero => VmError::Runtime(format!("Division by zero{suffix}")),
833            VmError::UndefinedVariable(name) => {
834                VmError::Runtime(format!("Undefined variable: {name}{suffix}"))
835            }
836            VmError::UndefinedBuiltin(name) => {
837                VmError::Runtime(format!("Undefined builtin: {name}{suffix}"))
838            }
839            VmError::ImmutableAssignment(name) => VmError::Runtime(format!(
840                "Cannot assign to immutable binding: {name}{suffix}"
841            )),
842            VmError::StackOverflow => {
843                VmError::Runtime(format!("Stack overflow: too many nested calls{suffix}"))
844            }
845            // Leave these untouched:
846            // - Thrown: user-thrown errors should not be silently modified
847            // - CategorizedError: structured errors for agent orchestration
848            // - Return: control flow, not a real error
849            // - StackUnderflow / InvalidInstruction: internal VM bugs
850            other => other,
851        }
852    }
853}