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
228impl QueryTrace {
229 /// Execute `f` with path tracing active on the current thread, returning
230 /// the result and the captured trace. Recording calls inside `f` (and
231 /// anything `f` calls on this thread) fill the returned trace.
232 ///
233 /// Nesting is supported: an inner `capture` pushes a fresh trace onto the
234 /// stack and gets its own result; the outer trace is unaffected by inner
235 /// recordings.
236 ///
237 /// When no capture is active (the normal hot path), [`QueryTrace::record`]
238 /// is a single TLS load + empty-check + return — zero allocation, zero
239 /// locking, no measurable cost.
240 pub fn capture<F, T>(f: F) -> (T, QueryTrace)
241 where
242 F: FnOnce() -> T,
243 {
244 Self::push_scope();
245 let result = f();
246 let trace = Self::pop_scope();
247 (result, trace)
248 }
249
250 /// Push a fresh trace onto the thread-local stack, starting a capture scope.
251 /// Pair with [`Self::pop_scope`] to retrieve the trace. This is the async-
252 /// compatible alternative to [`Self::capture`]: push before `await`, pop
253 /// after.
254 ///
255 /// **Thread affinity:** the trace is thread-local, so recordings must happen
256 /// on the same OS thread as the push/pop pair. This holds for synchronous
257 /// query paths (the common case) and for single-partition DataFusion scans
258 /// (physical planning + leaf execution run inline on the polling thread).
259 pub fn push_scope() {
260 STACK.with(|s| s.borrow_mut().push(QueryTrace::default()));
261 }
262
263 /// Pop the innermost trace from the thread-local stack, ending a capture
264 /// scope. Returns the captured trace. Panics if the stack is empty (unpaired
265 /// pop); see [`Self::push_scope`].
266 pub fn pop_scope() -> QueryTrace {
267 STACK.with(|s| s.borrow_mut().pop()).unwrap_or_default()
268 }
269
270 /// Whether path tracing is active on this thread (at least one
271 /// [`QueryTrace::capture`] scope is open).
272 #[inline]
273 pub fn capturing() -> bool {
274 STACK.with(|s| !s.borrow().is_empty())
275 }
276
277 /// Record into the innermost active trace via `f`. **No-op when not
278 /// capturing** — the hot path pays only the TLS load to check the stack.
279 ///
280 /// This is the primary recording primitive: call it at every decision point
281 /// (path selection, index rebuild, fast-path hit/miss). It is cheap enough
282 /// to call once per query entry point without measurable overhead.
283 #[inline]
284 pub fn record<F>(f: F)
285 where
286 F: FnOnce(&mut QueryTrace),
287 {
288 STACK.with(|s| {
289 if let Some(trace) = s.borrow_mut().last_mut() {
290 f(trace);
291 }
292 });
293 }
294
295 /// Returns `true` when this trace took a "good" (non-materializing) path:
296 /// a cursor, a pushdown, a shadow, or a count shortcut — and did **not**
297 /// rebuild indexes or materialize rows. Useful as a quick sanity check in
298 /// path-sensitive tests.
299 pub fn is_fast(&self) -> bool {
300 !matches!(self.scan_mode, ScanMode::Materialized | ScanMode::Unknown)
301 && self.index_rebuild != IndexRebuild::Rebuilt
302 && !self.row_materialized
303 }
304}
305
306impl fmt::Display for QueryTrace {
307 /// Compact one-line summary for benchmark output and ad-hoc inspection:
308 /// `native-pushdown pushed=2 survivors=12500 runs=1 idx=complete fast-rid`.
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310 write!(f, "{}", self.scan_mode)?;
311 if self.run_count > 0 {
312 write!(f, " runs={}", self.run_count)?;
313 }
314 if self.conditions_pushed > 0 {
315 write!(f, " pushed={}", self.conditions_pushed)?;
316 }
317 if self.conditions_residual > 0 {
318 write!(f, " residual={}", self.conditions_residual)?;
319 }
320 if let Some(n) = self.survivor_count {
321 write!(f, " survivors={}", n)?;
322 }
323 let idx = match self.index_rebuild {
324 IndexRebuild::None => "",
325 IndexRebuild::AlreadyComplete => " idx=complete",
326 IndexRebuild::Rebuilt => " idx=REBUILT",
327 };
328 f.write_str(idx)?;
329 if self.result_cache_hit {
330 f.write_str(" cache=hit")?;
331 }
332 if self.learned_range_used {
333 f.write_str(" learned-range")?;
334 }
335 if self.fast_row_id_map {
336 f.write_str(" fast-rid")?;
337 }
338 if self.row_materialized {
339 f.write_str(" row-mat")?;
340 }
341 if self.overlay_rows > 0 {
342 write!(f, " overlay={}", self.overlay_rows)?;
343 }
344 if self.pages_decoded > 0 {
345 write!(f, " pages={}", self.pages_decoded)?;
346 }
347 if self.pages_skipped > 0 {
348 write!(f, " skipped={}", self.pages_skipped)?;
349 }
350 Ok(())
351 }
352}
353
354// ---------------------------------------------------------------------------
355// Test assertion helpers — fluent methods for path-sensitive performance tests.
356// Available in integration tests and downstream test suites (not gated behind
357// #[cfg(test)] so they work from external test crates).
358// ---------------------------------------------------------------------------
359
360impl QueryTrace {
361 /// Assert the scan mode equals `expected`. Returns `&self` for chaining.
362 pub fn assert_mode(&self, expected: ScanMode) -> &Self {
363 assert_eq!(
364 self.scan_mode, expected,
365 "expected scan mode {expected:?} but got {:?} ({self})",
366 self.scan_mode
367 );
368 self
369 }
370
371 /// Assert no index rebuild happened during this query (Priority 10 guard).
372 pub fn assert_no_index_rebuild(&self) -> &Self {
373 assert_ne!(
374 self.index_rebuild,
375 IndexRebuild::Rebuilt,
376 "expected no index rebuild but indexes were rebuilt ({self})"
377 );
378 self
379 }
380
381 /// Assert the query did not materialize `Row { HashMap }` objects.
382 pub fn assert_not_materialized(&self) -> &Self {
383 assert!(
384 !self.row_materialized,
385 "expected columnar/cursor path but rows were materialized ({self})"
386 );
387 self
388 }
389
390 /// Assert the result cache returned a hit.
391 pub fn assert_cache_hit(&self) -> &Self {
392 assert!(
393 self.result_cache_hit,
394 "expected result cache hit but got miss ({self})"
395 );
396 self
397 }
398
399 /// Assert the fast clean-run row-id→position arithmetic was used.
400 pub fn assert_fast_row_id_map(&self) -> &Self {
401 assert!(
402 self.fast_row_id_map,
403 "expected fast row-id map but got fallback ({self})"
404 );
405 self
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 #[test]
414 fn capture_collects_records() {
415 // Recording outside a capture is a no-op (no panic).
416 QueryTrace::record(|t| {
417 t.run_count = 999;
418 });
419 assert!(!QueryTrace::capturing());
420
421 let (result, trace) = QueryTrace::capture(|| {
422 assert!(QueryTrace::capturing());
423 QueryTrace::record(|t| {
424 t.run_count = 3;
425 t.scan_mode = ScanMode::NativePushdown;
426 });
427 42
428 });
429 assert_eq!(result, 42);
430 assert_eq!(trace.run_count, 3);
431 assert_eq!(trace.scan_mode, ScanMode::NativePushdown);
432 assert!(!QueryTrace::capturing());
433 }
434
435 #[test]
436 fn nested_captures_are_independent() {
437 let (outer, outer_trace) = QueryTrace::capture(|| {
438 QueryTrace::record(|t| t.run_count = 1);
439 let (inner, inner_trace) = QueryTrace::capture(|| {
440 QueryTrace::record(|t| t.run_count = 99);
441 "inner"
442 });
443 assert_eq!(inner, "inner");
444 // The inner capture's records must NOT bleed into the outer trace.
445 assert_eq!(inner_trace.run_count, 99);
446 // But subsequent outer records still hit the outer trace.
447 QueryTrace::record(|t| t.conditions_pushed = 2);
448 "outer"
449 });
450 assert_eq!(outer, "outer");
451 assert_eq!(outer_trace.run_count, 1);
452 assert_eq!(outer_trace.conditions_pushed, 2);
453 }
454
455 #[test]
456 fn display_summary_is_compact() {
457 let t = QueryTrace {
458 scan_mode: ScanMode::NativePushdown,
459 run_count: 1,
460 conditions_pushed: 2,
461 survivor_count: Some(12500),
462 index_rebuild: IndexRebuild::AlreadyComplete,
463 fast_row_id_map: true,
464 ..Default::default()
465 };
466 let s = format!("{t}");
467 assert!(s.contains("native-pushdown"));
468 assert!(s.contains("runs=1"));
469 assert!(s.contains("pushed=2"));
470 assert!(s.contains("survivors=12500"));
471 assert!(s.contains("idx=complete"));
472 assert!(s.contains("fast-rid"));
473 }
474
475 #[test]
476 fn is_fast_distinguishes_paths() {
477 let good = QueryTrace {
478 scan_mode: ScanMode::NativePageCursor,
479 index_rebuild: IndexRebuild::AlreadyComplete,
480 ..Default::default()
481 };
482 assert!(good.is_fast());
483
484 let mut bad = good.clone();
485 bad.index_rebuild = IndexRebuild::Rebuilt;
486 assert!(!bad.is_fast());
487
488 let mut mat = good.clone();
489 mat.scan_mode = ScanMode::Materialized;
490 assert!(!mat.is_fast());
491 }
492
493 #[test]
494 fn assertion_helpers_chain() {
495 let t = QueryTrace {
496 scan_mode: ScanMode::ArrowShadow,
497 index_rebuild: IndexRebuild::AlreadyComplete,
498 ..Default::default()
499 };
500 t.assert_mode(ScanMode::ArrowShadow)
501 .assert_no_index_rebuild()
502 .assert_not_materialized();
503 }
504}