miden-air 0.23.0

Algebraic intermediate representation of Miden VM processor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! `DebugTraceBuilder` — the `LookupBuilder` adapter that updates
//! [`super::DebugTraceState`] per row of a concrete main trace.
//!
//! Pure implementation detail: instantiation happens inside
//! `super::run_trace_walk`. The builder, column, group, and batch handles all collapse
//! their associated types to `Felt` / `QuadFelt`.

use alloc::{format, string::ToString};

use miden_core::field::{PrimeCharacteristicRing, QuadFelt};
use miden_crypto::stark::air::RowWindow;

use super::{
    super::super::{
        BoundaryBuilder, Challenges, Deg, LookupBatch, LookupBuilder, LookupColumn, LookupGroup,
        LookupMessage,
    },
    DebugTraceState, MutualExclusionViolation, PushRecord,
};
use crate::Felt;

// BUILDER
// ================================================================================================

/// Real-trace `LookupBuilder` that updates [`super::DebugTraceState`] per row.
pub struct DebugTraceBuilder<'a> {
    main: RowWindow<'a, Felt>,
    periodic_values: &'a [Felt],
    challenges: &'a Challenges<QuadFelt>,
    state: &'a mut DebugTraceState,
    row_idx: usize,
    column_idx: usize,
}

impl<'a> DebugTraceBuilder<'a> {
    pub fn new(
        main: RowWindow<'a, Felt>,
        periodic_values: &'a [Felt],
        challenges: &'a Challenges<QuadFelt>,
        state: &'a mut DebugTraceState,
        row_idx: usize,
    ) -> Self {
        Self {
            main,
            periodic_values,
            challenges,
            state,
            row_idx,
            column_idx: 0,
        }
    }
}

impl<'a> LookupBuilder for DebugTraceBuilder<'a> {
    type F = Felt;
    type Expr = Felt;
    type Var = Felt;

    type EF = QuadFelt;
    type ExprEF = QuadFelt;
    type VarEF = QuadFelt;

    type PeriodicVar = Felt;

    type MainWindow = RowWindow<'a, Felt>;

    type Column<'c>
        = DebugTraceColumn<'c>
    where
        Self: 'c;

    fn main(&self) -> Self::MainWindow {
        self.main
    }

    fn periodic_values(&self) -> &[Self::PeriodicVar] {
        self.periodic_values
    }

    fn next_column<'c, R>(
        &'c mut self,
        f: impl FnOnce(&mut Self::Column<'c>) -> R,
        _deg: Deg,
    ) -> R {
        let mut col = DebugTraceColumn {
            challenges: self.challenges,
            state: &mut *self.state,
            row_idx: self.row_idx,
            column_idx: self.column_idx,
            next_group_idx: 0,
        };
        let result = f(&mut col);
        self.column_idx += 1;
        result
    }
}

// COLUMN
// ================================================================================================

pub struct DebugTraceColumn<'c> {
    challenges: &'c Challenges<QuadFelt>,
    state: &'c mut DebugTraceState,
    row_idx: usize,
    column_idx: usize,
    next_group_idx: usize,
}

impl<'c> DebugTraceColumn<'c> {
    /// Common path shared by `group` and `group_with_cached_encoding`. Opens a group,
    /// drives the caller's closure, folds the group's `(V_g, U_g)` into the column's
    /// running `(V_col, U_col)`, and (for cached-encoding groups) records any mutex
    /// violation.
    fn open_group<'g>(
        &'g mut self,
        is_cached_encoding: bool,
        f: impl FnOnce(&mut DebugTraceGroup<'g>),
    ) {
        let group_idx = self.next_group_idx;
        let column_idx = self.column_idx;
        let row_idx = self.row_idx;

        let mut group = DebugTraceGroup {
            challenges: self.challenges,
            state: &mut *self.state,
            u: QuadFelt::ONE,
            v: QuadFelt::ZERO,
            row_idx,
            column_idx,
            group_idx,
            check_mutex: is_cached_encoding,
            active_flag_count: 0,
        };
        f(&mut group);

        if group.check_mutex && group.active_flag_count > 1 {
            group.state.mutex_violations.push(MutualExclusionViolation {
                row: row_idx,
                column_idx,
                group_idx,
                active_flags: group.active_flag_count,
            });
        }
        // Fold `(V_g, U_g)` into `(V_col, U_col)`:  (V, U) ← (V·U_g + V_g·U, U·U_g)
        let (v_col, u_col) = group.state.column_folds[column_idx];
        group.state.column_folds[column_idx] = (v_col * group.u + group.v * u_col, u_col * group.u);

        self.next_group_idx += 1;
    }
}

