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 expression-memo counters of one operator or statement (ADR-0654,
202 /// ADR-0640): the per-memo facts summed over the memos the unit ran,
203 /// read once when each memo finishes — a memo's increments are the
204 /// ones already on its path, so collecting them adds none. Zero on
205 /// every unit that probed no memo.
206 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207 pub struct MemoCounters: u64 {
208 /// Inputs looked up in a memo table (warm-up inputs are not probes).
209 probes,
210 /// Probes a table answered.
211 hits,
212 /// Answers stored.
213 inserts,
214 /// Answers not stored because the meter or the ceiling refused.
215 refused,
216 /// The tables' allocation when read, bytes — never part of
217 /// `memory_bytes` (ADR-0654 §2).
218 bytes,
219 /// How many memos gave up at their hit-rate review.
220 disabled_count,
221 }
222}
223
224impl MemoCounters {
225 /// The group's six counts in `plan_keys::MEMO_GROUP_KEYS`' order
226 /// (probes, hits, inserts, refused, bytes, disabled count) — the
227 /// values the wire emitter pairs with that one key table.
228 pub fn counters(&self) -> [u64; 6] {
229 [
230 self.probes,
231 self.hits,
232 self.inserts,
233 self.refused,
234 self.bytes,
235 self.disabled_count,
236 ]
237 }
238
239 /// The memo types behind an operator's sums (ADR-0654 §3): every
240 /// operator-level memo is a guarded-state node-label memo (the
241 /// constructor memos report at statement level through
242 /// [`StatementMemoRecord`]), so a probed operator names that one kind.
243 /// The rule lives here, beside the sums it describes — the plan builder
244 /// asks, never decides which memo produced a count.
245 pub fn operator_kinds(&self) -> relate_model::wire::MemoKindsWire {
246 use relate_model::wire::{MemoKindWire, MemoKindsWire};
247 if self.probes > 0 {
248 MemoKindsWire::default().with(MemoKindWire::NodeLabel)
249 } else {
250 MemoKindsWire::default()
251 }
252 }
253}
254
255/// The statement-level memo facts (ADR-0654 §3): the constructor memos
256/// live in the query overlay and serve any expression, so they report once
257/// for the whole statement, attached at the plan root — the counters
258/// summed over them and the memo types that were probed.
259#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
260pub struct StatementMemoRecord {
261 pub counters: MemoCounters,
262 pub kinds: relate_model::wire::MemoKindsWire,
263}
264
265impl FrontierCounters {
266 /// The group's ten counts in `plan_keys::FRONTIER_GROUP_KEYS`' order
267 /// (edges, levels, endpoints, cells, memo hits, memo misses,
268 /// representative proofs, search proven, search disproven, declined
269 /// exhausted) — the values the wire emitter pairs with that one key
270 /// table.
271 pub fn counters(&self) -> [u64; 10] {
272 [
273 self.edge_visits,
274 self.levels,
275 self.endpoints,
276 self.cells,
277 self.memo_hits,
278 self.memo_misses,
279 self.representative_proofs,
280 self.search_proven,
281 self.search_disproven,
282 self.declined_exhausted,
283 ]
284 }
285
286 /// The fraction of one run's re-arrival work budget the clause's
287 /// runs spent: summed [`Self::rearrival_work`] over
288 /// [`REARRIVAL_WORK_BUDGET`] — `1.0` on a run the budget cut
289 /// mid-search (the work guard drains the budget to exactly zero
290 /// before declaring the cut), `0.0` on runs that never asked the
291 /// rule. A multi-seed clause sums every run's spend over the
292 /// one-run budget, so the fraction reads as run-equivalents.
293 pub fn budget_fraction(&self) -> f64 {
294 self.rearrival_work as f64 / REARRIVAL_WORK_BUDGET as f64
295 }
296}
297
298impl StoreReads {
299 /// The kinds' sum — the one `Db Hits` total, derived rather than
300 /// snapshotted a second time.
301 pub fn total(self) -> u64 {
302 self.hops + self.neighbor_walks + self.node_reads
303 }
304}
305
306/// How a `MATCH` walk chose its start element (LABS-369): the fact the
307/// opaque `Expand` hid. A displaced start — a cheap index seek that became
308/// a 135k-relationship backward traversal — is named here instead of
309/// showing up only as a large `Db Hits` total.
310#[derive(Clone, Copy, Debug, PartialEq, Eq)]
311pub struct WalkStart {
312 /// The pattern element index the walk started from.
313 pub element: usize,
314 /// Whether the walk ran the pivot's prefix backwards from it.
315 pub backward: bool,
316 /// Why that start won.
317 pub reason: StartReason,
318}
319
320impl WalkStart {
321 /// The un-optimised default start: the pattern's first element — the
322 /// seed side — walked forward, the `index-0` reason. The one spelling
323 /// every kernel and batch arm that ignores the start ladder records.
324 pub(crate) fn seed_side_forward() -> WalkStart {
325 WalkStart {
326 element: 0,
327 backward: false,
328 reason: StartReason::IndexZero,
329 }
330 }
331}
332
333/// The start-selection reason classes (ADR-0350's bound pivot, ADR-0351's
334/// cheapest-start estimate, the LABS-161 relationship seek, the default).
335#[derive(Clone, Copy, Debug, PartialEq, Eq)]
336pub enum StartReason {
337 /// A row-bound element anchored the walk (ADR-0350).
338 BoundPivot,
339 /// The cheapest-start estimate chose the element (ADR-0351).
340 Cheapest,
341 /// A LABS-161 relationship seek anchored the walk.
342 SeekAnchored,
343 /// The pattern's first element: the un-optimised default.
344 IndexZero,
345}
346
347impl StartReason {
348 /// The reason's stable wire name (LABS-369): the vocabulary the plan
349 /// args and the renderers spell, read from its single source
350 /// ([`plan_keys`](relate_model::wire::plan_keys)), as the rung names are.
351 pub fn as_str(self) -> &'static str {
352 match self {
353 StartReason::BoundPivot => relate_model::wire::plan_keys::START_REASON_BOUND_PIVOT,
354 StartReason::Cheapest => relate_model::wire::plan_keys::START_REASON_CHEAPEST,
355 StartReason::SeekAnchored => relate_model::wire::plan_keys::START_REASON_SEEK_ANCHORED,
356 StartReason::IndexZero => relate_model::wire::plan_keys::START_REASON_INDEX_ZERO,
357 }
358 }
359}
360
361/// Which rung served one `MATCH` clause (LABS-1117): the fact EXPLAIN
362/// could not show, because the rungs are runtime choices inside an
363/// operator, not plan nodes. The ladder records it per clause; the
364/// PROFILE record carries it. [`Walker`](Self::Walker) is the per-row
365/// walker, the rung every decline's home — the batch scan/filter chain
366/// is its own fact (`BatchFacts::ran`), never a rung here.
367#[derive(Clone, Copy, Debug, PartialEq, Eq)]
368pub enum KernelRung {
369 /// The unrolled fixed-k chain kernel, `hops` hops (ADR-0473).
370 Chain { hops: usize },
371 /// The hub-star candidate-intersection kernel (ADR-0473).
372 HubStar,
373 /// The frontier-NFA rung over the BFS (ADR-0478).
374 FrontierNfa,
375 /// The per-row walker — every gate's decline.
376 Walker,
377}
378
379impl KernelRung {
380 /// The rung's stable wire name (the `StartReason::as_str` pattern).
381 /// The names live in the wire vocabulary (`KernelRungWire`'s
382 /// constants), so the executor and every surface spell them once; the
383 /// variant↔name mapping is pinned by `relate`'s
384 /// `decline_and_start_reason_names_match_the_wire_tables`.
385 pub fn as_str(self) -> &'static str {
386 match self {
387 KernelRung::Chain { .. } => relate_model::wire::KernelRungWire::CHAIN,
388 KernelRung::HubStar => relate_model::wire::KernelRungWire::HUB_STAR,
389 KernelRung::FrontierNfa => relate_model::wire::KernelRungWire::FRONTIER_NFA,
390 KernelRung::Walker => relate_model::wire::KernelRungWire::WALKER,
391 }
392 }
393}
394
395/// The batch chain's PROFILE facts for one clause, carried as one value so
396/// the record never holds a loose flag beside its counter.
397#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
398pub struct BatchFacts {
399 /// Whether the clause ran ADR-0468's batch scan/filter/project chain
400 /// over `Chunk` (LABS-359) — the PROFILE-visible fact that a
401 /// scan-shaped `MATCH` interior executed as batch operators. `false`
402 /// is every other clause, and every clause the chain declined.
403 pub ran: bool,
404 /// The batch filter's zone skips (LABS-645): how many conjunct-batch
405 /// evaluations the chunk's derived min/max zone metadata provably
406 /// replaced with the correct empty survivor set. `0` on every clause
407 /// the chain declined and every clause that skipped nothing.
408 pub zone_skips: u64,
409}
410
411/// The `CALL { … } IN TRANSACTIONS` batch facts one `CallSubquery`
412/// operator reports to PROFILE (REL8-2047): the batch counters — how many
413/// batches ran, how many committed, how many rolled back under the `ON
414/// ERROR` policy — and the per-batch maxima: the input batch's retained
415/// row bytes, the installed output's, the scratch the batch created
416/// (entities, adjacency and property state — the redo log excluded, its
417/// bytes are the WAL figure), and the redo log's reserved bytes at commit,
418/// the WAL payload the batch wrote. The counters are arm-local (not global
419/// counter snapshots): the batch loop notes each finished batch into the
420/// shared cell the clause's record reads once its consumer drains the
421/// stream. All-zero on every other clause, and on an unprofiled run.
422#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
423pub struct InTxBatches {
424 /// Batches that started a transaction.
425 pub batches: u64,
426 /// Batches that committed (both arms of the commit: a facade sink's
427 /// durable per-batch commit, and the statement-level boundary a
428 /// nested or explicit-transaction run closes with).
429 pub committed: u64,
430 /// Batches that rolled back — a handled failure under `ON ERROR
431 /// CONTINUE`/`BREAK`, or the failing batch of `ON ERROR FAIL`.
432 pub rolled_back: u64,
433 /// The largest input batch's retained row bytes.
434 pub peak_input_rows_bytes: u64,
435 /// The largest installed output's retained row bytes.
436 pub peak_output_rows_bytes: u64,
437 /// The most scratch bytes one batch created (redo excluded).
438 pub peak_scratch_bytes: u64,
439 /// The most redo-log bytes one batch carried at its commit — the WAL
440 /// payload it wrote.
441 pub peak_wal_bytes: u64,
442}
443
444/// The `CALL { … } IN TRANSACTIONS` arm's PROFILE facts (REL8-2047): the
445/// batch counters and per-batch maxima the batch loop notes as each batch
446/// finishes, in a cell shared between the arm's iterator (the writer) and
447/// the stream's parked record (the reader), so the clause's record —
448/// reported once the consumer drains or stops the stream, after every
449/// batch has run — carries them. One is built only when a PROFILE record
450/// is attached, so an unprofiled run never pays a cell write per batch.
451pub(crate) struct InTxStats {
452 facts: std::cell::Cell<InTxBatches>,
453}
454
455/// How one finished batch ended, as [`InTxStats::note_batch`] reads it —
456/// the counted outcome with the per-batch figures beside it, so a
457/// committed batch cannot note peaks without its WAL payload and a rolled
458/// back one cannot note an installed output it never handed over.
459pub(crate) enum InTxBatchEnd {
460 /// The batch committed: its output was installed and its redo became
461 /// the WAL payload — all four peaks are live.
462 Committed {
463 input_bytes: u64,
464 output_bytes: u64,
465 scratch_bytes: u64,
466 wal_bytes: u64,
467 },
468 /// The batch rolled back: its own rows are gone, so there is no
469 /// output or WAL figure — the input it held and the scratch it created
470 /// before the rollback are the peaks it still reached.
471 RolledBack {
472 input_bytes: u64,
473 scratch_bytes: u64,
474 },
475}
476
477impl InTxStats {
478 pub(crate) fn new() -> Self {
479 Self {
480 facts: std::cell::Cell::new(InTxBatches::default()),
481 }
482 }
483
484 /// Note one finished batch: the outcome counter beside the batch count,
485 /// each figure keeping the running maximum — the one write path the
486 /// batch loop takes per batch.
487 pub(crate) fn note_batch(&self, end: InTxBatchEnd) {
488 let mut facts = self.facts.get();
489 facts.batches += 1;
490 match end {
491 InTxBatchEnd::Committed {
492 input_bytes,
493 output_bytes,
494 scratch_bytes,
495 wal_bytes,
496 } => {
497 facts.committed += 1;
498 facts.peak_input_rows_bytes = facts.peak_input_rows_bytes.max(input_bytes);
499 facts.peak_output_rows_bytes = facts.peak_output_rows_bytes.max(output_bytes);
500 facts.peak_scratch_bytes = facts.peak_scratch_bytes.max(scratch_bytes);
501 facts.peak_wal_bytes = facts.peak_wal_bytes.max(wal_bytes);
502 }
503 InTxBatchEnd::RolledBack {
504 input_bytes,
505 scratch_bytes,
506 } => {
507 facts.rolled_back += 1;
508 facts.peak_input_rows_bytes = facts.peak_input_rows_bytes.max(input_bytes);
509 facts.peak_scratch_bytes = facts.peak_scratch_bytes.max(scratch_bytes);
510 }
511 }
512 self.facts.set(facts);
513 }
514
515 /// The accumulated facts — the clause record's read, once the stream
516 /// reports.
517 pub(crate) fn facts(&self) -> InTxBatches {
518 self.facts.get()
519 }
520}
521
522/// A parked stream's PROFILE record (REL8-2047): the site and clause the
523/// record keys, with the `CALL { … } IN TRANSACTIONS` arm's batch-facts
524/// cell riding inside — one optional value, so a cell without a record,
525/// or a record whose form has no batches, is unrepresentable. Every
526/// non-batched form builds one with [`Self::at`]; the arm's constructor
527/// attaches a cell through [`Self::with_intx`] — the one attaching site
528/// the type's API states, not a field any caller can assign.
529#[derive(Clone)]
530pub(crate) struct ParkedRecord<'a> {
531 /// The statement's PROFILE site — the sink and the `(stage, part)`
532 /// position its keys ride.
533 pub(crate) site: PlanMetricsSite<'a>,
534 /// The clause index the record keys.
535 pub(crate) clause: usize,
536 /// The arm's batch-facts cell, noted by the batch loop as each batch
537 /// finishes; absent on every other parked form. Private: presence is
538 /// decided by the constructor alone.
539 intx: Option<std::rc::Rc<InTxStats>>,
540}
541
542impl<'a> ParkedRecord<'a> {
543 /// The plain record every non-batched form parks — no cell attached.
544 pub(crate) fn at(site: PlanMetricsSite<'a>, clause: usize) -> Self {
545 Self {
546 site,
547 clause,
548 intx: None,
549 }
550 }
551
552 /// Attach the `IN TRANSACTIONS` arm's batch-facts cell — the one
553 /// attaching site (the arm's constructor, which keeps the writer
554 /// handle beside the record it hands the reader); no other form can,
555 /// so the cell's presence states "this record's clause runs batches".
556 pub(crate) fn with_intx(self, stats: std::rc::Rc<InTxStats>) -> Self {
557 Self {
558 intx: Some(stats),
559 ..self
560 }
561 }
562
563 /// The accumulated batch facts for the clause record's stamp — zeroed
564 /// on every record with no cell attached.
565 pub(crate) fn intx_facts(&self) -> InTxBatches {
566 self.intx
567 .as_deref()
568 .map(InTxStats::facts)
569 .unwrap_or_default()
570 }
571}
572
573impl InTxBatches {
574 /// Whether the arm ran any batch — the group's one presence rule: a
575 /// clause that ran none emits no `InTx*` key at all, so its absence is
576 /// the whole "no batches" fact (never a fabricated zero group).
577 pub fn ran(&self) -> bool {
578 self.batches > 0
579 }
580
581 /// The group's seven counts in `plan_keys::IN_TX_GROUP_KEYS`' order
582 /// (batches, committed, rolled back, peak input bytes, peak output
583 /// bytes, peak scratch bytes, peak WAL bytes) — the values the wire
584 /// emitter pairs with that one key table.
585 pub fn counters(&self) -> [u64; 7] {
586 [
587 self.batches,
588 self.committed,
589 self.rolled_back,
590 self.peak_input_rows_bytes,
591 self.peak_output_rows_bytes,
592 self.peak_scratch_bytes,
593 self.peak_wal_bytes,
594 ]
595 }
596}
597
598/// One clause operator's PROFILE metrics, reported to the sink (ADR-0344
599/// phase 2 + the metric-fields phase): the position key `(stage, part,
600/// clause)` — the same walk the plan tree construction uses — beside the
601/// operator's actuals. Bundled so the sink signature stays at one
602/// argument however many metrics a later phase adds.
603pub struct ClauseMetricsRecord {
604 /// The NEXT-chain position (1-based, matching the tree's stage
605 /// numbering): each NEXT stage restarts its part indices at 0, so the
606 /// stage keeps the keys disjoint — without it a chained statement's
607 /// later stage overwrites the earlier stage's entries.
608 pub stage: usize,
609 pub part: usize,
610 pub clause: usize,
611 /// Rows the operator produced.
612 pub rows: u64,
613 /// Row-materialization bytes: the summed logical size
614 /// (`Value::logical_bytes`, ADR-0042, plus each key's string bytes)
615 /// of the rows the operator produced. Stateful operators'
616 /// non-row state (aggregation tables, sort buffers) is a follow-up.
617 pub memory_bytes: u64,
618 /// Expression allocation bytes the clause's arm charged against the
619 /// ADR-0463 statement budget — the delta of the view's expression
620 /// counter across the arm, the same snapshot/delta shape as
621 /// [`ClauseMetricsRecord::reads`]. Zero for a clause that builds no
622 /// containers or strings.
623 pub expression_built_bytes: u64,
624 /// The operator's elapsed time, nanoseconds.
625 pub time_ns: u128,
626 /// The store-read mix (LABS-369) behind the operator's `Db Hits`
627 /// total: hops vs neighbor walks vs node reads.
628 pub reads: StoreReads,
629 /// The clause's inclusive phase times (LABS-448): the seek (candidate
630 /// resolution and checks) and the walk (relationship traversal),
631 /// stamped only while a PROFILE statement's arm runs — a non-PROFILEd
632 /// statement's record carries zeros.
633 pub phases: PhaseTimes,
634 /// How the walk chose its start, when the clause ran a `MATCH` walk
635 /// (LABS-369) — `None` for clauses that walk nothing.
636 pub start: Option<WalkStart>,
637 /// Which rung served the clause's `MATCH` walk (LABS-1117): the
638 /// chain kernel, the hub-star kernel, the frontier-NFA rung, or the
639 /// per-row walker — the operator the clause's `MATCH` ladder (or, for
640 /// a `SEARCH` `MATCH`, its direct walker call) returned. `None`
641 /// exactly when no `MATCH` operator ran: a non-`MATCH` clause; a
642 /// `MATCH` a fold answered (`try_match_folds`, a boolean or walk
643 /// count); a `MATCH` inside a nested evaluation (its own loop); and a
644 /// `MATCH` the ADR-0468 batch chain answered — that operator is
645 /// [`Self::batched`]'s own fact, never a traversal rung.
646 pub kernel: Option<KernelRung>,
647 /// What ADR-0468's batch scan/filter/project chain did for the
648 /// clause: whether it ran and what its filter skipped.
649 pub batch: BatchFacts,
650 /// The frontier family's run counters (ADR-0478): the BFS's edge
651 /// visits, completed levels, and accepted endpoints, summed over the
652 /// clause's per-seed runs. Zero on every clause the frontier's
653 /// compile gates declined (it never ran); a run-time decline
654 /// ([`FrontierDeclineReason::Run`]) keeps them recorded, since the
655 /// rung did run. The plan table's `Details` cell marks the operator
656 /// (`[frontier edges=N levels=L endpoints=P]`) when it ran.
657 pub frontier: FrontierCounters,
658 /// Why the frontier rung did not serve the clause (ADR-0516, extended
659 /// by the plan-time half): the first typed reason, `None` on every
660 /// clause the rung served and on every clause the rung never
661 /// considered (no single quantified pattern, the diagnostic switch's
662 /// `walk` stand-down, a nested evaluation's own arm). A plan-time
663 /// reason ([`FrontierDeclineReason::Plan`]) is a gate that kept the
664 /// clause off the rung — the clause itself ran no frontier (its counters
665 /// stay zero unless a nested EXISTS frontier run in the same clause
666 /// contributed); a run-time reason
667 /// ([`FrontierDeclineReason::Run`]) is the re-arrival budget's
668 /// exhaustion or the table ceiling's crossing, the counters recorded
669 /// beside it.
670 pub frontier_decline: Option<FrontierDeclineReason>,
671 /// The expression-memo counters of the guarded-state memos the clause's
672 /// stage ran (ADR-0654 §3), summed, with `disabled_count` in place of a
673 /// per-memo flag. Zero on every clause that probed no memo; stamped
674 /// only while a PROFILE statement's arm runs.
675 pub memo: MemoCounters,
676 /// The `CALL { … } IN TRANSACTIONS` batch facts (REL8-2047) — the one
677 /// clause kind that runs batches. Zeroed by the shared record
678 /// constructor; the arm's shared cell stamps its accumulated facts
679 /// onto the record at the one site that reports for the arm.
680 pub intx: InTxBatches,
681}
682
683/// Per-clause PROFILE metrics sink (ADR-0344 phase 2): the dispatch loop
684/// reports each statement-level clause operator's metrics once it
685/// finishes, keyed `(stage, part, clause)` — the same walk the plan tree
686/// construction uses, so the collected entries stamp onto the PROFILE
687/// result's plan tree without a second mapping.
688pub trait PlanMetricsSink {
689 /// The record's `stage` is the NEXT-chain position (1-based, matching
690 /// the tree's stage numbering): each NEXT stage restarts its part
691 /// indices at 0, so the stage keeps the keys disjoint — without it a
692 /// chained statement's later stage overwrites the earlier stage's
693 /// entries.
694 fn record_clause(&self, record: ClauseMetricsRecord);
695
696 /// The statement's constructor-memo facts, reported once when the
697 /// statement finished (ADR-0654 §3): they belong to no one operator,
698 /// so the consumer attaches them at the plan root.
699 fn record_statement_memos(&self, record: StatementMemoRecord);
700}
701
702#[cfg(test)]
703mod tests {
704 use super::*;
705
706 /// REL8-2047: the batch-facts cell accumulates its counters and keeps
707 /// the running maxima — a smaller later batch never lowers a peak, and
708 /// a rolled-back batch counts without an output or WAL figure.
709 #[test]
710 fn intx_stats_accumulate_counters_and_keep_maxima() {
711 let stats = InTxStats::new();
712 stats.note_batch(InTxBatchEnd::Committed {
713 input_bytes: 100,
714 output_bytes: 60,
715 scratch_bytes: 500,
716 wal_bytes: 200,
717 });
718 stats.note_batch(InTxBatchEnd::RolledBack {
719 input_bytes: 80,
720 scratch_bytes: 300,
721 });
722 let facts = stats.facts();
723 assert_eq!(facts.batches, 2);
724 assert_eq!(facts.committed, 1);
725 assert_eq!(facts.rolled_back, 1);
726 assert_eq!(facts.peak_input_rows_bytes, 100, "the larger input holds");
727 assert_eq!(facts.peak_output_rows_bytes, 60);
728 assert_eq!(facts.peak_scratch_bytes, 500, "the larger scratch holds");
729 assert_eq!(facts.peak_wal_bytes, 200);
730 }
731}