Skip to main content

vortex_array/test_harness/trace/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Snapshot-friendly tracing harness for the optimizer and executor.
5//!
6//! # What this records
7//!
8//! [`trace_op`] runs a closure with a thread-local recorder installed. While the recorder is
9//! active, calls to the `trace_op!` macro inside the optimizer and executor push
10//! structured events into the recorder. The recorder produces a [`TraceDisplay`] that renders
11//! as a deterministic, hierarchical text trace suitable for `insta` snapshot assertions.
12//!
13//! Events cover:
14//!
15//! - **Optimization**: optimize/recursive-optimize entry, fixpoint loop iterations, applied
16//!   reduce rules, applied parent-reduce rules.
17//! - **Execution**: `execute_until` iterations, single-step entries, parent kernel attempts and
18//!   matches, slot transitions, builder start/append/finish, and the eventual canonical output.
19//!
20//! Despite the name `trace_op`, the harness is *not* a generic logging facility: it is closely
21//! coupled to the optimizer/executor state machines so that the resulting trace is stable enough
22//! to commit as a snapshot.
23//!
24//! # When to use it
25//!
26//! Use [`trace_op`] to write a regression test that asserts on the sequence of optimizer
27//! rewrites or executor steps an array goes through. Typical scenarios:
28//!
29//! - A reduce rule should fire exactly once on a specific input shape.
30//! - A parent kernel should be tried in a specific order and the first match should win.
31//! - The executor should walk into a slot, finish it, and pop back to the parent without
32//!   building a canonical intermediate.
33//! - A chunked array should drive the builder path rather than the stack path.
34//!
35//! Two resolutions are available:
36//!
37//! - [`TraceResolution::ExecutedOnly`] (default) — only events that actually fired (rule
38//!   rewrites that matched, kernels that succeeded, execution steps that ran). Optimizer
39//!   passes that produced no change are elided.
40//! - [`TraceResolution::Attempts`] — also records declined rule attempts, kernels that did
41//!   not match, and per-loop bookkeeping. Use this when ordering or fall-through matters.
42//!
43//! # Cost and scope
44//!
45//! - Capture is thread-local. Worker threads spawned inside `f` do not inherit the recorder.
46//! - Nested captures return an error so that unrelated traces never merge.
47//! - In release builds and CodSpeed benchmark builds, every `trace_op!` invocation is compiled
48//!   away by the macro's `cfg` gating; this module is then unused. See
49//!   `trace_op!` for the gating rules.
50//!
51//! # Example
52//!
53//! ```ignore
54//! use vortex_array::test_harness::trace::trace_op;
55//!
56//! let traced = trace_op(|| filter_array.optimize_ctx(&session))?;
57//! assert!(traced.output.is::<Primitive>());
58//! insta::assert_snapshot!(traced.trace.to_string(), @r"
59//! optimize root=vortex.filter(i32, len=4)
60//!   reduce TrivialFilterRule: vortex.filter(i32, len=4) -> vortex.primitive(i32, len=4)
61//!   done output=vortex.primitive(i32, len=4)
62//! ");
63//! ```
64
65use std::cell::Cell;
66use std::cell::RefCell;
67use std::fmt;
68use std::fmt::Debug;
69use std::fmt::Display;
70use std::sync::atomic::AtomicUsize;
71use std::sync::atomic::Ordering;
72
73use vortex_error::VortexExpect;
74use vortex_error::VortexResult;
75use vortex_error::vortex_err;
76
77use crate::ArrayRef;
78
79/// Controls how much rule and kernel resolution detail is captured.
80#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
81pub enum TraceResolution {
82    /// Record only the operations that actually executed.
83    #[default]
84    ExecutedOnly,
85    /// Also record rule and kernel attempts that matched but declined, or did not match.
86    Attempts,
87}
88
89/// Options for [`trace_op_with`].
90#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
91pub struct TraceOptions {
92    /// The amount of rule and kernel resolution detail to include.
93    pub resolution: TraceResolution,
94}
95
96/// The result of a traced operation.
97#[derive(Clone, Debug)]
98pub struct Traced<T> {
99    /// The value returned by the traced closure.
100    pub output: T,
101    /// A stable, snapshot-friendly rendering of optimizer and execution activity.
102    pub trace: TraceDisplay,
103}
104
105/// A stable, snapshot-friendly trace.
106#[derive(Clone, Debug, Default)]
107pub struct TraceDisplay {
108    options: TraceOptions,
109    events: Vec<TraceEvent>,
110}
111
112impl Display for TraceDisplay {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        let hidden_events = self.hidden_events();
115        let mut optimize_depth = 0usize;
116        let mut wrote_event = false;
117
118        for (idx, event) in self.events.iter().enumerate() {
119            if hidden_events[idx] {
120                continue;
121            }
122
123            if event.closes_before(self.options.resolution) {
124                optimize_depth = optimize_depth.saturating_sub(1);
125            }
126
127            if event.is_hidden(self.options.resolution) {
128                continue;
129            }
130
131            if wrote_event {
132                writeln!(f)?;
133            } else {
134                wrote_event = true;
135            }
136
137            write_indent(
138                f,
139                optimize_depth + event.relative_indent(self.options.resolution, optimize_depth > 0),
140            )?;
141            event.fmt_line(f, self.options.resolution)?;
142
143            if event.opens_after(self.options.resolution) {
144                optimize_depth += 1;
145            }
146            if event.closes_after(self.options.resolution) {
147                optimize_depth = optimize_depth.saturating_sub(1);
148            }
149        }
150        Ok(())
151    }
152}
153
154impl TraceDisplay {
155    fn hidden_events(&self) -> Vec<bool> {
156        let mut hidden = vec![false; self.events.len()];
157        if self.options.resolution != TraceResolution::ExecutedOnly {
158            return hidden;
159        }
160
161        let mut optimize_stack = Vec::new();
162        for (idx, event) in self.events.iter().enumerate() {
163            match event {
164                TraceEvent::OptimizeStart { .. } => optimize_stack.push(idx),
165                TraceEvent::OptimizeDone { changed, .. } => {
166                    let Some(start) = optimize_stack.pop() else {
167                        continue;
168                    };
169                    if !changed {
170                        hidden[start..=idx].fill(true);
171                    }
172                }
173                _ => {}
174            }
175        }
176        hidden
177    }
178}
179
180fn write_indent(f: &mut fmt::Formatter<'_>, depth: usize) -> fmt::Result {
181    for _ in 0..depth {
182        f.write_str("  ")?;
183    }
184    Ok(())
185}
186
187/// Run `f` while capturing a trace of the optimizer and executor work it performs.
188///
189/// `f` typically invokes an operation that drives the executor or optimizer, such as
190/// [`ArrayOptimizer::optimize_ctx`][crate::optimizer::ArrayOptimizer::optimize_ctx] or
191/// [`ArrayRef::execute`][crate::ArrayRef::execute]. While `f` runs,
192/// the optimizer and executor emit structured events via the `trace_op!`
193/// macro into a thread-local recorder. When `f` returns, the recorder is finalized and
194/// returned alongside the closure's output as a [`Traced<T>`].
195///
196/// The default resolution ([`TraceResolution::ExecutedOnly`]) records the rule rewrites,
197/// parent kernels, execution steps, and builder activity that actually executed. Optimizer
198/// passes that produced no change are hidden from the rendered trace. Use [`trace_op_with`]
199/// with [`TraceResolution::Attempts`] when a test needs to assert on declined rule attempts,
200/// kernels that did not match, or other fall-through detail.
201///
202/// # Examples
203///
204/// ```ignore
205/// let traced = trace_op(|| filter_array.optimize_ctx(&session))?;
206/// assert!(traced.output.is::<Primitive>());
207/// insta::assert_snapshot!(traced.trace.to_string(), @r"
208/// optimize root=vortex.filter(i32, len=4)
209///   reduce TrivialFilterRule: vortex.filter(i32, len=4) -> vortex.primitive(i32, len=4)
210///   done output=vortex.primitive(i32, len=4)
211/// ");
212/// ```
213///
214/// # Errors
215///
216/// Returns whatever error `f` produces. Returns an error if a recorder is already active on
217/// the current thread — nested traces are not supported.
218pub fn trace_op<T>(f: impl FnOnce() -> VortexResult<T>) -> VortexResult<Traced<T>> {
219    trace_op_with(TraceOptions::default(), f)
220}
221
222/// Run `f` while capturing a trace using `options`.
223///
224/// See [`trace_op`] for the common case. Use this when you need to override the default
225/// [`TraceResolution`] to capture declined rules and unmatched kernels.
226///
227/// Trace capture is thread-local and intentionally does not propagate to worker threads. Nested
228/// trace captures return an error so tests do not accidentally merge unrelated traces.
229pub fn trace_op_with<T>(
230    options: TraceOptions,
231    f: impl FnOnce() -> VortexResult<T>,
232) -> VortexResult<Traced<T>> {
233    let interest = TraceInterest::from(options.resolution);
234    ACTIVE_TRACE.with(|active| {
235        let mut active = active.borrow_mut();
236        if active.is_some() {
237            return Err(vortex_err!("trace_op captures cannot be nested"));
238        }
239        *active = Some(TraceRecorder::new(options));
240        Ok(())
241    })?;
242    TRACE_INTEREST.with(|trace_interest| trace_interest.set(interest));
243    ACTIVE_TRACE_COUNT.fetch_add(1, Ordering::Relaxed);
244    if interest == TraceInterest::Attempts {
245        ATTEMPTS_TRACE_COUNT.fetch_add(1, Ordering::Relaxed);
246    }
247
248    let guard = ActiveTraceGuard { interest };
249    let output = f();
250    let recorder = ACTIVE_TRACE.with(|active| {
251        active
252            .borrow_mut()
253            .take()
254            .vortex_expect("trace recorder must be installed")
255    });
256    drop(guard);
257
258    output.map(|output| Traced {
259        output,
260        trace: recorder.finish(),
261    })
262}
263
264/// Returns true when the current thread has an active trace recorder.
265#[allow(clippy::inline_always)]
266#[inline(always)]
267pub(crate) fn is_active() -> bool {
268    if ACTIVE_TRACE_COUNT.load(Ordering::Relaxed) == 0 {
269        return false;
270    }
271    TRACE_INTEREST.with(|interest| interest.get().is_active())
272}
273
274#[allow(clippy::inline_always)]
275#[inline(always)]
276fn attempts_enabled() -> bool {
277    if ATTEMPTS_TRACE_COUNT.load(Ordering::Relaxed) == 0 {
278        return false;
279    }
280    TRACE_INTEREST.with(|interest| interest.get() == TraceInterest::Attempts)
281}
282
283#[derive(Clone, Copy, Debug)]
284enum TraceSource {
285    Session(usize),
286}
287
288impl Display for TraceSource {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        match self {
291            TraceSource::Session(idx) => write!(f, "session[{idx}]"),
292        }
293    }
294}
295
296#[derive(Clone, Copy, Debug)]
297enum AttemptOutcome {
298    Declined,
299}
300
301impl Display for AttemptOutcome {
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        match self {
304            AttemptOutcome::Declined => f.write_str("declined"),
305        }
306    }
307}
308
309#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
310enum TraceInterest {
311    #[default]
312    Off,
313    ExecutedOnly,
314    Attempts,
315}
316
317impl TraceInterest {
318    #[inline]
319    fn is_active(self) -> bool {
320        self != Self::Off
321    }
322}
323
324impl From<TraceResolution> for TraceInterest {
325    fn from(resolution: TraceResolution) -> Self {
326        match resolution {
327            TraceResolution::ExecutedOnly => Self::ExecutedOnly,
328            TraceResolution::Attempts => Self::Attempts,
329        }
330    }
331}
332
333/// Snapshot-friendly wrapper around [`ArrayRef`] that renders the encoding, dtype, and length
334/// using the canonical [`Display`] format (`vortex.primitive(i32, len=4)`).
335///
336/// Carries a clone of the [`ArrayRef`] instead of duplicating fields,
337/// so trace events stay small and share the same rendering as every other `{array}` print in
338/// the codebase.
339#[derive(Clone, Debug)]
340pub(crate) struct ArraySummary(ArrayRef);
341
342impl ArraySummary {
343    pub(crate) fn new(array: &ArrayRef) -> Self {
344        Self(array.clone())
345    }
346}
347
348impl Display for ArraySummary {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        Display::fmt(&self.0, f)
351    }
352}
353
354pub(crate) fn record_optimize_start(root: &ArrayRef) {
355    record(TraceEvent::OptimizeStart {
356        root: ArraySummary::new(root),
357    });
358}
359
360pub(crate) fn record_optimize_loop_start(array: &ArrayRef) {
361    if !attempts_enabled() {
362        return;
363    }
364    record(TraceEvent::OptimizeLoopStart {
365        array: ArraySummary::new(array),
366    });
367}
368
369pub(crate) fn record_optimize_loop_end() {
370    if !attempts_enabled() {
371        return;
372    }
373    record(TraceEvent::OptimizeLoopEnd);
374}
375
376pub(crate) fn record_optimize_reduce_none(array: &ArrayRef) {
377    if !attempts_enabled() {
378        return;
379    }
380    record(TraceEvent::PhaseNone {
381        indent: 0,
382        phase: "reduce",
383        subject: "array",
384        array: ArraySummary::new(array),
385    });
386}
387
388pub(crate) fn record_optimize_parent_reduce_none(array: &ArrayRef) {
389    if !attempts_enabled() {
390        return;
391    }
392    record(TraceEvent::PhaseNone {
393        indent: 0,
394        phase: "reduce_parent",
395        subject: "array",
396        array: ArraySummary::new(array),
397    });
398}
399
400pub(crate) fn record_optimize_done(output: &ArrayRef, changed: bool) {
401    record(TraceEvent::OptimizeDone {
402        output: ArraySummary::new(output),
403        changed,
404    });
405}
406
407pub(crate) fn record_reduce_applied(array: &ArrayRef, rule: &dyn Debug, output: &ArrayRef) {
408    record(TraceEvent::ReduceApplied {
409        array: ArraySummary::new(array),
410        rule: compact_label(rule),
411        output: ArraySummary::new(output),
412    });
413}
414
415pub(crate) fn record_reduce_declined(array: &ArrayRef, rule: &dyn Debug) {
416    if !attempts_enabled() {
417        return;
418    }
419    record(TraceEvent::ReduceAttempt {
420        array: ArraySummary::new(array),
421        rule: compact_label(rule),
422        outcome: AttemptOutcome::Declined,
423    });
424}
425
426pub(crate) fn record_session_parent_reduce_applied(
427    parent: &ArrayRef,
428    child: &ArrayRef,
429    slot_idx: usize,
430    plugin_idx: usize,
431    kernel: &dyn Debug,
432    output: &ArrayRef,
433) {
434    record_parent_reduce_applied(
435        parent,
436        child,
437        slot_idx,
438        TraceSource::Session(plugin_idx),
439        compact_label(kernel),
440        output,
441    );
442}
443
444pub(crate) fn record_session_parent_reduce_declined(
445    parent: &ArrayRef,
446    child: &ArrayRef,
447    slot_idx: usize,
448    plugin_idx: usize,
449    kernel: &dyn Debug,
450) {
451    record_parent_reduce_attempt(
452        parent,
453        child,
454        slot_idx,
455        TraceSource::Session(plugin_idx),
456        compact_label(kernel),
457        AttemptOutcome::Declined,
458    );
459}
460
461fn record_parent_reduce_attempt(
462    parent: &ArrayRef,
463    child: &ArrayRef,
464    slot_idx: usize,
465    source: TraceSource,
466    rule: impl Into<String>,
467    outcome: AttemptOutcome,
468) {
469    if !attempts_enabled() {
470        return;
471    }
472    record(TraceEvent::ParentReduceAttempt {
473        parent: ArraySummary::new(parent),
474        child: ArraySummary::new(child),
475        slot_idx,
476        source,
477        rule: rule.into(),
478        outcome,
479    });
480}
481
482fn record_parent_reduce_applied(
483    parent: &ArrayRef,
484    child: &ArrayRef,
485    slot_idx: usize,
486    source: TraceSource,
487    rule: impl Into<String>,
488    output: &ArrayRef,
489) {
490    record(TraceEvent::ParentReduceApplied {
491        parent: ArraySummary::new(parent),
492        child: ArraySummary::new(child),
493        slot_idx,
494        source,
495        rule: rule.into(),
496        output: ArraySummary::new(output),
497    });
498}
499
500pub(crate) fn record_execute_until_start<M>(root: &ArrayRef) {
501    record(TraceEvent::ExecuteUntilStart {
502        target: short_type_name::<M>(),
503        root: ArraySummary::new(root),
504    });
505}
506
507pub(crate) fn record_execute_until_iteration(
508    iteration: usize,
509    current: &ArrayRef,
510    stack_parent: Option<(&ArrayRef, usize)>,
511    builder_active: bool,
512) {
513    record(TraceEvent::ExecuteUntilIteration {
514        iteration,
515        current: ArraySummary::new(current),
516        stack_parent: stack_parent.map(|(array, slot_idx)| (ArraySummary::new(array), slot_idx)),
517        builder_active,
518    });
519}
520
521pub(crate) fn record_execute_until_done_check(target: bool, canonical: bool) {
522    if !attempts_enabled() {
523        return;
524    }
525    record(TraceEvent::ExecuteUntilDoneCheck { target, canonical });
526}
527
528pub(crate) fn record_execute_until_return(output: &ArrayRef) {
529    record(TraceEvent::ExecuteUntilReturn {
530        output: ArraySummary::new(output),
531    });
532}
533
534pub(crate) fn record_execute_until_pop_frame(slot_idx: usize, output: &ArrayRef) {
535    record(TraceEvent::ExecuteUntilPopFrame {
536        slot_idx,
537        output: ArraySummary::new(output),
538    });
539}
540
541pub(crate) fn record_session_execute_parent_applied(
542    phase: &'static str,
543    parent: &ArrayRef,
544    child: &ArrayRef,
545    slot_idx: usize,
546    plugin_idx: usize,
547    output: &ArrayRef,
548) {
549    record_execute_parent_applied(
550        phase,
551        parent,
552        child,
553        slot_idx,
554        TraceSource::Session(plugin_idx),
555        "execute_parent_fn",
556        output,
557    );
558}
559
560pub(crate) fn record_session_execute_parent_declined(
561    phase: &'static str,
562    parent: &ArrayRef,
563    child: &ArrayRef,
564    slot_idx: usize,
565    plugin_idx: usize,
566) {
567    record_execute_parent_attempt(
568        phase,
569        parent,
570        child,
571        slot_idx,
572        TraceSource::Session(plugin_idx),
573        "execute_parent_fn",
574        AttemptOutcome::Declined,
575    );
576}
577
578fn record_execute_parent_attempt(
579    phase: &'static str,
580    parent: &ArrayRef,
581    child: &ArrayRef,
582    slot_idx: usize,
583    source: TraceSource,
584    kernel: impl Into<String>,
585    outcome: AttemptOutcome,
586) {
587    if !attempts_enabled() {
588        return;
589    }
590    record(TraceEvent::ExecuteParentAttempt {
591        phase,
592        parent: ArraySummary::new(parent),
593        child: ArraySummary::new(child),
594        slot_idx,
595        source,
596        kernel: kernel.into(),
597        outcome,
598    });
599}
600
601fn record_execute_parent_applied(
602    phase: &'static str,
603    parent: &ArrayRef,
604    child: &ArrayRef,
605    slot_idx: usize,
606    source: TraceSource,
607    kernel: impl Into<String>,
608    output: &ArrayRef,
609) {
610    record(TraceEvent::ExecuteParentApplied {
611        phase,
612        parent: ArraySummary::new(parent),
613        child: ArraySummary::new(child),
614        slot_idx,
615        source,
616        kernel: kernel.into(),
617        output: ArraySummary::new(output),
618    });
619}
620
621pub(crate) fn record_execute_parent_none(phase: &'static str, current: &ArrayRef) {
622    if !attempts_enabled() {
623        return;
624    }
625    record(TraceEvent::PhaseNone {
626        indent: 2,
627        phase,
628        subject: "current",
629        array: ArraySummary::new(current),
630    });
631}
632
633pub(crate) fn record_execute_optimized(input: &ArrayRef, output: &ArrayRef) {
634    let changed = !ArrayRef::ptr_eq(input, output);
635    if !changed && !attempts_enabled() {
636        return;
637    }
638    record(TraceEvent::ExecuteOptimized {
639        input: ArraySummary::new(input),
640        output: ArraySummary::new(output),
641        changed,
642    });
643}
644
645pub(crate) fn record_execute_encoding(array: &ArrayRef) {
646    if !attempts_enabled() {
647        return;
648    }
649    record(TraceEvent::ExecuteEncoding {
650        array: ArraySummary::new(array),
651    });
652}
653
654pub(crate) fn record_execute_slot(slot_idx: usize, parent: &ArrayRef, child: &ArrayRef) {
655    record(TraceEvent::SlotTransition {
656        step: "ExecuteSlot",
657        slot_idx,
658        parent: ArraySummary::new(parent),
659        child: ArraySummary::new(child),
660    });
661}
662
663pub(crate) fn record_builder_start(array: &ArrayRef) {
664    record(TraceEvent::BuilderEvent {
665        action: "start",
666        subject: "array",
667        array: ArraySummary::new(array),
668    });
669}
670
671pub(crate) fn record_append_child(slot_idx: usize, parent: &ArrayRef, child: &ArrayRef) {
672    record(TraceEvent::SlotTransition {
673        step: "AppendChild",
674        slot_idx,
675        parent: ArraySummary::new(parent),
676        child: ArraySummary::new(child),
677    });
678}
679
680pub(crate) fn record_builder_append(child: &ArrayRef) {
681    record(TraceEvent::BuilderEvent {
682        action: "append",
683        subject: "child",
684        array: ArraySummary::new(child),
685    });
686}
687
688pub(crate) fn record_execute_done(array: &ArrayRef) {
689    record(TraceEvent::ExecuteDone {
690        array: ArraySummary::new(array),
691    });
692}
693
694pub(crate) fn record_builder_finish(output: &ArrayRef) {
695    record(TraceEvent::BuilderEvent {
696        action: "finish",
697        subject: "output",
698        array: ArraySummary::new(output),
699    });
700}
701
702pub(crate) fn record_single_step_start(array: &ArrayRef) {
703    record(TraceEvent::SingleStepStart {
704        array: ArraySummary::new(array),
705    });
706}
707
708pub(crate) fn record_single_step_phase_none(phase: &'static str, array: &ArrayRef) {
709    if !attempts_enabled() {
710        return;
711    }
712    record(TraceEvent::PhaseNone {
713        indent: 1,
714        phase,
715        subject: "array",
716        array: ArraySummary::new(array),
717    });
718}
719
720pub(crate) fn record_single_step_applied(phase: &'static str, input: &ArrayRef, output: &ArrayRef) {
721    record(TraceEvent::SingleStepApplied {
722        phase,
723        input: ArraySummary::new(input),
724        output: ArraySummary::new(output),
725    });
726}
727
728fn record(event: TraceEvent) {
729    ACTIVE_TRACE.with(|active| {
730        if let Some(recorder) = active.borrow_mut().as_mut() {
731            recorder.events.push(event);
732        }
733    });
734}
735
736fn compact_label(value: &dyn Debug) -> String {
737    let label = format!("{value:?}");
738    if let Some(label) = adapter_field(&label, "rule") {
739        return label.to_string();
740    }
741    if let Some(label) = adapter_field(&label, "kernel") {
742        return label.to_string();
743    }
744    label
745}
746
747fn adapter_field<'a>(label: &'a str, field: &str) -> Option<&'a str> {
748    let marker = format!("{field}: ");
749    let start = label.find(&marker)? + marker.len();
750    let rest = &label[start..];
751    let end = rest.rfind(" }")?;
752    Some(&rest[..end])
753}
754
755fn short_type_name<T>() -> String {
756    std::any::type_name::<T>()
757        .rsplit("::")
758        .next()
759        .vortex_expect("type names are never empty")
760        .to_string()
761}
762
763thread_local! {
764    static TRACE_INTEREST: Cell<TraceInterest> = const { Cell::new(TraceInterest::Off) };
765    static ACTIVE_TRACE: RefCell<Option<TraceRecorder>> = const { RefCell::new(None) };
766}
767
768static ACTIVE_TRACE_COUNT: AtomicUsize = AtomicUsize::new(0);
769static ATTEMPTS_TRACE_COUNT: AtomicUsize = AtomicUsize::new(0);
770
771struct ActiveTraceGuard {
772    interest: TraceInterest,
773}
774
775impl Drop for ActiveTraceGuard {
776    fn drop(&mut self) {
777        if self.interest == TraceInterest::Attempts {
778            ATTEMPTS_TRACE_COUNT.fetch_sub(1, Ordering::Relaxed);
779        }
780        ACTIVE_TRACE_COUNT.fetch_sub(1, Ordering::Relaxed);
781        TRACE_INTEREST.with(|interest| interest.set(TraceInterest::Off));
782        ACTIVE_TRACE.with(|active| {
783            active.borrow_mut().take();
784        });
785    }
786}
787
788#[derive(Debug)]
789struct TraceRecorder {
790    options: TraceOptions,
791    events: Vec<TraceEvent>,
792}
793
794impl TraceRecorder {
795    fn new(options: TraceOptions) -> Self {
796        Self {
797            options,
798            events: Vec::new(),
799        }
800    }
801
802    fn finish(self) -> TraceDisplay {
803        TraceDisplay {
804            options: self.options,
805            events: self.events,
806        }
807    }
808}
809
810#[derive(Clone, Debug)]
811enum TraceEvent {
812    OptimizeStart {
813        root: ArraySummary,
814    },
815    OptimizeLoopStart {
816        array: ArraySummary,
817    },
818    OptimizeLoopEnd,
819    OptimizeDone {
820        output: ArraySummary,
821        changed: bool,
822    },
823    ReduceAttempt {
824        array: ArraySummary,
825        rule: String,
826        outcome: AttemptOutcome,
827    },
828    ReduceApplied {
829        array: ArraySummary,
830        rule: String,
831        output: ArraySummary,
832    },
833    ParentReduceAttempt {
834        parent: ArraySummary,
835        child: ArraySummary,
836        slot_idx: usize,
837        source: TraceSource,
838        rule: String,
839        outcome: AttemptOutcome,
840    },
841    ParentReduceApplied {
842        parent: ArraySummary,
843        child: ArraySummary,
844        slot_idx: usize,
845        source: TraceSource,
846        rule: String,
847        output: ArraySummary,
848    },
849    ExecuteUntilStart {
850        target: String,
851        root: ArraySummary,
852    },
853    ExecuteUntilIteration {
854        iteration: usize,
855        current: ArraySummary,
856        stack_parent: Option<(ArraySummary, usize)>,
857        builder_active: bool,
858    },
859    ExecuteUntilDoneCheck {
860        target: bool,
861        canonical: bool,
862    },
863    ExecuteUntilReturn {
864        output: ArraySummary,
865    },
866    ExecuteUntilPopFrame {
867        slot_idx: usize,
868        output: ArraySummary,
869    },
870    ExecuteParentAttempt {
871        phase: &'static str,
872        parent: ArraySummary,
873        child: ArraySummary,
874        slot_idx: usize,
875        source: TraceSource,
876        kernel: String,
877        outcome: AttemptOutcome,
878    },
879    ExecuteParentApplied {
880        phase: &'static str,
881        parent: ArraySummary,
882        child: ArraySummary,
883        slot_idx: usize,
884        source: TraceSource,
885        kernel: String,
886        output: ArraySummary,
887    },
888    PhaseNone {
889        indent: usize,
890        phase: &'static str,
891        subject: &'static str,
892        array: ArraySummary,
893    },
894    ExecuteOptimized {
895        input: ArraySummary,
896        output: ArraySummary,
897        changed: bool,
898    },
899    ExecuteEncoding {
900        array: ArraySummary,
901    },
902    SlotTransition {
903        step: &'static str,
904        slot_idx: usize,
905        parent: ArraySummary,
906        child: ArraySummary,
907    },
908    BuilderEvent {
909        action: &'static str,
910        subject: &'static str,
911        array: ArraySummary,
912    },
913    ExecuteDone {
914        array: ArraySummary,
915    },
916    SingleStepStart {
917        array: ArraySummary,
918    },
919    SingleStepApplied {
920        phase: &'static str,
921        input: ArraySummary,
922        output: ArraySummary,
923    },
924}
925
926impl TraceEvent {
927    fn is_hidden(&self, resolution: TraceResolution) -> bool {
928        match resolution {
929            TraceResolution::Attempts => matches!(self, TraceEvent::OptimizeLoopEnd),
930            TraceResolution::ExecutedOnly => matches!(
931                self,
932                TraceEvent::OptimizeLoopStart { .. }
933                    | TraceEvent::OptimizeLoopEnd
934                    | TraceEvent::PhaseNone { .. }
935                    | TraceEvent::ExecuteUntilDoneCheck { .. }
936                    | TraceEvent::ExecuteEncoding { .. }
937                    | TraceEvent::ExecuteOptimized { changed: false, .. }
938                    | TraceEvent::ExecuteParentAttempt { .. }
939                    | TraceEvent::ReduceAttempt { .. }
940                    | TraceEvent::ParentReduceAttempt { .. }
941            ),
942        }
943    }
944
945    fn opens_after(&self, resolution: TraceResolution) -> bool {
946        match resolution {
947            TraceResolution::Attempts => matches!(
948                self,
949                TraceEvent::OptimizeStart { .. } | TraceEvent::OptimizeLoopStart { .. }
950            ),
951            TraceResolution::ExecutedOnly => matches!(self, TraceEvent::OptimizeStart { .. }),
952        }
953    }
954
955    fn closes_before(&self, resolution: TraceResolution) -> bool {
956        match resolution {
957            TraceResolution::Attempts => matches!(self, TraceEvent::OptimizeLoopEnd),
958            TraceResolution::ExecutedOnly => false,
959        }
960    }
961
962    fn closes_after(&self, _resolution: TraceResolution) -> bool {
963        matches!(self, TraceEvent::OptimizeDone { .. })
964    }
965
966    fn relative_indent(&self, _resolution: TraceResolution, in_optimize_scope: bool) -> usize {
967        match self {
968            TraceEvent::OptimizeStart { .. }
969            | TraceEvent::OptimizeLoopStart { .. }
970            | TraceEvent::OptimizeDone { .. } => 0,
971            TraceEvent::ReduceAttempt { .. }
972            | TraceEvent::ReduceApplied { .. }
973            | TraceEvent::ParentReduceAttempt { .. }
974            | TraceEvent::ParentReduceApplied { .. }
975                if in_optimize_scope =>
976            {
977                0
978            }
979            TraceEvent::PhaseNone { indent, .. } => *indent,
980            TraceEvent::ReduceAttempt { .. }
981            | TraceEvent::ReduceApplied { .. }
982            | TraceEvent::ParentReduceAttempt { .. }
983            | TraceEvent::ParentReduceApplied { .. }
984            | TraceEvent::ExecuteUntilDoneCheck { .. }
985            | TraceEvent::ExecuteUntilPopFrame { .. }
986            | TraceEvent::ExecuteParentAttempt { .. }
987            | TraceEvent::ExecuteParentApplied { .. }
988            | TraceEvent::ExecuteOptimized { .. }
989            | TraceEvent::ExecuteEncoding { .. }
990            | TraceEvent::SlotTransition { .. }
991            | TraceEvent::BuilderEvent { .. }
992            | TraceEvent::ExecuteDone { .. } => 2,
993            TraceEvent::ExecuteUntilIteration { .. }
994            | TraceEvent::ExecuteUntilReturn { .. }
995            | TraceEvent::SingleStepApplied { .. } => 1,
996            TraceEvent::OptimizeLoopEnd
997            | TraceEvent::ExecuteUntilStart { .. }
998            | TraceEvent::SingleStepStart { .. } => 0,
999        }
1000    }
1001
1002    fn fmt_line(&self, f: &mut fmt::Formatter<'_>, resolution: TraceResolution) -> fmt::Result {
1003        match self {
1004            TraceEvent::OptimizeStart { root } => {
1005                write!(f, "optimize root={root}")
1006            }
1007            TraceEvent::OptimizeLoopStart { array } => {
1008                write!(f, "loop input={array}")
1009            }
1010            TraceEvent::OptimizeLoopEnd => Ok(()),
1011            TraceEvent::OptimizeDone { output, changed } => match resolution {
1012                TraceResolution::Attempts => write!(f, "done output={output} changed={changed}"),
1013                TraceResolution::ExecutedOnly => write!(f, "done output={output}"),
1014            },
1015            TraceEvent::ReduceAttempt {
1016                array,
1017                rule,
1018                outcome,
1019            } => write!(
1020                f,
1021                "reduce attempt array={array} source=static rule={rule} outcome={outcome}"
1022            ),
1023            TraceEvent::ReduceApplied {
1024                array,
1025                rule,
1026                output,
1027            } => match resolution {
1028                TraceResolution::Attempts => write!(
1029                    f,
1030                    "reduce applied array={array} source=static rule={rule} output={output}"
1031                ),
1032                TraceResolution::ExecutedOnly => {
1033                    write!(f, "reduce {rule}: {array} -> {output}")
1034                }
1035            },
1036            TraceEvent::ParentReduceAttempt {
1037                parent,
1038                child,
1039                slot_idx,
1040                source,
1041                rule,
1042                outcome,
1043            } => write!(
1044                f,
1045                "reduce_parent attempt slot={slot_idx} parent={parent} child={child} source={source} rule={rule} outcome={outcome}"
1046            ),
1047            TraceEvent::ParentReduceApplied {
1048                parent,
1049                child,
1050                slot_idx,
1051                source,
1052                rule,
1053                output,
1054            } => match resolution {
1055                TraceResolution::Attempts => write!(
1056                    f,
1057                    "reduce_parent applied slot={slot_idx} parent={parent} child={child} source={source} rule={rule} output={output}"
1058                ),
1059                TraceResolution::ExecutedOnly => write!(
1060                    f,
1061                    "reduce_parent {source}:{rule} slot={slot_idx} parent={parent} child={child} -> {output}"
1062                ),
1063            },
1064            TraceEvent::ExecuteUntilStart { target, root } => {
1065                write!(f, "execute_until target={target} root={root}")
1066            }
1067            TraceEvent::ExecuteUntilIteration {
1068                iteration,
1069                current,
1070                stack_parent,
1071                builder_active,
1072            } => {
1073                write!(f, "iter {iteration} current={current}")?;
1074                if let Some((parent, slot_idx)) = stack_parent {
1075                    write!(f, " stack_parent={parent} slot={slot_idx}")?;
1076                }
1077                write!(f, " builder_active={builder_active}")
1078            }
1079            TraceEvent::ExecuteUntilDoneCheck { target, canonical } => {
1080                write!(f, "done_check target={target} canonical={canonical}")
1081            }
1082            TraceEvent::ExecuteUntilReturn { output } => {
1083                write!(f, "return output={output}")
1084            }
1085            TraceEvent::ExecuteUntilPopFrame { slot_idx, output } => {
1086                write!(f, "pop_frame slot={slot_idx} output={output}")
1087            }
1088            TraceEvent::ExecuteParentAttempt {
1089                phase,
1090                parent,
1091                child,
1092                slot_idx,
1093                source,
1094                kernel,
1095                outcome,
1096            } => write!(
1097                f,
1098                "{phase} attempt slot={slot_idx} parent={parent} child={child} source={source} kernel={kernel} outcome={outcome}"
1099            ),
1100            TraceEvent::ExecuteParentApplied {
1101                phase,
1102                parent,
1103                child,
1104                slot_idx,
1105                source,
1106                kernel,
1107                output,
1108            } => match resolution {
1109                TraceResolution::Attempts => write!(
1110                    f,
1111                    "{phase} applied slot={slot_idx} parent={parent} child={child} source={source} kernel={kernel} output={output}"
1112                ),
1113                TraceResolution::ExecutedOnly => write!(
1114                    f,
1115                    "{phase} {source}:{kernel} slot={slot_idx} parent={parent} child={child} -> {output}"
1116                ),
1117            },
1118            TraceEvent::PhaseNone {
1119                phase,
1120                subject,
1121                array,
1122                ..
1123            } => {
1124                write!(f, "{phase} none {subject}={array}")
1125            }
1126            TraceEvent::ExecuteOptimized {
1127                input,
1128                output,
1129                changed,
1130            } => match resolution {
1131                TraceResolution::Attempts => write!(
1132                    f,
1133                    "optimize input={input} output={output} changed={changed}"
1134                ),
1135                TraceResolution::ExecutedOnly => write!(f, "optimize {input} -> {output}"),
1136            },
1137            TraceEvent::ExecuteEncoding { array } => {
1138                write!(f, "execute encoding={array}")
1139            }
1140            TraceEvent::SlotTransition {
1141                step,
1142                slot_idx,
1143                parent,
1144                child,
1145            } => write!(f, "{step} slot={slot_idx} parent={parent} child={child}"),
1146            TraceEvent::ExecuteDone { array } => {
1147                write!(f, "Done array={array}")
1148            }
1149            TraceEvent::BuilderEvent {
1150                action,
1151                subject,
1152                array,
1153            } => {
1154                write!(f, "builder {action} {subject}={array}")
1155            }
1156            TraceEvent::SingleStepStart { array } => {
1157                write!(f, "execute_step input={array}")
1158            }
1159            TraceEvent::SingleStepApplied {
1160                phase,
1161                input,
1162                output,
1163            } => match resolution {
1164                TraceResolution::Attempts => {
1165                    write!(f, "{phase} applied input={input} output={output}")
1166                }
1167                TraceResolution::ExecutedOnly => write!(f, "{phase} {input} -> {output}"),
1168            },
1169        }
1170    }
1171}
1172
1173#[cfg(test)]
1174mod tests;