impl<'c> LookupColumn for DebugTraceColumn<'c> {
    type Expr = Felt;
    type ExprEF = QuadFelt;

    type Group<'g>
        = DebugTraceGroup<'g>
    where
        Self: 'g;

    fn group<'g>(
        &'g mut self,
        _name: &'static str,
        f: impl FnOnce(&mut Self::Group<'g>),
        _deg: Deg,
    ) {
        self.open_group(false, f);
    }

    fn group_with_cached_encoding<'g>(
        &'g mut self,
        _name: &'static str,
        canonical: impl FnOnce(&mut Self::Group<'g>),
        _encoded: impl FnOnce(&mut Self::Group<'g>),
        _deg: Deg,
    ) {
        // Run only the canonical closure: both closures must describe the same
        // interaction set by contract (`DebugStructureBuilder` verifies their folds
        // agree on sampled rows), and running both here would double-count balance
        // multiplicities.
        self.open_group(true, canonical);
    }
}

// GROUP
// ================================================================================================

pub struct DebugTraceGroup<'g> {
    challenges: &'g Challenges<QuadFelt>,
    state: &'g mut DebugTraceState,
    u: QuadFelt,
    v: QuadFelt,
    row_idx: usize,
    column_idx: usize,
    group_idx: usize,
    /// `true` for `group_with_cached_encoding` — triggers the mutex check at group close.
    check_mutex: bool,
    active_flag_count: usize,
}

impl<'g> DebugTraceGroup<'g> {
    /// Count active flags for mutex checks. Only meaningful when `check_mutex == true`,
    /// but cheap enough to run unconditionally.
    fn track_mutex(&mut self, flag: Felt) {
        if self.check_mutex && flag != Felt::ZERO {
            self.active_flag_count += 1;
        }
    }

    /// Push one `(multiplicity, denom)` into both the balance map and the push log,
    /// with the group's current `(row, col, group)` source coordinates.
    fn record(&mut self, msg_repr: alloc::string::String, denom: QuadFelt, multiplicity: Felt) {
        *self.state.balances.entry(denom).or_insert(Felt::ZERO) += multiplicity;
        self.state.push_log.push(PushRecord {
            row: self.row_idx,
            column_idx: self.column_idx,
            group_idx: self.group_idx,
            msg_repr,
            denom,
            multiplicity,
        });
    }
}

impl<'g> LookupGroup for DebugTraceGroup<'g> {
    type Expr = Felt;
    type ExprEF = QuadFelt;

    type Batch<'b>
        = DebugTraceBatch<'b>
    where
        Self: 'b;

    fn insert<M>(
        &mut self,
        _name: &'static str,
        flag: Felt,
        multiplicity: Felt,
        msg: impl FnOnce() -> M,
        _deg: Deg,
    ) where
        M: LookupMessage<Felt, QuadFelt>,
    {
        self.track_mutex(flag);
        if flag == Felt::ZERO {
            return;
        }
        let built = msg();
        let v_msg = built.encode(self.challenges);
        self.record(format!("{built:?}"), v_msg, multiplicity);
        self.u += (v_msg - QuadFelt::ONE) * flag;
        self.v += flag * multiplicity;
    }

    fn batch<'b>(
        &'b mut self,
        _name: &'static str,
        flag: Felt,
        build: impl FnOnce(&mut Self::Batch<'b>),
        _deg: Deg,
    ) {
        self.track_mutex(flag);
        let active = flag != Felt::ZERO;
        let (n, d) = {
            let mut batch = DebugTraceBatch {
                challenges: self.challenges,
                state: &mut *self.state,
                active,
                n: QuadFelt::ZERO,
                d: QuadFelt::ONE,
                row_idx: self.row_idx,
                column_idx: self.column_idx,
                group_idx: self.group_idx,
            };
            build(&mut batch);
            (batch.n, batch.d)
        };
        self.u += (d - QuadFelt::ONE) * flag;
        self.v += n * flag;
    }

    fn beta_powers(&self) -> &[QuadFelt] {
        &self.challenges.beta_powers[..]
    }

