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