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