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 /// The store-read mix a clause's arm performed (LABS-369): the kinds the
105 /// single `Db Hits` total blends. A `Rows=103` operator that spent 300k
106 /// relationship hops and 0 node reads is a different animal from one that
107 /// read 103 nodes — the one-glance diagnosis for the scan-turned-traversal
108 /// family.
109 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
110 pub struct StoreReads: u64 {
111 /// Relationship hops taken.
112 hops,
113 /// Neighbors the walk traversed (counted at the adjacency walk).
114 neighbor_walks,
115 /// Node-store reads: one per candidate a node match examined (the
116 /// all-nodes scan, the label scan, the index seek).
117 node_reads,
118 }
119}
120
121delta_counters! {
122 /// The clause's inclusive phase times (LABS-448): the elapsed time spent
123 /// resolving node candidates (the seek — the store work behind the
124 /// `Nodes` kind) and following relationships (the walk — the store work
125 /// behind the `Rels`/`Degree` kinds); the per-candidate admission checks
126 /// and the arm's binding/cloning stay unattributed. Inclusive of the nesting
127 /// a compound operator performs: a walk that triggers nested seeks counts
128 /// both, like the table's `Total` column.
129 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
130 pub struct PhaseTimes: u128 {
131 /// The seek phase's elapsed nanoseconds.
132 seek_ns,
133 /// The walk phase's elapsed nanoseconds.
134 walk_ns,
135 }
136}
137
138/// The re-arrival rule's shared expansion budget across one frontier run
139/// (the ADR-0395 fixed-constant family, like the runner's
140/// `FRONTIER_WALK_BUDGET`): a fixed constant, no ambient knob — the
141/// remedy for legitimate work that needs more is a new ADR. Every
142/// trail-existence search of the run draws from this one pool, so the
143/// rule's total cost is bounded by it however many re-arrivals a run
144/// sees; sized an order under the runner's own edge-visit budget. The
145/// denominator of [`FrontierCounters::budget_fraction`], so it lives
146/// beside the counter it calibrates.
147pub const REARRIVAL_WORK_BUDGET: u64 = 1_000_000;
148
149delta_counters! {
150 merge
151 /// The frontier family's run counters (ADR-0478), one clause's sum over
152 /// its per-seed BFS runs: the edge visits (the work the walk budget
153 /// caps), the completed levels, the accepted endpoints, and the NFA
154 /// rung's own PROFILE facts — the (node, state) cells the runs created,
155 /// the re-arrival work spent, the rule memo's hits and misses, and the
156 /// admission asks by verdict. Zero on every clause the frontier
157 /// declined — `levels > 0` is the engagement marker (a run always
158 /// completes its level 0).
159 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
160 pub struct FrontierCounters: u64 {
161 /// Incident-edge visits across the clause's frontier runs — the
162 /// budget's own work counter.
163 edge_visits,
164 /// BFS levels completed (level 0 included).
165 levels,
166 /// Endpoints the runs accepted, in arrival order.
167 endpoints,
168 /// (node, state) cells the runs created — the pairs that occupied
169 /// the span×states tables, the BFS's own memory shape.
170 cells,
171 /// Re-arrival rule work spent, summed over the runs — the numerator
172 /// of [`Self::budget_fraction`].
173 rearrival_work,
174 /// Rule-memo hits: asks the run's verdict table answered without a
175 /// search.
176 memo_hits,
177 /// Rule-memo misses: asks that ran the bounded search.
178 memo_misses,
179 /// Admission asks the representative-chain proof settled — no
180 /// search.
181 representative_proofs,
182 /// Admission asks the bounded search proved (an in-bounds path
183 /// found).
184 search_proven,
185 /// Admission asks the bounded search disproved within its bounds.
186 search_disproven,
187 /// Admission asks the shared work budget cut — the run-time decline's
188 /// verdict class (ADR-0516).
189 declined_exhausted,
190 }
191}
192
193impl FrontierCounters {
194 /// The fraction of one run's re-arrival work budget the clause's
195 /// runs spent: summed [`Self::rearrival_work`] over
196 /// [`REARRIVAL_WORK_BUDGET`] — `1.0` on a run the budget cut
197 /// mid-search (the work guard drains the budget to exactly zero
198 /// before declaring the cut), `0.0` on runs that never asked the
199 /// rule. A multi-seed clause sums every run's spend over the
200 /// one-run budget, so the fraction reads as run-equivalents.
201 pub fn budget_fraction(&self) -> f64 {
202 self.rearrival_work as f64 / REARRIVAL_WORK_BUDGET as f64
203 }
204}
205
206impl StoreReads {
207 /// The kinds' sum — the one `Db Hits` total, derived rather than
208 /// snapshotted a second time.
209 pub fn total(self) -> u64 {
210 self.hops + self.neighbor_walks + self.node_reads
211 }
212}
213
214/// How a `MATCH` walk chose its start element (LABS-369): the fact the
215/// opaque `Expand` hid. A displaced start — a cheap index seek that became
216/// a 135k-relationship backward traversal — is named here instead of
217/// showing up only as a large `Db Hits` total.
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219pub struct WalkStart {
220 /// The pattern element index the walk started from.
221 pub element: usize,
222 /// Whether the walk ran the pivot's prefix backwards from it.
223 pub backward: bool,
224 /// Why that start won.
225 pub reason: StartReason,
226}
227
228impl WalkStart {
229 /// The un-optimised default start: the pattern's first element — the
230 /// seed side — walked forward, the `index-0` reason. The one spelling
231 /// every kernel and batch arm that ignores the start ladder records.
232 pub(crate) fn seed_side_forward() -> WalkStart {
233 WalkStart {
234 element: 0,
235 backward: false,
236 reason: StartReason::IndexZero,
237 }
238 }
239}
240
241/// The start-selection reason classes (ADR-0350's bound pivot, ADR-0351's
242/// cheapest-start estimate, the LABS-161 relationship seek, the default).
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub enum StartReason {
245 /// A row-bound element anchored the walk (ADR-0350).
246 BoundPivot,
247 /// The cheapest-start estimate chose the element (ADR-0351).
248 Cheapest,
249 /// A LABS-161 relationship seek anchored the walk.
250 SeekAnchored,
251 /// The pattern's first element: the un-optimised default.
252 IndexZero,
253}
254
255impl StartReason {
256 /// The reason's stable wire name (LABS-369): the vocabulary the plan
257 /// args and the renderers spell, read from its single source
258 /// ([`plan_keys`](relate_model::wire::plan_keys)), as the rung names are.
259 pub fn as_str(self) -> &'static str {
260 match self {
261 StartReason::BoundPivot => relate_model::wire::plan_keys::START_REASON_BOUND_PIVOT,
262 StartReason::Cheapest => relate_model::wire::plan_keys::START_REASON_CHEAPEST,
263 StartReason::SeekAnchored => relate_model::wire::plan_keys::START_REASON_SEEK_ANCHORED,
264 StartReason::IndexZero => relate_model::wire::plan_keys::START_REASON_INDEX_ZERO,
265 }
266 }
267}
268
269/// Which rung served one `MATCH` clause (LABS-1117): the fact EXPLAIN
270/// could not show, because the rungs are runtime choices inside an
271/// operator, not plan nodes. The ladder records it per clause; the
272/// PROFILE record carries it. [`Walker`](Self::Walker) is the per-row
273/// walker, the rung every decline's home — the batch scan/filter chain
274/// is its own fact (`ClauseMetricsRecord::batched`), never a rung here.
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276pub enum KernelRung {
277 /// The unrolled fixed-k chain kernel, `hops` hops (ADR-0473).
278 Chain { hops: usize },
279 /// The hub-star candidate-intersection kernel (ADR-0473).
280 HubStar,
281 /// The frontier-NFA rung over the BFS (ADR-0478).
282 FrontierNfa,
283 /// The per-row walker — every gate's decline.
284 Walker,
285}
286
287impl KernelRung {
288 /// The rung's stable wire name (the `StartReason::as_str` pattern).
289 /// The names live in the wire vocabulary (`KernelRungWire`'s
290 /// constants), so the executor and every surface spell them once; the
291 /// variant↔name mapping is pinned by `relate`'s
292 /// `decline_and_start_reason_names_match_the_wire_tables`.
293 pub fn as_str(self) -> &'static str {
294 match self {
295 KernelRung::Chain { .. } => relate_model::wire::KernelRungWire::CHAIN,
296 KernelRung::HubStar => relate_model::wire::KernelRungWire::HUB_STAR,
297 KernelRung::FrontierNfa => relate_model::wire::KernelRungWire::FRONTIER_NFA,
298 KernelRung::Walker => relate_model::wire::KernelRungWire::WALKER,
299 }
300 }
301}
302
303/// One clause operator's PROFILE metrics, reported to the sink (ADR-0344
304/// phase 2 + the metric-fields phase): the position key `(stage, part,
305/// clause)` — the same walk the plan tree construction uses — beside the
306/// operator's actuals. Bundled so the sink signature stays at one
307/// argument however many metrics a later phase adds.
308pub struct ClauseMetricsRecord {
309 /// The NEXT-chain position (1-based, matching the tree's stage
310 /// numbering): each NEXT stage restarts its part indices at 0, so the
311 /// stage keeps the keys disjoint — without it a chained statement's
312 /// later stage overwrites the earlier stage's entries.
313 pub stage: usize,
314 pub part: usize,
315 pub clause: usize,
316 /// Rows the operator produced.
317 pub rows: u64,
318 /// Row-materialization bytes: the summed logical size
319 /// (`Value::logical_bytes`, ADR-0042, plus each key's string bytes)
320 /// of the rows the operator produced. Stateful operators'
321 /// non-row state (aggregation tables, sort buffers) is a follow-up.
322 pub memory_bytes: u64,
323 /// Expression allocation bytes the clause's arm charged against the
324 /// ADR-0463 statement budget — the delta of the view's expression
325 /// counter across the arm, the same snapshot/delta shape as
326 /// [`ClauseMetricsRecord::reads`]. Zero for a clause that builds no
327 /// containers or strings.
328 pub expression_built_bytes: u64,
329 /// The operator's elapsed time, nanoseconds.
330 pub time_ns: u128,
331 /// The store-read mix (LABS-369) behind the operator's `Db Hits`
332 /// total: hops vs neighbor walks vs node reads.
333 pub reads: StoreReads,
334 /// The clause's inclusive phase times (LABS-448): the seek (candidate
335 /// resolution and checks) and the walk (relationship traversal),
336 /// stamped only while a PROFILE statement's arm runs — a non-PROFILEd
337 /// statement's record carries zeros.
338 pub phases: PhaseTimes,
339 /// How the walk chose its start, when the clause ran a `MATCH` walk
340 /// (LABS-369) — `None` for clauses that walk nothing.
341 pub start: Option<WalkStart>,
342 /// Which rung served the clause's `MATCH` walk (LABS-1117): the
343 /// chain kernel, the hub-star kernel, the frontier-NFA rung, or the
344 /// per-row walker — the operator the clause's `MATCH` ladder (or, for
345 /// a `SEARCH` `MATCH`, its direct walker call) returned. `None`
346 /// exactly when no `MATCH` operator ran: a non-`MATCH` clause; a
347 /// `MATCH` a fold answered (`try_match_folds`, a boolean or walk
348 /// count); a `MATCH` inside a nested evaluation (its own loop); and a
349 /// `MATCH` the ADR-0468 batch chain answered — that operator is
350 /// [`Self::batched`]'s own fact, never a traversal rung.
351 pub kernel: Option<KernelRung>,
352 /// Whether the clause ran ADR-0468's batch scan/filter/project chain
353 /// over `Chunk` (LABS-359) — the PROFILE-visible fact that a
354 /// scan-shaped `MATCH` interior executed as batch operators. `false`
355 /// is every other clause, and every clause the chain declined.
356 pub batched: bool,
357 /// The batch filter's zone skips (LABS-645): how many conjunct-batch
358 /// evaluations the chunk's derived min/max zone metadata provably
359 /// replaced with the correct empty survivor set. `0` on every clause
360 /// the chain declined and every clause that skipped nothing.
361 pub zone_skips: u64,
362 /// The frontier family's run counters (ADR-0478): the BFS's edge
363 /// visits, completed levels, and accepted endpoints, summed over the
364 /// clause's per-seed runs. Zero on every clause the frontier's
365 /// compile gates declined (it never ran); a run-time decline
366 /// ([`FrontierDeclineReason::Run`]) keeps them recorded, since the
367 /// rung did run. The plan table's `Details` cell marks the operator
368 /// (`[frontier edges=N levels=L endpoints=P]`) when it ran.
369 pub frontier: FrontierCounters,
370 /// Why the frontier rung did not serve the clause (ADR-0516, extended
371 /// by the plan-time half): the first typed reason, `None` on every
372 /// clause the rung served and on every clause the rung never
373 /// considered (no single quantified pattern, the diagnostic switch's
374 /// `walk` stand-down, a nested evaluation's own arm). A plan-time
375 /// reason ([`FrontierDeclineReason::Plan`]) is a gate that kept the
376 /// clause off the rung — the clause itself ran no frontier (its counters
377 /// stay zero unless a nested EXISTS frontier run in the same clause
378 /// contributed); a run-time reason
379 /// ([`FrontierDeclineReason::Run`]) is the re-arrival budget's
380 /// exhaustion or the table ceiling's crossing, the counters recorded
381 /// beside it.
382 pub frontier_decline: Option<FrontierDeclineReason>,
383}
384
385/// Per-clause PROFILE metrics sink (ADR-0344 phase 2): the dispatch loop
386/// reports each statement-level clause operator's metrics once it
387/// finishes, keyed `(stage, part, clause)` — the same walk the plan tree
388/// construction uses, so the collected entries stamp onto the PROFILE
389/// result's plan tree without a second mapping.
390pub trait PlanMetricsSink {
391 /// The record's `stage` is the NEXT-chain position (1-based, matching
392 /// the tree's stage numbering): each NEXT stage restarts its part
393 /// indices at 0, so the stage keeps the keys disjoint — without it a
394 /// chained statement's later stage overwrites the earlier stage's
395 /// entries.
396 fn record_clause(&self, record: ClauseMetricsRecord);
397}