relate-executor 1.3.0

In-memory graph and Cypher physical executor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
//! Query execution entry points, plan folding, and the `exec/` submodule
//! wiring.

use std::collections::BTreeMap;

use relate_core::{CancelToken, Error, QueryClockGuard, Result, Value};
use relate_ir::{Clause, LabelExpr};
use relate_names::{SmallName, Token};
use relate_planner::{clause_mutates_store, clause_projects_rows, plan_any_clause, LogicalPlan};

use crate::metrics::{PlanMetricsSink, PlanMetricsSite};

use crate::row::Row;

// The instrumentation cluster (LABS-448's extraction) — one private
// module, re-exported here so the walkers' `super::` paths keep working:
// the store-read counters and the walk-start slot. The phase clocks live
// in `crate::ctx` (LABS-668), the lowest module both walk engines share.
mod profiling;
use crate::graph::{Graph, QueryStats, SchemaSnapshot};
use crate::overlay::ExecGraph;
use crate::procedure_registry::call_writes_store;
use crate::StatementEffect;
pub(crate) use profiling::{
    arm_store_profiling, count_frontier, count_neighbor_walks, count_zone_skip, record_memos,
    record_walk_start, restore_store_profiling, take_walk_start, DeltaSnapshot, StageDelta,
    WalkStartSwap, WalkTallies,
};
#[cfg(test)]
pub(crate) use profiling::{
    disarm_store_profiling, memo_counters, take_frontier_counters, take_hop_expands,
    take_neighbor_walks, take_node_reads, take_zone_skips,
};

pub(crate) mod agg_fold;
pub(crate) mod aggregate;
pub(crate) mod batch;
pub(crate) mod batch_tail;
pub(crate) mod bulk;
pub(crate) mod call;
pub(crate) mod candidates;
pub(crate) mod catalog;
pub(crate) mod catalog_schema;
pub(crate) mod catalog_show;
pub(crate) mod create_admission;
// ADR-0468's SoA chunk type layer: the types, the conversion, and the
// operator-serving constructions the batch chain (exec/batch.rs) reads.
pub(crate) mod chunk;
pub(crate) mod classification;
mod clause_arms;
pub(crate) mod compose;
pub(crate) mod constraint_validation;
pub(crate) mod create;
pub(crate) mod ddl;
pub(crate) mod ddl_notifications;
pub(crate) mod ddl_options;
pub(crate) mod dispatch;
pub(crate) mod exists_probe;
pub(crate) mod expand;
pub(crate) mod far_probe;
pub(crate) mod feed;
pub(crate) mod fulltext;
pub(crate) mod gpm;
pub(crate) mod graph_type_schema;
mod load_csv;
mod match_arm;
mod profile_chain;
mod profile_tick;
// The LABS-348 hub join — the whole family (gate, join, row-shape
// helpers, test hooks), invoked by the driver at its pattern-0→
// pattern-1 boundary (`match_clause::match_paths`) over the caller's
// own pattern-0 rows.
pub(crate) mod hub_join;
// ADR-0473 (LABS-644): the contracted traversal kernels — structural
// matcher, cost gate, chain and hub-star operators over the substrate.
pub(crate) mod kernels;
pub(crate) mod match_cap;
pub(crate) mod match_chain;
pub(crate) mod match_clause;
pub(crate) mod match_consumer;
pub(crate) mod match_folds;
pub(crate) mod named_path;
// The one engine fork (`match_one_path`) every per-path consumer routes
// through — the driver's pattern loop (match_clause), the hub join's
// plain-side enumeration, and the exists probe's dispatch — hoisted
// beside `expand` so every consumer imports it downward.
pub(crate) mod one_path;
pub(crate) mod order;
pub(crate) mod pattern_policies;
pub(crate) mod pivot;
pub(crate) mod post_merge;
pub(crate) mod predicate_spec;
pub(crate) mod procedure_rows;
pub(crate) mod procedures;
pub(crate) mod project;
pub(crate) mod property_defaults;
pub(crate) mod pushdown;
pub(crate) mod rel_seek;
pub(crate) mod rider;
pub(crate) mod scope;
pub(crate) mod search;
pub(crate) mod search_filters;
pub(crate) mod shortest_eval;
pub(crate) mod sink;
mod stats_short_circuit;
pub(crate) mod subquery_eval;
pub(crate) mod top_k;
pub(crate) mod union;
pub(crate) mod unwind;
pub(crate) mod vector;
pub(crate) mod write;

pub use catalog_show::catalog_create_statements;

