relate_executor/exec/mod.rs
1//! Query execution entry points, plan folding, and the `exec/` submodule
2//! wiring.
3
4use std::collections::BTreeMap;
5
6use relate_core::{CancelToken, Error, QueryClockGuard, Result, Value};
7use relate_ir::{Clause, LabelExpr};
8use relate_names::{SmallName, Token};
9use relate_planner::{clause_mutates_store, clause_projects_rows, plan_any_clause, LogicalPlan};
10
11use crate::metrics::{PlanMetricsSink, PlanMetricsSite};
12
13use crate::row::Row;
14
15// The instrumentation cluster (LABS-448's extraction) — one private
16// module, re-exported here so the walkers' `super::` paths keep working:
17// the store-read counters and the walk-start slot. The phase clocks live
18// in `crate::ctx` (LABS-668), the lowest module both walk engines share.
19mod profiling;
20use crate::graph::{Graph, QueryStats, SchemaSnapshot};
21use crate::overlay::ExecGraph;
22use crate::procedure_registry::call_writes_store;
23use crate::StatementEffect;
24pub(crate) use profiling::{
25 arm_store_profiling, count_frontier, count_neighbor_walks, count_zone_skip, record_memos,
26 record_walk_start, restore_store_profiling, take_walk_start, DeltaSnapshot, StageDelta,
27 WalkStartSwap, WalkTallies,
28};
29#[cfg(test)]
30pub(crate) use profiling::{
31 disarm_store_profiling, memo_counters, take_frontier_counters, take_hop_expands,
32 take_neighbor_walks, take_node_reads, take_zone_skips,
33};
34
35pub(crate) mod agg_fold;
36pub(crate) mod aggregate;
37pub(crate) mod batch;
38pub(crate) mod batch_tail;
39pub(crate) mod bulk;
40pub(crate) mod call;
41pub(crate) mod candidates;
42pub(crate) mod catalog;
43pub(crate) mod catalog_schema;
44pub(crate) mod catalog_show;
45pub(crate) mod create_admission;
46// ADR-0468's SoA chunk type layer: the types, the conversion, and the
47// operator-serving constructions the batch chain (exec/batch.rs) reads.
48pub(crate) mod chunk;
49pub(crate) mod classification;
50mod clause_arms;
51pub(crate) mod compose;
52pub(crate) mod constraint_validation;
53pub(crate) mod create;
54pub(crate) mod ddl;
55pub(crate) mod ddl_notifications;
56pub(crate) mod ddl_options;
57pub(crate) mod dispatch;
58pub(crate) mod exists_probe;
59pub(crate) mod expand;
60pub(crate) mod far_probe;
61pub(crate) mod feed;
62pub(crate) mod fulltext;
63pub(crate) mod gpm;
64pub(crate) mod graph_type_schema;
65mod load_csv;
66mod match_arm;
67mod profile_chain;
68mod profile_tick;
69// The LABS-348 hub join — the whole family (gate, join, row-shape
70// helpers, test hooks), invoked by the driver at its pattern-0→
71// pattern-1 boundary (`match_clause::match_paths`) over the caller's
72// own pattern-0 rows.
73pub(crate) mod hub_join;
74// ADR-0473 (LABS-644): the contracted traversal kernels — structural
75// matcher, cost gate, chain and hub-star operators over the substrate.
76pub(crate) mod kernels;
77pub(crate) mod match_cap;
78pub(crate) mod match_chain;
79pub(crate) mod match_clause;
80pub(crate) mod match_consumer;
81pub(crate) mod match_folds;
82pub(crate) mod named_path;
83// The one engine fork (`match_one_path`) every per-path consumer routes
84// through — the driver's pattern loop (match_clause), the hub join's
85// plain-side enumeration, and the exists probe's dispatch — hoisted
86// beside `expand` so every consumer imports it downward.
87pub(crate) mod one_path;
88pub(crate) mod order;
89pub(crate) mod pattern_policies;
90pub(crate) mod pivot;
91pub(crate) mod post_merge;
92pub(crate) mod predicate_spec;
93pub(crate) mod procedure_rows;
94pub(crate) mod procedures;
95pub(crate) mod project;
96pub(crate) mod property_defaults;
97pub(crate) mod pushdown;
98pub(crate) mod rel_seek;
99pub(crate) mod rider;
100pub(crate) mod scope;
101pub(crate) mod search;
102pub(crate) mod search_filters;
103pub(crate) mod shortest_eval;
104pub(crate) mod sink;
105mod stats_short_circuit;
106pub(crate) mod subquery_eval;
107pub(crate) mod top_k;
108pub(crate) mod union;
109pub(crate) mod unwind;
110pub(crate) mod vector;
111pub(crate) mod write;
112
113pub use catalog_show::catalog_create_statements;
114
115/// The read path's one rejection policy: the message a `ClauseMode::Read`
116/// clause loop refuses `c` with, or `None` to dispatch it. The dispatcher
117/// asks once per clause, before its clause match.
118///
119/// The table is the planner's published per-clause answer
120/// ([`clause_mutates_store`], catalog commands included: the `SHOW` family is
121/// a read, a catalog DDL command is a write) plus the two shapes this layer
122/// decides: `FOREACH` names itself, and `CALL { … } IN TRANSACTIONS` needs a
123/// write transaction. A catalog write reaching a read run is therefore a
124/// typed rejection, not a write that only the read-only scratch's panic
125/// backstops.
126///
127/// The name states the policy, not a clause classification: it answers "does
128/// the read path reject this clause, and with what message?", which is
129/// narrower than the mutation question the composition rules ask
130/// ([`mutates_store`]).
131pub(crate) fn read_path_rejection(c: &Clause) -> Option<&'static str> {
132 match c {
133 Clause::Foreach { .. } => Some("internal: FOREACH on read path"),
134 Clause::CallSubquery {
135 in_transactions: Some(_),
136 ..
137 } => Some("internal: CALL IN TRANSACTIONS requires a write transaction"),
138 other if clause_mutates_store(other) => Some("internal: write clause on read path"),
139 _ => None,
140 }
141}
142
143/// Whether one clause mutates the store — the per-clause form of
144/// [`plan_mutates_store`], shared with the composition rules that ask the
145/// mutation question rather than the read-admission one. The two answers
146/// this layer decides below the planner table live here:
147///
148/// - `LOAD CSV` is `Write` in the clause table (write-*routed* by the
149/// conservative access fold, ADR-0332) but only reads a file;
150/// - a `CALL` is the procedure registry's writes flag
151/// ([`call_writes_store`]) — a registered procedure is a static row table
152/// and cannot mutate the store.
153pub(crate) fn mutates_store(clause: &Clause) -> bool {
154 match clause {
155 Clause::LoadCsv { .. } => false,
156 Clause::Call { name, .. } => name.with_str(call_writes_store),
157 other => clause_mutates_store(other),
158 }
159}
160
161/// Whether `plan` holds a mutation operator — the statement's ADR-0402
162/// Decision 2 write-attempt fact, recorded once at statement entry (before
163/// any rows flow) through the canonical plan walk
164/// (`relate_planner::plan_any_clause` over `walk_plan_clauses`): every
165/// part, every `NEXT` stage, and every nested body the walk descends into
166/// (`CALL { … }`, `WHEN`/`ELSE`, `FOREACH` bodies, expression subqueries). A
167/// write inside a body that never dispatches — an empty driving row set, an
168/// untaken branch — is therefore still an attempt, which is the same
169/// short-circuit the empty top-level pipeline is made of. Both statement
170/// boundaries that name an effect record it here — the write path and the
171/// read admission — so the fact has one source on every route.
172///
173/// The planner's [`clause_mutates_store`] answers each clause; the two shapes
174/// whose answer lives at this layer are decided by [`mutates_store`], which
175/// this walk applies clause by clause.
176pub(crate) fn plan_mutates_store(plan: &LogicalPlan) -> bool {
177 plan_any_clause(plan, &mut mutates_store)
178}
179
180/// Record on the statement's view every name the plan declares — the one
181/// per-clause vocabulary ([`scope::clause_declared_names`]) folded
182/// cumulatively over the same canonical plan walk
183/// ([`plan_mutates_store`]'s `plan_any_clause`), nested bodies (`CALL { … }`,
184/// `FOREACH`, expression subqueries) included, so the set is complete
185/// before any clause runs and does not depend on which body has run. A
186/// name declared only in a nested body is therefore declared
187/// statement-wide; no synthetic column can carry it, because every
188/// synthetic prefix is chosen past the declared set
189/// ([`ExecGraph::uncolliding_prefix`]). Cumulative: a name dropped by a
190/// later `WITH` stays declared, since rows between the two still carry it.
191/// Called only by [`ExecGraph::begin_statement`], so the reset and this
192/// seeding are one operation no entry can split.
193pub(crate) fn declare_plan_names(graph: &ExecGraph<'_>, plan: &LogicalPlan) {
194 plan_any_clause(plan, &mut |clause| {
195 let names = scope::clause_declared_names(clause);
196 graph.declare_names(names.iter().map(String::as_str));
197 false
198 });
199}
200
201use constraint_validation::validate_constraints;
202use dispatch::{execute_part_read_seeded, run_clauses};
203use scope::visible_keys;
204pub(crate) use shortest_eval::{eval_shortest, ShortestWant};
205pub(crate) use subquery_eval::{eval_collect_query, eval_count_query, eval_exists_query};
206
207use crate::ctx::QueryCtx;
208
209/// The lowering duplicates a static label/type list into a `LabelExpr`
210/// (`labels`/`types` carry the same names). A label expression is
211/// batch-safe exactly when it is a tree of static `Label` leaves over
212/// precisely those names — no wildcards, dynamics, or negation.
213/// Hoisted from `exec/bulk.rs` (round 4, F-4-1): the static-mirror
214/// discrimination the bulk-write recognizer and the count-only shape
215/// recognizer share — one canonical helper per policy.
216pub(crate) fn static_label_tree(expr: &LabelExpr, names: &[(SmallName, Token)]) -> bool {
217 fn leaves<'a>(expr: &'a LabelExpr, out: &mut Vec<&'a SmallName>) -> bool {
218 match expr {
219 LabelExpr::Label(name) => {
220 out.push(name);
221 true
222 }
223 LabelExpr::And(parts) | LabelExpr::Or(parts) => {
224 parts.iter().all(|part| leaves(part, out))
225 }
226 _ => false,
227 }
228 }
229 let mut found = Vec::new();
230 leaves(expr, &mut found)
231 && found.len() == names.len()
232 && found
233 .iter()
234 .all(|name| names.iter().any(|(n, _)| n == *name))
235}
236
237/// Whether an optional label expression is absent or static-matches
238/// `names` — the one gate every label-expression-accepting recognizer
239/// consults: gate on static-vs-dynamic, never on presence (round 4,
240/// F-4-1/F-4-2: the raw front-lowered shape carries the static mirror,
241/// and a presence gate would decline real pipeline shapes).
242pub(crate) fn label_expr_ok(expr: &Option<LabelExpr>, names: &[(SmallName, Token)]) -> bool {
243 expr.as_ref().is_none_or(|e| static_label_tree(e, names))
244}
245
246pub struct QueryResult {
247 pub columns: Vec<String>,
248 pub rows: Vec<Vec<Value>>,
249 pub stats: QueryStats,
250 /// The engine's truthful write effect for this statement (ADR-0402
251 /// Decision 2), named once at the statement boundary from two execution
252 /// facts: whether the statement's plan holds a mutation operator (the one
253 /// plan walk, [`plan_mutates_store`]) and whether any change reached the
254 /// write redo since the statement's entry reset. A read therefore carries
255 /// [`StatementEffect::None`]. Results built *inside* a statement (a
256 /// clause's rows, a nested body's output) go through the crate-private
257 /// `QueryResult::intermediate` and never spell this field: the boundary is
258 /// the one place that names it. See [`StatementEffect`] for why neither
259 /// the plan's query type nor the mutation counters can answer this.
260 pub effect: StatementEffect,
261}
262
263impl QueryResult {
264 /// A result a statement boundary finished, its effect named by the
265 /// execution that produced it — the construction for a crate outside this
266 /// one (the ADR-0209 batched bulk write is its own statement boundary and
267 /// runs no clause loop). The effect always comes from
268 /// [`StatementEffect`]'s own constructors, so a caller never spells a
269 /// zero state at the construction site.
270 pub fn finished(
271 columns: Vec<String>,
272 rows: Vec<Vec<Value>>,
273 stats: QueryStats,
274 effect: StatementEffect,
275 ) -> Self {
276 Self {
277 columns,
278 rows,
279 stats,
280 effect,
281 }
282 }
283
284 /// A result built *inside* a statement — a clause's rows, a nested
285 /// body's output, a finishing projection — before the boundary names its
286 /// effect.
287 ///
288 /// The effect starts as the unstamped read state; the statement boundary
289 /// ([`execute`] on the write path, `execute_read_at` on the read path) is
290 /// the one place that names it from the execution's own facts. Routing
291 /// every intermediate construction through this constructor is what keeps
292 /// a placeholder out of the construction sites: no clause can hand a
293 /// surface an effect that claims a write applied nothing.
294 pub(crate) fn intermediate(
295 columns: Vec<String>,
296 rows: Vec<Vec<Value>>,
297 stats: QueryStats,
298 ) -> Self {
299 Self::finished(columns, rows, stats, StatementEffect::None)
300 }
301
302 /// CIP-159's empty unit result — no columns, no rows, default stats —
303 /// the one spelling of the terminal-void answer.
304 pub(crate) fn unit() -> Self {
305 Self::intermediate(Vec::new(), Vec::new(), QueryStats::default())
306 }
307}
308
309/// The plan, parameters, source text, and authenticated principal shared by
310/// every execution entry point. `query_text` is the source text of the
311/// statement (exposed as `SHOW TRANSACTIONS`' `currentQuery` column); the
312/// statement's CIP-150 version preamble rides on the plan. `principal` is the
313/// connection's authenticated principal (ADR-0273), read by
314/// `dbms.showCurrentUser`; `None` reports the documented placeholder.
315/// `Copy`: every field is a reference (or an optional reference) — the
316/// commit path reuses the caller's request with its own batch-commit
317/// sink attached, without rebuilding the bundle field by field.
318#[derive(Clone, Copy)]
319pub struct ExecRequest<'a> {
320 pub plan: &'a LogicalPlan,
321 pub params: &'a BTreeMap<String, Value>,
322 pub query_text: &'a str,
323 pub principal: Option<&'a str>,
324 /// ADR-0210: per-batch durable-commit sink for `CALL { … } IN
325 /// TRANSACTIONS`; `None` keeps the accumulate-to-statement-end
326 /// behavior.
327 pub batch_commit: Option<&'a dyn crate::ctx::BatchCommit>,
328 /// ADR-0344 phase 2: the PROFILE metrics sink for the statement's own
329 /// clauses; `None` on every non-PROFILE run. The dispatch loop
330 /// records one entry per clause operator; nested execution strips it.
331 pub plan_metrics: Option<&'a dyn crate::metrics::PlanMetricsSink>,
332}
333
334impl<'a> ExecRequest<'a> {
335 /// The None-default request: no principal, no batch-commit sink, no
336 /// PROFILE sink — the statement's own execution with none of the
337 /// optional carriers. The one construction site for the defaults, so
338 /// a new optional field lands here, not at every caller.
339 pub fn new(
340 plan: &'a LogicalPlan,
341 params: &'a BTreeMap<String, Value>,
342 query_text: &'a str,
343 ) -> Self {
344 Self {
345 plan,
346 params,
347 query_text,
348 principal: None,
349 batch_commit: None,
350 plan_metrics: None,
351 }
352 }
353}
354
355/// A read admitted at a caller-pinned timestamp: the `graph`, the pinned
356/// `snapshot_ts`, and the `schema` captured together with that pin under the
357/// publication read guard, plus the `request` to run and its optional
358/// cooperative cancellation token (ADR-0111; `None` is never cancelled).
359pub struct ReadAdmission<'a> {
360 pub graph: &'a Graph,
361 pub snapshot_ts: u64,
362 pub schema: &'a SchemaSnapshot,
363 pub request: ExecRequest<'a>,
364 pub cancel: Option<&'a CancelToken>,
365 /// The store's ontology document (verbatim) captured at admission
366 /// (ADR-0121 §3, ADR-0227): attached to the read view like `cancel`
367 /// and read by `db.ontology.get` / `db.ontology.apply`; `None` when
368 /// the store holds no ontology.
369 pub ontology_document: Option<&'a str>,
370}
371
372/// The write boundary a batch of writes closes with, in order: the graph
373/// type's property default values, then the constraint validation. One
374/// home beside the write pipeline — the statement boundary
375/// ([`execute`]) and the `CALL { … } IN TRANSACTIONS` batch attempt both
376/// call it, so the two cannot drift.
377pub(crate) fn close_write_boundary(graph: &ExecGraph<'_>) -> Result<()> {
378 property_defaults::apply_property_defaults(graph)?;
379 validate_constraints(graph)
380}
381
382/// Execute a write-capable plan, then validate the constraints against what
383/// it wrote (ADR-0172). Each call starts a fresh CSV memo even when `graph`
384/// is reused across statements.
385pub fn execute(graph: &ExecGraph<'_>, request: &ExecRequest<'_>) -> Result<QueryResult> {
386 let (result, attempted) = run_statement(graph, request)?;
387 // CIP-262: the statement is this engine's transaction, so the graph
388 // type's property default values land at its boundary -- after the
389 // writes (the statement's own RETURN already saw null, CE1), before
390 // the post-statement constraint validation sees the defaulted
391 // properties like any other write. They are writes, so they land
392 // before the effect's applied fact is read (below).
393 close_write_boundary(graph)?;
394 finish_statement(result, graph, attempted)
395}
396
397/// [`execute`] without the constraint validation: the statement's writes
398/// stay in the redo slice the next `validate_constraints` checks. The
399/// executor's own tests drive this entry (`exec::test_support`); production
400/// always takes the validated one.
401///
402/// It is the same statement boundary, so it names the effect from its own two
403/// facts rather than handing back a placeholder: a caller that stops here
404/// still cannot read a read state off a statement that wrote.
405#[cfg(test)]
406pub(crate) fn execute_unvalidated(
407 graph: &ExecGraph<'_>,
408 request: &ExecRequest<'_>,
409) -> Result<QueryResult> {
410 let (result, attempted) = run_statement(graph, request)?;
411 finish_statement(result, graph, attempted)
412}
413
414/// The private un-finished runner every write statement entry shares: the
415/// per-statement resets, the entry checks, the entry facts, and the plan's
416/// execution. It never names the effect and never polls the token ledger —
417/// [`finish_statement`] does both, exactly once, so `execute` and
418/// `execute_unvalidated` cannot stamp a statement twice.
419///
420/// Returns the un-finished result and the statement's write-attempt fact
421/// ([`plan_mutates_store`]), recorded here before any rows flow and handed to
422/// [`finish_statement`] unchanged.
423fn run_statement(graph: &ExecGraph<'_>, request: &ExecRequest<'_>) -> Result<(QueryResult, bool)> {
424 let attempted = plan_mutates_store(request.plan);
425 // One statement entry: the per-statement resets and the declared-name
426 // seeding restart together (ADR-0309 stats + the ADR-0402 applied count,
427 // the ADR-0395 nested-evaluation budget, the spelled-name set).
428 graph.begin_statement(request.plan);
429 graph.check_cancelled()?;
430 let _clock = QueryClockGuard::within(graph.transaction_clock());
431 let qctx = QueryCtx::new(request.query_text)
432 .with_principal(request.principal)
433 .with_batch_commit(request.batch_commit);
434 let result = execute_plan_stage_seeded(
435 graph,
436 request.plan,
437 request.params,
438 vec![Row::new()],
439 qctx,
440 request.plan_metrics,
441 )?;
442 Ok((result, attempted))
443}
444
445/// Execute a read-only plan at the caller-pinned timestamp in `admission`
446/// without repinning. The caller must keep its `Graph::pin_now()` guard alive
447/// through this call so version GC cannot discard rows visible at
448/// `snapshot_ts`, and must capture `schema` alongside that pin while
449/// serializing with graph publication.
450///
451/// There is deliberately no graph-only wrapper that acquires both itself: the
452/// publication read guard lives on the embedded database's `Shared` state, not
453/// on a bare `Graph`, so such a wrapper could not capture the pin and schema
454/// atomically. Admission must happen under that guard at the caller.
455pub fn execute_read_at(admission: &ReadAdmission<'_>) -> Result<QueryResult> {
456 let view = ExecGraph::read_at(admission.graph, admission.snapshot_ts)
457 .with_schema(admission.schema)
458 .with_cancel(admission.cancel)
459 .with_ontology_document(admission.ontology_document);
460 view.check_cancelled()?;
461 // A read view carries no scratch, so the resets are vacuous and this
462 // call is the declared-name seeding — kept through the same one
463 // statement-entry operation every write entry takes, never a second
464 // spelling of it.
465 view.begin_statement(admission.request.plan);
466 let _clock = QueryClockGuard::new();
467 // A read admission records its write-attempt fact from the same canonical
468 // plan walk as every write entry — never a hardcoded "a read cannot
469 // write": a mutation operator reaching this route is still an attempt (the
470 // read-only scratch refuses to apply it). A read view applies nothing, so
471 // its applied count is the zero the admission starts with.
472 let attempted = plan_mutates_store(admission.request.plan);
473 // ADR-0395: the freshly constructed view carries a zeroed counter —
474 // the read admission's statement gets its own budget.
475 let qctx =
476 QueryCtx::new(admission.request.query_text).with_principal(admission.request.principal);
477 let mut result = execute_plan_read_seeded(
478 &view,
479 admission.request.plan,
480 admission.request.params,
481 vec![Row::new()],
482 qctx,
483 admission.request.plan_metrics,
484 )?;
485 result.stats = QueryStats::default();
486 finish_statement(result, &view, attempted)
487}
488
489/// Name the statement's effect and finish the result — the one assignment to
490/// [`QueryResult::effect`], and the one token-ledger poll. Every entry into a
491/// statement (the write path, the unvalidated path, a read admission) runs
492/// the un-finished runner and ends here exactly once, so no entry can return
493/// a fabricated effect for a statement that wrote, and none stamps twice.
494///
495/// The two facts are taken where they are known: `attempted` from the plan
496/// walk at statement entry, `applied` from the statement's own change count —
497/// zeroed by the same entry reset as the stats and grown by every redo push,
498/// so no baseline has to travel beside it.
499fn finish_statement(
500 mut result: QueryResult,
501 graph: &ExecGraph<'_>,
502 attempted: bool,
503) -> Result<QueryResult> {
504 result.effect = StatementEffect::from_facts(attempted, graph.applied_ops() > 0);
505 finish_tokens(result)
506}
507
508fn finish_tokens(result: QueryResult) -> Result<QueryResult> {
509 relate_core::tokens::poll()?;
510 Ok(result)
511}
512
513pub(crate) fn result_seed_rows(result: &QueryResult) -> Vec<Row> {
514 result
515 .rows
516 .iter()
517 .map(|values| {
518 result
519 .columns
520 .iter()
521 .enumerate()
522 .map(|(i, name)| {
523 (
524 name.clone(),
525 values
526 .get(i)
527 .cloned()
528 .expect("QueryResult rows are rectangular with respect to its columns"),
529 )
530 })
531 .collect()
532 })
533 .collect()
534}
535
536/// Result of the rows' visible keys (sorted). This clones: the clause-exit
537/// PROFILE tick still reads these rows. [`materialize_rows`] is the move
538/// path, used once a tick has already recorded the clause.
539pub(crate) fn rows_as_result(graph: &ExecGraph<'_>, rows: &[Row]) -> QueryResult {
540 let mut columns = rows
541 .first()
542 .map(|row| visible_keys(graph, row))
543 .unwrap_or_default();
544 columns.sort();
545 let data = rows
546 .iter()
547 .map(|row| {
548 read_declared_columns(row, &columns, Missing::Null)
549 .expect("padding a missing result column with null is infallible")
550 })
551 .collect();
552 QueryResult::intermediate(columns, data, graph.stats())
553}
554
555/// How the one materialization loop treats a declared column the row does
556/// not bind.
557#[derive(Clone, Copy)]
558pub(crate) enum Missing {
559 /// Pad the cell with null (the CALL export policy).
560 Null,
561 /// A miss is the engine contract break it is — every declared column is
562 /// bound by the same rule that declared it.
563 Error,
564}
565
566/// One cell of a declared column under the one miss policy — the single
567/// spelling both halves of the cell loop read, so the borrowed and the
568/// moving read cannot disagree on what a miss means.
569fn declared_cell(value: Option<Value>, column: &str, missing: Missing) -> Result<Value> {
570 match (value, missing) {
571 (Some(value), _) => Ok(value),
572 (None, Missing::Null) => Ok(Value::Null),
573 (None, Missing::Error) => Err(missing_column_error(column)),
574 }
575}
576
577/// The one miss message — for [`declared_cell`] and for the arms that read a
578/// column without going through the cell loop (the borrowed single-column
579/// DISTINCT key), so a miss reads the same wherever it is reported.
580pub(crate) fn missing_column_error(column: &str) -> Error {
581 Error::internal(format!("row is missing declared result column {column:?}"))
582}
583
584/// One row's declared columns, moved out — for a caller that owns its rows
585/// and does not need them again. A miss under [`Missing::Error`] is the
586/// engine contract break it is.
587pub(crate) fn take_declared_columns(
588 row: &mut Row,
589 columns: &[String],
590 missing: Missing,
591) -> Result<Vec<Value>> {
592 columns
593 .iter()
594 .map(|column| declared_cell(row.take_value(column), column, missing))
595 .collect()
596}
597
598/// One row's declared columns, cloned — the borrowed half of the same
599/// loop, for a caller that still needs the row (a clause-exit PROFILE tick
600/// has read it, a catalog row is read twice).
601pub(crate) fn read_declared_columns(
602 row: &Row,
603 columns: &[String],
604 missing: Missing,
605) -> Result<Vec<Value>> {
606 columns
607 .iter()
608 .map(|column| declared_cell(row.get(column).cloned(), column, missing))
609 .collect()
610}
611
612/// The one materialization loop: move each cell of `rows` onto `columns`.
613/// The source slots are left null; callers that still need the values must
614/// clone (or record their metrics) before this.
615fn materialize_rows_with(
616 rows: &mut [Row],
617 columns: &[String],
618 missing: Missing,
619) -> Result<Vec<Vec<Value>>> {
620 rows.iter_mut()
621 .map(|row| take_declared_columns(row, columns, missing))
622 .collect()
623}
624
625/// Materialize `rows` onto `columns`, moving each cell and padding misses
626/// with null. See [`materialize_rows_with`] for the move semantics.
627pub(crate) fn materialize_rows(rows: &mut [Row], columns: &[String]) -> Vec<Vec<Value>> {
628 materialize_rows_with(rows, columns, Missing::Null)
629 .expect("padding a missing result column with null is infallible")
630}
631
632/// Materialize `rows` onto `columns`, moving each cell and treating a miss
633/// as the engine contract break it is. The projection result path's policy.
634pub(crate) fn materialize_rows_strict(
635 rows: &mut [Row],
636 columns: &[String],
637) -> Result<Vec<Vec<Value>>> {
638 materialize_rows_with(rows, columns, Missing::Error)
639}
640
641/// The rows a projection consumes: the one inter-clause stream — a held
642/// container or a generator clause fused into the projection (ADR-0660) —
643/// or the aggregation a producer already folded the rows into. The stream
644/// is the only row-bearing form; a `Folded` feed holds no rows, so its
645/// consumer finishes it (`aggregate_rows`) instead of walking it. The
646/// projection pipeline's input shape lives here — the seam the dispatcher
647/// (which builds one), the generator producers (which feed one) and the
648/// projection and aggregation consumers (which read one) all already
649/// reach; the stream machinery itself lives in [`feed`], beside this seam.
650pub(crate) enum RowFeed<'a> {
651 /// The one inter-clause stream: a held container, or a generator the
652 /// projection is fused with.
653 Held(feed::RowStream<'a>),
654 /// Rows already folded into an [`aggregate::Aggregation`] by the
655 /// producer: the projection only finishes it. Built by the streaming
656 /// match sink.
657 Folded(Box<aggregate::Aggregation<'a>>),
658}
659
660impl<'a> RowFeed<'a> {
661 /// The rows already in hand, for the decisions that read the row shape
662 /// before the walk starts. A generated stream has none yet.
663 pub(crate) fn probe(&self) -> &[Row] {
664 match self {
665 RowFeed::Held(stream) => stream.probe(),
666 RowFeed::Folded(_) => &[],
667 }
668 }
669}
670
671/// One stage-walk driver for both dispatch modes (ADR-0344 phase 2
672/// review): fold the stage's parts through the runner, then recurse into
673/// the NEXT stage with the shared seeding policy (ADR-0287) and the
674/// stage count — the scaffolding exists once; the write and read
675/// entries supply only their per-part runner. The stage travels with the
676/// walk (the tree's stage numbering: the root is stage 1, every NEXT
677/// link one later), so the PROFILE metrics key's stage fact stays the
678/// tree's own.
679/// A stage's per-part runner: the stage's number, the part's index, its
680/// clauses, and its seed rows into that part's result — the write and
681/// read walkers supply their own mode.
682type PartRunner<'a> = dyn Fn(usize, usize, &[Clause], Vec<Row>) -> Result<QueryResult> + 'a;
683
684fn walk_plan_stages(
685 plan: &LogicalPlan,
686 stage: usize,
687 seeds: Vec<Row>,
688 run_part: &PartRunner,
689) -> Result<QueryResult> {
690 // A stage with one part consumes the seeds. Later parts of a UNION
691 // each need the same bag, so those plans still clone it.
692 let result = if plan.parts.len() == 1 {
693 run_part(stage, 0, plan.parts[0].as_slice(), seeds)?
694 } else {
695 union::fold_parts(plan, |part, part_clauses| {
696 run_part(stage, part, part_clauses, seeds.clone())
697 })?
698 };
699 match &plan.next {
700 Some(next) => walk_plan_stages(
701 next,
702 stage + 1,
703 next_seeds(&result, plan.parts.iter().map(|p| p.as_slice())),
704 run_part,
705 ),
706 None => Ok(result),
707 }
708}
709
710fn execute_plan_stage_seeded(
711 graph: &ExecGraph<'_>,
712 plan: &LogicalPlan,
713 params: &BTreeMap<String, Value>,
714 seeds: Vec<Row>,
715 qctx: QueryCtx<'_>,
716 sink: Option<&dyn PlanMetricsSink>,
717) -> Result<QueryResult> {
718 let result = walk_plan_stages(plan, 1, seeds, &|stage, part, part_clauses, part_seeds| {
719 let (mut rows, last) = run_clauses(
720 graph,
721 part_clauses,
722 params,
723 part_seeds,
724 qctx,
725 // The statement-level walker: the PROFILE site — the sink the
726 // admission attached and this part's (stage, part) key, one
727 // fact — rides to the clause loop.
728 sink.map(|sink| PlanMetricsSite::at(sink, stage, part)),
729 )?;
730 Ok(call::concluding_part_result(
731 graph,
732 part_clauses,
733 &mut rows,
734 last,
735 graph.stats(),
736 ))
737 })?;
738 report_statement_memos(graph, sink);
739 Ok(result)
740}
741
742/// Hand the statement's constructor-memo facts (ADR-0654 §3) to the
743/// PROFILE sink once the statement finished: they serve any expression, so
744/// they belong to the statement, not to an operator. A non-PROFILE
745/// statement has no sink and reads nothing.
746fn report_statement_memos(graph: &ExecGraph<'_>, sink: Option<&dyn PlanMetricsSink>) {
747 if let Some(sink) = sink {
748 sink.record_statement_memos(graph.construct_memo_record());
749 }
750}
751
752/// The NEXT-stage seeding policy (one spelling, every NEXT-chain walker
753/// reads it — both pass their parts iterator, plan-level or subquery):
754/// the stage's result rows, or — for a stage whose unit output is a
755/// single row (ADR-0287) — one empty seed so the next stage still runs.
756pub(crate) fn next_seeds<'p>(
757 result: &QueryResult,
758 parts: impl Iterator<Item = &'p [Clause]>,
759) -> Vec<Row> {
760 let mut seeds = result_seed_rows(result);
761 if seeds.is_empty() && parts_have_unit_output(parts) {
762 seeds.push(Row::new());
763 }
764 seeds
765}
766
767pub(crate) fn execute_plan_read_seeded(
768 graph: &ExecGraph<'_>,
769 plan: &LogicalPlan,
770 params: &BTreeMap<String, Value>,
771 seeds: Vec<Row>,
772 qctx: QueryCtx<'_>,
773 sink: Option<&dyn PlanMetricsSink>,
774) -> Result<QueryResult> {
775 let result = walk_plan_stages(plan, 1, seeds, &|stage, part, part_clauses, part_seeds| {
776 execute_part_read_seeded(
777 graph,
778 part_clauses,
779 params,
780 part_seeds,
781 qctx,
782 // The statement-level walker, read mode: the PROFILE site —
783 // sink and this part's (stage, part) key, one fact — rides to
784 // the clause loop here too.
785 sink.map(|sink| PlanMetricsSite::at(sink, stage, part)),
786 )
787 })?;
788 report_statement_memos(graph, sink);
789 Ok(result)
790}
791
792/// Whether a finished stage seeds the next `NEXT` stage with one unit row
793/// when its own result is empty (ADR-0287). Data-write parts
794/// (`CREATE`/`MERGE`/`DELETE`/`SET`/`REMOVE`/`FOREACH`/`CALL { … }`) and
795/// `FINISH` count, and so do schema/admin DDL parts — the IR-native
796/// index/constraint variants outright, and `Clause::Catalog` exactly when
797/// the canonical `relate-front` predicate says the command is NOT
798/// row-producing. Row-producing catalog commands (the SHOW family and
799/// `TERMINATE TRANSACTIONS`) keep their row semantics: they seed the next
800/// stage from their projected rows, never with a unit row.
801fn parts_have_unit_output<'p>(mut parts: impl Iterator<Item = &'p [Clause]>) -> bool {
802 parts.all(|part| part.last().is_some_and(unit_output_clause))
803}
804
805/// Whether the clause concluding a part makes that part unit output: an
806/// empty result still seeds the next `NEXT` stage with one row (ADR-0287).
807/// [`clause_spills_rows`] decides it, plus the one arm this seeding policy
808/// adds over that classification: `CALL { … }` is a data write in the
809/// ADR-0287 vocabulary, even though its merged rows are a statement result
810/// of its own.
811fn unit_output_clause(clause: &Clause) -> bool {
812 matches!(clause, Clause::CallSubquery { .. }) || !clause_spills_rows(clause)
813}
814
815/// Whether the clause concluding a part spills statement rows when it runs
816/// — the planner's published [`clause_projects_rows`] table plus the one
817/// refinement only this layer can make: a `WHEN`/`ELSE` conditional whose
818/// branch bodies are all unit output spills no rows (the per-row driver's
819/// buckets stay empty), so it projects none. Every concluding-clause
820/// policy reads this one answer — the `CALL { … }` merge policy
821/// ([`part_projects_rows`]), a conditional branch body's row-lessness and
822/// the NEXT-stage seeding policy ([`unit_output_clause`]) — so a unit
823/// conditional body is a unit body everywhere: its caller's outer rows
824/// pass through, never drop, and its `IN TRANSACTIONS` iterations report
825/// their status rows.
826fn clause_spills_rows(clause: &Clause) -> bool {
827 if !clause_projects_rows(clause) {
828 return false;
829 }
830 match clause {
831 Clause::Conditional {
832 branches,
833 else_query,
834 } => call::conditional_produces_rows(branches, else_query.as_deref()),
835 _ => true,
836 }
837}
838
839/// Whether a part (one UNION arm) projects statement rows of its own — the
840/// one classification over the concluding-clause vocabulary
841/// ([`clause_spills_rows`]: the planner table plus the all-unit
842/// conditional refinement), read by the `CALL { … }` merge policy and by a
843/// conditional branch body's row-lessness (and, through
844/// [`unit_output_clause`], by the NEXT-stage seeding policy).
845pub(crate) fn part_projects_rows(clauses: &[Clause]) -> bool {
846 clauses.last().is_none_or(clause_spills_rows)
847}
848
849#[cfg(test)]
850mod aggregate_charge_tests;
851#[cfg(test)]
852mod aggregate_footprint_tests;
853#[cfg(test)]
854mod aggregate_percentile_tests;
855#[cfg(test)]
856mod aggregate_pool_tests;
857#[cfg(test)]
858mod aggregate_tests;
859#[cfg(test)]
860mod batch_limit_tests;
861#[cfg(test)]
862mod batch_tests;
863#[cfg(test)]
864mod breaker_stream_tests;
865#[cfg(test)]
866mod chunk_tests;
867#[cfg(test)]
868mod conditional_tests;
869mod count_stats;
870#[cfg(test)]
871mod count_stats_tests;
872#[cfg(test)]
873mod direct_fold_tests;
874#[cfg(test)]
875mod effect_tests;
876#[cfg(test)]
877mod exists_probe_tests;
878#[cfg(test)]
879mod expand_tests;
880#[cfg(test)]
881mod far_node_tests;
882mod foreach;
883#[cfg(test)]
884mod foreach_tests;
885pub mod graph_stats;
886#[cfg(test)]
887mod graph_stats_tests;
888#[cfg(test)]
889mod id_seek_tests;
890mod index_aggregates;
891#[cfg(test)]
892mod index_aggregates_tests;
893#[cfg(test)]
894mod integer_arg_tests;
895#[cfg(test)]
896mod kernels_tests;
897mod label_set_groups;
898#[cfg(test)]
899mod label_set_groups_tests;
900#[cfg(test)]
901mod limit_where_tests;
902#[cfg(test)]
903mod match_chain_tests;
904#[cfg(test)]
905mod match_fold_tests;
906#[cfg(test)]
907mod match_memory_tests;
908#[cfg(test)]
909mod nested_eval_tests;
910#[cfg(test)]
911mod one_hop_fold_tests;
912#[cfg(test)]
913mod path_fold_tests;
914#[cfg(test)]
915mod pivot_tests;
916#[cfg(test)]
917mod predicate_spec_tests;
918#[cfg(test)]
919mod procedures_tests;
920#[cfg(test)]
921mod profiling_tests;
922#[cfg(test)]
923mod project_tests;
924#[cfg(test)]
925mod pushdown_tests;
926#[cfg(test)]
927mod range_start_tests;
928#[cfg(test)]
929mod rel_list_binding_tests;
930#[cfg(test)]
931mod rel_seek_tests;
932#[cfg(test)]
933mod seek_readiness_tests;
934mod shortcut_common;
935#[cfg(test)]
936mod shortest_expression_tests;
937#[cfg(test)]
938mod shortest_path_tests;
939#[cfg(test)]
940mod stream_agg_tests;
941#[cfg(test)]
942mod subquery_eval_tests;
943#[cfg(test)]
944pub(crate) mod test_support;
945#[cfg(test)]
946mod text_seek_tests;