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 memo types behind an operator's sums (ADR-0654 §3): every
226 /// operator-level memo is a guarded-state node-label memo (the
227 /// constructor memos report at statement level through
228 /// [`StatementMemoRecord`]), so a probed operator names that one kind.
229 /// The rule lives here, beside the sums it describes — the plan builder
230 /// asks, never decides which memo produced a count.
231 pub fn operator_kinds(&self) -> relate_model::wire::MemoKindsWire {
232 use relate_model::wire::{MemoKindWire, MemoKindsWire};
233 if self.probes > 0 {
234 MemoKindsWire::default().with(MemoKindWire::NodeLabel)
235 } else {
236 MemoKindsWire::default()
237 }
238 }
239}
240
241/// The statement-level memo facts (ADR-0654 §3): the constructor memos
242/// live in the query overlay and serve any expression, so they report once
243/// for the whole statement, attached at the plan root — the counters
244/// summed over them and the memo types that were probed.
245#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
246pub struct StatementMemoRecord {
247 pub counters: MemoCounters,
248 pub kinds: relate_model::wire::MemoKindsWire,
249}
250
251impl FrontierCounters {
252 /// The fraction of one run's re-arrival work budget the clause's
253 /// runs spent: summed [`Self::rearrival_work`] over
254 /// [`REARRIVAL_WORK_BUDGET`] — `1.0` on a run the budget cut
255 /// mid-search (the work guard drains the budget to exactly zero
256 /// before declaring the cut), `0.0` on runs that never asked the
257 /// rule. A multi-seed clause sums every run's spend over the
258 /// one-run budget, so the fraction reads as run-equivalents.
259 pub fn budget_fraction(&self) -> f64 {
260 self.rearrival_work as f64 / REARRIVAL_WORK_BUDGET as f64
261 }
262}
263
264impl StoreReads {
265 /// The kinds' sum — the one `Db Hits` total, derived rather than
266 /// snapshotted a second time.
267 pub fn total(self) -> u64 {
268 self.hops + self.neighbor_walks + self.node_reads
269 }
270}
271
272/// How a `MATCH` walk chose its start element (LABS-369): the fact the
273/// opaque `Expand` hid. A displaced start — a cheap index seek that became
274/// a 135k-relationship backward traversal — is named here instead of
275/// showing up only as a large `Db Hits` total.
276#[derive(Clone, Copy, Debug, PartialEq, Eq)]
277pub struct WalkStart {
278 /// The pattern element index the walk started from.
279 pub element: usize,
280 /// Whether the walk ran the pivot's prefix backwards from it.
281 pub backward: bool,
282 /// Why that start won.
283 pub reason: StartReason,
284}
285
286impl WalkStart {
287 /// The un-optimised default start: the pattern's first element — the
288 /// seed side — walked forward, the `index-0` reason. The one spelling
289 /// every kernel and batch arm that ignores the start ladder records.
290 pub(crate) fn seed_side_forward() -> WalkStart {
291 WalkStart {
292 element: 0,
293 backward: false,
294 reason: StartReason::IndexZero,
295 }
296 }
297}
298
299/// The start-selection reason classes (ADR-0350's bound pivot, ADR-0351's
300/// cheapest-start estimate, the LABS-161 relationship seek, the default).
301#[derive(Clone, Copy, Debug, PartialEq, Eq)]
302pub enum StartReason {
303 /// A row-bound element anchored the walk (ADR-0350).
304 BoundPivot,
305 /// The cheapest-start estimate chose the element (ADR-0351).
306 Cheapest,
307 /// A LABS-161 relationship seek anchored the walk.
308 SeekAnchored,
309 /// The pattern's first element: the un-optimised default.
310 IndexZero,
311}
312
313impl StartReason {
314 /// The reason's stable wire name (LABS-369): the vocabulary the plan
315 /// args and the renderers spell, read from its single source
316 /// ([`plan_keys`](relate_model::wire::plan_keys)), as the rung names are.
317 pub fn as_str(self) -> &'static str {
318 match self {
319 StartReason::BoundPivot => relate_model::wire::plan_keys::START_REASON_BOUND_PIVOT,
320 StartReason::Cheapest => relate_model::wire::plan_keys::START_REASON_CHEAPEST,
321 StartReason::SeekAnchored => relate_model::wire::plan_keys::START_REASON_SEEK_ANCHORED,
322 StartReason::IndexZero => relate_model::wire::plan_keys::START_REASON_INDEX_ZERO,
323 }
324 }
325}
326
327/// Which rung served one `MATCH` clause (LABS-1117): the fact EXPLAIN
328/// could not show, because the rungs are runtime choices inside an
329/// operator, not plan nodes. The ladder records it per clause; the
330/// PROFILE record carries it. [`Walker`](Self::Walker) is the per-row
331/// walker, the rung every decline's home — the batch scan/filter chain
332/// is its own fact (`BatchFacts::ran`), never a rung here.
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub enum KernelRung {
335 /// The unrolled fixed-k chain kernel, `hops` hops (ADR-0473).
336 Chain { hops: usize },
337 /// The hub-star candidate-intersection kernel (ADR-0473).
338 HubStar,
339 /// The frontier-NFA rung over the BFS (ADR-0478).
340 FrontierNfa,
341 /// The per-row walker — every gate's decline.
342 Walker,
343}
344
345impl KernelRung {
346 /// The rung's stable wire name (the `StartReason::as_str` pattern).
347 /// The names live in the wire vocabulary (`KernelRungWire`'s
348 /// constants), so the executor and every surface spell them once; the
349 /// variant↔name mapping is pinned by `relate`'s
350 /// `decline_and_start_reason_names_match_the_wire_tables`.
351 pub fn as_str(self) -> &'static str {
352 match self {
353 KernelRung::Chain { .. } => relate_model::wire::KernelRungWire::CHAIN,
354 KernelRung::HubStar => relate_model::wire::KernelRungWire::HUB_STAR,
355 KernelRung::FrontierNfa => relate_model::wire::KernelRungWire::FRONTIER_NFA,
356 KernelRung::Walker => relate_model::wire::KernelRungWire::WALKER,
357 }
358 }
359}
360
361/// The batch chain's PROFILE facts for one clause, carried as one value so
362/// the record never holds a loose flag beside its counter.
363#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
364pub struct BatchFacts {
365 /// Whether the clause ran ADR-0468's batch scan/filter/project chain
366 /// over `Chunk` (LABS-359) — the PROFILE-visible fact that a
367 /// scan-shaped `MATCH` interior executed as batch operators. `false`
368 /// is every other clause, and every clause the chain declined.
369 pub ran: bool,
370 /// The batch filter's zone skips (LABS-645): how many conjunct-batch
371 /// evaluations the chunk's derived min/max zone metadata provably
372 /// replaced with the correct empty survivor set. `0` on every clause
373 /// the chain declined and every clause that skipped nothing.
374 pub zone_skips: u64,
375}
376
377/// One clause operator's PROFILE metrics, reported to the sink (ADR-0344
378/// phase 2 + the metric-fields phase): the position key `(stage, part,
379/// clause)` — the same walk the plan tree construction uses — beside the
380/// operator's actuals. Bundled so the sink signature stays at one
381/// argument however many metrics a later phase adds.
382pub struct ClauseMetricsRecord {
383 /// The NEXT-chain position (1-based, matching the tree's stage
384 /// numbering): each NEXT stage restarts its part indices at 0, so the
385 /// stage keeps the keys disjoint — without it a chained statement's
386 /// later stage overwrites the earlier stage's entries.
387 pub stage: usize,
388 pub part: usize,
389 pub clause: usize,
390 /// Rows the operator produced.
391 pub rows: u64,
392 /// Row-materialization bytes: the summed logical size
393 /// (`Value::logical_bytes`, ADR-0042, plus each key's string bytes)
394 /// of the rows the operator produced. Stateful operators'
395 /// non-row state (aggregation tables, sort buffers) is a follow-up.
396 pub memory_bytes: u64,
397 /// Expression allocation bytes the clause's arm charged against the
398 /// ADR-0463 statement budget — the delta of the view's expression
399 /// counter across the arm, the same snapshot/delta shape as
400 /// [`ClauseMetricsRecord::reads`]. Zero for a clause that builds no
401 /// containers or strings.
402 pub expression_built_bytes: u64,
403 /// The operator's elapsed time, nanoseconds.
404 pub time_ns: u128,
405 /// The store-read mix (LABS-369) behind the operator's `Db Hits`
406 /// total: hops vs neighbor walks vs node reads.
407 pub reads: StoreReads,
408 /// The clause's inclusive phase times (LABS-448): the seek (candidate
409 /// resolution and checks) and the walk (relationship traversal),
410 /// stamped only while a PROFILE statement's arm runs — a non-PROFILEd
411 /// statement's record carries zeros.
412 pub phases: PhaseTimes,
413 /// How the walk chose its start, when the clause ran a `MATCH` walk
414 /// (LABS-369) — `None` for clauses that walk nothing.
415 pub start: Option<WalkStart>,
416 /// Which rung served the clause's `MATCH` walk (LABS-1117): the
417 /// chain kernel, the hub-star kernel, the frontier-NFA rung, or the
418 /// per-row walker — the operator the clause's `MATCH` ladder (or, for
419 /// a `SEARCH` `MATCH`, its direct walker call) returned. `None`
420 /// exactly when no `MATCH` operator ran: a non-`MATCH` clause; a
421 /// `MATCH` a fold answered (`try_match_folds`, a boolean or walk
422 /// count); a `MATCH` inside a nested evaluation (its own loop); and a
423 /// `MATCH` the ADR-0468 batch chain answered — that operator is
424 /// [`Self::batched`]'s own fact, never a traversal rung.
425 pub kernel: Option<KernelRung>,
426 /// What ADR-0468's batch scan/filter/project chain did for the
427 /// clause: whether it ran and what its filter skipped.
428 pub batch: BatchFacts,
429 /// The frontier family's run counters (ADR-0478): the BFS's edge
430 /// visits, completed levels, and accepted endpoints, summed over the
431 /// clause's per-seed runs. Zero on every clause the frontier's
432 /// compile gates declined (it never ran); a run-time decline
433 /// ([`FrontierDeclineReason::Run`]) keeps them recorded, since the
434 /// rung did run. The plan table's `Details` cell marks the operator
435 /// (`[frontier edges=N levels=L endpoints=P]`) when it ran.
436 pub frontier: FrontierCounters,
437 /// Why the frontier rung did not serve the clause (ADR-0516, extended
438 /// by the plan-time half): the first typed reason, `None` on every
439 /// clause the rung served and on every clause the rung never
440 /// considered (no single quantified pattern, the diagnostic switch's
441 /// `walk` stand-down, a nested evaluation's own arm). A plan-time
442 /// reason ([`FrontierDeclineReason::Plan`]) is a gate that kept the
443 /// clause off the rung — the clause itself ran no frontier (its counters
444 /// stay zero unless a nested EXISTS frontier run in the same clause
445 /// contributed); a run-time reason
446 /// ([`FrontierDeclineReason::Run`]) is the re-arrival budget's
447 /// exhaustion or the table ceiling's crossing, the counters recorded
448 /// beside it.
449 pub frontier_decline: Option<FrontierDeclineReason>,
450 /// The expression-memo counters of the guarded-state memos the clause's
451 /// stage ran (ADR-0654 §3), summed, with `disabled_count` in place of a
452 /// per-memo flag. Zero on every clause that probed no memo; stamped
453 /// only while a PROFILE statement's arm runs.
454 pub memo: MemoCounters,
455}
456
457/// Per-clause PROFILE metrics sink (ADR-0344 phase 2): the dispatch loop
458/// reports each statement-level clause operator's metrics once it
459/// finishes, keyed `(stage, part, clause)` — the same walk the plan tree
460/// construction uses, so the collected entries stamp onto the PROFILE
461/// result's plan tree without a second mapping.
462pub trait PlanMetricsSink {
463 /// The record's `stage` is the NEXT-chain position (1-based, matching
464 /// the tree's stage numbering): each NEXT stage restarts its part
465 /// indices at 0, so the stage keeps the keys disjoint — without it a
466 /// chained statement's later stage overwrites the earlier stage's
467 /// entries.
468 fn record_clause(&self, record: ClauseMetricsRecord);
469
470 /// The statement's constructor-memo facts, reported once when the
471 /// statement finished (ADR-0654 §3): they belong to no one operator,
472 /// so the consumer attaches them at the plan root.
473 fn record_statement_memos(&self, record: StatementMemoRecord);
474}