/// The read path's one rejection policy: the message a `ClauseMode::Read`
/// clause loop refuses `c` with, or `None` to dispatch it. The dispatcher
/// asks once per clause, before its clause match.
///
/// The table is the planner's published per-clause answer
/// ([`clause_mutates_store`], catalog commands included: the `SHOW` family is
/// a read, a catalog DDL command is a write) plus the two shapes this layer
/// decides: `FOREACH` names itself, and `CALL { … } IN TRANSACTIONS` needs a
/// write transaction. A catalog write reaching a read run is therefore a
/// typed rejection, not a write that only the read-only scratch's panic
/// backstops.
///
/// The name states the policy, not a clause classification: it answers "does
/// the read path reject this clause, and with what message?", which is
/// narrower than the mutation question the composition rules ask
/// ([`mutates_store`]).
pub(crate) fn read_path_rejection(c: &Clause) -> Option<&'static str> {
    match c {
        Clause::Foreach { .. } => Some("internal: FOREACH on read path"),
        Clause::CallSubquery {
            in_transactions: Some(_),
            ..
        } => Some("internal: CALL IN TRANSACTIONS requires a write transaction"),
        other if clause_mutates_store(other) => Some("internal: write clause on read path"),
        _ => None,
    }
}

/// Whether one clause mutates the store — the per-clause form of
/// [`plan_mutates_store`], shared with the composition rules that ask the
/// mutation question rather than the read-admission one. The two answers
/// this layer decides below the planner table live here:
///
/// - `LOAD CSV` is `Write` in the clause table (write-*routed* by the
///   conservative access fold, ADR-0332) but only reads a file;
/// - a `CALL` is the procedure registry's writes flag
///   ([`call_writes_store`]) — a registered procedure is a static row table
///   and cannot mutate the store.
pub(crate) fn mutates_store(clause: &Clause) -> bool {
    match clause {
        Clause::LoadCsv { .. } => false,
        Clause::Call { name, .. } => name.with_str(call_writes_store),
        other => clause_mutates_store(other),
    }
}

/// Whether `plan` holds a mutation operator — the statement's ADR-0402
/// Decision 2 write-attempt fact, recorded once at statement entry (before
/// any rows flow) through the canonical plan walk
/// (`relate_planner::plan_any_clause` over `walk_plan_clauses`): every
/// part, every `NEXT` stage, and every nested body the walk descends into
/// (`CALL { … }`, `WHEN`/`ELSE`, `FOREACH` bodies, expression subqueries). A
/// write inside a body that never dispatches — an empty driving row set, an
/// untaken branch — is therefore still an attempt, which is the same
/// short-circuit the empty top-level pipeline is made of. Both statement
/// boundaries that name an effect record it here — the write path and the
/// read admission — so the fact has one source on every route.
///
/// The planner's [`clause_mutates_store`] answers each clause; the two shapes
/// whose answer lives at this layer are decided by [`mutates_store`], which
/// this walk applies clause by clause.
pub(crate) fn plan_mutates_store(plan: &LogicalPlan) -> bool {
    plan_any_clause(plan, &mut mutates_store)
}

/// Record on the statement's view every name the plan declares — the one
/// per-clause vocabulary ([`scope::clause_declared_names`]) folded
/// cumulatively over the same canonical plan walk
/// ([`plan_mutates_store`]'s `plan_any_clause`), nested bodies (`CALL { … }`,
/// `FOREACH`, expression subqueries) included, so the set is complete
/// before any clause runs and does not depend on which body has run. A
/// name declared only in a nested body is therefore declared
/// statement-wide; no synthetic column can carry it, because every
/// synthetic prefix is chosen past the declared set
/// ([`ExecGraph::uncolliding_prefix`]). Cumulative: a name dropped by a
/// later `WITH` stays declared, since rows between the two still carry it.
/// Called only by [`ExecGraph::begin_statement`], so the reset and this
/// seeding are one operation no entry can split.
pub(crate) fn declare_plan_names(graph: &ExecGraph<'_>, plan: &LogicalPlan) {
    plan_any_clause(plan, &mut |clause| {
        let names = scope::clause_declared_names(clause);
        graph.declare_names(names.iter().map(String::as_str));
        false
    });
}

use constraint_validation::validate_constraints;
use dispatch::{execute_part_read_seeded, run_clauses};
use scope::visible_keys;
pub(crate) use shortest_eval::{eval_shortest, ShortestWant};
pub(crate) use subquery_eval::{eval_collect_query, eval_count_query, eval_exists_query};

use crate::ctx::QueryCtx;

