Skip to main content

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