relate_executor/metrics.rs
1//! The PROFILE metric vocabulary (ADR-0344): the sink the dispatch loop
2//! reports each statement-level clause operator's metrics to, the record it
3//! reports, and the typed facts the record carries (store-read mix, phase
4//! times, walk start, kernel rung, frontier counters). The thread-local
5//! clocks and counters that feed these live beside the phase they count:
6//! the phase clocks and node reads in [`crate::ctx`], the hop,
7//! neighbor-walk, zone-skip and frontier tallies in
8//! [`crate::exec::profiling`].
9
10use crate::frontier_decline::FrontierDeclineReason;
11
12/// Declares a counter struct of same-typed monotonic fields together with
13/// the field-wise delta `since` — a decrease is a broken invariant, so the
14/// subtraction is checked and stays loud in release as in debug, never a
15/// wrapped or clamped value. One field list generates both, so a new
16/// counter can neither miss the delta nor the `since`. A `merge`
17/// declaration additionally generates the field-wise merge
18/// (`AddAssign`), for the counter whose documented semantic is
19/// accumulation across runs. The family is the *monotone* counters;
20/// `exec::profile_tick`'s `ExpressionBytes` stays outside it because its
21/// meter falls when an arm releases memory, so its delta saturates.
22macro_rules! delta_counters {
23 // The accumulating counter: the declaration plus the merge.
24 (merge $($rest:tt)*) => {
25 delta_counters!(@declare [merge] $($rest)*);
26 };
27 // The one parse of the declaration grammar: the struct, its `since`,
28 // and — when declared `merge` — the field-wise merge.
29 (@declare [$($mode:ident)?]
30 $(#[$meta:meta])*
31 pub struct $name:ident: $ty:ty {
32 $($(#[$fmeta:meta])* $field:ident,)+
33 }
34 ) => {
35 $(#[$meta])*
36 pub struct $name {
37 $($(#[$fmeta])* pub $field: $ty,)+
38 }
39
40 impl $name {
41 /// The field-wise delta from `earlier` — the one spelling every
42 /// reader uses. The counters only ever increase, so a decrease
43 /// is a broken invariant: the subtraction is checked, never a
44 /// wrapped or clamped value.
45 pub fn since(self, earlier: $name) -> $name {
46 $name {
47 $(
48 $field: self.$field
49 .checked_sub(earlier.$field)
50 .expect("the counters only ever increase"),
51 )+
52 }
53 }
54 }
55
56 delta_counters!(@maybe_merge $($mode)? $name { $($field,)+ });
57 };
58 // The merge: the per-run accumulation in
59 // `exec::profiling::count_frontier`, the delta's checked spelling.
60 (@maybe_merge merge $name:ident { $($field:ident,)+ }) => {
61 impl std::ops::AddAssign for $name {
62 fn add_assign(&mut self, run: $name) {
63 $(
64 self.$field = self.$field
65 .checked_add(run.$field)
66 .expect("the counters only ever accumulate");
67 )+
68 }
69 }
70 };
71 (@maybe_merge $name:ident { $($field:ident,)+ }) => {};
72 // The plain counter: the declaration only.
73 ($($rest:tt)*) => {
74 delta_counters!(@declare [] $($rest)*);
75 };
76}
77
78/// The statement's PROFILE site (ADR-0344 phase 2): the metrics sink and
79/// the `(stage, part)` position its keys ride — one fact, built by the
80/// statement-level walkers when they call the clause loop, so the sink
81/// never travels without the position it keys.
82#[derive(Clone, Copy)]
83pub(crate) struct PlanMetricsSite<'a> {
84 /// The sink the facade's PROFILE path attached.
85 pub(crate) sink: &'a dyn PlanMetricsSink,
86 /// The NEXT-chain stage (1-based, matching the tree's stage
87 /// numbering): each NEXT stage restarts its part indices at 0, so the
88 /// stage keeps the keys disjoint.
89 pub(crate) stage: usize,
90 /// The part index within the stage.
91 pub(crate) part: usize,
92}
93
94impl<'a> PlanMetricsSite<'a> {
95 /// The one pairing of a sink with the clause loop's `(stage, part)`
96 /// key — the statement-level walkers' single construction, so a sink
97 /// never travels without the position it keys.
98 pub(crate) fn at(sink: &'a dyn PlanMetricsSink, stage: usize, part: usize) -> Self {
99 PlanMetricsSite { sink, stage, part }
100 }
101}
102
103delta_counters! {
104 merge
105 /// The store-read mix a clause's arm performed (LABS-369): the kinds the
106 /// single `Db Hits` total blends. A `Rows=103` operator that spent 300k
107 /// relationship hops and 0 node reads is a different animal from one that
108 /// read 103 nodes — the one-glance diagnosis for the scan-turned-traversal
109 /// family. Merged across one streamed stage's PROFILE windows
110 /// (`profile_chain.rs`): the stage's record is the checked sum over
111 /// its batches, minus the immediate downstream stage's sum.
112 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113 pub struct StoreReads: u64 {
114 /// Relationship hops taken.
115 hops,
116 /// Neighbors the walk traversed (counted at the adjacency walk).
117 neighbor_walks,
118 /// Node-store reads: one per candidate a node match examined (the
119 /// all-nodes scan, the label scan, the index seek).
120 node_reads,
121 }
122}
123
124delta_counters! {
125 merge
126 /// The clause's inclusive phase times (LABS-448): the elapsed time spent
127 /// resolving node candidates (the seek — the store work behind the
128 /// `Nodes` kind) and following relationships (the walk — the store work
129 /// behind the `Rels`/`Degree` kinds); the per-candidate admission checks
130 /// and the arm's binding/cloning stay unattributed. Inclusive of the nesting
131 /// a compound operator performs: a walk that triggers nested seeks counts
132 /// both, like the table's `Total` column. Merged across one streamed
133 /// stage's PROFILE windows (`profile_chain.rs`), the store-read mix's
134 /// shape.
135 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
136 pub struct PhaseTimes: u128 {
137 /// The seek phase's elapsed nanoseconds.
138 seek_ns,
139 /// The walk phase's elapsed nanoseconds.
140 walk_ns,
141 }
142}
143
144/// The re-arrival rule's shared expansion budget across one frontier run
145/// (the ADR-0395 fixed-constant family, like the runner's
146/// `FRONTIER_WALK_BUDGET`): a fixed constant, no ambient knob — the
147/// remedy for legitimate work that needs more is a new ADR. Every
148/// trail-existence search of the run draws from this one pool, so the
149/// rule's total cost is bounded by it however many re-arrivals a run
150/// sees; sized an order under the runner's own edge-visit budget. The
151/// denominator of [`FrontierCounters::budget_fraction`], so it lives
152/// beside the counter it calibrates.
153pub const REARRIVAL_WORK_BUDGET: u64 = 1_000_000;
154
155delta_counters! {
156 merge
157 /// The frontier family's run counters (ADR-0478), one clause's sum over
158 /// its per-seed BFS runs: the edge visits (the work the walk budget
159 /// caps), the completed levels, the accepted endpoints, and the NFA
160 /// rung's own PROFILE facts — the (node, state) cells the runs created,
161 /// the re-arrival work spent, the rule memo's hits and misses, and the
162 /// admission asks by verdict. Zero on every clause the frontier
163 /// declined — `levels > 0` is the engagement marker (a run always
164 /// completes its level 0).
165 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
166 pub struct FrontierCounters: u64 {
167 /// Incident-edge visits across the clause's frontier runs — the
168 /// budget's own work counter.
169 edge_visits,
170 /// BFS levels completed (level 0 included).
171 levels,
172 /// Endpoints the runs accepted, in arrival order.
173 endpoints,
174 /// (node, state) cells the runs created — the pairs that occupied
175 /// the span×states tables, the BFS's own memory shape.
176 cells,
177 /// Re-arrival rule work spent, summed over the runs — the numerator
178 /// of [`Self::budget_fraction`].
179 rearrival_work,
180 /// Rule-memo hits: asks the run's verdict table answered without a
181 /// search.
182 memo_hits,
183 /// Rule-memo misses: asks that ran the bounded search.
184 memo_misses,
185 /// Admission asks the representative-chain proof settled — no
186 /// search.
187 representative_proofs,
188 /// Admission asks the bounded search proved (an in-bounds path
189 /// found).
190 search_proven,
191 /// Admission asks the bounded search disproved within its bounds.
192 search_disproven,
193 /// Admission asks the shared work budget cut — the run-time decline's
194 /// verdict class (ADR-0516).
195 declined_exhausted,
196 }
197}
198
199delta_counters! {
200 merge
201 /// The ExpandInto walk counters of one clause (probes and reversed probes).
202 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
203 pub struct ExpandIntoCounters: u64 {
204 /// Bound-both-ends ExpandInto probe attempts.
205 probes,
206 /// ExpandInto probes that scanned the reversed direction (to_deg < from_deg).
207 reversed,
208 }
209}
210
211delta_counters! {
212 merge
213 /// The vector-similarity scans one clause ran, by the path that served
214 /// each (ADR-0705): the packed matrix, or the `Value` sweep it declined
215 /// to. A clause that searched once reports one nonzero count; a clause
216 /// that searched per input row can report both.
217 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
218 pub struct VectorScanCounters: u64 {
219 /// Scans the packed matrix answered.
220 matrix,
221 /// Scans the `Value` sweep answered (the matrix declined or is off).
222 value_scan,
223 }
224}
225
226impl VectorScanCounters {
227 /// Whether any vector scan ran — the group's one presence rule: the
228 /// wire emits its keys only when it holds, and the thread-local merge
229 /// skips an empty delta by it.
230 pub fn ran(&self) -> bool {
231 self.matrix + self.value_scan > 0
232 }
233}
234
235delta_counters! {
236 merge
237 /// The HashJoin walk counters of one clause.
238 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
239 pub struct HashJoinCounters: u64 {
240 /// Hash-join build table rows.
241 build_rows,
242 /// Hash-join probe stream rows examined.
243 probe_rows,
244 /// Candidates rejected by the semi-masker SIP bitset/set.
245 semi_mask_rejected,
246 }
247}
248
249delta_counters! {
250 merge
251 /// The expression-memo counters of one operator or statement (ADR-0654,
252 /// ADR-0640): the per-memo facts summed over the memos the unit ran,
253 /// read once when each memo finishes — a memo's increments are the
254 /// ones already on its path, so collecting them adds none. Zero on
255 /// every unit that probed no memo.
256 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
257 pub struct MemoCounters: u64 {
258 /// Inputs looked up in a memo table (warm-up inputs are not probes).
259 probes,
260 /// Probes a table answered.
261 hits,
262 /// Answers stored.
263 inserts,
264 /// Answers not stored because the meter or the ceiling refused.
265 refused,
266 /// The tables' allocation when read, bytes — never part of
267 /// `memory_bytes` (ADR-0654 §2).
268 bytes,
269 /// How many memos gave up at their hit-rate review.
270 disabled_count,
271 }
272}
273
274impl MemoCounters {
275 /// The group's six counts in `plan_keys::MEMO_GROUP_KEYS`' order
276 /// (probes, hits, inserts, refused, bytes, disabled count) — the
277 /// values the wire emitter pairs with that one key table.
278 pub fn counters(&self) -> [u64; 6] {
279 [
280 self.probes,
281 self.hits,
282 self.inserts,
283 self.refused,
284 self.bytes,
285 self.disabled_count,
286 ]
287 }
288
289 /// The memo types behind an operator's sums (ADR-0654 §3): every
290 /// operator-level memo is a guarded-state node-label memo (the
291 /// constructor memos report at statement level through
292 /// [`StatementMemoRecord`]), so a probed operator names that one kind.
293 /// The rule lives here, beside the sums it describes — the plan builder
294 /// asks, never decides which memo produced a count.
295 pub fn operator_kinds(&self) -> relate_model::wire::MemoKindsWire {
296 use relate_model::wire::{MemoKindWire, MemoKindsWire};
297 if self.probes > 0 {
298 MemoKindsWire::default().with(MemoKindWire::NodeLabel)
299 } else {
300 MemoKindsWire::default()
301 }
302 }
303}
304
305/// The statement-level memo facts (ADR-0654 §3): the constructor memos
306/// live in the query overlay and serve any expression, so they report once
307/// for the whole statement, attached at the plan root — the counters
308/// summed over them and the memo types that were probed.
309#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
310pub struct StatementMemoRecord {
311 pub counters: MemoCounters,
312 pub kinds: relate_model::wire::MemoKindsWire,
313}
314
315impl FrontierCounters {
316 /// The group's ten counts in `plan_keys::FRONTIER_GROUP_KEYS`' order
317 /// (edges, levels, endpoints, cells, memo hits, memo misses,
318 /// representative proofs, search proven, search disproven, declined
319 /// exhausted) — the values the wire emitter pairs with that one key
320 /// table.
321 pub fn counters(&self) -> [u64; 10] {
322 [
323 self.edge_visits,
324 self.levels,
325 self.endpoints,
326 self.cells,
327 self.memo_hits,
328 self.memo_misses,
329 self.representative_proofs,
330 self.search_proven,
331 self.search_disproven,
332 self.declined_exhausted,
333 ]
334 }
335
336 /// The fraction of one run's re-arrival work budget the clause's
337 /// runs spent: summed [`Self::rearrival_work`] over
338 /// [`REARRIVAL_WORK_BUDGET`] — `1.0` on a run the budget cut
339 /// mid-search (the work guard drains the budget to exactly zero
340 /// before declaring the cut), `0.0` on runs that never asked the
341 /// rule. A multi-seed clause sums every run's spend over the
342 /// one-run budget, so the fraction reads as run-equivalents.
343 pub fn budget_fraction(&self) -> f64 {
344 self.rearrival_work as f64 / REARRIVAL_WORK_BUDGET as f64
345 }
346}
347
348impl StoreReads {
349 /// The kinds' sum — the one `Db Hits` total, derived rather than
350 /// snapshotted a second time.
351 pub fn total(self) -> u64 {
352 self.hops + self.neighbor_walks + self.node_reads
353 }
354}
355
356/// How a `MATCH` walk chose its start element (LABS-369): the fact the
357/// opaque `Expand` hid. A displaced start — a cheap index seek that became
358/// a 135k-relationship backward traversal — is named here instead of
359/// showing up only as a large `Db Hits` total.
360#[derive(Clone, Copy, Debug, PartialEq, Eq)]
361pub struct WalkStart {
362 /// The pattern element index the walk started from.
363 pub element: usize,
364 /// Whether the walk ran the pivot's prefix backwards from it.
365 pub backward: bool,
366 /// Why that start won.
367 pub reason: StartReason,
368}
369
370impl WalkStart {
371 /// The un-optimised default start: the pattern's first element — the
372 /// seed side — walked forward, the `index-0` reason. The one spelling
373 /// every kernel and batch arm that ignores the start ladder records.
374 pub(crate) fn seed_side_forward() -> WalkStart {
375 WalkStart {
376 element: 0,
377 backward: false,
378 reason: StartReason::IndexZero,
379 }
380 }
381}
382
383/// The start-selection reason classes (ADR-0350's bound pivot, ADR-0351's
384/// cheapest-start estimate, the LABS-161 relationship seek, the default).
385#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum StartReason {
387 /// A row-bound element anchored the walk (ADR-0350).
388 BoundPivot,
389 /// The cheapest-start estimate chose the element (ADR-0351).
390 Cheapest,
391 /// A LABS-161 relationship seek anchored the walk.
392 SeekAnchored,
393 /// The pattern's first element: the un-optimised default.
394 IndexZero,
395}
396
397impl StartReason {
398 /// The reason's stable wire name (LABS-369): the vocabulary the plan
399 /// args and the renderers spell, read from its single source
400 /// ([`plan_keys`](relate_model::wire::plan_keys)), as the rung names are.
401 pub fn as_str(self) -> &'static str {
402 match self {
403 StartReason::BoundPivot => relate_model::wire::plan_keys::START_REASON_BOUND_PIVOT,
404 StartReason::Cheapest => relate_model::wire::plan_keys::START_REASON_CHEAPEST,
405 StartReason::SeekAnchored => relate_model::wire::plan_keys::START_REASON_SEEK_ANCHORED,
406 StartReason::IndexZero => relate_model::wire::plan_keys::START_REASON_INDEX_ZERO,
407 }
408 }
409}
410
411/// Which rung served one `MATCH` clause (LABS-1117): the fact EXPLAIN
412/// could not show, because the rungs are runtime choices inside an
413/// operator, not plan nodes. The ladder records it per clause; the
414/// PROFILE record carries it. [`Walker`](Self::Walker) is the per-row
415/// walker, the rung every decline's home — the batch scan/filter chain
416/// is its own fact (`BatchFacts::ran`), never a rung here.
417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
418pub enum KernelRung {
419 /// The unrolled fixed-k chain kernel, `hops` hops (ADR-0473).
420 Chain { hops: usize },
421 /// The frontier-NFA rung over the BFS (ADR-0478).
422 FrontierNfa,
423 /// The per-row walker — every gate's decline.
424 Walker,
425}
426
427impl KernelRung {
428 /// The rung's stable wire name (the `StartReason::as_str` pattern).
429 /// The names live in the wire vocabulary (`KernelRungWire`'s
430 /// constants), so the executor and every surface spell them once; the
431 /// variant↔name mapping is pinned by `relate`'s
432 /// `decline_and_start_reason_names_match_the_wire_tables`.
433 pub fn as_str(self) -> &'static str {
434 match self {
435 KernelRung::Chain { .. } => relate_model::wire::KernelRungWire::CHAIN,
436 KernelRung::FrontierNfa => relate_model::wire::KernelRungWire::FRONTIER_NFA,
437 KernelRung::Walker => relate_model::wire::KernelRungWire::WALKER,
438 }
439 }
440}
441
442/// The batch chain's PROFILE facts for one clause, carried as one value so
443/// the record never holds a loose flag beside its counter.
444#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
445pub struct BatchFacts {
446 /// Whether the clause ran ADR-0468's batch scan/filter/project chain
447 /// over `Chunk` (LABS-359) — the PROFILE-visible fact that a
448 /// scan-shaped `MATCH` interior executed as batch operators. `false`
449 /// is every other clause, and every clause the chain declined.
450 pub ran: bool,
451 /// The batch filter's zone skips (LABS-645): how many conjunct-batch
452 /// evaluations the chunk's derived min/max zone metadata provably
453 /// replaced with the correct empty survivor set. `0` on every clause
454 /// the chain declined and every clause that skipped nothing.
455 pub zone_skips: u64,
456}
457
458/// The `CALL { … } IN TRANSACTIONS` batch facts one `CallSubquery`
459/// operator reports to PROFILE (REL8-2047): the batch counters — how many
460/// batches ran, how many committed, how many rolled back under the `ON
461/// ERROR` policy — and the per-batch maxima: the input batch's retained
462/// row bytes, the installed output's, the scratch the batch created
463/// (entities, adjacency and property state — the redo log excluded, its
464/// bytes are the WAL figure), and the redo log's reserved bytes at commit,
465/// the WAL payload the batch wrote. The counters are arm-local (not global
466/// counter snapshots): the batch loop notes each finished batch into the
467/// shared cell the clause's record reads once its consumer drains the
468/// stream. All-zero on every other clause, and on an unprofiled run.
469#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
470pub struct InTxBatches {
471 /// Batches that started a transaction.
472 pub batches: u64,
473 /// Batches that committed (both arms of the commit: a facade sink's
474 /// durable per-batch commit, and the statement-level boundary a
475 /// nested or explicit-transaction run closes with).
476 pub committed: u64,
477 /// Batches that rolled back — a handled failure under `ON ERROR
478 /// CONTINUE`/`BREAK`, or the failing batch of `ON ERROR FAIL`.
479 pub rolled_back: u64,
480 /// The largest input batch's retained row bytes.
481 pub peak_input_rows_bytes: u64,
482 /// The largest installed output's retained row bytes.
483 pub peak_output_rows_bytes: u64,
484 /// The most scratch bytes one batch created (redo excluded).
485 pub peak_scratch_bytes: u64,
486 /// The most redo-log bytes one batch carried at its commit — the WAL
487 /// payload it wrote.
488 pub peak_wal_bytes: u64,
489}
490
491/// The `CALL { … } IN TRANSACTIONS` arm's PROFILE facts (REL8-2047): the
492/// batch counters and per-batch maxima the batch loop notes as each batch
493/// finishes, in a cell shared between the arm's iterator (the writer) and
494/// the stream's parked record (the reader), so the clause's record —
495/// reported once the consumer drains or stops the stream, after every
496/// batch has run — carries them. One is built only when a PROFILE record
497/// is attached, so an unprofiled run never pays a cell write per batch.
498pub(crate) struct InTxStats {
499 facts: std::cell::Cell<InTxBatches>,
500}
501
502/// How one finished batch ended, as [`InTxStats::note_batch`] reads it —
503/// the counted outcome with the per-batch figures beside it, so a
504/// committed batch cannot note peaks without its WAL payload and a rolled
505/// back one cannot note an installed output it never handed over.
506pub(crate) enum InTxBatchEnd {
507 /// The batch committed: its output was installed and its redo became
508 /// the WAL payload — all four peaks are live.
509 Committed {
510 input_bytes: u64,
511 output_bytes: u64,
512 scratch_bytes: u64,
513 wal_bytes: u64,
514 },
515 /// The batch rolled back: its own rows are gone, so there is no
516 /// output or WAL figure — the input it held and the scratch it created
517 /// before the rollback are the peaks it still reached.
518 RolledBack {
519 input_bytes: u64,
520 scratch_bytes: u64,
521 },
522}
523
524impl InTxStats {
525 pub(crate) fn new() -> Self {
526 Self {
527 facts: std::cell::Cell::new(InTxBatches::default()),
528 }
529 }
530
531 /// Note one finished batch: the outcome counter beside the batch count,
532 /// each figure keeping the running maximum — the one write path the
533 /// batch loop takes per batch.
534 pub(crate) fn note_batch(&self, end: InTxBatchEnd) {
535 let mut facts = self.facts.get();
536 facts.batches += 1;
537 match end {
538 InTxBatchEnd::Committed {
539 input_bytes,
540 output_bytes,
541 scratch_bytes,
542 wal_bytes,
543 } => {
544 facts.committed += 1;
545 facts.peak_input_rows_bytes = facts.peak_input_rows_bytes.max(input_bytes);
546 facts.peak_output_rows_bytes = facts.peak_output_rows_bytes.max(output_bytes);
547 facts.peak_scratch_bytes = facts.peak_scratch_bytes.max(scratch_bytes);
548 facts.peak_wal_bytes = facts.peak_wal_bytes.max(wal_bytes);
549 }
550 InTxBatchEnd::RolledBack {
551 input_bytes,
552 scratch_bytes,
553 } => {
554 facts.rolled_back += 1;
555 facts.peak_input_rows_bytes = facts.peak_input_rows_bytes.max(input_bytes);
556 facts.peak_scratch_bytes = facts.peak_scratch_bytes.max(scratch_bytes);
557 }
558 }
559 self.facts.set(facts);
560 }
561
562 /// The accumulated facts — the clause record's read, once the stream
563 /// reports.
564 pub(crate) fn facts(&self) -> InTxBatches {
565 self.facts.get()
566 }
567}
568
569/// A parked stream's PROFILE record (REL8-2047): the site and clause the
570/// record keys, with the `CALL { … } IN TRANSACTIONS` arm's batch-facts
571/// cell riding inside — one optional value, so a cell without a record,
572/// or a record whose form has no batches, is unrepresentable. Every
573/// non-batched form builds one with [`Self::at`]; the arm's constructor
574/// attaches a cell through [`Self::with_intx`] — the one attaching site
575/// the type's API states, not a field any caller can assign.
576#[derive(Clone)]
577pub(crate) struct ParkedRecord<'a> {
578 /// The statement's PROFILE site — the sink and the `(stage, part)`
579 /// position its keys ride.
580 pub(crate) site: PlanMetricsSite<'a>,
581 /// The clause index the record keys.
582 pub(crate) clause: usize,
583 /// The arm's batch-facts cell, noted by the batch loop as each batch
584 /// finishes; absent on every other parked form. Private: presence is
585 /// decided by the constructor alone.
586 intx: Option<std::rc::Rc<InTxStats>>,
587}
588
589impl<'a> ParkedRecord<'a> {
590 /// The plain record every non-batched form parks — no cell attached.
591 pub(crate) fn at(site: PlanMetricsSite<'a>, clause: usize) -> Self {
592 Self {
593 site,
594 clause,
595 intx: None,
596 }
597 }
598
599 /// Attach the `IN TRANSACTIONS` arm's batch-facts cell — the one
600 /// attaching site (the arm's constructor, which keeps the writer
601 /// handle beside the record it hands the reader); no other form can,
602 /// so the cell's presence states "this record's clause runs batches".
603 pub(crate) fn with_intx(self, stats: std::rc::Rc<InTxStats>) -> Self {
604 Self {
605 intx: Some(stats),
606 ..self
607 }
608 }
609
610 /// The accumulated batch facts for the clause record's stamp — zeroed
611 /// on every record with no cell attached.
612 pub(crate) fn intx_facts(&self) -> InTxBatches {
613 self.intx
614 .as_deref()
615 .map(InTxStats::facts)
616 .unwrap_or_default()
617 }
618}
619
620impl InTxBatches {
621 /// Whether the arm ran any batch — the group's one presence rule: a
622 /// clause that ran none emits no `InTx*` key at all, so its absence is
623 /// the whole "no batches" fact (never a fabricated zero group).
624 pub fn ran(&self) -> bool {
625 self.batches > 0
626 }
627
628 /// The group's seven counts in `plan_keys::IN_TX_GROUP_KEYS`' order
629 /// (batches, committed, rolled back, peak input bytes, peak output
630 /// bytes, peak scratch bytes, peak WAL bytes) — the values the wire
631 /// emitter pairs with that one key table.
632 pub fn counters(&self) -> [u64; 7] {
633 [
634 self.batches,
635 self.committed,
636 self.rolled_back,
637 self.peak_input_rows_bytes,
638 self.peak_output_rows_bytes,
639 self.peak_scratch_bytes,
640 self.peak_wal_bytes,
641 ]
642 }
643}
644
645/// One clause operator's PROFILE metrics, reported to the sink (ADR-0344
646/// phase 2 + the metric-fields phase): the position key `(stage, part,
647/// clause)` — the same walk the plan tree construction uses — beside the
648/// operator's actuals. Bundled so the sink signature stays at one
649/// argument however many metrics a later phase adds.
650pub struct ClauseMetricsRecord {
651 /// The NEXT-chain position (1-based, matching the tree's stage
652 /// numbering): each NEXT stage restarts its part indices at 0, so the
653 /// stage keeps the keys disjoint — without it a chained statement's
654 /// later stage overwrites the earlier stage's entries.
655 pub stage: usize,
656 pub part: usize,
657 pub clause: usize,
658 /// Rows the operator produced.
659 pub rows: u64,
660 /// Row-materialization bytes: the summed logical size
661 /// (`Value::logical_bytes`, ADR-0042, plus each key's string bytes)
662 /// of the rows the operator produced. Stateful operators'
663 /// non-row state (aggregation tables, sort buffers) is a follow-up.
664 pub memory_bytes: u64,
665 /// Expression allocation bytes the clause's arm charged against the
666 /// ADR-0463 statement budget — the delta of the view's expression
667 /// counter across the arm, the same snapshot/delta shape as
668 /// [`ClauseMetricsRecord::reads`]. Zero for a clause that builds no
669 /// containers or strings.
670 pub expression_built_bytes: u64,
671 /// The operator's elapsed time, nanoseconds.
672 pub time_ns: u128,
673 /// The store-read mix (LABS-369) behind the operator's `Db Hits`
674 /// total: hops vs neighbor walks vs node reads.
675 pub reads: StoreReads,
676 /// The clause's inclusive phase times (LABS-448): the seek (candidate
677 /// resolution and checks) and the walk (relationship traversal),
678 /// stamped only while a PROFILE statement's arm runs — a non-PROFILEd
679 /// statement's record carries zeros.
680 pub phases: PhaseTimes,
681 /// How the walk chose its start, when the clause ran a `MATCH` walk
682 /// (LABS-369) — `None` for clauses that walk nothing.
683 pub start: Option<WalkStart>,
684 /// Which rung served the clause's `MATCH` walk (LABS-1117): the
685 /// chain kernel, the hub-star kernel, the frontier-NFA rung, or the
686 /// per-row walker — the operator the clause's `MATCH` ladder (or, for
687 /// a `SEARCH` `MATCH`, its direct walker call) returned. `None`
688 /// exactly when no `MATCH` operator ran: a non-`MATCH` clause; a
689 /// `MATCH` a fold answered (`try_match_folds`, a boolean or walk
690 /// count); a `MATCH` inside a nested evaluation (its own loop); and a
691 /// `MATCH` the ADR-0468 batch chain answered — that operator is
692 /// [`Self::batched`]'s own fact, never a traversal rung.
693 pub kernel: Option<KernelRung>,
694 /// What ADR-0468's batch scan/filter/project chain did for the
695 /// clause: whether it ran and what its filter skipped.
696 pub batch: BatchFacts,
697 /// The frontier family's run counters (ADR-0478): the BFS's edge
698 /// visits, completed levels, and accepted endpoints, summed over the
699 /// clause's per-seed runs. Zero on every clause the frontier's
700 /// compile gates declined (it never ran); a run-time decline
701 /// ([`FrontierDeclineReason::Run`]) keeps them recorded, since the
702 /// rung did run. The plan table's `Details` cell marks the operator
703 /// (`[frontier edges=N levels=L endpoints=P]`) when it ran.
704 pub frontier: FrontierCounters,
705 /// Why the frontier rung did not serve the clause (ADR-0516, extended
706 /// by the plan-time half): the first typed reason, `None` on every
707 /// clause the rung served and on every clause the rung never
708 /// considered (no single quantified pattern, the diagnostic switch's
709 /// `walk` stand-down, a nested evaluation's own arm). A plan-time
710 /// reason ([`FrontierDeclineReason::Plan`]) is a gate that kept the
711 /// clause off the rung — the clause itself ran no frontier (its counters
712 /// stay zero unless a nested EXISTS frontier run in the same clause
713 /// contributed); a run-time reason
714 /// ([`FrontierDeclineReason::Run`]) is the re-arrival budget's
715 /// exhaustion or the table ceiling's crossing, the counters recorded
716 /// beside it.
717 pub frontier_decline: Option<FrontierDeclineReason>,
718 /// The expression-memo counters of the guarded-state memos the clause's
719 /// stage ran (ADR-0654 §3), summed, with `disabled_count` in place of a
720 /// per-memo flag. Zero on every clause that probed no memo; stamped
721 /// only while a PROFILE statement's arm runs.
722 pub memo: MemoCounters,
723 /// The `CALL { … } IN TRANSACTIONS` batch facts (REL8-2047) — the one
724 /// clause kind that runs batches. Zeroed by the shared record
725 /// constructor; the arm's shared cell stamps its accumulated facts
726 /// onto the record at the one site that reports for the arm.
727 pub intx: InTxBatches,
728 /// Bound-both-ends ExpandInto probes and reversed probes.
729 pub expand_into: ExpandIntoCounters,
730 /// Composable HashJoin and SemiMasker SIP facts.
731 pub hash_join: HashJoinCounters,
732 /// Vector scans by serving path (ADR-0705).
733 pub vector_scan: VectorScanCounters,
734}
735
736/// Per-clause PROFILE metrics sink (ADR-0344 phase 2): the dispatch loop
737/// reports each statement-level clause operator's metrics once it
738/// finishes, keyed `(stage, part, clause)` — the same walk the plan tree
739/// construction uses, so the collected entries stamp onto the PROFILE
740/// result's plan tree without a second mapping.
741pub trait PlanMetricsSink {
742 /// The record's `stage` is the NEXT-chain position (1-based, matching
743 /// the tree's stage numbering): each NEXT stage restarts its part
744 /// indices at 0, so the stage keeps the keys disjoint — without it a
745 /// chained statement's later stage overwrites the earlier stage's
746 /// entries.
747 fn record_clause(&self, record: ClauseMetricsRecord);
748
749 /// The statement's constructor-memo facts, reported once when the
750 /// statement finished (ADR-0654 §3): they belong to no one operator,
751 /// so the consumer attaches them at the plan root.
752 fn record_statement_memos(&self, record: StatementMemoRecord);
753}
754
755#[cfg(test)]
756mod tests {
757 use super::*;
758
759 /// REL8-2047: the batch-facts cell accumulates its counters and keeps
760 /// the running maxima — a smaller later batch never lowers a peak, and
761 /// a rolled-back batch counts without an output or WAL figure.
762 #[test]
763 fn intx_stats_accumulate_counters_and_keep_maxima() {
764 let stats = InTxStats::new();
765 stats.note_batch(InTxBatchEnd::Committed {
766 input_bytes: 100,
767 output_bytes: 60,
768 scratch_bytes: 500,
769 wal_bytes: 200,
770 });
771 stats.note_batch(InTxBatchEnd::RolledBack {
772 input_bytes: 80,
773 scratch_bytes: 300,
774 });
775 let facts = stats.facts();
776 assert_eq!(facts.batches, 2);
777 assert_eq!(facts.committed, 1);
778 assert_eq!(facts.rolled_back, 1);
779 assert_eq!(facts.peak_input_rows_bytes, 100, "the larger input holds");
780 assert_eq!(facts.peak_output_rows_bytes, 60);
781 assert_eq!(facts.peak_scratch_bytes, 500, "the larger scratch holds");
782 assert_eq!(facts.peak_wal_bytes, 200);
783 }
784}