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