/// The lowering duplicates a static label/type list into a `LabelExpr`
/// (`labels`/`types` carry the same names). A label expression is
/// batch-safe exactly when it is a tree of static `Label` leaves over
/// precisely those names — no wildcards, dynamics, or negation.
/// Hoisted from `exec/bulk.rs` (round 4, F-4-1): the static-mirror
/// discrimination the bulk-write recognizer and the count-only shape
/// recognizer share — one canonical helper per policy.
pub(crate) fn static_label_tree(expr: &LabelExpr, names: &[(SmallName, Token)]) -> bool {
    fn leaves<'a>(expr: &'a LabelExpr, out: &mut Vec<&'a SmallName>) -> bool {
        match expr {
            LabelExpr::Label(name) => {
                out.push(name);
                true
            }
            LabelExpr::And(parts) | LabelExpr::Or(parts) => {
                parts.iter().all(|part| leaves(part, out))
            }
            _ => false,
        }
    }
    let mut found = Vec::new();
    leaves(expr, &mut found)
        && found.len() == names.len()
        && found
            .iter()
            .all(|name| names.iter().any(|(n, _)| n == *name))
}

/// Whether an optional label expression is absent or static-matches
/// `names` — the one gate every label-expression-accepting recognizer
/// consults: gate on static-vs-dynamic, never on presence (round 4,
/// F-4-1/F-4-2: the raw front-lowered shape carries the static mirror,
/// and a presence gate would decline real pipeline shapes).
pub(crate) fn label_expr_ok(expr: &Option<LabelExpr>, names: &[(SmallName, Token)]) -> bool {
    expr.as_ref().is_none_or(|e| static_label_tree(e, names))
}

pub struct QueryResult {
    pub columns: Vec<String>,
    pub rows: Vec<Vec<Value>>,
    pub stats: QueryStats,
    /// The engine's truthful write effect for this statement (ADR-0402
    /// Decision 2), named once at the statement boundary from two execution
    /// facts: whether the statement's plan holds a mutation operator (the one
    /// plan walk, [`plan_mutates_store`]) and whether any change reached the
    /// write redo since the statement's entry reset. A read therefore carries
    /// [`StatementEffect::None`]. Results built *inside* a statement (a
    /// clause's rows, a nested body's output) go through the crate-private
    /// `QueryResult::intermediate` and never spell this field: the boundary is
    /// the one place that names it. See [`StatementEffect`] for why neither
    /// the plan's query type nor the mutation counters can answer this.
    pub effect: StatementEffect,
}

impl QueryResult {
    /// A result a statement boundary finished, its effect named by the
    /// execution that produced it — the construction for a crate outside this
    /// one (the ADR-0209 batched bulk write is its own statement boundary and
    /// runs no clause loop). The effect always comes from
    /// [`StatementEffect`]'s own constructors, so a caller never spells a
    /// zero state at the construction site.
    pub fn finished(
        columns: Vec<String>,
        rows: Vec<Vec<Value>>,
        stats: QueryStats,
        effect: StatementEffect,
    ) -> Self {
        Self {
            columns,
            rows,
            stats,
            effect,
        }
    }

    /// A result built *inside* a statement — a clause's rows, a nested
    /// body's output, a finishing projection — before the boundary names its
    /// effect.
    ///
    /// The effect starts as the unstamped read state; the statement boundary
    /// ([`execute`] on the write path, `execute_read_at` on the read path) is
    /// the one place that names it from the execution's own facts. Routing
    /// every intermediate construction through this constructor is what keeps
    /// a placeholder out of the construction sites: no clause can hand a
    /// surface an effect that claims a write applied nothing.
    pub(crate) fn intermediate(
        columns: Vec<String>,
        rows: Vec<Vec<Value>>,
        stats: QueryStats,
    ) -> Self {
        Self::finished(columns, rows, stats, StatementEffect::None)
    }

    /// CIP-159's empty unit result — no columns, no rows, default stats —
    /// the one spelling of the terminal-void answer.
    pub(crate) fn unit() -> Self {
        Self::intermediate(Vec::new(), Vec::new(), QueryStats::default())
    }
}

/// The plan, parameters, source text, and authenticated principal shared by
/// every execution entry point. `query_text` is the source text of the
/// statement (exposed as `SHOW TRANSACTIONS`' `currentQuery` column); the
/// statement's CIP-150 version preamble rides on the plan. `principal` is the
/// connection's authenticated principal (ADR-0273), read by
/// `dbms.showCurrentUser`; `None` reports the documented placeholder.
/// `Copy`: every field is a reference (or an optional reference) — the
/// commit path reuses the caller's request with its own batch-commit
/// sink attached, without rebuilding the bundle field by field.
#[derive(Clone, Copy)]
pub struct ExecRequest<'a> {
    pub plan: &'a LogicalPlan,
    pub params: &'a BTreeMap<String, Value>,
    pub query_text: &'a str,
    pub principal: Option<&'a str>,
    /// ADR-0210: per-batch durable-commit sink for `CALL { … } IN
    /// TRANSACTIONS`; `None` keeps the accumulate-to-statement-end
    /// behavior.
    pub batch_commit: Option<&'a dyn crate::ctx::BatchCommit>,
    /// ADR-0344 phase 2: the PROFILE metrics sink for the statement's own
    /// clauses; `None` on every non-PROFILE run. The dispatch loop
    /// records one entry per clause operator; nested execution strips it.
    pub plan_metrics: Option<&'a dyn crate::metrics::PlanMetricsSink>,
}

