Skip to main content

miden_air_definitions/vm/
execution_trace.rs

1//! Materialized VM relation data and trace diagnostics shared by execution and proving.
2
3use alloc::vec::Vec;
4#[cfg(any(test, feature = "testing"))]
5use core::ops::Range;
6
7use miden_core::{
8    Felt, Word, ZERO,
9    deferred::Digest,
10    program::{MIN_STACK_DEPTH, ProgramInfo, StackInputs, StackOutputs},
11    utils::RowMajorMatrix,
12};
13
14#[cfg(test)]
15use super::trace::MIN_TRACE_LEN;
16use super::{
17    MIDEN_AIR_COUNT, MidenAir, PublicInputs,
18    trace::{MainTrace, RowIndex, eidos_compression::EIDOS_COMPRESSION_CYCLE_LEN},
19};
20
21// VM EXECUTION TRACE
22// ================================================================================================
23
24/// Execution trace which is generated when a program is executed on the VM.
25///
26/// The trace consists of the following components:
27/// - Per-AIR main traces for Core, Chiplets, Eidos compression, and byte-pair lookup.
28/// - Information about the program (program hash and the kernel).
29/// - Information about the initial and final stack states and authenticated precompile root.
30/// - Summary of trace lengths of the main trace components.
31#[derive(Debug)]
32pub struct VmTrace {
33    main_trace: MainTrace,
34    program_info: ProgramInfo,
35    stack_inputs: StackInputs,
36    stack_outputs: StackOutputs,
37    precompile_root: Digest,
38    trace_len_summary: TraceLenSummary,
39}
40
41impl VmTrace {
42    // CONSTRUCTOR
43    // --------------------------------------------------------------------------------------------
44
45    /// Combines main-trace matrices with their public inputs and row-count summary.
46    ///
47    /// The caller must supply public inputs and a summary for the same execution as `main_trace`.
48    /// The summary's padded heights must match the matrices in [`crate::vm::AIRS`] order.
49    /// Construction does not evaluate the AIR constraints.
50    pub fn new_from_parts(
51        program_info: ProgramInfo,
52        stack_inputs: StackInputs,
53        stack_outputs: StackOutputs,
54        precompile_root: Digest,
55        main_trace: MainTrace,
56        trace_len_summary: TraceLenSummary,
57    ) -> Self {
58        Self {
59            main_trace,
60            program_info,
61            stack_inputs,
62            stack_outputs,
63            precompile_root,
64            trace_len_summary,
65        }
66    }
67
68    // PUBLIC ACCESSORS
69    // --------------------------------------------------------------------------------------------
70
71    /// Returns the program info of this execution trace.
72    pub fn program_info(&self) -> &ProgramInfo {
73        &self.program_info
74    }
75
76    /// Returns hash of the program execution of which resulted in this execution trace.
77    pub fn program_hash(&self) -> &Word {
78        self.program_info.program_hash()
79    }
80
81    /// Returns outputs of the program execution which resulted in this execution trace.
82    pub fn stack_outputs(&self) -> &StackOutputs {
83        &self.stack_outputs
84    }
85
86    /// Returns the public inputs for this execution trace.
87    pub fn public_inputs(&self) -> PublicInputs {
88        PublicInputs::new(
89            self.program_info.clone(),
90            self.stack_inputs,
91            self.stack_outputs,
92            self.precompile_root,
93        )
94    }
95
96    /// Returns the public values for this execution trace.
97    pub fn to_public_values(&self) -> Vec<Felt> {
98        self.public_inputs().to_elements()
99    }
100
101    /// Returns a reference to the main trace.
102    pub fn main_trace(&self) -> &MainTrace {
103        &self.main_trace
104    }
105
106    /// Returns the authenticated root of the deferred precompile state.
107    pub fn precompile_root(&self) -> Digest {
108        self.precompile_root
109    }
110
111    /// Returns the owned stack outputs required for proof packaging.
112    pub fn into_outputs(self) -> StackOutputs {
113        self.stack_outputs
114    }
115
116    /// Returns the initial state of the top 16 stack registers.
117    pub fn init_stack_state(&self) -> StackInputs {
118        self.stack_inputs
119    }
120
121    /// Returns the final state of the top 16 stack registers.
122    pub fn last_stack_state(&self) -> StackOutputs {
123        let last_step = RowIndex::from(self.last_step());
124        let mut result = [ZERO; MIN_STACK_DEPTH];
125        for (i, result) in result.iter_mut().enumerate() {
126            *result = self.main_trace.stack_element(i, last_step);
127        }
128        result.into()
129    }
130
131    /// Returns the trace length.
132    pub fn get_trace_len(&self) -> usize {
133        self.main_trace.num_rows()
134    }
135
136    /// Returns the length of the trace (number of rows in the main trace).
137    pub fn length(&self) -> usize {
138        self.get_trace_len()
139    }
140
141    /// Returns a summary of the per-AIR trace lengths.
142    pub fn trace_len_summary(&self) -> &TraceLenSummary {
143        &self.trace_len_summary
144    }
145
146    /// Consuming variant for the proving hot path: moves the row-major buffers.
147    pub fn into_air_matrices(
148        self,
149    ) -> (
150        RowMajorMatrix<Felt>,
151        RowMajorMatrix<Felt>,
152        RowMajorMatrix<Felt>,
153        RowMajorMatrix<Felt>,
154    ) {
155        self.main_trace.into_air_matrices()
156    }
157
158    // HELPER METHODS
159    // --------------------------------------------------------------------------------------------
160
161    /// Returns the index of the last row in the Core trace.
162    fn last_step(&self) -> usize {
163        self.main_trace.core_height() - 1
164    }
165
166    #[cfg(any(test, feature = "testing"))]
167    pub fn get_column_range(&self, range: Range<usize>) -> Vec<Vec<Felt>> {
168        self.main_trace.get_column_range(range)
169    }
170}
171
172// TRACE LENGTH SUMMARY
173// ================================================================================================
174
175/// Error returned by [`TraceLenSummary::new`] when the padded AIR heights are inconsistent.
176#[derive(Debug, Clone, Copy, Eq, PartialEq, thiserror::Error)]
177pub enum TraceLenSummaryError {
178    /// The chiplet row counts add up to more than `usize::MAX`.
179    #[error("the chiplet row counts add up to more than usize::MAX")]
180    ChipletsRowsOverflow,
181    /// The padded height of an AIR is zero.
182    #[error("padded height of the {air} AIR is zero")]
183    ZeroHeight {
184        /// Name of the AIR with the invalid height.
185        air: &'static str,
186    },
187    /// The padded height of an AIR is smaller than its number of unpadded rows.
188    #[error("padded height {padded_height} of the {air} AIR is below its {rows} unpadded rows")]
189    HeightBelowRows {
190        /// Name of the AIR with the invalid height.
191        air: &'static str,
192        /// The rejected padded height.
193        padded_height: usize,
194        /// The unpadded row count that the padded height must cover.
195        rows: usize,
196    },
197}
198
199/// Row counts for the AIR segments produced by trace generation.
200///
201/// Dynamic AIRs store their unpadded row counts. Use the `*_height()` accessors for their padded
202/// power-of-two AIR matrix heights. The byte-pair lookup stores its fixed physical row count.
203#[derive(Debug, Eq, PartialEq, Clone, Copy)]
204pub struct TraceLenSummary {
205    core_rows: usize,
206    chiplets: ChipletsLengths,
207    eidos_compression_rows: usize,
208    byte_pair_lookup_rows: usize,
209    /// Actual padded heights in [`crate::vm::AIRS`] order.
210    padded_heights: [usize; MIDEN_AIR_COUNT],
211}
212
213impl TraceLenSummary {
214    /// Builds a summary after the trace builder has computed the padded per-AIR heights, in
215    /// [`crate::vm::AIRS`] order: Core, Chiplets, Eidos compression, then And8 lookup.
216    ///
217    /// # Errors
218    ///
219    /// Returns an error if the chiplet row counts overflow `usize`, or if a padded height is zero
220    /// or smaller than the unpadded row count of its AIR. These checks keep
221    /// [`Self::padding_percentage`] from underflowing or dividing by zero.
222    pub fn new(
223        core_rows: usize,
224        chiplets: ChipletsLengths,
225        eidos_compression_rows: usize,
226        byte_pair_lookup_rows: usize,
227        padded_heights: [usize; MIDEN_AIR_COUNT],
228    ) -> Result<Self, TraceLenSummaryError> {
229        let chiplets_rows =
230            chiplets.checked_trace_len().ok_or(TraceLenSummaryError::ChipletsRowsOverflow)?;
231        let unpadded_rows: [(&'static str, usize); MIDEN_AIR_COUNT] = [
232            ("Core", core_rows),
233            ("Chiplets", chiplets_rows),
234            ("Eidos compression", eidos_compression_rows),
235            ("byte-pair lookup", byte_pair_lookup_rows),
236        ];
237        for ((air, rows), padded_height) in unpadded_rows.into_iter().zip(padded_heights) {
238            if padded_height == 0 {
239                return Err(TraceLenSummaryError::ZeroHeight { air });
240            }
241            if padded_height < rows {
242                return Err(TraceLenSummaryError::HeightBelowRows { air, padded_height, rows });
243            }
244        }
245
246        Ok(TraceLenSummary {
247            core_rows,
248            chiplets,
249            eidos_compression_rows,
250            byte_pair_lookup_rows,
251            padded_heights,
252        })
253    }
254
255    /// Returns the unpadded core AIR rows (system + decoder + stack).
256    pub fn core_rows(&self) -> usize {
257        self.core_rows
258    }
259
260    /// Returns the chiplet row-count breakdown.
261    pub fn chiplets(&self) -> ChipletsLengths {
262        self.chiplets
263    }
264
265    /// Returns the unpadded chiplets AIR rows.
266    pub fn chiplets_rows(&self) -> usize {
267        self.chiplets.trace_len()
268    }
269
270    /// Returns the unpadded Eidos compression AIR rows.
271    pub fn eidos_compression_rows(&self) -> usize {
272        self.eidos_compression_rows
273    }
274
275    /// Returns the number of Eidos compression blocks represented by the standalone compression
276    /// AIR rows.
277    pub fn eidos_compression_count(&self) -> usize {
278        debug_assert_eq!(self.eidos_compression_rows % EIDOS_COMPRESSION_CYCLE_LEN, 0);
279        self.eidos_compression_rows / EIDOS_COMPRESSION_CYCLE_LEN
280    }
281
282    /// Returns the fixed byte-pair lookup AIR rows.
283    ///
284    /// This table has one row per byte pair, so its row count is already its physical AIR height.
285    pub fn byte_pair_lookup_rows(&self) -> usize {
286        self.byte_pair_lookup_rows
287    }
288
289    /// Returns the maximum unpadded row count among the four AIRs.
290    pub fn trace_len(&self) -> usize {
291        self.core_rows
292            .max(self.chiplets_rows())
293            .max(self.eidos_compression_rows)
294            .max(self.byte_pair_lookup_rows)
295    }
296
297    /// Returns the padded height of the core AIR.
298    pub fn core_height(&self) -> usize {
299        self.padded_heights[MidenAir::CORE.instance_index()]
300    }
301
302    /// Returns the padded height of the chiplets AIR.
303    pub fn chiplets_height(&self) -> usize {
304        self.padded_heights[MidenAir::CHIPLETS.instance_index()]
305    }
306
307    /// Returns the padded height of the Eidos compression AIR.
308    pub fn eidos_compression_height(&self) -> usize {
309        self.padded_heights[MidenAir::EIDOS_COMPRESSION.instance_index()]
310    }
311
312    /// Returns the greatest padded height among the four AIRs.
313    pub fn padded_trace_len(&self) -> usize {
314        self.padded_heights.into_iter().max().expect("heights is non-empty")
315    }
316
317    /// Returns the actual padded per-AIR heights, in [`crate::vm::AIRS`] order.
318    pub fn padded_heights(&self) -> &[usize; MIDEN_AIR_COUNT] {
319        &self.padded_heights
320    }
321
322    /// Returns the percent (0 - 100) of rows added by padding.
323    ///
324    /// This cannot underflow, overflow, or divide by zero: [`Self::new`] guarantees that every
325    /// padded height is nonzero and covers the unpadded rows of its AIR.
326    pub fn padding_percentage(&self) -> usize {
327        // Widen to `u128` so that `(padded - rows) * 100` cannot overflow for very large heights.
328        // The result is at most 100, so it always fits back into `usize`.
329        let padded = self.padded_trace_len() as u128;
330        let unpadded = self.trace_len() as u128;
331        ((padded - unpadded) * 100 / padded) as usize
332    }
333}
334
335// CHIPLET LENGTHS
336// ================================================================================================
337
338/// Contains trace lengths of all chiplets: hash, bitwise, memory, ACE, and kernel ROM.
339#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
340pub struct ChipletsLengths {
341    hash_chiplet_len: usize,
342    bitwise_chiplet_len: usize,
343    memory_chiplet_len: usize,
344    ace_chiplet_len: usize,
345    kernel_rom_len: usize,
346}
347
348impl ChipletsLengths {
349    pub fn from_parts(
350        hash_len: usize,
351        bitwise_len: usize,
352        memory_len: usize,
353        ace_len: usize,
354        kernel_len: usize,
355    ) -> Self {
356        ChipletsLengths {
357            hash_chiplet_len: hash_len,
358            bitwise_chiplet_len: bitwise_len,
359            memory_chiplet_len: memory_len,
360            ace_chiplet_len: ace_len,
361            kernel_rom_len: kernel_len,
362        }
363    }
364
365    /// Returns the length of the hash chiplet trace.
366    pub fn hash_chiplet_len(&self) -> usize {
367        self.hash_chiplet_len
368    }
369
370    /// Returns the length of the bitwise trace.
371    pub fn bitwise_chiplet_len(&self) -> usize {
372        self.bitwise_chiplet_len
373    }
374
375    /// Returns the length of the memory trace.
376    pub fn memory_chiplet_len(&self) -> usize {
377        self.memory_chiplet_len
378    }
379
380    /// Returns the length of the ACE chiplet trace.
381    pub fn ace_chiplet_len(&self) -> usize {
382        self.ace_chiplet_len
383    }
384
385    /// Returns the length of the kernel ROM trace.
386    pub fn kernel_rom_len(&self) -> usize {
387        self.kernel_rom_len
388    }
389
390    /// Returns the length of the trace required to accommodate chiplet components and 1
391    /// mandatory padding row required for ensuring sufficient trace length for auxiliary connector
392    /// columns that rely on the memory chiplet.
393    pub fn trace_len(&self) -> usize {
394        self.hash_chiplet_len()
395            + self.bitwise_chiplet_len()
396            + self.memory_chiplet_len()
397            + self.ace_chiplet_len()
398            + self.kernel_rom_len()
399            + 1
400    }
401
402    /// Same as [`Self::trace_len`], but returns `None` instead of overflowing.
403    pub fn checked_trace_len(&self) -> Option<usize> {
404        self.hash_chiplet_len()
405            .checked_add(self.bitwise_chiplet_len())?
406            .checked_add(self.memory_chiplet_len())?
407            .checked_add(self.ace_chiplet_len())?
408            .checked_add(self.kernel_rom_len())?
409            .checked_add(1)
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    #[test]
418    fn trace_len_summary_reports_eidos_compression_count() {
419        let summary = TraceLenSummary::new(
420            0,
421            ChipletsLengths::default(),
422            3 * EIDOS_COMPRESSION_CYCLE_LEN,
423            0,
424            [
425                MIN_TRACE_LEN,
426                MIN_TRACE_LEN,
427                (3 * EIDOS_COMPRESSION_CYCLE_LEN).next_power_of_two().max(MIN_TRACE_LEN),
428                MIN_TRACE_LEN,
429            ],
430        )
431        .expect("valid padded heights");
432
433        assert_eq!(summary.eidos_compression_rows(), 3 * EIDOS_COMPRESSION_CYCLE_LEN);
434        assert_eq!(summary.eidos_compression_count(), 3);
435    }
436
437    #[test]
438    fn trace_len_summary_records_four_air_heights_in_instance_order() {
439        let heights = [MIN_TRACE_LEN, 2 * MIN_TRACE_LEN, 4 * MIN_TRACE_LEN, 1 << 16];
440        let summary = TraceLenSummary::new(
441            17,
442            ChipletsLengths::from_parts(19, 0, 0, 0, 0),
443            3 * EIDOS_COMPRESSION_CYCLE_LEN,
444            1 << 16,
445            heights,
446        )
447        .expect("valid padded heights");
448
449        assert_eq!(summary.core_rows(), 17);
450        // ChipletsLengths adds the mandatory connector-padding row.
451        assert_eq!(summary.chiplets_rows(), 20);
452        assert_eq!(summary.eidos_compression_rows(), 3 * EIDOS_COMPRESSION_CYCLE_LEN);
453        assert_eq!(summary.byte_pair_lookup_rows(), 1 << 16);
454        assert_eq!(summary.padded_heights(), &heights);
455        assert_eq!(summary.core_height(), heights[0]);
456        assert_eq!(summary.chiplets_height(), heights[1]);
457        assert_eq!(summary.eidos_compression_height(), heights[2]);
458        assert_eq!(summary.padded_trace_len(), 1 << 16);
459    }
460
461    #[test]
462    fn trace_len_summary_rejects_zero_padded_height() {
463        for air in 0..MIDEN_AIR_COUNT {
464            let mut heights = [MIN_TRACE_LEN; MIDEN_AIR_COUNT];
465            heights[air] = 0;
466            let result = TraceLenSummary::new(0, ChipletsLengths::default(), 0, 0, heights);
467            assert!(
468                matches!(result, Err(TraceLenSummaryError::ZeroHeight { .. })),
469                "AIR {air}: {result:?}",
470            );
471        }
472    }
473
474    #[test]
475    fn trace_len_summary_rejects_padded_height_below_rows() {
476        let rows = 2 * MIN_TRACE_LEN;
477        let result = TraceLenSummary::new(
478            rows,
479            ChipletsLengths::default(),
480            0,
481            0,
482            [MIN_TRACE_LEN; MIDEN_AIR_COUNT],
483        );
484
485        assert_eq!(
486            result,
487            Err(TraceLenSummaryError::HeightBelowRows {
488                air: "Core",
489                padded_height: MIN_TRACE_LEN,
490                rows,
491            })
492        );
493    }
494
495    #[test]
496    fn trace_len_summary_padding_percentage_for_valid_heights() {
497        let heights = [MIN_TRACE_LEN; MIDEN_AIR_COUNT];
498
499        let half_full =
500            TraceLenSummary::new(MIN_TRACE_LEN / 2, ChipletsLengths::default(), 0, 0, heights)
501                .expect("valid padded heights");
502        assert_eq!(half_full.padding_percentage(), 50);
503
504        let full = TraceLenSummary::new(MIN_TRACE_LEN, ChipletsLengths::default(), 0, 0, heights)
505            .expect("valid padded heights");
506        assert_eq!(full.padding_percentage(), 0);
507    }
508
509    #[test]
510    fn trace_len_summary_padding_percentage_does_not_overflow_for_huge_heights() {
511        let heights = [1usize << (usize::BITS - 1); MIDEN_AIR_COUNT];
512        let summary = TraceLenSummary::new(0, ChipletsLengths::default(), 0, 0, heights)
513            .expect("valid padded heights");
514
515        // The default chiplets contribute one connector-padding row, so almost all rows are
516        // padding. The percentage is rounded down.
517        assert_eq!(summary.padding_percentage(), 99);
518    }
519
520    #[test]
521    fn trace_len_summary_rejects_chiplets_row_count_overflow() {
522        for chiplets in [
523            // The mandatory padding row overflows.
524            ChipletsLengths::from_parts(usize::MAX, 0, 0, 0, 0),
525            // The sum of the chiplets overflows.
526            ChipletsLengths::from_parts(usize::MAX, 1, 0, 0, 0),
527        ] {
528            let result = TraceLenSummary::new(0, chiplets, 0, 0, [MIN_TRACE_LEN; MIDEN_AIR_COUNT]);
529            assert_eq!(result, Err(TraceLenSummaryError::ChipletsRowsOverflow));
530        }
531    }
532}