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