impl<'a> ExecRequest<'a> {
    /// The None-default request: no principal, no batch-commit sink, no
    /// PROFILE sink — the statement's own execution with none of the
    /// optional carriers. The one construction site for the defaults, so
    /// a new optional field lands here, not at every caller.
    pub fn new(
        plan: &'a LogicalPlan,
        params: &'a BTreeMap<String, Value>,
        query_text: &'a str,
    ) -> Self {
        Self {
            plan,
            params,
            query_text,
            principal: None,
            batch_commit: None,
            plan_metrics: None,
        }
    }
}

/// A read admitted at a caller-pinned timestamp: the `graph`, the pinned
/// `snapshot_ts`, and the `schema` captured together with that pin under the
/// publication read guard, plus the `request` to run and its optional
/// cooperative cancellation token (ADR-0111; `None` is never cancelled).
pub struct ReadAdmission<'a> {
    pub graph: &'a Graph,
    pub snapshot_ts: u64,
    pub schema: &'a SchemaSnapshot,
    pub request: ExecRequest<'a>,
    pub cancel: Option<&'a CancelToken>,
    /// The store's ontology document (verbatim) captured at admission
    /// (ADR-0121 §3, ADR-0227): attached to the read view like `cancel`
    /// and read by `db.ontology.get` / `db.ontology.apply`; `None` when
    /// the store holds no ontology.
    pub ontology_document: Option<&'a str>,
}

/// The write boundary a batch of writes closes with, in order: the graph
/// type's property default values, then the constraint validation. One
/// home beside the write pipeline — the statement boundary
/// ([`execute`]) and the `CALL { … } IN TRANSACTIONS` batch attempt both
/// call it, so the two cannot drift.
pub(crate) fn close_write_boundary(graph: &ExecGraph<'_>) -> Result<()> {
    property_defaults::apply_property_defaults(graph)?;
    validate_constraints(graph)
}

/// Execute a write-capable plan, then validate the constraints against what
/// it wrote (ADR-0172). Each call starts a fresh CSV memo even when `graph`
/// is reused across statements.
pub fn execute(graph: &ExecGraph<'_>, request: &ExecRequest<'_>) -> Result<QueryResult> {
    let (result, attempted) = run_statement(graph, request)?;
    // CIP-262: the statement is this engine's transaction, so the graph
    // type's property default values land at its boundary -- after the
    // writes (the statement's own RETURN already saw null, CE1), before
    // the post-statement constraint validation sees the defaulted
    // properties like any other write. They are writes, so they land
    // before the effect's applied fact is read (below).
    close_write_boundary(graph)?;
    finish_statement(result, graph, attempted)
}

/// [`execute`] without the constraint validation: the statement's writes
/// stay in the redo slice the next `validate_constraints` checks. The
/// executor's own tests drive this entry (`exec::test_support`); production
/// always takes the validated one.
///
/// It is the same statement boundary, so it names the effect from its own two
/// facts rather than handing back a placeholder: a caller that stops here
/// still cannot read a read state off a statement that wrote.
#[cfg(test)]
pub(crate) fn execute_unvalidated(
    graph: &ExecGraph<'_>,
    request: &ExecRequest<'_>,
) -> Result<QueryResult> {
    let (result, attempted) = run_statement(graph, request)?;
    finish_statement(result, graph, attempted)
}

/// The private un-finished runner every write statement entry shares: the
/// per-statement resets, the entry checks, the entry facts, and the plan's
/// execution. It never names the effect and never polls the token ledger —
/// [`finish_statement`] does both, exactly once, so `execute` and
/// `execute_unvalidated` cannot stamp a statement twice.
///
/// Returns the un-finished result and the statement's write-attempt fact
/// ([`plan_mutates_store`]), recorded here before any rows flow and handed to
/// [`finish_statement`] unchanged.
fn run_statement(graph: &ExecGraph<'_>, request: &ExecRequest<'_>) -> Result<(QueryResult, bool)> {
    let attempted = plan_mutates_store(request.plan);
    // One statement entry: the per-statement resets and the declared-name
    // seeding restart together (ADR-0309 stats + the ADR-0402 applied count,
    // the ADR-0395 nested-evaluation budget, the spelled-name set).
    graph.begin_statement(request.plan);
    graph.check_cancelled()?;
    let _clock = QueryClockGuard::within(graph.transaction_clock());
    let qctx = QueryCtx::new(request.query_text)
        .with_principal(request.principal)
        .with_batch_commit(request.batch_commit);
    let result = execute_plan_stage_seeded(
        graph,
        request.plan,
        request.params,
        vec![Row::new()],
        qctx,
        request.plan_metrics,
    )?;
    Ok((result, attempted))
}

