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