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