relate_executor/ctx.rs
1//! Shared execution-context parameter objects threaded through clause
2//! execution and expression evaluation — plus the PROFILE phase clocks (LABS-448) the phase wrappers stamp. The
3//! pattern-walk vocabulary both walk engines (eval, exec) share —
4//! bindings, hop bounds, stub binders, path-walk carriers — lives one
5//! module over, [`crate::pattern_walk`] (LABS-668).
6
7use std::cell::Cell;
8use std::collections::BTreeMap;
9use std::thread::LocalKey;
10
11use relate_core::{Result, Value};
12use web_time::Instant;
13
14use crate::metrics::PhaseTimes;
15use crate::overlay::ExecGraph;
16use crate::redo::RedoOp;
17use crate::row::Row;
18
19/// Statement-level context threaded through clause execution: the
20/// statement's source text (which feeds `SHOW TRANSACTIONS`'
21/// `currentQuery` column) and the connection's authenticated principal
22/// (ADR-0273: set by a surface that verified an identity — the Bolt server
23/// after a validated HELLO — else `None`). The principal is display-only;
24/// both readers (`dbms.showCurrentUser`, `SHOW TRANSACTIONS`) render it
25/// through `exec::catalog::principal_cell`, each passing the placeholder its command
26/// documents for an unauthenticated connection.
27#[derive(Clone, Copy)]
28pub(crate) struct QueryCtx<'a> {
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 PROFILE phase clocks (LABS-448) — the thread-locals behind
39// [`PhaseTimes`] and the wrappers every walker stamps through. They live
40// here, the crate's lowest shared module, so both walk engines (eval,
41// exec) read them downward (LABS-668): the eval walkers' phase spans made
42// the old home beside the exec-only counters (`exec/profiling`) an upward
43// import for `eval`. The clocks and their stamp body stay private to this
44// module: the stamp→run→count pairing is the wrappers' implementation
45// detail, never an API a walker could hand-roll beside them.
46thread_local! {
47 /// Whether a PROFILE statement's clause arm is running (LABS-448) —
48 /// the phase stamps read this before touching the clock, so a
49 /// non-PROFILEd statement pays the thread-local read and nothing
50 /// else. Armed by the clause's metric tick, disarmed by its drop.
51 static PHASE_PROFILING: Cell<bool> = const { Cell::new(false) };
52 /// The inclusive seek-phase sum (LABS-448): the elapsed time
53 /// resolving and checking node candidates — the store work behind the
54 /// `Nodes` kind. Inclusive like the table's `Total` column: a walk
55 /// that triggers nested seeks counts both.
56 static SEEK_NS: Cell<u128> = const { Cell::new(0) };
57 /// The inclusive walk-phase sum (LABS-448): the elapsed time following
58 /// relationships — the store work behind the `Rels`/`Degree` kinds.
59 static WALK_NS: Cell<u128> = const { Cell::new(0) };
60}
61
62/// Arm the phase stamps for a PROFILE clause arm (LABS-448) — the metric
63/// tick's first act, undone by its drop, so the stamps never run outside a
64/// profiled statement.
65pub(crate) fn arm_phase_profiling() {
66 PHASE_PROFILING.with(|c| c.set(true));
67}
68
69/// Disarm the phase stamps (LABS-448) — the metric tick's last act.
70pub(crate) fn disarm_phase_profiling() {
71 PHASE_PROFILING.with(|c| c.set(false));
72}
73
74/// The one phase-span body both wrappers delegate to (LABS-448; one
75/// spelling since LABS-668's stellar round): take the stamp, run the
76/// work, count its elapsed time into `sum`. The stamp is this helper's
77/// local — taken only while a PROFILE statement's arm runs, so a
78/// non-PROFILEd statement pays the one thread-local read and nothing
79/// else, and a `None` stamp counts nothing. A run that errors counts
80/// nothing either: the arm's `time_ns` covers what the phases do not.
81fn phase_span<T>(sum: &'static LocalKey<Cell<u128>>, run: impl FnOnce() -> Result<T>) -> Result<T> {
82 let stamp = PHASE_PROFILING.with(Cell::get).then(Instant::now);
83 let out = run()?;
84 if let Some(start) = stamp {
85 sum.with(|c| c.set(c.get() + start.elapsed().as_nanos()));
86 }
87 Ok(out)
88}
89
90/// One seek-phase span around a pattern node's candidate resolution
91/// (LABS-448). Since the PR-604 stellar round the stamp is the counted
92/// funnel's, not a per-walker obligation: `node_candidates`
93/// (`crate::pattern_walk`, the shared walk tier) resolves through this —
94/// the one caller — so the seek stamp lives beside the read count it
95/// pairs with and every path that bumps the `Nodes` counter (both walk
96/// engines' candidate reads) carries seek time, never a re-stamped copy
97/// per walker. `None` stamps (non-PROFILEd statements) resolve unchanged.
98pub(crate) fn phase_seek<T>(resolve: impl FnOnce() -> Result<T>) -> Result<T> {
99 phase_span(&SEEK_NS, resolve)
100}
101
102/// One walk-phase span around a relationship traversal (LABS-448): the
103/// symmetric spelling of [`phase_seek`] over the walk clock — both
104/// delegate to the one span body, so the walker sites never hand-roll
105/// the stamp→run→count pairing, and the walk-phase contract (inclusive of
106/// nested phases) is stated once, here. `None` stamps resolve unchanged
107/// on non-PROFILEd statements.
108pub(crate) fn phase_walk<T>(walk: impl FnOnce() -> Result<T>) -> Result<T> {
109 phase_span(&WALK_NS, walk)
110}
111
112/// The phase-time sums right now (LABS-448), snapshotted at the clause
113/// tick the way the store-read mix (`exec::profiling::store_reads`) is:
114/// the delta across the arm is the clause's phase times, two thread-local
115/// reads per clause.
116pub(crate) fn phase_times() -> PhaseTimes {
117 PhaseTimes {
118 seek_ns: SEEK_NS.with(Cell::get),
119 walk_ns: WALK_NS.with(Cell::get),
120 }
121}
122
123// The node-store reads (LABS-375): one per candidate a node match
124// examined (the all-nodes scan, the label scan, the index seek) — the
125// scan work the hop/neighbor counters never see, because they count
126// relationship traversal only. It lives beside the phase clocks because
127// its one counting point is the node-candidate funnel
128// (`crate::pattern_walk::node_candidates`), which both walk engines read:
129// a counter with an engine's name on it would be an upward import from
130// the walk tier that bumps it.
131thread_local! {
132 static NODE_READS: Cell<u64> = const { Cell::new(0) };
133}
134
135/// Count `count` node-store reads (LABS-375) — batched because the one
136/// funnel yields the whole candidate list at once, and every node-match
137/// path reads it.
138pub(crate) fn count_node_reads(count: u64) {
139 NODE_READS.with(|c| c.set(c.get() + count));
140}
141
142/// The node-read total right now — read by the store-read mix
143/// ([`crate::exec::profiling::store_reads`]) at clause boundaries, so a
144/// per-clause delta costs one thread-local read, never a per-row one.
145pub(crate) fn node_reads() -> u64 {
146 NODE_READS.with(Cell::get)
147}
148
149/// Take the node-read total, leaving zero — the test-side snapshot the
150/// store-read pins assert against.
151#[cfg(test)]
152pub(crate) fn take_node_reads() -> u64 {
153 NODE_READS.with(|c| c.replace(0))
154}
155
156/// Per-batch commit sink for `CALL { … } IN TRANSACTIONS` (ADR-0210).
157/// Called by the executor after each successful batch with the batch's
158/// drained redo ops and the snapshot timestamp they were built against;
159/// the implementation commits them durably (WAL + apply) before the next
160/// batch starts, so live scratch state stays bounded by one batch.
161/// Returns the commit timestamp the batch was applied at — the caller
162/// rebases its scratch onto it, so only the sink (which owns the commit)
163/// ever reads the base graph's clock.
164pub trait BatchCommit {
165 fn commit_batch(&self, ops: Vec<RedoOp>, snapshot_ts: u64) -> Result<u64>;
166}
167
168impl<'a> QueryCtx<'a> {
169 pub(crate) fn new(query_text: &'a str) -> Self {
170 Self {
171 query_text,
172 principal: None,
173 batch_commit: None,
174 }
175 }
176
177 /// ADR-0273: attach the connection's authenticated principal.
178 pub(crate) fn with_principal(mut self, principal: Option<&'a str>) -> Self {
179 self.principal = principal;
180 self
181 }
182
183 /// ADR-0210: attach the per-batch commit sink.
184 pub(crate) fn with_batch_commit(mut self, sink: Option<&'a dyn BatchCommit>) -> Self {
185 self.batch_commit = sink;
186 self
187 }
188}
189
190/// Graph view + query parameters shared by clause execution and evaluation.
191/// `principal` is the connection's authenticated principal (ADR-0273), read
192/// by the `dbms.showCurrentUser` procedure arm; `None` when the surface set
193/// none.
194#[derive(Clone, Copy)]
195pub(crate) struct ExecCtx<'a> {
196 pub graph: &'a ExecGraph<'a>,
197 pub params: &'a BTreeMap<String, Value>,
198 pub principal: Option<&'a str>,
199}
200
201impl<'a> ExecCtx<'a> {
202 pub(crate) fn new(graph: &'a ExecGraph<'a>, params: &'a BTreeMap<String, Value>) -> Self {
203 Self {
204 graph,
205 params,
206 principal: None,
207 }
208 }
209
210 /// ADR-0273: attach the connection's authenticated principal.
211 pub(crate) fn with_principal(mut self, principal: Option<&'a str>) -> Self {
212 self.principal = principal;
213 self
214 }
215}
216
217/// Expression-evaluation context: graph view, current row, and parameters.
218#[derive(Clone, Copy)]
219pub(crate) struct EvalCtx<'a> {
220 pub graph: &'a ExecGraph<'a>,
221 pub row: &'a Row,
222 pub params: &'a BTreeMap<String, Value>,
223}