/// Execute a read-only plan at the caller-pinned timestamp in `admission`
/// without repinning. The caller must keep its `Graph::pin_now()` guard alive
/// through this call so version GC cannot discard rows visible at
/// `snapshot_ts`, and must capture `schema` alongside that pin while
/// serializing with graph publication.
///
/// There is deliberately no graph-only wrapper that acquires both itself: the
/// publication read guard lives on the embedded database's `Shared` state, not
/// on a bare `Graph`, so such a wrapper could not capture the pin and schema
/// atomically. Admission must happen under that guard at the caller.
pub fn execute_read_at(admission: &ReadAdmission<'_>) -> Result<QueryResult> {
    let view = ExecGraph::read_at(admission.graph, admission.snapshot_ts)
        .with_schema(admission.schema)
        .with_cancel(admission.cancel)
        .with_ontology_document(admission.ontology_document);
    view.check_cancelled()?;
    // A read view carries no scratch, so the resets are vacuous and this
    // call is the declared-name seeding — kept through the same one
    // statement-entry operation every write entry takes, never a second
    // spelling of it.
    view.begin_statement(admission.request.plan);
    let _clock = QueryClockGuard::new();
    // A read admission records its write-attempt fact from the same canonical
    // plan walk as every write entry — never a hardcoded "a read cannot
    // write": a mutation operator reaching this route is still an attempt (the
    // read-only scratch refuses to apply it). A read view applies nothing, so
    // its applied count is the zero the admission starts with.
    let attempted = plan_mutates_store(admission.request.plan);
    // ADR-0395: the freshly constructed view carries a zeroed counter —
    // the read admission's statement gets its own budget.
    let qctx =
        QueryCtx::new(admission.request.query_text).with_principal(admission.request.principal);
    let mut result = execute_plan_read_seeded(
        &view,
        admission.request.plan,
        admission.request.params,
        vec![Row::new()],
        qctx,
        admission.request.plan_metrics,
    )?;
    result.stats = QueryStats::default();
    finish_statement(result, &view, attempted)
}

/// Name the statement's effect and finish the result — the one assignment to
/// [`QueryResult::effect`], and the one token-ledger poll. Every entry into a
/// statement (the write path, the unvalidated path, a read admission) runs
/// the un-finished runner and ends here exactly once, so no entry can return
/// a fabricated effect for a statement that wrote, and none stamps twice.
///
/// The two facts are taken where they are known: `attempted` from the plan
/// walk at statement entry, `applied` from the statement's own change count —
/// zeroed by the same entry reset as the stats and grown by every redo push,
/// so no baseline has to travel beside it.
fn finish_statement(
    mut result: QueryResult,
    graph: &ExecGraph<'_>,
    attempted: bool,
) -> Result<QueryResult> {
    result.effect = StatementEffect::from_facts(attempted, graph.applied_ops() > 0);
    finish_tokens(result)
}

fn finish_tokens(result: QueryResult) -> Result<QueryResult> {
    relate_core::tokens::poll()?;
    Ok(result)
}

pub(crate) fn result_seed_rows(result: &QueryResult) -> Vec<Row> {
    result
        .rows
        .iter()
        .map(|values| {
            result
                .columns
                .iter()
                .enumerate()
                .map(|(i, name)| {
                    (
                        name.clone(),
                        values
                            .get(i)
                            .cloned()
                            .expect("QueryResult rows are rectangular with respect to its columns"),
                    )
                })
                .collect()
        })
        .collect()
}

/// Result of the rows' visible keys (sorted). This clones: the clause-exit
/// PROFILE tick still reads these rows. [`materialize_rows`] is the move
/// path, used once a tick has already recorded the clause.
pub(crate) fn rows_as_result(graph: &ExecGraph<'_>, rows: &[Row]) -> QueryResult {
    let mut columns = rows
        .first()
        .map(|row| visible_keys(graph, row))
        .unwrap_or_default();
    columns.sort();
    let data = rows
        .iter()
        .map(|row| {
            read_declared_columns(row, &columns, Missing::Null)
                .expect("padding a missing result column with null is infallible")
        })
        .collect();
    QueryResult::intermediate(columns, data, graph.stats())
}

/// How the one materialization loop treats a declared column the row does
/// not bind.
#[derive(Clone, Copy)]
pub(crate) enum Missing {
    /// Pad the cell with null (the CALL export policy).
    Null,
    /// A miss is the engine contract break it is — every declared column is
    /// bound by the same rule that declared it.
    Error,
}

