relate_executor/ctx.rs
1//! Shared execution-context parameter objects threaded through clause
2//! execution and expression evaluation — plus the PROFILE metric types and
3//! the PROFILE phase clocks (LABS-448) the phase wrappers stamp. The
4//! pattern-walk vocabulary both walk engines (eval, exec) share —
5//! bindings, hop bounds, stub binders, path-walk carriers — lives one
6//! module over, [`crate::pattern_walk`] (LABS-668).
7
8use std::cell::Cell;
9use std::collections::BTreeMap;
10use std::thread::LocalKey;
11
12use relate_core::{Result, Value};
13use web_time::Instant;
14
15use crate::overlay::ExecGraph;
16use crate::redo::RedoOp;
17use crate::row::Row;
18
19/// Statement-level context threaded through clause execution: the parsed
20/// CIP-150 `CYPHER <version>` preamble (typed, from `Statement::cypher_version`
21/// via `LogicalPlan::cypher_version`), the statement's source text (which
22/// feeds `SHOW TRANSACTIONS`' `currentQuery` column), and the connection's
23/// authenticated principal (ADR-0273: set by a surface that verified an
24/// identity — the Bolt server after a validated HELLO — else `None`, and
25/// `dbms.showCurrentUser` reports the documented placeholder).
26#[derive(Clone, Copy)]
27pub(crate) struct QueryCtx<'a> {
28 pub cypher_version: Option<u32>,
29 pub query_text: &'a str,
30 pub principal: Option<&'a str>,
31 /// ADR-0210: per-batch durable-commit sink for `CALL { … } IN
32 /// TRANSACTIONS`. Set by the facade's auto-commit write path; `None`
33 /// everywhere else (tests, nested execution, explicit transactions),
34 /// where batching keeps the accumulate-in-scratch semantics.
35 pub batch_commit: Option<&'a dyn BatchCommit>,
36}
37
38/// The statement's PROFILE site (ADR-0344 phase 2): the metrics sink and
39/// the `(stage, part)` position its keys ride — one fact, built by the
40/// statement-level walkers when they call the clause loop, so the sink
41/// never travels without the position it keys.
42#[derive(Clone, Copy)]
43pub(crate) struct PlanMetricsSite<'a> {
44 /// The sink the facade's PROFILE path attached.
45 pub(crate) sink: &'a dyn PlanMetricsSink,
46 /// The NEXT-chain stage (1-based, matching the tree's stage
47 /// numbering): each NEXT stage restarts its part indices at 0, so the
48 /// stage keeps the keys disjoint.
49 pub(crate) stage: usize,
50 /// The part index within the stage.
51 pub(crate) part: usize,
52}
53
54impl<'a> PlanMetricsSite<'a> {
55 /// The one pairing of a sink with the clause loop's `(stage, part)`
56 /// key — the statement-level walkers' single construction, so a sink
57 /// never travels without the position it keys.
58 pub(crate) fn at(sink: &'a dyn PlanMetricsSink, stage: usize, part: usize) -> Self {
59 PlanMetricsSite { sink, stage, part }
60 }
61}
62
63/// The store-read mix a clause's arm performed (LABS-369): the kinds the
64/// single `Db Hits` total blends. A `Rows=103` operator that spent 300k
65/// relationship hops and 0 node reads is a different animal from one that
66/// read 103 nodes — the one-glance diagnosis for the scan-turned-traversal
67/// family.
68#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
69pub struct StoreReads {
70 /// Relationship hops taken.
71 pub hops: u64,
72 /// Neighbors the walk traversed (counted at the adjacency walk).
73 pub neighbor_walks: u64,
74 /// Node-store reads: one per candidate a node match examined (the
75 /// all-nodes scan, the label scan, the index seek).
76 pub node_reads: u64,
77}
78
79/// The clause's inclusive phase times (LABS-448): the elapsed time spent
80/// resolving node candidates (the seek — the store work behind the
81/// `Nodes` kind) and following relationships (the walk — the store work
82/// behind the `Rels`/`Degree` kinds); the per-candidate admission checks
83/// and the arm's binding/cloning stay unattributed. Inclusive of the nesting
84/// a compound operator performs: a walk that triggers nested seeks counts
85/// both, like the table's `Total` column.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub struct PhaseTimes {
88 /// The seek phase's elapsed nanoseconds.
89 pub seek_ns: u128,
90 /// The walk phase's elapsed nanoseconds.
91 pub walk_ns: u128,
92}
93
94impl PhaseTimes {
95 /// The phases one clause's arm performed: `self` minus the snapshot
96 /// taken when the arm started. The sums only ever increase, so a
97 /// decrease is a broken invariant — the same loud subtraction
98 /// [`StoreReads::since`] uses, never a clamp to a fabricated zero.
99 pub fn since(self, earlier: PhaseTimes) -> PhaseTimes {
100 PhaseTimes {
101 seek_ns: self.seek_ns - earlier.seek_ns,
102 walk_ns: self.walk_ns - earlier.walk_ns,
103 }
104 }
105}
106
107// The PROFILE phase clocks (LABS-448) — the thread-locals behind
108// [`PhaseTimes`] and the wrappers every walker stamps through. They live
109// here, the crate's lowest shared module, so both walk engines (eval,
110// exec) read them downward (LABS-668): the eval walkers' phase spans made
111// the old home beside the exec-only counters (`exec/profiling`) an upward
112// import for `eval`. The clocks and their stamp body stay private to this
113// module: the stamp→run→count pairing is the wrappers' implementation
114// detail, never an API a walker could hand-roll beside them.
115thread_local! {
116 /// Whether a PROFILE statement's clause arm is running (LABS-448) —
117 /// the phase stamps read this before touching the clock, so a
118 /// non-PROFILEd statement pays the thread-local read and nothing
119 /// else. Armed by the clause's metric tick, disarmed by its drop.
120 static PHASE_PROFILING: Cell<bool> = const { Cell::new(false) };
121 /// The inclusive seek-phase sum (LABS-448): the elapsed time
122 /// resolving and checking node candidates — the store work behind the
123 /// `Nodes` kind. Inclusive like the table's `Total` column: a walk
124 /// that triggers nested seeks counts both.
125 static SEEK_NS: Cell<u128> = const { Cell::new(0) };
126 /// The inclusive walk-phase sum (LABS-448): the elapsed time following
127 /// relationships — the store work behind the `Rels`/`Degree` kinds.
128 static WALK_NS: Cell<u128> = const { Cell::new(0) };
129}
130
131/// Arm the phase stamps for a PROFILE clause arm (LABS-448) — the metric
132/// tick's first act, undone by its drop, so the stamps never run outside a
133/// profiled statement.
134pub(crate) fn arm_phase_profiling() {
135 PHASE_PROFILING.with(|c| c.set(true));
136}
137
138/// Disarm the phase stamps (LABS-448) — the metric tick's last act.
139pub(crate) fn disarm_phase_profiling() {
140 PHASE_PROFILING.with(|c| c.set(false));
141}
142
143/// The one phase-span body both wrappers delegate to (LABS-448; one
144/// spelling since LABS-668's stellar round): take the stamp, run the
145/// work, count its elapsed time into `sum`. The stamp is this helper's
146/// local — taken only while a PROFILE statement's arm runs, so a
147/// non-PROFILEd statement pays the one thread-local read and nothing
148/// else, and a `None` stamp counts nothing. A run that errors counts
149/// nothing either: the arm's `time_ns` covers what the phases do not.
150fn phase_span<T>(sum: &'static LocalKey<Cell<u128>>, run: impl FnOnce() -> Result<T>) -> Result<T> {
151 let stamp = PHASE_PROFILING.with(Cell::get).then(Instant::now);
152 let out = run()?;
153 if let Some(start) = stamp {
154 sum.with(|c| c.set(c.get() + start.elapsed().as_nanos()));
155 }
156 Ok(out)
157}
158
159/// One seek-phase span around a pattern node's candidate resolution
160/// (LABS-448). Since the PR-604 stellar round the stamp is the counted
161/// funnel's, not a per-walker obligation: `node_candidates`
162/// (`crate::pattern_walk`, the shared walk tier) resolves through this —
163/// the one caller — so the seek stamp lives beside the read count it
164/// pairs with and every path that bumps the `Nodes` counter (both walk
165/// engines' candidate reads) carries seek time, never a re-stamped copy
166/// per walker. `None` stamps (non-PROFILEd statements) resolve unchanged.
167pub(crate) fn phase_seek<T>(resolve: impl FnOnce() -> Result<T>) -> Result<T> {
168 phase_span(&SEEK_NS, resolve)
169}
170
171/// One walk-phase span around a relationship traversal (LABS-448): the
172/// symmetric spelling of [`phase_seek`] over the walk clock — both
173/// delegate to the one span body, so the walker sites never hand-roll
174/// the stamp→run→count pairing, and the walk-phase contract (inclusive of
175/// nested phases) is stated once, here. `None` stamps resolve unchanged
176/// on non-PROFILEd statements.
177pub(crate) fn phase_walk<T>(walk: impl FnOnce() -> Result<T>) -> Result<T> {
178 phase_span(&WALK_NS, walk)
179}
180
181/// The phase-time sums right now (LABS-448), snapshotted at the clause
182/// tick the way the store-read mix (`exec::profiling::store_reads`) is:
183/// the delta across the arm is the clause's phase times, two thread-local
184/// reads per clause.
185pub(crate) fn phase_times() -> PhaseTimes {
186 PhaseTimes {
187 seek_ns: SEEK_NS.with(Cell::get),
188 walk_ns: WALK_NS.with(Cell::get),
189 }
190}
191
192// The node-store reads (LABS-375): one per candidate a node match
193// examined (the all-nodes scan, the label scan, the index seek) — the
194// scan work the hop/neighbor counters never see, because they count
195// relationship traversal only. It lives beside the phase clocks because
196// its one counting point is the node-candidate funnel
197// (`crate::pattern_walk::node_candidates`), which both walk engines read:
198// a counter with an engine's name on it would be an upward import from
199// the walk tier that bumps it.
200thread_local! {
201 static NODE_READS: Cell<u64> = const { Cell::new(0) };
202}
203
204/// Count `count` node-store reads (LABS-375) — batched because the one
205/// funnel yields the whole candidate list at once, and every node-match
206/// path reads it.
207pub(crate) fn count_node_reads(count: u64) {
208 NODE_READS.with(|c| c.set(c.get() + count));
209}
210
211/// The node-read total right now — read by the store-read mix
212/// ([`crate::exec::profiling::store_reads`]) at clause boundaries, so a
213/// per-clause delta costs one thread-local read, never a per-row one.
214pub(crate) fn node_reads() -> u64 {
215 NODE_READS.with(Cell::get)
216}
217
218/// Take the node-read total, leaving zero — the test-side snapshot the
219/// store-read pins assert against.
220#[cfg(test)]
221pub(crate) fn take_node_reads() -> u64 {
222 NODE_READS.with(|c| c.replace(0))
223}
224
225/// The re-arrival rule's shared expansion budget across one frontier run
226/// (the ADR-0395 fixed-constant family, like the runner's
227/// `FRONTIER_WALK_BUDGET`): a fixed constant, no ambient knob — the
228/// remedy for legitimate work that needs more is a new ADR. Every
229/// trail-existence search of the run draws from this one pool, so the
230/// rule's total cost is bounded by it however many re-arrivals a run
231/// sees; sized an order under the runner's own edge-visit budget. The
232/// denominator of [`FrontierCounters::budget_fraction`], so it lives
233/// beside the counter it calibrates.
234pub const REARRIVAL_WORK_BUDGET: u64 = 1_000_000;
235
236/// The frontier family's run counters (ADR-0478), one clause's sum over
237/// its per-seed BFS runs: the edge visits (the work the walk budget
238/// caps), the completed levels, the accepted endpoints, and the NFA
239/// rung's own PROFILE facts — the (node, state) cells the runs created,
240/// the re-arrival work spent, the rule memo's hits and misses, and the
241/// admission asks by verdict. Zero on every clause the frontier
242/// declined — `levels > 0` is the engagement marker (a run always
243/// completes its level 0).
244#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
245pub struct FrontierCounters {
246 /// Incident-edge visits across the clause's frontier runs — the
247 /// budget's own work counter.
248 pub edge_visits: u64,
249 /// BFS levels completed (level 0 included).
250 pub levels: u64,
251 /// Endpoints the runs accepted, in arrival order.
252 pub endpoints: u64,
253 /// (node, state) cells the runs created — the pairs that occupied
254 /// the span×states tables, the BFS's own memory shape.
255 pub cells: u64,
256 /// Re-arrival rule work spent, summed over the runs — the numerator
257 /// of [`Self::budget_fraction`].
258 pub rearrival_work: u64,
259 /// Rule-memo hits: asks the run's verdict table answered without a
260 /// search.
261 pub memo_hits: u64,
262 /// Rule-memo misses: asks that ran the bounded search.
263 pub memo_misses: u64,
264 /// Admission asks the representative-chain proof settled — no
265 /// search.
266 pub representative_proofs: u64,
267 /// Admission asks the bounded search proved (an in-bounds path
268 /// found).
269 pub search_proven: u64,
270 /// Admission asks the bounded search disproved within its bounds.
271 pub search_disproven: u64,
272 /// Admission asks the shared work budget cut — the run-time decline's
273 /// verdict class (ADR-0516).
274 pub declined_exhausted: u64,
275}
276
277impl FrontierCounters {
278 /// The counters one clause's arm performed: `self` minus the snapshot
279 /// taken when the arm started — the counters only ever increase, so
280 /// a decrease is a broken invariant, the same loud subtraction
281 /// [`StoreReads::since`] uses.
282 pub fn since(self, earlier: FrontierCounters) -> FrontierCounters {
283 self - earlier
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
298/// The field-wise delta, the one spelling [`FrontierCounters::since`]
299/// reads: destructured, so a new counter cannot be silently dropped.
300impl std::ops::Sub for FrontierCounters {
301 type Output = FrontierCounters;
302
303 fn sub(self, earlier: FrontierCounters) -> FrontierCounters {
304 let FrontierCounters {
305 edge_visits,
306 levels,
307 endpoints,
308 cells,
309 rearrival_work,
310 memo_hits,
311 memo_misses,
312 representative_proofs,
313 search_proven,
314 search_disproven,
315 declined_exhausted,
316 } = earlier;
317 FrontierCounters {
318 edge_visits: self.edge_visits - edge_visits,
319 levels: self.levels - levels,
320 endpoints: self.endpoints - endpoints,
321 cells: self.cells - cells,
322 rearrival_work: self.rearrival_work - rearrival_work,
323 memo_hits: self.memo_hits - memo_hits,
324 memo_misses: self.memo_misses - memo_misses,
325 representative_proofs: self.representative_proofs - representative_proofs,
326 search_proven: self.search_proven - search_proven,
327 search_disproven: self.search_disproven - search_disproven,
328 declined_exhausted: self.declined_exhausted - declined_exhausted,
329 }
330 }
331}
332
333/// The field-wise merge, the one spelling the per-run accumulation
334/// (`exec::profiling::count_frontier`) and the rule's tally merge read:
335/// destructured, so a new counter cannot be silently dropped.
336impl std::ops::AddAssign for FrontierCounters {
337 fn add_assign(&mut self, run: FrontierCounters) {
338 let FrontierCounters {
339 edge_visits,
340 levels,
341 endpoints,
342 cells,
343 rearrival_work,
344 memo_hits,
345 memo_misses,
346 representative_proofs,
347 search_proven,
348 search_disproven,
349 declined_exhausted,
350 } = run;
351 self.edge_visits += edge_visits;
352 self.levels += levels;
353 self.endpoints += endpoints;
354 self.cells += cells;
355 self.rearrival_work += rearrival_work;
356 self.memo_hits += memo_hits;
357 self.memo_misses += memo_misses;
358 self.representative_proofs += representative_proofs;
359 self.search_proven += search_proven;
360 self.search_disproven += search_disproven;
361 self.declined_exhausted += declined_exhausted;
362 }
363}
364
365impl StoreReads {
366 /// The reads one clause's arm performed: `self` minus the snapshot
367 /// taken when the arm started. The counters only ever increase, so a
368 /// decrease is a broken invariant — the same loud subtraction the
369 /// store-access total uses, never a clamp to a fabricated zero.
370 pub fn since(self, earlier: StoreReads) -> StoreReads {
371 StoreReads {
372 hops: self.hops - earlier.hops,
373 neighbor_walks: self.neighbor_walks - earlier.neighbor_walks,
374 node_reads: self.node_reads - earlier.node_reads,
375 }
376 }
377
378 /// The kinds' sum — the one `Db Hits` total, derived rather than
379 /// snapshotted a second time.
380 pub fn total(self) -> u64 {
381 self.hops + self.neighbor_walks + self.node_reads
382 }
383}
384
385/// How a `MATCH` walk chose its start element (LABS-369): the fact the
386/// opaque `Expand` hid. A displaced start — a cheap index seek that became
387/// a 135k-relationship backward traversal — is named here instead of
388/// showing up only as a large `Db Hits` total.
389#[derive(Clone, Copy, Debug, PartialEq, Eq)]
390pub struct WalkStart {
391 /// The pattern element index the walk started from.
392 pub element: usize,
393 /// Whether the walk ran the pivot's prefix backwards from it.
394 pub backward: bool,
395 /// Why that start won.
396 pub reason: StartReason,
397}
398
399impl WalkStart {
400 /// The un-optimised default start: the pattern's first element — the
401 /// seed side — walked forward, the `index-0` reason. The one spelling
402 /// every kernel and batch arm that ignores the start ladder records.
403 pub(crate) fn seed_side_forward() -> WalkStart {
404 WalkStart {
405 element: 0,
406 backward: false,
407 reason: StartReason::IndexZero,
408 }
409 }
410}
411
412/// The start-selection reason classes (ADR-0350's bound pivot, ADR-0351's
413/// cheapest-start estimate, the LABS-161 relationship seek, the default).
414#[derive(Clone, Copy, Debug, PartialEq, Eq)]
415pub enum StartReason {
416 /// A row-bound element anchored the walk (ADR-0350).
417 BoundPivot,
418 /// The cheapest-start estimate chose the element (ADR-0351).
419 Cheapest,
420 /// A LABS-161 relationship seek anchored the walk.
421 SeekAnchored,
422 /// The pattern's first element: the un-optimised default.
423 IndexZero,
424}
425
426impl StartReason {
427 /// The reason's stable wire name (LABS-369): the vocabulary the plan
428 /// args and the renderers spell, single-sourced here.
429 pub fn as_str(self) -> &'static str {
430 match self {
431 StartReason::BoundPivot => "bound-pivot",
432 StartReason::Cheapest => "cheapest",
433 StartReason::SeekAnchored => "seek-anchored",
434 StartReason::IndexZero => "index-0",
435 }
436 }
437}
438
439/// Which rung served one `MATCH` clause (LABS-1117): the fact EXPLAIN
440/// could not show, because the rungs are runtime choices inside an
441/// operator, not plan nodes. The ladder records it per clause; the
442/// PROFILE record carries it. [`Walker`](Self::Walker) is the per-row
443/// walker, the rung every decline's home — the batch scan/filter chain
444/// is its own fact (`ClauseMetricsRecord::batched`), never a rung here.
445#[derive(Clone, Copy, Debug, PartialEq, Eq)]
446pub enum KernelRung {
447 /// The unrolled fixed-k chain kernel, `hops` hops (ADR-0473).
448 Chain { hops: usize },
449 /// The hub-star candidate-intersection kernel (ADR-0473).
450 HubStar,
451 /// The frontier-NFA rung over the BFS (ADR-0478).
452 FrontierNfa,
453 /// The per-row walker — every gate's decline.
454 Walker,
455}
456
457impl KernelRung {
458 /// The rung's stable wire name (the `StartReason::as_str` pattern).
459 /// The names live in the wire vocabulary (`KernelRungWire`'s
460 /// constants), so the executor and every surface spell them once; the
461 /// variant↔name mapping is pinned by `relate`'s
462 /// `decline_and_start_reason_names_match_the_wire_tables`.
463 pub fn as_str(self) -> &'static str {
464 match self {
465 KernelRung::Chain { .. } => relate_model::wire::KernelRungWire::CHAIN,
466 KernelRung::HubStar => relate_model::wire::KernelRungWire::HUB_STAR,
467 KernelRung::FrontierNfa => relate_model::wire::KernelRungWire::FRONTIER_NFA,
468 KernelRung::Walker => relate_model::wire::KernelRungWire::WALKER,
469 }
470 }
471}
472
473/// The frontier rung's run-time declines (ADR-0516): the reasons a rung
474/// that engaged and ran still falls through, typed so the PROFILE record
475/// names the one that kept the DFS. The compile-time gates' own
476/// vocabulary (`frontier_match::FrontierDecline`) stays with the
477/// matcher that constructs it — every one of those decides before a
478/// single walk, and none rides the record. Lives here — the crate's
479/// lowest shared module — beside the other PROFILE vocabularies
480/// (`StartReason`): the rider wiring records it and the metric record
481/// carries it. Two today: the re-arrival budget's exhaustion (ADR-0516)
482/// and the sparse tables' allocation ceiling (ADR-0521); a later
483/// run-time decline adds its variant (and its wire name) here.
484#[derive(Debug, Clone, Copy, PartialEq, Eq)]
485pub enum FrontierRunDecline {
486 /// The re-arrival rule's shared work budget cut a search — the
487 /// endpoint set is unproven, so the run's buffered rows are
488 /// discarded and the clause falls through to the next rung
489 /// unchanged (the DFS answers these shapes exactly). Constructed on
490 /// the production decline path — the run's outcome carries it
491 /// (`frontier::RunOutcome::Declined`) and the rider wiring records
492 /// it for the PROFILE record.
493 RearrivalBudget,
494 /// The run's sparse tables — sized by the (node, state) pairs it
495 /// touched, never by the store's node-id span — plus the re-arrival
496 /// rule's buffers crossed the allocation ceiling
497 /// (`FRONTIER_TABLE_BUDGET`, ADR-0521) at a level boundary. A
498 /// run-time decline like [`Self::RearrivalBudget`] — the rung ran, so
499 /// its counters stay recorded beside the reason — never a compile
500 /// gate: the run's buffered rows are discarded and the DFS, with its
501 /// own caps, answers the clause.
502 TableBudget,
503}
504
505impl FrontierRunDecline {
506 /// Every run-time decline, in declaration order — the parity pin's
507 /// iteration source against the wire table
508 /// (`plan_keys::DECLINE_REASONS`).
509 pub const ALL: [FrontierRunDecline; 2] = [
510 FrontierRunDecline::RearrivalBudget,
511 FrontierRunDecline::TableBudget,
512 ];
513
514 /// The decline's stable wire name (the `StartReason::as_str` pattern):
515 /// the vocabulary the plan args and the renderers spell,
516 /// single-sourced here.
517 pub fn as_str(self) -> &'static str {
518 match self {
519 FrontierRunDecline::RearrivalBudget => "rearrival-budget",
520 FrontierRunDecline::TableBudget => "table-budget",
521 }
522 }
523}
524
525/// One clause operator's PROFILE metrics, reported to the sink (ADR-0344
526/// phase 2 + the metric-fields phase): the position key `(stage, part,
527/// clause)` — the same walk the plan tree construction uses — beside the
528/// operator's actuals. Bundled so the sink signature stays at one
529/// argument however many metrics a later phase adds.
530pub struct ClauseMetricsRecord {
531 /// The NEXT-chain position (1-based, matching the tree's stage
532 /// numbering): each NEXT stage restarts its part indices at 0, so the
533 /// stage keeps the keys disjoint — without it a chained statement's
534 /// later stage overwrites the earlier stage's entries.
535 pub stage: usize,
536 pub part: usize,
537 pub clause: usize,
538 /// Rows the operator produced.
539 pub rows: u64,
540 /// Row-materialization bytes: the summed logical size
541 /// (`Value::logical_bytes`, ADR-0042, plus each key's string bytes)
542 /// of the rows the operator produced. Stateful operators'
543 /// non-row state (aggregation tables, sort buffers) is a follow-up.
544 pub memory_bytes: u64,
545 /// Expression allocation bytes the clause's arm charged against the
546 /// ADR-0463 statement budget — the delta of the view's expression
547 /// counter across the arm, the same snapshot/delta shape as
548 /// [`ClauseMetricsRecord::db_hits`]. Zero for a clause that builds no
549 /// containers or strings.
550 pub expression_built_bytes: u64,
551 /// The operator's elapsed time, nanoseconds.
552 pub time_ns: u128,
553 /// The store-read mix behind [`ClauseMetricsRecord::db_hits`]
554 /// (LABS-369): hops vs neighbor walks vs node reads.
555 pub reads: StoreReads,
556 /// The clause's inclusive phase times (LABS-448): the seek (candidate
557 /// resolution and checks) and the walk (relationship traversal),
558 /// stamped only while a PROFILE statement's arm runs — a non-PROFILEd
559 /// statement's record carries zeros.
560 pub phases: PhaseTimes,
561 /// How the walk chose its start, when the clause ran a `MATCH` walk
562 /// (LABS-369) — `None` for clauses that walk nothing.
563 pub start: Option<WalkStart>,
564 /// Which rung served the clause's `MATCH` walk (LABS-1117): the
565 /// chain kernel, the hub-star kernel, the frontier-NFA rung, or the
566 /// per-row walker — the operator the clause's `MATCH` ladder (or, for
567 /// a `SEARCH` `MATCH`, its direct walker call) returned. `None`
568 /// exactly when no `MATCH` operator ran: a non-`MATCH` clause; a
569 /// `MATCH` a fold answered (`try_match_folds`, a boolean or walk
570 /// count); a `MATCH` inside a nested evaluation (its own loop); and a
571 /// `MATCH` the ADR-0468 batch chain answered — that operator is
572 /// [`Self::batched`]'s own fact, never a traversal rung.
573 pub kernel: Option<KernelRung>,
574 /// Whether the clause ran ADR-0468's batch scan/filter/project chain
575 /// over `Chunk` (LABS-359) — the PROFILE-visible fact that a
576 /// scan-shaped `MATCH` interior executed as batch operators. `false`
577 /// is every other clause, and every clause the chain declined.
578 pub batched: bool,
579 /// The batch filter's zone skips (LABS-645): how many conjunct-batch
580 /// evaluations the chunk's derived min/max zone metadata provably
581 /// replaced with the correct empty survivor set. `0` on every clause
582 /// the chain declined and every clause that skipped nothing.
583 pub zone_skips: u64,
584 /// The frontier family's run counters (ADR-0478): the BFS's edge
585 /// visits, completed levels, and accepted endpoints, summed over the
586 /// clause's per-seed runs. Zero on every clause the frontier's
587 /// compile gates declined (it never ran); a run-time decline
588 /// (`frontier_decline` set) keeps them recorded, since the rung did
589 /// run. The plan table's `Details` cell marks the operator
590 /// (`[frontier edges=N levels=L endpoints=P]`) when it ran.
591 pub frontier: FrontierCounters,
592 /// The frontier rung's run-time decline (ADR-0516), when it engaged,
593 /// ran, and fell through — `None` on every clause that never
594 /// declined and on every compile-gate decline (which never ran). The
595 /// typed reason the PROFILE record carries beside the run counters:
596 /// the re-arrival budget's exhaustion or the table ceiling's crossing.
597 pub frontier_decline: Option<FrontierRunDecline>,
598}
599
600/// Per-clause PROFILE metrics sink (ADR-0344 phase 2): the dispatch loop
601/// reports each statement-level clause operator's metrics once it
602/// finishes, keyed `(stage, part, clause)` — the same walk the plan tree
603/// construction uses, so the collected entries stamp onto the PROFILE
604/// result's plan tree without a second mapping.
605pub trait PlanMetricsSink {
606 /// The record's `stage` is the NEXT-chain position (1-based, matching
607 /// the tree's stage numbering): each NEXT stage restarts its part
608 /// indices at 0, so the stage keeps the keys disjoint — without it a
609 /// chained statement's later stage overwrites the earlier stage's
610 /// entries.
611 fn record_clause(&self, record: ClauseMetricsRecord);
612}
613
614/// Per-batch commit sink for `CALL { … } IN TRANSACTIONS` (ADR-0210).
615/// Called by the executor after each successful batch with the batch's
616/// drained redo ops and the snapshot timestamp they were built against;
617/// the implementation commits them durably (WAL + apply) before the next
618/// batch starts, so live scratch state stays bounded by one batch.
619/// Returns the commit timestamp the batch was applied at — the caller
620/// rebases its scratch onto it, so only the sink (which owns the commit)
621/// ever reads the base graph's clock.
622pub trait BatchCommit {
623 fn commit_batch(&self, ops: Vec<RedoOp>, snapshot_ts: u64) -> Result<u64>;
624}
625
626impl<'a> QueryCtx<'a> {
627 pub(crate) fn new(cypher_version: Option<u32>, query_text: &'a str) -> Self {
628 Self {
629 cypher_version,
630 query_text,
631 principal: None,
632 batch_commit: None,
633 }
634 }
635
636 /// ADR-0273: attach the connection's authenticated principal.
637 pub(crate) fn with_principal(mut self, principal: Option<&'a str>) -> Self {
638 self.principal = principal;
639 self
640 }
641
642 /// ADR-0210: attach the per-batch commit sink.
643 pub(crate) fn with_batch_commit(mut self, sink: Option<&'a dyn BatchCommit>) -> Self {
644 self.batch_commit = sink;
645 self
646 }
647
648 /// True when the statement carried an explicit `CYPHER 5` preamble.
649 pub(crate) fn is_cypher5(&self) -> bool {
650 is_cypher5(self.cypher_version)
651 }
652}
653
654/// The dialect fact on its own ([`relate_core::is_cypher5`]): the free
655/// form lets `cypher_version` threading points that hold no [`QueryCtx`]
656/// read the same rule.
657pub(crate) use relate_core::is_cypher5;
658
659/// Graph view + query parameters shared by clause execution and evaluation.
660/// `cypher_version` is the enclosing statement's CIP-150 preamble: expression
661/// subqueries (EXISTS/COUNT/COLLECT) lowered with `Query::cypher_version: None`
662/// observe it at evaluation time. `principal` is the connection's
663/// authenticated principal (ADR-0273), read by the `dbms.showCurrentUser`
664/// procedure arm; `None` when the surface set none.
665#[derive(Clone, Copy)]
666pub(crate) struct ExecCtx<'a> {
667 pub graph: &'a ExecGraph<'a>,
668 pub params: &'a BTreeMap<String, Value>,
669 pub cypher_version: Option<u32>,
670 pub principal: Option<&'a str>,
671}
672
673impl<'a> ExecCtx<'a> {
674 pub(crate) fn new(
675 graph: &'a ExecGraph<'a>,
676 params: &'a BTreeMap<String, Value>,
677 cypher_version: Option<u32>,
678 ) -> Self {
679 Self {
680 graph,
681 params,
682 cypher_version,
683 principal: None,
684 }
685 }
686
687 /// ADR-0273: attach the connection's authenticated principal.
688 pub(crate) fn with_principal(mut self, principal: Option<&'a str>) -> Self {
689 self.principal = principal;
690 self
691 }
692}
693
694/// Expression-evaluation context: graph view, current row, parameters, and
695/// the enclosing statement's CIP-150 `cypher_version` (see [`ExecCtx`]).
696#[derive(Clone, Copy)]
697pub(crate) struct EvalCtx<'a> {
698 pub graph: &'a ExecGraph<'a>,
699 pub row: &'a Row,
700 pub params: &'a BTreeMap<String, Value>,
701 pub cypher_version: Option<u32>,
702}