    fn bus_prefix(&self, bus_id: usize) -> QuadFelt {
        self.challenges.bus_prefix[bus_id]
    }

    fn insert_encoded(
        &mut self,
        _name: &'static str,
        flag: Felt,
        multiplicity: Felt,
        encoded: impl FnOnce() -> QuadFelt,
        _deg: Deg,
    ) {
        self.track_mutex(flag);
        if flag == Felt::ZERO {
            return;
        }
        let v_msg = encoded();
        self.record("<encoded>".to_string(), v_msg, multiplicity);
        self.u += (v_msg - QuadFelt::ONE) * flag;
        self.v += flag * multiplicity;
    }
}

// BATCH
// ================================================================================================

pub struct DebugTraceBatch<'b> {
    challenges: &'b Challenges<QuadFelt>,
    state: &'b mut DebugTraceState,
    /// `false` if the outer group's flag was zero — batch-level short-circuit for balance
    /// accumulation. `(N, D)` still tracks normally so the outer group's `(V_g, U_g)` fold
    /// stays correct.
    active: bool,
    n: QuadFelt,
    d: QuadFelt,
    /// Source coordinates inherited from the enclosing group for push-log records.
    row_idx: usize,
    column_idx: usize,
    group_idx: usize,
}

impl<'b> DebugTraceBatch<'b> {
    fn record(&mut self, msg_repr: alloc::string::String, denom: QuadFelt, multiplicity: Felt) {
        *self.state.balances.entry(denom).or_insert(Felt::ZERO) += multiplicity;
        self.state.push_log.push(PushRecord {
            row: self.row_idx,
            column_idx: self.column_idx,
            group_idx: self.group_idx,
            msg_repr,
            denom,
            multiplicity,
        });
    }
}

impl<'b> LookupBatch for DebugTraceBatch<'b> {
    type Expr = Felt;
    type ExprEF = QuadFelt;

    fn insert<M>(&mut self, _name: &'static str, multiplicity: Felt, msg: M, _deg: Deg)
    where
        M: LookupMessage<Felt, QuadFelt>,
    {
        let v_msg = msg.encode(self.challenges);
        if self.active {
            self.record(format!("{msg:?}"), v_msg, multiplicity);
        }
        let d_prev = self.d;
        self.n = self.n * v_msg + d_prev * multiplicity;
        self.d *= v_msg;
    }

    fn insert_encoded(
        &mut self,
        _name: &'static str,
        multiplicity: Felt,
        encoded: impl FnOnce() -> QuadFelt,
        _deg: Deg,
    ) {
        let v_msg = encoded();
        if self.active {
            self.record("<encoded>".to_string(), v_msg, multiplicity);
        }
        let d_prev = self.d;
        self.n = self.n * v_msg + d_prev * multiplicity;
        self.d *= v_msg;
    }
}

// BOUNDARY EMITTER
// ================================================================================================

/// `BoundaryBuilder` impl that writes once-per-proof emissions into the same
/// [`DebugTraceState`] as the per-row `DebugTraceBuilder`. Emissions are tagged with
/// `row: usize::MAX` and `msg_repr` prefixed `[boundary:<name>]` so they're visible
/// in the report as originating outside the trace.
pub struct DebugBoundaryEmitter<'a> {
    pub(super) challenges: &'a Challenges<QuadFelt>,
    pub(super) state: &'a mut DebugTraceState,
    pub(super) public_values: &'a [Felt],
    pub(super) var_len_public_inputs: &'a [&'a [Felt]],
}

impl<'a> BoundaryBuilder for DebugBoundaryEmitter<'a> {
    type F = Felt;
    type EF = QuadFelt;

    fn public_values(&self) -> &[Felt] {
        self.public_values
    }

    fn var_len_public_inputs(&self) -> &[&[Felt]] {
        self.var_len_public_inputs
    }

    fn insert<M>(&mut self, name: &'static str, multiplicity: Felt, msg: M)
    where
        M: LookupMessage<Felt, QuadFelt>,
    {
        let denom = msg.encode(self.challenges);
        *self.state.balances.entry(denom).or_insert(Felt::ZERO) += multiplicity;
        self.state.push_log.push(PushRecord {
            row: usize::MAX,
            column_idx: usize::MAX,
            group_idx: usize::MAX,
            msg_repr: format!("[boundary:{name}] {msg:?}"),
            denom,
            multiplicity,
        });
    }
}