/// One cell of a declared column under the one miss policy — the single
/// spelling both halves of the cell loop read, so the borrowed and the
/// moving read cannot disagree on what a miss means.
fn declared_cell(value: Option<Value>, column: &str, missing: Missing) -> Result<Value> {
    match (value, missing) {
        (Some(value), _) => Ok(value),
        (None, Missing::Null) => Ok(Value::Null),
        (None, Missing::Error) => Err(missing_column_error(column)),
    }
}

/// The one miss message — for [`declared_cell`] and for the arms that read a
/// column without going through the cell loop (the borrowed single-column
/// DISTINCT key), so a miss reads the same wherever it is reported.
pub(crate) fn missing_column_error(column: &str) -> Error {
    Error::internal(format!("row is missing declared result column {column:?}"))
}

/// One row's declared columns, moved out — for a caller that owns its rows
/// and does not need them again. A miss under [`Missing::Error`] is the
/// engine contract break it is.
pub(crate) fn take_declared_columns(
    row: &mut Row,
    columns: &[String],
    missing: Missing,
) -> Result<Vec<Value>> {
    columns
        .iter()
        .map(|column| declared_cell(row.take_value(column), column, missing))
        .collect()
}

/// One row's declared columns, cloned — the borrowed half of the same
/// loop, for a caller that still needs the row (a clause-exit PROFILE tick
/// has read it, a catalog row is read twice).
pub(crate) fn read_declared_columns(
    row: &Row,
    columns: &[String],
    missing: Missing,
) -> Result<Vec<Value>> {
    columns
        .iter()
        .map(|column| declared_cell(row.get(column).cloned(), column, missing))
        .collect()
}

/// The one materialization loop: move each cell of `rows` onto `columns`.
/// The source slots are left null; callers that still need the values must
/// clone (or record their metrics) before this.
fn materialize_rows_with(
    rows: &mut [Row],
    columns: &[String],
    missing: Missing,
) -> Result<Vec<Vec<Value>>> {
    rows.iter_mut()
        .map(|row| take_declared_columns(row, columns, missing))
        .collect()
}

/// Materialize `rows` onto `columns`, moving each cell and padding misses
/// with null. See [`materialize_rows_with`] for the move semantics.
pub(crate) fn materialize_rows(rows: &mut [Row], columns: &[String]) -> Vec<Vec<Value>> {
    materialize_rows_with(rows, columns, Missing::Null)
        .expect("padding a missing result column with null is infallible")
}

/// Materialize `rows` onto `columns`, moving each cell and treating a miss
/// as the engine contract break it is. The projection result path's policy.
pub(crate) fn materialize_rows_strict(
    rows: &mut [Row],
    columns: &[String],
) -> Result<Vec<Vec<Value>>> {
    materialize_rows_with(rows, columns, Missing::Error)
}

