Skip to main content

relate_model/
plan_metrics_wire.rs

1//! The PROFILE metric-wire family (ADR-0344 phase 2 + metric fields,
2//! split from `plan_wire.rs` when the IN-TRANSACTIONS batch facts made it
3//! the family's seventh shape): the traversal rung a node reports, the
4//! metric set as named fields, and the shapes the set composes — the
5//! store-read mix, the phase times, the walk start, the frontier
6//! family's run counters, the `CALL { … } IN TRANSACTIONS` batch facts
7//! (REL8-2047) — plus the profiled-facts presentation bundle. The node
8//! wire form and its decoder stay in `plan_wire.rs`; this module is the
9//! family's one home, re-exported through `wire` the way the memo and
10//! warning shapes are.
11
12/// The traversal rung a PROFILE node reports (LABS-1117), typed from the
13/// wire vocabulary: the chain carries its hop count, so a chain without
14/// one — the half-state the parser rejects — is unrepresentable. [`Self::as_str`]
15/// is the vocabulary's one spelling; `plan_keys::KERNEL_RUNGS` is derived
16/// from it.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum KernelRungWire {
19    /// The unrolled fixed-k chain kernel, `hops` hops.
20    Chain { hops: i64 },
21    /// The frontier-NFA rung over the BFS.
22    FrontierNfa,
23    /// The per-row walker — every gate's decline.
24    Walker,
25}
26
27impl KernelRungWire {
28    /// The chain rung's wire name — a name, never a variant value, so no
29    /// hop count is fabricated to reach it.
30    pub const CHAIN: &'static str = "chain";
31    /// The frontier-NFA rung's wire name.
32    pub const FRONTIER_NFA: &'static str = "frontier-nfa";
33    /// The per-row walker's wire name.
34    pub const WALKER: &'static str = "walker";
35    /// Every rung name, in vocabulary order — the wire table's one
36    /// spelling. `plan_keys::KERNEL_RUNGS` is this list; the executor's
37    /// `KernelRung::as_str` reads the same constants.
38    pub const NAMES: [&'static str; 3] = [Self::CHAIN, Self::FRONTIER_NFA, Self::WALKER];
39
40    /// The rung's wire name (`const` so the table derives from this match
41    /// instead of repeating it).
42    pub const fn as_str(self) -> &'static str {
43        match self {
44            KernelRungWire::Chain { .. } => Self::CHAIN,
45            KernelRungWire::FrontierNfa => Self::FRONTIER_NFA,
46            KernelRungWire::Walker => Self::WALKER,
47        }
48    }
49
50    /// The chain rung's hop count — `None` for every other rung.
51    pub const fn hops(self) -> Option<i64> {
52        match self {
53            KernelRungWire::Chain { hops } => Some(hops),
54            KernelRungWire::FrontierNfa | KernelRungWire::Walker => None,
55        }
56    }
57}
58
59/// Which planner ladder level produced a node's `EstimatedRows`
60/// (ADR-0708): one variant per planner `Estimate` variant, so the
61/// reader can tell a measurement from a default. [`Self::as_str`] is the
62/// vocabulary's one spelling; [`Self::NAMES`] is derived
63/// from it. Not the key statistics' own trust label.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum EstimateProvenance {
66    /// A count the store measured: a bound variable, an index equality
67    /// or window, label rows.
68    Measured,
69    /// A sampled `CONTAINS` seed.
70    Sampled,
71    /// Label rows scaled by the key statistics' selectivity (REL8-2249) —
72    /// a statistic, never a default.
73    Statistic,
74    /// The default-selectivity table (ADR-0694) — a default, never a
75    /// measurement.
76    Defaulted,
77}
78
79impl EstimateProvenance {
80    /// Every name, vocabulary order.
81    const VARIANTS: [Self; 4] = [
82        Self::Measured,
83        Self::Sampled,
84        Self::Statistic,
85        Self::Defaulted,
86    ];
87    pub const NAMES: [&'static str; 4] = [
88        Self::VARIANTS[0].as_str(),
89        Self::VARIANTS[1].as_str(),
90        Self::VARIANTS[2].as_str(),
91        Self::VARIANTS[3].as_str(),
92    ];
93
94    /// The wire name (`const` so [`Self::NAMES`] and this match cannot
95    /// drift apart: the pinned test compares them).
96    pub const fn as_str(self) -> &'static str {
97        match self {
98            EstimateProvenance::Measured => "measured",
99            EstimateProvenance::Sampled => "sampled",
100            EstimateProvenance::Statistic => "statistic",
101            EstimateProvenance::Defaulted => "defaulted",
102        }
103    }
104
105    /// The variant a wire name denotes — `None` for a name outside the
106    /// vocabulary (the decoder fails loudly on it).
107    pub fn from_name(name: &str) -> Option<Self> {
108        Self::VARIANTS
109            .into_iter()
110            .find(|provenance| provenance.as_str() == name)
111    }
112}
113
114/// The PROFILE metric set (ADR-0344 phase 2 + metric fields) as named
115/// fields: which number is rows, nanoseconds, store accesses, or
116/// row-materialization bytes is stated by the names, not by a position
117/// convention.
118#[derive(Clone, Copy, Debug, Default, PartialEq)]
119pub struct PlanMetricsWire {
120    pub rows: i64,
121    pub time_ns: i64,
122    pub db_hits: i64,
123    pub memory_bytes: i64,
124    /// Expression allocation bytes charged by the operator's clause
125    /// (ADR-0463), beside the row-materialization `memory_bytes`.
126    pub expression_built_bytes: i64,
127    /// The store-read mix behind `db_hits` (LABS-369).
128    pub reads: PlanReadsWire,
129    /// The phase times behind the read kinds (LABS-448): the seek's and
130    /// the walk's elapsed nanoseconds — emitted with the metric block,
131    /// like the kinds, so a half-present pair is a wire-contract break.
132    pub phases: PlanPhasesWire,
133    /// The walk's chosen start, when the clause walked one (LABS-369).
134    pub start: Option<PlanStartWire>,
135    /// Which rung served the clause's `MATCH` walk (LABS-1117), typed: the
136    /// chain carries its hop count, so the half-state the wire rejects (a
137    /// chain rung without one) is unrepresentable here. `None` when the
138    /// producer emitted no key (a non-`MATCH` clause, a folded or `SEARCH`
139    /// `MATCH`, or a batch-chain `MATCH`).
140    pub kernel: Option<KernelRungWire>,
141    /// Whether the clause ran ADR-0468's batch scan/filter/project chain
142    /// (LABS-359) — `false` on the wire means absent, the producer emits
143    /// the key only when true.
144    pub batched: bool,
145    /// The batch filter's zone skips (LABS-645): conjunct-batch
146    /// evaluations the chunk's derived min/max zone metadata provably
147    /// replaced with the correct empty survivor set — `0` on the wire
148    /// means absent, the producer emits the key only when nonzero.
149    pub zone_skips: i64,
150    /// The frontier family's run counters (ADR-0478), `Default` = the
151    /// family declined the clause: the producer emits the whole set —
152    /// the run counters, the NFA rung's facts, and the budget fraction —
153    /// only when it ran (`levels > 0`), all together like the start
154    /// trio.
155    pub frontier: PlanFrontierWire,
156    /// Why the frontier rung did not serve the clause: a run-time decline
157    /// (ADR-0516) or a plan-time gate (ADR-0478), one of the
158    /// `plan_keys::DECLINE_REASONS` vocabulary — `None` on every clause
159    /// the rung served or never considered, present only on a PROFILE node.
160    pub frontier_decline: Option<&'static str>,
161    /// The expression-memo counters (ADR-0654): `None` = no memo was
162    /// probed on this node, the producer emitting the group only when one
163    /// was (the `batched` / `zone_skips` / `frontier` presence rule).
164    pub memo: Option<super::plan_memo::PlanMemoWire>,
165    /// The `CALL { … } IN TRANSACTIONS` batch facts (REL8-2047):
166    /// `Default` = the arm ran no batch, the producer emitting the seven
167    /// integers together only when one did (the `frontier` presence
168    /// rule's).
169    pub intx: PlanInTxWire,
170    /// Bound-both-ends ExpandInto probe facts, `Default` = no ExpandInto probe
171    /// was executed on this operator.
172    pub expand_into: PlanExpandIntoWire,
173    /// Composable HashJoin and SemiMasker SIP facts, `Default` = no HashJoin
174    /// was executed on this operator.
175    pub hash_join: PlanHashJoinWire,
176    /// Vector scans by serving path (ADR-0705), `Default` = no vector scan
177    /// ran on this operator.
178    pub vector_scan: PlanVectorScanWire,
179}
180
181/// The composable HashJoin and SemiMasker SIP counters a PROFILE node reports:
182/// the build rows, probe rows examined, and semi-mask rejected candidates.
183#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
184pub struct PlanHashJoinWire {
185    pub build_rows: u64,
186    pub probe_rows: u64,
187    pub semi_mask_rejected: u64,
188}
189
190/// The vector scans a PROFILE node ran, by the path that served each: the
191/// packed matrix (ADR-0705) or the `Value` sweep it declined to.
192#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
193pub struct PlanVectorScanWire {
194    pub matrix: u64,
195    pub value_scan: u64,
196}
197
198/// The bound-both-ends ExpandInto probe counters a PROFILE node reports:
199/// the probe attempts and the probes that scanned the smaller-degree destination side.
200#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
201pub struct PlanExpandIntoWire {
202    pub probes: u64,
203    pub reversed: u64,
204}
205
206/// The frontier family's run counters a PROFILE node reports (ADR-0478):
207/// the BFS's edge visits (the work its walk budget caps), its completed
208/// levels, and its accepted endpoints — the `[frontier …]` operator
209/// marker's own trio — beside the NFA rung's own facts: the
210/// (node, state) cells the runs created, the re-arrival rule memo's
211/// hits and misses, the admission asks by verdict, and the budget
212/// fraction the rule's work spent.
213#[derive(Clone, Copy, Debug, Default, PartialEq)]
214pub struct PlanFrontierWire {
215    pub edge_visits: i64,
216    pub levels: i64,
217    pub endpoints: i64,
218    /// (node, state) cells the runs created — the pairs that occupied
219    /// the span×states tables.
220    pub cells: i64,
221    /// Re-arrival rule memo hits: asks the verdict table answered
222    /// without a search.
223    pub memo_hits: i64,
224    /// Re-arrival rule memo misses: asks that ran the bounded search.
225    pub memo_misses: i64,
226    /// Admission asks the representative-chain proof settled.
227    pub representative_proofs: i64,
228    /// Admission asks the bounded search proved.
229    pub search_proven: i64,
230    /// Admission asks the bounded search disproved within its bounds.
231    pub search_disproven: i64,
232    /// Admission asks the shared work budget cut (ADR-0516).
233    pub declined_exhausted: i64,
234    /// The re-arrival work fraction the runs spent — one run's budget as
235    /// the denominator, so `1.0` is a drained (declined) run and a
236    /// multi-seed clause reads as run-equivalents.
237    pub budget_fraction: f64,
238}
239
240/// The `CALL { … } IN TRANSACTIONS` batch facts a PROFILE node reports
241/// (REL8-2047): the batch counters — run, committed, rolled back — and
242/// the per-batch maxima: the input batch's and the installed output's
243/// retained row bytes, the scratch the batch created, and the redo
244/// log's reserved bytes at commit (the WAL payload it wrote). `Default`
245/// = the arm ran no batch (or the node is not the batched call): the
246/// producer emits the seven integers together only when one did.
247#[derive(Clone, Copy, Debug, Default, PartialEq)]
248pub struct PlanInTxWire {
249    /// Batches that started a transaction.
250    pub batches: i64,
251    /// Batches that committed.
252    pub committed: i64,
253    /// Batches that rolled back under the `ON ERROR` policy.
254    pub rolled_back: i64,
255    /// The largest input batch's retained row bytes.
256    pub peak_input_rows_bytes: i64,
257    /// The largest installed output's retained row bytes.
258    pub peak_output_rows_bytes: i64,
259    /// The most scratch bytes one batch created (redo excluded).
260    pub peak_scratch_bytes: i64,
261    /// The most redo-log bytes one batch carried at its commit — the WAL
262    /// payload it wrote.
263    pub peak_wal_bytes: i64,
264}
265
266impl PlanInTxWire {
267    /// Whether the arm ran any batch — the group's one presence rule (the
268    /// executor twin is `relate_executor::InTxBatches::ran`): the wire
269    /// emits the seven keys only when it holds, so their absence is the
270    /// whole "no batches" fact.
271    pub fn ran(&self) -> bool {
272        self.batches > 0
273    }
274}
275
276/// A metrics-carrying node's presentation bundle (cumulative vs self):
277/// the PROFILE metric set and its subtree total — the derived total
278/// travels with the metrics it sums, present together or not at all, so
279/// no presentation can render a total beside unavailable metrics or a
280/// metric set without one.
281#[derive(Clone, Copy, Debug, PartialEq)]
282pub struct PlanProfiledFacts {
283    /// The node's PROFILE metric set.
284    pub metrics: PlanMetricsWire,
285    /// The subtree total of the node's elapsed time: its own `time_ns`
286    /// plus every descendant's — the one fact the `Total (ms)` cell and
287    /// the document's `total_time_ms` render.
288    pub total_time_ns: i64,
289}
290
291/// The store-read mix a PROFILE node reports (LABS-369): the kinds the
292/// one `Db Hits` total blends — relationship hops, neighbor walks, and
293/// node-store reads.
294#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
295pub struct PlanReadsWire {
296    pub hops: i64,
297    pub neighbor_walks: i64,
298    pub node_reads: i64,
299}
300
301/// The phase times a PROFILE node reports (LABS-448): the elapsed time
302/// the read kinds' store work spent — the seek (candidate resolution and
303/// admission, the `Nodes` kind's work) and the walk (relationship
304/// traversal, the `Rels`/`Degree` kinds' work), inclusive of a
305/// multi-element pattern's nested phases.
306#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
307pub struct PlanPhasesWire {
308    /// The seek phase's nanoseconds.
309    pub seek_ns: i64,
310    /// The walk phase's nanoseconds.
311    pub walk_ns: i64,
312}
313
314/// How a PROFILE node's walk chose its start (LABS-369): the pattern
315/// element index, the direction, and the reason class the executor
316/// recorded (`bound-pivot`, `cheapest`, `seek-anchored`, `index-0`).
317#[derive(Clone, Copy, Debug, PartialEq, Eq)]
318pub struct PlanStartWire {
319    pub element: i64,
320    pub backward: bool,
321    /// The reason class, one of the `plan_keys::REASONS` vocabulary — a
322    /// borrowed static, like the warning names.
323    pub reason: &'static str,
324}