Skip to main content

mongreldb_core/
trace.rs

1//! Query path instrumentation (OPTIMIZATIONS.md Priority 0 / 16).
2//!
3//! MongrelDB has many physical paths a query can take: an O(1) metadata count,
4//! a zero-copy Arrow IPC shadow, a single-run lazy page cursor, a multi-run
5//! k-way merge cursor, an index-pushdown columnar gather, or a full row
6//! materialization. Correctness tests verify *results* but never reveal *which*
7//! path ran, so performance regressions are currently invisible until a
8//! benchmark accidentally trips one.
9//!
10//! [`QueryTrace`] makes those path decisions observable. It is a lightweight,
11//! opt-in record filled at decision points via a thread-local scope collector.
12//! The hot path (no capture active) pays only a single TLS load per record site
13//! and then returns immediately — there is no allocation, no lock, and no
14//! signature change to the hundreds of internal functions that serve queries.
15//!
16//! ## Usage
17//!
18//! The public `_traced` methods on [`crate::engine::Table`] (and
19//! `MongrelSession::run_sql_traced` in the query crate) wrap the corresponding
20//! query in [`QueryTrace::capture`] and return the result alongside the trace:
21//!
22//! ```no_run
23//! # use mongreldb_core::*;
24//! # let mut db: Table = unimplemented!();
25//! # let snap = db.snapshot();
26//! # let conditions = &[];
27//! # let proj = &[];
28//! let (cols, trace) = db.query_columns_native_traced(conditions, Some(proj), snap).unwrap();
29//! assert_eq!(trace.scan_mode, trace::ScanMode::NativePushdown);
30//! assert_eq!(trace.index_rebuild, trace::IndexRebuild::AlreadyComplete);
31//! ```
32//!
33//! ## Extensibility
34//!
35//! New fields can be added to [`QueryTrace`] freely — it is `#[derive(Default)]`,
36//! so existing callers and tests continue to compile. New recording sites are a
37//! single [`QueryTrace::record`] call at the decision point; no plumbing is
38//! required because the thread-local stack is the transport.
39
40use std::cell::RefCell;
41use std::fmt;
42
43thread_local! {
44    /// A stack of in-progress traces, supporting nested captures (an inner
45    /// `capture` gets its own fresh trace; the outer trace is unaffected).
46    static STACK: RefCell<Vec<QueryTrace>> = const { RefCell::new(Vec::new()) };
47}
48
49/// Which physical scan path served a query. Recorded by the SQL scan
50/// ([`crate::scan`]) and the native query entry points. Used in benchmarks and
51/// path-sensitive tests to assert that the expected path was taken.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53pub enum ScanMode {
54    /// The trace was never filled (no recording site ran). Indicates a path
55    /// that has not yet been instrumented.
56    #[default]
57    Unknown,
58    /// `COUNT(*)` / empty projection answered from the maintained `live_count`
59    /// metadata in O(1) — no run read, no index resolve.
60    CountMetadata,
61    /// `COUNT(*)` with a pushed `WHERE` answered from survivor set cardinality
62    /// via [`crate::engine::Table::count_conditions`] — index resolve only, no
63    /// column decode.
64    CountSurvivors,
65    /// Zero-copy Arrow IPC shadow read — no per-column decode at all (clean
66    /// single-run unfiltered table).
67    ArrowShadow,
68    /// Single-run lazy page cursor: fused predicate + page skip + late
69    /// materialization ([`crate::cursor::NativePageCursor`]).
70    NativePageCursor,
71    /// Multi-run k-way merge cursor ([`crate::cursor::MultiRunCursor`]).
72    MultiRunCursor,
73    /// Index pushdown fast path: survivors resolved then gathered column-wise
74    /// from a single reader ([`crate::engine::Table::query_columns_native`]
75    /// fast path — no cursor streaming, but no row materialization either).
76    NativePushdown,
77    /// Full materialization fallback: `visible_columns_native` or
78    /// `rows_for_rids` — rows go through the `Row { HashMap }` shape. This is
79    /// the path optimizations try to avoid.
80    Materialized,
81    /// §5.3 direct SQL dispatch: a simple single-table `SELECT` recognized from
82    /// the raw SQL (sqlparser AST) and served straight from the native column
83    /// cursor, bypassing DataFusion parse+plan+optimize entirely.
84    DirectDispatch,
85    /// DataFusion scan served by an external table module / virtual table
86    /// provider rather than a native MongrelDB storage table.
87    ExternalModule,
88}
89
90impl fmt::Display for ScanMode {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        let s = match self {
93            ScanMode::Unknown => "unknown",
94            ScanMode::CountMetadata => "count-metadata",
95            ScanMode::CountSurvivors => "count-survivors",
96            ScanMode::ArrowShadow => "arrow-shadow",
97            ScanMode::NativePageCursor => "native-page-cursor",
98            ScanMode::MultiRunCursor => "multi-run-cursor",
99            ScanMode::NativePushdown => "native-pushdown",
100            ScanMode::Materialized => "materialized",
101            ScanMode::DirectDispatch => "direct-dispatch",
102            ScanMode::ExternalModule => "external-module",
103        };
104        f.write_str(s)
105    }
106}
107
108/// Which join execution path served a query (Priority 13: join diagnostics).
109/// `None` for non-join queries.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
111pub enum JoinMode {
112    /// No join in the query (or the join path was never reached).
113    #[default]
114    None,
115    /// Native FK↔PK roaring-bitmap intersection — no hash-join materialization
116    /// ([`crate::engine::Table`] index resolve only).
117    FkBitmap,
118    /// Fell back to DataFusion's hash join (shape the native path can't serve).
119    DataFusionHash,
120}
121
122impl fmt::Display for JoinMode {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.write_str(match self {
125            JoinMode::None => "none",
126            JoinMode::FkBitmap => "fk-bitmap",
127            JoinMode::DataFusionHash => "datafusion-hash",
128        })
129    }
130}
131
132/// Whether `ensure_indexes_complete` rebuilt indexes during this query. A
133/// rebuild is the user-facing stall case (Priority 10); this field exposes it.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
135pub enum IndexRebuild {
136    /// No index rebuild happened (no query ran, or the table had no indexes).
137    #[default]
138    None,
139    /// Indexes were already complete; `ensure_indexes_complete` was a no-op.
140    AlreadyComplete,
141    /// Indexes were rebuilt from runs during this query (the stall case).
142    Rebuilt,
143}
144
145/// Records which engine path a query took. Filled at decision points via
146/// [`QueryTrace::record`]; collected via [`QueryTrace::capture`].
147///
148/// All fields are `#[derive(Default)]`, so adding a new field is non-breaking.
149/// Fields default to zero / `false` / `None` so a trace from an uninstrumented
150/// path still reads cleanly.
151#[derive(Debug, Default, Clone)]
152pub struct QueryTrace {
153    /// The physical scan path that served this query.
154    pub scan_mode: ScanMode,
155    /// Number of sorted runs in the table at query time. `1` = single-run fast
156    /// path eligible; `>1` = k-way merge; `0` = empty/memtable-only table.
157    pub run_count: usize,
158    /// Rows in the memtable overlay (unflushed puts/updates/deletes).
159    pub memtable_rows: usize,
160    /// Rows in the mutable-run tier overlay.
161    pub mutable_run_rows: usize,
162    /// Rows in the materialized overlay batch yielded by a cursor (memtable +
163    /// mutable-run combined, post-filter). Non-zero means the query paid
164    /// overlay materialization cost.
165    pub overlay_rows: usize,
166    /// How many conditions were translated to native pushdown (index-served).
167    pub conditions_pushed: usize,
168    /// How many conditions could not be pushed down (residual / fallback).
169    pub conditions_residual: usize,
170    /// Survivor row count after predicate resolution, if known without decoding
171    /// data columns (set for index-served and count paths).
172    pub survivor_count: Option<usize>,
173    /// Whether `ensure_indexes_complete` rebuilt indexes during this query.
174    pub index_rebuild: IndexRebuild,
175    /// Whether the fast clean-run row-id→position arithmetic was used (avoids
176    /// decoding + binary-searching the system row-id column).
177    pub fast_row_id_map: bool,
178    /// Whether a learned (PGM) range index served a `Range`/`RangeF64`
179    /// condition (in-memory, no column read).
180    pub learned_range_used: bool,
181    /// Whether the result cache returned a hit (no re-decode / re-resolve).
182    pub result_cache_hit: bool,
183    /// Whether rows were materialized as `Row { HashMap }` (the slow path).
184    pub row_materialized: bool,
185    /// Number of pages decoded (lazily filled by cursors when capturing).
186    pub pages_decoded: usize,
187    /// Number of pages skipped by page-stat pruning or empty page plans.
188    pub pages_skipped: usize,
189    /// Which join path served the query (Priority 13). `None` for non-joins.
190    pub join_mode: JoinMode,
191    /// Logical-planning time in nanoseconds (Priority 8: parse + plan, separate
192    /// from execution). `0` on a result-cache hit (planning was skipped) or when
193    /// the plan came from the logical-plan cache.
194    pub planning_nanos: u64,
195    /// Authorization/RLS candidate-cache work for the query.
196    pub authorization_nanos: u64,
197    pub rls_cache_hit: bool,
198    pub rls_rows_evaluated: usize,
199    pub rls_policy_columns_decoded: usize,
200    pub authorization_retries: usize,
201    /// AI retrieval stage timings and bounded cardinalities.
202    pub hard_filter_nanos: u64,
203    /// ANN backend selected by the authoritative index schema.
204    pub ann_algorithm: Option<crate::schema::AnnAlgorithm>,
205    /// ANN representation selected by the authoritative index schema.
206    pub ann_quantization: Option<crate::schema::AnnQuantization>,
207    /// Concrete backend executing the ANN candidate search.
208    pub ann_backend: Option<&'static str>,
209    pub ann_candidate_nanos: u64,
210    pub ann_candidate_cap_hit: bool,
211    pub sparse_candidate_nanos: u64,
212    pub minhash_candidate_nanos: u64,
213    pub candidate_count: usize,
214    pub union_size: usize,
215    pub fusion_nanos: u64,
216    pub exact_vector_gather_nanos: u64,
217    pub exact_vector_score_nanos: u64,
218    pub exact_set_gather_nanos: u64,
219    pub exact_set_parse_nanos: u64,
220    pub exact_set_score_nanos: u64,
221    pub projection_nanos: u64,
222    pub projection_rows: usize,
223    pub projection_cells: usize,
224    pub work_consumed: usize,
225    pub total_nanos: u64,
226
227    // ---- TODO §1: point-lookup directory trace fields --------------------
228    /// Whether the `RunLookupDirectory` was consulted and produced a complete
229    /// candidate set for this get. `false` means the legacy range-scan fallback
230    /// ran (which is acceptable but not optimal).
231    pub directory_complete: bool,
232    /// Number of run locators the directory returned for the queried `RowId`.
233    pub directory_candidates: usize,
234    /// Number of runs rejected by the header-derived `run_row_id_ranges` filter.
235    pub run_range_rejects: usize,
236    /// Number of runs rejected by membership / predicate filters before open.
237    pub membership_filter_rejects: usize,
238    /// How many immutable run readers were actually opened.
239    pub run_readers_opened: usize,
240    /// Set when the lookup short-circuited because the best candidate was
241    /// provably newer than every remaining locator's upper bound.
242    pub early_stop: bool,
243    /// Point cache hits (replay of a recent in-process lookup result).
244    pub point_cache_hits: usize,
245
246    // ---- TODO §3: controlled-scan streaming trace fields ------------------
247    /// Total versions examined across all segments during the scan.
248    pub controlled_scan_versions_examined: usize,
249    /// Rows emitted by the scan (post-filter).
250    pub controlled_scan_rows_emitted: usize,
251    /// Number of times a segment cursor was refilled.
252    pub controlled_scan_source_refills: usize,
253    /// Peak number of buffered rows held by the streaming merge at any moment.
254    pub controlled_scan_peak_source_buffer_rows: usize,
255    /// Peak number of versions seen for any single `RowId` during the scan.
256    pub controlled_scan_peak_same_row_versions: usize,
257    /// Number of `ExecutionControl::checkpoint` calls issued during the scan.
258    pub controlled_scan_checkpoints: usize,
259    /// Wall-clock time to produce the first row, in microseconds.
260    pub controlled_scan_time_to_first_row_us: u64,
261    /// Time from `cancel` to the scan actually observing cancellation, in µs.
262    pub controlled_scan_cancel_latency_us: u64,
263
264    // ---- TODO §5: HOT fallback trace fields ------------------------------
265    /// Whether a HOT lookup was attempted for this query.
266    pub hot_lookup_attempted: bool,
267    /// Whether the HOT lookup was a hit (no fallback).
268    pub hot_lookup_hit: bool,
269    /// Stable reason label when the HOT lookup fell back. `None` on hit.
270    pub hot_fallback_reason: Option<&'static str>,
271    /// Overlay versions examined during the fallback path.
272    pub hot_fallback_overlay_versions: usize,
273    /// Sorted runs considered during the fallback path.
274    pub hot_fallback_runs_considered: usize,
275    /// Sorted run readers actually opened during the fallback path.
276    pub hot_fallback_runs_opened: usize,
277    /// Pages decoded during the fallback path.
278    pub hot_fallback_pages_decoded: usize,
279    /// Rows materialized during the fallback path.
280    pub hot_fallback_rows_materialized: usize,
281    /// Wall-clock time spent on the HOT fast-path lookup, in nanoseconds.
282    pub hot_lookup_nanos: u64,
283    /// Wall-clock time spent on the fallback path, in nanoseconds.
284    pub hot_fallback_nanos: u64,
285
286    // ---- TODO §4: per-family retrieval trace fields ----------------------
287    /// Raw candidates produced by the index backend before dedup.
288    pub raw_candidates: usize,
289    /// Unique candidates after `(RowId)` dedup.
290    pub unique_candidates: usize,
291    /// Duplicate candidates dropped during dedup.
292    pub duplicate_candidates: usize,
293    /// Candidates rejected by `Snapshot::observes_row`.
294    pub visibility_rejected: usize,
295    /// Candidates rejected as tombstones.
296    pub tombstone_rejected: usize,
297    /// Candidates rejected by TTL.
298    pub ttl_rejected: usize,
299    /// Candidates rejected by authorization (RLS / allowed set).
300    pub authorization_rejected: usize,
301    /// Candidates rejected by hard filter.
302    pub hard_filter_rejected: usize,
303    /// Configured candidate cap for the retrieval.
304    pub candidate_cap: usize,
305    /// Whether the candidate cap was hit.
306    pub candidate_cap_hit: bool,
307    /// Final number of hits returned to the caller.
308    pub final_hits: usize,
309}
310
311/// Reasons a HOT (`Hash-Organized Table`) PK lookup may fall back to the slower
312/// overlay + sorted-run path. Stable identifiers; the string literals are the
313/// stable wire/label form (see TODO §5.1).
314#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
315pub enum HotFallbackReason {
316    MissingMapping,
317    StaleRowId,
318    InvisibleAtSnapshot,
319    HistoricalSnapshot,
320    Tombstone,
321    TtlExpired,
322    PrimaryKeyMismatch,
323    IndexIncomplete,
324    CheckpointRejected,
325}
326
327impl HotFallbackReason {
328    pub fn as_str(self) -> &'static str {
329        match self {
330            HotFallbackReason::MissingMapping => "missing_mapping",
331            HotFallbackReason::StaleRowId => "stale_row_id",
332            HotFallbackReason::InvisibleAtSnapshot => "invisible_at_snapshot",
333            HotFallbackReason::HistoricalSnapshot => "historical_snapshot",
334            HotFallbackReason::Tombstone => "tombstone",
335            HotFallbackReason::TtlExpired => "ttl_expired",
336            HotFallbackReason::PrimaryKeyMismatch => "primary_key_mismatch",
337            HotFallbackReason::IndexIncomplete => "index_incomplete",
338            HotFallbackReason::CheckpointRejected => "checkpoint_rejected",
339        }
340    }
341}
342
343impl fmt::Display for HotFallbackReason {
344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345        f.write_str(self.as_str())
346    }
347}
348
349impl QueryTrace {
350    /// Execute `f` with path tracing active on the current thread, returning
351    /// the result and the captured trace. Recording calls inside `f` (and
352    /// anything `f` calls on this thread) fill the returned trace.
353    ///
354    /// Nesting is supported: an inner `capture` pushes a fresh trace onto the
355    /// stack and gets its own result; the outer trace is unaffected by inner
356    /// recordings.
357    ///
358    /// When no capture is active (the normal hot path), [`QueryTrace::record`]
359    /// is a single TLS load + empty-check + return — zero allocation, zero
360    /// locking, no measurable cost.
361    pub fn capture<F, T>(f: F) -> (T, QueryTrace)
362    where
363        F: FnOnce() -> T,
364    {
365        Self::push_scope();
366        let result = f();
367        let trace = Self::pop_scope();
368        (result, trace)
369    }
370
371    /// Push a fresh trace onto the thread-local stack, starting a capture scope.
372    /// Pair with [`Self::pop_scope`] to retrieve the trace. This is the async-
373    /// compatible alternative to [`Self::capture`]: push before `await`, pop
374    /// after.
375    ///
376    /// **Thread affinity:** the trace is thread-local, so recordings must happen
377    /// on the same OS thread as the push/pop pair. This holds for synchronous
378    /// query paths (the common case) and for single-partition DataFusion scans
379    /// (physical planning + leaf execution run inline on the polling thread).
380    pub fn push_scope() {
381        STACK.with(|s| s.borrow_mut().push(QueryTrace::default()));
382    }
383
384    /// Pop the innermost trace from the thread-local stack, ending a capture
385    /// scope. Returns the captured trace. Panics if the stack is empty (unpaired
386    /// pop); see [`Self::push_scope`].
387    pub fn pop_scope() -> QueryTrace {
388        STACK.with(|s| s.borrow_mut().pop()).unwrap_or_default()
389    }
390
391    /// Whether path tracing is active on this thread (at least one
392    /// [`QueryTrace::capture`] scope is open).
393    #[inline]
394    pub fn capturing() -> bool {
395        STACK.with(|s| !s.borrow().is_empty())
396    }
397
398    /// Record into the innermost active trace via `f`. **No-op when not
399    /// capturing** — the hot path pays only the TLS load to check the stack.
400    ///
401    /// This is the primary recording primitive: call it at every decision point
402    /// (path selection, index rebuild, fast-path hit/miss). It is cheap enough
403    /// to call once per query entry point without measurable overhead.
404    #[inline]
405    pub fn record<F>(f: F)
406    where
407        F: FnOnce(&mut QueryTrace),
408    {
409        STACK.with(|s| {
410            if let Some(trace) = s.borrow_mut().last_mut() {
411                f(trace);
412            }
413        });
414    }
415
416    /// Returns `true` when this trace took a "good" (non-materializing) path:
417    /// a cursor, a pushdown, a shadow, or a count shortcut — and did **not**
418    /// rebuild indexes or materialize rows. Useful as a quick sanity check in
419    /// path-sensitive tests.
420    pub fn is_fast(&self) -> bool {
421        !matches!(self.scan_mode, ScanMode::Materialized | ScanMode::Unknown)
422            && self.index_rebuild != IndexRebuild::Rebuilt
423            && !self.row_materialized
424    }
425}
426
427impl fmt::Display for QueryTrace {
428    /// Compact one-line summary for benchmark output and ad-hoc inspection:
429    /// `native-pushdown pushed=2 survivors=12500 runs=1 idx=complete fast-rid`.
430    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431        write!(f, "{}", self.scan_mode)?;
432        if self.run_count > 0 {
433            write!(f, " runs={}", self.run_count)?;
434        }
435        if self.conditions_pushed > 0 {
436            write!(f, " pushed={}", self.conditions_pushed)?;
437        }
438        if self.conditions_residual > 0 {
439            write!(f, " residual={}", self.conditions_residual)?;
440        }
441        if let Some(n) = self.survivor_count {
442            write!(f, " survivors={}", n)?;
443        }
444        let idx = match self.index_rebuild {
445            IndexRebuild::None => "",
446            IndexRebuild::AlreadyComplete => " idx=complete",
447            IndexRebuild::Rebuilt => " idx=REBUILT",
448        };
449        f.write_str(idx)?;
450        if self.result_cache_hit {
451            f.write_str(" cache=hit")?;
452        }
453        if self.learned_range_used {
454            f.write_str(" learned-range")?;
455        }
456        if self.fast_row_id_map {
457            f.write_str(" fast-rid")?;
458        }
459        if self.row_materialized {
460            f.write_str(" row-mat")?;
461        }
462        if self.overlay_rows > 0 {
463            write!(f, " overlay={}", self.overlay_rows)?;
464        }
465        if self.pages_decoded > 0 {
466            write!(f, " pages={}", self.pages_decoded)?;
467        }
468        if self.pages_skipped > 0 {
469            write!(f, " skipped={}", self.pages_skipped)?;
470        }
471        if self.directory_complete {
472            write!(f, " dir=complete candidates={}", self.directory_candidates)?;
473        }
474        if self.run_readers_opened > 0 {
475            write!(f, " run-readers={}", self.run_readers_opened)?;
476        }
477        if self.early_stop {
478            f.write_str(" early-stop")?;
479        }
480        if self.controlled_scan_versions_examined > 0 {
481            write!(
482                f,
483                " controlled=versions={} emitted={}",
484                self.controlled_scan_versions_examined, self.controlled_scan_rows_emitted
485            )?;
486        }
487        if self.hot_lookup_attempted {
488            if self.hot_lookup_hit {
489                f.write_str(" hot=hit")?;
490            } else {
491                write!(
492                    f,
493                    " hot=fallback reason={}",
494                    self.hot_fallback_reason.unwrap_or("unspecified")
495                )?;
496            }
497        }
498        if self.candidate_cap_hit {
499            write!(f, " cap-hit={}", self.final_hits)?;
500        }
501        Ok(())
502    }
503}
504
505// ---------------------------------------------------------------------------
506// Test assertion helpers — fluent methods for path-sensitive performance tests.
507// Available in integration tests and downstream test suites (not gated behind
508// #[cfg(test)] so they work from external test crates).
509// ---------------------------------------------------------------------------
510
511impl QueryTrace {
512    /// Assert the scan mode equals `expected`. Returns `&self` for chaining.
513    pub fn assert_mode(&self, expected: ScanMode) -> &Self {
514        assert_eq!(
515            self.scan_mode, expected,
516            "expected scan mode {expected:?} but got {:?} ({self})",
517            self.scan_mode
518        );
519        self
520    }
521
522    /// Assert no index rebuild happened during this query (Priority 10 guard).
523    pub fn assert_no_index_rebuild(&self) -> &Self {
524        assert_ne!(
525            self.index_rebuild,
526            IndexRebuild::Rebuilt,
527            "expected no index rebuild but indexes were rebuilt ({self})"
528        );
529        self
530    }
531
532    /// Assert the query did not materialize `Row { HashMap }` objects.
533    pub fn assert_not_materialized(&self) -> &Self {
534        assert!(
535            !self.row_materialized,
536            "expected columnar/cursor path but rows were materialized ({self})"
537        );
538        self
539    }
540
541    /// Assert the result cache returned a hit.
542    pub fn assert_cache_hit(&self) -> &Self {
543        assert!(
544            self.result_cache_hit,
545            "expected result cache hit but got miss ({self})"
546        );
547        self
548    }
549
550    /// Assert the fast clean-run row-id→position arithmetic was used.
551    pub fn assert_fast_row_id_map(&self) -> &Self {
552        assert!(
553            self.fast_row_id_map,
554            "expected fast row-id map but got fallback ({self})"
555        );
556        self
557    }
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    #[test]
565    fn capture_collects_records() {
566        // Recording outside a capture is a no-op (no panic).
567        QueryTrace::record(|t| {
568            t.run_count = 999;
569        });
570        assert!(!QueryTrace::capturing());
571
572        let (result, trace) = QueryTrace::capture(|| {
573            assert!(QueryTrace::capturing());
574            QueryTrace::record(|t| {
575                t.run_count = 3;
576                t.scan_mode = ScanMode::NativePushdown;
577            });
578            42
579        });
580        assert_eq!(result, 42);
581        assert_eq!(trace.run_count, 3);
582        assert_eq!(trace.scan_mode, ScanMode::NativePushdown);
583        assert!(!QueryTrace::capturing());
584    }
585
586    #[test]
587    fn nested_captures_are_independent() {
588        let (outer, outer_trace) = QueryTrace::capture(|| {
589            QueryTrace::record(|t| t.run_count = 1);
590            let (inner, inner_trace) = QueryTrace::capture(|| {
591                QueryTrace::record(|t| t.run_count = 99);
592                "inner"
593            });
594            assert_eq!(inner, "inner");
595            // The inner capture's records must NOT bleed into the outer trace.
596            assert_eq!(inner_trace.run_count, 99);
597            // But subsequent outer records still hit the outer trace.
598            QueryTrace::record(|t| t.conditions_pushed = 2);
599            "outer"
600        });
601        assert_eq!(outer, "outer");
602        assert_eq!(outer_trace.run_count, 1);
603        assert_eq!(outer_trace.conditions_pushed, 2);
604    }
605
606    #[test]
607    fn display_summary_is_compact() {
608        let t = QueryTrace {
609            scan_mode: ScanMode::NativePushdown,
610            run_count: 1,
611            conditions_pushed: 2,
612            survivor_count: Some(12500),
613            index_rebuild: IndexRebuild::AlreadyComplete,
614            fast_row_id_map: true,
615            ..Default::default()
616        };
617        let s = format!("{t}");
618        assert!(s.contains("native-pushdown"));
619        assert!(s.contains("runs=1"));
620        assert!(s.contains("pushed=2"));
621        assert!(s.contains("survivors=12500"));
622        assert!(s.contains("idx=complete"));
623        assert!(s.contains("fast-rid"));
624    }
625
626    #[test]
627    fn is_fast_distinguishes_paths() {
628        let good = QueryTrace {
629            scan_mode: ScanMode::NativePageCursor,
630            index_rebuild: IndexRebuild::AlreadyComplete,
631            ..Default::default()
632        };
633        assert!(good.is_fast());
634
635        let mut bad = good.clone();
636        bad.index_rebuild = IndexRebuild::Rebuilt;
637        assert!(!bad.is_fast());
638
639        let mut mat = good.clone();
640        mat.scan_mode = ScanMode::Materialized;
641        assert!(!mat.is_fast());
642    }
643
644    #[test]
645    fn assertion_helpers_chain() {
646        let t = QueryTrace {
647            scan_mode: ScanMode::ArrowShadow,
648            index_rebuild: IndexRebuild::AlreadyComplete,
649            ..Default::default()
650        };
651        t.assert_mode(ScanMode::ArrowShadow)
652            .assert_no_index_rebuild()
653            .assert_not_materialized();
654    }
655}