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}
82
83impl fmt::Display for ScanMode {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 let s = match self {
86 ScanMode::Unknown => "unknown",
87 ScanMode::CountMetadata => "count-metadata",
88 ScanMode::CountSurvivors => "count-survivors",
89 ScanMode::ArrowShadow => "arrow-shadow",
90 ScanMode::NativePageCursor => "native-page-cursor",
91 ScanMode::MultiRunCursor => "multi-run-cursor",
92 ScanMode::NativePushdown => "native-pushdown",
93 ScanMode::Materialized => "materialized",
94 };
95 f.write_str(s)
96 }
97}
98
99/// Which join execution path served a query (Priority 13: join diagnostics).
100/// `None` for non-join queries.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
102pub enum JoinMode {
103 /// No join in the query (or the join path was never reached).
104 #[default]
105 None,
106 /// Native FK↔PK roaring-bitmap intersection — no hash-join materialization
107 /// ([`crate::engine::Table`] index resolve only).
108 FkBitmap,
109 /// Fell back to DataFusion's hash join (shape the native path can't serve).
110 DataFusionHash,
111}
112
113impl fmt::Display for JoinMode {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.write_str(match self {
116 JoinMode::None => "none",
117 JoinMode::FkBitmap => "fk-bitmap",
118 JoinMode::DataFusionHash => "datafusion-hash",
119 })
120 }
121}
122
123/// Whether `ensure_indexes_complete` rebuilt indexes during this query. A
124/// rebuild is the user-facing stall case (Priority 10); this field exposes it.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
126pub enum IndexRebuild {
127 /// No index rebuild happened (no query ran, or the table had no indexes).
128 #[default]
129 None,
130 /// Indexes were already complete; `ensure_indexes_complete` was a no-op.
131 AlreadyComplete,
132 /// Indexes were rebuilt from runs during this query (the stall case).
133 Rebuilt,
134}
135
136/// Records which engine path a query took. Filled at decision points via
137/// [`QueryTrace::record`]; collected via [`QueryTrace::capture`].
138///
139/// All fields are `#[derive(Default)]`, so adding a new field is non-breaking.
140/// Fields default to zero / `false` / `None` so a trace from an uninstrumented
141/// path still reads cleanly.
142#[derive(Debug, Default, Clone)]
143pub struct QueryTrace {
144 /// The physical scan path that served this query.
145 pub scan_mode: ScanMode,
146 /// Number of sorted runs in the table at query time. `1` = single-run fast
147 /// path eligible; `>1` = k-way merge; `0` = empty/memtable-only table.
148 pub run_count: usize,
149 /// Rows in the memtable overlay (unflushed puts/updates/deletes).
150 pub memtable_rows: usize,
151 /// Rows in the mutable-run tier overlay.
152 pub mutable_run_rows: usize,
153 /// Rows in the materialized overlay batch yielded by a cursor (memtable +
154 /// mutable-run combined, post-filter). Non-zero means the query paid
155 /// overlay materialization cost.
156 pub overlay_rows: usize,
157 /// How many conditions were translated to native pushdown (index-served).
158 pub conditions_pushed: usize,
159 /// How many conditions could not be pushed down (residual / fallback).
160 pub conditions_residual: usize,
161 /// Survivor row count after predicate resolution, if known without decoding
162 /// data columns (set for index-served and count paths).
163 pub survivor_count: Option<usize>,
164 /// Whether `ensure_indexes_complete` rebuilt indexes during this query.
165 pub index_rebuild: IndexRebuild,
166 /// Whether the fast clean-run row-id→position arithmetic was used (avoids
167 /// decoding + binary-searching the system row-id column).
168 pub fast_row_id_map: bool,
169 /// Whether a learned (PGM) range index served a `Range`/`RangeF64`
170 /// condition (in-memory, no column read).
171 pub learned_range_used: bool,
172 /// Whether the result cache returned a hit (no re-decode / re-resolve).
173 pub result_cache_hit: bool,
174 /// Whether rows were materialized as `Row { HashMap }` (the slow path).
175 pub row_materialized: bool,
176 /// Number of pages decoded (lazily filled by cursors when capturing).
177 pub pages_decoded: usize,
178 /// Number of pages skipped by page-stat pruning or empty page plans.
179 pub pages_skipped: usize,
180 /// Which join path served the query (Priority 13). `None` for non-joins.
181 pub join_mode: JoinMode,
182 /// Logical-planning time in nanoseconds (Priority 8: parse + plan, separate
183 /// from execution). `0` on a result-cache hit (planning was skipped) or when
184 /// the plan came from the logical-plan cache.
185 pub planning_nanos: u64,
186}
187
188impl QueryTrace {
189 /// Execute `f` with path tracing active on the current thread, returning
190 /// the result and the captured trace. Recording calls inside `f` (and
191 /// anything `f` calls on this thread) fill the returned trace.
192 ///
193 /// Nesting is supported: an inner `capture` pushes a fresh trace onto the
194 /// stack and gets its own result; the outer trace is unaffected by inner
195 /// recordings.
196 ///
197 /// When no capture is active (the normal hot path), [`QueryTrace::record`]
198 /// is a single TLS load + empty-check + return — zero allocation, zero
199 /// locking, no measurable cost.
200 pub fn capture<F, T>(f: F) -> (T, QueryTrace)
201 where
202 F: FnOnce() -> T,
203 {
204 Self::push_scope();
205 let result = f();
206 let trace = Self::pop_scope();
207 (result, trace)
208 }
209
210 /// Push a fresh trace onto the thread-local stack, starting a capture scope.
211 /// Pair with [`Self::pop_scope`] to retrieve the trace. This is the async-
212 /// compatible alternative to [`Self::capture`]: push before `await`, pop
213 /// after.
214 ///
215 /// **Thread affinity:** the trace is thread-local, so recordings must happen
216 /// on the same OS thread as the push/pop pair. This holds for synchronous
217 /// query paths (the common case) and for single-partition DataFusion scans
218 /// (physical planning + leaf execution run inline on the polling thread).
219 pub fn push_scope() {
220 STACK.with(|s| s.borrow_mut().push(QueryTrace::default()));
221 }
222
223 /// Pop the innermost trace from the thread-local stack, ending a capture
224 /// scope. Returns the captured trace. Panics if the stack is empty (unpaired
225 /// pop); see [`Self::push_scope`].
226 pub fn pop_scope() -> QueryTrace {
227 STACK.with(|s| s.borrow_mut().pop()).unwrap_or_default()
228 }
229
230 /// Whether path tracing is active on this thread (at least one
231 /// [`QueryTrace::capture`] scope is open).
232 #[inline]
233 pub fn capturing() -> bool {
234 STACK.with(|s| !s.borrow().is_empty())
235 }
236
237 /// Record into the innermost active trace via `f`. **No-op when not
238 /// capturing** — the hot path pays only the TLS load to check the stack.
239 ///
240 /// This is the primary recording primitive: call it at every decision point
241 /// (path selection, index rebuild, fast-path hit/miss). It is cheap enough
242 /// to call once per query entry point without measurable overhead.
243 #[inline]
244 pub fn record<F>(f: F)
245 where
246 F: FnOnce(&mut QueryTrace),
247 {
248 STACK.with(|s| {
249 if let Some(trace) = s.borrow_mut().last_mut() {
250 f(trace);
251 }
252 });
253 }
254
255 /// Returns `true` when this trace took a "good" (non-materializing) path:
256 /// a cursor, a pushdown, a shadow, or a count shortcut — and did **not**
257 /// rebuild indexes or materialize rows. Useful as a quick sanity check in
258 /// path-sensitive tests.
259 pub fn is_fast(&self) -> bool {
260 !matches!(self.scan_mode, ScanMode::Materialized | ScanMode::Unknown)
261 && self.index_rebuild != IndexRebuild::Rebuilt
262 && !self.row_materialized
263 }
264}
265
266impl fmt::Display for QueryTrace {
267 /// Compact one-line summary for benchmark output and ad-hoc inspection:
268 /// `native-pushdown pushed=2 survivors=12500 runs=1 idx=complete fast-rid`.
269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 write!(f, "{}", self.scan_mode)?;
271 if self.run_count > 0 {
272 write!(f, " runs={}", self.run_count)?;
273 }
274 if self.conditions_pushed > 0 {
275 write!(f, " pushed={}", self.conditions_pushed)?;
276 }
277 if self.conditions_residual > 0 {
278 write!(f, " residual={}", self.conditions_residual)?;
279 }
280 if let Some(n) = self.survivor_count {
281 write!(f, " survivors={}", n)?;
282 }
283 let idx = match self.index_rebuild {
284 IndexRebuild::None => "",
285 IndexRebuild::AlreadyComplete => " idx=complete",
286 IndexRebuild::Rebuilt => " idx=REBUILT",
287 };
288 f.write_str(idx)?;
289 if self.result_cache_hit {
290 f.write_str(" cache=hit")?;
291 }
292 if self.learned_range_used {
293 f.write_str(" learned-range")?;
294 }
295 if self.fast_row_id_map {
296 f.write_str(" fast-rid")?;
297 }
298 if self.row_materialized {
299 f.write_str(" row-mat")?;
300 }
301 if self.overlay_rows > 0 {
302 write!(f, " overlay={}", self.overlay_rows)?;
303 }
304 if self.pages_decoded > 0 {
305 write!(f, " pages={}", self.pages_decoded)?;
306 }
307 if self.pages_skipped > 0 {
308 write!(f, " skipped={}", self.pages_skipped)?;
309 }
310 Ok(())
311 }
312}
313
314// ---------------------------------------------------------------------------
315// Test assertion helpers — fluent methods for path-sensitive performance tests.
316// Available in integration tests and downstream test suites (not gated behind
317// #[cfg(test)] so they work from external test crates).
318// ---------------------------------------------------------------------------
319
320impl QueryTrace {
321 /// Assert the scan mode equals `expected`. Returns `&self` for chaining.
322 pub fn assert_mode(&self, expected: ScanMode) -> &Self {
323 assert_eq!(
324 self.scan_mode, expected,
325 "expected scan mode {expected:?} but got {:?} ({self})",
326 self.scan_mode
327 );
328 self
329 }
330
331 /// Assert no index rebuild happened during this query (Priority 10 guard).
332 pub fn assert_no_index_rebuild(&self) -> &Self {
333 assert_ne!(
334 self.index_rebuild,
335 IndexRebuild::Rebuilt,
336 "expected no index rebuild but indexes were rebuilt ({self})"
337 );
338 self
339 }
340
341 /// Assert the query did not materialize `Row { HashMap }` objects.
342 pub fn assert_not_materialized(&self) -> &Self {
343 assert!(
344 !self.row_materialized,
345 "expected columnar/cursor path but rows were materialized ({self})"
346 );
347 self
348 }
349
350 /// Assert the result cache returned a hit.
351 pub fn assert_cache_hit(&self) -> &Self {
352 assert!(
353 self.result_cache_hit,
354 "expected result cache hit but got miss ({self})"
355 );
356 self
357 }
358
359 /// Assert the fast clean-run row-id→position arithmetic was used.
360 pub fn assert_fast_row_id_map(&self) -> &Self {
361 assert!(
362 self.fast_row_id_map,
363 "expected fast row-id map but got fallback ({self})"
364 );
365 self
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[test]
374 fn capture_collects_records() {
375 // Recording outside a capture is a no-op (no panic).
376 QueryTrace::record(|t| {
377 t.run_count = 999;
378 });
379 assert!(!QueryTrace::capturing());
380
381 let (result, trace) = QueryTrace::capture(|| {
382 assert!(QueryTrace::capturing());
383 QueryTrace::record(|t| {
384 t.run_count = 3;
385 t.scan_mode = ScanMode::NativePushdown;
386 });
387 42
388 });
389 assert_eq!(result, 42);
390 assert_eq!(trace.run_count, 3);
391 assert_eq!(trace.scan_mode, ScanMode::NativePushdown);
392 assert!(!QueryTrace::capturing());
393 }
394
395 #[test]
396 fn nested_captures_are_independent() {
397 let (outer, outer_trace) = QueryTrace::capture(|| {
398 QueryTrace::record(|t| t.run_count = 1);
399 let (inner, inner_trace) = QueryTrace::capture(|| {
400 QueryTrace::record(|t| t.run_count = 99);
401 "inner"
402 });
403 assert_eq!(inner, "inner");
404 // The inner capture's records must NOT bleed into the outer trace.
405 assert_eq!(inner_trace.run_count, 99);
406 // But subsequent outer records still hit the outer trace.
407 QueryTrace::record(|t| t.conditions_pushed = 2);
408 "outer"
409 });
410 assert_eq!(outer, "outer");
411 assert_eq!(outer_trace.run_count, 1);
412 assert_eq!(outer_trace.conditions_pushed, 2);
413 }
414
415 #[test]
416 fn display_summary_is_compact() {
417 let t = QueryTrace {
418 scan_mode: ScanMode::NativePushdown,
419 run_count: 1,
420 conditions_pushed: 2,
421 survivor_count: Some(12500),
422 index_rebuild: IndexRebuild::AlreadyComplete,
423 fast_row_id_map: true,
424 ..Default::default()
425 };
426 let s = format!("{t}");
427 assert!(s.contains("native-pushdown"));
428 assert!(s.contains("runs=1"));
429 assert!(s.contains("pushed=2"));
430 assert!(s.contains("survivors=12500"));
431 assert!(s.contains("idx=complete"));
432 assert!(s.contains("fast-rid"));
433 }
434
435 #[test]
436 fn is_fast_distinguishes_paths() {
437 let good = QueryTrace {
438 scan_mode: ScanMode::NativePageCursor,
439 index_rebuild: IndexRebuild::AlreadyComplete,
440 ..Default::default()
441 };
442 assert!(good.is_fast());
443
444 let mut bad = good.clone();
445 bad.index_rebuild = IndexRebuild::Rebuilt;
446 assert!(!bad.is_fast());
447
448 let mut mat = good.clone();
449 mat.scan_mode = ScanMode::Materialized;
450 assert!(!mat.is_fast());
451 }
452
453 #[test]
454 fn assertion_helpers_chain() {
455 let t = QueryTrace {
456 scan_mode: ScanMode::ArrowShadow,
457 index_rebuild: IndexRebuild::AlreadyComplete,
458 ..Default::default()
459 };
460 t.assert_mode(ScanMode::ArrowShadow)
461 .assert_no_index_rebuild()
462 .assert_not_materialized();
463 }
464}