Skip to main content

miden_processor/fast/
execution_api.rs

1use alloc::{sync::Arc, vec::Vec};
2use core::ops::ControlFlow;
3
4use miden_core::{
5    Word,
6    mast::{MastForest, MastNodeId},
7    program::{KernelDescriptor, MIN_STACK_DEPTH, Program, StackInputs, StackOutputs},
8};
9use miden_mast_package::debug_info::{
10    DebugSourceGraphLookupError, DebugSourceNodeId, PackageDebugInfo,
11};
12use tracing::instrument;
13
14use super::{
15    FastProcessor, NoopTracer,
16    external::maybe_use_caller_error_context,
17    step::{BreakReason, NeverStopper, ResumeContext, StepStopper},
18};
19#[cfg(feature = "std")]
20use crate::PrecompileWitness;
21use crate::{
22    AdviceProvider, ExecutionError, ExecutionOutput, ExecutionWitness, Host, LoadedMastForest,
23    Stopper, SyncHost,
24    advice::AdviceError,
25    continuation_stack::{Continuation, ContinuationStack, SourceInlineCallContext},
26    errors::{
27        MapExecErr, MapExecErrNoCtx, PackageSourceDebugContext, malformed_mast_forest_with_context,
28    },
29    execution::{
30        InternalBreakReason, execute_impl, finish_emit_op_execution,
31        finish_load_mast_forest_from_dyn_start, finish_load_mast_forest_from_external,
32    },
33    trace::execution_tracer::ExecutionTracer,
34    tracer::Tracer,
35};
36
37impl FastProcessor {
38    // EXECUTE
39    // -------------------------------------------------------------------------------------------
40
41    /// Executes the given program synchronously and returns the execution output.
42    pub fn execute_sync(
43        self,
44        program: &Program,
45        host: &mut impl SyncHost,
46    ) -> Result<ExecutionOutput, ExecutionError> {
47        self.execute_with_tracer_sync(program, host, &mut NoopTracer)
48    }
49
50    /// Executes the given program synchronously with package-owned source/debug context.
51    ///
52    /// This derives the entrypoint source occurrence from [`PackageDebugInfo`], so the source graph
53    /// must contain at most one root for the executable entrypoint. When the package manifest names
54    /// the exact entrypoint source occurrence, use
55    /// [`Self::execute_with_package_debug_info_at_source_node_sync`] instead.
56    pub fn execute_with_package_debug_info_sync(
57        self,
58        program: &Program,
59        package_debug_info: &PackageDebugInfo,
60        host: &mut impl SyncHost,
61    ) -> Result<ExecutionOutput, ExecutionError> {
62        self.execute_with_package_debug_info_and_tracer_sync(
63            program,
64            package_debug_info,
65            None,
66            host,
67            &mut NoopTracer,
68        )
69    }
70
71    /// Executes the given program synchronously with package-owned source/debug context rooted at
72    /// `entrypoint_source_node_id`.
73    ///
74    /// Use this when the package manifest names the exact source/debug occurrence for the
75    /// executable entrypoint. This preserves source disambiguation when multiple source roots map
76    /// to the same executable MAST node.
77    pub fn execute_with_package_debug_info_at_source_node_sync(
78        self,
79        program: &Program,
80        package_debug_info: &PackageDebugInfo,
81        entrypoint_source_node_id: DebugSourceNodeId,
82        host: &mut impl SyncHost,
83    ) -> Result<ExecutionOutput, ExecutionError> {
84        self.execute_with_package_debug_info_and_tracer_sync(
85            program,
86            package_debug_info,
87            Some(entrypoint_source_node_id),
88            host,
89            &mut NoopTracer,
90        )
91    }
92
93    /// Async variant of [`Self::execute_sync`] for hosts that need async callbacks.
94    #[inline(always)]
95    pub async fn execute(
96        self,
97        program: &Program,
98        host: &mut impl Host,
99    ) -> Result<ExecutionOutput, ExecutionError> {
100        self.execute_with_tracer(program, host, &mut NoopTracer).await
101    }
102
103    /// Async variant of [`Self::execute_with_package_debug_info_sync`].
104    ///
105    /// When the package manifest names the exact entrypoint source occurrence, use
106    /// [`Self::execute_with_package_debug_info_at_source_node`] instead.
107    #[inline(always)]
108    pub async fn execute_with_package_debug_info(
109        self,
110        program: &Program,
111        package_debug_info: &PackageDebugInfo,
112        host: &mut impl Host,
113    ) -> Result<ExecutionOutput, ExecutionError> {
114        self.execute_with_package_debug_info_and_tracer(
115            program,
116            package_debug_info,
117            None,
118            host,
119            &mut NoopTracer,
120        )
121        .await
122    }
123
124    /// Async variant of [`Self::execute_with_package_debug_info_at_source_node_sync`].
125    #[inline(always)]
126    pub async fn execute_with_package_debug_info_at_source_node(
127        self,
128        program: &Program,
129        package_debug_info: &PackageDebugInfo,
130        entrypoint_source_node_id: DebugSourceNodeId,
131        host: &mut impl Host,
132    ) -> Result<ExecutionOutput, ExecutionError> {
133        self.execute_with_package_debug_info_and_tracer(
134            program,
135            package_debug_info,
136            Some(entrypoint_source_node_id),
137            host,
138            &mut NoopTracer,
139        )
140        .await
141    }
142
143    /// Executes the program and builds its execution trace, overlapping the two when a Rayon worker
144    /// is available. The hasher chiplet — the dominant serial part of trace building — consumes a
145    /// live stream of requests while execution is still running, hiding its cost behind the
146    /// (inherently sequential) execution itself. When the caller is Rayon's only worker, this uses
147    /// compact buffered replay and builds the trace after execution.
148    ///
149    /// `budget` applies the same modelled peak-memory bound as
150    /// [`crate::trace::build_trace`] does; the streamed hasher builds ahead of that
151    /// call, so it needs its own copy of the derived row cap.
152    /// The supplied model must satisfy the compatibility requirements documented on
153    /// [`crate::trace::build_trace`].
154    ///
155    /// Produces the same trace as [`Self::execute_for_proving_sync`] followed by
156    /// [`ExecutionWitness::into_parts`] and [`crate::trace::build_trace`]. The optional
157    /// precompile witness is returned separately because [`crate::trace::VmTrace`] retains only
158    /// its authenticated root.
159    #[cfg(feature = "std")]
160    #[instrument(name = "execute_and_build_trace_sync", skip_all)]
161    pub fn execute_and_build_trace_sync(
162        self,
163        program: &Program,
164        host: &mut impl SyncHost,
165        budget: &miden_stark::memory::ProvingBudget<{ miden_air_definitions::vm::MIDEN_AIR_COUNT }>,
166    ) -> Result<(crate::trace::VmTrace, Option<PrecompileWitness>), ExecutionError> {
167        use crate::trace::{
168            MAX_TRACE_LEN, build_hasher_chiplet, build_trace, build_trace_with_prebuilt_hasher,
169        };
170
171        if Self::rayon_has_no_parallel_worker() {
172            let (vm_witness, precompiles_witness) =
173                self.execute_for_proving_sync(program, host)?.into_parts();
174            let trace = build_trace(vm_witness, budget)?;
175            return Ok((trace, precompiles_witness));
176        }
177
178        let stack_inputs = self.initial_stack_inputs();
179        let max_trace_len = MAX_TRACE_LEN.min(budget.max_any_height());
180        let (sender, receiver) = std::sync::mpsc::channel();
181        let mut tracer = ExecutionTracer::new_with_streamed_hasher(
182            self.options.core_trace_fragment_size(),
183            self.options.max_stack_depth(),
184            sender,
185        );
186
187        let mut hasher = None;
188        let hasher_slot = &mut hasher;
189        // Keep `tracer` owned by the scope body. If execution unwinds, dropping the body closes the
190        // stream before Rayon waits for the builder, so the builder cannot remain blocked on input.
191        let execution_output = rayon::in_place_scope(move |scope| {
192            // Execution and the host remain on the calling thread. An idle Rayon worker can steal
193            // only the builder task.
194            let span = tracing::Span::current();
195            scope.spawn(move |_| {
196                let _span = span.entered();
197                let result = build_hasher_chiplet(
198                    receiver.into_iter().map(Ok),
199                    max_trace_len,
200                    max_trace_len,
201                );
202                *hasher_slot = Some(result);
203            });
204
205            let execution_output = self.execute_with_tracer_sync(program, host, &mut tracer);
206
207            match execution_output {
208                Ok(output) => {
209                    let (mut vm_witness, precompiles_witness) =
210                        Self::execution_witness_from_parts(program, stack_inputs, output, tracer)
211                            .0
212                            .into_parts();
213                    // End the stream before this scope waits for the builder.
214                    drop(vm_witness.take_hasher_replay());
215                    Ok((vm_witness, precompiles_witness))
216                },
217                Err(err) => {
218                    // Dropping the tracer closes the stream and lets the builder finish. The
219                    // execution error remains the root cause even if the partial replay also
220                    // failed.
221                    drop(tracer);
222                    Err(err)
223                },
224            }
225        });
226
227        let hasher = hasher.expect("hasher builder did not run");
228        let (vm_witness, precompiles_witness) = match execution_output {
229            Ok(output) => output,
230            Err(err) => {
231                if let Err(builder_err) = hasher {
232                    tracing::debug!(%builder_err, "hasher builder also failed");
233                }
234                return Err(err);
235            },
236        };
237
238        let trace = build_trace_with_prebuilt_hasher(vm_witness, hasher?, budget)?;
239        Ok((trace, precompiles_witness))
240    }
241
242    #[cfg(feature = "std")]
243    fn rayon_has_no_parallel_worker() -> bool {
244        // `current_num_threads` initializes Rayon's global fallback before the thread-index check.
245        rayon::current_num_threads() == 1 && rayon::current_thread_index().is_some()
246    }
247
248    /// Executes the given program synchronously and returns its complete post-execution witness.
249    ///
250    /// # Example
251    /// ```
252    /// use miden_assembly::Assembler;
253    /// use miden_processor::{DefaultHost, FastProcessor, StackInputs};
254    ///
255    /// let program = Assembler::default()
256    ///     .assemble_program("prg", "begin push.1 drop end")
257    ///     .unwrap()
258    ///     .unwrap_program();
259    /// let mut host = DefaultHost::default();
260    ///
261    /// let execution_witness = FastProcessor::new(StackInputs::default())
262    ///     .execute_for_proving_sync(&program, &mut host)
263    ///     .unwrap();
264    /// let (vm_witness, _) = execution_witness.into_parts();
265    /// let trace =
266    ///     miden_processor::trace::build_trace(vm_witness, &miden_vm_stark::memory::default_budget())
267    ///         .unwrap();
268    ///
269    /// assert_eq!(*trace.program_hash(), program.hash());
270    /// ```
271    #[instrument(name = "execute_for_proving_sync", skip_all)]
272    pub fn execute_for_proving_sync(
273        self,
274        program: &Program,
275        host: &mut impl SyncHost,
276    ) -> Result<ExecutionWitness, ExecutionError> {
277        self.execute_for_proving_with_advice_sync(program, host)
278            .map(|(witness, _)| witness)
279    }
280
281    /// Executes the program synchronously and returns its witness and final advice provider.
282    ///
283    /// The advice provider retains the final advice stack, map, and Merkle store. It is returned
284    /// separately from the witness and is not included in the witness's serialized form.
285    #[instrument(name = "execute_for_proving_with_advice_sync", skip_all)]
286    pub fn execute_for_proving_with_advice_sync(
287        self,
288        program: &Program,
289        host: &mut impl SyncHost,
290    ) -> Result<(ExecutionWitness, AdviceProvider), ExecutionError> {
291        let stack_inputs = self.initial_stack_inputs();
292        let mut tracer = ExecutionTracer::new(
293            self.options.core_trace_fragment_size(),
294            self.options.max_stack_depth(),
295        );
296        let execution_output = self.execute_with_tracer_sync(program, host, &mut tracer)?;
297        Ok(Self::execution_witness_from_parts(
298            program,
299            stack_inputs,
300            execution_output,
301            tracer,
302        ))
303    }
304
305    /// Executes the given program synchronously with package-owned source/debug context and returns
306    /// its complete post-execution witness.
307    #[instrument(name = "execute_for_proving_with_package_debug_info_sync", skip_all)]
308    pub fn execute_for_proving_with_package_debug_info_sync(
309        self,
310        program: &Program,
311        package_debug_info: &PackageDebugInfo,
312        host: &mut impl SyncHost,
313    ) -> Result<ExecutionWitness, ExecutionError> {
314        self.execute_for_proving_with_package_debug_info_and_advice_sync(
315            program,
316            package_debug_info,
317            host,
318        )
319        .map(|(witness, _)| witness)
320    }
321
322    /// Executes synchronously with package debug information and returns the witness and final
323    /// advice provider.
324    #[instrument(name = "execute_for_proving_with_package_debug_info_and_advice_sync", skip_all)]
325    pub fn execute_for_proving_with_package_debug_info_and_advice_sync(
326        self,
327        program: &Program,
328        package_debug_info: &PackageDebugInfo,
329        host: &mut impl SyncHost,
330    ) -> Result<(ExecutionWitness, AdviceProvider), ExecutionError> {
331        let stack_inputs = self.initial_stack_inputs();
332        let mut tracer = ExecutionTracer::new(
333            self.options.core_trace_fragment_size(),
334            self.options.max_stack_depth(),
335        );
336        let execution_output = self.execute_with_package_debug_info_and_tracer_sync(
337            program,
338            package_debug_info,
339            None,
340            host,
341            &mut tracer,
342        )?;
343        Ok(Self::execution_witness_from_parts(
344            program,
345            stack_inputs,
346            execution_output,
347            tracer,
348        ))
349    }
350
351    /// Executes the given program synchronously with package-owned source/debug context rooted at
352    /// `entrypoint_source_node_id` and returns its complete post-execution witness.
353    #[instrument(
354        name = "execute_for_proving_with_package_debug_info_at_source_node_sync",
355        skip_all
356    )]
357    pub fn execute_for_proving_with_package_debug_info_at_source_node_sync(
358        self,
359        program: &Program,
360        package_debug_info: &PackageDebugInfo,
361        entrypoint_source_node_id: DebugSourceNodeId,
362        host: &mut impl SyncHost,
363    ) -> Result<ExecutionWitness, ExecutionError> {
364        self.execute_for_proving_with_package_debug_info_at_source_node_and_advice_sync(
365            program,
366            package_debug_info,
367            entrypoint_source_node_id,
368            host,
369        )
370        .map(|(witness, _)| witness)
371    }
372
373    /// Executes synchronously with package debug information rooted at `entrypoint_source_node_id`
374    /// and returns the witness and final advice provider.
375    #[instrument(
376        name = "execute_for_proving_with_package_debug_info_at_source_node_and_advice_sync",
377        skip_all
378    )]
379    pub fn execute_for_proving_with_package_debug_info_at_source_node_and_advice_sync(
380        self,
381        program: &Program,
382        package_debug_info: &PackageDebugInfo,
383        entrypoint_source_node_id: DebugSourceNodeId,
384        host: &mut impl SyncHost,
385    ) -> Result<(ExecutionWitness, AdviceProvider), ExecutionError> {
386        let stack_inputs = self.initial_stack_inputs();
387        let mut tracer = ExecutionTracer::new(
388            self.options.core_trace_fragment_size(),
389            self.options.max_stack_depth(),
390        );
391        let execution_output = self.execute_with_package_debug_info_and_tracer_sync(
392            program,
393            package_debug_info,
394            Some(entrypoint_source_node_id),
395            host,
396            &mut tracer,
397        )?;
398        Ok(Self::execution_witness_from_parts(
399            program,
400            stack_inputs,
401            execution_output,
402            tracer,
403        ))
404    }
405
406    /// Async variant of [`Self::execute_for_proving_sync`] for async hosts.
407    #[inline(always)]
408    #[instrument(name = "execute_for_proving", skip_all)]
409    pub async fn execute_for_proving(
410        self,
411        program: &Program,
412        host: &mut impl Host,
413    ) -> Result<ExecutionWitness, ExecutionError> {
414        self.execute_for_proving_with_advice(program, host)
415            .await
416            .map(|(witness, _)| witness)
417    }
418
419    /// Async variant of [`Self::execute_for_proving_with_advice_sync`].
420    #[inline(always)]
421    #[instrument(name = "execute_for_proving_with_advice", skip_all)]
422    pub async fn execute_for_proving_with_advice(
423        self,
424        program: &Program,
425        host: &mut impl Host,
426    ) -> Result<(ExecutionWitness, AdviceProvider), ExecutionError> {
427        let stack_inputs = self.initial_stack_inputs();
428        let mut tracer = ExecutionTracer::new(
429            self.options.core_trace_fragment_size(),
430            self.options.max_stack_depth(),
431        );
432        let execution_output = self.execute_with_tracer(program, host, &mut tracer).await?;
433        Ok(Self::execution_witness_from_parts(
434            program,
435            stack_inputs,
436            execution_output,
437            tracer,
438        ))
439    }
440
441    /// Async variant of [`Self::execute_for_proving_with_package_debug_info_sync`].
442    #[inline(always)]
443    #[instrument(name = "execute_for_proving_with_package_debug_info", skip_all)]
444    pub async fn execute_for_proving_with_package_debug_info(
445        self,
446        program: &Program,
447        package_debug_info: &PackageDebugInfo,
448        host: &mut impl Host,
449    ) -> Result<ExecutionWitness, ExecutionError> {
450        self.execute_for_proving_with_package_debug_info_and_advice(
451            program,
452            package_debug_info,
453            host,
454        )
455        .await
456        .map(|(witness, _)| witness)
457    }
458
459    /// Async variant of [`Self::execute_for_proving_with_package_debug_info_and_advice_sync`].
460    #[inline(always)]
461    #[instrument(name = "execute_for_proving_with_package_debug_info_and_advice", skip_all)]
462    pub async fn execute_for_proving_with_package_debug_info_and_advice(
463        self,
464        program: &Program,
465        package_debug_info: &PackageDebugInfo,
466        host: &mut impl Host,
467    ) -> Result<(ExecutionWitness, AdviceProvider), ExecutionError> {
468        let stack_inputs = self.initial_stack_inputs();
469        let mut tracer = ExecutionTracer::new(
470            self.options.core_trace_fragment_size(),
471            self.options.max_stack_depth(),
472        );
473        let execution_output = self
474            .execute_with_package_debug_info_and_tracer(
475                program,
476                package_debug_info,
477                None,
478                host,
479                &mut tracer,
480            )
481            .await?;
482        Ok(Self::execution_witness_from_parts(
483            program,
484            stack_inputs,
485            execution_output,
486            tracer,
487        ))
488    }
489
490    /// Async variant of
491    /// [`Self::execute_for_proving_with_package_debug_info_at_source_node_sync`].
492    #[inline(always)]
493    #[instrument(name = "execute_for_proving_with_package_debug_info_at_source_node", skip_all)]
494    pub async fn execute_for_proving_with_package_debug_info_at_source_node(
495        self,
496        program: &Program,
497        package_debug_info: &PackageDebugInfo,
498        entrypoint_source_node_id: DebugSourceNodeId,
499        host: &mut impl Host,
500    ) -> Result<ExecutionWitness, ExecutionError> {
501        self.execute_for_proving_with_package_debug_info_at_source_node_and_advice(
502            program,
503            package_debug_info,
504            entrypoint_source_node_id,
505            host,
506        )
507        .await
508        .map(|(witness, _)| witness)
509    }
510
511    /// Async variant of
512    /// [`Self::execute_for_proving_with_package_debug_info_at_source_node_and_advice_sync`].
513    #[inline(always)]
514    #[instrument(
515        name = "execute_for_proving_with_package_debug_info_at_source_node_and_advice",
516        skip_all
517    )]
518    pub async fn execute_for_proving_with_package_debug_info_at_source_node_and_advice(
519        self,
520        program: &Program,
521        package_debug_info: &PackageDebugInfo,
522        entrypoint_source_node_id: DebugSourceNodeId,
523        host: &mut impl Host,
524    ) -> Result<(ExecutionWitness, AdviceProvider), ExecutionError> {
525        let stack_inputs = self.initial_stack_inputs();
526        let mut tracer = ExecutionTracer::new(
527            self.options.core_trace_fragment_size(),
528            self.options.max_stack_depth(),
529        );
530        let execution_output = self
531            .execute_with_package_debug_info_and_tracer(
532                program,
533                package_debug_info,
534                Some(entrypoint_source_node_id),
535                host,
536                &mut tracer,
537            )
538            .await?;
539        Ok(Self::execution_witness_from_parts(
540            program,
541            stack_inputs,
542            execution_output,
543            tracer,
544        ))
545    }
546
547    /// Executes the given program with the provided tracer using an async host.
548    async fn execute_with_tracer<T>(
549        mut self,
550        program: &Program,
551        host: &mut impl Host,
552        tracer: &mut T,
553    ) -> Result<ExecutionOutput, ExecutionError>
554    where
555        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
556    {
557        let mut continuation_stack = ContinuationStack::new(program);
558        let mut current_forest = program.mast_forest().clone();
559        let mut package_debug_info = None;
560        let mut inline_call_contexts = Vec::new();
561
562        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
563        let flow = self
564            .execute_impl_async(
565                &mut continuation_stack,
566                &mut current_forest,
567                program.kernel(),
568                host,
569                tracer,
570                &NeverStopper,
571                &mut package_debug_info,
572                &mut inline_call_contexts,
573            )
574            .await;
575        Self::execution_result_from_flow(flow, self)
576    }
577
578    /// Executes the given program with package-owned source/debug context and the provided tracer
579    /// using an async host.
580    async fn execute_with_package_debug_info_and_tracer<T>(
581        mut self,
582        program: &Program,
583        package_debug_info: &PackageDebugInfo,
584        entrypoint_source_node_id: Option<DebugSourceNodeId>,
585        host: &mut impl Host,
586        tracer: &mut T,
587    ) -> Result<ExecutionOutput, ExecutionError>
588    where
589        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
590    {
591        let mut continuation_stack = Self::source_aware_continuation_stack(
592            program,
593            package_debug_info,
594            entrypoint_source_node_id,
595        )?;
596        let mut current_forest = program.mast_forest().clone();
597        let mut package_debug_info = Some(Arc::new(package_debug_info.clone()));
598        let mut inline_call_contexts = Vec::new();
599
600        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
601        let flow = self
602            .execute_impl_async(
603                &mut continuation_stack,
604                &mut current_forest,
605                program.kernel(),
606                host,
607                tracer,
608                &NeverStopper,
609                &mut package_debug_info,
610                &mut inline_call_contexts,
611            )
612            .await;
613        Self::execution_result_from_flow(flow, self)
614    }
615
616    /// Executes the given program with the provided tracer using a sync host.
617    fn execute_with_tracer_sync<T>(
618        mut self,
619        program: &Program,
620        host: &mut impl SyncHost,
621        tracer: &mut T,
622    ) -> Result<ExecutionOutput, ExecutionError>
623    where
624        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
625    {
626        let mut continuation_stack = ContinuationStack::new(program);
627        let mut current_forest = program.mast_forest().clone();
628        let mut package_debug_info = None;
629        let mut inline_call_contexts = Vec::new();
630
631        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
632        let flow = self.execute_impl(
633            &mut continuation_stack,
634            &mut current_forest,
635            program.kernel(),
636            host,
637            tracer,
638            &NeverStopper,
639            &mut package_debug_info,
640            &mut inline_call_contexts,
641        );
642        Self::execution_result_from_flow(flow, self)
643    }
644
645    /// Executes the given program with package-owned source/debug context and the provided tracer
646    /// using a sync host.
647    fn execute_with_package_debug_info_and_tracer_sync<T>(
648        mut self,
649        program: &Program,
650        package_debug_info: &PackageDebugInfo,
651        entrypoint_source_node_id: Option<DebugSourceNodeId>,
652        host: &mut impl SyncHost,
653        tracer: &mut T,
654    ) -> Result<ExecutionOutput, ExecutionError>
655    where
656        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
657    {
658        let mut continuation_stack = Self::source_aware_continuation_stack(
659            program,
660            package_debug_info,
661            entrypoint_source_node_id,
662        )?;
663        let mut current_forest = program.mast_forest().clone();
664        let mut package_debug_info = Some(Arc::new(package_debug_info.clone()));
665        let mut inline_call_contexts = Vec::new();
666
667        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
668        let flow = self.execute_impl(
669            &mut continuation_stack,
670            &mut current_forest,
671            program.kernel(),
672            host,
673            tracer,
674            &NeverStopper,
675            &mut package_debug_info,
676            &mut inline_call_contexts,
677        );
678        Self::execution_result_from_flow(flow, self)
679    }
680
681    /// Executes a single clock cycle synchronously.
682    pub fn step_sync(
683        &mut self,
684        host: &mut impl SyncHost,
685        resume_ctx: ResumeContext,
686    ) -> Result<Option<ResumeContext>, ExecutionError> {
687        let ResumeContext {
688            mut current_forest,
689            mut continuation_stack,
690            kernel,
691            mut package_debug_info,
692            mut inline_call_contexts,
693        } = resume_ctx;
694
695        let flow = self.execute_impl(
696            &mut continuation_stack,
697            &mut current_forest,
698            &kernel,
699            host,
700            &mut NoopTracer,
701            &StepStopper,
702            &mut package_debug_info,
703            &mut inline_call_contexts,
704        );
705        Self::resume_context_from_flow(
706            flow,
707            continuation_stack,
708            current_forest,
709            kernel,
710            package_debug_info,
711            inline_call_contexts,
712        )
713    }
714
715    /// Executes a single clock cycle synchronously with package-owned source/debug context.
716    pub fn step_with_package_debug_info_sync(
717        &mut self,
718        host: &mut impl SyncHost,
719        resume_ctx: ResumeContext,
720        package_debug_info: &PackageDebugInfo,
721    ) -> Result<Option<ResumeContext>, ExecutionError> {
722        let ResumeContext {
723            mut current_forest,
724            mut continuation_stack,
725            kernel,
726            package_debug_info: mut active_package_debug_info,
727            mut inline_call_contexts,
728        } = resume_ctx;
729        Self::ensure_source_aware_step_context(
730            &mut continuation_stack,
731            &mut active_package_debug_info,
732            package_debug_info,
733        )?;
734
735        let flow = self.execute_impl(
736            &mut continuation_stack,
737            &mut current_forest,
738            &kernel,
739            host,
740            &mut NoopTracer,
741            &StepStopper,
742            &mut active_package_debug_info,
743            &mut inline_call_contexts,
744        );
745        Self::resume_context_from_flow(
746            flow,
747            continuation_stack,
748            current_forest,
749            kernel,
750            active_package_debug_info,
751            inline_call_contexts,
752        )
753    }
754
755    /// Async variant of [`Self::step_sync`].
756    #[inline(always)]
757    pub async fn step(
758        &mut self,
759        host: &mut impl Host,
760        resume_ctx: ResumeContext,
761    ) -> Result<Option<ResumeContext>, ExecutionError> {
762        let ResumeContext {
763            mut current_forest,
764            mut continuation_stack,
765            kernel,
766            mut package_debug_info,
767            mut inline_call_contexts,
768        } = resume_ctx;
769
770        let flow = self
771            .execute_impl_async(
772                &mut continuation_stack,
773                &mut current_forest,
774                &kernel,
775                host,
776                &mut NoopTracer,
777                &StepStopper,
778                &mut package_debug_info,
779                &mut inline_call_contexts,
780            )
781            .await;
782        Self::resume_context_from_flow(
783            flow,
784            continuation_stack,
785            current_forest,
786            kernel,
787            package_debug_info,
788            inline_call_contexts,
789        )
790    }
791
792    /// Async variant of [`Self::step_with_package_debug_info_sync`].
793    #[inline(always)]
794    pub async fn step_with_package_debug_info(
795        &mut self,
796        host: &mut impl Host,
797        resume_ctx: ResumeContext,
798        package_debug_info: &PackageDebugInfo,
799    ) -> Result<Option<ResumeContext>, ExecutionError> {
800        let ResumeContext {
801            mut current_forest,
802            mut continuation_stack,
803            kernel,
804            package_debug_info: mut active_package_debug_info,
805            mut inline_call_contexts,
806        } = resume_ctx;
807        Self::ensure_source_aware_step_context(
808            &mut continuation_stack,
809            &mut active_package_debug_info,
810            package_debug_info,
811        )?;
812
813        let flow = self
814            .execute_impl_async(
815                &mut continuation_stack,
816                &mut current_forest,
817                &kernel,
818                host,
819                &mut NoopTracer,
820                &StepStopper,
821                &mut active_package_debug_info,
822                &mut inline_call_contexts,
823            )
824            .await;
825        Self::resume_context_from_flow(
826            flow,
827            continuation_stack,
828            current_forest,
829            kernel,
830            active_package_debug_info,
831            inline_call_contexts,
832        )
833    }
834
835    /// Pairs execution output with the initial inputs and replay witness captured during execution.
836    #[inline(always)]
837    fn execution_witness_from_parts(
838        program: &Program,
839        stack_inputs: StackInputs,
840        execution_output: ExecutionOutput,
841        tracer: ExecutionTracer,
842    ) -> (ExecutionWitness, AdviceProvider) {
843        ExecutionWitness::from_execution(
844            program.to_info(),
845            stack_inputs,
846            execution_output,
847            tracer.into_trace_replay(),
848        )
849    }
850
851    /// Returns the current top 16 stack elements in public input order.
852    #[inline(always)]
853    fn initial_stack_inputs(&self) -> StackInputs {
854        core::array::from_fn(|idx| self.stack_get(idx)).into()
855    }
856
857    pub(super) fn source_aware_continuation_stack(
858        program: &Program,
859        package_debug_info: &PackageDebugInfo,
860        entrypoint_source_node_id: Option<DebugSourceNodeId>,
861    ) -> Result<ContinuationStack<Arc<MastForest>>, ExecutionError> {
862        if let Some(source_node_id) = entrypoint_source_node_id {
863            let Some(source_node) = package_debug_info.source_node(source_node_id) else {
864                return Err(ExecutionError::Internal(
865                    "package debug source graph is missing the entrypoint source node",
866                ));
867            };
868            if source_node.exec_node != program.entrypoint() {
869                return Err(ExecutionError::Internal(
870                    "package debug entrypoint source node does not match the program entrypoint",
871                ));
872            }
873
874            return Ok(ContinuationStack::new_with_source_node_id(program, source_node_id));
875        }
876
877        let Some(source_node_id) = package_debug_info
878            .unique_source_root_for_exec_node(program.entrypoint())
879            .map_err(|_| {
880                ExecutionError::Internal(
881                    "package debug source graph has ambiguous or malformed entrypoint roots",
882                )
883            })?
884        else {
885            return Ok(ContinuationStack::new_with_optional_source_node_id(program, None));
886        };
887
888        Ok(ContinuationStack::new_with_source_node_id(program, source_node_id))
889    }
890
891    #[cfg(any(test, feature = "testing"))]
892    fn source_aware_resume_context(
893        &mut self,
894        program: &Program,
895        package_debug_info: &PackageDebugInfo,
896        entrypoint_source_node_id: Option<DebugSourceNodeId>,
897    ) -> Result<ResumeContext, ExecutionError> {
898        self.advice
899            .extend_map(program.mast_forest().advice_map())
900            .map_exec_err_no_ctx()?;
901
902        Ok(ResumeContext {
903            current_forest: program.mast_forest().clone(),
904            continuation_stack: Self::source_aware_continuation_stack(
905                program,
906                package_debug_info,
907                entrypoint_source_node_id,
908            )?,
909            kernel: program.kernel().clone(),
910            package_debug_info: Some(Arc::new(package_debug_info.clone())),
911            inline_call_contexts: Vec::new(),
912        })
913    }
914
915    fn ensure_source_aware_step_context(
916        continuation_stack: &mut ContinuationStack<Arc<MastForest>>,
917        package_debug_info: &mut Option<Arc<PackageDebugInfo>>,
918        supplied_package_debug_info: &PackageDebugInfo,
919    ) -> Result<(), ExecutionError> {
920        if package_debug_info.is_none() {
921            *package_debug_info = Some(Arc::new(supplied_package_debug_info.clone()));
922        }
923
924        if !continuation_stack.tracks_source_nodes() {
925            let source_node_id = Self::source_root_for_next_continuation(
926                continuation_stack,
927                package_debug_info.as_deref().expect("package debug info was just initialized"),
928            )?;
929            continuation_stack.start_tracking_source_nodes(source_node_id);
930        }
931
932        Ok(())
933    }
934
935    fn source_root_for_next_continuation(
936        continuation_stack: &ContinuationStack<Arc<MastForest>>,
937        package_debug_info: &PackageDebugInfo,
938    ) -> Result<Option<DebugSourceNodeId>, ExecutionError> {
939        let Some((continuation, _)) = continuation_stack.peek_continuation_with_source_node_id()
940        else {
941            return Ok(None);
942        };
943
944        let Some(exec_node) = continuation.exec_node() else {
945            return Ok(None);
946        };
947
948        package_debug_info.unique_source_root_for_exec_node(exec_node).map_err(|_| {
949            ExecutionError::Internal(
950                "package debug source graph has ambiguous or malformed continuation roots",
951            )
952        })
953    }
954
955    /// Converts a step-wise execution result into the next resume context, if execution stopped.
956    #[inline(always)]
957    fn resume_context_from_flow(
958        flow: ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>,
959        mut continuation_stack: ContinuationStack<Arc<MastForest>>,
960        mut current_forest: Arc<MastForest>,
961        kernel: KernelDescriptor,
962        mut package_debug_info: Option<Arc<PackageDebugInfo>>,
963        mut inline_call_contexts: Vec<Option<SourceInlineCallContext>>,
964    ) -> Result<Option<ResumeContext>, ExecutionError> {
965        match flow {
966            ControlFlow::Continue(_) => Ok(None),
967            ControlFlow::Break(break_reason) => match break_reason {
968                BreakReason::Err(err) => Err(err),
969                BreakReason::Stopped(maybe_continuation) => {
970                    if let Some((continuation, source_node_id)) = maybe_continuation {
971                        continuation_stack
972                            .push_resumed_with_source_node_id(continuation, source_node_id);
973                    }
974
975                    while matches!(
976                        continuation_stack.peek_continuation(),
977                        Some(Continuation::EnterForest { .. })
978                    ) {
979                        let Some((
980                            Continuation::EnterForest {
981                                forest,
982                                package_debug_info: restored_debug_info,
983                                inline_context_depth,
984                            },
985                            _,
986                        )) = continuation_stack.pop_continuation_with_source_node_id()
987                        else {
988                            unreachable!("peeked continuation must still be EnterForest")
989                        };
990                        current_forest = forest;
991                        package_debug_info = restored_debug_info;
992                        inline_call_contexts.truncate(inline_context_depth);
993                    }
994
995                    Ok(Some(ResumeContext {
996                        current_forest,
997                        continuation_stack,
998                        kernel,
999                        package_debug_info,
1000                        inline_call_contexts,
1001                    }))
1002                },
1003            },
1004        }
1005    }
1006
1007    /// Materializes the current stack as public outputs without consuming the processor.
1008    #[inline(always)]
1009    fn current_stack_outputs(&self) -> StackOutputs {
1010        StackOutputs::new(
1011            &self.stack[self.stack_bot_idx..self.stack_top_idx]
1012                .iter()
1013                .rev()
1014                .copied()
1015                .collect::<Vec<_>>(),
1016        )
1017        .unwrap()
1018    }
1019
1020    /// Executes the given program with the provided tracer and returns the stack outputs.
1021    ///
1022    /// This function takes a `&mut self` (compared to `self` for the public sync execution
1023    /// methods) so that the processor state may be accessed after execution. Reusing the same
1024    /// processor for a second program is incorrect. This is mainly meant to be used in tests.
1025    fn execute_impl<S, T>(
1026        &mut self,
1027        continuation_stack: &mut ContinuationStack<Arc<MastForest>>,
1028        current_forest: &mut Arc<MastForest>,
1029        kernel: &KernelDescriptor,
1030        host: &mut impl SyncHost,
1031        tracer: &mut T,
1032        stopper: &S,
1033        package_debug_info: &mut Option<Arc<PackageDebugInfo>>,
1034        inline_call_contexts: &mut Vec<Option<SourceInlineCallContext>>,
1035    ) -> ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>
1036    where
1037        S: Stopper<Processor = Self, Forest = Arc<MastForest>>,
1038        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
1039    {
1040        while let ControlFlow::Break(internal_break_reason) = execute_impl(
1041            self,
1042            continuation_stack,
1043            current_forest,
1044            kernel,
1045            host,
1046            tracer,
1047            stopper,
1048            package_debug_info,
1049            inline_call_contexts,
1050        ) {
1051            let current_package_debug_info = package_debug_info.as_deref();
1052            let source_aware_execution =
1053                current_package_debug_info.is_some() || continuation_stack.tracks_source_nodes();
1054            match internal_break_reason {
1055                InternalBreakReason::User(break_reason) => return ControlFlow::Break(break_reason),
1056                InternalBreakReason::Emit { op_idx, continuation, source_node_id } => {
1057                    self.op_emit_sync(host, op_idx, current_package_debug_info, source_node_id)?;
1058
1059                    finish_emit_op_execution(
1060                        continuation,
1061                        source_node_id,
1062                        self,
1063                        continuation_stack,
1064                        current_forest,
1065                        tracer,
1066                        stopper,
1067                    )?;
1068                },
1069                InternalBreakReason::LoadMastForestFromDyn { callee_hash, source_node_id } => {
1070                    let (root_id, new_forest, new_package_debug_info, new_source_node_id) =
1071                        match self.load_mast_forest_sync(
1072                            callee_hash,
1073                            host,
1074                            current_package_debug_info,
1075                            source_node_id,
1076                            source_aware_execution,
1077                        ) {
1078                            Ok(result) => result,
1079                            Err(err) => return ControlFlow::Break(BreakReason::Err(err)),
1080                        };
1081
1082                    finish_load_mast_forest_from_dyn_start(
1083                        root_id,
1084                        new_forest,
1085                        new_package_debug_info,
1086                        new_source_node_id,
1087                        self,
1088                        current_forest,
1089                        package_debug_info,
1090                        inline_call_contexts.as_slice(),
1091                        continuation_stack,
1092                        tracer,
1093                        stopper,
1094                    )?;
1095                },
1096                InternalBreakReason::LoadMastForestFromExternal {
1097                    external_node_id,
1098                    procedure_hash,
1099                    source_node_id,
1100                } => {
1101                    let inline_call_context = package_debug_info.clone().and_then(|debug_info| {
1102                        SourceInlineCallContext::for_source_boundary(debug_info, source_node_id)
1103                    });
1104                    let (root_id, new_forest, new_package_debug_info, new_source_node_id) =
1105                        match self.load_mast_forest_sync(
1106                            procedure_hash,
1107                            host,
1108                            current_package_debug_info,
1109                            source_node_id,
1110                            source_aware_execution,
1111                        ) {
1112                            Ok(result) => result,
1113                            Err(err) => {
1114                                let maybe_enriched_err = maybe_use_caller_error_context(
1115                                    err,
1116                                    continuation_stack,
1117                                    current_package_debug_info,
1118                                    host,
1119                                );
1120                                return ControlFlow::Break(BreakReason::Err(maybe_enriched_err));
1121                            },
1122                        };
1123
1124                    finish_load_mast_forest_from_external(
1125                        root_id,
1126                        new_forest,
1127                        new_package_debug_info,
1128                        new_source_node_id,
1129                        inline_call_context,
1130                        (external_node_id, source_node_id),
1131                        current_forest,
1132                        package_debug_info,
1133                        inline_call_contexts,
1134                        continuation_stack,
1135                        tracer,
1136                    )?;
1137                },
1138            }
1139        }
1140
1141        match StackOutputs::new(
1142            &self.stack[self.stack_bot_idx..self.stack_top_idx]
1143                .iter()
1144                .rev()
1145                .copied()
1146                .collect::<Vec<_>>(),
1147        ) {
1148            Ok(stack_outputs) => ControlFlow::Continue(stack_outputs),
1149            Err(_) => ControlFlow::Break(BreakReason::Err(ExecutionError::OutputStackOverflow(
1150                self.stack_top_idx - self.stack_bot_idx - MIN_STACK_DEPTH,
1151            ))),
1152        }
1153    }
1154
1155    async fn execute_impl_async<S, T>(
1156        &mut self,
1157        continuation_stack: &mut ContinuationStack<Arc<MastForest>>,
1158        current_forest: &mut Arc<MastForest>,
1159        kernel: &KernelDescriptor,
1160        host: &mut impl Host,
1161        tracer: &mut T,
1162        stopper: &S,
1163        package_debug_info: &mut Option<Arc<PackageDebugInfo>>,
1164        inline_call_contexts: &mut Vec<Option<SourceInlineCallContext>>,
1165    ) -> ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>
1166    where
1167        S: Stopper<Processor = Self, Forest = Arc<MastForest>>,
1168        T: Tracer<Processor = Self, Forest = Arc<MastForest>>,
1169    {
1170        while let ControlFlow::Break(internal_break_reason) = execute_impl(
1171            self,
1172            continuation_stack,
1173            current_forest,
1174            kernel,
1175            host,
1176            tracer,
1177            stopper,
1178            package_debug_info,
1179            inline_call_contexts,
1180        ) {
1181            let current_package_debug_info = package_debug_info.as_deref();
1182            let source_aware_execution =
1183                current_package_debug_info.is_some() || continuation_stack.tracks_source_nodes();
1184            match internal_break_reason {
1185                InternalBreakReason::User(break_reason) => return ControlFlow::Break(break_reason),
1186                InternalBreakReason::Emit { op_idx, continuation, source_node_id } => {
1187                    self.op_emit(host, op_idx, current_package_debug_info, source_node_id).await?;
1188
1189                    finish_emit_op_execution(
1190                        continuation,
1191                        source_node_id,
1192                        self,
1193                        continuation_stack,
1194                        current_forest,
1195                        tracer,
1196                        stopper,
1197                    )?;
1198                },
1199                InternalBreakReason::LoadMastForestFromDyn { callee_hash, source_node_id } => {
1200                    let (root_id, new_forest, new_package_debug_info, new_source_node_id) =
1201                        match self
1202                            .load_mast_forest(
1203                                callee_hash,
1204                                host,
1205                                current_package_debug_info,
1206                                source_node_id,
1207                                source_aware_execution,
1208                            )
1209                            .await
1210                        {
1211                            Ok(result) => result,
1212                            Err(err) => return ControlFlow::Break(BreakReason::Err(err)),
1213                        };
1214
1215                    finish_load_mast_forest_from_dyn_start(
1216                        root_id,
1217                        new_forest,
1218                        new_package_debug_info,
1219                        new_source_node_id,
1220                        self,
1221                        current_forest,
1222                        package_debug_info,
1223                        inline_call_contexts.as_slice(),
1224                        continuation_stack,
1225                        tracer,
1226                        stopper,
1227                    )?;
1228                },
1229                InternalBreakReason::LoadMastForestFromExternal {
1230                    external_node_id,
1231                    procedure_hash,
1232                    source_node_id,
1233                } => {
1234                    let inline_call_context = package_debug_info.clone().and_then(|debug_info| {
1235                        SourceInlineCallContext::for_source_boundary(debug_info, source_node_id)
1236                    });
1237                    let (root_id, new_forest, new_package_debug_info, new_source_node_id) =
1238                        match self
1239                            .load_mast_forest(
1240                                procedure_hash,
1241                                host,
1242                                current_package_debug_info,
1243                                source_node_id,
1244                                source_aware_execution,
1245                            )
1246                            .await
1247                        {
1248                            Ok(result) => result,
1249                            Err(err) => {
1250                                let maybe_enriched_err = maybe_use_caller_error_context(
1251                                    err,
1252                                    continuation_stack,
1253                                    current_package_debug_info,
1254                                    host,
1255                                );
1256                                return ControlFlow::Break(BreakReason::Err(maybe_enriched_err));
1257                            },
1258                        };
1259
1260                    finish_load_mast_forest_from_external(
1261                        root_id,
1262                        new_forest,
1263                        new_package_debug_info,
1264                        new_source_node_id,
1265                        inline_call_context,
1266                        (external_node_id, source_node_id),
1267                        current_forest,
1268                        package_debug_info,
1269                        inline_call_contexts,
1270                        continuation_stack,
1271                        tracer,
1272                    )?;
1273                },
1274            }
1275        }
1276
1277        match StackOutputs::new(
1278            &self.stack[self.stack_bot_idx..self.stack_top_idx]
1279                .iter()
1280                .rev()
1281                .copied()
1282                .collect::<Vec<_>>(),
1283        ) {
1284            Ok(stack_outputs) => ControlFlow::Continue(stack_outputs),
1285            Err(_) => ControlFlow::Break(BreakReason::Err(ExecutionError::OutputStackOverflow(
1286                self.stack_top_idx - self.stack_bot_idx - MIN_STACK_DEPTH,
1287            ))),
1288        }
1289    }
1290
1291    // HELPERS
1292    // ------------------------------------------------------------------------------------------
1293
1294    fn load_mast_forest_sync(
1295        &mut self,
1296        node_digest: Word,
1297        host: &mut impl SyncHost,
1298        package_debug_info: Option<&PackageDebugInfo>,
1299        source_node_id: Option<DebugSourceNodeId>,
1300        source_aware_execution: bool,
1301    ) -> Result<
1302        (
1303            MastNodeId,
1304            Arc<MastForest>,
1305            Option<Arc<PackageDebugInfo>>,
1306            Option<DebugSourceNodeId>,
1307        ),
1308        ExecutionError,
1309    > {
1310        let cached = self.loaded_mast_forests.get(&node_digest).cloned();
1311        let was_cached = cached.is_some();
1312        let loaded_mast_forest = match cached {
1313            Some(mast_forest) => mast_forest,
1314            None => host.get_mast_forest(&node_digest).ok_or_else(|| {
1315                match (package_debug_info, source_node_id) {
1316                    (Some(debug_info), Some(source_node_id)) => {
1317                        crate::errors::procedure_not_found_with_package_source_context(
1318                            node_digest,
1319                            PackageSourceDebugContext::new(debug_info, source_node_id),
1320                            host,
1321                        )
1322                    },
1323                    _ => crate::errors::procedure_not_found_with_context(node_digest),
1324                }
1325            })?,
1326        };
1327        let mast_forest = loaded_mast_forest.mast_forest().clone();
1328
1329        let root_id = mast_forest.find_procedure_root(node_digest).ok_or_else(|| {
1330            let context = match (package_debug_info, source_node_id) {
1331                (Some(debug_info), Some(source_node_id)) => {
1332                    Some(PackageSourceDebugContext::new(debug_info, source_node_id))
1333                },
1334                _ => None,
1335            };
1336            malformed_mast_forest_with_context(node_digest, context, host)
1337        })?;
1338
1339        if !was_cached {
1340            self.cache_loaded_mast_forest(&loaded_mast_forest);
1341        }
1342        self.merge_mast_forest_advice(&mast_forest).map_exec_err()?;
1343        let (loaded_package_debug_info, loaded_source_node_id) =
1344            Self::loaded_package_source_context(
1345                &loaded_mast_forest,
1346                root_id,
1347                source_aware_execution,
1348            )?;
1349
1350        Ok((root_id, mast_forest, loaded_package_debug_info, loaded_source_node_id))
1351    }
1352
1353    async fn load_mast_forest(
1354        &mut self,
1355        node_digest: Word,
1356        host: &mut impl Host,
1357        package_debug_info: Option<&PackageDebugInfo>,
1358        source_node_id: Option<DebugSourceNodeId>,
1359        source_aware_execution: bool,
1360    ) -> Result<
1361        (
1362            MastNodeId,
1363            Arc<MastForest>,
1364            Option<Arc<PackageDebugInfo>>,
1365            Option<DebugSourceNodeId>,
1366        ),
1367        ExecutionError,
1368    > {
1369        let cached = self.loaded_mast_forests.get(&node_digest).cloned();
1370        let was_cached = cached.is_some();
1371        let loaded_mast_forest = match cached {
1372            Some(mast_forest) => mast_forest,
1373            None => {
1374                if let Some(mast_forest) = host.get_mast_forest(&node_digest).await {
1375                    mast_forest
1376                } else {
1377                    return Err(match (package_debug_info, source_node_id) {
1378                        (Some(debug_info), Some(source_node_id)) => {
1379                            crate::errors::procedure_not_found_with_package_source_context(
1380                                node_digest,
1381                                PackageSourceDebugContext::new(debug_info, source_node_id),
1382                                host,
1383                            )
1384                        },
1385                        _ => crate::errors::procedure_not_found_with_context(node_digest),
1386                    });
1387                }
1388            },
1389        };
1390        let mast_forest = loaded_mast_forest.mast_forest().clone();
1391
1392        let root_id = mast_forest.find_procedure_root(node_digest).ok_or_else(|| {
1393            let context = match (package_debug_info, source_node_id) {
1394                (Some(debug_info), Some(source_node_id)) => {
1395                    Some(PackageSourceDebugContext::new(debug_info, source_node_id))
1396                },
1397                _ => None,
1398            };
1399            malformed_mast_forest_with_context(node_digest, context, host)
1400        })?;
1401
1402        if !was_cached {
1403            self.cache_loaded_mast_forest(&loaded_mast_forest);
1404        }
1405        self.merge_mast_forest_advice(&mast_forest).map_exec_err()?;
1406        let (loaded_package_debug_info, loaded_source_node_id) =
1407            Self::loaded_package_source_context(
1408                &loaded_mast_forest,
1409                root_id,
1410                source_aware_execution,
1411            )?;
1412
1413        Ok((root_id, mast_forest, loaded_package_debug_info, loaded_source_node_id))
1414    }
1415
1416    fn cache_loaded_mast_forest(&mut self, loaded_mast_forest: &LoadedMastForest) {
1417        for procedure_digest in loaded_mast_forest.mast_forest().local_procedure_digests() {
1418            self.loaded_mast_forests
1419                .entry(procedure_digest)
1420                .or_insert_with(|| loaded_mast_forest.clone());
1421        }
1422    }
1423
1424    fn merge_mast_forest_advice(&mut self, mast_forest: &MastForest) -> Result<(), AdviceError> {
1425        let commitment = mast_forest.commitment();
1426        if self.merged_mast_forests.contains(&commitment) {
1427            return Ok(());
1428        }
1429
1430        self.advice.extend_map(mast_forest.advice_map())?;
1431        self.merged_mast_forests.insert(commitment);
1432        Ok(())
1433    }
1434
1435    fn loaded_package_source_context(
1436        loaded_mast_forest: &LoadedMastForest,
1437        root_id: MastNodeId,
1438        source_aware_execution: bool,
1439    ) -> Result<(Option<Arc<PackageDebugInfo>>, Option<DebugSourceNodeId>), ExecutionError> {
1440        if !source_aware_execution {
1441            return Ok((None, None));
1442        }
1443
1444        let Some(package_debug_info) = loaded_mast_forest
1445            .package_debug_info()
1446            .map_err(|_| ExecutionError::Internal("loaded package debug info is malformed"))?
1447        else {
1448            return Ok((None, None));
1449        };
1450
1451        let source_node_id = match package_debug_info.unique_source_root_for_exec_node(root_id) {
1452            Ok(source_node_id) => source_node_id,
1453            Err(DebugSourceGraphLookupError::AmbiguousRoot { .. }) => None,
1454            Err(_) => {
1455                return Err(ExecutionError::Internal(
1456                    "loaded package debug source graph has malformed entrypoint roots",
1457                ));
1458            },
1459        };
1460
1461        Ok((Some(package_debug_info), source_node_id))
1462    }
1463
1464    /// Executes the given program synchronously one step at a time.
1465    pub fn execute_by_step_sync(
1466        mut self,
1467        program: &Program,
1468        host: &mut impl SyncHost,
1469    ) -> Result<StackOutputs, ExecutionError> {
1470        let mut current_resume_ctx = self.get_initial_resume_context(program)?;
1471
1472        loop {
1473            match self.step_sync(host, current_resume_ctx)? {
1474                Some(next_resume_ctx) => {
1475                    current_resume_ctx = next_resume_ctx;
1476                },
1477                None => break Ok(self.current_stack_outputs()),
1478            }
1479        }
1480    }
1481
1482    /// Executes the given program synchronously one step at a time with package-owned source/debug
1483    /// context.
1484    #[cfg(any(test, feature = "testing"))]
1485    pub fn execute_by_step_with_package_debug_info_sync(
1486        mut self,
1487        program: &Program,
1488        package_debug_info: &PackageDebugInfo,
1489        host: &mut impl SyncHost,
1490    ) -> Result<StackOutputs, ExecutionError> {
1491        let mut current_resume_ctx =
1492            self.source_aware_resume_context(program, package_debug_info, None)?;
1493
1494        loop {
1495            match self.step_with_package_debug_info_sync(
1496                host,
1497                current_resume_ctx,
1498                package_debug_info,
1499            )? {
1500                Some(next_resume_ctx) => {
1501                    current_resume_ctx = next_resume_ctx;
1502                },
1503                None => break Ok(self.current_stack_outputs()),
1504            }
1505        }
1506    }
1507
1508    /// Executes the given program synchronously one step at a time with package-owned source/debug
1509    /// context rooted at `entrypoint_source_node_id`.
1510    #[cfg(any(test, feature = "testing"))]
1511    pub fn execute_by_step_with_package_debug_info_at_source_node_sync(
1512        mut self,
1513        program: &Program,
1514        package_debug_info: &PackageDebugInfo,
1515        entrypoint_source_node_id: DebugSourceNodeId,
1516        host: &mut impl SyncHost,
1517    ) -> Result<StackOutputs, ExecutionError> {
1518        let mut current_resume_ctx = self.source_aware_resume_context(
1519            program,
1520            package_debug_info,
1521            Some(entrypoint_source_node_id),
1522        )?;
1523
1524        loop {
1525            match self.step_with_package_debug_info_sync(
1526                host,
1527                current_resume_ctx,
1528                package_debug_info,
1529            )? {
1530                Some(next_resume_ctx) => {
1531                    current_resume_ctx = next_resume_ctx;
1532                },
1533                None => break Ok(self.current_stack_outputs()),
1534            }
1535        }
1536    }
1537
1538    /// Async variant of [`Self::execute_by_step_sync`].
1539    #[inline(always)]
1540    pub async fn execute_by_step(
1541        mut self,
1542        program: &Program,
1543        host: &mut impl Host,
1544    ) -> Result<StackOutputs, ExecutionError> {
1545        let mut current_resume_ctx = self.get_initial_resume_context(program)?;
1546        let mut processor = self;
1547
1548        loop {
1549            match processor.step(host, current_resume_ctx).await? {
1550                Some(next_resume_ctx) => {
1551                    current_resume_ctx = next_resume_ctx;
1552                },
1553                None => break Ok(processor.current_stack_outputs()),
1554            }
1555        }
1556    }
1557
1558    /// Async variant of [`Self::execute_by_step_with_package_debug_info_sync`].
1559    #[cfg(any(test, feature = "testing"))]
1560    #[inline(always)]
1561    pub async fn execute_by_step_with_package_debug_info(
1562        mut self,
1563        program: &Program,
1564        package_debug_info: &PackageDebugInfo,
1565        host: &mut impl Host,
1566    ) -> Result<StackOutputs, ExecutionError> {
1567        let mut current_resume_ctx =
1568            self.source_aware_resume_context(program, package_debug_info, None)?;
1569        let mut processor = self;
1570
1571        loop {
1572            match processor
1573                .step_with_package_debug_info(host, current_resume_ctx, package_debug_info)
1574                .await?
1575            {
1576                Some(next_resume_ctx) => {
1577                    current_resume_ctx = next_resume_ctx;
1578                },
1579                None => break Ok(processor.current_stack_outputs()),
1580            }
1581        }
1582    }
1583
1584    /// Async variant of
1585    /// [`Self::execute_by_step_with_package_debug_info_at_source_node_sync`].
1586    #[cfg(any(test, feature = "testing"))]
1587    #[inline(always)]
1588    pub async fn execute_by_step_with_package_debug_info_at_source_node(
1589        mut self,
1590        program: &Program,
1591        package_debug_info: &PackageDebugInfo,
1592        entrypoint_source_node_id: DebugSourceNodeId,
1593        host: &mut impl Host,
1594    ) -> Result<StackOutputs, ExecutionError> {
1595        let mut current_resume_ctx = self.source_aware_resume_context(
1596            program,
1597            package_debug_info,
1598            Some(entrypoint_source_node_id),
1599        )?;
1600        let mut processor = self;
1601
1602        loop {
1603            match processor
1604                .step_with_package_debug_info(host, current_resume_ctx, package_debug_info)
1605                .await?
1606            {
1607                Some(next_resume_ctx) => {
1608                    current_resume_ctx = next_resume_ctx;
1609                },
1610                None => break Ok(processor.current_stack_outputs()),
1611            }
1612        }
1613    }
1614
1615    /// Similar to [`Self::execute_sync`], but allows mutable access to the processor.
1616    ///
1617    /// This is mainly meant to be used in tests.
1618    #[cfg(any(test, feature = "testing"))]
1619    pub fn execute_mut_sync(
1620        &mut self,
1621        program: &Program,
1622        host: &mut impl SyncHost,
1623    ) -> Result<StackOutputs, ExecutionError> {
1624        let mut continuation_stack = ContinuationStack::new(program);
1625        let mut current_forest = program.mast_forest().clone();
1626        let mut package_debug_info = None;
1627        let mut inline_call_contexts = Vec::new();
1628
1629        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
1630
1631        let flow = self.execute_impl(
1632            &mut continuation_stack,
1633            &mut current_forest,
1634            program.kernel(),
1635            host,
1636            &mut NoopTracer,
1637            &NeverStopper,
1638            &mut package_debug_info,
1639            &mut inline_call_contexts,
1640        );
1641        Self::stack_result_from_flow(flow)
1642    }
1643
1644    /// Async variant of [`Self::execute_mut_sync`].
1645    #[cfg(any(test, feature = "testing"))]
1646    #[inline(always)]
1647    pub async fn execute_mut(
1648        &mut self,
1649        program: &Program,
1650        host: &mut impl Host,
1651    ) -> Result<StackOutputs, ExecutionError> {
1652        let mut continuation_stack = ContinuationStack::new(program);
1653        let mut current_forest = program.mast_forest().clone();
1654        let mut package_debug_info = None;
1655        let mut inline_call_contexts = Vec::new();
1656
1657        self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
1658
1659        let flow = self
1660            .execute_impl_async(
1661                &mut continuation_stack,
1662                &mut current_forest,
1663                program.kernel(),
1664                host,
1665                &mut NoopTracer,
1666                &NeverStopper,
1667                &mut package_debug_info,
1668                &mut inline_call_contexts,
1669            )
1670            .await;
1671        Self::stack_result_from_flow(flow)
1672    }
1673}
1674
1675#[cfg(all(test, feature = "std"))]
1676mod tests {
1677    use super::FastProcessor;
1678
1679    #[test]
1680    fn sole_rayon_worker_requires_buffered_trace_building() {
1681        rayon::ThreadPoolBuilder::new()
1682            .num_threads(1)
1683            .build()
1684            .unwrap()
1685            .install(|| assert!(FastProcessor::rayon_has_no_parallel_worker()));
1686    }
1687}