/// The rows a projection consumes: the one inter-clause stream — a held
/// container or a generator clause fused into the projection (ADR-0660) —
/// or the aggregation a producer already folded the rows into. The stream
/// is the only row-bearing form; a `Folded` feed holds no rows, so its
/// consumer finishes it (`aggregate_rows`) instead of walking it. The
/// projection pipeline's input shape lives here — the seam the dispatcher
/// (which builds one), the generator producers (which feed one) and the
/// projection and aggregation consumers (which read one) all already
/// reach; the stream machinery itself lives in [`feed`], beside this seam.
pub(crate) enum RowFeed<'a> {
    /// The one inter-clause stream: a held container, or a generator the
    /// projection is fused with.
    Held(feed::RowStream<'a>),
    /// Rows already folded into an [`aggregate::Aggregation`] by the
    /// producer: the projection only finishes it. Built by the streaming
    /// match sink.
    Folded(Box<aggregate::Aggregation<'a>>),
}

impl<'a> RowFeed<'a> {
    /// The rows already in hand, for the decisions that read the row shape
    /// before the walk starts. A generated stream has none yet.
    pub(crate) fn probe(&self) -> &[Row] {
        match self {
            RowFeed::Held(stream) => stream.probe(),
            RowFeed::Folded(_) => &[],
        }
    }
}

/// One stage-walk driver for both dispatch modes (ADR-0344 phase 2
/// review): fold the stage's parts through the runner, then recurse into
/// the NEXT stage with the shared seeding policy (ADR-0287) and the
/// stage count — the scaffolding exists once; the write and read
/// entries supply only their per-part runner. The stage travels with the
/// walk (the tree's stage numbering: the root is stage 1, every NEXT
/// link one later), so the PROFILE metrics key's stage fact stays the
/// tree's own.
/// A stage's per-part runner: the stage's number, the part's index, its
/// clauses, and its seed rows into that part's result — the write and
/// read walkers supply their own mode.
type PartRunner<'a> = dyn Fn(usize, usize, &[Clause], Vec<Row>) -> Result<QueryResult> + 'a;

fn walk_plan_stages(
    plan: &LogicalPlan,
    stage: usize,
    seeds: Vec<Row>,
    run_part: &PartRunner,
) -> Result<QueryResult> {
    // A stage with one part consumes the seeds. Later parts of a UNION
    // each need the same bag, so those plans still clone it.
    let result = if plan.parts.len() == 1 {
        run_part(stage, 0, plan.parts[0].as_slice(), seeds)?
    } else {
        union::fold_parts(plan, |part, part_clauses| {
            run_part(stage, part, part_clauses, seeds.clone())
        })?
    };
    match &plan.next {
        Some(next) => walk_plan_stages(
            next,
            stage + 1,
            next_seeds(&result, plan.parts.iter().map(|p| p.as_slice())),
            run_part,
        ),
        None => Ok(result),
    }
}

fn execute_plan_stage_seeded(
    graph: &ExecGraph<'_>,
    plan: &LogicalPlan,
    params: &BTreeMap<String, Value>,
    seeds: Vec<Row>,
    qctx: QueryCtx<'_>,
    sink: Option<&dyn PlanMetricsSink>,
) -> Result<QueryResult> {
    let result = walk_plan_stages(plan, 1, seeds, &|stage, part, part_clauses, part_seeds| {
        let (mut rows, last) = run_clauses(
            graph,
            part_clauses,
            params,
            part_seeds,
            qctx,
            // The statement-level walker: the PROFILE site — the sink the
            // admission attached and this part's (stage, part) key, one
            // fact — rides to the clause loop.
            sink.map(|sink| PlanMetricsSite::at(sink, stage, part)),
        )?;
        Ok(call::concluding_part_result(
            graph,
            part_clauses,
            &mut rows,
            last,
            graph.stats(),
        ))
    })?;
    report_statement_memos(graph, sink);
    Ok(result)
}

/// Hand the statement's constructor-memo facts (ADR-0654 §3) to the
/// PROFILE sink once the statement finished: they serve any expression, so
/// they belong to the statement, not to an operator. A non-PROFILE
/// statement has no sink and reads nothing.
fn report_statement_memos(graph: &ExecGraph<'_>, sink: Option<&dyn PlanMetricsSink>) {
    if let Some(sink) = sink {
        sink.record_statement_memos(graph.construct_memo_record());
    }
}

/// The NEXT-stage seeding policy (one spelling, every NEXT-chain walker
/// reads it — both pass their parts iterator, plan-level or subquery):
/// the stage's result rows, or — for a stage whose unit output is a
/// single row (ADR-0287) — one empty seed so the next stage still runs.
pub(crate) fn next_seeds<'p>(
    result: &QueryResult,
    parts: impl Iterator<Item = &'p [Clause]>,
) -> Vec<Row> {
    let mut seeds = result_seed_rows(result);
    if seeds.is_empty() && parts_have_unit_output(parts) {
        seeds.push(Row::new());
    }
    seeds
}

pub(crate) fn execute_plan_read_seeded(
    graph: &ExecGraph<'_>,
    plan: &LogicalPlan,
    params: &BTreeMap<String, Value>,
    seeds: Vec<Row>,
    qctx: QueryCtx<'_>,
    sink: Option<&dyn PlanMetricsSink>,
) -> Result<QueryResult> {
    let result = walk_plan_stages(plan, 1, seeds, &|stage, part, part_clauses, part_seeds| {
        execute_part_read_seeded(
            graph,
            part_clauses,
            params,
            part_seeds,
            qctx,
            // The statement-level walker, read mode: the PROFILE site —
            // sink and this part's (stage, part) key, one fact — rides to
            // the clause loop here too.
            sink.map(|sink| PlanMetricsSite::at(sink, stage, part)),
        )
    })?;
    report_statement_memos(graph, sink);
    Ok(result)
}

/// Whether a finished stage seeds the next `NEXT` stage with one unit row
/// when its own result is empty (ADR-0287). Data-write parts
/// (`CREATE`/`MERGE`/`DELETE`/`SET`/`REMOVE`/`FOREACH`/`CALL { … }`) and
/// `FINISH` count, and so do schema/admin DDL parts — the IR-native
/// index/constraint variants outright, and `Clause::Catalog` exactly when
/// the canonical `relate-front` predicate says the command is NOT
/// row-producing. Row-producing catalog commands (the SHOW family and
/// `TERMINATE TRANSACTIONS`) keep their row semantics: they seed the next
/// stage from their projected rows, never with a unit row.
fn parts_have_unit_output<'p>(mut parts: impl Iterator<Item = &'p [Clause]>) -> bool {
    parts.all(|part| part.last().is_some_and(unit_output_clause))
}

/// Whether the clause concluding a part makes that part unit output: an
/// empty result still seeds the next `NEXT` stage with one row (ADR-0287).
/// [`clause_spills_rows`] decides it, plus the one arm this seeding policy
/// adds over that classification: `CALL { … }` is a data write in the
/// ADR-0287 vocabulary, even though its merged rows are a statement result
/// of its own.
fn unit_output_clause(clause: &Clause) -> bool {
    matches!(clause, Clause::CallSubquery { .. }) || !clause_spills_rows(clause)
}

/// Whether the clause concluding a part spills statement rows when it runs
/// — the planner's published [`clause_projects_rows`] table plus the one
/// refinement only this layer can make: a `WHEN`/`ELSE` conditional whose
/// branch bodies are all unit output spills no rows (the per-row driver's
/// buckets stay empty), so it projects none. Every concluding-clause
/// policy reads this one answer — the `CALL { … }` merge policy
/// ([`part_projects_rows`]), a conditional branch body's row-lessness and
/// the NEXT-stage seeding policy ([`unit_output_clause`]) — so a unit
/// conditional body is a unit body everywhere: its caller's outer rows
/// pass through, never drop, and its `IN TRANSACTIONS` iterations report
/// their status rows.
fn clause_spills_rows(clause: &Clause) -> bool {
    if !clause_projects_rows(clause) {
        return false;
    }
    match clause {
        Clause::Conditional {
            branches,
            else_query,
        } => call::conditional_produces_rows(branches, else_query.as_deref()),
        _ => true,
    }
}

/// Whether a part (one UNION arm) projects statement rows of its own — the
/// one classification over the concluding-clause vocabulary
/// ([`clause_spills_rows`]: the planner table plus the all-unit
/// conditional refinement), read by the `CALL { … }` merge policy and by a
/// conditional branch body's row-lessness (and, through
/// [`unit_output_clause`], by the NEXT-stage seeding policy).
pub(crate) fn part_projects_rows(clauses: &[Clause]) -> bool {
    clauses.last().is_none_or(clause_spills_rows)
}

#[cfg(test)]
mod aggregate_charge_tests;
#[cfg(test)]
mod aggregate_footprint_tests;
#[cfg(test)]
mod aggregate_percentile_tests;
#[cfg(test)]
mod aggregate_pool_tests;
#[cfg(test)]
mod aggregate_tests;
#[cfg(test)]
mod batch_limit_tests;
#[cfg(test)]
mod batch_tests;
#[cfg(test)]
mod breaker_stream_tests;
#[cfg(test)]
mod chunk_tests;
#[cfg(test)]
mod conditional_tests;
mod count_stats;
#[cfg(test)]
mod count_stats_tests;
#[cfg(test)]
mod direct_fold_tests;
#[cfg(test)]
mod effect_tests;
#[cfg(test)]
mod exists_probe_tests;
#[cfg(test)]
mod expand_tests;
#[cfg(test)]
mod far_node_tests;
mod foreach;
#[cfg(test)]
mod foreach_tests;
pub mod graph_stats;
#[cfg(test)]
mod graph_stats_tests;
#[cfg(test)]
mod id_seek_tests;
mod index_aggregates;
#[cfg(test)]
mod index_aggregates_tests;
#[cfg(test)]
mod integer_arg_tests;
#[cfg(test)]
mod kernels_tests;
mod label_set_groups;
#[cfg(test)]
mod label_set_groups_tests;
#[cfg(test)]
mod limit_where_tests;
#[cfg(test)]
mod match_chain_tests;
#[cfg(test)]
mod match_fold_tests;
#[cfg(test)]
mod match_memory_tests;
#[cfg(test)]
mod nested_eval_tests;
#[cfg(test)]
mod one_hop_fold_tests;
#[cfg(test)]
mod path_fold_tests;
#[cfg(test)]
mod pivot_tests;
#[cfg(test)]
mod predicate_spec_tests;
#[cfg(test)]
mod procedures_tests;
#[cfg(test)]
mod profiling_tests;
#[cfg(test)]
mod project_tests;
#[cfg(test)]
mod pushdown_tests;
#[cfg(test)]
mod range_start_tests;
#[cfg(test)]
mod rel_list_binding_tests;
#[cfg(test)]
mod rel_seek_tests;
#[cfg(test)]
mod seek_readiness_tests;
mod shortcut_common;
#[cfg(test)]
mod shortest_expression_tests;
#[cfg(test)]
mod shortest_path_tests;
#[cfg(test)]
mod stream_agg_tests;
#[cfg(test)]
mod subquery_eval_tests;
#[cfg(test)]
pub(crate) mod test_support;
#[cfg(test)]
mod text_seek_tests;