Skip to main content

waratah_compute/
plan.rs

1//! SPARQL algebra parsing and logical planning.
2//!
3//! Pipeline: `spargebra` parse → `sparopt` rewrite → FILTER-forced OPTIONAL to
4//! inner join → Waratah physical lower.
5//! [`LogicalPlan::parse`] is `SELECT`-only; CONSTRUCT / DESCRIBE / ASK reuse
6//! [`LogicalPlan::from_algebra`] on the WHERE `GraphPattern`.
7//! [`LogicalPlan::explain`] (in `explain.rs`) accepts all four forms. Physical
8//! scan order and [`JoinStrategy`] stay Waratah-owned (sketches + Phase 9a2
9//! costing). Supported algebra: BGP, JOIN, FILTER, OPTIONAL (LeftJoin), UNION,
10//! VALUES, BIND / non-aggregate Extend, GROUP BY / HAVING, aggregates (`COUNT`,
11//! `SUM`, `AVG`, `MIN`, `MAX`, `SAMPLE`, `GROUP_CONCAT`, including `DISTINCT`
12//! where it changes the result), property paths (`*`, `+`, `?`, `|`, `!`,
13//! nested `/`), `GRAPH`, `FROM` / `FROM NAMED`, LIMIT / OFFSET, `ORDER BY`, and nested
14//! `SELECT` (SubSelect) as an opaque [`PlanNode::SubSelect`] boundary.
15//! Top-level `FILTER EXISTS` / `NOT EXISTS` conjuncts lower to
16//! [`ExistsClause`] (uncorrelated ASK, simple-BGP semi-join, or nested probe).
17//! Other `EXISTS` placements stay [`ComputeError::UnsupportedSparql`] — the
18//! list is on [`ExistsClause`]. Anything else is a typed
19//! [`ComputeError::UnsupportedSparql`].
20
21use std::sync::Arc;
22
23use rustc_hash::FxHashMap;
24
25use crate::query::caches::SCAN_MEMO_MAX_ENTRY_ROWS;
26use crate::query::scan_memo_eligible;
27use spargebra::Query;
28use spargebra::algebra::{
29    AggregateExpression, AggregateFunction, Expression, GraphPattern, OrderExpression,
30    PropertyPathExpression,
31};
32use spargebra::term::{GroundTerm, NamedNodePattern, TermPattern, TriplePattern};
33use waratah_proto::PatternSlot;
34use waratah_proto::{OMIT_GRAPH, OMIT_OBJECT, OMIT_PREDICATE, OMIT_SUBJECT};
35use waratah_stats::{
36    ExtraBoundSlots, GRAPH_FILTER_TERM_CAP, JoinKeySlot, JoinStrategy, PUSHDOWN_TERMS_LIMIT,
37    StatsProfile, VOCABULARY_OVERLAP_FULL_MILLI, bound_slots, estimate_join_key_domain,
38    estimate_join_rows_multi, estimate_pattern, estimate_pattern_with_bound_slots,
39    estimate_vocabulary_overlap, named_node_hash, pattern_is_point_lookup,
40};
41use waratah_storage::{
42    DomainCountMode, EncodedTerm, EncodedTriplePattern, IndexPermutation, IriOnlyMask,
43    PartitionAxis, QuadSlot, RDF_TYPE, SlotComparison, SnapshotId, StrHash, Term, Variable,
44    encode_term_bytes,
45};
46
47use crate::context::QueryContext;
48use crate::dataset::{
49    ComposedGraph, DefaultGraphWindow, GraphFilter, GraphScope, NamedGraphWindow, NamedVarWindow,
50    QueryDataset, push_graph_terms,
51};
52use crate::error::ComputeError;
53use crate::expr::{ExprCapability, and_fold, classify, flatten_and, variables_in_expression};
54use crate::liveness::{JoinSemiContext, annotate_liveness};
55
56/// Whether a scan slot column is projected downstream.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Liveness {
59    /// Column is part of the solution mapping above this scan.
60    Live,
61    /// Column is not projected, but its rows are needed for counting.
62    Counted,
63    /// Column is not projected and not counted, bag mark is ignored.
64    Dead,
65}
66
67/// Per-variable bag mark after the liveness walk.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum BagMark {
70    /// Required, and duplicate values may be collapsed (`DISTINCT ON` key).
71    /// The one meaning across liveness states: set semantics suffice. Live
72    /// columns may collapse to distinct rows; counted columns count distinct
73    /// terms instead of rows.
74    Insensitive,
75    /// Multiplicity must be kept. Live columns are payload (bag SELECT,
76    /// value aggregates). Counted columns count rows (`COUNT(?v)`,
77    /// `COUNT(*)`): the value is not projected, but the row is not a
78    /// collapse key.
79    Sensitive,
80}
81
82/// Liveness plus bag mark stamped on every scan slot after [`crate::liveness::annotate_liveness`].
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct SlotMark {
85    /// Whether the slot column is kept in scan output.
86    pub liveness: Liveness,
87    /// Whether duplicate values on this column may collapse.
88    ///
89    /// [`BagMark::Insensitive`] on a live column is a DISTINCT/GROUP collapse
90    /// key. [`BagMark::Sensitive`] keeps multiplicity, live or dead.
91    pub bag: BagMark,
92}
93
94impl SlotMark {
95    /// Live payload column; row multiplicity must be preserved.
96    pub const LIVE_SENSITIVE: Self = Self {
97        liveness: Liveness::Live,
98        bag: BagMark::Sensitive,
99    };
100    /// Live key eligible for DISTINCT/collapse (`DISTINCT ON`, GROUP BY key).
101    pub const LIVE_INSENSITIVE: Self = Self {
102        liveness: Liveness::Live,
103        bag: BagMark::Insensitive,
104    };
105    /// Unreferenced slot — safe to drop from output and skip-scans.
106    pub const DEAD: Self = Self {
107        liveness: Liveness::Dead,
108        bag: BagMark::Insensitive,
109    };
110    /// Counted column whose row multiplicity is still required (`COUNT(?v)`
111    /// or plain `COUNT(*)`). The value is not projected; a partition-side
112    /// run-length row count stands in for the column.
113    pub const COUNTED_SENSITIVE: Self = Self {
114        liveness: Liveness::Counted,
115        bag: BagMark::Sensitive,
116    };
117    /// Counted column whose distinct term cardinality is all that is
118    /// required (`COUNT(DISTINCT ?v)` over a dead slot, `COUNT(DISTINCT ?g)`
119    /// over the graph slot). The value is not projected; the partition
120    /// counts distinct terms per run instead.
121    pub const COUNTED_INSENSITIVE: Self = Self {
122        liveness: Liveness::Counted,
123        bag: BagMark::Insensitive,
124    };
125}
126
127/// Slot roles shared by the distinct domain scan and the domain count scan.
128///
129/// Slot 0 is a known constraint (pattern constant, grounded-kept term, or
130/// broadcast term set). Slot 1 is the head. The remaining slot is dead to the
131/// RPC. [`ScanOp::domain_scan`] emits **distinct** heads and requires that
132/// head to be live and bag-insensitive, with the dead slot dropped.
133/// [`ScanOp::domain_counts`] walks the same prefixes but returns each head's
134/// run length; the dead slot may be counted (`COUNT(?v)` / `COUNT(*)`) and
135/// the head may be bag-sensitive.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum DomainScanKind {
138    /// POSG: constraint predicate(s), dead subject, object head.
139    PredicateDomain,
140    /// PSOG: constraint predicate(s), dead object, subject head.
141    PredicateSubjects,
142    /// SPOG: constraint subject(s), dead object, predicate head.
143    SubjectPreds,
144    /// SOPG: constraint subject(s), dead predicate, object head.
145    SubjectDomain,
146    /// OPSG: constraint object(s), dead subject, predicate head.
147    ObjectPreds,
148}
149
150/// All domain-scan kinds in first-match order. The order is semantic: two
151/// kinds can share a head slot, so a rewrite for the O head must meet
152/// `PredicateDomain` before `SubjectDomain`, and one for the P head must
153/// meet `SubjectPreds` before `ObjectPreds`. Every stamp/rewrite matcher
154/// iterates this constant, so adding a kind here makes it visible to all
155/// of them in the same order.
156pub(crate) const DOMAIN_SCAN_KINDS: [DomainScanKind; 5] = [
157    DomainScanKind::PredicateDomain,
158    DomainScanKind::PredicateSubjects,
159    DomainScanKind::SubjectPreds,
160    DomainScanKind::SubjectDomain,
161    DomainScanKind::ObjectPreds,
162];
163
164impl DomainScanKind {
165    /// Axis-local CF the rewrite skip-scans.
166    pub fn permutation(self) -> IndexPermutation {
167        match self {
168            Self::PredicateDomain => IndexPermutation::Posg,
169            Self::PredicateSubjects => IndexPermutation::Psog,
170            Self::SubjectPreds => IndexPermutation::Spog,
171            Self::SubjectDomain => IndexPermutation::Sopg,
172            Self::ObjectPreds => IndexPermutation::Opsg,
173        }
174    }
175
176    /// Partition axis owning [`Self::permutation`].
177    pub fn axis(self) -> PartitionAxis {
178        self.permutation().into()
179    }
180
181    /// Pattern slot holding the known constraint term(s).
182    pub fn constraint_slot(self) -> PatternSlot {
183        match self {
184            Self::PredicateDomain | Self::PredicateSubjects => PatternSlot::Predicate,
185            Self::SubjectPreds | Self::SubjectDomain => PatternSlot::Subject,
186            Self::ObjectPreds => PatternSlot::Object,
187        }
188    }
189
190    /// Pattern slot of the head (distinct terms, or the counted run).
191    pub fn head_slot(self) -> PatternSlot {
192        match self {
193            Self::PredicateDomain | Self::SubjectDomain => PatternSlot::Object,
194            Self::PredicateSubjects => PatternSlot::Subject,
195            Self::SubjectPreds | Self::ObjectPreds => PatternSlot::Predicate,
196        }
197    }
198
199    /// Pattern slot the RPC does not return. Distinct scans require it
200    /// dropped; count scans may still need its multiplicity.
201    pub fn dead_slot(self) -> PatternSlot {
202        match self {
203            Self::PredicateDomain | Self::ObjectPreds => PatternSlot::Subject,
204            Self::PredicateSubjects | Self::SubjectPreds => PatternSlot::Object,
205            Self::SubjectDomain => PatternSlot::Predicate,
206        }
207    }
208
209    /// Lower-case name for EXPLAIN.
210    pub fn name(self) -> &'static str {
211        match self {
212            Self::PredicateDomain => "predicate_domain",
213            Self::PredicateSubjects => "predicate_subjects",
214            Self::SubjectPreds => "subject_preds",
215            Self::SubjectDomain => "subject_domain",
216            Self::ObjectPreds => "object_preds",
217        }
218    }
219}
220
221/// Which bare axis-head-scan rewrite a [`ScanOp`] uses.
222///
223/// No anchor terms at all: the RPC walks slot 0 of one whole CF and returns
224/// the **distinct** head terms. Both non-head slots are dead.
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226pub enum HeadScanKind {
227    /// SPOG: distinct subjects.
228    Subjects,
229    /// PSOG: distinct predicates.
230    Predicates,
231    /// OPSG: distinct objects.
232    Objects,
233    /// TSG: distinct classes (`rdf:type` objects; TSG stores only type
234    /// triples, so the predicate is implicit).
235    Classes,
236}
237
238impl HeadScanKind {
239    /// Axis-local CF the rewrite walks.
240    pub fn permutation(self) -> IndexPermutation {
241        match self {
242            Self::Subjects => IndexPermutation::Spog,
243            Self::Predicates => IndexPermutation::Psog,
244            Self::Objects => IndexPermutation::Opsg,
245            Self::Classes => IndexPermutation::Tsg,
246        }
247    }
248
249    /// Partition axis owning [`Self::permutation`].
250    pub fn axis(self) -> PartitionAxis {
251        self.permutation().into()
252    }
253
254    /// Pattern slot the RPC emits distinct head terms of.
255    pub fn head_slot(self) -> PatternSlot {
256        match self {
257            Self::Subjects => PatternSlot::Subject,
258            Self::Predicates => PatternSlot::Predicate,
259            Self::Objects | Self::Classes => PatternSlot::Object,
260        }
261    }
262
263    /// Lower-case name for EXPLAIN.
264    pub fn name(self) -> &'static str {
265        match self {
266            Self::Subjects => "subjects",
267            Self::Predicates => "predicates",
268            Self::Objects => "objects",
269            Self::Classes => "classes",
270        }
271    }
272}
273
274/// Why a scan's join-key domain is (or is not) cached in
275/// [`ScanOp::join_domains`]. Only `Known` is returned to pricing; every other
276/// state recomputes from the live pattern, so a missed refresh costs time,
277/// never correctness.
278///
279/// # Known limitation: stamps are scan-local
280///
281/// The stamp inputs are exactly `profile × pattern`. `IncomingBound`, the
282/// driver arm, and pushed value lists are deliberately not inputs, so a scan
283/// moved by an arm swap or join reassociation can never inherit a stamp
284/// derived under its old join context. A variable that is merely
285/// incoming-bound therefore stays a free pattern slot here: an `rdf:type`
286/// subject whose class is runtime-bound cannot use `class_counts[class]`,
287/// and pricing stays on the live predicate-level subject HLL. Exploiting
288/// `class_counts` for that shape would need a context-aware pricing path,
289/// not this cache.
290#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
291pub(crate) enum JoinDomainStamp {
292    /// No non-empty profile was available when the stamp was taken.
293    #[default]
294    NoProfile,
295    /// The predicate was still a variable; both slot answers are deferred
296    /// until a later pass binds it.
297    UnknownPredicate,
298    /// The predicate is bound, but the answer reads a slot that was still
299    /// free at stamp time — today only `rdf:type` + Subject + a free object
300    /// when `class_counts` is non-empty, so a later *plan-time* grounding can
301    /// select an exact class count. An incoming-bound variable is not
302    /// binding here: it names no term, and stamps are scan-local.
303    Deferred,
304    /// The predicate is bound, but the live estimator has no answer (no
305    /// named predicate hash or no HLL for it).
306    Unavailable,
307    /// Every input the answer reads was bound; the value cannot change.
308    Known(u64),
309}
310
311/// Per-slot [`JoinDomainStamp`] pair carried by every [`ScanOp`].
312#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
313pub(crate) struct JoinDomainStamps {
314    subject: JoinDomainStamp,
315    object: JoinDomainStamp,
316}
317
318impl JoinDomainStamps {
319    /// Classify both slots from the pattern as it stands now.
320    fn classify(profile: Option<&StatsProfile>, pattern: &EncodedTriplePattern) -> Self {
321        Self {
322            subject: JoinDomainStamp::classify(profile, pattern, JoinKeySlot::Subject),
323            object: JoinDomainStamp::classify(profile, pattern, JoinKeySlot::Object),
324        }
325    }
326
327    fn get(self, slot: JoinKeySlot) -> JoinDomainStamp {
328        match slot {
329            JoinKeySlot::Subject => self.subject,
330            JoinKeySlot::Object => self.object,
331        }
332    }
333}
334
335impl JoinDomainStamp {
336    fn classify(
337        profile: Option<&StatsProfile>,
338        pattern: &EncodedTriplePattern,
339        slot: JoinKeySlot,
340    ) -> Self {
341        let Some(profile) = profile.filter(|p| !p.is_empty()) else {
342            return Self::NoProfile;
343        };
344        let Some(predicate) = pattern.predicate.as_ref() else {
345            return Self::UnknownPredicate;
346        };
347        // `rdf:type` + Subject is the one answer that reads the object term:
348        // a bound class selects `class_counts[class]` when present (else the
349        // predicate-level HLL), while a still-free object slot means a later
350        // plan-time grounding can change the answer. "Incoming-bound" is not
351        // binding for this purpose: `IncomingBound` carries a distinct-count
352        // estimate, never the concrete runtime term, and these stamps are
353        // scan-local (`profile × pattern`) so arm swaps/reassociation cannot
354        // leave context-derived state behind. A runtime-bound class therefore
355        // stays `Deferred` and prices from the live predicate-level HLL.
356        // Defer only when an exact class
357        // count could make that change possible: with no `class_counts`
358        // entries, binding the object cannot change the subject answer, so
359        // the ordinary estimator may cache the subject HLL (or report
360        // `Unavailable`).
361        if slot == JoinKeySlot::Subject
362            && predicate == &RDF_TYPE
363            && pattern.object.is_none()
364            && !profile.class_counts.is_empty()
365        {
366            return Self::Deferred;
367        }
368        match estimate_join_key_domain(profile, pattern, slot) {
369            Some(domain) => Self::Known(domain),
370            None => Self::Unavailable,
371        }
372    }
373}
374
375/// One triple pattern resolved to an encoded scan plus its variable slots.
376#[derive(Debug, Clone, PartialEq)]
377pub struct ScanOp {
378    /// Encoded ground slots; `None` slots are variables.
379    pub pattern: EncodedTriplePattern,
380    /// Variable bound by the subject slot, if any.
381    pub subject: Option<Variable>,
382    /// Variable bound by the predicate slot, if any.
383    pub predicate: Option<Variable>,
384    /// Variable bound by the object slot, if any.
385    pub object: Option<Variable>,
386    /// Variable bound by the graph slot (`GRAPH ?g`), if any.
387    pub graph: Option<Variable>,
388    /// Estimated cardinality from the local sketch cache (1 when unknown).
389    pub produced_row_count_estimate: u64,
390    /// Return-row bound an ANCESTOR join's broadcast push imposes on this
391    /// scan: the claimer's pushed value list filters this scan's reads in
392    /// every seating of the joins below the claimer, so the pushed-return
393    /// estimate (`pushed_scan_return_bound`) is the scan's true whole read
394    /// there — a number this scan cannot recompute locally (the claimer's
395    /// driver domain lives in a subtree above it). The round-entry recost
396    /// bounds [`Self::produced_row_count_estimate`] at this value so inner
397    /// seating decisions price the bounded read, not catalog size (the
398    /// transects defect: an inner join re-pricing an ancestor-pushed arm
399    /// at its ~8M whole read instead of the ~1.5k the push returns).
400    /// Joins BELOW the claimer read it as an orientation-invariant driver
401    /// term (a foreign claim for them — `driver_whole_read_rows` prices the
402    /// bounded cell). The claimer's OWN next-round reads are
403    /// ownership-aware: the recost keeps the cell at the bound (correct
404    /// for the probe road, `produced`, EXPLAIN), but the seating's driver
405    /// term prices the intrinsic — the probe road's clamped return is not
406    /// a driving read (the tenant-union flip: an own-claim cell of ~80
407    /// priced a 50k-catalog arm as a phantom-cheap driver).
408    /// Writers: `clamp_broadcast_probe_estimates` (re-derived each round
409    /// against the claimer's settled driver — one round stale, the
410    /// pipeline's standard epistemic class) and the claim walk
411    /// `claim_broadcast_probe`, which stamps mark and bound as a pair so
412    /// a fresh claim carries its bound immediately. Sole
413    /// remover: `clear_broadcast_marks` — this bound's lifetime is exactly
414    /// the `broadcasted` claim mark's.
415    pub ancestor_push_return_bound: Option<u64>,
416    /// Runtime allow-list hint: join key probed on this slot (EXPLAIN /
417    /// costing only; execution still uses left solution values / runtime
418    /// `PushedKeyVals`). One variable, one slot — the wire filter is still a
419    /// single `BroadcastFilter`. Sole writer: `restamp_broadcast_marks`
420    /// (pre-order claim, first/outermost claim wins); sole remover: the
421    /// swap-time `clear_broadcast_marks` in `refinalize_joins`.
422    pub broadcasted: Option<(Variable, PatternSlot)>,
423    /// Plan-time fetch-once stamp: the priced trigger
424    /// decided this probe arm's per-page key-list broadcast costs more than
425    /// `MARGIN ×` one whole read, so the executor takes the built
426    /// (`Unfiltered`-shaped) arm from page 1 — it never enters
427    /// `join_keys_scan_filter`, skips the coverage machinery, and creates
428    /// no memo entries (the built table is the reuse structure). The
429    /// carried value is the UNCLAMPED arm row estimate the predicate
430    /// priced against (`estimate_unclamped_scan_rows` — NOT the push-clamped
431    /// `produced_row_count_estimate`, which answers what the arm returns
432    /// UNDER pushes): the runtime bail-out compares the drained rows
433    /// against exactly this number. Sole writer: `restamp_fetch_once`,
434    /// after the last seating round; readers: `execute_join`'s scan branch,
435    /// the concurrent-star probe fetch (eager path only — a
436    /// demand-bounded `LIMIT` pull must not over-drain), and
437    /// `fetch_whole`'s publish gate. Pure transport hint: rows are
438    /// identical either way.
439    pub fetch_once: Option<u64>,
440    /// Residual G allow-list or block-list (not a `PatternSlot`).
441    pub graph_filter: Option<GraphFilter>,
442    /// Plan-time grounded slots: variable names stay for projection; the
443    /// encoded term lives in `pattern`. Same variable may appear twice
444    /// (`?b` subject and object on `?b a ?b`).
445    pub grounded: Vec<(Variable, PatternSlot)>,
446    /// SPARQL default-graph RDF merge. Set when [`GraphScope::Default`] uses
447    /// [`DefaultGraphWindow::AllGraphs`] or [`DefaultGraphWindow::Allow`].
448    /// Storage emits each S/P/O once and rewrites G to DefaultGraph (not
449    /// user-visible: this scan does not project G). Never set inside `GRAPH`.
450    pub merge_default_graph: bool,
451    /// Per-slot liveness and bag marks. Empty = not yet annotated (every slot
452    /// name behaves as live bag-sensitive — see [`ScanOp::slot_mark`]).
453    pub marks: Vec<(Variable, Liveness, BagMark)>,
454    /// Execute via the constrained `DomainScan` RPC (known slot-0 constraint
455    /// → distinct slot-1 head terms) instead of a triple `ScanPattern`.
456    pub domain_scan: Option<DomainScanKind>,
457    /// Execute via the bare `AxisHeadScan` RPC (distinct slot-0 head terms of
458    /// one whole CF) instead of a triple `ScanPattern`. Mutually exclusive
459    /// with [`ScanOp::domain_scan`]; the liveness gates guarantee it.
460    pub head_scan: Option<HeadScanKind>,
461    /// Execute via the `DomainScanCounts` RPC (per-`(constraint, head)` run
462    /// lengths) instead of a triple `ScanPattern`: the bag consumer — a live
463    /// bag-SENSITIVE head slot whose values a plain scan would stream whole.
464    /// Run-length pairs reconstruct that identical multiset client-side.
465    /// Mutually exclusive with [`ScanOp::domain_scan`] and [`ScanOp::head_scan`].
466    pub domain_counts: Option<DomainScanKind>,
467    /// Execute via the `AxisHeadScanCounts` RPC instead of a triple
468    /// `ScanPattern`: `TOTAL` (the head slot is counted-distinct and the
469    /// head count is the group result) or `PER_HEAD` (the head is a live
470    /// group key, the slot-1 variable counted-distinct). Which of the two a
471    /// scan serves follows from the marks — see [`ScanOp::head_count_is_total`].
472    /// Mutually exclusive with the other scan rewrites.
473    pub head_scan_counts: Option<HeadScanKind>,
474    /// Variables the planner proved IRI-valued via kept `FILTER(isIRI(?x))`
475    /// conjuncts (see [`crate::iri_facts`]). Pushed to partitions as an S/O
476    /// first-byte pre-filter via [`Self::iri_only_slots`]; the filter
477    /// conjunct itself always stays in the plan — in the OPTIONAL case it is
478    /// what eliminates the unbound-extension rows.
479    pub iri_only: Vec<Variable>,
480    /// Slot comparisons derived from kept `FILTER(?v OP literal)` conjuncts
481    /// above this scan. The one plan-side record of these conjuncts; the
482    /// partition's wire list is derived from it at request build
483    /// ([`Self::pushed_comparisons`]). The conjunct stays in the plan and
484    /// remains authoritative: both the partition and the compute-side eager
485    /// filter drop only rows the comparison provably fails and keep every
486    /// row they cannot decide. Empty for scans with no such filter. See
487    /// [`crate::scan_comparisons`] and [`crate::scan_eager`].
488    pub eager: Vec<SlotComparison>,
489    /// Cached join-key domains, classified at construction and refreshed by
490    /// [`Self::record_grounded`] after a plan-time slot binding. Only a
491    /// [`JoinDomainStamp::Known`] value short-circuits pricing; the other
492    /// states recompute live. The concurrent-star predicate reads a
493    /// [`JoinDomainStamp::Known`] value as the driver page's distinct-key
494    /// bound ([`Self::known_join_domain`]). Fetch routing does not.
495    pub(crate) join_domains: JoinDomainStamps,
496}
497
498/// One derivation of a scan's output slot structure, produced by
499/// [`ScanOp::output_slots`] and consumed by every view that used to walk the
500/// S/P/O/G slots independently: [`ScanOp::materialized_variables`] (the page
501/// schema, and the live list in [`crate::query::caches::ScanMemoKey`]),
502/// [`ScanOp::repeat_slot_pairs`] (the memo-key repeat identity and the
503/// dead-slot rule of [`ScanOp::omitted_slots`]), and
504/// [`crate::solutions::EncodedSolutions::from_scan`] (schema, column
505/// mapping, and repeated-variable row filter). Keeping a single walk means
506/// those views cannot drift apart — the memo key bakes two of them into
507/// cached entries, so a drift would silently serve rows filtered by a
508/// different rule than the consumer expects.
509#[derive(Debug, Clone, PartialEq, Eq)]
510pub struct ScanOutputSlots {
511    /// Slot variables in S/P/O/G order; `None` where the slot carries no
512    /// variable (an unbound slot). Test-only — the derived views carry
513    /// everything production reads, so building this array (four
514    /// `Variable` clones per derivation) is skipped outside `cfg(test)`.
515    #[cfg(test)]
516    pub slots: [Option<Variable>; 4],
517    /// Same-name slot pairs as `(first, later)` slot indices (0=S, 1=P, 2=O,
518    /// 3=G). A pair survives even when the name is dropped: the
519    /// repeated-variable row filter must still compare the two slots
520    /// (`?a :p ?a` and a dead-named `?a :p ?a` filter alike; `?a :p ?dead`
521    /// does not).
522    pub repeats: Vec<(u8, u8)>,
523    /// Materialized output columns in first-appearance order: slot index
524    /// plus the variable it carries. Dropped names are excluded; a repeated
525    /// name appears once, at its first slot.
526    pub materialized: Vec<(u8, Variable)>,
527}
528
529impl ScanOp {
530    /// Build a minimal scan for a **plugin-minted** plan (the text plugin's
531    /// subject-mode predicate scan): variables bound in the two named
532    /// slots, every mark / stamp / estimate knob at its fresh default.
533    ///
534    /// Not for the SPARQL lowering path — `lower_pattern`'s constructor
535    /// carries the dataset scoping, sketch estimates, and join-domain
536    /// classification a lowered BGP needs. A plugin-minted scan reads at
537    /// the query snapshot like every scan; the graph-scope fields must be
538    /// copied from a sibling scan's [`ScanOp::applied_graph`] (or the
539    /// dataset fallback, [`applied_default_graph`]) so the minted scan sees
540    /// exactly the graphs the surrounding BGP sees.
541    pub fn for_plugin_pattern(
542        pattern: EncodedTriplePattern,
543        subject: Variable,
544        object: Variable,
545        graph: Option<Variable>,
546        graph_filter: Option<GraphFilter>,
547        merge_default_graph: bool,
548        produced_row_count_estimate: u64,
549    ) -> Self {
550        Self {
551            fetch_once: None,
552            ancestor_push_return_bound: None,
553            pattern,
554            subject: Some(subject),
555            predicate: None,
556            object: Some(object),
557            graph,
558            produced_row_count_estimate,
559            broadcasted: None,
560            graph_filter,
561            grounded: Vec::new(),
562            merge_default_graph,
563            marks: Vec::new(),
564            domain_scan: None,
565            head_scan: None,
566            head_scan_counts: None,
567            domain_counts: None,
568            iri_only: Vec::new(),
569            eager: Vec::new(),
570            join_domains: JoinDomainStamps::default(),
571        }
572    }
573
574    /// The applied graph scope this scan reads: the four fields that decide
575    /// which graphs it may see. Ground truth for its plan position —
576    /// plugin-minted scans copy this from a sibling scan so their visibility
577    /// matches the surrounding BGP.
578    pub fn applied_graph(&self) -> AppliedGraph {
579        AppliedGraph {
580            graph_name: self.pattern.graph_name.clone(),
581            graph: self.graph.clone(),
582            graph_filter: self.graph_filter.clone(),
583            merge_default_graph: self.merge_default_graph,
584        }
585    }
586
587    /// Variables this scan produces for downstream operators (live names only),
588    /// in subject/predicate/object/graph order. Dead+Counted slots are omitted here
589    /// but appear in [`Self::materialized_variables`] / [`EncodedSolutions::from_scan`].
590    pub fn variables(&self) -> Vec<Variable> {
591        let mut out = Vec::new();
592        for variable in [&self.subject, &self.predicate, &self.object, &self.graph]
593            .into_iter()
594            .flatten()
595        {
596            if !self.is_live(variable) {
597                continue;
598            }
599            if !out.contains(variable) {
600                out.push(variable.clone());
601            }
602        }
603        out
604    }
605
606    /// Single derivation of this scan's output slot structure — see
607    /// [`ScanOutputSlots`] for who consumes which field. Every former
608    /// independent slot walk builds on this, so the page schema, the memo
609    /// key, and `from_scan`'s row filter stay in agreement by construction.
610    pub fn output_slots(&self) -> ScanOutputSlots {
611        let names = [
612            self.subject.as_ref(),
613            self.predicate.as_ref(),
614            self.object.as_ref(),
615            self.graph.as_ref(),
616        ];
617        let mut first: Vec<(&Variable, u8)> = Vec::new();
618        let mut repeats = Vec::new();
619        let mut materialized = Vec::new();
620        for (i, variable) in names.iter().enumerate() {
621            let Some(variable) = variable else { continue };
622            if let Some((_, first_i)) = first.iter().find(|(name, _)| *name == *variable) {
623                repeats.push((*first_i, i as u8));
624                continue;
625            }
626            first.push((variable, i as u8));
627            if !self.is_dropped(variable) {
628                materialized.push((i as u8, (*variable).clone()));
629            }
630        }
631        ScanOutputSlots {
632            #[cfg(test)]
633            slots: [
634                self.subject.clone(),
635                self.predicate.clone(),
636                self.object.clone(),
637                self.graph.clone(),
638            ],
639            repeats,
640            materialized,
641        }
642    }
643
644    /// Live and Counted slot names in S/P/O/G order — schema for scan pages built
645    /// by [`EncodedSolutions::from_scan`]. Only `Dead` slots are excluded:
646    /// the run-length RPC stands in for counted columns on the count path,
647    /// but a plain scan still broadcasts the values, and a counted-distinct slot
648    /// must stay resolvable compute-side whenever the count rewrite does not
649    /// serve it.
650    ///
651    /// Derived from the single [`ScanOp::output_slots`] walk.
652    pub fn materialized_variables(&self) -> Vec<Variable> {
653        self.output_slots()
654            .materialized
655            .into_iter()
656            .map(|(_, variable)| variable)
657            .collect()
658    }
659
660    /// Response slots this scan can ask the partition to leave empty
661    /// (`ScanPatternRequest.omitted_slots`).
662    ///
663    /// A slot is omitted only when the receiver can put back exactly the term
664    /// an unomitted response would have carried, in one of two ways:
665    ///
666    /// - **Bound**: the effective pattern binds the slot — a constant in the
667    ///   query, or a term the executor just pinned with a broadcast push.
668    ///   Reassembly returns that term, so the row is identical to a full one
669    ///   and a cursor built from it encodes the same key. This bit is safe on
670    ///   every request shape: unary pages, windowed pulls, and resumable
671    ///   streams alike.
672    /// - **Dead** (`allow_dead` only): the slot carries a variable nothing
673    ///   downstream reads — dropped, and not part of a repeated-variable row
674    ///   filter. Reassembly returns the counted-presence sentinel instead of
675    ///   the stored term, which is a value change: a cursor built from such a
676    ///   row would encode a wrong key. Callers therefore set `allow_dead` only
677    ///   on requests whose rows can never become a `start_after` (a drain with
678    ///   no cursor that restarts on retry), never on paged or resumable ones.
679    ///
680    /// `effective` must be the pattern the request actually carries, not
681    /// `self.pattern`: grounding rewrites slots at execution time.
682    pub fn omitted_slots(&self, effective: &EncodedTriplePattern, allow_dead: bool) -> u8 {
683        let repeats = self.repeat_slot_pairs();
684        let mut omitted = 0u8;
685        let slots = [
686            (&self.subject, &effective.subject, OMIT_SUBJECT, 0u8),
687            (&self.predicate, &effective.predicate, OMIT_PREDICATE, 1),
688            (&self.object, &effective.object, OMIT_OBJECT, 2),
689            (&self.graph, &effective.graph_name, OMIT_GRAPH, 3),
690        ];
691        for (variable, bound, bit, index) in slots {
692            // A slot a pushed comparison reads must survive on every request
693            // shape: the compute-side FILTER evaluates the same conjunct on
694            // the row, so neither the counted-presence sentinel nor a
695            // restored bound term stands in for the stored term here.
696            if self.comparison_reads(index) {
697                continue;
698            }
699            if bound.is_some() {
700                omitted |= bit;
701                continue;
702            }
703            if !allow_dead {
704                continue;
705            }
706            let dead = match variable {
707                Some(variable) => self.is_dropped(variable),
708                // No variable and no bound term: nothing names this slot, so
709                // no consumer can read it.
710                None => true,
711            };
712            let repeated = repeats.iter().any(|(a, b)| *a == index || *b == index);
713            if dead && !repeated {
714                omitted |= bit;
715            }
716        }
717        omitted
718    }
719
720    /// Whether a pushed comparison reads this slot (`0` = S, `1` = P, `2` = O,
721    /// `3` = G). Such a slot is never omitted: the compute-side FILTER keeps
722    /// evaluating the same conjunct on the row, so the stored term has to
723    /// arrive unchanged even when the slot is dead or pattern-bound.
724    fn comparison_reads(&self, index: u8) -> bool {
725        let slot = match index {
726            0 => QuadSlot::Subject,
727            1 => QuadSlot::Predicate,
728            2 => QuadSlot::Object,
729            _ => QuadSlot::Graph,
730        };
731        self.eager.iter().any(|comparison| comparison.slot == slot)
732    }
733
734    /// Same-name slot pairs in S/P/O/G order as `(first, later)` slot
735    /// indices (0=S, 1=P, 2=O, 3=G) — the identity of
736    /// [`EncodedSolutions::from_scan`]'s repeated-variable row filter.
737    /// Part of the scan memo key: a cached table bakes the filter in, so
738    /// `?a :p ?a` and `?a :p ?dead` must never share an entry even when
739    /// their live column lists coincide (`materialized_variables`
740    /// deduplicates by name).
741    ///
742    /// Derived from the single [`ScanOp::output_slots`] walk.
743    pub fn repeat_slot_pairs(&self) -> Vec<(u8, u8)> {
744        self.output_slots().repeats
745    }
746
747    /// Slot names in S/P/O/G order, including dead repeats (`?x ?p ?x`).
748    pub fn slot_variables(&self) -> Vec<Variable> {
749        let mut out = Vec::new();
750        for variable in [&self.subject, &self.predicate, &self.object, &self.graph]
751            .into_iter()
752            .flatten()
753        {
754            if !out.contains(variable) {
755                out.push(variable.clone());
756            }
757        }
758        out
759    }
760
761    /// Full mark for a slot name. `None` when `variable` is not a slot.
762    pub fn slot_mark(&self, variable: &Variable) -> Option<SlotMark> {
763        if let Some((_, liveness, bag)) = self.marks.iter().find(|(v, _, _)| v == variable) {
764            return Some(SlotMark {
765                liveness: *liveness,
766                bag: *bag,
767            });
768        }
769        if self.marks.is_empty() {
770            let on_scan = [&self.subject, &self.predicate, &self.object, &self.graph]
771                .into_iter()
772                .flatten()
773                .any(|v| v == variable);
774            return on_scan.then_some(SlotMark::LIVE_SENSITIVE);
775        }
776        None
777    }
778
779    /// Bag mark for a slot. `None` when `variable` is not a slot on this scan.
780    pub fn bag_mark(&self, variable: &Variable) -> Option<BagMark> {
781        self.slot_mark(variable).map(|m| m.bag)
782    }
783
784    /// Whether `variable` is a live output column.
785    pub fn is_live(&self, variable: &Variable) -> bool {
786        self.slot_mark(variable)
787            .is_some_and(|m| m.liveness == Liveness::Live)
788    }
789
790    /// Whether `variable` is a dead slot whose column may be omitted. Not
791    /// relevant for a slot a pushed comparison reads (see
792    /// [`Self::comparison_reads`]).
793    pub fn is_dropped(&self, variable: &Variable) -> bool {
794        self.slot_mark(variable)
795            .is_some_and(|m| m.liveness == Liveness::Dead)
796    }
797
798    /// Force `variable` to stay in this scan's materialized output.
799    ///
800    /// Belt and braces for the eager comparison filter: a compared slot has to
801    /// reach the eager filter after its `FILTER` conjunct moves into the scan
802    /// (Track A), so the column must stay materialized for the post-intern
803    /// placement. **Liveness is the real guarantee, not this call.** The
804    /// comparison pass runs after the last `annotate_liveness`, which has
805    /// already marked every `FILTER`-referenced variable `Live` + `Sensitive`,
806    /// so for a planner-produced comparison this is a no-op. It exists for a
807    /// writer that stamps a comparison on a variable liveness never saw. The
808    /// existing bag mark is left alone so collapse decisions do not change,
809    /// and an unannotated scan already treats every slot as live.
810    pub(crate) fn ensure_materialized(&mut self, variable: &Variable) {
811        if self.marks.is_empty() {
812            return;
813        }
814        if let Some((_, liveness, _)) = self.marks.iter_mut().find(|(name, _, _)| name == variable)
815        {
816            *liveness = Liveness::Live;
817            return;
818        }
819        self.marks
820            .push((variable.clone(), Liveness::Live, BagMark::Sensitive));
821    }
822
823    /// Counted slot whose row multiplicity is required (`COUNT(?v)` or plain
824    /// `COUNT(*)`). The column is omitted from live output; a partition-side
825    /// run-length row count stands in for it.
826    pub fn is_counted(&self, variable: &Variable) -> bool {
827        self.slot_mark(variable)
828            .is_some_and(|m| m.liveness == Liveness::Counted && m.bag == BagMark::Sensitive)
829    }
830
831    /// Counted slot whose distinct term cardinality is all that is required
832    /// (`COUNT(DISTINCT ?v)` over a dead slot, or `COUNT(DISTINCT ?g)` over
833    /// the graph slot). The column is omitted from live output; the
834    /// partition counts distinct terms per run instead.
835    pub fn is_counted_distinct(&self, variable: &Variable) -> bool {
836        self.slot_mark(variable)
837            .is_some_and(|m| m.liveness == Liveness::Counted && m.bag == BagMark::Insensitive)
838    }
839
840    /// Whether this scan's `head_scan_counts` annotation serves the `TOTAL`
841    /// shape (head slot counted-distinct, group result = the whole CF's
842    /// distinct head count) rather than `PER_HEAD` (head is a live group
843    /// key; each hit counts distinct slot-1 terms under it).
844    pub fn head_count_is_total(&self, kind: HeadScanKind) -> bool {
845        let head = match kind.head_slot() {
846            PatternSlot::Subject => self.subject.as_ref(),
847            PatternSlot::Predicate => self.predicate.as_ref(),
848            PatternSlot::Object => self.object.as_ref(),
849        };
850        head.is_some_and(|v| self.is_counted_distinct(v))
851    }
852
853    /// What one run-count increment of this scan's `domain_counts` RPC
854    /// represents, derived from the marks: a counted-distinct graph slot is
855    /// [`DomainCountMode::DistinctGraphs`], a counted-distinct S/P/O slot is
856    /// [`DomainCountMode::DistinctTerms`], everything else is the bag
857    /// [`DomainCountMode::Rows`].
858    pub fn domain_count_mode(&self) -> DomainCountMode {
859        if let Some(g) = &self.graph
860            && self.is_counted_distinct(g)
861        {
862            return DomainCountMode::DistinctGraphs;
863        }
864        if self
865            .slot_variables()
866            .iter()
867            .any(|v| self.is_counted_distinct(v))
868        {
869            return DomainCountMode::DistinctTerms;
870        }
871        DomainCountMode::Rows
872    }
873
874    /// Whether this scan executes through a specialized RPC
875    /// (`domain_scan` / `head_scan` / `domain_counts` / `head_scan_counts`)
876    /// whose pushed filter is the RPC's CONSTRAINT SOURCE, not a
877    /// narrowable broadcast filter: specialized leaves never chunk their lists,
878    /// never take the leaf-local coverage drop, and are memo-ineligible.
879    /// One predicate so the fence means the same thing at every site (an
880    /// earlier drift had the coverage drop missing `head_scan_counts`).
881    pub(crate) fn has_specialized_rpc(&self) -> bool {
882        self.domain_scan.is_some()
883            || self.head_scan.is_some()
884            || self.domain_counts.is_some()
885            || self.head_scan_counts.is_some()
886    }
887
888    /// Live bag-insensitive columns (collapse keys). Empty if this scan must
889    /// not collapse (counted slot in either mode — a count RPC stands in for
890    /// it, or the generic consumer needs the un-collapsed rows — a live
891    /// Sensitive slot, or a domain rewrite).
892    pub fn collapse_keys(&self) -> Vec<Variable> {
893        if self.has_specialized_rpc() {
894            return Vec::new();
895        }
896        for variable in self.slot_variables() {
897            if self.is_counted(&variable) || self.is_counted_distinct(&variable) {
898                return Vec::new();
899            }
900            if self.is_live(&variable) && self.bag_mark(&variable) == Some(BagMark::Sensitive) {
901                return Vec::new();
902            }
903        }
904        self.slot_variables()
905            .into_iter()
906            .filter(|v| self.is_live(v) && self.bag_mark(v) == Some(BagMark::Insensitive))
907            .collect()
908    }
909
910    /// Compute-side `DISTINCT ON` collapse keys (not used by domain / head
911    /// scans).
912    pub fn will_collapse(&self) -> bool {
913        !self.collapse_keys().is_empty()
914    }
915
916    /// Whether `variable` carries a planner-derived IRI-only fact
917    /// (`FILTER(isIRI(?x))` conjunct proved above this scan).
918    pub fn is_iri_only(&self, variable: &Variable) -> bool {
919        self.iri_only.iter().any(|v| v == variable)
920    }
921
922    /// S/O pushdown flags for scan RPCs. G facts never ride the wire
923    /// (compute filters G itself), and P is always an IRI by encoding.
924    pub fn iri_only_slots(&self) -> IriOnlyMask {
925        let mut mask = IriOnlyMask::NONE;
926        for variable in &self.iri_only {
927            for slot in self.slot_of(variable) {
928                match slot {
929                    PatternSlot::Subject => mask.subject = true,
930                    PatternSlot::Object => mask.object = true,
931                    PatternSlot::Predicate => {}
932                }
933            }
934        }
935        mask
936    }
937
938    /// The subset of [`Self::eager`] to place on the scan request's
939    /// `comparisons` field.
940    ///
941    /// `eager` is the plan's one record of the filter conjuncts; the wire
942    /// field is a request-time view of it, not a second plan list. The view
943    /// is empty for a specialized rewrite (domain / head / counts): those scans
944    /// answer from their own RPC and never run the pattern walk the field
945    /// feeds. A graph-slot comparison never reaches `eager` — the planner
946    /// rejects it and the wire is S/P/O only — and the assertion below makes
947    /// a future writer that gets that wrong fail loudly here instead of
948    /// splitting into an encoder rejection and a transport that silently
949    /// ignores the entry. Every other conjunct rides the request; a partition
950    /// that cannot decide one keeps the row, and the compute-side eager filter
951    /// still evaluates it.
952    pub fn pushed_comparisons(&self) -> &[SlotComparison] {
953        debug_assert!(
954            self.eager
955                .iter()
956                .all(|comparison| comparison.slot != QuadSlot::Graph),
957            "the comparison wire is S/P/O only: a graph-slot entry would be \
958             rejected by the encoder and ignored by a transport default"
959        );
960        if self.has_specialized_rpc() {
961            return &[];
962        }
963        &self.eager
964    }
965
966    /// Number of ground slots — fallback selectivity when no profile is loaded.
967    pub fn bound_slots(&self) -> usize {
968        bound_slots(&self.pattern)
969    }
970
971    /// Every pattern slot that binds `variable`, in subject / predicate /
972    /// object order. Empty when the variable is not on this scan.
973    pub fn slot_of(&self, variable: &Variable) -> Vec<PatternSlot> {
974        let mut slots = Vec::new();
975        if self.subject.as_ref() == Some(variable) {
976            slots.push(PatternSlot::Subject);
977        }
978        if self.predicate.as_ref() == Some(variable) {
979            slots.push(PatternSlot::Predicate);
980        }
981        if self.object.as_ref() == Some(variable) {
982            slots.push(PatternSlot::Object);
983        }
984        slots
985    }
986
987    /// First matching slot, if any (runtime allow-list still uses one slot).
988    pub fn first_slot_of(&self, variable: &Variable) -> Option<PatternSlot> {
989        self.slot_of(variable).into_iter().next()
990    }
991
992    /// `Known` join-key domain for `variable` on this scan.
993    ///
994    /// The concurrent-star over-fetch gate uses it as the driver page's
995    /// distinct-key bound. A missing stamp (no profile, deferred, or a
996    /// predicate/graph slot) returns `None`; the gate then prices the page
997    /// as one distinct key per row.
998    pub(crate) fn known_join_domain(&self, variable: &Variable) -> Option<u64> {
999        let slot = if self.subject.as_ref() == Some(variable) {
1000            JoinKeySlot::Subject
1001        } else if self.object.as_ref() == Some(variable) {
1002            JoinKeySlot::Object
1003        } else {
1004            return None;
1005        };
1006        match self.join_domains.get(slot) {
1007            JoinDomainStamp::Known(n) => Some(n),
1008            _ => None,
1009        }
1010    }
1011
1012    /// Test-only: stamp one slot's join domain as
1013    /// [`JoinDomainStamp::Known`]. Production stamps arrive only through
1014    /// `JoinDomainStamps::classify` (a stats profile in hand); the
1015    /// leaf coverage-drop fence tests need a Known stamp without a
1016    /// profile fixture, and the fields are private to this module.
1017    #[cfg(test)]
1018    pub(crate) fn with_known_join_domain(mut self, slot: JoinKeySlot, domain: u64) -> Self {
1019        match slot {
1020            JoinKeySlot::Subject => self.join_domains.subject = JoinDomainStamp::Known(domain),
1021            JoinKeySlot::Object => self.join_domains.object = JoinDomainStamp::Known(domain),
1022        }
1023        self
1024    }
1025
1026    /// Runtime-grounded copy (broadcast grounding): same variable slots, marks, and
1027    /// estimates; only `pattern` gains the pinned term. The variable fields
1028    /// stay untouched so projection and materialization are unchanged. The
1029    /// join-domain stamps describe the old pattern, so they are dropped;
1030    /// execution does not price scans, and any future pricing caller
1031    /// recomputes live instead of reading a stale `Known`.
1032    pub(crate) fn with_pattern(&self, pattern: EncodedTriplePattern) -> ScanOp {
1033        let mut grounded = self.clone();
1034        grounded.pattern = pattern;
1035        grounded.join_domains = JoinDomainStamps::default();
1036        grounded
1037    }
1038
1039    /// Record that `variable` was plan-time grounded in `slot`, then
1040    /// re-classify the cached join-key domains from the now-current pattern.
1041    /// Both grounding passes funnel through here, so a delayed object or
1042    /// predicate binding re-classifies the affected stamp at the one place
1043    /// the pattern changes, promoting it to `Known` when the binding
1044    /// completes the inputs its answer reads and the profile has a sketch.
1045    fn record_grounded(
1046        &mut self,
1047        variable: &Variable,
1048        slot: PatternSlot,
1049        profile: Option<&StatsProfile>,
1050    ) {
1051        let entry = (variable.clone(), slot);
1052        if !self.grounded.contains(&entry) {
1053            self.grounded.push(entry);
1054        }
1055        self.refresh_join_domains(profile);
1056    }
1057
1058    /// Re-classify the cached join-key domains from the current pattern.
1059    /// Called only after a plan-time binding, so a `Deferred` /
1060    /// `UnknownPredicate` stamp can be promoted to `Known` when that binding
1061    /// completes the inputs its answer reads.
1062    fn refresh_join_domains(&mut self, profile: Option<&StatsProfile>) {
1063        self.join_domains = JoinDomainStamps::classify(profile, &self.pattern);
1064    }
1065}
1066
1067/// Compiled SPARQL 1.1 property path over interned [`EncodedTerm`] predicates.
1068#[derive(Debug, Clone, PartialEq)]
1069pub enum PropertyPath {
1070    /// A single predicate (`:p`).
1071    Predicate(EncodedTerm),
1072    /// Inverse path (`^path`).
1073    Reverse(Box<Self>),
1074    /// Sequence (`path1 / path2`), nested inside `*` / `+` / `?` / `|`.
1075    Sequence(Box<Self>, Box<Self>),
1076    /// Alternative (`path1 | path2`) — set semantics.
1077    Alternative(Box<Self>, Box<Self>),
1078    /// Zero or more (`path*`).
1079    ZeroOrMore(Box<Self>),
1080    /// One or more (`path+`).
1081    OneOrMore(Box<Self>),
1082    /// Zero or one (`path?`).
1083    ZeroOrOne(Box<Self>),
1084    /// Negated property set (`!(:p | :q | …)`).
1085    NegatedPropertySet(Vec<EncodedTerm>),
1086}
1087
1088impl PropertyPath {
1089    /// Whether this path contains `*` or `+` (including under `^` / `|` / `/` / `?`).
1090    pub fn contains_star_or_plus(&self) -> bool {
1091        match self {
1092            Self::ZeroOrMore(_) | Self::OneOrMore(_) => true,
1093            Self::Reverse(inner) | Self::ZeroOrOne(inner) => inner.contains_star_or_plus(),
1094            Self::Sequence(a, b) | Self::Alternative(a, b) => {
1095                a.contains_star_or_plus() || b.contains_star_or_plus()
1096            }
1097            Self::Predicate(_) | Self::NegatedPropertySet(_) => false,
1098        }
1099    }
1100}
1101
1102/// One property-path leaf after lowering.
1103///
1104/// Ground ends live in `subject_term` / `object_term` while the variable names
1105/// stay populated so projection still sees those columns (same pattern as
1106/// [`ScanOp`] after identity-FILTER fold).
1107#[derive(Debug, Clone, PartialEq)]
1108pub struct PathOp {
1109    /// Encoded start when the subject slot is ground.
1110    pub subject_term: Option<EncodedTerm>,
1111    /// Variable bound by the subject slot, if any.
1112    pub subject: Option<Variable>,
1113    /// Encoded path tree (predicates interned at plan time).
1114    pub path: PropertyPath,
1115    /// Encoded end when the object slot is ground.
1116    pub object_term: Option<EncodedTerm>,
1117    /// Variable bound by the object slot, if any.
1118    pub object: Option<Variable>,
1119    /// Estimated cardinality from boundness + sparopt-style sizes.
1120    pub produced_row_count_estimate: u64,
1121    /// Hash → raw string for hashed ground ends (`*` identity can emit a start
1122    /// that was never stored, so materialize cannot ask the registry).
1123    pub strings: Vec<(StrHash, String)>,
1124    /// Variable bound by the graph slot (`GRAPH ?g`), if any.
1125    pub graph: Option<Variable>,
1126    /// Bound graph name when G is ground.
1127    pub graph_name: Option<EncodedTerm>,
1128    /// Residual G allow-list or block-list for hops.
1129    pub graph_filter: Option<GraphFilter>,
1130    /// Same merge-default flag as [`ScanOp::merge_default_graph`]: hop scans unique
1131    /// S/P/O and rewrite G to DefaultGraph so `/` and ALP join on nodes across
1132    /// source graphs. Off inside `GRAPH`, where G is part of the vertex.
1133    pub merge_default_graph: bool,
1134}
1135
1136impl PathOp {
1137    /// Variables this path produces, subject then object, deduplicated.
1138    pub fn variables(&self) -> Vec<Variable> {
1139        let mut out = Vec::new();
1140        if let Some(variable) = &self.subject {
1141            out.push(variable.clone());
1142        }
1143        if let Some(variable) = &self.object
1144            && !out.contains(variable)
1145        {
1146            out.push(variable.clone());
1147        }
1148        if let Some(variable) = &self.graph
1149            && !out.contains(variable)
1150        {
1151            out.push(variable.clone());
1152        }
1153        out
1154    }
1155
1156    /// Number of ground ends (0–2), for leaf sort fallback.
1157    pub fn bound_ends(&self) -> usize {
1158        usize::from(self.subject_term.is_some()) + usize::from(self.object_term.is_some())
1159    }
1160
1161    /// Whether `variable` is the start, the end, or both.
1162    pub fn end_of(&self, variable: &Variable) -> Option<PathEnd> {
1163        let start = self.subject.as_ref() == Some(variable);
1164        let end = self.object.as_ref() == Some(variable);
1165        match (start, end) {
1166            (true, true) => Some(PathEnd::Both),
1167            (true, false) => Some(PathEnd::Start),
1168            (false, true) => Some(PathEnd::End),
1169            (false, false) => None,
1170        }
1171    }
1172}
1173
1174/// Which path endpoint a join key or FILTER variable occupies.
1175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1176pub enum PathEnd {
1177    /// Subject / start of the path.
1178    Start,
1179    /// Object / end of the path.
1180    End,
1181    /// Same variable on both ends (`?v :p* ?v`).
1182    Both,
1183}
1184
1185/// The liveness-dependent half of the general semi admission gate.
1186///
1187/// Recorded at the final liveness round's `Join` arm, where the join-boundary
1188/// capture exists, and consumed by [`stamp_semi_join_strategy`] after the
1189/// `SemiScan` promotion and the star stamp have claimed their joins. Only
1190/// passes that remove above-join uses or shrink a subtree's variable set run
1191/// in between, so a recorded fact can become over-strict but cannot become
1192/// permissive:
1193///
1194/// - [`derive_scan_comparisons`] removes `FILTER` conjuncts and may replace
1195///   a `Filter` with its inner; it never adds a use or a produced column.
1196/// - the `Distinct` wrap's columns are the seeded projection, and the `Sort`
1197///   wrap's keys are seeded into the liveness `required` map, so neither
1198///   adds a live name the recording did not see.
1199/// - `stamp_star_join_shapes`, `restamp_fetch_once`, and
1200///   `prefer_broadcast_for_small_slice` change stamps and strategy only.
1201///
1202/// Anything structural or profile-based (key binding, specialized scan,
1203/// driver domain, page count, price) is evaluated at use, not stored here.
1204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1205pub struct SemiGateFacts {
1206    /// A right-produced, non-hash-key column is live above the join, so the
1207    /// semi schema would drop something a consumer reads.
1208    pub right_payload: bool,
1209    /// Duplicate right keys would change an answer above the join.
1210    pub row_multiplicity_observed: bool,
1211    /// A plain `COUNT(*)` sits above the join.
1212    pub count_star: bool,
1213}
1214
1215/// Planner annotations on an inner join (costing / execution hints).
1216///
1217/// Structural join keys live on [`PlanNode::Join`]; this holds strategy and
1218/// two row-estimate frames — `produced` (all pushes active at the node) and
1219/// `own_push_removed` (this join's own probe push removed) — not a peer of
1220/// [`ScanOp`]. See the field docs for the frame table and the one-level
1221/// limitation of the own-push-removed record.
1222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1223pub struct JoinMeta {
1224    /// Broadcast / shuffle / hash hint from cardinality estimates.
1225    pub strategy: JoinStrategy,
1226    /// Rows this join is planned to produce, stamped in two phases:
1227    ///
1228    /// 1. During the `refinalize_joins` rounds, [`finalize_inner_join_meta`]
1229    ///    writes the uniform estimate. A path operand joined on one of its
1230    ///    ends is already priced push-aware here (`path_probe_row_bound`):
1231    ///    a bind-join probe returns the values-broadcast bound, not its
1232    ///    unbound leaf price, and the swap comparator's row tiebreak must
1233    ///    see the executed size or it seats the wrong driver. Structural
1234    ///    decisions consume exactly this number: the swap comparator's row
1235    ///    tiebreak and every ancestor join's own product.
1236    ///
1237    /// 2. After the last [`restamp_broadcast_marks`],
1238    ///    [`restamp_joins_produced_row_count_estimate`] overwrites it
1239    ///    **push-aware**: a join key whose runtime push is stamped on a
1240    ///    probe scan divides by the driver-side domain alone (the push
1241    ///    guarantees the key matches; `max(dom_L, dom_R)` was the pre-push
1242    ///    containment bound), and row counts are the settled post-clamp
1243    ///    values. The final tree's number reflects the pushes actually
1244    ///    planned.
1245    ///
1246    /// **Frame:** every push active at this node — the join's own probe
1247    /// push, pushes owned by joins inside either arm, and pushes arriving
1248    /// from ancestors above this join. This is the row count the executor's
1249    /// stream is expected to carry under the planned pushes, and the number
1250    /// seating, ancestor products, and the fetch-once page basis consume.
1251    /// The counterfactual with this join's own probe push removed is
1252    /// [`Self::own_push_removed_row_count_estimate`]; the two are not
1253    /// interchangeable.
1254    pub produced_row_count_estimate: u64,
1255    /// The uniform estimate with **this join's own probe push** removed:
1256    /// the rows this join would emit if it did not push its driver keys
1257    /// into its right arm, while keeping pushes owned by joins inside
1258    /// either arm and pushes from ancestors above this join. EXPLAIN shows
1259    /// it as `(price ~N)` beside the produced count.
1260    ///
1261    /// **Frame, not a general no-push estimate.** A child's value is not a
1262    /// valid input for a parent's own-push-removed estimate: the child
1263    /// removed *its* push, which is still active when the parent probes it.
1264    /// A parent-frame estimate ("remove P's push, keep N's own") needs
1265    /// clamp provenance this field does not carry. A fully unpushed
1266    /// estimate is a third frame, derived on demand by
1267    /// [`unpushed_row_count_estimate`] / [`unpushed_read_rows`], never
1268    /// stored here.
1269    ///
1270    /// **Current implementation is one level deep.**
1271    /// `finalize_inner_join_meta` re-derives only a direct right-arm path
1272    /// or claimed scan (`path_arm_own_push_removed_price`); a non-path right subtree
1273    /// and the entire left arm pass through their produced cells. A
1274    /// non-path child may already carry a clamp from a deeper join or an
1275    /// ancestor (the `refinalize_joins` rounds re-stamp from the settled
1276    /// cells), so this field can equal the produced count even though the
1277    /// frame says otherwise.
1278    ///
1279    /// **Consumers:** EXPLAIN and
1280    /// [`PlanNode::own_push_removed_row_count_estimate`]. The latter is the
1281    /// coverage-drop / concurrent-star **driver upper bound**: a larger
1282    /// driver estimate makes a covered-push drop less likely, which is the
1283    /// conservative direction. Seating and fetch-once do not read it.
1284    /// Written alongside [`Self::produced_row_count_estimate`] at finalize
1285    /// and never overwritten by the restamp.
1286    pub own_push_removed_row_count_estimate: u64,
1287    /// Star-spine membership: `Some(arm_count)` on the HEAD join of a spine
1288    /// the executor's concurrent-star `detect` admits under eager-path
1289    /// parameters (`slice_path = false`, `eager_star_page_rows()`); `None`
1290    /// on every other join (spine members, chains, non-joins). Sole writer:
1291    /// [`stamp_star_join_shapes`], which runs after the LAST seating round
1292    /// — nothing structural follows it, so the stamp cannot go stale and
1293    /// needs no clear pass (unlike `broadcasted`, which refinalize swaps
1294    /// must clear). Display-and-pricing annotation only: EXPLAIN renders
1295    /// the star shape from it and the fetch-once verdict's batch credit
1296    /// reads its arm count from it; the executor still runs
1297    /// its own `detect` (runtime structures must be assembled there) and
1298    /// debug-asserts agreement on the eager path. The slice path
1299    /// (OpenNode) may legitimately run a star this stamp does not name:
1300    /// its viability gate prices demand-bounded pages, which plan time
1301    /// cannot reproduce.
1302    pub star_arms: Option<u8>,
1303    /// The liveness-dependent semi gate facts, recorded by the final
1304    /// liveness round for a general-`Semi` candidate. `None` means the join
1305    /// was not recorded (not a candidate, or the round did not run);
1306    /// [`stamp_semi_join_strategy`] consumes the record.
1307    pub semi_gate: Option<SemiGateFacts>,
1308}
1309
1310/// Flat join record for BGP pipeline building and plan inspection.
1311///
1312/// Carries structural [`Self::hash_keys`] plus [`JoinMeta`] without owning
1313/// child plan trees (unlike [`PlanNode::Join`]).
1314#[derive(Debug, Clone, PartialEq)]
1315pub struct JoinEdge {
1316    /// Always-bound equality keys. Empty means a cartesian product (soft
1317    /// shared columns may still be reconciled at execution).
1318    pub hash_keys: Vec<Variable>,
1319    /// Strategy and estimated output cardinality.
1320    pub meta: JoinMeta,
1321}
1322
1323/// Planner row-count annotations on an OPTIONAL (`PlanNode::LeftJoin`).
1324///
1325/// Mirrors [`JoinMeta`]'s two-frame split (see those field docs): lowering
1326/// and each `refinalize_joins` round stamp **both frames** —
1327/// [`Self::produced_row_count_estimate`] with every push active at the node
1328/// (what ancestor costing reads via
1329/// `PlanNode::produced_row_count_estimate`) and
1330/// [`Self::own_push_removed_row_count_estimate`] with the right-arm probe
1331/// push removed — and [`restamp_joins_produced_row_count_estimate`]
1332/// overwrites the produced count after the last restamp (the matched term
1333/// becomes the probe's settled post-push return count). No strategy field:
1334/// the executor treats every LeftJoin probe the same, and runtime key
1335/// delivery is dynamic.
1336#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1337pub struct LeftJoinMeta {
1338    /// Rows this OPTIONAL is planned to produce (matched rows plus the
1339    /// unmatched required-side pass-through), two-phase as above.
1340    ///
1341    /// **Frame:** every push active at this node — the OPTIONAL's own probe
1342    /// push, pushes owned by joins inside either arm, and pushes from
1343    /// ancestors above it.
1344    pub produced_row_count_estimate: u64,
1345    /// The right-arm probe push removed, keeping internal and ancestor
1346    /// pushes. EXPLAIN shows it as `(price ~N)` beside the produced count.
1347    /// A right-arm path or claimed scan is re-derived at its bare pattern
1348    /// price (`path_arm_own_push_removed_price`), so the record does not depend on
1349    /// the clamp timing of the node's own stamp. Like the inner-join field,
1350    /// this is one level deep and is not a general no-push estimate; it is
1351    /// EXPLAIN-only today (`PlanNode::own_push_removed_row_count_estimate`
1352    /// returns `None` for a `LeftJoin`).
1353    pub own_push_removed_row_count_estimate: u64,
1354}
1355
1356/// Output variable boundness for a plan subtree.
1357#[derive(Debug, Clone, PartialEq, Eq, Default)]
1358pub struct OutputVars {
1359    /// Variables guaranteed bound in every solution row.
1360    pub always_bound: Vec<Variable>,
1361    /// Variables that may be unbound (e.g. introduced by `OPTIONAL`).
1362    pub maybe_unbound: Vec<Variable>,
1363}
1364
1365impl OutputVars {
1366    /// Always-bound then maybe-unbound, deduplicated.
1367    pub fn all(&self) -> Vec<Variable> {
1368        let mut out = self.always_bound.clone();
1369        for v in &self.maybe_unbound {
1370            if !out.contains(v) {
1371                out.push(v.clone());
1372            }
1373        }
1374        out
1375    }
1376
1377    fn contains(&self, variable: &Variable) -> bool {
1378        self.always_bound.contains(variable) || self.maybe_unbound.contains(variable)
1379    }
1380
1381    fn is_always_bound(&self, variable: &Variable) -> bool {
1382        self.always_bound.contains(variable)
1383    }
1384}
1385
1386/// SPARQL Join of inner with `{ graph_var → active_var }`: `graph_var` is
1387/// always-bound afterwards; `active_var` is dropped.
1388fn join_graph_var_output_vars(
1389    inner: &OutputVars,
1390    graph_var: &Variable,
1391    active_var: &Variable,
1392) -> OutputVars {
1393    let mut always_bound: Vec<Variable> = inner
1394        .always_bound
1395        .iter()
1396        .filter(|v| *v != active_var)
1397        .cloned()
1398        .collect();
1399    let maybe_unbound: Vec<Variable> = inner
1400        .maybe_unbound
1401        .iter()
1402        .filter(|v| *v != active_var && *v != graph_var)
1403        .cloned()
1404        .collect();
1405    if !always_bound.contains(graph_var) {
1406        always_bound.push(graph_var.clone());
1407    }
1408    OutputVars {
1409        always_bound,
1410        maybe_unbound,
1411    }
1412}
1413
1414fn hash_keys_for(left: &OutputVars, right: &OutputVars) -> Vec<Variable> {
1415    left.always_bound
1416        .iter()
1417        .filter(|v| right.is_always_bound(v))
1418        .cloned()
1419        .collect()
1420}
1421
1422/// BIND / Extend produces a guaranteed term only for ground constants and
1423/// always-bound variables (plan: otherwise maybe-unbound).
1424fn extend_var_always_bound(inner: &OutputVars, expression: &Expression) -> bool {
1425    match expression {
1426        Expression::NamedNode(_) | Expression::Literal(_) => true,
1427        Expression::Variable(variable) => inner.is_always_bound(variable),
1428        Expression::Bound(_) => true,
1429        _ => false,
1430    }
1431}
1432
1433fn group_output_vars(
1434    inner: &OutputVars,
1435    keys: &[Variable],
1436    aggregates: &[(Variable, AggregateExpression)],
1437) -> OutputVars {
1438    let mut always_bound = Vec::new();
1439    let mut maybe_unbound = Vec::new();
1440    for key in keys {
1441        if inner.is_always_bound(key) {
1442            if !always_bound.contains(key) {
1443                always_bound.push(key.clone());
1444            }
1445        } else if !maybe_unbound.contains(key) {
1446            maybe_unbound.push(key.clone());
1447        }
1448    }
1449    for (variable, agg) in aggregates {
1450        if aggregate_result_always_bound(agg) {
1451            if !always_bound.contains(variable) {
1452                always_bound.push(variable.clone());
1453            }
1454            maybe_unbound.retain(|v| v != variable);
1455        } else if !always_bound.contains(variable) && !maybe_unbound.contains(variable) {
1456            maybe_unbound.push(variable.clone());
1457        }
1458    }
1459    OutputVars {
1460        always_bound,
1461        maybe_unbound,
1462    }
1463}
1464
1465fn aggregate_result_always_bound(agg: &AggregateExpression) -> bool {
1466    matches!(
1467        agg,
1468        AggregateExpression::CountSolutions { .. }
1469            | AggregateExpression::FunctionCall {
1470                name: AggregateFunction::Count,
1471                ..
1472            }
1473    )
1474}
1475
1476fn reject_unsupported_aggregates(
1477    aggregates: &[(Variable, AggregateExpression)],
1478) -> Result<(), ComputeError> {
1479    for (_, agg) in aggregates {
1480        match agg {
1481            AggregateExpression::CountSolutions { .. } => {}
1482            AggregateExpression::FunctionCall {
1483                name: AggregateFunction::Custom(name),
1484                ..
1485            } => {
1486                return Err(ComputeError::UnsupportedSparql(format!(
1487                    "custom aggregate {name} is not supported"
1488                )));
1489            }
1490            AggregateExpression::FunctionCall { expr, .. } => match crate::expr::classify(expr) {
1491                crate::expr::ExprCapability::Unsupported => {
1492                    return Err(ComputeError::UnsupportedSparql(format!(
1493                        "aggregate argument is not supported: {expr}"
1494                    )));
1495                }
1496                crate::expr::ExprCapability::AlwaysResolve
1497                | crate::expr::ExprCapability::AlwaysEncoded
1498                | crate::expr::ExprCapability::MaybeEncoded => {
1499                    let _ = crate::expr::split_filter(expr)?;
1500                }
1501            },
1502        }
1503    }
1504    Ok(())
1505}
1506
1507/// Group-elimination rewrite for whole-CF head counts: when a `Group`'s inner
1508/// scan is a bare (anchor-free) scan whose single distinct-count aggregate
1509/// counts the column family's slot-0 head (TOTAL) or slot-1 term grouped by
1510/// the head (PER_HEAD), replace the whole `Group` with
1511/// [`PlanNode::HeadCounts`] — one [`AxisHeadScanCounts`][crate::clients::HexastoreScan]
1512/// call answers the group. Runs once after [`fold_identity_filters`], and
1513/// BEFORE [`eliminate_domain_counts_groups`]: the flagship type shape
1514/// (`?f a ?cls GROUP BY ?cls COUNT(DISTINCT ?f)`) matches both rewrites and
1515/// the head pass wins — TSG is the smaller, type-dense CF holding the same
1516/// logical content as POSG under `rdf:type`. Shapes the head pass cannot
1517/// take (extra aggregates, anchored/broadcast scans, VALUES facets) fall
1518/// through to the domain pass or to the ScanOp-residual liveness paths.
1519pub(crate) fn eliminate_head_counts_groups(node: &mut PlanNode, profile: Option<&StatsProfile>) {
1520    match node {
1521        PlanNode::CustomNode(op) => {
1522            for child in &mut op.children {
1523                eliminate_head_counts_groups(child, profile);
1524            }
1525        }
1526        PlanNode::Group {
1527            inner,
1528            variables,
1529            aggregates,
1530            ..
1531        } => {
1532            // Lower inner first. So this becomes bottom-up.
1533            eliminate_head_counts_groups(inner, profile);
1534            if let Some(replacement) =
1535                try_head_counts_plan_node(inner, variables, aggregates, profile)
1536            {
1537                *node = replacement;
1538            }
1539        }
1540        PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
1541            eliminate_head_counts_groups(left, profile);
1542            eliminate_head_counts_groups(right, profile);
1543        }
1544        PlanNode::Union { left, right } => {
1545            eliminate_head_counts_groups(left, profile);
1546            eliminate_head_counts_groups(right, profile);
1547        }
1548        PlanNode::Filter { inner, exists, .. } => {
1549            eliminate_head_counts_groups(inner, profile);
1550            for clause in exists {
1551                eliminate_head_counts_groups(&mut clause.body, profile);
1552            }
1553        }
1554        PlanNode::Extend { inner, .. }
1555        | PlanNode::Slice { inner, .. }
1556        | PlanNode::Distinct { inner, .. }
1557        | PlanNode::Sort { inner, .. }
1558        | PlanNode::JoinGraphVar { inner, .. } => eliminate_head_counts_groups(inner, profile),
1559        PlanNode::SubSelect(sub) => eliminate_head_counts_groups(&mut sub.inner, profile),
1560        PlanNode::Scan(_)
1561        | PlanNode::Path(_)
1562        | PlanNode::Values(_)
1563        | PlanNode::NamedGraphs { .. }
1564        | PlanNode::NamedGraphExists { .. }
1565        // A head-count leaf can only exist if this pass created it (it runs
1566        // first); domain/pattern-count leaves are created by LATER passes and
1567        // cannot appear here — but the match must still be exhaustive.
1568        | PlanNode::DomainCounts { .. }
1569        | PlanNode::HeadCounts { .. }
1570        | PlanNode::PatternCount { .. }
1571        | PlanNode::Unit => {}
1572    }
1573}
1574
1575fn try_head_counts_plan_node(
1576    lowered: &PlanNode,
1577    keys: &[Variable],
1578    aggregates: &[(Variable, AggregateExpression)],
1579    profile: Option<&StatsProfile>,
1580) -> Option<PlanNode> {
1581    if aggregates.len() != 1 {
1582        return None;
1583    }
1584    let (count_var, counted_var) = match &aggregates[0] {
1585        (
1586            var,
1587            AggregateExpression::FunctionCall {
1588                name: AggregateFunction::Count,
1589                distinct: true,
1590                expr: Expression::Variable(v),
1591            },
1592        ) => (var.clone(), v.clone()),
1593        // Plain counts, `COUNT(*)` / `COUNT(DISTINCT *)` and value
1594        // aggregates need either the bag or whole mappings — never the
1595        // head-count RPC.
1596        _ => return None,
1597    };
1598    let PlanNode::Scan(scan) = lowered else {
1599        // `VALUES ⋈ Scan` is refused: a head count has no constraint slot
1600        // for the VALUES to anchor, so a joined VALUES could only filter —
1601        // which the generic path must then evaluate.
1602        return None;
1603    };
1604    if scan.broadcasted.is_some()
1605        // An unbound `?g` keeps G identity (`GRAPH ?g { … }`): the head-count
1606        // RPC is existence-only on G.
1607        || scan.graph.is_some()
1608        || crate::liveness::repeated_var_needs_dropped_slot(scan)
1609    {
1610        return None;
1611    }
1612    // Kind candidates consistent with the pattern: the type shape anchors
1613    // the TSG family (subject term unbound — the head-count RPC has no
1614    // subject constraint), everything else requires a fully bare pattern.
1615    let mut candidates = Vec::new();
1616    if scan.pattern.predicate.as_ref() == Some(&RDF_TYPE) {
1617        if scan.pattern.subject.is_none() {
1618            candidates.push((
1619                HeadScanKind::Classes,
1620                PatternSlot::Object,
1621                PatternSlot::Subject,
1622            ));
1623        }
1624    } else if scan.pattern.subject.is_none()
1625        && scan.pattern.predicate.is_none()
1626        && scan.pattern.object.is_none()
1627    {
1628        candidates.push((
1629            HeadScanKind::Subjects,
1630            PatternSlot::Subject,
1631            PatternSlot::Predicate,
1632        ));
1633        candidates.push((
1634            HeadScanKind::Predicates,
1635            PatternSlot::Predicate,
1636            PatternSlot::Subject,
1637        ));
1638        candidates.push((
1639            HeadScanKind::Objects,
1640            PatternSlot::Object,
1641            PatternSlot::Predicate,
1642        ));
1643    }
1644    for (kind, head_slot, counted_slot) in candidates {
1645        let Some(head_var) = scan_slot_variable(scan, head_slot) else {
1646            continue;
1647        };
1648        let Some(slot1_var) = scan_slot_variable(scan, counted_slot) else {
1649            continue;
1650        };
1651        // TOTAL: ungrouped `COUNT(DISTINCT ?slot0)` — the whole CF's
1652        // distinct head count as one row.
1653        let total = keys.is_empty() && counted_var == *head_var;
1654        // PER_HEAD: `GROUP BY ?slot0 COUNT(DISTINCT ?slot1)`.
1655        let per_head = keys.len() == 1 && &keys[0] == head_var && counted_var == *slot1_var;
1656        if !(total || per_head) {
1657            continue;
1658        }
1659        let produced_row_count_estimate = if total {
1660            1
1661        } else {
1662            profile
1663                .and_then(|profile| head_domain_estimate(profile, scan, head_slot))
1664                .unwrap_or(scan.produced_row_count_estimate)
1665        };
1666        return Some(PlanNode::HeadCounts {
1667            kind,
1668            total,
1669            counted: counted_var.clone(),
1670            group: per_head.then(|| head_var.clone()),
1671            count: count_var,
1672            graph_name: scan.pattern.graph_name.clone(),
1673            graph_filter: scan.graph_filter.clone(),
1674            iri_only: scan.is_iri_only(head_var),
1675            produced_row_count_estimate,
1676        });
1677    }
1678    None
1679}
1680
1681/// Group-node entry of the group-elimination pass, named for the
1682/// sum-of-products rewrite. Tries the existing single-scan DomainCounts
1683/// replacement first, then the count-split — the priority of the old
1684/// inline Group arm. Returns immediately on a match, so the replacement
1685/// subtree is not re-visited.
1686fn eliminate_count_split_groups(node: &mut PlanNode, profile: Option<&StatsProfile>) {
1687    let PlanNode::Group {
1688        inner,
1689        variables,
1690        aggregates,
1691        ..
1692    } = node
1693    else {
1694        return;
1695    };
1696    // Lower inner first. So this becomes bottom-up.
1697    eliminate_domain_counts_groups(inner, profile);
1698    if let Some(replacement) = try_domain_counts_plan_node(inner, variables, aggregates, profile) {
1699        // This is the "Eliminate Group" optimization
1700        // Replace the Group with the new DomainCounts node
1701        *node = replacement;
1702    } else if let Some(replacement) =
1703        try_count_split_plan_node(inner, variables, aggregates, profile)
1704    {
1705        // Count-split: a bare count over a join becomes per-arm count
1706        // relations combined by sum-of-products.
1707        *node = replacement;
1708    }
1709}
1710
1711/// Group-elimination rewrite: when a `Group`'s inner scan shape matches, replace
1712/// the whole `Group` with [`PlanNode::DomainCounts`] (RPC row is already the
1713/// group result). Runs once after [`fold_identity_filters`], before liveness.
1714pub(crate) fn eliminate_domain_counts_groups(node: &mut PlanNode, profile: Option<&StatsProfile>) {
1715    match node {
1716        PlanNode::CustomNode(op) => {
1717            for child in &mut op.children {
1718                eliminate_domain_counts_groups(child, profile);
1719            }
1720        }
1721        PlanNode::Group { .. } => eliminate_count_split_groups(node, profile),
1722        PlanNode::Join { left, right, .. } => {
1723            eliminate_domain_counts_groups(left, profile);
1724            eliminate_domain_counts_groups(right, profile);
1725        }
1726        PlanNode::LeftJoin { left, right, .. } => {
1727            eliminate_domain_counts_groups(left, profile);
1728            eliminate_domain_counts_groups(right, profile);
1729        }
1730        PlanNode::Union { left, right } => {
1731            eliminate_domain_counts_groups(left, profile);
1732            eliminate_domain_counts_groups(right, profile);
1733        }
1734        PlanNode::Filter { inner, exists, .. } => {
1735            eliminate_domain_counts_groups(inner, profile);
1736            for clause in exists {
1737                eliminate_domain_counts_groups(&mut clause.body, profile);
1738            }
1739        }
1740        PlanNode::Extend { inner, .. }
1741        | PlanNode::Slice { inner, .. }
1742        | PlanNode::Distinct { inner, .. }
1743        | PlanNode::Sort { inner, .. }
1744        | PlanNode::JoinGraphVar { inner, .. } => eliminate_domain_counts_groups(inner, profile),
1745        PlanNode::SubSelect(sub) => eliminate_domain_counts_groups(&mut sub.inner, profile),
1746        PlanNode::Scan(_)
1747        | PlanNode::Path(_)
1748        | PlanNode::Values(_)
1749        | PlanNode::NamedGraphs { .. }
1750        | PlanNode::NamedGraphExists { .. }
1751        | PlanNode::DomainCounts { .. }
1752        | PlanNode::HeadCounts { .. }
1753        | PlanNode::PatternCount { .. }
1754        | PlanNode::Unit => {}
1755    }
1756}
1757
1758/// Group-elimination rewrite for ungrouped bag `COUNT(*)` / `COUNT(?v)` over
1759/// a single BGP: replace the Group with [`PlanNode::PatternCount`] so one
1760/// `CountPattern` RPC answers. Runs after [`eliminate_head_counts_groups`]
1761/// and [`eliminate_domain_counts_groups`] so distinct TOTAL and facet
1762/// `GROUP BY` counts keep those leaves. Zero group keys only — any
1763/// `GROUP BY` stays on DomainCounts / residual Group.
1764pub(crate) fn eliminate_pattern_count_groups(node: &mut PlanNode) {
1765    match node {
1766        PlanNode::CustomNode(op) => {
1767            for child in &mut op.children {
1768                eliminate_pattern_count_groups(child);
1769            }
1770        }
1771        PlanNode::Group {
1772            inner,
1773            variables,
1774            aggregates,
1775            ..
1776        } => {
1777            eliminate_pattern_count_groups(inner);
1778            if let Some(replacement) = try_pattern_count_plan_node(inner, variables, aggregates) {
1779                *node = replacement;
1780            }
1781        }
1782        PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
1783            eliminate_pattern_count_groups(left);
1784            eliminate_pattern_count_groups(right);
1785        }
1786        PlanNode::Union { left, right } => {
1787            eliminate_pattern_count_groups(left);
1788            eliminate_pattern_count_groups(right);
1789        }
1790        PlanNode::Filter { inner, exists, .. } => {
1791            eliminate_pattern_count_groups(inner);
1792            for clause in exists {
1793                eliminate_pattern_count_groups(&mut clause.body);
1794            }
1795        }
1796        PlanNode::Extend { inner, .. }
1797        | PlanNode::Slice { inner, .. }
1798        | PlanNode::Distinct { inner, .. }
1799        | PlanNode::Sort { inner, .. }
1800        | PlanNode::JoinGraphVar { inner, .. } => eliminate_pattern_count_groups(inner),
1801        PlanNode::SubSelect(sub) => eliminate_pattern_count_groups(&mut sub.inner),
1802        PlanNode::Scan(_)
1803        | PlanNode::Path(_)
1804        | PlanNode::Values(_)
1805        | PlanNode::NamedGraphs { .. }
1806        | PlanNode::NamedGraphExists { .. }
1807        | PlanNode::DomainCounts { .. }
1808        | PlanNode::HeadCounts { .. }
1809        | PlanNode::PatternCount { .. }
1810        | PlanNode::Unit => {}
1811    }
1812}
1813
1814fn try_pattern_count_plan_node(
1815    lowered: &PlanNode,
1816    keys: &[Variable],
1817    aggregates: &[(Variable, AggregateExpression)],
1818) -> Option<PlanNode> {
1819    if !keys.is_empty() || aggregates.len() != 1 {
1820        return None;
1821    }
1822    let PlanNode::Scan(scan) = lowered else {
1823        // Joins / VALUES⋈scan stay on DomainCounts or the generic Group.
1824        return None;
1825    };
1826    if scan.broadcasted.is_some()
1827        // Unbound `GRAPH ?g` keeps G identity; CountPattern is existence /
1828        // window only — refuse rather than drop graph identity.
1829        || scan.graph.is_some()
1830        || crate::liveness::repeated_var_needs_dropped_slot(scan)
1831    {
1832        return None;
1833    }
1834    let (count_var, counted, count_star) = match &aggregates[0] {
1835        (var, AggregateExpression::CountSolutions { distinct: false }) => (var.clone(), None, true),
1836        (
1837            var,
1838            AggregateExpression::FunctionCall {
1839                name: AggregateFunction::Count,
1840                distinct: false,
1841                expr: Expression::Variable(v),
1842            },
1843        ) => {
1844            if !scan.slot_variables().iter().any(|s| s == v) {
1845                return None;
1846            }
1847            (var.clone(), Some(v.clone()), false)
1848        }
1849        // `COUNT(DISTINCT *)` / `COUNT(DISTINCT ?v)` / other aggs: HeadCounts
1850        // or the generic Group.
1851        _ => return None,
1852    };
1853    Some(PlanNode::PatternCount {
1854        pattern: scan.pattern.clone(),
1855        subject: scan.subject.clone(),
1856        predicate: scan.predicate.clone(),
1857        object: scan.object.clone(),
1858        count: count_var,
1859        count_star,
1860        counted,
1861        graph_filter: scan.graph_filter.clone(),
1862        merge_default_graph: scan.merge_default_graph,
1863        produced_row_count_estimate: 1,
1864    })
1865}
1866
1867fn scan_from_group_body(node: &PlanNode) -> Option<&ScanOp> {
1868    match node {
1869        PlanNode::Scan(scan) => Some(scan),
1870        PlanNode::Join { left, right, .. } => match (left.as_ref(), right.as_ref()) {
1871            (PlanNode::Values(_), PlanNode::Scan(scan))
1872            | (PlanNode::Scan(scan), PlanNode::Values(_)) => Some(scan),
1873            _ => None,
1874        },
1875        _ => None,
1876    }
1877}
1878
1879/// The VALUES side of a `VALUES ⋈ Scan` group body, when that is the shape.
1880fn values_from_group_body(node: &PlanNode) -> Option<&ValuesOp> {
1881    match node {
1882        PlanNode::Join { left, right, .. } => match (left.as_ref(), right.as_ref()) {
1883            (PlanNode::Values(values), PlanNode::Scan(_))
1884            | (PlanNode::Scan(_), PlanNode::Values(values)) => Some(values),
1885            _ => None,
1886        },
1887        _ => None,
1888    }
1889}
1890
1891fn scan_op_pattern_term(scan: &ScanOp, slot: PatternSlot) -> Option<&EncodedTerm> {
1892    match slot {
1893        PatternSlot::Subject => scan.pattern.subject.as_ref(),
1894        PatternSlot::Predicate => scan.pattern.predicate.as_ref(),
1895        PatternSlot::Object => scan.pattern.object.as_ref(),
1896    }
1897}
1898
1899fn grounded_only_on_constraint(scan: &ScanOp, slot: PatternSlot) -> bool {
1900    scan.grounded.iter().all(|(variable, grounded_slot)| {
1901        *grounded_slot == slot
1902            && scan_slot_variable(scan, *grounded_slot) == Some(variable)
1903            && scan_op_pattern_term(scan, *grounded_slot).is_some()
1904    })
1905}
1906
1907fn constraint_terms_for_count_shortcut(
1908    inner: &PlanNode,
1909    scan: &ScanOp,
1910    kind: DomainScanKind,
1911) -> Option<(Vec<EncodedTerm>, Option<Variable>)> {
1912    let slot = kind.constraint_slot();
1913    if let Some(term) = scan_op_pattern_term(scan, slot) {
1914        let variable = scan_slot_variable(scan, slot);
1915        if let Some(v) = variable {
1916            if grounded_only_on_constraint(scan, slot) {
1917                return Some((vec![term.clone()], Some(v.clone())));
1918            }
1919            return None;
1920        }
1921        return Some((vec![term.clone()], None));
1922    }
1923    let variable = scan_slot_variable(scan, slot)?;
1924    let terms = allow_list_from_node(inner, variable)?;
1925    if terms.is_empty() {
1926        return None;
1927    }
1928    Some((terms.to_vec(), Some(variable.clone())))
1929}
1930
1931fn try_domain_counts_plan_node(
1932    lowered: &PlanNode,
1933    keys: &[Variable],
1934    aggregates: &[(Variable, AggregateExpression)],
1935    profile: Option<&StatsProfile>,
1936) -> Option<PlanNode> {
1937    if aggregates.len() != 1 {
1938        return None;
1939    }
1940    let scan = scan_from_group_body(lowered)?;
1941    // Unbound `?g` is not a merge: GRAPH keeps G identity. Default-union and
1942    // multi-FROM set `merge_default_graph` and stay eligible; the count RPC
1943    // uniques S/P/O when that flag is forwarded.
1944    if scan.graph.is_some() {
1945        return None;
1946    }
1947    let (count_var, counted, count_distinct) = match &aggregates[0] {
1948        (var, AggregateExpression::CountSolutions { distinct: false }) => {
1949            (var.clone(), None, false)
1950        }
1951        (
1952            var,
1953            AggregateExpression::FunctionCall {
1954                name: AggregateFunction::Count,
1955                distinct,
1956                expr: Expression::Variable(v),
1957            },
1958        ) => (var.clone(), Some(v.clone()), *distinct),
1959        // `COUNT(DISTINCT *)` needs the whole mapping; a counted slot has no
1960        // values to dedup, so the shortcut never serves it.
1961        _ => return None,
1962    };
1963    if keys.len() == 1 && scan.broadcasted.is_some() {
1964        return None;
1965    }
1966    match keys.len() {
1967        1 => try_domain_counts_one_key(
1968            lowered,
1969            scan,
1970            keys,
1971            &count_var,
1972            counted.as_ref(),
1973            count_distinct,
1974            profile,
1975        ),
1976        2 => try_domain_counts_two_keys(
1977            lowered,
1978            scan,
1979            keys,
1980            &count_var,
1981            counted.as_ref(),
1982            count_distinct,
1983            profile,
1984        ),
1985        _ => None,
1986    }
1987}
1988
1989fn try_domain_counts_one_key(
1990    inner: &PlanNode,
1991    scan: &ScanOp,
1992    keys: &[Variable],
1993    count_var: &Variable,
1994    counted: Option<&Variable>,
1995    count_distinct: bool,
1996    profile: Option<&StatsProfile>,
1997) -> Option<PlanNode> {
1998    if counted == Some(&keys[0]) {
1999        return None;
2000    }
2001    let slot_var = |slot: PatternSlot| scan_slot_variable(scan, slot);
2002    for kind in DOMAIN_SCAN_KINDS {
2003        let Some(head) = slot_var(kind.head_slot()) else {
2004            continue;
2005        };
2006        if head != &keys[0] {
2007            continue;
2008        }
2009        if scan
2010            .grounded
2011            .iter()
2012            .any(|(_, slot)| *slot != kind.constraint_slot())
2013        {
2014            continue;
2015        }
2016        let dead = slot_var(kind.dead_slot());
2017        if scan_op_pattern_term(scan, kind.head_slot()).is_some()
2018            || scan_op_pattern_term(scan, kind.dead_slot()).is_some()
2019        {
2020            continue;
2021        }
2022        let Some((constraints, constraint_var)) =
2023            constraint_terms_for_count_shortcut(inner, scan, kind)
2024        else {
2025            continue;
2026        };
2027        if constraint_var.is_some() || constraints.len() != 1 {
2028            continue;
2029        }
2030        let counted_ok = match counted {
2031            Some(v) => dead == Some(v),
2032            None => true,
2033        };
2034        if !counted_ok {
2035            continue;
2036        }
2037        if let Some(v) = counted
2038            && scan.slot_variables().iter().filter(|s| *s == v).count() != 1
2039        {
2040            continue;
2041        }
2042        if crate::liveness::repeated_var_needs_dropped_slot(scan) {
2043            continue;
2044        }
2045        let produced_row_count_estimate = profile
2046            .and_then(|profile| head_domain_estimate(profile, scan, kind.head_slot()))
2047            .unwrap_or(scan.produced_row_count_estimate);
2048        return Some(PlanNode::DomainCounts {
2049            kind,
2050            constraints,
2051            // One pattern constant: the join multiplicity is 1.
2052            constraint_multiplicity: vec![1],
2053            constraint_var: None,
2054            head: keys[0].clone(),
2055            count: count_var.clone(),
2056            dead: dead.cloned(),
2057            count_star: counted.is_none(),
2058            count_distinct,
2059            graph_name: scan.pattern.graph_name.clone(),
2060            graph_filter: scan.graph_filter.clone(),
2061            merge_default_graph: scan.merge_default_graph,
2062            iri_only: scan.is_iri_only(head),
2063            produced_row_count_estimate,
2064        });
2065    }
2066    None
2067}
2068
2069fn try_domain_counts_two_keys(
2070    inner: &PlanNode,
2071    scan: &ScanOp,
2072    keys: &[Variable],
2073    count_var: &Variable,
2074    counted: Option<&Variable>,
2075    count_distinct: bool,
2076    profile: Option<&StatsProfile>,
2077) -> Option<PlanNode> {
2078    let slot_var = |slot: PatternSlot| scan_slot_variable(scan, slot);
2079    for kind in DOMAIN_SCAN_KINDS {
2080        let Some(head) = slot_var(kind.head_slot()) else {
2081            continue;
2082        };
2083        let constraint_v = scan_slot_variable(scan, kind.constraint_slot());
2084        let dead = slot_var(kind.dead_slot());
2085        let Some(constraint_v) = constraint_v else {
2086            continue;
2087        };
2088        if !keys.contains(head) || !keys.contains(constraint_v) {
2089            continue;
2090        }
2091        if scan_op_pattern_term(scan, kind.head_slot()).is_some()
2092            || scan_op_pattern_term(scan, kind.dead_slot()).is_some()
2093        {
2094            continue;
2095        }
2096        let Some((constraints, constraint_var)) =
2097            constraint_terms_for_count_shortcut(inner, scan, kind)
2098        else {
2099            continue;
2100        };
2101        if constraint_var.as_ref() != Some(constraint_v) {
2102            continue;
2103        }
2104        if constraints.is_empty() || constraints.len() > GRAPH_FILTER_TERM_CAP as usize {
2105            continue;
2106        }
2107        // VALUES is a multiset. The RPC list stays distinct (`prepare_constraints`
2108        // would unique it anyway); each term's row count scales the run length
2109        // after the scan. UNDEF, or another VALUES column that is also a scan
2110        // slot, does not factor that way — leave the Group in place.
2111        let Some(constraint_multiplicity) =
2112            constraint_multiplicity_for_two_keys(inner, scan, constraint_v, &constraints)
2113        else {
2114            continue;
2115        };
2116        let counted_ok = match counted {
2117            Some(v) => dead == Some(v),
2118            None => true,
2119        };
2120        if !counted_ok {
2121            continue;
2122        }
2123        if let Some(v) = counted
2124            && scan.slot_variables().iter().filter(|s| *s == v).count() != 1
2125        {
2126            continue;
2127        }
2128        if crate::liveness::repeated_var_needs_dropped_slot(scan) {
2129            continue;
2130        }
2131        let produced_row_count_estimate = profile
2132            .and_then(|profile| head_domain_estimate(profile, scan, kind.head_slot()))
2133            .unwrap_or(scan.produced_row_count_estimate);
2134        // Key-order the (constraint, multiplicity) pairs — the order every
2135        // domain walker visits constraints in (`prepare_constraints_sorted`)
2136        // — moving the two arrays in lockstep: the materializer matches each
2137        // hit's run length to its VALUES factor by position in
2138        // `constraints` (`constraint_multiplicity_of`), so the pairing must
2139        // survive the sort.
2140        let mut keyed: Vec<(EncodedTerm, u64)> = constraints
2141            .into_iter()
2142            .zip(constraint_multiplicity)
2143            .collect();
2144        keyed.sort_by_key(|(term, _)| encode_term_bytes(term));
2145        let (constraints, constraint_multiplicity): (Vec<EncodedTerm>, Vec<u64>) =
2146            keyed.into_iter().unzip();
2147        return Some(PlanNode::DomainCounts {
2148            kind,
2149            constraints,
2150            constraint_multiplicity,
2151            constraint_var: Some(constraint_v.clone()),
2152            head: head.clone(),
2153            count: count_var.clone(),
2154            dead: dead.cloned(),
2155            count_star: counted.is_none(),
2156            count_distinct,
2157            graph_name: scan.pattern.graph_name.clone(),
2158            graph_filter: scan.graph_filter.clone(),
2159            merge_default_graph: scan.merge_default_graph,
2160            iri_only: scan.is_iri_only(head),
2161            produced_row_count_estimate,
2162        });
2163    }
2164    None
2165}
2166
2167/// Minimum estimated join-product rows per stored-relation head value for
2168/// the count-split to fire. The split replaces each join arm with a per-key
2169/// count relation and pays one storage run-length read per distinct head
2170/// value, so it wins only when the join would have produced far more rows
2171/// than the head domain holds values. Below this ratio the row-shipping
2172/// plan (possibly with broadcast seeks) is at least as good, and the
2173/// estimate gate refuses. The benchmark shape this serves runs at roughly
2174/// twelve million product rows per head value, far above the threshold;
2175/// highly selective filter shapes sit near or below it.
2176const COUNT_SPLIT_MIN_PRODUCT_PER_HEAD: u64 = 256;
2177
2178/// Count-split arm roles, assigned per arm by shape — never by position.
2179#[derive(Clone, Copy)]
2180enum CountSplitRole {
2181    /// A single scan the DomainCounts RPC reads as a stored count relation.
2182    Storage(DomainScanKind),
2183    /// A subtree collapsed to a per-key pair count by an ordinary Group.
2184    Collapse,
2185}
2186
2187/// Group-elimination rewrite: a bare non-distinct count over a join of two
2188/// count-relation-reducible arms becomes two per-key count relations joined
2189/// on the shared key, multiplied per key, and summed — the equijoin
2190/// cardinality identity `Σ_k a(k)·b(k)` evaluated exactly. The per-arm
2191/// counts carry every multiplicity factor from their own subtrees, so the
2192/// product is the join's row count, not an estimate.
2193///
2194/// Refused shapes (each for a structural or economic reason):
2195/// - any `GROUP BY` (needs a per-group multiplicative sum, deferred);
2196/// - `COUNT(DISTINCT …)` or any other aggregate (products count pairs, not
2197///   distinct values, and the other aggregates have no exact decomposition
2198///   here);
2199/// - a body that is not exactly one single-key join (an intervening filter
2200///   changes the count, and a multi-key join has no single relation key);
2201/// - an arm deeper than one join level (the collapse does not recurse);
2202/// - neither arm storage-countable (no exact rewrite exists short of
2203///   reading the arms anyway);
2204/// - no profile, or a product estimate not far above the head-domain read
2205///   cost.
2206fn try_count_split_plan_node(
2207    lowered: &PlanNode,
2208    keys: &[Variable],
2209    aggregates: &[(Variable, AggregateExpression)],
2210    profile: Option<&StatsProfile>,
2211) -> Option<PlanNode> {
2212    // Gate 1 — one non-distinct count.
2213    if aggregates.len() != 1 {
2214        return None;
2215    }
2216    let (count_var, counted) = match &aggregates[0] {
2217        (var, AggregateExpression::CountSolutions { distinct: false }) => (var.clone(), None),
2218        (
2219            var,
2220            AggregateExpression::FunctionCall {
2221                name: AggregateFunction::Count,
2222                distinct: false,
2223                expr: Expression::Variable(v),
2224            },
2225        ) => (var.clone(), Some(v.clone())),
2226        _ => return None,
2227    };
2228    // Gate 2 — the query's own grouping is empty. The per-key grouping the
2229    // identity needs is rewrite machinery; a query GROUP BY would need a
2230    // per-group multiplicative sum.
2231    if !keys.is_empty() {
2232        return None;
2233    }
2234    // Gate 3 — the body is exactly a single-key join.
2235    let PlanNode::Join {
2236        left,
2237        right,
2238        hash_keys,
2239        meta,
2240        ..
2241    } = lowered
2242    else {
2243        return None;
2244    };
2245    let [join_key] = hash_keys.as_slice() else {
2246        return None;
2247    };
2248    // Arm roles are shape-driven, in either position: the association pass has
2249    // already settled the association, and each arm gets the role its own
2250    // geometry supports.
2251    let left_storage = storage_countable(left, join_key, counted.as_ref());
2252    let right_storage = storage_countable(right, join_key, counted.as_ref());
2253    let (left_role, right_role) = match (left_storage, right_storage) {
2254        // Both arms storage-countable: two stored relations, no collapse.
2255        // `COUNT(?v)` is refused here because which relation absorbs the
2256        // counted variable's multiplicity would be ambiguous; only the bare
2257        // `COUNT(*)` decomposes this way in the first cut.
2258        (Some(left_kind), Some(right_kind)) => {
2259            if counted.is_some() {
2260                return None;
2261            }
2262            (
2263                CountSplitRole::Storage(left_kind),
2264                CountSplitRole::Storage(right_kind),
2265            )
2266        }
2267        (Some(kind), None) => {
2268            if !collapse_countable(right) {
2269                return None;
2270            }
2271            (CountSplitRole::Storage(kind), CountSplitRole::Collapse)
2272        }
2273        (None, Some(kind)) => {
2274            if !collapse_countable(left) {
2275                return None;
2276            }
2277            (CountSplitRole::Collapse, CountSplitRole::Storage(kind))
2278        }
2279        (None, None) => return None,
2280    };
2281    // Gate 4 — estimate, last: fire only when the join's product estimate
2282    // at THIS pipeline position dwarfs the run-length read cost. Pi is the
2283    // join's stamped produced estimate (nothing is re-derived); the two
2284    // later refinalize_joins rounds may re-seat the emitted relations, so
2285    // this is not a claim about the final plan's estimate. H is one profile
2286    // call per stored relation; with two stored relations the larger head
2287    // domain is the conservative read-cost proxy (the read pays their sum,
2288    // and the larger one already refuses the selective shapes this gate
2289    // exists for). No profile means no honest comparison, so the status-quo
2290    // plan stays.
2291    let profile = profile?;
2292    let mut head_domain: Option<u64> = None;
2293    for (arm, kind) in [(left.as_ref(), left_role), (right.as_ref(), right_role)] {
2294        let CountSplitRole::Storage(kind) = kind else {
2295            continue;
2296        };
2297        let PlanNode::Scan(scan) = arm else {
2298            return None;
2299        };
2300        let estimate = head_domain_estimate(profile, scan, kind.head_slot())?;
2301        head_domain = Some(head_domain.map_or(estimate, |current: u64| current.max(estimate)));
2302    }
2303    let head_domain = head_domain?;
2304    if meta.produced_row_count_estimate
2305        < head_domain.saturating_mul(COUNT_SPLIT_MIN_PRODUCT_PER_HEAD)
2306    {
2307        return None;
2308    }
2309
2310    // Emit: per-arm count relations, the key join, the per-key product, and
2311    // the single-group sum. The Group node is replaced in place, so its
2312    // aggregate variable name (which the alias Extend above reads) and the
2313    // output schema both survive unchanged.
2314    let (left_relation, left_count) =
2315        count_split_relation(left_role, left, join_key, counted.as_ref(), Some(profile))?;
2316    let (right_relation, right_count) =
2317        count_split_relation(right_role, right, join_key, counted.as_ref(), Some(profile))?;
2318    let count_join = join_nodes(left_relation, right_relation, Some(profile));
2319    let product = mint_count_split_var("product");
2320    let product_node = PlanNode::Extend {
2321        inner: Box::new(count_join),
2322        variable: product.clone(),
2323        expression: Expression::Multiply(
2324            Box::new(Expression::Variable(left_count)),
2325            Box::new(Expression::Variable(right_count)),
2326        ),
2327        const_strings: Vec::new(),
2328        const_blobs: Vec::new(),
2329    };
2330    Some(PlanNode::Group {
2331        inner: Box::new(product_node),
2332        variables: Vec::new(),
2333        aggregates: vec![(
2334            count_var,
2335            AggregateExpression::FunctionCall {
2336                name: AggregateFunction::Sum,
2337                expr: Expression::Variable(product),
2338                distinct: false,
2339            },
2340        )],
2341        const_strings: Vec::new(),
2342        const_blobs: Vec::new(),
2343    })
2344}
2345
2346/// Whether `arm` can serve as a stored count relation for the count-split:
2347/// a single scan whose slot geometry fits a [`DomainScanKind`] with the
2348/// join key on the head slot and, when the aggregate counts a variable,
2349/// that variable on the dead slot. Returns the fitting kind so the caller
2350/// does not re-iterate kinds when emitting the node.
2351///
2352/// The dead slot's liveness mark is deliberately not consulted. The
2353/// split's structural gates — empty query group keys, a single
2354/// non-distinct count, and a body that is exactly a join — already imply
2355/// no value of either arm is read above the join: the relation replaces
2356/// the arm wholesale, and the dead slot's multiplicity is the payload.
2357/// The sibling matchers' liveness conditions describe plans where the
2358/// scan survives the rewrite; this scan does not.
2359///
2360/// A broadcast claim on the head slot is also not refused, another
2361/// deliberate divergence from the sibling matchers: claims are restamped
2362/// for the joined plan at the match point, but the arm is replaced by the
2363/// count relation, so the claim's fetch plan dies with the scan. The rule
2364/// exists for scans that keep executing.
2365fn storage_countable(
2366    arm: &PlanNode,
2367    join_key: &Variable,
2368    counted: Option<&Variable>,
2369) -> Option<DomainScanKind> {
2370    let PlanNode::Scan(scan) = arm else {
2371        return None;
2372    };
2373    // The count RPC has no graph-slot identity: an unbound GRAPH window
2374    // keeps G in the plan and cannot be served by the run-length read.
2375    if scan.graph.is_some() || crate::liveness::repeated_var_needs_dropped_slot(scan) {
2376        return None;
2377    }
2378    DOMAIN_SCAN_KINDS.into_iter().find(|kind| {
2379        // The head slot carries the join key: that column is both the
2380        // relation's key and the counted family's distinct value.
2381        if scan_slot_variable(scan, kind.head_slot()) != Some(join_key) {
2382            return false;
2383        }
2384        // A pattern constant on the head or dead slot is not a count
2385        // family: a bound head has no domain walk, and a bound dead slot
2386        // constrains a slot the RPC never returns.
2387        if scan_op_pattern_term(scan, kind.head_slot()).is_some()
2388            || scan_op_pattern_term(scan, kind.dead_slot()).is_some()
2389        {
2390            return false;
2391        }
2392        if let Some(counted) = counted {
2393            // COUNT(?v) binds ?v to the counted slot; the relation absorbs
2394            // its multiplicity. A variable counted elsewhere in the join
2395            // body has no first-cut binding.
2396            if scan_slot_variable(scan, kind.dead_slot()) != Some(counted) {
2397                return false;
2398            }
2399            // The counted variable must occur once: twice means the dead
2400            // slot's run length no longer carries its multiplicity.
2401            if scan
2402                .slot_variables()
2403                .iter()
2404                .filter(|s| *s == counted)
2405                .count()
2406                != 1
2407            {
2408                return false;
2409            }
2410        }
2411        true
2412    })
2413}
2414
2415/// Whether `arm` can collapse to a per-key pair count: a scan, or a
2416/// one-level join of two scans. Deeper subtrees stay on the generic group
2417/// path — the first cut does not recurse, because a nested split would
2418/// multiply the refusal surface without a corpus shape to justify it.
2419fn collapse_countable(arm: &PlanNode) -> bool {
2420    match arm {
2421        PlanNode::Scan(_) => true,
2422        PlanNode::Join { left, right, .. } => {
2423            matches!(left.as_ref(), PlanNode::Scan(_))
2424                && matches!(right.as_ref(), PlanNode::Scan(_))
2425        }
2426        _ => false,
2427    }
2428}
2429
2430/// The count relation for one classified arm: a stored [`PlanNode::DomainCounts`]
2431/// read for the storage role, or a per-key `COUNT(*)` collapse for the
2432/// other. Returns the relation node and its count column.
2433fn count_split_relation(
2434    role: CountSplitRole,
2435    arm: &PlanNode,
2436    join_key: &Variable,
2437    counted: Option<&Variable>,
2438    profile: Option<&StatsProfile>,
2439) -> Option<(PlanNode, Variable)> {
2440    match role {
2441        CountSplitRole::Storage(kind) => {
2442            let PlanNode::Scan(scan) = arm else {
2443                return None;
2444            };
2445            let (constraints, constraint_var) =
2446                constraint_terms_for_count_shortcut(arm, scan, kind)?;
2447            // First cut: a lone pattern constant. A constraint column that
2448            // is also a key (the VALUES two-key shape) does not arise in a
2449            // join arm, and a multi-term list would need the VALUES
2450            // multiplicity machinery.
2451            if constraint_var.is_some() || constraints.len() != 1 {
2452                return None;
2453            }
2454            let count = mint_count_split_var("count");
2455            let dead = scan_slot_variable(scan, kind.dead_slot()).cloned();
2456            let produced = profile
2457                .and_then(|profile| head_domain_estimate(profile, scan, kind.head_slot()))
2458                .unwrap_or(scan.produced_row_count_estimate);
2459            let node = PlanNode::DomainCounts {
2460                kind,
2461                constraints,
2462                constraint_multiplicity: vec![1],
2463                constraint_var: None,
2464                head: join_key.clone(),
2465                count: count.clone(),
2466                dead,
2467                count_star: counted.is_none(),
2468                count_distinct: false,
2469                graph_name: scan.pattern.graph_name.clone(),
2470                graph_filter: scan.graph_filter.clone(),
2471                merge_default_graph: scan.merge_default_graph,
2472                iri_only: scan.is_iri_only(join_key),
2473                produced_row_count_estimate: produced,
2474            };
2475            Some((node, count))
2476        }
2477        CountSplitRole::Collapse => {
2478            let count = mint_count_split_var("count");
2479            Some((
2480                PlanNode::Group {
2481                    inner: Box::new(arm.clone()),
2482                    variables: vec![join_key.clone()],
2483                    aggregates: vec![(
2484                        count.clone(),
2485                        AggregateExpression::CountSolutions { distinct: false },
2486                    )],
2487                    const_strings: Vec::new(),
2488                    const_blobs: Vec::new(),
2489                },
2490                count,
2491            ))
2492        }
2493    }
2494}
2495
2496/// Hidden count-split variable: `cs_<random>_<suffix>`. Same collision
2497/// rationale as [`mint_graph_active_var`]: relation columns are internal to
2498/// the emitted subtree and must never capture a user variable.
2499fn mint_count_split_var(suffix: &str) -> Variable {
2500    let sq = mint_scope_prefix();
2501    Variable::new_unchecked(format!(
2502        "cs_{}{}",
2503        sq.strip_prefix("sq_").unwrap_or(&sq),
2504        suffix
2505    ))
2506}
2507
2508/// Per-constraint VALUES row counts, parallel to `constraints`.
2509///
2510/// No VALUES sibling (folded `sameTerm`, lone scan): every factor is 1.
2511/// A VALUES table must bind `constraint` on every row. Another column that
2512/// also sits on the scan is a join key, not a scalar on this term, so the
2513/// rewrite refuses. The distinct-term list must already match `constraints`
2514/// (allow-list order, or the single grounded pattern term).
2515fn constraint_multiplicity_for_two_keys(
2516    inner: &PlanNode,
2517    scan: &ScanOp,
2518    constraint: &Variable,
2519    constraints: &[EncodedTerm],
2520) -> Option<Vec<u64>> {
2521    let Some(values) = values_from_group_body(inner) else {
2522        return Some(vec![1; constraints.len()]);
2523    };
2524    let slots = scan.slot_variables();
2525    for column in &values.variables {
2526        if column != constraint && slots.iter().any(|slot| slot == column) {
2527            return None;
2528        }
2529    }
2530    let (terms, counts) = values.constraint_row_counts(constraint)?;
2531    if terms.as_slice() != constraints {
2532        return None;
2533    }
2534    Some(counts)
2535}
2536
2537pub(crate) fn domain_counts_schema_vars(
2538    constraint_var: &Option<Variable>,
2539    head: &Variable,
2540    count: &Variable,
2541) -> Vec<Variable> {
2542    match constraint_var {
2543        Some(cv) => vec![cv.clone(), head.clone(), count.clone()],
2544        None => vec![head.clone(), count.clone()],
2545    }
2546}
2547
2548/// Output schema of a [`PlanNode::HeadCounts`] leaf: the PER_HEAD group key
2549/// (`None` in TOTAL mode) followed by the count alias.
2550pub(crate) fn head_counts_schema_vars(group: &Option<Variable>, count: &Variable) -> Vec<Variable> {
2551    match group {
2552        Some(g) => vec![g.clone(), count.clone()],
2553        None => vec![count.clone()],
2554    }
2555}
2556
2557fn join_output_vars(left: &OutputVars, right: &OutputVars) -> OutputVars {
2558    let mut always_bound = Vec::new();
2559    let mut maybe_unbound = Vec::new();
2560
2561    for v in &left.always_bound {
2562        if !always_bound.contains(v) {
2563            always_bound.push(v.clone());
2564        }
2565    }
2566    for v in &right.always_bound {
2567        if !always_bound.contains(v) {
2568            always_bound.push(v.clone());
2569        }
2570    }
2571    // Shared maybe-unbound on both sides stays maybe; promote if the other
2572    // side always-binds (handled above when that side's always list is copied).
2573    for v in left.maybe_unbound.iter().chain(right.maybe_unbound.iter()) {
2574        if always_bound.contains(v) || maybe_unbound.contains(v) {
2575            continue;
2576        }
2577        // Shared: if either side always-binds, already in always_bound.
2578        // Otherwise maybe.
2579        maybe_unbound.push(v.clone());
2580    }
2581    OutputVars {
2582        always_bound,
2583        maybe_unbound,
2584    }
2585}
2586
2587fn left_join_output_vars(left: &OutputVars, right: &OutputVars) -> OutputVars {
2588    let mut maybe_unbound = left.maybe_unbound.clone();
2589    for v in right.all() {
2590        if left.contains(&v) {
2591            continue; // join key / already on left
2592        }
2593        if !maybe_unbound.contains(&v) {
2594            maybe_unbound.push(v);
2595        }
2596    }
2597    OutputVars {
2598        always_bound: left.always_bound.clone(),
2599        maybe_unbound,
2600    }
2601}
2602
2603/// SPARQL `UNION`: a var is always-bound only if both arms always-bind it.
2604fn union_output_vars(left: &OutputVars, right: &OutputVars) -> OutputVars {
2605    let always_bound: Vec<Variable> = left
2606        .always_bound
2607        .iter()
2608        .filter(|v| right.is_always_bound(v))
2609        .cloned()
2610        .collect();
2611    let mut maybe_unbound = Vec::new();
2612    for v in left.all().into_iter().chain(right.all()) {
2613        if always_bound.contains(&v) || maybe_unbound.contains(&v) {
2614            continue;
2615        }
2616        maybe_unbound.push(v);
2617    }
2618    OutputVars {
2619        always_bound,
2620        maybe_unbound,
2621    }
2622}
2623
2624/// Every leaf arm of a `Union` spine, in left-to-right plan order.
2625///
2626/// `spargebra` lowers `A UNION B UNION C` left-deep, so the plan carries one
2627/// binary [`PlanNode::Union`] per branch after the first. Consumers that work
2628/// per branch — today the eager executor's arm schedule — want the flat leaf
2629/// list rather than the nested nodes, so this collects it once. A non-`Union`
2630/// node yields itself, so no caller needs a shape check.
2631pub(crate) fn union_arms(node: &PlanNode) -> Vec<&PlanNode> {
2632    let mut arms = Vec::new();
2633    collect_union_arms(node, &mut arms);
2634    arms
2635}
2636
2637fn collect_union_arms<'a>(node: &'a PlanNode, out: &mut Vec<&'a PlanNode>) {
2638    match node {
2639        PlanNode::Union { left, right } => {
2640            collect_union_arms(left, out);
2641            collect_union_arms(right, out);
2642        }
2643        other => out.push(other),
2644    }
2645}
2646
2647/// Plan-fixed output schema of a flat [`union_arms`] list: each arm's live
2648/// variables in left-to-right arm order, each name once.
2649///
2650/// The eager UNION accumulator is seeded with this list, so its column order
2651/// does not depend on completion order. It is also the canonical layout for
2652/// `COUNT(DISTINCT *)` when a group fold consumes arm tables directly: the
2653/// row key is positional, and an arm's own schema may order the same names
2654/// differently or omit a name another arm binds.
2655pub(crate) fn union_schema(arms: &[&PlanNode]) -> Vec<Variable> {
2656    let mut schema: Vec<Variable> = Vec::new();
2657    for arm in arms {
2658        for variable in arm.variables() {
2659            if !schema.contains(&variable) {
2660                schema.push(variable);
2661            }
2662        }
2663    }
2664    schema
2665}
2666
2667/// How a group's `COUNT(DISTINCT ?v)` accumulator implements the DISTINCT.
2668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2669pub(crate) enum CountMode {
2670    /// Keep the per-group DISTINCT seen-set.
2671    Distinct,
2672    /// Count bound rows. The plan proved the arm binds the counted variable at
2673    /// most once per group, so the seen-set cannot change the result.
2674    CountRows,
2675}
2676
2677/// Plan-time mode map for a fused group fold over a `UNION` spine.
2678///
2679/// The arm discriminator is a group key bound to a row-invariant constant by
2680/// every arm (`?dim` in the facet shape). A group key includes that constant,
2681/// so a group can span two arms only when two arms share the constant; those
2682/// entries stay on `Distinct`. Only new groups consult the map, at
2683/// [`crate::aggregate::Grouping::fold`]'s group-creation step.
2684#[derive(Debug, Clone)]
2685pub(crate) struct CountModePlan {
2686    /// The group key that identifies the arm (`?dim`).
2687    pub(crate) dim: Variable,
2688    /// Its position in the Group's key list.
2689    pub(crate) dim_index: usize,
2690    /// Per arm discriminator, the mode for the Group's single aggregate.
2691    pub(crate) by_dim: FxHashMap<EncodedTerm, CountMode>,
2692}
2693
2694impl CountModePlan {
2695    /// Mode for the group whose key carries `key_terms[dim_index]`.
2696    /// `None` means the caller must keep `Distinct` (the conservative default).
2697    pub(crate) fn for_key(&self, key_terms: &[Option<EncodedTerm>]) -> Option<CountMode> {
2698        let term = key_terms.get(self.dim_index)?.as_ref()?;
2699        self.by_dim.get(term).copied()
2700    }
2701
2702    /// Debug summary for the execution-side marker.
2703    pub(crate) fn summary(&self) -> String {
2704        let count_rows = self
2705            .by_dim
2706            .values()
2707            .filter(|mode| **mode == CountMode::CountRows)
2708            .count();
2709        format!(
2710            "dim=?{} arms_count_rows={} arms_distinct={}",
2711            self.dim.as_str(),
2712            count_rows,
2713            self.by_dim.len() - count_rows
2714        )
2715    }
2716}
2717
2718/// Build the per-group `COUNT(DISTINCT)` mode map for a fused group fold.
2719///
2720/// The first cut accepts only the two fused shapes:
2721/// - `Group(Union)`, where no join sits between an arm and the Group;
2722/// - `Group(Join { left: Union, right: Scan, strategy: Semi })`, where the
2723///   right scan is key-unique so both the semi filter and the runtime hash
2724///   fallback preserve the counted variable's row count.
2725///
2726/// The arm proof is deliberately narrow: one plain `Scan` under a
2727/// row-invariant `Extend` that binds the arm discriminator; the counted
2728/// variable bound exactly once, not grounded, not a group key; every other
2729/// scan variable a group key or ground; fixed graph; no specialized scan.
2730/// Anything else leaves the group on `Distinct`.
2731pub(crate) fn count_mode_plan(
2732    inner: &PlanNode,
2733    keys: &[Variable],
2734    aggregates: &[(Variable, AggregateExpression)],
2735) -> Option<CountModePlan> {
2736    let arms = match inner {
2737        PlanNode::Union { .. } => union_arms(inner),
2738        PlanNode::Join {
2739            left,
2740            right,
2741            hash_keys,
2742            meta,
2743            ..
2744        } if meta.strategy == JoinStrategy::SemiScan
2745            && matches!(left.as_ref(), PlanNode::Union { .. })
2746            && right.as_scan().is_some_and(|scan| {
2747                !scan.has_specialized_rpc() && scan_is_key_unique(scan, hash_keys)
2748            }) =>
2749        {
2750            union_arms(left)
2751        }
2752        _ => return None,
2753    };
2754    if arms.is_empty() || aggregates.len() != 1 {
2755        return None;
2756    }
2757    let counted = match &aggregates[0].1 {
2758        AggregateExpression::FunctionCall {
2759            name: AggregateFunction::Count,
2760            distinct: true,
2761            expr: Expression::Variable(variable),
2762        } => variable,
2763        _ => return None,
2764    };
2765    if keys.contains(counted) {
2766        return None;
2767    }
2768    // The arm discriminator is the one group key every arm binds to a
2769    // row-invariant constant. More than one such key would need a tuple key;
2770    // the first cut refuses instead of guessing which one identifies the arm.
2771    let mut dims = keys.iter().filter(|key| {
2772        arms.iter()
2773            .all(|arm| walk_arm(arm, key).is_some_and(|(term, _)| term.is_some()))
2774    });
2775    let dim = dims.next()?.clone();
2776    if dims.next().is_some() {
2777        return None;
2778    }
2779    let dim_index = keys.iter().position(|key| key == &dim)?;
2780    let mut by_dim: FxHashMap<EncodedTerm, CountMode> = FxHashMap::default();
2781    for arm in &arms {
2782        let (term, scan) = walk_arm(arm, &dim)?;
2783        let term = term?;
2784        let mode = if scan.is_some_and(|scan| arm_count_rows_eligible(scan, counted, keys)) {
2785            CountMode::CountRows
2786        } else {
2787            CountMode::Distinct
2788        };
2789        match by_dim.get_mut(&term) {
2790            Some(existing) => {
2791                // Two arms sharing a constant share groups, and the same
2792                // counted value can appear in both arms. That needs the
2793                // seen-set even when each arm's own pattern is unique.
2794                *existing = CountMode::Distinct;
2795            }
2796            None => {
2797                by_dim.insert(term, mode);
2798            }
2799        }
2800    }
2801    Some(CountModePlan {
2802        dim,
2803        dim_index,
2804        by_dim,
2805    })
2806}
2807
2808/// Walk one arm's edge: a row-invariant `Extend` for `dim` over optional
2809/// `Filter`s and a core node.
2810///
2811/// `Some((Some(term), Some(scan)))` is a plain scan arm that binds `dim`;
2812/// `Some((Some(term), None))` is an identifiable arm whose core is not a
2813/// scan (a join, path, or other node), so it stays on `Distinct`; `None`
2814/// means the edge binds another variable, binds `dim` more than once, or
2815/// the scan itself also carries a `dim` slot.
2816fn walk_arm<'a>(
2817    arm: &'a PlanNode,
2818    dim: &Variable,
2819) -> Option<(Option<EncodedTerm>, Option<&'a ScanOp>)> {
2820    let mut node = arm;
2821    let mut term = None;
2822    loop {
2823        match node {
2824            PlanNode::Extend {
2825                inner,
2826                variable,
2827                expression,
2828                ..
2829            } => {
2830                if variable != dim || term.is_some() || !crate::expr::is_row_invariant(expression) {
2831                    return None;
2832                }
2833                term = Some(constant_encoded_term(expression)?);
2834                node = inner;
2835            }
2836            PlanNode::Filter { inner, .. } => node = inner,
2837            PlanNode::Scan(scan) => {
2838                if scan.slot_variables().iter().any(|variable| variable == dim) {
2839                    return None;
2840                }
2841                return Some((term, Some(scan)));
2842            }
2843            _ => return Some((term, None)),
2844        }
2845    }
2846}
2847
2848fn constant_encoded_term(expression: &Expression) -> Option<EncodedTerm> {
2849    match expression {
2850        Expression::NamedNode(node) => Some(EncodedTerm::from(node)),
2851        Expression::Literal(literal) => Some(crate::plugin::encode_user_literal(literal)),
2852        _ => None,
2853    }
2854}
2855
2856/// Whether one arm's single pattern proves `counted` is unique within each
2857/// group. The walker has already established `dim` is a row-invariant group
2858/// key on the arm and that the core is a plain scan.
2859fn arm_count_rows_eligible(scan: &ScanOp, counted: &Variable, keys: &[Variable]) -> bool {
2860    if scan.has_specialized_rpc()
2861        || scan.merge_default_graph
2862        || scan.graph_filter.is_some()
2863        || scan
2864            .grounded
2865            .iter()
2866            .any(|(variable, _)| variable == counted)
2867        || keys.contains(counted)
2868    {
2869        return false;
2870    }
2871    if let Some(graph) = &scan.graph
2872        && !keys.contains(graph)
2873    {
2874        return false;
2875    }
2876    // The uniqueness proof is over the triple's S/P/O slots. A graph
2877    // variable is bound once per row but a graph can hold many triples with
2878    // the same group key, so `COUNT(DISTINCT ?g)` does not reduce to
2879    // `COUNT(?g)`.
2880    if ![&scan.subject, &scan.predicate, &scan.object]
2881        .into_iter()
2882        .flatten()
2883        .any(|variable| variable == counted)
2884    {
2885        return false;
2886    }
2887    let mut counted_slots = 0usize;
2888    for variable in scan.slot_variables() {
2889        if variable == *counted {
2890            counted_slots += 1;
2891            continue;
2892        }
2893        if keys.contains(&variable)
2894            || scan
2895                .grounded
2896                .iter()
2897                .any(|(grounded, _)| *grounded == variable)
2898        {
2899            continue;
2900        }
2901        return false;
2902    }
2903    counted_slots == 1
2904}
2905
2906/// SPARQL `VALUES` table after encoding (UNDEF cells are `None`).
2907#[derive(Debug, Clone, PartialEq)]
2908pub struct ValuesOp {
2909    /// Column names, in `VALUES` order.
2910    pub variables: Vec<Variable>,
2911    /// One inner vec per row; `None` is UNDEF.
2912    pub rows: Vec<Vec<Option<EncodedTerm>>>,
2913    /// Hash → raw string for hashed constants (filled into the query cache).
2914    pub strings: Vec<(StrHash, String)>,
2915    /// Blob id → original lexical bytes for blob-backed constants (filled
2916    /// into the query blob cache). A plugin-encoded datatype (GeoSPARQL)
2917    /// mints a native term whose payload the registry store never sees —
2918    /// query constants are not data — so the plan carries the query's own
2919    /// bytes, and execution installs them where decode and residual
2920    /// evaluation look first.
2921    pub blobs: Vec<(StrHash, Vec<u8>)>,
2922}
2923
2924impl ValuesOp {
2925    /// Exact cardinality of this table (`0` for `VALUES {}`).
2926    pub fn produced_row_count_estimate(&self) -> u64 {
2927        self.rows.len() as u64
2928    }
2929
2930    /// Columns with any UNDEF are maybe-unbound; others are always-bound.
2931    pub fn output_vars(&self) -> OutputVars {
2932        let mut always_bound = Vec::new();
2933        let mut maybe_unbound = Vec::new();
2934        for (index, variable) in self.variables.iter().enumerate() {
2935            let has_undef = self
2936                .rows
2937                .iter()
2938                .any(|row| row.get(index).is_none_or(Option::is_none));
2939            if has_undef {
2940                maybe_unbound.push(variable.clone());
2941            } else {
2942                always_bound.push(variable.clone());
2943            }
2944        }
2945        OutputVars {
2946            always_bound,
2947            maybe_unbound,
2948        }
2949    }
2950
2951    /// Distinct bound terms in `variable`, for join-key domain costing.
2952    pub(crate) fn distinct_key_count(&self, variable: &Variable) -> Option<u64> {
2953        let index = self.variables.iter().position(|known| known == variable)?;
2954        let mut seen: Vec<&EncodedTerm> = Vec::new();
2955        for row in &self.rows {
2956            if let Some(Some(term)) = row.get(index)
2957                && !seen.contains(&term)
2958            {
2959                seen.push(term);
2960            }
2961        }
2962        Some(seen.len() as u64)
2963    }
2964
2965    /// Single distinct bound term for `variable`, if every row agrees (no UNDEF).
2966    fn unique_term(&self, variable: &Variable) -> Option<EncodedTerm> {
2967        let index = self.variables.iter().position(|known| known == variable)?;
2968        let mut found: Option<&EncodedTerm> = None;
2969        for row in &self.rows {
2970            match row.get(index) {
2971                Some(Some(term)) => {
2972                    if let Some(existing) = found {
2973                        if existing != term {
2974                            return None;
2975                        }
2976                    } else {
2977                        found = Some(term);
2978                    }
2979                }
2980                _ => return None,
2981            }
2982        }
2983        found.cloned()
2984    }
2985
2986    /// Distinct bound terms for `variable` (skips UNDEF).
2987    fn distinct_terms(&self, variable: &Variable) -> Option<Vec<EncodedTerm>> {
2988        let index = self.variables.iter().position(|known| known == variable)?;
2989        let mut seen: Vec<EncodedTerm> = Vec::new();
2990        for row in &self.rows {
2991            if let Some(Some(term)) = row.get(index)
2992                && !seen.iter().any(|existing| existing == term)
2993            {
2994                seen.push(term.clone());
2995            }
2996        }
2997        Some(seen)
2998    }
2999
3000    /// Distinct bound terms of `variable`, in first-seen order, and how many
3001    /// rows carry each. `None` when the column is missing or any row is UNDEF:
3002    /// an unbound VALUES cell is compatible with every BGP binding, which a
3003    /// per-term scalar cannot express.
3004    fn constraint_row_counts(&self, variable: &Variable) -> Option<(Vec<EncodedTerm>, Vec<u64>)> {
3005        let index = self.variables.iter().position(|known| known == variable)?;
3006        let mut terms: Vec<EncodedTerm> = Vec::new();
3007        let mut counts: Vec<u64> = Vec::new();
3008        for row in &self.rows {
3009            let Some(Some(term)) = row.get(index) else {
3010                return None;
3011            };
3012            if let Some(pos) = terms.iter().position(|existing| existing == term) {
3013                counts[pos] = counts[pos].saturating_add(1);
3014            } else {
3015                terms.push(term.clone());
3016                counts.push(1);
3017            }
3018        }
3019        if terms.is_empty() {
3020            return None;
3021        }
3022        Some((terms, counts))
3023    }
3024}
3025
3026/// Costing fallback for [`PlanNode::NamedGraphs`] when no cluster profile is loaded.
3027const NAMED_GRAPHS_ESTIMATED_ROWS: u64 = 1_000_000;
3028
3029fn named_graphs_estimated_rows(profile: Option<&StatsProfile>) -> u64 {
3030    match profile {
3031        Some(p) => p.named_graph_count.max(1),
3032        None => NAMED_GRAPHS_ESTIMATED_ROWS,
3033    }
3034}
3035
3036/// Physical plan tree after sparopt + Waratah lowering.
3037#[derive(Debug, Clone, PartialEq)]
3038pub enum PlanNode {
3039    /// Scan one triple pattern on a hexastore axis.
3040    Scan(ScanOp),
3041    /// Plugin-defined custom operator (`geo_scan` from the `geosparql`
3042    /// plugin in v1): an opaque leaf or wrapper the planner/executor plugins
3043    /// own. Core passes treat it as a leaf producing `variables`.
3044    CustomNode(CustomOp),
3045    /// SPARQL 1.1 property path (`*`, `+`, `?`, `|`, `!`, nested `/`).
3046    Path(PathOp),
3047    /// Inner join of two sub-plans.
3048    Join {
3049        /// Build / probe left side.
3050        left: Box<PlanNode>,
3051        /// Probe / build right side (often a scan for broadcast).
3052        right: Box<PlanNode>,
3053        /// Always-bound equality join keys.
3054        hash_keys: Vec<Variable>,
3055        /// Probe-side distinct-value estimate per hash key, aligned with
3056        /// `hash_keys` (the probe is this join's right arm — pushed key
3057        /// lists filter it). Written at finalize/refinalize (recomputed for
3058        /// the current seating, like `strategy`), read at runtime by the
3059        /// pushdown coverage check in `PushedKeyVals::combine`: a list covering
3060        /// ~the probe's whole key space selects nothing and is skipped, so
3061        /// the scan runs unbound and the join applies the same predicate
3062        /// downstream. Advisory only: 0/absent = unknown → keep pushing.
3063        /// Never read by the estimator — costing keeps deriving from the
3064        /// profile (`join_key_domain_for_node`).
3065        probe_key_domains: Vec<u64>,
3066        /// Per-key vocabulary containment stamp, aligned with `hash_keys`
3067        /// (milli-scaled `|driver vocab ∩ probe vocab| / driver vocab`,
3068        /// `estimate_vocabulary_overlap`): how much of the probe's key
3069        /// space a pushed list can actually reach. Scales the runtime
3070        /// coverage verdict — a cross-population list (candidate ops,
3071        /// unrelated predicates' vocabularies) prunes the probe even when
3072        /// its length saturates the domain count, which the bare count
3073        /// rule cannot see. 1000/absent = full containment (the count
3074        /// rule's sound home) — every degrade path lands here, making
3075        /// 1000 the byte-identical historical behavior.
3076        probe_key_overlap_milli: Vec<u64>,
3077        /// Variables the right (probe) subtree can consume as pushed
3078        /// allow-list keys: hosted in an S/P/O (or graph) slot of a scan
3079        /// leaf reachable through push-transparent containers — the exact
3080        /// topology `probe_scan_has_key` walks ("the modeled
3081        /// push-reachability topology") — plus custom-op outputs (the
3082        /// keyed regime consumes pushed values directly). Stamped by
3083        /// [`stamp_rhs_hostable_keys`] at the finalize/refinalize sites,
3084        /// from the FINAL right arm — after the seating swap and the
3085        /// arm-reshaping passes (grounding removes a hosted slot; graph
3086        /// compose adds one) — unlike the key-aligned stamps, which are
3087        /// taken before the reshaping. A set, not a key-aligned array:
3088        /// hostability does
3089        /// not depend on key order, so
3090        /// `reorder_hash_keys_by_probe_return` never invalidates it.
3091        /// Consumed at runtime by the subtree push gate
3092        /// (`PushGate::Hostable`): a hash key not in this set has no
3093        /// scan leaf to filter anywhere in the probe subtree, so pushing
3094        /// it is dead wire weight, and an ancestor entry outside this
3095        /// set has no consumer below this join.
3096        rhs_hostable_keys: Arc<[Variable]>,
3097        /// Strategy and estimated output cardinality.
3098        meta: JoinMeta,
3099    },
3100    /// SPARQL `OPTIONAL` (left outer join).
3101    LeftJoin {
3102        /// Required side.
3103        left: Box<PlanNode>,
3104        /// Optional side.
3105        right: Box<PlanNode>,
3106        /// Always-bound equality join keys.
3107        hash_keys: Vec<Variable>,
3108        /// Encoded / MaybeEncoded conjuncts folded into the Diff-once probe.
3109        early_filter: Option<Expression>,
3110        /// AlwaysResolve residual (Diff-once after windowed string resolve).
3111        residual_filter: Option<Expression>,
3112        /// Probe-side distinct-value estimate per hash key, aligned with
3113        /// `hash_keys` (the probe is this OPTIONAL's right arm — pushed key
3114        /// lists filter it). Written at finalize/refinalize (recomputed for
3115        /// the current seating, like `strategy`), read at runtime by the
3116        /// pushdown coverage check in `PushedKeyVals::combine`: a list covering
3117        /// ~the probe's whole key space selects nothing and is skipped, so
3118        /// the scan runs unbound and the join applies the same predicate
3119        /// downstream. Advisory only: 0/absent = unknown → keep pushing.
3120        /// Never read by the estimator — costing keeps deriving from the
3121        /// profile (`join_key_domain_for_node`).
3122        probe_key_domains: Vec<u64>,
3123        /// Per-key vocabulary containment stamp, aligned with `hash_keys`
3124        /// (see the `Join` variant's field for the full contract; the
3125        /// OPTIONAL probe's runtime path consumes it identically).
3126        probe_key_overlap_milli: Vec<u64>,
3127        /// Row-count annotations (no strategy — the executor treats every
3128        /// LeftJoin probe identically; runtime key delivery is dynamic).
3129        meta: LeftJoinMeta,
3130    },
3131    /// SPARQL `FILTER`.
3132    Filter {
3133        /// Input solutions.
3134        inner: Box<PlanNode>,
3135        /// Encoded / MaybeEncoded conjuncts (no registry).
3136        early: Option<Expression>,
3137        /// AlwaysResolve residual (windowed resolve then ground EBV).
3138        residual: Option<Expression>,
3139        /// Top-level `EXISTS` / `NOT EXISTS` conjuncts, lowered separately.
3140        /// Empty is an ordinary FILTER. HAVING (`Filter` over `Group`) never
3141        /// populates this — those expressions stay in `early`/`residual` and
3142        /// are rejected by [`split_filter`].
3143        exists: Vec<ExistsClause>,
3144        /// Inner demand may follow caller `n` instead of [`crate::query::tunables::SCAN_BATCH`].
3145        ///
3146        /// Stamped by [`crate::iri_facts::derive_iri_facts`] when every kept
3147        /// conjunct is `isIRI(?v)` / `isURI(?v)` and there is no EXISTS
3148        /// clause. The residual still runs; OpenNode pages the child at `n`
3149        /// because this shape is expected to keep every inner row.
3150        one_to_one: bool,
3151    },
3152    /// SPARQL `UNION` (multiset / bag union of solution mappings).
3153    Union {
3154        /// Left arm.
3155        left: Box<PlanNode>,
3156        /// Right arm.
3157        right: Box<PlanNode>,
3158    },
3159    /// SPARQL empty group `{ }`: one solution with no bindings (join identity).
3160    Unit,
3161    /// SPARQL `VALUES` (inline table).
3162    Values(ValuesOp),
3163    /// Execute-time named-graph catalog (`GRAPH ?g` with no `FROM NAMED`).
3164    ///
3165    /// Enumerated `FROM NAMED` uses [`Self::Values`] instead (no catalog RPC).
3166    /// Estimated rows are [`StatsProfile::named_graph_count`] when a cluster
3167    /// profile is loaded; otherwise [`NAMED_GRAPHS_ESTIMATED_ROWS`].
3168    NamedGraphs {
3169        /// Variable bound to each catalog graph IRI (`?g`).
3170        variable: Variable,
3171        /// Catalog cardinality used for join costing.
3172        produced_row_count_estimate: u64,
3173    },
3174    /// Execute-time catalog membership for empty `GRAPH <iri> { }` when the
3175    /// named window is engine-default (no `FROM NAMED`). One empty row if
3176    /// `graph` is Present; zero rows otherwise. `FROM NAMED` stays plan-time.
3177    NamedGraphExists {
3178        /// Grounded named-graph IRI to look up.
3179        graph: EncodedTerm,
3180    },
3181    /// SPARQL `Join(eval(P), { ?g → μ(?g_active) })` after `GRAPH ?g { P }`
3182    /// when `P` uses `?g` as a triple/OPTIONAL/FILTER variable.
3183    ///
3184    /// Inner scans project the active graph as `active_var`; SPARQL `?g` stays
3185    /// a normal term variable. Unbound `graph_var` is filled from `active_var`
3186    /// (OPTIONAL miss); unequal bound values drop the row.
3187    JoinGraphVar {
3188        /// Inner evaluation of `P` (G slot = `active_var`).
3189        inner: Box<PlanNode>,
3190        /// SPARQL GRAPH variable (`?g`).
3191        graph_var: Variable,
3192        /// Hidden active-graph column projected from inner G slots.
3193        active_var: Variable,
3194    },
3195    /// SPARQL `BIND` / non-aggregate `SELECT (expr AS ?v)` (`Extend`).
3196    Extend {
3197        /// Input solutions.
3198        inner: Box<PlanNode>,
3199        /// Variable introduced by the extend.
3200        variable: Variable,
3201        /// Expression evaluated per row.
3202        expression: Expression,
3203        /// Plan-carried const seed entries for EVERY constant position of
3204        /// `expression` — top level and nested (`COALESCE` fallbacks, `IF`
3205        /// branches, function arguments). Collected at plan finalization
3206        /// ([`attach_const_seeds`]); installed into the executing cache at
3207        /// op entry (`execute_extend`), the `execute_values` contract:
3208        /// hash-only encodings (IRIs, long strings, plugin-encoded
3209        /// geometry) decode from cache entries a fresh mint would not
3210        /// have — inline-encoded constants (numerics, small strings) mint
3211        /// no entries at all — and query constants are not store data,
3212        /// while an arm workspace inherits nothing, so the entries must
3213        /// ride the op that mints them.
3214        const_strings: Vec<(StrHash, String)>,
3215        /// Blob-map payloads for blob-backed const positions (plugin-
3216        /// encoded geometry), keyed like [`Self::const_strings`].
3217        const_blobs: Vec<(StrHash, Vec<u8>)>,
3218    },
3219    /// SPARQL `LIMIT` / `OFFSET` (`Slice`).
3220    Slice {
3221        /// Input solutions.
3222        inner: Box<PlanNode>,
3223        /// Solutions to skip (`OFFSET`).
3224        start: u64,
3225        /// Solutions to keep (`LIMIT`); `None` is OFFSET-only.
3226        length: Option<u64>,
3227    },
3228    /// SPARQL `DISTINCT` on the SELECT projection (first-seen row wins).
3229    Distinct {
3230        /// Input solutions (full join width; extra columns are carried).
3231        inner: Box<PlanNode>,
3232        /// Variables the DEDUP DECIDES on (first-seen key-tuple wins).
3233        /// NOT the output projection: the runtime carries every inner
3234        /// column through, so two rows differing only in a non-key column
3235        /// collapse to the first one (its non-key values win). The SELECT
3236        /// list narrows the width later, in the projection.
3237        columns: Vec<Variable>,
3238    },
3239    /// SPARQL `ORDER BY` (after Distinct, before Slice).
3240    Sort {
3241        /// Input solutions.
3242        inner: Box<PlanNode>,
3243        /// Sort keys (SPARQL order: first key primary).
3244        keys: Vec<SortKey>,
3245    },
3246    /// SPARQL `GROUP BY` plus aggregates (HAVING is a [`Self::Filter`] above).
3247    ///
3248    /// Output columns are the grouping keys plus each aggregate's result
3249    /// variable. Inner columns that are not keys exist only as aggregator
3250    /// inputs and are not projected.
3251    Group {
3252        /// Input solutions (the pattern being grouped).
3253        inner: Box<PlanNode>,
3254        /// `GROUP BY` variables (empty = implicit one group over the whole input).
3255        variables: Vec<Variable>,
3256        /// Aggregate result variable and expression (including `COUNT(*)`).
3257        aggregates: Vec<(Variable, AggregateExpression)>,
3258        /// Plan-carried const seed entries for every constant position of
3259        /// every aggregate-argument expression (same contract as
3260        /// [`Self::Extend`]'s fields): the fold evaluates argument
3261        /// expressions on the encoded path and a const argument's mint
3262        /// escapes into the group value. Installed at
3263        /// `resolve_aggregate_args` entry, above its variable-driven
3264        /// early return — a const-only argument has an empty variable
3265        /// list and would otherwise skip its own seeding.
3266        const_strings: Vec<(StrHash, String)>,
3267        /// Blob-map payloads for blob-backed const positions, keyed like
3268        /// [`Self::const_strings`].
3269        const_blobs: Vec<(StrHash, Vec<u8>)>,
3270    },
3271    /// Group-eliminating count scan: per-`(constraint, head)` run lengths
3272    /// from one `DomainScanCounts` rpc, replacing `Group { Scan { .. } }`
3273    /// for the lone-COUNT shape (Group elimination — no rows are streamed
3274    /// and no compute-side aggregation runs).
3275    ///
3276    /// Output columns are exactly `[head, count]` — the replaced Group's
3277    /// schema (its single key plus the aggregate's alias) — so `Extend`
3278    /// alias passthroughs, HAVING filters, and `Sort`s above keep working.
3279    /// The counted variable is never emitted: the partition supplies its
3280    /// per-head multiplicity as `count`.
3281    DomainCounts {
3282        /// Which constraint/head slot family this scan is.
3283        kind: DomainScanKind,
3284        /// Plan-time constraint term list (one pattern constant, folded
3285        /// sameTerm, or a VALUES allow-list). Distinct: the count RPC
3286        /// uniques its constraint list. Key-sorted (encoded key bytes),
3287        /// matching the order every domain walker visits constraints in.
3288        constraints: Vec<EncodedTerm>,
3289        /// How many VALUES rows carried each [`Self::constraints`] term.
3290        /// Parallel to that list. A lone pattern constant is `[1]`. The
3291        /// materializer multiplies each hit's run length by the factor for
3292        /// `hit.constraint`. The two-key rewrite is not taken when this
3293        /// column has an UNDEF, or when another VALUES column is also a
3294        /// scan slot (that column is a join key, not a scalar).
3295        constraint_multiplicity: Vec<u64>,
3296        /// When the constraint slot is also a GROUP BY key (`VALUES ?p` or
3297        /// grounded-kept predicate), the variable name — omitted for the
3298        /// one-key `?s :p ?o GROUP BY ?o` shape.
3299        constraint_var: Option<Variable>,
3300        /// Group-key variable — the kind's head slot (or second key in the
3301        /// two-key VALUES shape).
3302        head: Variable,
3303        /// Count result variable — the aggregate's alias.
3304        count: Variable,
3305        /// Variable on the kind's dead slot, when the triple named one.
3306        ///
3307        /// Explain reconstructs `COUNT(?dead)` and the source triple from
3308        /// this. The count RPC never returns the slot.
3309        dead: Option<Variable>,
3310        /// `COUNT(*)` rather than `COUNT(?dead)`. The run length is the
3311        /// solution count either way; explain needs the source spelling.
3312        count_star: bool,
3313        /// `COUNT(DISTINCT ?dead)`: the RPC counts distinct slot-2 terms per
3314        /// run, so each hit's count is already the distinct cardinality and
3315        /// VALUES multiplicity must not scale it. The shortcut never serves
3316        /// the graph-count mode (an unbound `?g` refuses the rewrite).
3317        count_distinct: bool,
3318        /// Bound graph name, when the query's graph window is a single
3319        /// grounded graph (`GRAPH <iri>`).
3320        graph_name: Option<EncodedTerm>,
3321        /// Residual graph window pushed with the scan.
3322        graph_filter: Option<GraphFilter>,
3323        /// RDF-merge default graph (`--default-union` / multi-`FROM`). The
3324        /// count RPC uniques S/P/O and skips extra G. The graph filter above
3325        /// is left as the scan planned it.
3326        merge_default_graph: bool,
3327        /// Planner-derived `FILTER(isIRI(?head))` pushdown.
3328        ///
3329        /// Set by [`crate::iri_facts::derive_iri_facts`] when an ancestor
3330        /// conjunct is `isIRI` of the head (the group key). Non-IRI heads
3331        /// are their own groups, so dropping them in the count RPC matches
3332        /// filtering those groups afterwards. The conjunct stays in the plan.
3333        iri_only: bool,
3334        /// Distinct-head estimate for costing (`head_domain_estimate`).
3335        produced_row_count_estimate: u64,
3336    },
3337    /// Group-eliminating head-count leaf (`eliminate_head_counts_groups`):
3338    /// a whole-CF [`AxisHeadScanCounts`][crate::clients::HexastoreScan] call
3339    /// replaces the Group — either the TOTAL shape (ungrouped
3340    /// `COUNT(DISTINCT ?head)`: one integer for the whole column family) or
3341    /// the PER_HEAD shape (`GROUP BY ?head COUNT(DISTINCT ?slot1)`: one
3342    /// `(group, count)` row per slot-0 head, e.g. TSG per-class subject
3343    /// counts). Head counts have no constraint slot, so there is no anchor
3344    /// machinery and no VALUES-facet form.
3345    HeadCounts {
3346        /// Which axis-local column family this scan walks.
3347        kind: HeadScanKind,
3348        /// `true` = TOTAL mode (the distinct slot-0 head count of the whole
3349        /// CF as one row); `false` = PER_HEAD mode (one row per head).
3350        total: bool,
3351        /// The distinct-counted variable: the CF's slot-0 head (TOTAL) or
3352        /// slot-1 term (PER_HEAD). Never broadcast by the RPC in either mode.
3353        counted: Variable,
3354        /// PER_HEAD group-key variable — the CF's slot-0 head. `None` in
3355        /// TOTAL mode (nothing is grouped).
3356        group: Option<Variable>,
3357        /// Count result variable — the aggregate's alias.
3358        count: Variable,
3359        /// Bound graph name, when the query's graph window is a single
3360        /// grounded graph (`GRAPH <iri>`).
3361        graph_name: Option<EncodedTerm>,
3362        /// Residual graph window pushed with the scan.
3363        graph_filter: Option<GraphFilter>,
3364        /// Planner-derived `FILTER(isIRI(?head))` pushdown for the slot-0
3365        /// head term.
3366        iri_only: bool,
3367        /// Distinct-head estimate for costing.
3368        produced_row_count_estimate: u64,
3369    },
3370    /// Group-eliminating bag-count leaf (`eliminate_pattern_count_groups`):
3371    /// ungrouped `COUNT(*)` / bag `COUNT(?v)` over a single BGP. One
3372    /// [`CountPattern`][crate::clients::HexastoreScan] RPC returns the visible
3373    /// Put cardinality; no solution rows cross the wire. Runs after the
3374    /// head/domain eliminate passes so facet and `COUNT(DISTINCT …)` shapes
3375    /// keep those leaves.
3376    PatternCount {
3377        /// Encoded ground slots of the source scan (`None` = unbound).
3378        pattern: EncodedTriplePattern,
3379        /// Subject slot variable, when the BGP named one (EXPLAIN only).
3380        subject: Option<Variable>,
3381        /// Predicate slot variable, when the BGP named one (EXPLAIN only).
3382        predicate: Option<Variable>,
3383        /// Object slot variable, when the BGP named one (EXPLAIN only).
3384        object: Option<Variable>,
3385        /// Count result variable — the aggregate's alias.
3386        count: Variable,
3387        /// `COUNT(*)` rather than `COUNT(?counted)`.
3388        count_star: bool,
3389        /// Variable of a bag `COUNT(?v)`, when that form was rewritten.
3390        counted: Option<Variable>,
3391        /// Residual graph window pushed with the scan.
3392        graph_filter: Option<GraphFilter>,
3393        /// RDF-merge default graph (`--default-union` / multi-`FROM`).
3394        merge_default_graph: bool,
3395        /// Always `1`: the leaf emits one aggregate row.
3396        produced_row_count_estimate: u64,
3397    },
3398    /// SPARQL nested `SELECT` (SubSelect) — an opaque, independently
3399    /// evaluated query boundary.
3400    ///
3401    /// The inner plan is lowered and executed on its own; only `variables`
3402    /// (the subselect's `SELECT` list) cross the boundary and join with the
3403    /// enclosing group. Non-projected inner names are renamed with a random
3404    /// per-subselect scope token at lowering time (`sq_<16 random chars>_`),
3405    /// so same-named outer variables can never collide with them in join
3406    /// keys, filters, or liveness.
3407    SubSelect(SubSelectOp),
3408}
3409
3410/// Explicit execution-cost model for one plugin op ([`CustomOp::cost`]).
3411///
3412/// `produced_row_count_estimate` does double duty today: cardinality for
3413/// join math AND a stand-in execution cost. That conflation is wrong for
3414/// ops whose work does not scale with their OUTPUT — the geo scan's keyless
3415/// (driver-side) sweep drains and relates a whole window regardless of how
3416/// few rows it emits, and its keyed (probe-side) regime is whatever the
3417/// executor's roads make it: a direct per-key decision when the op has one
3418/// (`direct_probe`), otherwise one drain plus a filter over the drain's
3419/// output. This struct names the inputs of those regime formulas; the
3420/// formulas live on [`CustomOp`] (`sweep_cost`, `probe_page_cost`,
3421/// `probe_drain_amortized`, `keyed_cost`) as the CONSERVATIVE PLANNER BOUND
3422/// of the executor's break-even: every key prices at `per_key_unit` because
3423/// the planner knows value COUNTS, never key SHAPES, so a point-heavy mix
3424/// prices higher here than the executor's shape-aware road choice.
3425///
3426/// The probe fields exist because the two old roads were not enough for
3427/// index-scan ops. A text `text:query` drain is driven by the QUERY, not by
3428/// the pushed keys, so its work is the same for a one-key list and a
3429/// million-key list, and its executor has no direct road at all. Pricing
3430/// such an op as `min(direct, drain + survivors × unit)` made it look
3431/// cheap on the probe side and pushed the plan into per-page re-drains.
3432/// `direct_probe = false` removes the invented road;
3433/// `probe_keyed_columns` names which output columns are answered by a keyed
3434/// lookup — a pushed key in an unkeyed column (the text subject resolve's
3435/// graph column) still scans the whole drain output — and
3436/// `probe_memo_entry_rows` says whether the drain can be paid ONCE (the
3437/// op's window fits its drain memo) or must be charged on every page.
3438///
3439/// Consumed by the seating-cost model: the custom driver's work prices
3440/// [`CustomOp::sweep_cost`] via `seat_driver_work_rows`, and the custom
3441/// probe branch of `seat_cost_total` prices `probe_page_cost` per page plus
3442/// the drain once-or-per-page; EXPLAIN renders the drain/unit stamp.
3443///
3444/// Units are the seating-cost model's `rows` currency: one unit ≈ the work of
3445/// reading one row. Partition-side index walks and per-term CPU work both
3446/// map onto it; custom ops carry no index seeks, so they price at zero
3447/// seeks. An op with `cost: None` (every construction site that has not
3448/// opted in) prices opaquely at its row estimate — the pre-cost-model
3449/// behavior, unchanged.
3450#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3451pub struct CustomOpCost {
3452    /// Cost of the op's candidate drain WHEN the execution runs one: the
3453    /// keyless regime always drains; the keyed regime drains only when it
3454    /// takes the semi-join road instead of relating the pushed values
3455    /// directly. The partition-side walk + dedup over the op's index
3456    /// ranges, priced in rows.
3457    pub drain_rows: u64,
3458    /// Per-term relate work for a BLOB-BACKED term: one pushed value in the
3459    /// keyed regime, one candidate in the keyless regime's relate loop —
3460    /// blob fetch (amortized), parse, and exact relate. One conservative
3461    /// unit per op; term-mix refinement is the consumer's option, not the
3462    /// model's.
3463    pub per_key_unit: u64,
3464    /// Relate-only work of an INLINE term: a `LiteralPoint` relates from
3465    /// its stored coordinates with no blob fetch and no parse. The
3466    /// EXECUTOR classifies the actual pushed values by term shape and prices
3467    /// the direct road per key with this unit; the plan-side probe price
3468    /// keeps the conservative all-blob bound because the planner knows key
3469    /// COUNTS, never key SHAPES.
3470    pub inline_point_unit: u64,
3471    /// The op can decide one pushed key locally, without draining. Geo and
3472    /// the text prefix/suffix modes have this road; text FTS and the text
3473    /// subject resolve do not (their candidate set comes from the index
3474    /// query, and a pushed literal/subject cannot be answered by a local
3475    /// test).
3476    pub direct_probe: bool,
3477    /// Bit `i` set: output variable `i` is answered by a KEYED lookup, so a
3478    /// probe page on that column examines `min(pushed, produced)` and pays
3479    /// `pushed × probe_filter_unit`. Bit clear, or no known pushed column:
3480    /// the page filters the WHOLE drain output (`produced`).
3481    ///
3482    /// Single-column ops use `0` for a scan filter (the literal-mode
3483    /// candidate scan) and `1` for a keyed decision (geo, the subject
3484    /// resolve). The subject resolve's two-column shape is `0b1`: the
3485    /// memoized window is sorted by `(subject, graph)`, so a pushed subject
3486    /// is a binary search while a pushed GRAPH still scans the window.
3487    pub probe_keyed_columns: u8,
3488    /// Per-row work of a probe page's filter over the drain output. For an
3489    /// op that filters the drain's rows this is the per-row compare cost;
3490    /// for one that indexes the drain output by key it would be the lookup
3491    /// cost instead.
3492    pub probe_filter_unit: u64,
3493    /// Rows the op's drain-window memo can admit (`0` = never amortized).
3494    /// When `produced <= probe_memo_entry_rows` the cost model charges the drain
3495    /// ONCE and only the filter per page; otherwise the drain is charged on
3496    /// every page — the honest price for a window the memo will refuse and
3497    /// the executor will re-drain.
3498    pub probe_memo_entry_rows: u64,
3499}
3500
3501/// One plugin-defined custom operator.
3502///
3503/// `plugin_id` names the registered plugin (`"geosparql"`); `op_id` names the
3504/// operation inside it (`"geo_scan"`). `payload` is typed and downcast
3505/// inside the plugin — never a stringly blob. `children` lets future plugins
3506/// wrap inner plans (FTS/time); the geo scan is a leaf. Every core pass
3507/// (liveness, explain, pushdown, …) treats a `CustomOp` as an opaque leaf
3508/// producing exactly `variables` unless the plugin supplies hooks.
3509#[derive(Debug, Clone, PartialEq)]
3510pub struct CustomOp {
3511    /// Registered plugin that owns this op (`"geosparql"`).
3512    pub plugin_id: &'static str,
3513    /// Operation inside the plugin (`"geo_scan"`).
3514    pub op_id: &'static str,
3515    /// Typed payload (downcast inside the plugin).
3516    pub payload: crate::plugin::PluginPayloadBox,
3517    /// Wrapped inner plan (empty for a leaf like `geo_scan`).
3518    pub children: Vec<PlanNode>,
3519    /// Output schema (variables this op binds).
3520    pub variables: Vec<Variable>,
3521    /// Planner estimate for join costing.
3522    pub produced_row_count_estimate: u64,
3523    /// Explicit regime cost model ([`CustomOpCost`]), stamped by the
3524    /// minting rewrite and clampable by later estimate passes. Cardinality
3525    /// stays in `produced_row_count_estimate` — this prices EXECUTION, and
3526    /// exists so placement/pricing never mistakes a low-output op for a
3527    /// cheap one. `None` = opaque (price at the row estimate).
3528    pub cost: Option<CustomOpCost>,
3529    /// Pinned output bindings stamped by plan specialization: the
3530    /// broadcast-probe emulation of a Scan's grounded pattern slot. When the
3531    /// op is the probe arm of a join whose driver binds an output variable to
3532    /// exactly ONE ground term, the rewrite pins `(variable, term)` and the
3533    /// executor relates exactly that term (no runtime key delivery needed).
3534    /// A pin fixes one COLUMN: it makes the op a point only when the op emits
3535    /// that column alone, so a multi-column op keeps its row estimate.
3536    /// Empty for driver-side / list-driven ops. Mirrors the Scan contract
3537    /// that grounded slots survive `clear_broadcast_marks`.
3538    pub pinned: Vec<(Variable, EncodedTerm)>,
3539}
3540
3541impl CustomOp {
3542    /// Keyless (driver-side) execution price: one candidate drain, then a
3543    /// relate pass over every candidate. The regime a BUILD-side geo scan
3544    /// runs — the one whose window-wide work is invisible to output-based
3545    /// pricing. `None` = opaque op (price at `produced_row_count_estimate`).
3546    pub fn sweep_cost(&self) -> Option<u64> {
3547        let cost = self.cost?;
3548        Some(
3549            cost.drain_rows.saturating_add(
3550                self.produced_row_count_estimate
3551                    .saturating_mul(cost.per_key_unit),
3552            ),
3553        )
3554    }
3555
3556    /// One probe page's work for `pushed_val_count` keys, and whether that
3557    /// page's road pays the drain. The cheaper of:
3558    ///
3559    /// - **direct**, only when the op has that road: `pushed × per_key_unit`,
3560    ///   no drain;
3561    /// - **filter**: `examined × probe_filter_unit`, where `examined` is the
3562    ///   whole drain output unless the pushed column is one the op answers
3563    ///   by key ([`CustomOpCost::probe_keyed_columns`]), in which case it is
3564    ///   `min(pushed, produced)` survivors — plus the drain itself.
3565    ///
3566    /// the cost model charges the drain once for a memoizable window
3567    /// ([`Self::probe_drain_amortized`]) and per page otherwise.
3568    /// `pushed_column` is the pushed output variable's position, or `None`
3569    /// when no column-specific push is known.
3570    /// `None` = opaque op (price at `produced_row_count_estimate`).
3571    pub fn probe_page_cost(
3572        &self,
3573        pushed_val_count: u64,
3574        pushed_column: Option<usize>,
3575    ) -> Option<(u64, bool)> {
3576        let cost = self.cost?;
3577        let direct = cost
3578            .direct_probe
3579            .then(|| pushed_val_count.saturating_mul(cost.per_key_unit));
3580        let keyed = pushed_column
3581            .is_some_and(|column| column < 8 && cost.probe_keyed_columns & (1u8 << column) != 0);
3582        let examined = if keyed {
3583            pushed_val_count.min(self.produced_row_count_estimate)
3584        } else {
3585            self.produced_row_count_estimate
3586        };
3587        let filter = examined.saturating_mul(cost.probe_filter_unit);
3588        Some(match direct {
3589            Some(direct) if direct <= filter => (direct, false),
3590            _ => (filter, true),
3591        })
3592    }
3593
3594    /// Whether the drain is paid ONCE for this op's window: the op's drain
3595    /// memo admits it (`produced <= probe_memo_entry_rows`, and the op opted
3596    /// in with a non-zero limit). A false answer prices the drain on every
3597    /// probe page — the executor re-drains when the memo refuses.
3598    pub fn probe_drain_amortized(&self) -> bool {
3599        self.cost.is_some_and(|cost| {
3600            cost.probe_memo_entry_rows > 0
3601                && self.produced_row_count_estimate <= cost.probe_memo_entry_rows
3602        })
3603    }
3604
3605    /// Keyed (probe-side) execution price for ONE execution against
3606    /// `pushed_val_count` pushed values in `pushed_column`: the page price
3607    /// plus the drain when that road pays it. This is the per-EXECUTION
3608    /// bound the keyed-driver cost estimate charges per ancestor page; the custom
3609    /// probe branch uses [`Self::probe_page_cost`] plus
3610    /// [`Self::probe_drain_amortized`] to decide between one drain and one
3611    /// per page. `None` = opaque op (price at
3612    /// `produced_row_count_estimate`).
3613    pub fn keyed_cost(&self, pushed_val_count: u64, pushed_column: Option<usize>) -> Option<u64> {
3614        let (per_page, pays_drain) = self.probe_page_cost(pushed_val_count, pushed_column)?;
3615        Some(if pays_drain {
3616            self.cost?.drain_rows.saturating_add(per_page)
3617        } else {
3618            per_page
3619        })
3620    }
3621}
3622
3623/// One SPARQL `ORDER BY` key.
3624#[derive(Debug, Clone, PartialEq)]
3625pub struct SortKey {
3626    /// Sort expression.
3627    pub expression: Expression,
3628    /// `true` for `DESC()`.
3629    pub descending: bool,
3630}
3631
3632/// How a lowered [`ExistsClause`] will run.
3633#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3634pub enum ExistsKind {
3635    /// No shared names with the outer pattern (including FILTER/BIND
3636    /// expressions). One ASK for the whole query.
3637    Uncorrelated,
3638    /// Simple BGP body; semi-join on always-bound correlation keys. Every
3639    /// expression-referenced correlation var is also a body column.
3640    SemiJoin,
3641    /// OPTIONAL / UNION / Path / nested EXISTS / `GRAPH ?g` / maybe-unbound
3642    /// keys / expression-only correlation (outer vars used in FILTER/BIND
3643    /// that the body does not produce as columns).
3644    NestedProbe,
3645}
3646
3647/// One `EXISTS { P }` or `NOT EXISTS { P }` FILTER conjunct.
3648///
3649/// Only top-level `&&` conjuncts of a `FILTER` (not HAVING, not OPTIONAL
3650/// conditions) lower here. The following stay
3651/// [`ComputeError::UnsupportedSparql`]:
3652///
3653/// - `BIND(EXISTS { … } AS ?e)`
3654/// - `IF(EXISTS { … }, …, …)` (and any other `EXISTS` left in a residual
3655///   expression, including `FILTER(EXISTS { … } || …)`)
3656/// - `HAVING EXISTS { … }`
3657/// - OPTIONAL / LeftJoin *condition* containing `EXISTS`
3658/// - EXISTS body sub-SELECT that references outer variables
3659/// - EXISTS body `GROUP BY` that references outer variables
3660/// - `EXISTS` remaining as an expression inside a renamed sub-SELECT /
3661///   NestedProbe scope (`EXISTS inside a sub-SELECT is not supported`)
3662#[derive(Debug, Clone, PartialEq)]
3663pub struct ExistsClause {
3664    /// `true` for `NOT EXISTS`.
3665    pub negated: bool,
3666    /// Lowered body (sparopt + Waratah). Mode 3 may rename inner-only names.
3667    pub body: Box<PlanNode>,
3668    /// Outer variables that appear in the body. Empty ⇒ uncorrelated.
3669    pub correlation: Vec<Variable>,
3670    /// Execution strategy chosen after the body was lowered.
3671    pub kind: ExistsKind,
3672}
3673
3674/// Lowered nested `SELECT` (SubSelect) boundary.
3675#[derive(Debug, Clone, PartialEq)]
3676pub struct SubSelectOp {
3677    /// The fully lowered subselect, including its own Distinct / Slice
3678    /// modifier spine (`lower_subselect` folds `Slice?(Distinct?(Project))`
3679    /// in), plus any Group / HAVING from the body. Executes as an
3680    /// independent query, bounded by its own OFFSET/LIMIT.
3681    pub inner: Box<PlanNode>,
3682    /// The subselect's `SELECT` list — the only variables visible outside the
3683    /// boundary, in `SELECT` order. Liveness may prune dead names from this
3684    /// list (see `crate::liveness`); an in-boundary `Distinct.columns` keeps
3685    /// the FULL list — deduping by a pruned column would change the output
3686    /// multiset.
3687    pub variables: Vec<Variable>,
3688}
3689
3690impl SubSelectOp {
3691    /// Exact boundary schema.
3692    pub fn variables(&self) -> &[Variable] {
3693        &self.variables
3694    }
3695
3696    /// Estimated cardinality of the subquery output. The in-boundary Slice
3697    /// (when the subselect has OFFSET/LIMIT) caps the body estimate; Group
3698    /// caps it at one row per key.
3699    pub fn produced_row_count_estimate(&self) -> u64 {
3700        self.inner.produced_row_count_estimate().max(1)
3701    }
3702}
3703
3704/// Extra row-equivalents per input row for a FILTER's scalar conjuncts.
3705///
3706/// Each `early` / `residual` conjunct is classified by
3707/// [`crate::expr::ExprCapability`]: encoded conjuncts are cheapest,
3708/// maybe-encoded ones may materialize a term, and resolve conjuncts take the
3709/// deferred string path. The rate is per conjunct, so an AND of three pays
3710/// three times. EXISTS clauses are excluded here: their body rows are a
3711/// separate term the cost walks already add.
3712fn filter_row_cost_milli(early: Option<&Expression>, residual: Option<&Expression>) -> u64 {
3713    let mut total = 0u64;
3714    for expression in early.iter().chain(residual.iter()) {
3715        for conjunct in flatten_and(expression) {
3716            let rate = match classify(&conjunct) {
3717                ExprCapability::AlwaysEncoded => {
3718                    crate::query::tunables::FILTER_ENCODED_ROW_EQUIV_MILLI
3719                }
3720                ExprCapability::MaybeEncoded => {
3721                    crate::query::tunables::FILTER_MAYBE_ENCODED_ROW_EQUIV_MILLI
3722                }
3723                ExprCapability::AlwaysResolve | ExprCapability::Unsupported => {
3724                    crate::query::tunables::FILTER_RESOLVE_ROW_EQUIV_MILLI
3725                }
3726            };
3727            total = total.saturating_add(rate);
3728        }
3729    }
3730    total
3731}
3732
3733/// FILTER selectivity, in milli (1000 = pass every row).
3734///
3735/// No selectivity model exists yet, so this is always `None`: unknown means
3736/// the consumer keeps the input estimate. A future model can fill this from
3737/// pushed comparisons or a runtime sample; it must never return a
3738/// fabricated "-1 row" placeholder.
3739///
3740/// Row-count consumers apply it through [`apply_filter_selectivity`].
3741/// [`join_key_domain_for_node`] cannot use a global factor (it does not say
3742/// which keys survive); when a factor is present it clamps the inner domain
3743/// to the filtered output rows instead.
3744fn filter_selectivity_milli(
3745    _early: Option<&Expression>,
3746    _residual: Option<&Expression>,
3747    _exists: &[ExistsClause],
3748) -> Option<u64> {
3749    None
3750}
3751
3752/// Apply [`filter_selectivity_milli`] to a FILTER's input row estimate.
3753/// `None` (unknown) leaves the input unchanged; a future factor scales it
3754/// down and floors at one row (the planner's degenerate-arm convention).
3755fn apply_filter_selectivity(
3756    rows: u64,
3757    early: Option<&Expression>,
3758    residual: Option<&Expression>,
3759    exists: &[ExistsClause],
3760) -> u64 {
3761    let rows = rows.max(1);
3762    filter_selectivity_milli(early, residual, exists).map_or(rows, |selectivity| {
3763        let scaled = u128::from(rows).saturating_mul(u128::from(selectivity)) / 1000;
3764        u64::try_from(scaled).unwrap_or(rows).clamp(1, rows)
3765    })
3766}
3767
3768/// Bound a FILTER's surviving distinct-key domain by its output row count.
3769///
3770/// A global selectivity factor cannot say which keys survive, but the output
3771/// rows are an upper bound on the surviving distinct keys. `None` is not a
3772/// factor: callers must not clamp on an absent model, because the inner row
3773/// cell may be a push clamp the domain walk is deliberately seeing through.
3774fn filter_domain_bound(inner_domain: u64, inner_rows: u64, selectivity: u64) -> u64 {
3775    let output = u128::from(inner_rows.max(1)).saturating_mul(u128::from(selectivity)) / 1000;
3776    let output = u64::try_from(output).unwrap_or(inner_rows).max(1);
3777    inner_domain.min(output)
3778}
3779
3780impl PlanNode {
3781    /// Driver-bound row estimate for the coverage policies:
3782    /// a Join's [`JoinMeta::own_push_removed_row_count_estimate`], or a
3783    /// Scan's `produced_row_count_estimate` cell (the only scan-local number
3784    /// available; it may itself be clamped by a join or ancestor push).
3785    ///
3786    /// This is an **upper bound** input, not a strict frame read: a larger
3787    /// driver estimate makes `coverage_drop_allowed`'s single-chunk case
3788    /// less likely, which is the conservative direction. `None` = no
3789    /// estimate basis (a subtree with no join-meta estimate), and the policy
3790    /// then admits only the memo-sized arm.
3791    pub(crate) fn own_push_removed_row_count_estimate(&self) -> Option<u64> {
3792        match self {
3793            Self::Scan(scan) => Some(scan.produced_row_count_estimate),
3794            Self::Join { meta, .. } => Some(meta.own_push_removed_row_count_estimate),
3795            _ => None,
3796        }
3797    }
3798
3799    /// Columns this subtree produces. This is the *structural* variable list
3800    /// (Scan slot names, path ends, VALUES columns, group outputs) — computed
3801    /// bottom-up WITHOUT consulting liveness marks, so it is safe to call
3802    /// during the liveness walk itself (unlike [`Self::variables`], which
3803    /// filters by `is_live` and would read the marks being rewritten).
3804    pub fn inner_variables(&self) -> Vec<Variable> {
3805        match self {
3806            Self::Scan(scan) => scan.slot_variables(),
3807            Self::Path(path) => path.variables(),
3808            Self::Join { left, right, .. }
3809            | Self::LeftJoin { left, right, .. }
3810            | Self::Union { left, right } => {
3811                let mut out = left.inner_variables();
3812                for variable in right.inner_variables() {
3813                    if !out.contains(&variable) {
3814                        out.push(variable);
3815                    }
3816                }
3817                out
3818            }
3819            Self::CustomNode(op) => {
3820                let mut out = op.variables.clone();
3821                for child in &op.children {
3822                    for variable in child.inner_variables() {
3823                        if !out.contains(&variable) {
3824                            out.push(variable);
3825                        }
3826                    }
3827                }
3828                out
3829            }
3830            Self::Filter { inner, .. } | Self::Extend { inner, .. } => inner.inner_variables(),
3831            Self::JoinGraphVar {
3832                inner,
3833                graph_var,
3834                active_var,
3835            } => {
3836                let mut out = inner.inner_variables();
3837                out.retain(|v| v != active_var);
3838                if !out.contains(graph_var) {
3839                    out.push(graph_var.clone());
3840                }
3841                out
3842            }
3843            Self::Unit | Self::NamedGraphExists { .. } => Vec::new(),
3844            Self::Values(values) => values.output_vars().all(),
3845            Self::NamedGraphs { variable, .. } => vec![variable.clone()],
3846            Self::Slice { inner, .. } | Self::Distinct { inner, .. } | Self::Sort { inner, .. } => {
3847                inner.inner_variables()
3848            }
3849            Self::Group {
3850                inner,
3851                variables,
3852                aggregates,
3853                ..
3854            } => {
3855                let mut out = inner.inner_variables();
3856                for variable in variables {
3857                    if !out.contains(variable) {
3858                        out.push(variable.clone());
3859                    }
3860                }
3861                for (result, agg) in aggregates {
3862                    if let AggregateExpression::FunctionCall { expr, .. } = agg {
3863                        for variable in crate::expr::variables_in_expression(expr) {
3864                            if !out.contains(&variable) {
3865                                out.push(variable);
3866                            }
3867                        }
3868                    }
3869                    if !out.contains(result) {
3870                        out.push(result.clone());
3871                    }
3872                }
3873                out
3874            }
3875            // Schema is the constraint variable (when the count has two keys),
3876            // then the head, then the count alias — not GROUP BY text order.
3877            Self::DomainCounts {
3878                constraint_var,
3879                head,
3880                count,
3881                ..
3882            } => domain_counts_schema_vars(constraint_var, head, count),
3883            Self::HeadCounts {
3884                counted: _,
3885                group,
3886                count,
3887                ..
3888            } => head_counts_schema_vars(group, count),
3889            Self::PatternCount { count, .. } => vec![count.clone()],
3890            Self::SubSelect(sub) => sub.inner.inner_variables(),
3891        }
3892    }
3893
3894    /// Boundness of variables produced by this subtree.
3895    pub fn output_vars(&self) -> OutputVars {
3896        match self {
3897            Self::Scan(scan) => OutputVars {
3898                always_bound: scan.variables(),
3899                maybe_unbound: Vec::new(),
3900            },
3901            Self::Path(path) => OutputVars {
3902                always_bound: path.variables(),
3903                maybe_unbound: Vec::new(),
3904            },
3905            // A plugin op binds its declared outputs on every emitted row
3906            // (geo_scan emits only surviving ?g terms). With children the
3907            // schema is the op's variables joined with the children's.
3908            Self::CustomNode(op) if op.children.is_empty() => OutputVars {
3909                always_bound: op.variables.clone(),
3910                maybe_unbound: Vec::new(),
3911            },
3912            Self::CustomNode(op) => {
3913                let mut vars = OutputVars {
3914                    always_bound: op.variables.clone(),
3915                    maybe_unbound: Vec::new(),
3916                };
3917                for child in &op.children {
3918                    vars = join_output_vars(&vars, &child.output_vars());
3919                }
3920                vars
3921            }
3922            Self::Join { left, right, .. } => {
3923                join_output_vars(&left.output_vars(), &right.output_vars())
3924            }
3925            Self::LeftJoin { left, right, .. } => {
3926                left_join_output_vars(&left.output_vars(), &right.output_vars())
3927            }
3928            Self::Filter { inner, .. } => inner.output_vars(),
3929            Self::JoinGraphVar {
3930                inner,
3931                graph_var,
3932                active_var,
3933            } => join_graph_var_output_vars(&inner.output_vars(), graph_var, active_var),
3934            Self::Union { left, right } => {
3935                union_output_vars(&left.output_vars(), &right.output_vars())
3936            }
3937            Self::Unit | Self::NamedGraphExists { .. } => OutputVars::default(),
3938            Self::Values(values) => values.output_vars(),
3939            Self::NamedGraphs { variable, .. } => OutputVars {
3940                always_bound: vec![variable.clone()],
3941                maybe_unbound: Vec::new(),
3942            },
3943            // Every emitted row binds the head, the count, and — for a
3944            // two-key count — the constraint variable. Same order as
3945            // [`domain_counts_schema_vars`].
3946            Self::DomainCounts {
3947                constraint_var,
3948                head,
3949                count,
3950                ..
3951            } => OutputVars {
3952                always_bound: domain_counts_schema_vars(constraint_var, head, count),
3953                maybe_unbound: Vec::new(),
3954            },
3955            Self::HeadCounts {
3956                counted: _,
3957                group,
3958                count,
3959                ..
3960            } => OutputVars {
3961                always_bound: head_counts_schema_vars(group, count),
3962                maybe_unbound: Vec::new(),
3963            },
3964            Self::PatternCount { count, .. } => OutputVars {
3965                always_bound: vec![count.clone()],
3966                maybe_unbound: Vec::new(),
3967            },
3968            Self::Extend {
3969                inner,
3970                variable,
3971                expression,
3972                ..
3973            } => {
3974                let mut out = inner.output_vars();
3975                if extend_var_always_bound(&out, expression) {
3976                    if !out.always_bound.contains(variable) {
3977                        out.always_bound.push(variable.clone());
3978                    }
3979                    out.maybe_unbound.retain(|v| v != variable);
3980                } else if !out.contains(variable) {
3981                    out.maybe_unbound.push(variable.clone());
3982                }
3983                out
3984            }
3985            Self::Slice { inner, .. } | Self::Distinct { inner, .. } | Self::Sort { inner, .. } => {
3986                inner.output_vars()
3987            }
3988            Self::Group {
3989                inner,
3990                variables,
3991                aggregates,
3992                ..
3993            } => group_output_vars(&inner.output_vars(), variables, aggregates),
3994            Self::SubSelect(sub) => {
3995                // Only the SELECT list crosses the boundary. A projected name
3996                // stays always-bound iff the subquery body always binds it
3997                // (`SELECT ?x WHERE { OPTIONAL { ... } }` projects unbound ?x).
3998                let inner_out = sub.inner.output_vars();
3999                let mut always_bound = Vec::new();
4000                let mut maybe_unbound = Vec::new();
4001                for variable in &sub.variables {
4002                    if inner_out.is_always_bound(variable) {
4003                        always_bound.push(variable.clone());
4004                    } else {
4005                        maybe_unbound.push(variable.clone());
4006                    }
4007                }
4008                OutputVars {
4009                    always_bound,
4010                    maybe_unbound,
4011                }
4012            }
4013        }
4014    }
4015
4016    /// Variables produced by this subtree (always-bound first, then maybe-unbound).
4017    pub fn variables(&self) -> Vec<Variable> {
4018        self.output_vars().all()
4019    }
4020
4021    /// Estimated cardinality for costing (best-effort).
4022    pub fn produced_row_count_estimate(&self) -> u64 {
4023        match self {
4024            Self::Scan(scan) => scan.produced_row_count_estimate,
4025            Self::Path(path) => path.produced_row_count_estimate,
4026            Self::Join { meta, .. } => meta.produced_row_count_estimate,
4027            Self::LeftJoin { meta, .. } => meta.produced_row_count_estimate.max(1),
4028            Self::Filter {
4029                inner,
4030                early,
4031                residual,
4032                exists,
4033                ..
4034            } => apply_filter_selectivity(
4035                inner.produced_row_count_estimate().max(1),
4036                early.as_ref(),
4037                residual.as_ref(),
4038                exists,
4039            ),
4040            Self::Union { left, right } => left
4041                .produced_row_count_estimate()
4042                .saturating_add(right.produced_row_count_estimate())
4043                .max(1),
4044            Self::CustomNode(op) => op.produced_row_count_estimate,
4045            Self::Unit | Self::NamedGraphExists { .. } => 1,
4046            Self::Values(values) => values.produced_row_count_estimate(),
4047            Self::NamedGraphs {
4048                produced_row_count_estimate,
4049                ..
4050            } => *produced_row_count_estimate,
4051            Self::DomainCounts {
4052                produced_row_count_estimate,
4053                ..
4054            } => *produced_row_count_estimate,
4055            Self::HeadCounts {
4056                produced_row_count_estimate,
4057                ..
4058            } => *produced_row_count_estimate,
4059            Self::PatternCount {
4060                produced_row_count_estimate,
4061                ..
4062            } => *produced_row_count_estimate,
4063            Self::JoinGraphVar { inner, .. }
4064            | Self::Extend { inner, .. }
4065            | Self::Distinct { inner, .. }
4066            | Self::Sort { inner, .. } => inner.produced_row_count_estimate(),
4067            Self::Slice {
4068                inner,
4069                start,
4070                length,
4071            } => {
4072                let after_offset = inner.produced_row_count_estimate().saturating_sub(*start);
4073                match length {
4074                    Some(n) => after_offset.min(*n),
4075                    None => after_offset,
4076                }
4077            }
4078            Self::Group {
4079                inner, variables, ..
4080            } => {
4081                if variables.is_empty() {
4082                    1
4083                } else {
4084                    inner.produced_row_count_estimate().max(1)
4085                }
4086            }
4087            Self::SubSelect(sub) => sub.produced_row_count_estimate(),
4088        }
4089    }
4090
4091    /// If this node is a single scan, return it.
4092    pub fn as_scan(&self) -> Option<&ScanOp> {
4093        match self {
4094            Self::Scan(scan) => Some(scan),
4095            _ => None,
4096        }
4097    }
4098
4099    /// Mutable [`Self::as_scan`] — the fetch-once stamp pass writes
4100    /// `ScanOp::fetch_once` through this (its sole writer).
4101    pub fn as_scan_mut(&mut self) -> Option<&mut ScanOp> {
4102        match self {
4103            Self::Scan(scan) => Some(scan),
4104            _ => None,
4105        }
4106    }
4107
4108    /// Scan under a chain of `FILTER` / `BIND` wrappers (inner-join Broadcast).
4109    pub fn as_broadcast_scan(&self) -> Option<&ScanOp> {
4110        match self {
4111            Self::Scan(scan) => Some(scan),
4112            Self::Filter { inner, .. } | Self::Extend { inner, .. } => inner.as_broadcast_scan(),
4113            _ => None,
4114        }
4115    }
4116
4117    /// Union under a chain of `FILTER` / `BIND` wrappers (scan↔Union driver swap).
4118    pub fn as_union(&self) -> Option<&PlanNode> {
4119        match self {
4120            Self::Union { .. } => Some(self),
4121            Self::Filter { inner, .. } | Self::Extend { inner, .. } => inner.as_union(),
4122            _ => None,
4123        }
4124    }
4125
4126    /// If this node is a single property path, return it.
4127    pub fn as_path(&self) -> Option<&PathOp> {
4128        match self {
4129            Self::Path(path) => Some(path),
4130            _ => None,
4131        }
4132    }
4133
4134    /// Path under a chain of `FILTER` / `BIND` wrappers (dependent Broadcast).
4135    pub fn as_dependent_path(&self) -> Option<&PathOp> {
4136        match self {
4137            Self::Path(path) => Some(path),
4138            Self::Filter { inner, .. } | Self::Extend { inner, .. } => inner.as_dependent_path(),
4139            _ => None,
4140        }
4141    }
4142
4143    /// Path under BIND (`Extend`) only — not `FILTER`.
4144    ///
4145    /// Slice may push `OFFSET+LIMIT` through BIND (1:1). FILTER can reject
4146    /// rows, so it must not use this helper.
4147    pub fn as_extend_path(&self) -> Option<&PathOp> {
4148        match self {
4149            Self::Path(path) => Some(path),
4150            Self::Extend { inner, .. } => inner.as_extend_path(),
4151            _ => None,
4152        }
4153    }
4154
4155    /// If this node is a nested `SELECT` boundary, return it.
4156    pub fn as_subselect(&self) -> Option<&SubSelectOp> {
4157        match self {
4158            Self::SubSelect(sub) => Some(sub),
4159            _ => None,
4160        }
4161    }
4162}
4163
4164/// A `SELECT` reduced to a plan tree and a projection list.
4165#[derive(Debug, Clone, PartialEq)]
4166pub struct LogicalPlan {
4167    /// Root of the physical plan tree.
4168    pub root: PlanNode,
4169    /// Variables the query projects, in `SELECT` order.
4170    pub projection: Vec<Variable>,
4171    /// Set when planning deleted at least one `FILTER` conjunct because a
4172    /// scan's exact comparison decides it
4173    /// (`waratah_compute::scan_comparisons::derive_scan_comparisons`).
4174    ///
4175    /// Such a plan is only complete while the eager scan filter runs: the
4176    /// conjunct left the tree, so its only remaining record is the scan's
4177    /// `eager` list. Executing it with the filter switched off would return
4178    /// rows the deleted `FILTER` would have rejected, so execution entry
4179    /// refuses the pairing (`QueryEngine::execute_with_cache`). Read it
4180    /// through [`LogicalPlan::depends_on_eager_scan_filter`]. Private: the
4181    /// only writer is the planner pass that performs the removal.
4182    exact_filter_removed: bool,
4183}
4184
4185/// Install plan-carried const seeds into every mint-capable node of the
4186/// finished plan tree. `Extend` expressions and `Group` aggregate
4187/// arguments are the two surfaces whose encoded-path mints escape into
4188/// result columns (Values and the ground arm seed themselves; no other
4189/// node mints escapable terms). Runs AFTER all planning rewrites — last
4190/// thing before the plan is returned — so every expression it sees is in
4191/// final form: whatever constants the executor will evaluate are exactly
4192/// the constants this walk collects. Recursion mirrors
4193/// [`collect_subtree_variables`], whose coverage discipline this walk
4194/// shares: a new node type adds its arm here exactly as there.
4195fn attach_const_seeds(node: &mut PlanNode) {
4196    match node {
4197        PlanNode::Extend {
4198            expression,
4199            const_strings,
4200            const_blobs,
4201            inner,
4202            ..
4203        } => {
4204            collect_expression_const_seeds(expression, const_strings, const_blobs);
4205            attach_const_seeds(inner);
4206        }
4207        PlanNode::Group {
4208            aggregates,
4209            const_strings,
4210            const_blobs,
4211            inner,
4212            ..
4213        } => {
4214            for (_, agg) in aggregates {
4215                match agg {
4216                    AggregateExpression::FunctionCall { expr, .. } => {
4217                        collect_expression_const_seeds(expr, const_strings, const_blobs);
4218                    }
4219                    // Exhaustive on purpose: a future AggregateExpression
4220                    // variant carrying an argument expression must add its
4221                    // arm here, or its constants are silently unseeded —
4222                    // the exact failure mode this change exists to remove.
4223                    AggregateExpression::CountSolutions { .. } => {}
4224                }
4225            }
4226            attach_const_seeds(inner);
4227        }
4228        PlanNode::Filter { inner, exists, .. } => {
4229            for clause in exists {
4230                attach_const_seeds(&mut clause.body);
4231            }
4232            attach_const_seeds(inner);
4233        }
4234        PlanNode::Join { left, right, .. }
4235        | PlanNode::LeftJoin { left, right, .. }
4236        | PlanNode::Union { left, right } => {
4237            attach_const_seeds(left);
4238            attach_const_seeds(right);
4239        }
4240        PlanNode::SubSelect(sub) => attach_const_seeds(&mut sub.inner),
4241        PlanNode::JoinGraphVar { inner, .. }
4242        | PlanNode::Slice { inner, .. }
4243        | PlanNode::Distinct { inner, .. }
4244        | PlanNode::Sort { inner, .. } => attach_const_seeds(inner),
4245        // `CustomOp.children` is the documented wrap-a-subtree extension
4246        // point, and the executor runs Extends under custom children (the
4247        // executor plugins' own rewrites already handle that shape), so
4248        // the walk must descend like every sibling pass: a skipped
4249        // child's consts would mint with empty seed lists and fail the
4250        // result decode.
4251        PlanNode::CustomNode(op) => {
4252            for child in &mut op.children {
4253                attach_const_seeds(child);
4254            }
4255        }
4256        PlanNode::Scan(_)
4257        | PlanNode::Path(_)
4258        | PlanNode::Values(_)
4259        | PlanNode::Unit
4260        | PlanNode::NamedGraphs { .. }
4261        | PlanNode::NamedGraphExists { .. }
4262        | PlanNode::DomainCounts { .. }
4263        | PlanNode::HeadCounts { .. }
4264        | PlanNode::PatternCount { .. } => {}
4265    }
4266}
4267
4268/// Every constant position of `expression`, as cache seed entries, pushed
4269/// hash-deduped into the node's seed lists. Nested positions are
4270/// collected — COALESCE fallbacks, IF branches, function arguments —
4271/// anywhere the encoded evaluator can mint from expression text.
4272/// Filter-position constants are collected too when the caller asks
4273/// (the walk only calls this for Extend/Group today): they never escape
4274/// into a column, so they carry no correctness obligation here.
4275fn collect_expression_const_seeds(
4276    expression: &Expression,
4277    strings: &mut Vec<(StrHash, String)>,
4278    blobs: &mut Vec<(StrHash, Vec<u8>)>,
4279) {
4280    match expression {
4281        Expression::NamedNode(node) => {
4282            push_seed_entries_for(&Term::NamedNode(node.clone()), strings, blobs);
4283        }
4284        Expression::Literal(literal) => {
4285            push_seed_entries_for(&Term::Literal(literal.clone()), strings, blobs);
4286        }
4287        Expression::Variable(_) | Expression::Bound(_) | Expression::Exists(_) => {}
4288        Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
4289            collect_expression_const_seeds(inner, strings, blobs);
4290        }
4291        Expression::And(a, b)
4292        | Expression::Or(a, b)
4293        | Expression::SameTerm(a, b)
4294        | Expression::Equal(a, b)
4295        | Expression::Greater(a, b)
4296        | Expression::GreaterOrEqual(a, b)
4297        | Expression::Less(a, b)
4298        | Expression::LessOrEqual(a, b)
4299        | Expression::Add(a, b)
4300        | Expression::Subtract(a, b)
4301        | Expression::Multiply(a, b)
4302        | Expression::Divide(a, b) => {
4303            collect_expression_const_seeds(a, strings, blobs);
4304            collect_expression_const_seeds(b, strings, blobs);
4305        }
4306        Expression::FunctionCall(_, args) => {
4307            for arg in args {
4308                collect_expression_const_seeds(arg, strings, blobs);
4309            }
4310        }
4311        Expression::If(a, b, c) => {
4312            collect_expression_const_seeds(a, strings, blobs);
4313            collect_expression_const_seeds(b, strings, blobs);
4314            collect_expression_const_seeds(c, strings, blobs);
4315        }
4316        Expression::Coalesce(args) => {
4317            for arg in args {
4318                collect_expression_const_seeds(arg, strings, blobs);
4319            }
4320        }
4321        Expression::In(left, args) => {
4322            collect_expression_const_seeds(left, strings, blobs);
4323            for arg in args {
4324                collect_expression_const_seeds(arg, strings, blobs);
4325            }
4326        }
4327    }
4328}
4329
4330/// Mint one constant and append its seed entries, hash-deduped — the
4331/// collector's arm for every ground term shape, so no arm can forget the
4332/// one-encode-path rule or the seeding predicate's geo arm. The lists are
4333/// query-sized (a handful of constants), so the linear scan is the right
4334/// dedup shape.
4335fn push_seed_entries_for(
4336    term: &Term,
4337    strings: &mut Vec<(StrHash, String)>,
4338    blobs: &mut Vec<(StrHash, Vec<u8>)>,
4339) {
4340    let (_, (new_strings, new_blobs)) = crate::query::caches::mint_const_entries(term);
4341    for (hash, raw) in new_strings {
4342        if !strings.iter().any(|(existing, _)| *existing == hash) {
4343            strings.push((hash, raw));
4344        }
4345    }
4346    for (hash, payload) in new_blobs {
4347        if !blobs.iter().any(|(existing, _)| *existing == hash) {
4348            blobs.push((hash, payload));
4349        }
4350    }
4351}
4352
4353impl LogicalPlan {
4354    /// Build a plan around a hand-built root for executor tests that need a
4355    /// shape the planner will not produce on demand (a forced strategy or a
4356    /// fixed orientation). The eager-filter flag starts false: a hand-built
4357    /// tree has no deleted conjuncts.
4358    #[cfg(test)]
4359    pub(crate) fn from_root_for_test(root: PlanNode, projection: Vec<Variable>) -> Self {
4360        Self {
4361            root,
4362            projection,
4363            exact_filter_removed: false,
4364        }
4365    }
4366
4367    /// Parse and plan a SPARQL `SELECT` query without a stats profile.
4368    pub fn parse(sparql: &str) -> Result<Self, ComputeError> {
4369        Self::parse_with_profile(sparql, None)
4370    }
4371
4372    /// Parse and plan with a caller-supplied query context (the plugin
4373    /// rewrite hooks see it — index epochs, rolled-up histogram). The
4374    /// dataset still resolves from the query text's `FROM` clauses.
4375    pub fn parse_with_context(sparql: &str, ctx: &QueryContext) -> Result<Self, ComputeError> {
4376        let parse_started = std::time::Instant::now();
4377        let query = crate::rephrase_error::parse_query(sparql)?;
4378        let Query::Select {
4379            pattern, dataset, ..
4380        } = query
4381        else {
4382            return Err(ComputeError::UnsupportedSparql(
4383                "only SELECT queries are supported".into(),
4384            ));
4385        };
4386        let ctx =
4387            ctx.clone()
4388                .with_dataset(QueryDataset::resolve(&[], &[], dataset.as_ref(), false)?);
4389        let (variables, optimized, slice, distinct, order) =
4390            prepare_algebra(pattern, ctx.eval_env())?;
4391        PLANNER_PARSE_US.with(|cell| cell.set(parse_started.elapsed().as_micros() as u64));
4392        Self::from_prepared(variables, optimized, slice, distinct, order, None, &ctx)
4393    }
4394
4395    /// Parse and plan, optionally reordering from a local [`StatsProfile`].
4396    pub fn parse_with_profile(
4397        sparql: &str,
4398        profile: Option<&StatsProfile>,
4399    ) -> Result<Self, ComputeError> {
4400        let parse_started = std::time::Instant::now();
4401        let query = crate::rephrase_error::parse_query(sparql)?;
4402        let Query::Select {
4403            pattern, dataset, ..
4404        } = query
4405        else {
4406            return Err(ComputeError::UnsupportedSparql(
4407                "only SELECT queries are supported".into(),
4408            ));
4409        };
4410        let ctx = QueryContext::from_snapshot(SnapshotId::latest())
4411            .with_dataset(QueryDataset::resolve(&[], &[], dataset.as_ref(), false)?);
4412        let (variables, optimized, slice, distinct, order) =
4413            prepare_algebra(pattern, ctx.eval_env())?;
4414        PLANNER_PARSE_US.with(|cell| cell.set(parse_started.elapsed().as_micros() as u64));
4415        Self::from_prepared(variables, optimized, slice, distinct, order, profile, &ctx)
4416    }
4417
4418    /// Lower a spargebra WHERE/`Project` algebra (CONSTRUCT / DESCRIBE / SELECT / ASK).
4419    ///
4420    /// `pattern` is the query body after spargebra wrapping (`Project`, optional
4421    /// outer `Slice`). Dataset clauses are taken from `ctx.dataset()`.
4422    pub fn from_algebra(
4423        pattern: GraphPattern,
4424        profile: Option<&StatsProfile>,
4425    ) -> Result<Self, ComputeError> {
4426        Self::from_algebra_with_ctx(
4427            pattern,
4428            profile,
4429            &QueryContext::from_snapshot(SnapshotId::latest()),
4430        )
4431    }
4432
4433    /// Same as [`Self::from_algebra`] with a caller-supplied query context.
4434    pub(crate) fn from_algebra_with_ctx(
4435        pattern: GraphPattern,
4436        profile: Option<&StatsProfile>,
4437        ctx: &QueryContext,
4438    ) -> Result<Self, ComputeError> {
4439        let parse_started = std::time::Instant::now();
4440        let (variables, optimized, slice, distinct, order) =
4441            prepare_algebra(pattern, ctx.eval_env())?;
4442        PLANNER_PARSE_US.with(|cell| cell.set(parse_started.elapsed().as_micros() as u64));
4443        Self::from_prepared(variables, optimized, slice, distinct, order, profile, ctx)
4444    }
4445
4446    /// Lower a SPARQL `ASK` graph pattern: cap the outer slice at `LIMIT 1`.
4447    ///
4448    /// `ASK { SELECT ... }` is a SubSelect under ASK's implicit `SELECT *`.
4449    /// Extra top-level `Project` nodes are peeled so the inner query is the
4450    /// ASK body. Nested `SELECT` in a `SELECT` WHERE is unchanged.
4451    pub fn from_ask_algebra(
4452        pattern: GraphPattern,
4453        profile: Option<&StatsProfile>,
4454    ) -> Result<Self, ComputeError> {
4455        Self::from_ask_algebra_with_ctx(
4456            pattern,
4457            profile,
4458            &QueryContext::from_snapshot(SnapshotId::latest()),
4459        )
4460    }
4461
4462    /// Same as [`Self::from_ask_algebra`] with a caller-supplied query context.
4463    pub(crate) fn from_ask_algebra_with_ctx(
4464        pattern: GraphPattern,
4465        profile: Option<&StatsProfile>,
4466        ctx: &QueryContext,
4467    ) -> Result<Self, ComputeError> {
4468        Self::from_algebra_with_ctx(cap_ask_slice(flatten_ask_subselect(pattern)), profile, ctx)
4469    }
4470
4471    fn from_prepared(
4472        variables: Vec<Variable>,
4473        optimized: GraphPattern,
4474        slice: Option<SliceSpec>,
4475        distinct: bool,
4476        order: Vec<SortKey>,
4477        profile: Option<&StatsProfile>,
4478        ctx: &QueryContext,
4479    ) -> Result<Self, ComputeError> {
4480        let plan_started = std::time::Instant::now();
4481        clear_union_domain_cache();
4482        let pass_started = std::time::Instant::now();
4483        let mut root = lower_pattern(
4484            &optimized,
4485            profile,
4486            &IncomingBound::default(),
4487            ctx,
4488            &GraphScope::Default,
4489        )?;
4490        fold_identity_filters(&mut root, profile);
4491        classify_exists_in_plan(&mut root)?;
4492        // Plugin plan rewrites (GeoSPARQL FILTER → scan + join) run HERE:
4493        // after EXISTS classification (conjuncts are settled in
4494        // early/residual/exists) and before the reassociate pass, so the
4495        // injected Join(geo_scan, …) cluster is present when the spine
4496        // pools — and pools with it as ONE atomic operand when its op is
4497        // cost-stamped and unpinned (an unpriced or pinned cluster keeps
4498        // the whole spine frozen).
4499        for plugin in crate::plugin::process_plugins().planner_plugins() {
4500            plugin.rewrite(&mut root, ctx)?;
4501        }
4502        let lower_us = pass_started.elapsed().as_micros() as u64;
4503        let pass_started = std::time::Instant::now();
4504        // Cost-based reassociation of flat inner-join chains: after identity
4505        // folding (grounds are already in the scans, so the association pass prices the
4506        // real prefix reads without any pin machinery) and the plugin
4507        // rewrites, before the first restamp_broadcast_marks — nothing is
4508        // claimed yet, so the rebuild clears nothing and the boundary restamp
4509        // re-derives marks for the final shape. filter-split BGP pools are
4510        // whole again here: a saturated identity filter node is gone, so its
4511        // scans share one spine.
4512        reassociate_inner_joins(&mut root, profile, Some(ctx));
4513        // Re-derive `broadcasted` marks for the reassociated tree before the
4514        // eliminate gates read them (they refuse marked scans) — construction
4515        // no longer stamps them.
4516        restamp_broadcast_marks(&mut root, profile);
4517        eliminate_head_counts_groups(&mut root, profile);
4518        eliminate_domain_counts_groups(&mut root, profile);
4519        // Ungrouped bag COUNT(*) / COUNT(?v) over a single BGP → CountPattern.
4520        // After head/domain so DISTINCT TOTAL and GROUP BY facets keep those
4521        // leaves.
4522        eliminate_pattern_count_groups(&mut root);
4523        // After the eliminates: the count rewrites CONSUME the Group/HAVING
4524        // shape, and `DomainCounts.iri_only` only exists once that node does
4525        // — the isIRI-on-group-key stamp lands here, still before
4526        // `annotate_liveness` (which must not clear it).
4527        crate::iri_facts::derive_iri_facts(&mut root);
4528        let rewrite_us = pass_started.elapsed().as_micros() as u64;
4529        let pass_started = std::time::Instant::now();
4530        // Structural pass → re-derive marks → re-derive liveness, twice. The
4531        // second iteration re-decides strategy/swaps with the rewrite-aware
4532        // recosts and the first iteration's grounds, and the final tree always
4533        // ends with marks AND rewrite stamps derived from the final shape (the
4534        // restamp → annotate_liveness pair is atomic: rewrite stamps are invalid
4535        // between the two). Plugin-op join arms need no separate placement
4536        // pass: the ownership-aware driver reads price the geo join's arms
4537        // on the ancestor-bounded truth in every seating, so refinalize's
4538        // own swap rule re-derives the orientation on the settled
4539        // estimates. (The deleted `replan_custom_node_arms` was the
4540        // compensating pass for the pre-seam-fix poisoned input;
4541        // `ancestor_push_return_bound_flips_the_comparator_itself` pins the
4542        // comparator-only flip, and `comparator_keeps_a_pinned_op_on_the_
4543        // probe_side` pins the pin invariant.)
4544        // A top-level `ORDER BY` is peeled above the Project, so its
4545        // variables are not in `variables`. Liveness must still see them:
4546        // the `Sort` node is attached only after the walk, and a sort key
4547        // marked dead can be omitted from a cursor-free drain or dropped by
4548        // a domain/head-scan rewrite.
4549        let mut order_keys: Vec<Variable> = Vec::new();
4550        for key in &order {
4551            let mut mentions = Vec::new();
4552            collect_expression_mentions(&mut mentions, &key.expression);
4553            for (variable, _) in mentions {
4554                if !order_keys.contains(&variable) {
4555                    order_keys.push(variable);
4556                }
4557            }
4558        }
4559        for round in 0..2 {
4560            refinalize_joins(&mut root, profile, Some(ctx));
4561            restamp_broadcast_marks(&mut root, profile);
4562            // The final liveness round records the general `Semi` gate's
4563            // liveness-dependent half (payload, multiplicity, COUNT(*)) on
4564            // `JoinMeta`, where the boundary capture exists. The gate itself
4565            // runs in `stamp_semi_join_strategy`, after the specialised and
4566            // star stamps have claimed their shapes.
4567            // A root Slice runs the joins through OpenNode, which does not
4568            // consult `JoinStrategy`; the stamp pass is skipped, so no gate
4569            // record is needed (and none should ride into execution).
4570            let gate_ctx = (round == 1 && slice.is_none()).then_some(ctx);
4571            annotate_liveness(
4572                &mut root,
4573                &variables,
4574                &order_keys,
4575                distinct,
4576                profile,
4577                gate_ctx,
4578            );
4579        }
4580        let seat_us = pass_started.elapsed().as_micros() as u64;
4581        let pass_started = std::time::Instant::now();
4582        // Attach `FILTER(?v OP literal)` comparisons to the scans that bind
4583        // them, on the final tree shape (after the seating rounds, so the
4584        // stamps ride the scans the executor runs). The Filter conjunct stays
4585        // unless the comparison is exact and `ctx` allows the removal; the
4586        // return value says whether any conjunct left, which the plan carries
4587        // to execution because a removed conjunct only survives as the scan's
4588        // eager authority.
4589        let exact_filter_removed =
4590            crate::scan_comparisons::derive_scan_comparisons(&mut root, ctx.eager_scan_filter());
4591        // SPARQL: Project → Distinct → OrderBy → Slice.
4592        if distinct {
4593            root = PlanNode::Distinct {
4594                inner: Box::new(root),
4595                columns: variables.clone(),
4596            };
4597        }
4598        if !order.is_empty() {
4599            root = PlanNode::Sort {
4600                inner: Box::new(root),
4601                keys: order,
4602            };
4603        }
4604        // `sliced` captured before the wrap: the wrap moves the spec's
4605        // fields, and the flag feeds the divisor suppression below.
4606        let sliced = slice.is_some();
4607        if let Some(slice) = slice {
4608            prefer_broadcast_for_small_slice(&mut root, slice.start, slice.length);
4609            root = PlanNode::Slice {
4610                inner: Box::new(root),
4611                start: slice.start,
4612                length: slice.length,
4613            };
4614        }
4615        // Build-once stamps, after the LAST seating round AND after the
4616        // root wraps: the wraps add only nodes above the root, and the
4617        // Slice wrap's small-slice broadcast flip must land before
4618        // pricing, so the stamps price the tree the executor will
4619        // actually run. Star-shape stamps FIRST (nothing structural
4620        // follows them either), and BEFORE the fetch-once verdicts — the
4621        // verdict's fetch-concurrency divisor consumes the `star_arms`
4622        // membership (stamp/price coherence: the stamp describes the tree
4623        // the price runs on). EXPLAIN renders from it and the executor
4624        // debug-asserts agreement at its eager detect site. `sliced`
4625        // suppresses the divisor entirely: the slice cursor runs every
4626        // join per-page, so no batch fetch concurrency exists to price.
4627        stamp_star_join_shapes(&mut root);
4628        restamp_fetch_once(&mut root, profile, Some(ctx), sliced);
4629        // Build-once claims: the `SemiScan` promotion reads the fetch-once
4630        // verdict (whole read vs per-page push) rather than re-pricing it,
4631        // and the same pass then runs the general `Semi` gate on every join
4632        // the promotion and the star stamp left unclaimed.
4633        // A root Slice suppresses it: the Slice path runs through OpenNode,
4634        // which does not consult `JoinStrategy`, so a Semi stamp there would
4635        // name a road the executor never takes. The produced-row restamp runs
4636        // afterwards and keeps its hash-product upper bound.
4637        if !sliced {
4638            stamp_semi_join_strategy(&mut root, profile, sliced, Some(ctx), &[]);
4639        }
4640        // Diagnostic (stamp-written-never-consumed): count immediately
4641        // after the writer — pairs with the execute-entry count in
4642        // `execute_with_cache` to bisect where the marks disappear.
4643        ctx.log(
4644            crate::context::LogLevel::Debug,
4645            &format!(
4646                "fetch-once-stamps after restamp: {}",
4647                count_stamps_after_restamp(&root)
4648            ),
4649        );
4650        // Estimate-only, after the last restamp: the marks just re-derived
4651        // from the final shape now condition the join produced-row
4652        // estimates (finalize's in-round stamp is the own-push-removed
4653        // model — see the JoinMeta field doc). Nothing structural
4654        // follows, so the numbers this writes are the ones that land.
4655        restamp_joins_produced_row_count_estimate(&mut root, profile);
4656        let stamps_us = pass_started.elapsed().as_micros() as u64;
4657        compile_regexes_in_node(&root, ctx.eval_env());
4658        let total_us = plan_started.elapsed().as_micros() as u64;
4659        let parse_us = PLANNER_PARSE_US.with(|cell| cell.replace(0));
4660        if ctx.log_sink().enabled_at(crate::context::LogLevel::Debug) {
4661            ctx.log(
4662                crate::context::LogLevel::Debug,
4663                &format!(
4664                    "planner-time: parse={parse_us}µs lower={lower_us}µs \
4665                     rewrite={rewrite_us}µs seat={seat_us}µs stamps={stamps_us}µs \
4666                     total={total_us}µs"
4667                ),
4668            );
4669        }
4670        // Plan-carried const seeds, after the LAST structural rewrite: the
4671        // walk must see the final expression forms (the rewrites above may
4672        // rebuild Extend nodes), and the seed lists ride the nodes the
4673        // executor will actually run.
4674        attach_const_seeds(&mut root);
4675        if ctx.log_sink().enabled_at(crate::context::LogLevel::Debug) {
4676            ctx.log(
4677                crate::context::LogLevel::Debug,
4678                &format!("plan-tree:\n{}", crate::explain::format_plan_tree(&root)),
4679            );
4680        }
4681        Ok(Self {
4682            root,
4683            projection: variables,
4684            exact_filter_removed,
4685        })
4686    }
4687
4688    /// Whether planning removed exact `FILTER` conjuncts into scan eager
4689    /// comparisons. When it did, this plan's answers depend on the eager
4690    /// scan filter running, so it cannot be executed with a context that
4691    /// disables it.
4692    ///
4693    /// [`Self::parse_with_context`] plans under the caller's context: a
4694    /// context with the filter off keeps every conjunct in the plan, and the
4695    /// returned plan answers correctly under that same context.
4696    pub fn depends_on_eager_scan_filter(&self) -> bool {
4697        self.exact_filter_removed
4698    }
4699
4700    /// Left-deep BGP scan list when the plan is scans + inner joins only.
4701    pub fn scans(&self) -> Option<Vec<&ScanOp>> {
4702        let mut out = Vec::new();
4703        collect_bgp_scans(&self.root, &mut out)?;
4704        Some(out)
4705    }
4706
4707    /// Flat join edges for a left-deep BGP plan.
4708    pub fn join_ops(&self) -> Option<Vec<JoinEdge>> {
4709        let mut out = Vec::new();
4710        collect_join_edges(&self.root, &mut out)?;
4711        Some(out)
4712    }
4713}
4714
4715fn compile_regexes_in_node(node: &PlanNode, env: &crate::expr::ExprEvalEnv) {
4716    match node {
4717        PlanNode::CustomNode(op) => {
4718            for child in &op.children {
4719                compile_regexes_in_node(child, env);
4720            }
4721        }
4722        PlanNode::Filter {
4723            inner,
4724            early,
4725            residual,
4726            exists,
4727            ..
4728        } => {
4729            if let Some(expr) = early {
4730                env.precompile_from_expression(expr);
4731            }
4732            if let Some(expr) = residual {
4733                env.precompile_from_expression(expr);
4734            }
4735            compile_regexes_in_node(inner, env);
4736            for clause in exists {
4737                compile_regexes_in_node(&clause.body, env);
4738            }
4739        }
4740        PlanNode::LeftJoin {
4741            left,
4742            right,
4743            early_filter,
4744            residual_filter,
4745            ..
4746        } => {
4747            if let Some(expr) = early_filter {
4748                env.precompile_from_expression(expr);
4749            }
4750            if let Some(expr) = residual_filter {
4751                env.precompile_from_expression(expr);
4752            }
4753            compile_regexes_in_node(left, env);
4754            compile_regexes_in_node(right, env);
4755        }
4756        PlanNode::Extend {
4757            inner, expression, ..
4758        } => {
4759            env.precompile_from_expression(expression);
4760            compile_regexes_in_node(inner, env);
4761        }
4762        PlanNode::Group {
4763            inner, aggregates, ..
4764        } => {
4765            for (_, agg) in aggregates {
4766                if let spargebra::algebra::AggregateExpression::FunctionCall { expr, .. } = agg {
4767                    env.precompile_from_expression(expr);
4768                }
4769            }
4770            compile_regexes_in_node(inner, env);
4771        }
4772        PlanNode::SubSelect(sub) => compile_regexes_in_node(&sub.inner, env),
4773        PlanNode::Join { left, right, .. } | PlanNode::Union { left, right, .. } => {
4774            compile_regexes_in_node(left, env);
4775            compile_regexes_in_node(right, env);
4776        }
4777        PlanNode::Sort { inner, keys } => {
4778            for key in keys {
4779                env.precompile_from_expression(&key.expression);
4780            }
4781            compile_regexes_in_node(inner, env);
4782        }
4783        PlanNode::Slice { inner, .. }
4784        | PlanNode::Distinct { inner, .. }
4785        | PlanNode::JoinGraphVar { inner, .. } => {
4786            compile_regexes_in_node(inner, env);
4787        }
4788        PlanNode::Scan(_)
4789        | PlanNode::Path(_)
4790        | PlanNode::Values(_)
4791        | PlanNode::NamedGraphs { .. }
4792        | PlanNode::NamedGraphExists { .. }
4793        | PlanNode::DomainCounts { .. }
4794        | PlanNode::HeadCounts { .. }
4795        | PlanNode::PatternCount { .. }
4796        | PlanNode::Unit => {}
4797    }
4798}
4799
4800fn collect_bgp_scans<'a>(node: &'a PlanNode, out: &mut Vec<&'a ScanOp>) -> Option<()> {
4801    match node {
4802        PlanNode::Scan(scan) => {
4803            out.push(scan);
4804            Some(())
4805        }
4806        PlanNode::Path(_)
4807        | PlanNode::Values(_)
4808        | PlanNode::NamedGraphs { .. }
4809        | PlanNode::NamedGraphExists { .. }
4810        | PlanNode::DomainCounts { .. }
4811        | PlanNode::HeadCounts { .. }
4812        | PlanNode::PatternCount { .. }        // A CustomOp is not a BGP scan; with children it wraps them (not a
4813        // BGP either).
4814        | PlanNode::CustomNode(_)
4815        | PlanNode::Unit => Some(()),
4816        PlanNode::Join { left, right, .. } => {
4817            collect_bgp_scans(left, out)?;
4818            collect_bgp_scans(right, out)
4819        }
4820        PlanNode::Slice { inner, .. }
4821        | PlanNode::Distinct { inner, .. }
4822        | PlanNode::Sort { inner, .. }
4823        | PlanNode::Group { inner, .. }
4824        | PlanNode::JoinGraphVar { inner, .. } => collect_bgp_scans(inner, out),
4825        PlanNode::LeftJoin { .. }
4826        | PlanNode::Filter { .. }
4827        | PlanNode::Union { .. }
4828        | PlanNode::Extend { .. }
4829        | PlanNode::SubSelect(_) => None,
4830    }
4831}
4832
4833fn collect_join_edges(node: &PlanNode, out: &mut Vec<JoinEdge>) -> Option<()> {
4834    match node {
4835        PlanNode::Scan(_)
4836        | PlanNode::Path(_)
4837        | PlanNode::Values(_)
4838        | PlanNode::NamedGraphs { .. }
4839        | PlanNode::NamedGraphExists { .. }
4840        | PlanNode::DomainCounts { .. }
4841        | PlanNode::HeadCounts { .. }
4842        | PlanNode::PatternCount { .. }
4843        | PlanNode::CustomNode(_)
4844        | PlanNode::Unit => Some(()),
4845        PlanNode::Join {
4846            left,
4847            right,
4848            hash_keys,
4849            probe_key_domains: _,
4850            probe_key_overlap_milli: _,
4851            rhs_hostable_keys: _,
4852            meta,
4853        } => {
4854            collect_join_edges(left, out)?;
4855            match right.as_ref() {
4856                PlanNode::Scan(_)
4857                | PlanNode::Path(_)
4858                | PlanNode::Values(_)
4859                | PlanNode::NamedGraphs { .. }
4860                | PlanNode::NamedGraphExists { .. }
4861                | PlanNode::Unit => {}
4862                _ => {
4863                    collect_join_edges(right, out)?;
4864                }
4865            }
4866            out.push(JoinEdge {
4867                hash_keys: hash_keys.clone(),
4868                meta: *meta,
4869            });
4870            Some(())
4871        }
4872        PlanNode::Slice { inner, .. }
4873        | PlanNode::Distinct { inner, .. }
4874        | PlanNode::Sort { inner, .. }
4875        | PlanNode::Group { inner, .. }
4876        | PlanNode::JoinGraphVar { inner, .. } => collect_join_edges(inner, out),
4877        PlanNode::LeftJoin { .. }
4878        | PlanNode::Filter { .. }
4879        | PlanNode::Union { .. }
4880        | PlanNode::Extend { .. }
4881        | PlanNode::SubSelect(_) => None,
4882    }
4883}
4884
4885/// SPARQL `LIMIT` / `OFFSET` peeled from the algebra before lowering.
4886pub(crate) struct SliceSpec {
4887    pub(crate) start: u64,
4888    pub(crate) length: Option<u64>,
4889}
4890
4891/// `ASK { SELECT ... }` wraps a SubSelect in ASK's implicit `SELECT *`.
4892/// Peel one inner `Project`; keep the outer projection for [`prepare_algebra`].
4893/// Nested `SELECT` in a `SELECT` WHERE is unchanged.
4894pub(crate) fn flatten_ask_subselect(pattern: GraphPattern) -> GraphPattern {
4895    match pattern {
4896        GraphPattern::Slice {
4897            inner,
4898            start,
4899            length,
4900        } => GraphPattern::Slice {
4901            inner: Box::new(flatten_ask_subselect(*inner)),
4902            start,
4903            length,
4904        },
4905        GraphPattern::Distinct { inner } => GraphPattern::Distinct {
4906            inner: Box::new(flatten_ask_subselect(*inner)),
4907        },
4908        GraphPattern::Project { inner, variables } => match *inner {
4909            GraphPattern::Project {
4910                inner: nested_inner,
4911                ..
4912            } => GraphPattern::Project {
4913                inner: nested_inner,
4914                variables,
4915            },
4916            other => GraphPattern::Project {
4917                inner: Box::new(other),
4918                variables,
4919            },
4920        },
4921        other => other,
4922    }
4923}
4924
4925/// ASK only needs existence: keep `LIMIT 0`, otherwise cap at `LIMIT 1`.
4926pub(crate) fn cap_ask_slice(pattern: GraphPattern) -> GraphPattern {
4927    match pattern {
4928        GraphPattern::Slice {
4929            inner,
4930            start,
4931            length: Some(0),
4932        } => GraphPattern::Slice {
4933            inner,
4934            start,
4935            length: Some(0),
4936        },
4937        GraphPattern::Slice { inner, start, .. } => GraphPattern::Slice {
4938            inner,
4939            start,
4940            length: Some(1),
4941        },
4942        GraphPattern::Distinct { inner } => GraphPattern::Distinct {
4943            inner: Box::new(cap_ask_slice(*inner)),
4944        },
4945        other => GraphPattern::Slice {
4946            inner: Box::new(other),
4947            start: 0,
4948            length: Some(1),
4949        },
4950    }
4951}
4952
4953/// When OFFSET+LIMIT is a small output budget, prefer Broadcast over a full
4954/// right-side hash/shuffle build so execution can nested-loop and stop early.
4955fn prefer_broadcast_for_small_slice(root: &mut PlanNode, start: u64, length: Option<u64>) {
4956    let Some(n) = length else {
4957        return;
4958    };
4959    if n == 0 {
4960        return;
4961    }
4962    let budget = start.saturating_add(n);
4963    if !(1..=PUSHDOWN_TERMS_LIMIT).contains(&budget) {
4964        return;
4965    }
4966    replan_scan_joins_strat_broadcast(root);
4967}
4968
4969fn replan_scan_joins_strat_broadcast(node: &mut PlanNode) {
4970    match node {
4971        PlanNode::Join {
4972            left, right, meta, ..
4973        } => {
4974            if right.as_broadcast_scan().is_some() || right.as_dependent_path().is_some() {
4975                meta.strategy = JoinStrategy::Broadcast;
4976            }
4977            replan_scan_joins_strat_broadcast(left);
4978            replan_scan_joins_strat_broadcast(right);
4979        }
4980        PlanNode::CustomNode(op) => {
4981            for child in &mut op.children {
4982                replan_scan_joins_strat_broadcast(child);
4983            }
4984        }
4985        PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
4986            replan_scan_joins_strat_broadcast(left);
4987            replan_scan_joins_strat_broadcast(right);
4988        }
4989        PlanNode::Filter { inner, .. }
4990        | PlanNode::Extend { inner, .. }
4991        | PlanNode::Slice { inner, .. }
4992        | PlanNode::Distinct { inner, .. }
4993        | PlanNode::Sort { inner, .. }
4994        | PlanNode::Group { inner, .. }
4995        | PlanNode::JoinGraphVar { inner, .. } => replan_scan_joins_strat_broadcast(inner),
4996        // The outer Slice budget does not apply inside a subquery boundary
4997        // (its own Slices own their budgets); leave the inner joins alone.
4998        PlanNode::SubSelect(_) => {}
4999        PlanNode::Scan(_)
5000        | PlanNode::Path(_)
5001        | PlanNode::Values(_)
5002        | PlanNode::NamedGraphs { .. }
5003        | PlanNode::NamedGraphExists { .. }
5004        | PlanNode::DomainCounts { .. }
5005        | PlanNode::HeadCounts { .. }
5006        | PlanNode::PatternCount { .. }
5007        | PlanNode::Unit => {}
5008    }
5009}
5010
5011/// Reconstruct a `Project` (+ optional `Distinct` / `OrderBy` / `Slice`) after Sparopt / VALUES push.
5012pub(crate) fn wrap_project_slice(
5013    variables: Vec<Variable>,
5014    inner: GraphPattern,
5015    slice: Option<SliceSpec>,
5016    distinct: bool,
5017    order: Vec<SortKey>,
5018) -> GraphPattern {
5019    let mut pattern = GraphPattern::Project {
5020        inner: Box::new(inner),
5021        variables,
5022    };
5023    if distinct {
5024        pattern = GraphPattern::Distinct {
5025            inner: Box::new(pattern),
5026        };
5027    }
5028    if !order.is_empty() {
5029        pattern = GraphPattern::OrderBy {
5030            inner: Box::new(pattern),
5031            expression: order
5032                .into_iter()
5033                .map(|key| {
5034                    if key.descending {
5035                        OrderExpression::Desc(key.expression)
5036                    } else {
5037                        OrderExpression::Asc(key.expression)
5038                    }
5039                })
5040                .collect(),
5041        };
5042    }
5043    if let Some(slice) = slice {
5044        pattern = GraphPattern::Slice {
5045            inner: Box::new(pattern),
5046            start: slice.start as usize,
5047            length: slice.length.map(|n| n as usize),
5048        };
5049    }
5050    pattern
5051}
5052
5053/// Peel slice / distinct / order / project, reject unsupported modifiers, sparopt-rewrite `pattern`.
5054#[allow(clippy::type_complexity)]
5055pub(crate) fn prepare_algebra(
5056    pattern: GraphPattern,
5057    fold_eval: &crate::expr::ExprEvalEnv,
5058) -> Result<
5059    (
5060        Vec<Variable>,
5061        GraphPattern,
5062        Option<SliceSpec>,
5063        bool,
5064        Vec<SortKey>,
5065    ),
5066    ComputeError,
5067> {
5068    let mut pattern = pattern;
5069    let mut slice = None;
5070    let mut distinct = false;
5071    let mut order = Vec::new();
5072    loop {
5073        match pattern {
5074            GraphPattern::Slice {
5075                inner,
5076                start,
5077                length,
5078            } => {
5079                slice = Some(SliceSpec {
5080                    start: start as u64,
5081                    length: length.map(|n| n as u64),
5082                });
5083                pattern = *inner;
5084            }
5085            GraphPattern::OrderBy { inner, expression } => {
5086                order = expression
5087                    .into_iter()
5088                    .map(|oe| match oe {
5089                        OrderExpression::Asc(expression) => SortKey {
5090                            expression,
5091                            descending: false,
5092                        },
5093                        OrderExpression::Desc(expression) => SortKey {
5094                            expression,
5095                            descending: true,
5096                        },
5097                    })
5098                    .collect();
5099                pattern = *inner;
5100            }
5101            GraphPattern::Distinct { inner } => {
5102                distinct = true;
5103                pattern = *inner;
5104            }
5105            GraphPattern::Reduced { inner } => {
5106                // SPARQL 1.1 §18.2.4.1: REDUCED *permits but does not require*
5107                // duplicate elimination. Returning the un-deduped multiset is
5108                // conformant; the reducer is free to keep all rows.
5109                pattern = *inner;
5110            }
5111            other => {
5112                pattern = other;
5113                break;
5114            }
5115        }
5116    }
5117
5118    let GraphPattern::Project { inner, variables } = pattern else {
5119        return Err(ComputeError::UnsupportedSparql(format!(
5120            "unsupported query shape: {}",
5121            shape_name(&pattern)
5122        )));
5123    };
5124
5125    let optimized = {
5126        // A plugin's candidate producer must be built at most once per query.
5127        // The algebra optimizer clones a FILTER into both inputs of every
5128        // inner join that binds its variables, and into every UNION arm, so a
5129        // subject-mode text FILTER ends up once per binding site of the
5130        // subject (nine on a seven-arm dimension UNION) and each copy scans
5131        // its predicates' whole literal domain. Pin those conjuncts behind a
5132        // variable the optimizer cannot push; `restore_and_sink_conjuncts`
5133        // then reinstates each one at the lowest single point that covers its
5134        // variables.
5135        // Cost: one algebra walk to substitute, one to restore, one to strip,
5136        // plus one binding-site walk per pin. All of it is linear in a tree of
5137        // tens of nodes next to a plan that costs a few milliseconds end to
5138        // end, so nothing here is memoized.
5139        let mut pins: Vec<PinnedConjunct> = Vec::new();
5140        let pinned = if crate::plugin::process_plugins()
5141            .planner_plugins()
5142            .next()
5143            .is_some()
5144        {
5145            let pin: &dyn Fn(&Expression) -> bool = &pins_candidate_conjunct;
5146            pin_candidate_conjuncts(*inner, pin, &mut pins)
5147        } else {
5148            *inner
5149        };
5150        let pins = PinnedConjuncts::new(pins);
5151        let restored = optimize_preserving_graph(pinned);
5152        let folded = crate::expr::fold_constants(restored, fold_eval);
5153        // Alt→UNION rewrite before VALUES push so a `VALUES` join above a
5154        // simple alternation is copied into every new arm (`alt_to_union`
5155        // module doc explains the ordering).
5156        let flattened = crate::alt_to_union::flatten_alternative_paths(folded);
5157        // A top-level ORDER BY is peeled above the Project, so its expression
5158        // variables are not part of the SELECT list; a VALUES column read only
5159        // by a sort key must still survive placement.
5160        let mut visible = variables.clone();
5161        let mut order_mentions = Vec::new();
5162        for key in &order {
5163            collect_expression_mentions(&mut order_mentions, &key.expression);
5164        }
5165        for (variable, _) in order_mentions {
5166            if !visible.contains(&variable) {
5167                visible.push(variable);
5168            }
5169        }
5170        // Pinned conjuncts are hidden behind their ghosts until the restore
5171        // below. Their variables are still readers of a VALUES column, so the
5172        // placement pass must treat them as visible even though the algebra
5173        // does not name them yet.
5174        for variable in pins.variables() {
5175            if !visible.contains(&variable) {
5176                visible.push(variable);
5177            }
5178        }
5179        let with_values =
5180            push_values_into_union(place_values_at_lca_with_live(flattened, &visible));
5181        // The OPTIONAL-to-join pass reads FILTER conjuncts to decide whether an
5182        // optional's miss rows would be rejected. It must see the pinned
5183        // conjunct's real expression, not the placeholder: the four string
5184        // functions it recognises are exactly the ones the text plugin pins.
5185        let unpin = |expression: &Expression| pins.unpin(expression);
5186        let forced = crate::optional_to_join::replace_filter_forced_joins(with_values, &unpin);
5187        let grounded = push_groundings_into_subselects(forced);
5188        if pins.is_empty() {
5189            grounded
5190        } else {
5191            let mut seen = vec![0u32; pins.len()];
5192            let mut anchors = vec![0u32; pins.len()];
5193            let optimized = restore_and_sink_conjuncts(grounded, &pins, &mut seen);
5194            let optimized = strip_pin_extends(optimized, &pins, &mut anchors);
5195            check_pin_survival(&optimized, &pins, &seen, &anchors)?;
5196            optimized
5197        }
5198    };
5199    Ok((variables, optimized, slice, distinct, order))
5200}
5201
5202/// sparopt flattens `GRAPH` onto triples/paths and drops it around VALUES /
5203/// BIND / nested GRAPH (the outer `?g` is overwritten). Keep `GRAPH` nodes so
5204/// [`attach_graph_domain`] still sees scan-free and nested `GRAPH ?g`.
5205fn optimize_preserving_graph(pattern: GraphPattern) -> GraphPattern {
5206    if !pattern_contains_graph(&pattern) {
5207        return sparopt_roundtrip(pattern);
5208    }
5209    match pattern {
5210        GraphPattern::Graph { name, inner } => GraphPattern::Graph {
5211            name,
5212            inner: Box::new(optimize_preserving_graph(*inner)),
5213        },
5214        GraphPattern::Join { left, right } => GraphPattern::Join {
5215            left: Box::new(optimize_preserving_graph(*left)),
5216            right: Box::new(optimize_preserving_graph(*right)),
5217        },
5218        GraphPattern::LeftJoin {
5219            left,
5220            right,
5221            expression,
5222        } => GraphPattern::LeftJoin {
5223            left: Box::new(optimize_preserving_graph(*left)),
5224            right: Box::new(optimize_preserving_graph(*right)),
5225            expression,
5226        },
5227        GraphPattern::Union { left, right } => GraphPattern::Union {
5228            left: Box::new(optimize_preserving_graph(*left)),
5229            right: Box::new(optimize_preserving_graph(*right)),
5230        },
5231        GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
5232            expr,
5233            inner: Box::new(optimize_preserving_graph(*inner)),
5234        },
5235        GraphPattern::Extend {
5236            inner,
5237            variable,
5238            expression,
5239        } => GraphPattern::Extend {
5240            inner: Box::new(optimize_preserving_graph(*inner)),
5241            variable,
5242            expression,
5243        },
5244        GraphPattern::Minus { left, right } => GraphPattern::Minus {
5245            left: Box::new(optimize_preserving_graph(*left)),
5246            right: Box::new(optimize_preserving_graph(*right)),
5247        },
5248        GraphPattern::Slice {
5249            inner,
5250            start,
5251            length,
5252        } => GraphPattern::Slice {
5253            inner: Box::new(optimize_preserving_graph(*inner)),
5254            start,
5255            length,
5256        },
5257        GraphPattern::Group {
5258            inner,
5259            variables,
5260            aggregates,
5261        } => GraphPattern::Group {
5262            inner: Box::new(optimize_preserving_graph(*inner)),
5263            variables,
5264            aggregates,
5265        },
5266        GraphPattern::Project { inner, variables } => GraphPattern::Project {
5267            inner: Box::new(optimize_preserving_graph(*inner)),
5268            variables,
5269        },
5270        GraphPattern::Distinct { inner } => GraphPattern::Distinct {
5271            inner: Box::new(optimize_preserving_graph(*inner)),
5272        },
5273        GraphPattern::Reduced { inner } => GraphPattern::Reduced {
5274            inner: Box::new(optimize_preserving_graph(*inner)),
5275        },
5276        GraphPattern::OrderBy { inner, expression } => GraphPattern::OrderBy {
5277            inner: Box::new(optimize_preserving_graph(*inner)),
5278            expression,
5279        },
5280        GraphPattern::Service {
5281            name,
5282            inner,
5283            silent,
5284        } => GraphPattern::Service {
5285            name,
5286            inner: Box::new(optimize_preserving_graph(*inner)),
5287            silent,
5288        },
5289        other => sparopt_roundtrip(other),
5290    }
5291}
5292
5293/// One FILTER conjunct a planner plugin asked the algebra optimizer not to
5294/// duplicate, and the ghost variable that carries it across the sparopt
5295/// roundtrip.
5296struct PinnedConjunct {
5297    /// Variable substituted for the conjunct before sparopt runs. It is bound
5298    /// nowhere in the pattern, so sparopt's filter pushdown cannot move it.
5299    ghost: Variable,
5300    /// The original conjunct, reinstated after the roundtrip.
5301    expression: Expression,
5302}
5303
5304/// Whether an expression contains an `EXISTS` anywhere, including inside a
5305/// function argument or a nested expression.
5306///
5307/// A pinned conjunct is restored and re-seated by [`sink_pinned_conjunct`],
5308/// whose variable walk reads only the expression tree; the correlated names a
5309/// body reads are invisible to it. Refusing to pin such a conjunct keeps it
5310/// where the algebra optimizer left it instead of re-seating it with an
5311/// incomplete variable set.
5312fn expression_contains_exists(expression: &Expression) -> bool {
5313    match expression {
5314        Expression::Exists(_) => true,
5315        Expression::NamedNode(_)
5316        | Expression::Literal(_)
5317        | Expression::Variable(_)
5318        | Expression::Bound(_) => false,
5319        Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
5320            expression_contains_exists(inner)
5321        }
5322        Expression::And(left, right)
5323        | Expression::Or(left, right)
5324        | Expression::SameTerm(left, right)
5325        | Expression::Equal(left, right)
5326        | Expression::Greater(left, right)
5327        | Expression::GreaterOrEqual(left, right)
5328        | Expression::Less(left, right)
5329        | Expression::LessOrEqual(left, right)
5330        | Expression::Add(left, right)
5331        | Expression::Subtract(left, right)
5332        | Expression::Multiply(left, right)
5333        | Expression::Divide(left, right) => {
5334            expression_contains_exists(left) || expression_contains_exists(right)
5335        }
5336        Expression::FunctionCall(_, args) | Expression::Coalesce(args) => {
5337            args.iter().any(expression_contains_exists)
5338        }
5339        Expression::If(cond, then_branch, else_branch) => {
5340            expression_contains_exists(cond)
5341                || expression_contains_exists(then_branch)
5342                || expression_contains_exists(else_branch)
5343        }
5344        Expression::In(inner, args) => {
5345            expression_contains_exists(inner) || args.iter().any(expression_contains_exists)
5346        }
5347    }
5348}
5349
5350/// Whether any planner plugin marks `expression` as a candidate producer that
5351/// must be built at most once
5352/// ([`crate::plugin::PlannerPlugin::pins_through_optimizer`]).
5353fn pins_candidate_conjunct(expression: &Expression) -> bool {
5354    if expression_contains_exists(expression) {
5355        return false;
5356    }
5357    crate::plugin::process_plugins()
5358        .planner_plugins()
5359        .any(|plugin| plugin.pins_through_optimizer(expression))
5360}
5361
5362/// Mint the ghost variable that pins one conjunct: a fresh token per pin keeps
5363/// sibling pins apart and a name the query text cannot produce keeps a user
5364/// variable from colliding with it.
5365fn pinned_ghost_variable() -> Variable {
5366    Variable::new_unchecked(format!("__waratah_pin_{}", mint_scope_token()))
5367}
5368
5369/// The ghost variable a pinned conjunct carries: the planted `!?ghost` form, or
5370/// a bare `?ghost` if a later pass ever strips the negation.
5371fn pinned_ghost_variable_of(conjunct: &Expression) -> Option<&Variable> {
5372    match conjunct {
5373        Expression::Variable(variable) => Some(variable),
5374        Expression::Not(inner) => match inner.as_ref() {
5375            Expression::Variable(variable) => Some(variable),
5376            _ => None,
5377        },
5378        _ => None,
5379    }
5380}
5381
5382/// The pinned-conjunct table: the original expressions hidden behind their
5383/// ghost anchors, with the two read-only projections its consumers need.
5384///
5385/// While a conjunct is pinned the algebra carries only `!?ghost`, so a pass
5386/// that runs before [`restore_and_sink_conjuncts`] sees neither the real
5387/// expression nor the names it reads. [`Self::unpin`] projects a ghost back to
5388/// the expression (the OPTIONAL-to-join pass needs the shape);
5389/// [`Self::variables`] projects the expressions to their variable names (the
5390/// VALUES placement pass needs the readers). Both read this one table.
5391struct PinnedConjuncts {
5392    pins: Vec<PinnedConjunct>,
5393}
5394
5395impl PinnedConjuncts {
5396    fn new(pins: Vec<PinnedConjunct>) -> Self {
5397        Self { pins }
5398    }
5399
5400    /// The original expression behind a planted ghost, if `expression` is
5401    /// one. Does not modify the algebra; the restore is a separate pass.
5402    fn unpin(&self, expression: &Expression) -> Option<Expression> {
5403        pinned_ghost_variable_of(expression).and_then(|ghost| {
5404            self.pins
5405                .iter()
5406                .find(|pin| &pin.ghost == ghost)
5407                .map(|pin| pin.expression.clone())
5408        })
5409    }
5410
5411    /// Every variable the pinned expressions read. The ghost hides them from
5412    /// the visible tree, so a pass that decides liveness or placement before
5413    /// the restore must add these names explicitly.
5414    fn variables(&self) -> Vec<Variable> {
5415        let mut mentions = Vec::new();
5416        for pin in &self.pins {
5417            collect_expression_mentions(&mut mentions, &pin.expression);
5418        }
5419        let mut out = Vec::new();
5420        for (variable, _) in mentions {
5421            if !out.contains(&variable) {
5422                out.push(variable);
5423            }
5424        }
5425        out
5426    }
5427}
5428
5429impl std::ops::Deref for PinnedConjuncts {
5430    type Target = [PinnedConjunct];
5431
5432    fn deref(&self) -> &Self::Target {
5433        &self.pins
5434    }
5435}
5436
5437/// Substitute a ghost variable for every conjunct a planner plugin marks as a
5438/// candidate producer.
5439///
5440/// sparopt's filter pushdown clones a conjunct into both inputs of an inner
5441/// join whose sides both bind its variables, and into every UNION arm. A
5442/// `text:query` subject filter inside a seven-arm dimension UNION therefore
5443/// becomes one full candidate semi-join per binding site of the subject — nine
5444/// of them on the s32 facets shape — and each copy scans its predicates' whole
5445/// literal domain. Replacing the conjunct with `!?ghost`, a negation of a
5446/// variable bound nowhere, makes it unpushable: the optimizer leaves it at the
5447/// top of the enclosing scope, so exactly one copy survives.
5448/// [`restore_and_sink_conjuncts`] puts the real expression back and places it at
5449/// the lowest single point that covers its variables.
5450///
5451/// The negation is load-bearing in two ways. Without the anchor, a bare
5452/// `?ghost` filter is typed exactly UNDEF and the optimizer's normalization
5453/// replaces the *whole pattern* with the empty table (observed when the pin was
5454/// first written). With the anchor, the variable is typed as
5455/// possibly-undefined, so a bare filter would survive but error on every row —
5456/// an empty answer. `!?ghost` is typed as a literal, so the filter neither
5457/// errors nor collapses, which also means a lost anchor surfaces as a hard
5458/// error in [`check_pin_survival`] instead of being accepted as a provably
5459/// empty scope.
5460fn pin_candidate_conjuncts(
5461    pattern: GraphPattern,
5462    pins: &dyn Fn(&Expression) -> bool,
5463    out: &mut Vec<PinnedConjunct>,
5464) -> GraphPattern {
5465    match pattern {
5466        GraphPattern::Filter { expr, inner } => {
5467            let mut inner = pin_candidate_conjuncts(*inner, pins, out);
5468            let mut remaining = Vec::new();
5469            let mut ghosts = Vec::new();
5470            for conjunct in flatten_and(&expr) {
5471                if pins(&conjunct) {
5472                    let ghost = pinned_ghost_variable();
5473                    out.push(PinnedConjunct {
5474                        ghost: ghost.clone(),
5475                        expression: conjunct,
5476                    });
5477                    ghosts.push(ghost);
5478                } else {
5479                    remaining.push(conjunct);
5480                }
5481            }
5482            // One Extend per pin, wrapping the inner. The optimizer's filter
5483            // pushdown keeps a conjunct that reads an Extend's variable above
5484            // that Extend (a filter cannot be pushed below the BIND that
5485            // defines its variable), and an Extend is a pattern node, so the
5486            // UNION arm cloning rule cannot reach the filter through it. The
5487            // Extend is needed for that reason: a filter directly above a
5488            // UNION is cloned into every arm even when its variable is bound
5489            // nowhere. `strip_pin_extends` removes every planted Extend.
5490            for ghost in &ghosts {
5491                inner = GraphPattern::Extend {
5492                    inner: Box::new(inner),
5493                    variable: ghost.clone(),
5494                    expression: Expression::Not(Box::new(Expression::Variable(ghost.clone()))),
5495                };
5496            }
5497            for ghost in ghosts {
5498                remaining.push(Expression::Not(Box::new(Expression::Variable(ghost))));
5499            }
5500            GraphPattern::Filter {
5501                expr: and_fold(remaining).expect("a FILTER has at least one conjunct"),
5502                inner: Box::new(inner),
5503            }
5504        }
5505        other => map_algebra_children(other, &mut |child| {
5506            pin_candidate_conjuncts(child, pins, out)
5507        }),
5508    }
5509}
5510
5511/// Reinstate every pinned conjunct and sink it to the lowest single point that
5512/// covers its variables.
5513///
5514/// `seen` counts how many times each ghost survived the algebra passes; the
5515/// caller requires exactly one per pin, so an optimizer rule that prunes or
5516/// clones the placeholder fails the query loudly instead of silently dropping
5517/// a FILTER (a filter over an unbound variable errors on every row, so the
5518/// silent failure mode is an empty answer).
5519fn restore_and_sink_conjuncts(
5520    pattern: GraphPattern,
5521    pins: &[PinnedConjunct],
5522    seen: &mut [u32],
5523) -> GraphPattern {
5524    match pattern {
5525        GraphPattern::Filter { expr, inner } => {
5526            let inner = restore_and_sink_conjuncts(*inner, pins, seen);
5527            let mut remaining = Vec::new();
5528            let mut restored = Vec::new();
5529            for conjunct in flatten_and(&expr) {
5530                let index = pinned_ghost_variable_of(&conjunct)
5531                    .and_then(|ghost| pins.iter().position(|pin| &pin.ghost == ghost));
5532                match index {
5533                    Some(index) => {
5534                        seen[index] += 1;
5535                        restored.push(index);
5536                    }
5537                    None => remaining.push(conjunct),
5538                }
5539            }
5540            let mut inner = inner;
5541            for index in restored {
5542                inner = sink_pinned_conjunct(inner, pins[index].expression.clone());
5543            }
5544            match and_fold(remaining) {
5545                Some(expr) => GraphPattern::Filter {
5546                    expr,
5547                    inner: Box::new(inner),
5548                },
5549                None => inner,
5550            }
5551        }
5552        other => map_algebra_children(other, &mut |child| {
5553            restore_and_sink_conjuncts(child, pins, seen)
5554        }),
5555    }
5556}
5557
5558/// Remove every Extend layer planted by [`pin_candidate_conjuncts`], counting
5559/// each one so the caller can require exactly one removal per pin. A leftover
5560/// Extend would bind a ghost variable in the lowered plan, and its
5561/// self-referential expression would then be evaluated for a column nothing
5562/// reads.
5563fn strip_pin_extends(
5564    pattern: GraphPattern,
5565    pins: &[PinnedConjunct],
5566    stripped: &mut [u32],
5567) -> GraphPattern {
5568    match pattern {
5569        GraphPattern::Extend {
5570            inner,
5571            variable,
5572            expression,
5573        } => {
5574            if let Some(index) = pins.iter().position(|pin| pin.ghost == variable) {
5575                stripped[index] += 1;
5576                strip_pin_extends(*inner, pins, stripped)
5577            } else {
5578                GraphPattern::Extend {
5579                    inner: Box::new(strip_pin_extends(*inner, pins, stripped)),
5580                    variable,
5581                    expression,
5582                }
5583            }
5584        }
5585        other => map_algebra_children(other, &mut |child| strip_pin_extends(child, pins, stripped)),
5586    }
5587}
5588
5589/// Whether `pattern` provably produces no rows.
5590///
5591/// Sound in one direction only: `true` means no solution can survive, so a
5592/// pinned conjunct the algebra passes dropped together with its scope cannot
5593/// change the answer. `Group` without keys is the exception that keeps its one
5594/// aggregate row, and an empty `Bgp` is the unit pattern, not the empty table.
5595fn pattern_is_surely_empty(pattern: &GraphPattern) -> bool {
5596    match pattern {
5597        GraphPattern::Values { bindings, .. } => bindings.is_empty(),
5598        GraphPattern::Join { left, right } => {
5599            pattern_is_surely_empty(left) || pattern_is_surely_empty(right)
5600        }
5601        GraphPattern::Union { left, right } => {
5602            pattern_is_surely_empty(left) && pattern_is_surely_empty(right)
5603        }
5604        GraphPattern::LeftJoin { left, .. } | GraphPattern::Minus { left, .. } => {
5605            pattern_is_surely_empty(left)
5606        }
5607        GraphPattern::Filter { inner, .. }
5608        | GraphPattern::Extend { inner, .. }
5609        | GraphPattern::Project { inner, .. }
5610        | GraphPattern::Distinct { inner }
5611        | GraphPattern::Reduced { inner }
5612        | GraphPattern::OrderBy { inner, .. }
5613        | GraphPattern::Graph { inner, .. } => pattern_is_surely_empty(inner),
5614        GraphPattern::Slice { inner, length, .. } => {
5615            *length == Some(0) || pattern_is_surely_empty(inner)
5616        }
5617        // An aggregate-only group over the empty table keeps its single row.
5618        GraphPattern::Group {
5619            inner, variables, ..
5620        } => !variables.is_empty() && pattern_is_surely_empty(inner),
5621        GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Service { .. } => {
5622            false
5623        }
5624    }
5625}
5626
5627/// Require each pin to have survived the algebra passes exactly once.
5628///
5629/// The one accepted exception is a pin whose conjunct **and** anchor both
5630/// vanished inside a pattern the passes proved empty: an empty `VALUES`, a
5631/// `FILTER(false)`, or an empty group side makes the optimizer drop the whole
5632/// subtree, and the answer is empty regardless of the filter. Anything else —
5633/// one surviving copy of the conjunct, a missing anchor next to a surviving
5634/// conjunct — is a hard error, because the substitution's assumptions no
5635/// longer hold and the failure would otherwise be a silently empty answer.
5636fn check_pin_survival(
5637    optimized: &GraphPattern,
5638    pins: &[PinnedConjunct],
5639    seen: &[u32],
5640    anchors: &[u32],
5641) -> Result<(), ComputeError> {
5642    for ((pin, conjuncts), anchors) in pins.iter().zip(seen.iter()).zip(anchors.iter()) {
5643        if *conjuncts == 1 && *anchors == 1 {
5644            continue;
5645        }
5646        if *conjuncts == 0 && *anchors == 0 && pattern_is_surely_empty(optimized) {
5647            continue;
5648        }
5649        return Err(ComputeError::Internal(format!(
5650            "pinned FILTER conjunct ?{} survived the algebra optimizer as {conjuncts} filter \
5651             occurrence(s) and {anchors} anchor(s), expected exactly one of each: the pin \
5652             substitutes a negation of a variable bound nowhere, and a rule that prunes or \
5653             duplicates either form invalidates the substitution",
5654            pin.ghost.as_str()
5655        )));
5656    }
5657    Ok(())
5658}
5659
5660/// Place `expression` at the lowest single point inside `pattern` that covers
5661/// every variable it reads: the lowest common ancestor of its binding sites.
5662///
5663/// Monotone: the filter only ever moves down. No binding site (a UNION arm
5664/// that cannot produce the variable), a target at the root, or an unsafe path
5665/// all leave the filter directly above `pattern`, which is where it already is.
5666/// A filter is never lifted, because raising it can only grow the row set it
5667/// evaluates — unlike lowering it, which can shrink that set.
5668fn sink_pinned_conjunct(pattern: GraphPattern, expression: Expression) -> GraphPattern {
5669    let mut variables = variables_in_expression(&expression);
5670    variables.sort();
5671    variables.dedup();
5672    // Every variable must have a binding site the sink can see. A variable
5673    // whose only binding sits inside a container the sink refuses to enter —
5674    // a `Project` that hides it, a `Group` that does not key it, the right
5675    // side of a `Minus` — records no site, and sinking to the remaining
5676    // variables' ancestor would evaluate the predicate where it is unbound.
5677    // That errors on every row, dropping them: a semijoin cannot bring rows
5678    // back, so an unprovable target must keep the filter where it is.
5679    let mut sites = Vec::new();
5680    let mut every_variable_bound = !variables.is_empty();
5681    for variable in &variables {
5682        let before = sites.len();
5683        collect_binding_sites(
5684            &pattern,
5685            std::slice::from_ref(variable),
5686            &mut Vec::new(),
5687            &mut sites,
5688        );
5689        if sites.len() == before {
5690            every_variable_bound = false;
5691            break;
5692        }
5693    }
5694    let target = every_variable_bound
5695        .then(|| common_path_prefix(&sites))
5696        .flatten();
5697    let Some(target) = target
5698        .filter(|target| !target.is_empty() && sink_path_is_safe(&pattern, target, &variables))
5699    else {
5700        return GraphPattern::Filter {
5701            expr: expression,
5702            inner: Box::new(pattern),
5703        };
5704    };
5705    insert_filter_at(pattern, &target, expression)
5706}
5707
5708/// Collect the path of every node inside `pattern` that introduces one of
5709/// `variables`.
5710///
5711/// A site is recorded wherever the binding is visible *above* the node, even
5712/// when the sink may not enter it: `Graph` and `Service` bindings flow out to
5713/// the enclosing solution, and an `OPTIONAL`'s right side binds its variables
5714/// for matching rows. Where a container hides a binding from above — a
5715/// `Project` that does not expose a variable, a `Group` that does not key it,
5716/// the right side of a `Minus` — there is no site, and the sink's
5717/// every-variable check keeps the filter where it is.
5718fn collect_binding_sites(
5719    pattern: &GraphPattern,
5720    variables: &[Variable],
5721    path: &mut Vec<usize>,
5722    out: &mut Vec<Vec<usize>>,
5723) {
5724    match pattern {
5725        GraphPattern::Bgp { patterns } => {
5726            if patterns.iter().any(|triple| {
5727                term_pattern_binds(&triple.subject, variables)
5728                    || named_node_pattern_binds(&triple.predicate, variables)
5729                    || term_pattern_binds(&triple.object, variables)
5730            }) {
5731                out.push(path.clone());
5732            }
5733        }
5734        GraphPattern::Path {
5735            subject, object, ..
5736        } => {
5737            if term_pattern_binds(subject, variables) || term_pattern_binds(object, variables) {
5738                out.push(path.clone());
5739            }
5740        }
5741        GraphPattern::Values {
5742            variables: columns, ..
5743        } => {
5744            if columns.iter().any(|column| variables.contains(column)) {
5745                out.push(path.clone());
5746            }
5747        }
5748        GraphPattern::Extend {
5749            inner, variable, ..
5750        } => {
5751            if variables.contains(variable) {
5752                // The Extend defines the variable, so a filter cannot cross it.
5753                out.push(path.clone());
5754            } else {
5755                path.push(0);
5756                collect_binding_sites(inner, variables, path, out);
5757                path.pop();
5758            }
5759        }
5760        GraphPattern::Group {
5761            variables: keys,
5762            aggregates,
5763            ..
5764        } => {
5765            // A Group hides every variable that is not a key or an aggregate;
5766            // only the ones it exposes can carry a filter below it, and those
5767            // are bound by the Group itself.
5768            if keys.iter().any(|key| variables.contains(key))
5769                || aggregates
5770                    .iter()
5771                    .any(|(variable, _)| variables.contains(variable))
5772            {
5773                out.push(path.clone());
5774            }
5775        }
5776        GraphPattern::Project {
5777            inner,
5778            variables: projected,
5779        } => {
5780            if variables
5781                .iter()
5782                .all(|variable| projected.contains(variable))
5783            {
5784                path.push(0);
5785                collect_binding_sites(inner, variables, path, out);
5786                path.pop();
5787            }
5788        }
5789        GraphPattern::Filter { inner, .. }
5790        | GraphPattern::OrderBy { inner, .. }
5791        | GraphPattern::Distinct { inner }
5792        | GraphPattern::Reduced { inner }
5793        | GraphPattern::Slice { inner, .. } => {
5794            path.push(0);
5795            collect_binding_sites(inner, variables, path, out);
5796            path.pop();
5797        }
5798        GraphPattern::Join { left, right } | GraphPattern::Union { left, right } => {
5799            path.push(0);
5800            collect_binding_sites(left, variables, path, out);
5801            path.pop();
5802            path.push(1);
5803            collect_binding_sites(right, variables, path, out);
5804            path.pop();
5805        }
5806        // An OPTIONAL's right side binds its variables for matching rows, and
5807        // those bindings are visible above the LeftJoin — so the site exists.
5808        // The sink may not enter that side (moving a filter into it turns a
5809        // miss row's unbound value from "filter error, row dropped" into a
5810        // surviving miss row); `sink_path_is_safe` is the barrier.
5811        GraphPattern::LeftJoin { left, right, .. } => {
5812            path.push(0);
5813            collect_binding_sites(left, variables, path, out);
5814            path.pop();
5815            path.push(1);
5816            collect_binding_sites(right, variables, path, out);
5817            path.pop();
5818        }
5819        // A MINUS right side never contributes bindings to the result.
5820        GraphPattern::Minus { left, .. } => {
5821            path.push(0);
5822            collect_binding_sites(left, variables, path, out);
5823            path.pop();
5824        }
5825        // GRAPH and SERVICE bindings flow out to the enclosing solution, so
5826        // they are real sites; the sink still refuses to enter either node,
5827        // because that would change the filter's graph scope (GRAPH) or push
5828        // work into a remote call (SERVICE).
5829        GraphPattern::Graph { inner, .. } | GraphPattern::Service { inner, .. } => {
5830            path.push(0);
5831            collect_binding_sites(inner, variables, path, out);
5832            path.pop();
5833        }
5834    }
5835}
5836
5837fn term_pattern_binds(term: &TermPattern, variables: &[Variable]) -> bool {
5838    matches!(term, TermPattern::Variable(variable) if variables.contains(variable))
5839}
5840
5841fn named_node_pattern_binds(term: &NamedNodePattern, variables: &[Variable]) -> bool {
5842    matches!(term, NamedNodePattern::Variable(variable) if variables.contains(variable))
5843}
5844
5845/// The longest path prefix shared by every site — the lowest common ancestor —
5846/// or `None` when there is no site.
5847fn common_path_prefix(sites: &[Vec<usize>]) -> Option<Vec<usize>> {
5848    let first = sites.first()?;
5849    let mut prefix = Vec::new();
5850    'depth: for (depth, index) in first.iter().enumerate() {
5851        for site in &sites[1..] {
5852            if site.get(depth) != Some(index) {
5853                break 'depth;
5854            }
5855        }
5856        prefix.push(*index);
5857    }
5858    Some(prefix)
5859}
5860
5861/// Whether a filter may descend from `pattern` to `target`: never through a
5862/// `Slice` (the filter would select different rows), a `Union` (a partial
5863/// binding means the other arms' rows would escape the filter; if every arm
5864/// bound the variable, the common ancestor would be the Union itself), the
5865/// right side of a `LeftJoin` (a missed optional must keep its row with the
5866/// variable unbound, which a filter inside that side would have dropped) or of
5867/// a `Minus` (that side produces no result bindings), a `Graph` (the filter's
5868/// graph scope would change) or a `Service` (the filter would move into a
5869/// remote call), or a `Project` that does not expose every variable the filter
5870/// reads.
5871fn sink_path_is_safe(pattern: &GraphPattern, target: &[usize], variables: &[Variable]) -> bool {
5872    let mut node = pattern;
5873    for index in target {
5874        let may_cross = match node {
5875            GraphPattern::Slice { .. } | GraphPattern::Union { .. } => false,
5876            GraphPattern::Graph { .. } | GraphPattern::Service { .. } => false,
5877            GraphPattern::LeftJoin { .. } | GraphPattern::Minus { .. } => *index == 0,
5878            GraphPattern::Project {
5879                variables: projected,
5880                ..
5881            } => variables
5882                .iter()
5883                .all(|variable| projected.contains(variable)),
5884            _ => true,
5885        };
5886        if !may_cross {
5887            return false;
5888        }
5889        node = algebra_child(node, *index);
5890    }
5891    true
5892}
5893
5894/// The deepest prefix of `target` a `VALUES` join may be seated at.
5895///
5896/// A join may sit at any ancestor of its consumer sites, so a barrier is not a
5897/// reason to move the whole table back to the region root. Seat it at the
5898/// barrier instead: joining the whole barrier node keeps exactly the binding
5899/// the original top-level table gave every row, while a `UNION` at that
5900/// position can still distribute the join into each of its arms.
5901///
5902/// The barriers: a `UNION` (joining one arm only would leave the other arms
5903/// unbound), the right side of an `OPTIONAL` or `MINUS` (its miss or absent
5904/// rows keep their own binding), a `GRAPH`/`SERVICE` body, a `SLICE`, a
5905/// `DISTINCT`/`REDUCED` body, a `GROUP` body (each runs over its exact input
5906/// multiset or scope), and any `Project` sub-SELECT.
5907fn safe_join_target(pattern: &GraphPattern, target: &[usize]) -> Vec<usize> {
5908    let mut node = pattern;
5909    let mut safe = Vec::new();
5910    for index in target {
5911        let may_cross = match node {
5912            GraphPattern::Slice { .. } | GraphPattern::Union { .. } => false,
5913            GraphPattern::Graph { .. } | GraphPattern::Service { .. } => false,
5914            GraphPattern::LeftJoin { .. } | GraphPattern::Minus { .. } => *index == 0,
5915            // A DISTINCT or aggregate runs over its exact input multiset;
5916            // joining a table below it changes that multiset (and so the
5917            // distinct domain or the aggregate value).
5918            GraphPattern::Distinct { .. }
5919            | GraphPattern::Reduced { .. }
5920            | GraphPattern::Group { .. } => false,
5921            // A sub-SELECT boundary is its own modifier scope (DISTINCT,
5922            // LIMIT, GROUP). Sinking a join into it can change what those
5923            // modifiers see, so only the whole sub-SELECT is joined.
5924            GraphPattern::Project { .. } => false,
5925            _ => true,
5926        };
5927        if !may_cross {
5928            break;
5929        }
5930        safe.push(*index);
5931        node = algebra_child(node, *index);
5932    }
5933    safe
5934}
5935
5936/// Wrap the node at `target` with `Filter(expression)`. `target` is a path from
5937/// `pattern`'s root, so the empty path wraps the whole pattern.
5938fn insert_filter_at(
5939    pattern: GraphPattern,
5940    target: &[usize],
5941    expression: Expression,
5942) -> GraphPattern {
5943    let Some((&index, rest)) = target.split_first() else {
5944        return GraphPattern::Filter {
5945            expr: expression,
5946            inner: Box::new(pattern),
5947        };
5948    };
5949    replace_algebra_child(pattern, index, &mut |child| {
5950        insert_filter_at(child, rest, expression.clone())
5951    })
5952}
5953
5954/// The canonical child order: `Join` / `LeftJoin` / `Union` / `Minus` expose
5955/// left then right; every other container exposes its `inner` as child 0.
5956fn algebra_child(pattern: &GraphPattern, index: usize) -> &GraphPattern {
5957    match pattern {
5958        GraphPattern::Join { left, right }
5959        | GraphPattern::LeftJoin { left, right, .. }
5960        | GraphPattern::Union { left, right }
5961        | GraphPattern::Minus { left, right } => match index {
5962            0 => left,
5963            _ => right,
5964        },
5965        GraphPattern::Filter { inner, .. }
5966        | GraphPattern::Graph { inner, .. }
5967        | GraphPattern::Extend { inner, .. }
5968        | GraphPattern::OrderBy { inner, .. }
5969        | GraphPattern::Project { inner, .. }
5970        | GraphPattern::Distinct { inner }
5971        | GraphPattern::Reduced { inner }
5972        | GraphPattern::Slice { inner, .. }
5973        | GraphPattern::Group { inner, .. }
5974        | GraphPattern::Service { inner, .. } => inner,
5975        GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => {
5976            unreachable!("leaf patterns have no children")
5977        }
5978    }
5979}
5980
5981fn replace_algebra_child(
5982    pattern: GraphPattern,
5983    index: usize,
5984    f: &mut dyn FnMut(GraphPattern) -> GraphPattern,
5985) -> GraphPattern {
5986    match pattern {
5987        GraphPattern::Join { left, right } => GraphPattern::Join {
5988            left: Box::new(if index == 0 { f(*left) } else { *left }),
5989            right: Box::new(if index == 0 { *right } else { f(*right) }),
5990        },
5991        GraphPattern::LeftJoin {
5992            left,
5993            right,
5994            expression,
5995        } => GraphPattern::LeftJoin {
5996            left: Box::new(if index == 0 { f(*left) } else { *left }),
5997            right: Box::new(if index == 0 { *right } else { f(*right) }),
5998            expression,
5999        },
6000        GraphPattern::Union { left, right } => GraphPattern::Union {
6001            left: Box::new(if index == 0 { f(*left) } else { *left }),
6002            right: Box::new(if index == 0 { *right } else { f(*right) }),
6003        },
6004        GraphPattern::Minus { left, right } => GraphPattern::Minus {
6005            left: Box::new(if index == 0 { f(*left) } else { *left }),
6006            right: Box::new(if index == 0 { *right } else { f(*right) }),
6007        },
6008        GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
6009            expr,
6010            inner: Box::new(f(*inner)),
6011        },
6012        GraphPattern::Graph { name, inner } => GraphPattern::Graph {
6013            name,
6014            inner: Box::new(f(*inner)),
6015        },
6016        GraphPattern::Extend {
6017            inner,
6018            variable,
6019            expression,
6020        } => GraphPattern::Extend {
6021            inner: Box::new(f(*inner)),
6022            variable,
6023            expression,
6024        },
6025        GraphPattern::OrderBy { inner, expression } => GraphPattern::OrderBy {
6026            inner: Box::new(f(*inner)),
6027            expression,
6028        },
6029        GraphPattern::Project { inner, variables } => GraphPattern::Project {
6030            inner: Box::new(f(*inner)),
6031            variables,
6032        },
6033        GraphPattern::Distinct { inner } => GraphPattern::Distinct {
6034            inner: Box::new(f(*inner)),
6035        },
6036        GraphPattern::Reduced { inner } => GraphPattern::Reduced {
6037            inner: Box::new(f(*inner)),
6038        },
6039        GraphPattern::Slice {
6040            inner,
6041            start,
6042            length,
6043        } => GraphPattern::Slice {
6044            inner: Box::new(f(*inner)),
6045            start,
6046            length,
6047        },
6048        GraphPattern::Group {
6049            inner,
6050            variables,
6051            aggregates,
6052        } => GraphPattern::Group {
6053            inner: Box::new(f(*inner)),
6054            variables,
6055            aggregates,
6056        },
6057        GraphPattern::Service {
6058            name,
6059            inner,
6060            silent,
6061        } => GraphPattern::Service {
6062            name,
6063            inner: Box::new(f(*inner)),
6064            silent,
6065        },
6066        GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => {
6067            unreachable!("leaf patterns have no children")
6068        }
6069    }
6070}
6071
6072/// Rebuild `pattern` with `f` applied to every direct child, in the same
6073/// canonical child order [`algebra_child`] uses.
6074fn map_algebra_children(
6075    pattern: GraphPattern,
6076    f: &mut dyn FnMut(GraphPattern) -> GraphPattern,
6077) -> GraphPattern {
6078    match pattern {
6079        GraphPattern::Bgp { patterns } => GraphPattern::Bgp { patterns },
6080        GraphPattern::Path {
6081            subject,
6082            path,
6083            object,
6084        } => GraphPattern::Path {
6085            subject,
6086            path,
6087            object,
6088        },
6089        GraphPattern::Values {
6090            variables,
6091            bindings,
6092        } => GraphPattern::Values {
6093            variables,
6094            bindings,
6095        },
6096        GraphPattern::Join { left, right } => GraphPattern::Join {
6097            left: Box::new(f(*left)),
6098            right: Box::new(f(*right)),
6099        },
6100        GraphPattern::LeftJoin {
6101            left,
6102            right,
6103            expression,
6104        } => GraphPattern::LeftJoin {
6105            left: Box::new(f(*left)),
6106            right: Box::new(f(*right)),
6107            expression,
6108        },
6109        GraphPattern::Union { left, right } => GraphPattern::Union {
6110            left: Box::new(f(*left)),
6111            right: Box::new(f(*right)),
6112        },
6113        GraphPattern::Minus { left, right } => GraphPattern::Minus {
6114            left: Box::new(f(*left)),
6115            right: Box::new(f(*right)),
6116        },
6117        GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
6118            expr,
6119            inner: Box::new(f(*inner)),
6120        },
6121        GraphPattern::Graph { name, inner } => GraphPattern::Graph {
6122            name,
6123            inner: Box::new(f(*inner)),
6124        },
6125        GraphPattern::Extend {
6126            inner,
6127            variable,
6128            expression,
6129        } => GraphPattern::Extend {
6130            inner: Box::new(f(*inner)),
6131            variable,
6132            expression,
6133        },
6134        GraphPattern::OrderBy { inner, expression } => GraphPattern::OrderBy {
6135            inner: Box::new(f(*inner)),
6136            expression,
6137        },
6138        GraphPattern::Project { inner, variables } => GraphPattern::Project {
6139            inner: Box::new(f(*inner)),
6140            variables,
6141        },
6142        GraphPattern::Distinct { inner } => GraphPattern::Distinct {
6143            inner: Box::new(f(*inner)),
6144        },
6145        GraphPattern::Reduced { inner } => GraphPattern::Reduced {
6146            inner: Box::new(f(*inner)),
6147        },
6148        GraphPattern::Slice {
6149            inner,
6150            start,
6151            length,
6152        } => GraphPattern::Slice {
6153            inner: Box::new(f(*inner)),
6154            start,
6155            length,
6156        },
6157        GraphPattern::Group {
6158            inner,
6159            variables,
6160            aggregates,
6161        } => GraphPattern::Group {
6162            inner: Box::new(f(*inner)),
6163            variables,
6164            aggregates,
6165        },
6166        GraphPattern::Service {
6167            name,
6168            inner,
6169            silent,
6170        } => GraphPattern::Service {
6171            name,
6172            inner: Box::new(f(*inner)),
6173            silent,
6174        },
6175    }
6176}
6177
6178fn pattern_contains_graph(pattern: &GraphPattern) -> bool {
6179    match pattern {
6180        GraphPattern::Graph { .. } => true,
6181        GraphPattern::Join { left, right }
6182        | GraphPattern::Union { left, right }
6183        | GraphPattern::Minus { left, right } => {
6184            pattern_contains_graph(left) || pattern_contains_graph(right)
6185        }
6186        GraphPattern::LeftJoin { left, right, .. } => {
6187            pattern_contains_graph(left) || pattern_contains_graph(right)
6188        }
6189        GraphPattern::Filter { inner, .. }
6190        | GraphPattern::Extend { inner, .. }
6191        | GraphPattern::Distinct { inner }
6192        | GraphPattern::Reduced { inner }
6193        | GraphPattern::Slice { inner, .. }
6194        | GraphPattern::Group { inner, .. }
6195        | GraphPattern::OrderBy { inner, .. }
6196        | GraphPattern::Project { inner, .. }
6197        | GraphPattern::Service { inner, .. } => pattern_contains_graph(inner),
6198        _ => false,
6199    }
6200}
6201
6202fn sparopt_roundtrip(pattern: GraphPattern) -> GraphPattern {
6203    let sparopt_in = sparopt::algebra::GraphPattern::from(&pattern);
6204    let sparopt_out = sparopt::Optimizer::optimize_graph_pattern(sparopt_in);
6205    GraphPattern::from(&sparopt_out)
6206}
6207
6208/// Always-bound variables from outer LeftJoin lefts, with optional distinct counts.
6209///
6210/// `Some(n)` is the estimated domain for that variable. `None` means bound but
6211/// unknown count — keep per-key HLL fan-out (do not pretend the scan is huge).
6212#[derive(Debug, Clone, Default, PartialEq, Eq)]
6213struct IncomingBound {
6214    entries: Vec<(Variable, Option<u64>)>,
6215}
6216
6217impl IncomingBound {
6218    fn contains(&self, variable: &Variable) -> bool {
6219        self.entries.iter().any(|(known, _)| known == variable)
6220    }
6221
6222    /// Distinct-value estimate when known (`None` if unbound or count unknown).
6223    fn known_domain(&self, variable: &Variable) -> Option<u64> {
6224        self.entries
6225            .iter()
6226            .find(|(known, _)| known == variable)
6227            .and_then(|(_, domain)| *domain)
6228    }
6229
6230    fn insert(&mut self, variable: Variable, domain: Option<u64>) {
6231        if let Some((_, existing)) = self
6232            .entries
6233            .iter_mut()
6234            .find(|(known, _)| *known == variable)
6235        {
6236            *existing = match (*existing, domain) {
6237                (Some(a), Some(b)) => Some(a.min(b)),
6238                (a, b) => a.or(b),
6239            };
6240        } else {
6241            self.entries.push((variable, domain));
6242        }
6243    }
6244
6245    fn merge(&mut self, extra: &IncomingBound) {
6246        for (variable, domain) in &extra.entries {
6247            self.insert(variable.clone(), *domain);
6248        }
6249    }
6250}
6251
6252/// Peel top-level `EXISTS` / `NOT EXISTS` `&&` conjuncts. `||` trees that
6253/// contain `EXISTS` stay in the remainder so [`split_filter`] rejects them.
6254type PeeledExists = (Vec<(bool, GraphPattern)>, Option<Expression>);
6255
6256fn peel_exists_conjuncts(expr: &Expression) -> Result<PeeledExists, ComputeError> {
6257    let mut exists = Vec::new();
6258    let mut rest = Vec::new();
6259    for conjunct in flatten_and(expr) {
6260        match exists_conjunct(&conjunct) {
6261            Some((negated, body)) => exists.push((negated, body)),
6262            None => rest.push(conjunct),
6263        }
6264    }
6265    Ok((exists, and_fold(rest)))
6266}
6267
6268fn exists_conjunct(expr: &Expression) -> Option<(bool, GraphPattern)> {
6269    match expr {
6270        Expression::Exists(inner) => Some((false, (**inner).clone())),
6271        Expression::Not(inner) => match inner.as_ref() {
6272            Expression::Exists(body) => Some((true, (**body).clone())),
6273            _ => None,
6274        },
6275        _ => None,
6276    }
6277}
6278
6279fn lower_exists_clause(
6280    negated: bool,
6281    body: GraphPattern,
6282    outer: &PlanNode,
6283    incoming: &IncomingBound,
6284    profile: Option<&StatsProfile>,
6285    ctx: &QueryContext,
6286    scope: &GraphScope,
6287) -> Result<ExistsClause, ComputeError> {
6288    let outer_vars = outer.output_vars();
6289    if exists_has_correlated_subselect(&body, &outer_vars) {
6290        return Err(ComputeError::UnsupportedSparql(
6291            "EXISTS body sub-SELECT that references outer variables is not supported".into(),
6292        ));
6293    }
6294    // Mirror `prepare_algebra`'s pass order ( sparopt → alt→UNION flatten →
6295    // VALUES push → OPTIONAL-to-join ) so an EXISTS body plans like the same
6296    // pattern in a WHERE clause: sparopt normalizes query blank nodes to
6297    // variables BEFORE the flatten mints BGP arms, and the VALUES push sees
6298    // the unions the flatten created. `fold_constants` stays WHERE-only: it
6299    // rewrites expressions, never pattern structure, and EXISTS lowering has
6300    // no `ExprEvalEnv` to give it.
6301    // The body is a correlated probe: the outer row's bindings are pushed into
6302    // it, so a body VALUES column the outer can bind is a join key and must not
6303    // be dropped when the placement pass re-seats the body's tables. The outer
6304    // schema is exactly the set `exists_correlation` later uses to decide which
6305    // keys the probe pushes, so passing it as the live set keeps every column
6306    // that can affect the EXISTS boolean.
6307    let outer_live = outer_vars.all();
6308    let prepared = crate::optional_to_join::replace_filter_forced_joins(
6309        push_values_into_union(place_values_at_lca_with_live(
6310            crate::alt_to_union::flatten_alternative_paths(optimize_preserving_graph(body)),
6311            &outer_live,
6312        )),
6313        &|_| None,
6314    );
6315    let lowered = lower_pattern(&prepared, profile, incoming, ctx, scope)?;
6316    reject_exists_correlated_group(&lowered, &outer_vars)?;
6317    let correlation = exists_correlation(outer, &lowered);
6318    Ok(ExistsClause {
6319        negated,
6320        body: Box::new(lowered),
6321        correlation,
6322        kind: ExistsKind::NestedProbe,
6323    })
6324}
6325
6326fn exists_correlation(outer: &PlanNode, body: &PlanNode) -> Vec<Variable> {
6327    let outer_vars = outer.output_vars();
6328    let mut correlation = Vec::new();
6329    for variable in plan_referenced_variables(body) {
6330        if outer_vars.contains(&variable) && !correlation.contains(&variable) {
6331            correlation.push(variable);
6332        }
6333    }
6334    correlation
6335}
6336
6337fn plan_referenced_variables(node: &PlanNode) -> Vec<Variable> {
6338    let mut out = node.inner_variables();
6339    collect_plan_expr_vars(node, &mut out);
6340    out
6341}
6342
6343fn push_var(out: &mut Vec<Variable>, variable: Variable) {
6344    if !out.contains(&variable) {
6345        out.push(variable);
6346    }
6347}
6348
6349fn collect_plan_expr_vars(node: &PlanNode, out: &mut Vec<Variable>) {
6350    match node {
6351        PlanNode::CustomNode(op) => {
6352            for child in &op.children {
6353                collect_plan_expr_vars(child, out);
6354            }
6355        }
6356        PlanNode::Filter {
6357            inner,
6358            early,
6359            residual,
6360            exists,
6361            ..
6362        } => {
6363            for expr in early.iter().chain(residual.iter()) {
6364                for variable in variables_in_expression(expr) {
6365                    push_var(out, variable);
6366                }
6367            }
6368            collect_plan_expr_vars(inner, out);
6369            for clause in exists {
6370                for variable in &clause.correlation {
6371                    push_var(out, variable.clone());
6372                }
6373                collect_plan_expr_vars(&clause.body, out);
6374            }
6375        }
6376        PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
6377            collect_plan_expr_vars(left, out);
6378            collect_plan_expr_vars(right, out);
6379        }
6380        PlanNode::LeftJoin {
6381            left,
6382            right,
6383            early_filter,
6384            residual_filter,
6385            ..
6386        } => {
6387            collect_plan_expr_vars(left, out);
6388            collect_plan_expr_vars(right, out);
6389            for expr in early_filter.iter().chain(residual_filter.iter()) {
6390                for variable in variables_in_expression(expr) {
6391                    push_var(out, variable);
6392                }
6393            }
6394        }
6395        PlanNode::Extend {
6396            inner, expression, ..
6397        } => {
6398            for variable in variables_in_expression(expression) {
6399                push_var(out, variable);
6400            }
6401            collect_plan_expr_vars(inner, out);
6402        }
6403        PlanNode::Sort { inner, keys } => {
6404            for key in keys {
6405                for variable in variables_in_expression(&key.expression) {
6406                    push_var(out, variable);
6407                }
6408            }
6409            collect_plan_expr_vars(inner, out);
6410        }
6411        PlanNode::Group {
6412            inner, aggregates, ..
6413        } => {
6414            for (_, agg) in aggregates {
6415                if let AggregateExpression::FunctionCall { expr, .. } = agg {
6416                    for variable in variables_in_expression(expr) {
6417                        push_var(out, variable);
6418                    }
6419                }
6420            }
6421            collect_plan_expr_vars(inner, out);
6422        }
6423        PlanNode::Slice { inner, .. }
6424        | PlanNode::Distinct { inner, .. }
6425        | PlanNode::JoinGraphVar { inner, .. } => collect_plan_expr_vars(inner, out),
6426        PlanNode::SubSelect(sub) => collect_plan_expr_vars(&sub.inner, out),
6427        PlanNode::Scan(_)
6428        | PlanNode::Path(_)
6429        | PlanNode::Values(_)
6430        | PlanNode::NamedGraphs { .. }
6431        | PlanNode::NamedGraphExists { .. }
6432        | PlanNode::DomainCounts { .. }
6433        | PlanNode::HeadCounts { .. }
6434        | PlanNode::PatternCount { .. }
6435        | PlanNode::Unit => {}
6436    }
6437}
6438
6439fn is_simple_bgp_exists_body(node: &PlanNode) -> bool {
6440    match node {
6441        PlanNode::Scan(_)
6442        | PlanNode::Values(_)
6443        | PlanNode::Unit
6444        | PlanNode::NamedGraphExists { .. } => true,
6445        // A plugin op in an EXISTS body forces the NestedProbe path.
6446        PlanNode::CustomNode(_) => false,
6447        PlanNode::Join { left, right, .. } => {
6448            is_simple_bgp_exists_body(left) && is_simple_bgp_exists_body(right)
6449        }
6450        PlanNode::Filter { inner, exists, .. } => {
6451            exists.is_empty() && is_simple_bgp_exists_body(inner)
6452        }
6453        PlanNode::Extend { inner, .. } => is_simple_bgp_exists_body(inner),
6454        PlanNode::Path(_)
6455        | PlanNode::LeftJoin { .. }
6456        | PlanNode::Union { .. }
6457        | PlanNode::SubSelect(_)
6458        | PlanNode::Group { .. }
6459        | PlanNode::Slice { .. }
6460        | PlanNode::Distinct { .. }
6461        | PlanNode::Sort { .. }
6462        | PlanNode::NamedGraphs { .. }
6463        | PlanNode::DomainCounts { .. }
6464        | PlanNode::HeadCounts { .. }
6465        | PlanNode::PatternCount { .. }
6466        | PlanNode::JoinGraphVar { .. } => false,
6467    }
6468}
6469
6470/// Body columns that also appear in `correlation` (triple/path/VALUES slots).
6471pub(crate) fn exists_scan_keys(body: &PlanNode, correlation: &[Variable]) -> Vec<Variable> {
6472    let produced = body.inner_variables();
6473    correlation
6474        .iter()
6475        .filter(|variable| produced.contains(variable))
6476        .cloned()
6477        .collect()
6478}
6479
6480/// Correlation names that appear in body FILTER/BIND/OPTIONAL/Sort expressions.
6481/// Independent of [`exists_scan_keys`]: a var can be in both.
6482fn exists_expr_keys(body: &PlanNode, correlation: &[Variable]) -> Vec<Variable> {
6483    let mut expr = Vec::new();
6484    collect_plan_expr_vars(body, &mut expr);
6485    correlation
6486        .iter()
6487        .filter(|variable| expr.contains(variable))
6488        .cloned()
6489        .collect()
6490}
6491
6492/// Expression-referenced correlation vars the body does **not** produce as
6493/// columns. SemiJoin is unsound when this is non-empty; NestedProbe must
6494/// substitute these names into FILTER/BIND (VALUES under the expression).
6495pub(crate) fn exists_expr_only_keys(body: &PlanNode, correlation: &[Variable]) -> Vec<Variable> {
6496    let scan = exists_scan_keys(body, correlation);
6497    exists_expr_keys(body, correlation)
6498        .into_iter()
6499        .filter(|variable| !scan.contains(variable))
6500        .collect()
6501}
6502
6503fn classify_exists_kind(outer: &PlanNode, body: &PlanNode, correlation: &[Variable]) -> ExistsKind {
6504    if correlation.is_empty() {
6505        return ExistsKind::Uncorrelated;
6506    }
6507    let outer_vars = outer.output_vars();
6508    let always_bound = correlation
6509        .iter()
6510        .all(|variable| outer_vars.is_always_bound(variable));
6511    let expr_only = exists_expr_only_keys(body, correlation);
6512    if always_bound && is_simple_bgp_exists_body(body) && expr_only.is_empty() {
6513        ExistsKind::SemiJoin
6514    } else {
6515        ExistsKind::NestedProbe
6516    }
6517}
6518
6519/// After identity-fold grounds body scans, pick mode 1 / 2 / 3 and rename
6520/// NestedProbe inner-only names the same way SubSelect does.
6521fn classify_exists_in_plan(node: &mut PlanNode) -> Result<(), ComputeError> {
6522    match node {
6523        PlanNode::CustomNode(op) => {
6524            for child in &mut op.children {
6525                classify_exists_in_plan(child)?;
6526            }
6527        }
6528        PlanNode::Filter { inner, exists, .. } => {
6529            classify_exists_in_plan(inner)?;
6530            for clause in exists.iter_mut() {
6531                classify_exists_in_plan(&mut clause.body)?;
6532                clause.correlation = exists_correlation(inner, &clause.body);
6533                clause.kind = classify_exists_kind(inner, &clause.body, &clause.correlation);
6534                if clause.kind == ExistsKind::NestedProbe {
6535                    let prefix = mint_scope_prefix();
6536                    let projected = clause.correlation.clone();
6537                    rename_subselect_scope(&mut clause.body, &projected, &prefix)?;
6538                }
6539            }
6540        }
6541        PlanNode::Join { left, right, .. }
6542        | PlanNode::LeftJoin { left, right, .. }
6543        | PlanNode::Union { left, right } => {
6544            classify_exists_in_plan(left)?;
6545            classify_exists_in_plan(right)?;
6546        }
6547        PlanNode::Extend { inner, .. }
6548        | PlanNode::Slice { inner, .. }
6549        | PlanNode::Distinct { inner, .. }
6550        | PlanNode::Sort { inner, .. }
6551        | PlanNode::Group { inner, .. }
6552        | PlanNode::JoinGraphVar { inner, .. } => classify_exists_in_plan(inner)?,
6553        PlanNode::SubSelect(sub) => classify_exists_in_plan(&mut sub.inner)?,
6554        PlanNode::Scan(_)
6555        | PlanNode::Path(_)
6556        | PlanNode::Values(_)
6557        | PlanNode::NamedGraphs { .. }
6558        | PlanNode::NamedGraphExists { .. }
6559        | PlanNode::DomainCounts { .. }
6560        | PlanNode::HeadCounts { .. }
6561        | PlanNode::PatternCount { .. }
6562        | PlanNode::Unit => {}
6563    }
6564    Ok(())
6565}
6566
6567/// Nested sub-SELECT whose body (including non-projected names) shares a
6568/// variable with the EXISTS outer pattern. Hygiene rename would destroy that
6569/// correlation, so reject instead of silently ASK-once.
6570fn exists_has_correlated_subselect(pattern: &GraphPattern, outer: &OutputVars) -> bool {
6571    if let Some(spine) = subselect_spine(pattern) {
6572        if algebra_references_outer(spine.body, outer) {
6573            return true;
6574        }
6575        for key in &spine.order {
6576            if variables_in_expression(&key.expression)
6577                .iter()
6578                .any(|variable| outer.contains(variable))
6579            {
6580                return true;
6581            }
6582        }
6583        return exists_has_correlated_subselect(spine.body, outer);
6584    }
6585    match pattern {
6586        GraphPattern::Join { left, right }
6587        | GraphPattern::Union { left, right }
6588        | GraphPattern::Minus { left, right }
6589        | GraphPattern::LeftJoin { left, right, .. } => {
6590            exists_has_correlated_subselect(left, outer)
6591                || exists_has_correlated_subselect(right, outer)
6592        }
6593        GraphPattern::Filter { inner, .. }
6594        | GraphPattern::Extend { inner, .. }
6595        | GraphPattern::Group { inner, .. }
6596        | GraphPattern::Graph { inner, .. }
6597        | GraphPattern::Service { inner, .. }
6598        | GraphPattern::Project { inner, .. } => exists_has_correlated_subselect(inner, outer),
6599        _ => false,
6600    }
6601}
6602
6603fn algebra_references_outer(pattern: &GraphPattern, outer: &OutputVars) -> bool {
6604    match pattern {
6605        GraphPattern::Bgp { patterns } => patterns.iter().any(|triple| {
6606            term_pattern_is_outer(&triple.subject, outer)
6607                || named_node_pattern_is_outer(&triple.predicate, outer)
6608                || term_pattern_is_outer(&triple.object, outer)
6609        }),
6610        GraphPattern::Path {
6611            subject, object, ..
6612        } => term_pattern_is_outer(subject, outer) || term_pattern_is_outer(object, outer),
6613        GraphPattern::Join { left, right }
6614        | GraphPattern::Union { left, right }
6615        | GraphPattern::Minus { left, right } => {
6616            algebra_references_outer(left, outer) || algebra_references_outer(right, outer)
6617        }
6618        GraphPattern::LeftJoin {
6619            left,
6620            right,
6621            expression,
6622        } => {
6623            algebra_references_outer(left, outer)
6624                || algebra_references_outer(right, outer)
6625                || expression
6626                    .as_ref()
6627                    .is_some_and(|expr| expr_references_outer(expr, outer))
6628        }
6629        GraphPattern::Filter { expr, inner } => {
6630            expr_references_outer(expr, outer) || algebra_references_outer(inner, outer)
6631        }
6632        GraphPattern::Graph { name, inner } => {
6633            named_node_pattern_is_outer(name, outer) || algebra_references_outer(inner, outer)
6634        }
6635        GraphPattern::Extend {
6636            inner,
6637            variable,
6638            expression,
6639        } => {
6640            outer.contains(variable)
6641                || expr_references_outer(expression, outer)
6642                || algebra_references_outer(inner, outer)
6643        }
6644        GraphPattern::Values { variables, .. } => variables.iter().any(|v| outer.contains(v)),
6645        GraphPattern::OrderBy { inner, expression } => {
6646            expression
6647                .iter()
6648                .any(|oe| expr_references_outer(order_expression_expr(oe), outer))
6649                || algebra_references_outer(inner, outer)
6650        }
6651        GraphPattern::Slice { inner, .. }
6652        | GraphPattern::Distinct { inner }
6653        | GraphPattern::Reduced { inner }
6654        | GraphPattern::Service { inner, .. }
6655        | GraphPattern::Project { inner, .. } => algebra_references_outer(inner, outer),
6656        GraphPattern::Group {
6657            inner,
6658            variables,
6659            aggregates,
6660        } => {
6661            variables.iter().any(|v| outer.contains(v))
6662                || aggregates.iter().any(|(result, agg)| {
6663                    outer.contains(result)
6664                        || matches!(
6665                            agg,
6666                            AggregateExpression::FunctionCall { expr, .. }
6667                                if expr_references_outer(expr, outer)
6668                        )
6669                })
6670                || algebra_references_outer(inner, outer)
6671        }
6672    }
6673}
6674
6675fn order_expression_expr(oe: &OrderExpression) -> &Expression {
6676    match oe {
6677        OrderExpression::Asc(expression) | OrderExpression::Desc(expression) => expression,
6678    }
6679}
6680
6681fn expr_references_outer(expression: &Expression, outer: &OutputVars) -> bool {
6682    variables_in_expression(expression)
6683        .iter()
6684        .any(|variable| outer.contains(variable))
6685}
6686
6687fn term_pattern_is_outer(term: &TermPattern, outer: &OutputVars) -> bool {
6688    matches!(term, TermPattern::Variable(v) if outer.contains(v))
6689}
6690
6691fn named_node_pattern_is_outer(name: &NamedNodePattern, outer: &OutputVars) -> bool {
6692    matches!(name, NamedNodePattern::Variable(v) if outer.contains(v))
6693}
6694
6695fn reject_exists_correlated_group(node: &PlanNode, outer: &OutputVars) -> Result<(), ComputeError> {
6696    match node {
6697        // A plugin op is not a Group and cannot be correlated through.
6698        PlanNode::CustomNode(_) => Ok(()),
6699        PlanNode::Group {
6700            inner,
6701            variables,
6702            aggregates,
6703            ..
6704        } => {
6705            let mut refs = inner.inner_variables();
6706            collect_plan_expr_vars(node, &mut refs);
6707            for variable in variables {
6708                push_var(&mut refs, variable.clone());
6709            }
6710            for (result, _) in aggregates {
6711                push_var(&mut refs, result.clone());
6712            }
6713            if refs.iter().any(|variable| outer.contains(variable)) {
6714                return Err(ComputeError::UnsupportedSparql(
6715                    "EXISTS body GROUP BY that references outer variables is not supported".into(),
6716                ));
6717            }
6718            reject_exists_correlated_group(inner, outer)
6719        }
6720        PlanNode::Filter { inner, exists, .. } => {
6721            reject_exists_correlated_group(inner, outer)?;
6722            for clause in exists {
6723                reject_exists_correlated_group(&clause.body, outer)?;
6724            }
6725            Ok(())
6726        }
6727        PlanNode::Join { left, right, .. }
6728        | PlanNode::LeftJoin { left, right, .. }
6729        | PlanNode::Union { left, right } => {
6730            reject_exists_correlated_group(left, outer)?;
6731            reject_exists_correlated_group(right, outer)
6732        }
6733        PlanNode::Extend { inner, .. }
6734        | PlanNode::Slice { inner, .. }
6735        | PlanNode::Distinct { inner, .. }
6736        | PlanNode::Sort { inner, .. }
6737        | PlanNode::JoinGraphVar { inner, .. } => reject_exists_correlated_group(inner, outer),
6738        PlanNode::SubSelect(sub) => reject_exists_correlated_group(&sub.inner, outer),
6739        PlanNode::Scan(_)
6740        | PlanNode::Path(_)
6741        | PlanNode::Values(_)
6742        | PlanNode::NamedGraphs { .. }
6743        | PlanNode::NamedGraphExists { .. }
6744        | PlanNode::DomainCounts { .. }
6745        | PlanNode::HeadCounts { .. }
6746        | PlanNode::PatternCount { .. }
6747        | PlanNode::Unit => Ok(()),
6748    }
6749}
6750
6751/// Join a 1-row VALUES of expression-only correlation bindings under every
6752/// FILTER/BIND/OPTIONAL whose expression needs those names, so `get_var`
6753/// sees them as columns. Wrapping the Filter *node* would still evaluate the
6754/// expression on the BGP without those columns.
6755pub(crate) fn inject_exists_values(node: &mut PlanNode, values: &ValuesOp) {
6756    if values.variables.is_empty() {
6757        return;
6758    }
6759    match node {
6760        PlanNode::CustomNode(op) => {
6761            for child in &mut op.children {
6762                inject_exists_values(child, values);
6763            }
6764        }
6765        PlanNode::Filter {
6766            inner,
6767            early,
6768            residual,
6769            exists,
6770            ..
6771        } => {
6772            inject_exists_values(inner, values);
6773            let needs = early
6774                .iter()
6775                .chain(residual.iter())
6776                .any(|expr| expr_uses_values(expr, values));
6777            if needs && !node_produces_values(inner, values) {
6778                **inner = join_values_cartesian(values.clone(), (**inner).clone());
6779            }
6780            for clause in exists {
6781                inject_exists_values(&mut clause.body, values);
6782            }
6783        }
6784        PlanNode::Extend {
6785            inner, expression, ..
6786        } => {
6787            inject_exists_values(inner, values);
6788            if expr_uses_values(expression, values) && !node_produces_values(inner, values) {
6789                **inner = join_values_cartesian(values.clone(), (**inner).clone());
6790            }
6791        }
6792        PlanNode::LeftJoin {
6793            left,
6794            right,
6795            early_filter,
6796            residual_filter,
6797            ..
6798        } => {
6799            inject_exists_values(left, values);
6800            inject_exists_values(right, values);
6801            let needs = early_filter
6802                .iter()
6803                .chain(residual_filter.iter())
6804                .any(|expr| expr_uses_values(expr, values));
6805            if needs && !node_produces_values(left, values) {
6806                **left = join_values_cartesian(values.clone(), (**left).clone());
6807            }
6808        }
6809        PlanNode::Sort { inner, keys } => {
6810            inject_exists_values(inner, values);
6811            let needs = keys
6812                .iter()
6813                .any(|key| expr_uses_values(&key.expression, values));
6814            if needs && !node_produces_values(inner, values) {
6815                **inner = join_values_cartesian(values.clone(), (**inner).clone());
6816            }
6817        }
6818        PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
6819            inject_exists_values(left, values);
6820            inject_exists_values(right, values);
6821        }
6822        PlanNode::Slice { inner, .. }
6823        | PlanNode::Distinct { inner, .. }
6824        | PlanNode::Group { inner, .. }
6825        | PlanNode::JoinGraphVar { inner, .. } => inject_exists_values(inner, values),
6826        PlanNode::SubSelect(_)
6827        | PlanNode::Scan(_)
6828        | PlanNode::Path(_)
6829        | PlanNode::Values(_)
6830        | PlanNode::NamedGraphs { .. }
6831        | PlanNode::NamedGraphExists { .. }
6832        | PlanNode::DomainCounts { .. }
6833        | PlanNode::HeadCounts { .. }
6834        | PlanNode::PatternCount { .. }
6835        | PlanNode::Unit => {}
6836    }
6837}
6838
6839fn expr_uses_values(expression: &Expression, values: &ValuesOp) -> bool {
6840    variables_in_expression(expression)
6841        .iter()
6842        .any(|variable| values.variables.contains(variable))
6843}
6844
6845fn node_produces_values(node: &PlanNode, values: &ValuesOp) -> bool {
6846    let produced = node.output_vars();
6847    values
6848        .variables
6849        .iter()
6850        .all(|variable| produced.contains(variable))
6851}
6852
6853fn join_values_cartesian(values: ValuesOp, inner: PlanNode) -> PlanNode {
6854    let left = PlanNode::Values(values);
6855    let hash_keys = hash_keys_for(&left.output_vars(), &inner.output_vars());
6856    let rhs_hostable_keys = stamp_rhs_hostable_keys(&inner);
6857    PlanNode::Join {
6858        left: Box::new(left),
6859        right: Box::new(inner),
6860        hash_keys,
6861        // VALUES-driven joins are special-cased at runtime; no coverage data.
6862        probe_key_domains: Vec::new(),
6863        probe_key_overlap_milli: Vec::new(),
6864        rhs_hostable_keys,
6865        meta: JoinMeta {
6866            semi_gate: None,
6867            star_arms: None,
6868            strategy: JoinStrategy::Broadcast,
6869            produced_row_count_estimate: 1,
6870            own_push_removed_row_count_estimate: 1,
6871        },
6872    }
6873}
6874
6875fn lower_pattern(
6876    pattern: &GraphPattern,
6877    profile: Option<&StatsProfile>,
6878    incoming: &IncomingBound,
6879    ctx: &QueryContext,
6880    scope: &GraphScope,
6881) -> Result<PlanNode, ComputeError> {
6882    // Nested subselect spine: spargebra wraps a subselect's modifiers
6883    // OUTSIDE its projection (`Slice?(Distinct?(Project(body)))`), so peel
6884    // the whole spine here and let the boundary own it. The executor paths
6885    // then bound the body evaluation by the subselect's own OFFSET/LIMIT,
6886    // and every join arm is a bare `PlanNode::SubSelect`.
6887    if let Some(spine) = subselect_spine(pattern) {
6888        return lower_subselect(
6889            spine.body,
6890            spine.variables,
6891            spine.distinct,
6892            spine.slice,
6893            spine.order,
6894            profile,
6895            ctx,
6896            scope,
6897        );
6898    }
6899    let mut leaves = Vec::new();
6900    if collect_flat_leaves(pattern, &mut leaves) {
6901        return lower_pipeline(leaves, profile, incoming, ctx, scope);
6902    }
6903    match pattern {
6904        GraphPattern::Filter { expr, inner } => {
6905            let inner = lower_pattern(inner, profile, incoming, ctx, scope)?;
6906            // HAVING is a Filter on Group: leave EXISTS in the expression so
6907            // split_filter still rejects it.
6908            if matches!(inner, PlanNode::Group { .. }) {
6909                let (early, residual) = crate::expr::split_filter(expr)?;
6910                return Ok(PlanNode::Filter {
6911                    inner: Box::new(inner),
6912                    early,
6913                    residual,
6914                    exists: Vec::new(),
6915                    one_to_one: false,
6916                });
6917            }
6918            let (exists_raw, rest) = peel_exists_conjuncts(expr)?;
6919            let (early, residual) = match rest {
6920                Some(expr) => crate::expr::split_filter(&expr)?,
6921                None => (None, None),
6922            };
6923            let incoming_body = incoming_from_plan_left(incoming, &inner, profile);
6924            let mut exists = Vec::with_capacity(exists_raw.len());
6925            for (negated, body) in exists_raw {
6926                exists.push(lower_exists_clause(
6927                    negated,
6928                    body,
6929                    &inner,
6930                    &incoming_body,
6931                    profile,
6932                    ctx,
6933                    scope,
6934                )?);
6935            }
6936            Ok(PlanNode::Filter {
6937                inner: Box::new(inner),
6938                early,
6939                residual,
6940                exists,
6941                one_to_one: false,
6942            })
6943        }
6944        GraphPattern::LeftJoin {
6945            left,
6946            right,
6947            expression,
6948        } => {
6949            let left = lower_pattern(left, profile, incoming, ctx, scope)?;
6950            let right_incoming = incoming_from_plan_left(incoming, &left, profile);
6951            let mut right = lower_pattern(right, profile, &right_incoming, ctx, scope)?;
6952            let hash_keys = hash_keys_for(&left.output_vars(), &right.output_vars());
6953            ground_and_recost_broadcasted_arm(&left, &mut right, &hash_keys, profile);
6954            if !hash_keys.is_empty() {
6955                compose_graph_from_sibling(&left, &mut right, &hash_keys, profile, true);
6956            }
6957            let (early_filter, residual_filter) = match expression.as_ref() {
6958                Some(expr) => crate::expr::split_filter(expr)?,
6959                None => (None, None),
6960            };
6961            let meta = stamp_left_join_meta(
6962                left.produced_row_count_estimate(),
6963                &left,
6964                &right,
6965                &hash_keys,
6966                profile,
6967            );
6968            let probe_key_domains = stamp_probe_key_domains(profile, &right, &hash_keys);
6969            let probe_key_overlap_milli =
6970                stamp_probe_key_overlaps(profile, &left, &right, &hash_keys);
6971            Ok(PlanNode::LeftJoin {
6972                left: Box::new(left),
6973                right: Box::new(right),
6974                hash_keys,
6975                early_filter,
6976                residual_filter,
6977                probe_key_domains,
6978                probe_key_overlap_milli,
6979                meta,
6980            })
6981        }
6982        GraphPattern::Union { left, right } => {
6983            let left = lower_pattern(left, profile, incoming, ctx, scope)?;
6984            let right = lower_pattern(right, profile, incoming, ctx, scope)?;
6985            Ok(PlanNode::Union {
6986                left: Box::new(left),
6987                right: Box::new(right),
6988            })
6989        }
6990        GraphPattern::Extend {
6991            inner,
6992            variable,
6993            expression,
6994        } => {
6995            let inner = lower_pattern(inner, profile, incoming, ctx, scope)?;
6996            if inner.output_vars().contains(variable) {
6997                return Err(ComputeError::UnsupportedSparql(format!(
6998                    "BIND variable {variable} is already in-scope"
6999                )));
7000            }
7001            let _ = crate::expr::split_filter(expression)?;
7002            Ok(PlanNode::Extend {
7003                inner: Box::new(inner),
7004                variable: variable.clone(),
7005                expression: expression.clone(),
7006                // The finalization walk (`attach_const_seeds`) fills these
7007                // after every rewrite has settled the tree.
7008                const_strings: Vec::new(),
7009                const_blobs: Vec::new(),
7010            })
7011        }
7012        GraphPattern::Join { left, right } => {
7013            let left = lower_pattern(left, profile, incoming, ctx, scope)?;
7014            let right = lower_pattern(right, profile, incoming, ctx, scope)?;
7015            Ok(join_nodes(left, right, profile))
7016        }
7017        GraphPattern::Slice {
7018            inner,
7019            start,
7020            length,
7021        } => Ok(PlanNode::Slice {
7022            inner: Box::new(lower_pattern(inner, profile, incoming, ctx, scope)?),
7023            start: *start as u64,
7024            length: length.map(|n| n as u64),
7025        }),
7026        GraphPattern::Distinct { inner } => {
7027            let inner = lower_pattern(inner, profile, incoming, ctx, scope)?;
7028            let columns = inner.variables();
7029            Ok(PlanNode::Distinct {
7030                inner: Box::new(inner),
7031                columns,
7032            })
7033        }
7034        GraphPattern::Group {
7035            inner,
7036            variables,
7037            aggregates,
7038        } => {
7039            reject_unsupported_aggregates(aggregates)?;
7040            let lowered = lower_pattern(inner, profile, incoming, ctx, scope)?;
7041            Ok(PlanNode::Group {
7042                inner: Box::new(lowered),
7043                variables: variables.clone(),
7044                aggregates: aggregates.clone(),
7045                // Filled by `attach_const_seeds` (see the Extend arm).
7046                const_strings: Vec::new(),
7047                const_blobs: Vec::new(),
7048            })
7049        }
7050        // Project should always be caught by the subselect_spine function above.
7051        GraphPattern::Project { inner, variables } => lower_subselect(
7052            inner,
7053            variables,
7054            false,
7055            None,
7056            Vec::new(),
7057            profile,
7058            ctx,
7059            scope,
7060        ),
7061        GraphPattern::Path {
7062            subject,
7063            path,
7064            object,
7065        } => lower_path(subject, path, object, profile, incoming, ctx, scope),
7066        GraphPattern::Graph { name, inner } => {
7067            let inner_scope = graph_scope_for_name(name, ctx.dataset())?;
7068            if matches!(inner_scope, GraphScope::Empty) {
7069                let inner = lower_pattern(inner, profile, incoming, ctx, &GraphScope::Empty)?;
7070                return Ok(empty_plan_like(&inner, &inner_scope));
7071            }
7072            let (lower_scope, join_graph) = graph_lower_scope(inner, inner_scope);
7073            let lowered = lower_pattern(inner, profile, incoming, ctx, &lower_scope)?;
7074            if let Some(exists) = named_graph_exists_for_unit(&lowered, &lower_scope, ctx.dataset())
7075            {
7076                return Ok(exists);
7077            }
7078            let lowered = attach_graph_domain(lowered, &lower_scope, profile, ctx.dataset())?;
7079            Ok(match join_graph {
7080                Some((graph_var, active_var)) => PlanNode::JoinGraphVar {
7081                    inner: Box::new(lowered),
7082                    graph_var,
7083                    active_var,
7084                },
7085                None => lowered,
7086            })
7087        }
7088        GraphPattern::OrderBy { inner, expression } => {
7089            let keys: Vec<SortKey> = expression
7090                .iter()
7091                .map(|oe| match oe {
7092                    OrderExpression::Asc(expression) => SortKey {
7093                        expression: expression.clone(),
7094                        descending: false,
7095                    },
7096                    OrderExpression::Desc(expression) => SortKey {
7097                        expression: expression.clone(),
7098                        descending: true,
7099                    },
7100                })
7101                .collect();
7102            Ok(PlanNode::Sort {
7103                inner: Box::new(lower_pattern(inner, profile, incoming, ctx, scope)?),
7104                keys,
7105            })
7106        }
7107        other => Err(ComputeError::UnsupportedSparql(format!(
7108            "{} is not supported (BGP, JOIN, FILTER, OPTIONAL, UNION, VALUES, BIND, GROUP BY, GRAPH, sub-SELECT, property paths, LIMIT / OFFSET, ORDER BY only)",
7109            shape_name(other)
7110        ))),
7111    }
7112}
7113
7114/// Recognize a nested sub-select's full modifier spine.
7115///
7116/// spargebra lowers `SELECT [DISTINCT] … [ORDER BY] [OFFSET/LIMIT]` inside a
7117/// WHERE to `Slice?(OrderBy?(Distinct?(Project(body))))` — the modifiers sit
7118/// ABOVE the projection. `Reduced` is peeled as a no-op (same as the top-level
7119/// SELECT). Returns `None` when `pattern` is not a sub-select spine.
7120struct SubSelectSpine<'a> {
7121    body: &'a GraphPattern,
7122    variables: &'a [Variable],
7123    distinct: bool,
7124    slice: Option<(usize, Option<usize>)>,
7125    order: Vec<SortKey>,
7126}
7127
7128fn subselect_spine(pattern: &GraphPattern) -> Option<SubSelectSpine<'_>> {
7129    let mut cur = pattern;
7130    let mut distinct = false;
7131    let mut slice = None;
7132    let mut order = Vec::new();
7133    loop {
7134        match cur {
7135            GraphPattern::Slice {
7136                inner,
7137                start,
7138                length,
7139            } => {
7140                slice = Some((*start, *length));
7141                cur = inner;
7142            }
7143            GraphPattern::OrderBy { inner, expression } => {
7144                order = expression
7145                    .iter()
7146                    .map(|oe| match oe {
7147                        OrderExpression::Asc(expression) => SortKey {
7148                            expression: expression.clone(),
7149                            descending: false,
7150                        },
7151                        OrderExpression::Desc(expression) => SortKey {
7152                            expression: expression.clone(),
7153                            descending: true,
7154                        },
7155                    })
7156                    .collect();
7157                cur = inner;
7158            }
7159            GraphPattern::Distinct { inner } => {
7160                distinct = true;
7161                cur = inner;
7162            }
7163            GraphPattern::Reduced { inner } => {
7164                cur = inner;
7165            }
7166            GraphPattern::Project { inner, variables } => {
7167                return Some(SubSelectSpine {
7168                    body: inner,
7169                    variables,
7170                    distinct,
7171                    slice,
7172                    order,
7173                });
7174            }
7175            _ => return None,
7176        }
7177    }
7178}
7179
7180/// Lower a nested `SELECT` (sub-select spine) into an opaque boundary.
7181///
7182/// The boundary evaluates independently (outer bindings never leak in), its
7183/// output schema is exactly `variables`, and only those names join with the
7184/// enclosing group. It also OWNS the sub-select's modifier spine: `distinct`
7185/// dedups the body on the SELECT list, `order` sorts, and `slice` OFFSET/LIMITs
7186/// the ordered rows, in SPARQL order (`Slice(Sort(Distinct(body)))`), so every
7187/// materialization path stops pulling body rows once the sub-select's own
7188/// LIMIT is satisfied instead of computing the body in full and trimming
7189/// afterwards.
7190///
7191/// Non-projected inner names are renamed with a random per-subquery scope
7192/// token so they can never collide with same-named outer variables in join
7193/// keys, filters, or liveness.
7194#[allow(clippy::too_many_arguments)]
7195fn lower_subselect(
7196    inner: &GraphPattern,
7197    variables: &[Variable],
7198    distinct: bool,
7199    slice: Option<(usize, Option<usize>)>,
7200    order: Vec<SortKey>,
7201    profile: Option<&StatsProfile>,
7202    ctx: &QueryContext,
7203    scope: &GraphScope,
7204) -> Result<PlanNode, ComputeError> {
7205    let mut body = lower_pattern(inner, profile, &IncomingBound::default(), ctx, scope)?;
7206    let prefix = mint_scope_prefix();
7207    rename_subselect_scope(&mut body, variables, &prefix)?;
7208    // SPARQL solution modifiers apply Project → Distinct → OrderBy → Slice.
7209    // Distinct keyed on the SELECT list inside the boundary equals dedup after
7210    // projection, and the fixed Distinct-below-Sort-below-Slice order keeps
7211    // `LIMIT(ORDER BY(DISTINCT(·)))` semantics (the operators do not commute).
7212    if distinct {
7213        body = PlanNode::Distinct {
7214            inner: Box::new(body),
7215            columns: variables.to_vec(),
7216        };
7217    }
7218    if !order.is_empty() {
7219        body = PlanNode::Sort {
7220            inner: Box::new(body),
7221            keys: order,
7222        };
7223    }
7224    if let Some((start, length)) = slice {
7225        body = PlanNode::Slice {
7226            inner: Box::new(body),
7227            start: start as u64,
7228            length: length.map(|n| n as u64),
7229        };
7230    }
7231    Ok(PlanNode::SubSelect(SubSelectOp {
7232        inner: Box::new(body),
7233        variables: variables.to_vec(),
7234    }))
7235}
7236
7237/// Random scope token for one sub-SELECT's internal names: `sq_<16 chars>_`.
7238///
7239/// Counter prefixes (`sq1_`, `sq2_`, …) collided with any user variable that
7240/// happened to look like one — `?sq1_y` is a legal SPARQL name, and after the
7241/// rename both it and a renamed `?y` answered to the same string. 16 random
7242/// alphanumerics (~95 bits) make a collision require predicting the token;
7243/// the `sq_` wrapper keeps renamed names recognizable in EXPLAIN output.
7244fn mint_scope_prefix() -> String {
7245    format!("sq_{}_", mint_scope_token())
7246}
7247
7248/// Fresh 16-character random token (~95 bits) for scope-internal names.
7249///
7250/// Each `RandomState` is seeded independently, so successive draws are
7251/// unrelated; a collision requires predicting the token. Callers wrap the
7252/// token in their own recognizable prefix — `sq_…_` for sub-SELECT renames
7253/// ([`mint_scope_prefix`]), `gact_…` for graph-active variables,
7254/// `__text_h…` for the text plugin's subject-mode carriers — so the names
7255/// stay recognizable in EXPLAIN output while remaining unguessable.
7256pub fn mint_scope_token() -> String {
7257    use std::hash::{BuildHasher, Hasher};
7258    const ALPHABET: &[u8; 62] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
7259    let mut token = String::with_capacity(16);
7260    while token.len() < 16 {
7261        // Each RandomState is seeded independently, so successive draws are
7262        // unrelated. Two draws cover the 16 characters.
7263        let bits = std::collections::hash_map::RandomState::new()
7264            .build_hasher()
7265            .finish();
7266        for byte in bits.to_le_bytes() {
7267            token.push(ALPHABET[byte as usize % ALPHABET.len()] as char);
7268            if token.len() == 16 {
7269                break;
7270            }
7271        }
7272    }
7273    token
7274}
7275
7276/// Fresh scope-internal name for a non-projected subquery variable.
7277///
7278/// Pure function of the input name, so every occurrence of `?cat` in the
7279/// subtree maps to the same `sq_<token>_cat` without a side table.
7280/// Projected variables are the only cross-boundary join keys and keep
7281/// their names.
7282fn scope_rename(variable: &Variable, projection: &[Variable], prefix: &str) -> Option<Variable> {
7283    if projection.contains(variable) {
7284        return None;
7285    }
7286    Some(Variable::new_unchecked(format!(
7287        "{prefix}{}",
7288        variable.as_str()
7289    )))
7290}
7291
7292fn rename_opt_var(slot: &mut Option<Variable>, projection: &[Variable], prefix: &str) {
7293    if let Some(variable) = slot
7294        && let Some(fresh) = scope_rename(variable, projection, prefix)
7295    {
7296        *variable = fresh;
7297    }
7298}
7299
7300/// Rename every non-projected variable in a lowered subquery body.
7301///
7302/// Bottom-up lowering means a nested [`PlanNode::SubSelect`] inside `node`
7303/// was already renamed in its own scope: this walk renames its `variables`
7304/// list (those names are in scope here) and, for every list entry it
7305/// renames, extends the identical mapping into the nested subtree via
7306/// [`rename_variable_in_subtree`] — the subtree still binds the projected
7307/// name under its original spelling, and `project_to` looks output columns
7308/// up by name. Scan `marks` are skipped — [`annotate_liveness`] clears and
7309/// rebuilds them after this pass.
7310fn rename_subselect_scope(
7311    node: &mut PlanNode,
7312    projection: &[Variable],
7313    prefix: &str,
7314) -> Result<(), ComputeError> {
7315    match node {
7316        PlanNode::CustomNode(op) => {
7317            for variable in &mut op.variables {
7318                if let Some(fresh) = scope_rename(variable, projection, prefix) {
7319                    *variable = fresh;
7320                }
7321            }
7322            for child in &mut op.children {
7323                rename_subselect_scope(child, projection, prefix)?;
7324            }
7325        }
7326        PlanNode::Scan(scan) => {
7327            rename_opt_var(&mut scan.subject, projection, prefix);
7328            rename_opt_var(&mut scan.predicate, projection, prefix);
7329            rename_opt_var(&mut scan.object, projection, prefix);
7330            rename_opt_var(&mut scan.graph, projection, prefix);
7331            for (variable, _) in &mut scan.grounded {
7332                if let Some(fresh) = scope_rename(variable, projection, prefix) {
7333                    *variable = fresh;
7334                }
7335            }
7336            if let Some((variable, _)) = &mut scan.broadcasted
7337                && let Some(fresh) = scope_rename(variable, projection, prefix)
7338            {
7339                *variable = fresh;
7340            }
7341        }
7342        PlanNode::Path(path) => {
7343            rename_opt_var(&mut path.subject, projection, prefix);
7344            rename_opt_var(&mut path.object, projection, prefix);
7345            rename_opt_var(&mut path.graph, projection, prefix);
7346        }
7347        PlanNode::Join {
7348            left,
7349            right,
7350            hash_keys,
7351            ..
7352        } => {
7353            rename_subselect_scope(left, projection, prefix)?;
7354            rename_subselect_scope(right, projection, prefix)?;
7355            for key in &mut *hash_keys {
7356                if let Some(fresh) = scope_rename(key, projection, prefix) {
7357                    *key = fresh;
7358                }
7359            }
7360        }
7361        PlanNode::LeftJoin {
7362            left,
7363            right,
7364            hash_keys,
7365            early_filter,
7366            residual_filter,
7367            ..
7368        } => {
7369            rename_subselect_scope(left, projection, prefix)?;
7370            rename_subselect_scope(right, projection, prefix)?;
7371            for key in &mut *hash_keys {
7372                if let Some(fresh) = scope_rename(key, projection, prefix) {
7373                    *key = fresh;
7374                }
7375            }
7376            if let Some(expr) = early_filter {
7377                rename_expression_scope(expr, projection, prefix)?;
7378            }
7379            if let Some(expr) = residual_filter {
7380                rename_expression_scope(expr, projection, prefix)?;
7381            }
7382        }
7383        PlanNode::Filter {
7384            inner,
7385            early,
7386            residual,
7387            exists,
7388            ..
7389        } => {
7390            rename_subselect_scope(inner, projection, prefix)?;
7391            if let Some(expr) = early {
7392                rename_expression_scope(expr, projection, prefix)?;
7393            }
7394            if let Some(expr) = residual {
7395                rename_expression_scope(expr, projection, prefix)?;
7396            }
7397            for clause in exists {
7398                for variable in &mut clause.correlation {
7399                    if let Some(fresh) = scope_rename(variable, projection, prefix) {
7400                        *variable = fresh;
7401                    }
7402                }
7403                rename_subselect_scope(&mut clause.body, projection, prefix)?;
7404            }
7405        }
7406        PlanNode::Union { left, right } => {
7407            rename_subselect_scope(left, projection, prefix)?;
7408            rename_subselect_scope(right, projection, prefix)?;
7409        }
7410        PlanNode::Unit | PlanNode::NamedGraphExists { .. } => {}
7411        PlanNode::Values(values) => {
7412            for variable in &mut values.variables {
7413                if let Some(fresh) = scope_rename(variable, projection, prefix) {
7414                    *variable = fresh;
7415                }
7416            }
7417        }
7418        PlanNode::NamedGraphs { variable, .. } => {
7419            if let Some(fresh) = scope_rename(variable, projection, prefix) {
7420                *variable = fresh;
7421            }
7422        }
7423        PlanNode::Extend {
7424            inner,
7425            variable,
7426            expression,
7427            ..
7428        } => {
7429            rename_subselect_scope(inner, projection, prefix)?;
7430            if let Some(fresh) = scope_rename(variable, projection, prefix) {
7431                *variable = fresh;
7432            }
7433            rename_expression_scope(expression, projection, prefix)?;
7434        }
7435        PlanNode::Slice { inner, .. } => rename_subselect_scope(inner, projection, prefix)?,
7436        PlanNode::JoinGraphVar {
7437            inner,
7438            graph_var,
7439            active_var,
7440            ..
7441        } => {
7442            rename_subselect_scope(inner, projection, prefix)?;
7443            if let Some(fresh) = scope_rename(graph_var, projection, prefix) {
7444                *graph_var = fresh;
7445            }
7446            if let Some(fresh) = scope_rename(active_var, projection, prefix) {
7447                *active_var = fresh;
7448            }
7449        }
7450        PlanNode::Distinct { inner, columns } => {
7451            rename_subselect_scope(inner, projection, prefix)?;
7452            for column in &mut *columns {
7453                if let Some(fresh) = scope_rename(column, projection, prefix) {
7454                    *column = fresh;
7455                }
7456            }
7457        }
7458        PlanNode::Sort { inner, keys } => {
7459            rename_subselect_scope(inner, projection, prefix)?;
7460            for key in keys {
7461                rename_expression_scope(&mut key.expression, projection, prefix)?;
7462            }
7463        }
7464        PlanNode::Group {
7465            inner,
7466            variables,
7467            aggregates,
7468            ..
7469        } => {
7470            rename_subselect_scope(inner, projection, prefix)?;
7471            for key in &mut *variables {
7472                if let Some(fresh) = scope_rename(key, projection, prefix) {
7473                    *key = fresh;
7474                }
7475            }
7476            for (result, agg) in &mut *aggregates {
7477                if let Some(fresh) = scope_rename(result, projection, prefix) {
7478                    *result = fresh;
7479                }
7480                if let AggregateExpression::FunctionCall { expr, .. } = agg {
7481                    rename_expression_scope(expr, projection, prefix)?;
7482                }
7483            }
7484        }
7485        // The nested boundary's projected names are in scope here. Renaming
7486        // a list entry must reach the subtree too: the nested scope's own
7487        // rename pass skips projected names, so the subtree still binds the
7488        // original spelling while the boundary now declares the fresh one.
7489        PlanNode::SubSelect(sub) => {
7490            for variable in &mut sub.variables {
7491                if let Some(fresh) = scope_rename(variable, projection, prefix) {
7492                    let old = std::mem::replace(variable, fresh.clone());
7493                    rename_variable_in_subtree(&mut sub.inner, &old, &fresh)?;
7494                }
7495            }
7496        }
7497        // The count scan's output names (head key, count alias) are the
7498        // replaced Group's output schema — rename like any other projection.
7499        PlanNode::DomainCounts {
7500            head,
7501            count,
7502            dead,
7503            constraint_var,
7504            ..
7505        } => {
7506            if let Some(fresh) = scope_rename(head, projection, prefix) {
7507                *head = fresh;
7508            }
7509            if let Some(fresh) = scope_rename(count, projection, prefix) {
7510                *count = fresh;
7511            }
7512            if let Some(dead) = dead
7513                && let Some(fresh) = scope_rename(dead, projection, prefix)
7514            {
7515                *dead = fresh;
7516            }
7517            if let Some(cv) = constraint_var
7518                && let Some(fresh) = scope_rename(cv, projection, prefix)
7519            {
7520                *constraint_var = Some(fresh);
7521            }
7522        }
7523        PlanNode::HeadCounts {
7524            counted,
7525            group,
7526            count,
7527            ..
7528        } => {
7529            if let Some(fresh) = scope_rename(counted, projection, prefix) {
7530                *counted = fresh;
7531            }
7532            if let Some(group) = group
7533                && let Some(fresh) = scope_rename(group, projection, prefix)
7534            {
7535                *group = fresh;
7536            }
7537            if let Some(fresh) = scope_rename(count, projection, prefix) {
7538                *count = fresh;
7539            }
7540        }
7541        PlanNode::PatternCount {
7542            subject,
7543            predicate,
7544            object,
7545            count,
7546            counted,
7547            ..
7548        } => {
7549            rename_opt_var(subject, projection, prefix);
7550            rename_opt_var(predicate, projection, prefix);
7551            rename_opt_var(object, projection, prefix);
7552            if let Some(fresh) = scope_rename(count, projection, prefix) {
7553                *count = fresh;
7554            }
7555            if let Some(counted) = counted
7556                && let Some(fresh) = scope_rename(counted, projection, prefix)
7557            {
7558                *counted = fresh;
7559            }
7560        }
7561    }
7562    Ok(())
7563}
7564
7565/// Apply one variable rename (`old` → `fresh`) throughout a nested subquery
7566/// subtree.
7567///
7568/// Companion to [`rename_subselect_scope`]: when that pass relabels an entry
7569/// of a nested boundary's `variables` list, this walk relabels the bindings
7570/// inside so the boundary's declared schema stays equal to the columns its
7571/// plan produces. Where the subtree nests another boundary that projects
7572/// `old`, the rename crosses it — that boundary's list and subtree carry
7573/// the same variable chain. A boundary that does not project `old` renamed
7574/// every internal occurrence at its own lowering, so its subtree cannot
7575/// mention the name and is left alone. Scan `marks` are skipped for the
7576/// same reason as in [`rename_subselect_scope`].
7577fn rename_variable_in_subtree(
7578    node: &mut PlanNode,
7579    old: &Variable,
7580    fresh: &Variable,
7581) -> Result<(), ComputeError> {
7582    let rename_expr =
7583        |expression: &mut Expression| rename_expression_variable(expression, old, fresh);
7584    match node {
7585        PlanNode::CustomNode(op) => {
7586            for variable in &mut op.variables {
7587                if variable == old {
7588                    *variable = fresh.clone();
7589                }
7590            }
7591            for child in &mut op.children {
7592                rename_variable_in_subtree(child, old, fresh)?;
7593            }
7594        }
7595        PlanNode::Scan(scan) => {
7596            for slot in [
7597                &mut scan.subject,
7598                &mut scan.predicate,
7599                &mut scan.object,
7600                &mut scan.graph,
7601            ] {
7602                if slot.as_ref() == Some(old) {
7603                    *slot = Some(fresh.clone());
7604                }
7605            }
7606            for (variable, _) in &mut scan.grounded {
7607                if variable == old {
7608                    *variable = fresh.clone();
7609                }
7610            }
7611            if let Some((variable, _)) = &mut scan.broadcasted
7612                && variable == old
7613            {
7614                *variable = fresh.clone();
7615            }
7616        }
7617        PlanNode::Path(path) => {
7618            for slot in [&mut path.subject, &mut path.object, &mut path.graph] {
7619                if slot.as_ref() == Some(old) {
7620                    *slot = Some(fresh.clone());
7621                }
7622            }
7623        }
7624        PlanNode::Join {
7625            left,
7626            right,
7627            hash_keys,
7628            ..
7629        } => {
7630            rename_variable_in_subtree(left, old, fresh)?;
7631            rename_variable_in_subtree(right, old, fresh)?;
7632            for key in &mut *hash_keys {
7633                if key == old {
7634                    *key = fresh.clone();
7635                }
7636            }
7637        }
7638        PlanNode::LeftJoin {
7639            left,
7640            right,
7641            hash_keys,
7642            early_filter,
7643            residual_filter,
7644            ..
7645        } => {
7646            rename_variable_in_subtree(left, old, fresh)?;
7647            rename_variable_in_subtree(right, old, fresh)?;
7648            for key in &mut *hash_keys {
7649                if key == old {
7650                    *key = fresh.clone();
7651                }
7652            }
7653            if let Some(expr) = early_filter {
7654                rename_expr(expr)?;
7655            }
7656            if let Some(expr) = residual_filter {
7657                rename_expr(expr)?;
7658            }
7659        }
7660        PlanNode::Filter {
7661            inner,
7662            early,
7663            residual,
7664            exists,
7665            ..
7666        } => {
7667            rename_variable_in_subtree(inner, old, fresh)?;
7668            if let Some(expr) = early {
7669                rename_expr(expr)?;
7670            }
7671            if let Some(expr) = residual {
7672                rename_expr(expr)?;
7673            }
7674            for clause in exists {
7675                for variable in &mut clause.correlation {
7676                    if variable == old {
7677                        *variable = fresh.clone();
7678                    }
7679                }
7680                rename_variable_in_subtree(&mut clause.body, old, fresh)?;
7681            }
7682        }
7683        PlanNode::Union { left, right } => {
7684            rename_variable_in_subtree(left, old, fresh)?;
7685            rename_variable_in_subtree(right, old, fresh)?;
7686        }
7687        PlanNode::Unit | PlanNode::NamedGraphExists { .. } => {}
7688        PlanNode::Values(values) => {
7689            for variable in &mut values.variables {
7690                if variable == old {
7691                    *variable = fresh.clone();
7692                }
7693            }
7694        }
7695        PlanNode::NamedGraphs { variable, .. } => {
7696            if variable == old {
7697                *variable = fresh.clone();
7698            }
7699        }
7700        PlanNode::Extend {
7701            inner,
7702            variable,
7703            expression,
7704            ..
7705        } => {
7706            rename_variable_in_subtree(inner, old, fresh)?;
7707            if variable == old {
7708                *variable = fresh.clone();
7709            }
7710            rename_expr(expression)?;
7711        }
7712        PlanNode::Slice { inner, .. } => rename_variable_in_subtree(inner, old, fresh)?,
7713        PlanNode::JoinGraphVar {
7714            inner,
7715            graph_var,
7716            active_var,
7717            ..
7718        } => {
7719            rename_variable_in_subtree(inner, old, fresh)?;
7720            if graph_var == old {
7721                *graph_var = fresh.clone();
7722            }
7723            if active_var == old {
7724                *active_var = fresh.clone();
7725            }
7726        }
7727        PlanNode::Distinct { inner, columns } => {
7728            rename_variable_in_subtree(inner, old, fresh)?;
7729            for column in &mut *columns {
7730                if column == old {
7731                    *column = fresh.clone();
7732                }
7733            }
7734        }
7735        PlanNode::Sort { inner, keys } => {
7736            rename_variable_in_subtree(inner, old, fresh)?;
7737            for key in keys {
7738                rename_expr(&mut key.expression)?;
7739            }
7740        }
7741        PlanNode::Group {
7742            inner,
7743            variables,
7744            aggregates,
7745            ..
7746        } => {
7747            rename_variable_in_subtree(inner, old, fresh)?;
7748            for key in &mut *variables {
7749                if key == old {
7750                    *key = fresh.clone();
7751                }
7752            }
7753            for (result, agg) in &mut *aggregates {
7754                if result == old {
7755                    *result = fresh.clone();
7756                }
7757                if let AggregateExpression::FunctionCall { expr, .. } = agg {
7758                    rename_expr(expr)?;
7759                }
7760            }
7761        }
7762        PlanNode::SubSelect(sub) => {
7763            let projects_old = sub.variables.iter().any(|variable| variable == old);
7764            for variable in &mut sub.variables {
7765                if variable == old {
7766                    *variable = fresh.clone();
7767                }
7768            }
7769            if projects_old {
7770                rename_variable_in_subtree(&mut sub.inner, old, fresh)?;
7771            }
7772        }
7773        PlanNode::DomainCounts {
7774            head, count, dead, ..
7775        } => {
7776            if head == old {
7777                *head = fresh.clone();
7778            }
7779            if count == old {
7780                *count = fresh.clone();
7781            }
7782            if let Some(slot) = dead
7783                && slot == old
7784            {
7785                *slot = fresh.clone();
7786            }
7787        }
7788        PlanNode::HeadCounts {
7789            counted,
7790            group,
7791            count,
7792            ..
7793        } => {
7794            if counted == old {
7795                *counted = fresh.clone();
7796            }
7797            if let Some(group) = group
7798                && group == old
7799            {
7800                *group = fresh.clone();
7801            }
7802            if count == old {
7803                *count = fresh.clone();
7804            }
7805        }
7806        PlanNode::PatternCount {
7807            subject,
7808            predicate,
7809            object,
7810            count,
7811            counted,
7812            ..
7813        } => {
7814            for slot in [subject, predicate, object] {
7815                if slot.as_ref() == Some(old) {
7816                    *slot = Some(fresh.clone());
7817                }
7818            }
7819            if count == old {
7820                *count = fresh.clone();
7821            }
7822            if let Some(counted) = counted
7823                && counted == old
7824            {
7825                *counted = fresh.clone();
7826            }
7827        }
7828    }
7829    Ok(())
7830}
7831
7832/// Rewrite variable references inside a subquery expression to the renamed
7833/// scope names.
7834fn rename_expression_scope(
7835    expression: &mut Expression,
7836    projection: &[Variable],
7837    prefix: &str,
7838) -> Result<(), ComputeError> {
7839    rewrite_expression_vars(expression, &|variable| {
7840        scope_rename(variable, projection, prefix)
7841    })
7842}
7843
7844/// Rename one specific variable inside a subquery expression — the
7845/// expression half of [`rename_variable_in_subtree`].
7846fn rename_expression_variable(
7847    expression: &mut Expression,
7848    old: &Variable,
7849    fresh: &Variable,
7850) -> Result<(), ComputeError> {
7851    rewrite_expression_vars(expression, &|variable| {
7852        (variable == old).then(|| fresh.clone())
7853    })
7854}
7855
7856/// Apply a variable mapping through every reference in `expression`.
7857/// `EXISTS` embeds an unlowered [`GraphPattern`] that this pass cannot
7858/// traverse, so it is rejected (it is unsupported everywhere else too).
7859fn rewrite_expression_vars(
7860    expression: &mut Expression,
7861    rename: &dyn Fn(&Variable) -> Option<Variable>,
7862) -> Result<(), ComputeError> {
7863    match expression {
7864        Expression::NamedNode(_) | Expression::Literal(_) => {}
7865        Expression::Variable(variable) => {
7866            if let Some(fresh) = rename(variable) {
7867                *variable = fresh;
7868            }
7869        }
7870        Expression::Bound(variable) => {
7871            if let Some(fresh) = rename(variable) {
7872                *variable = fresh;
7873            }
7874        }
7875        Expression::Or(a, b)
7876        | Expression::And(a, b)
7877        | Expression::Equal(a, b)
7878        | Expression::SameTerm(a, b)
7879        | Expression::Greater(a, b)
7880        | Expression::GreaterOrEqual(a, b)
7881        | Expression::Less(a, b)
7882        | Expression::LessOrEqual(a, b)
7883        | Expression::Add(a, b)
7884        | Expression::Subtract(a, b)
7885        | Expression::Multiply(a, b)
7886        | Expression::Divide(a, b) => {
7887            rewrite_expression_vars(a, rename)?;
7888            rewrite_expression_vars(b, rename)?;
7889        }
7890        Expression::In(left, args) => {
7891            rewrite_expression_vars(left, rename)?;
7892            for arg in args {
7893                rewrite_expression_vars(arg, rename)?;
7894            }
7895        }
7896        Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) | Expression::Not(inner) => {
7897            rewrite_expression_vars(inner, rename)?;
7898        }
7899        Expression::Exists(_) => {
7900            return Err(ComputeError::UnsupportedSparql(
7901                "EXISTS inside a sub-SELECT is not supported".into(),
7902            ));
7903        }
7904        Expression::If(condition, then_branch, else_branch) => {
7905            rewrite_expression_vars(condition, rename)?;
7906            rewrite_expression_vars(then_branch, rename)?;
7907            rewrite_expression_vars(else_branch, rename)?;
7908        }
7909        Expression::Coalesce(args) | Expression::FunctionCall(_, args) => {
7910            for arg in args {
7911                rewrite_expression_vars(arg, rename)?;
7912            }
7913        }
7914    }
7915    Ok(())
7916}
7917
7918fn graph_scope_for_name(
7919    name: &NamedNodePattern,
7920    dataset: &QueryDataset,
7921) -> Result<GraphScope, ComputeError> {
7922    Ok(match name {
7923        NamedNodePattern::NamedNode(node) => {
7924            GraphScope::named_iri(EncodedTerm::from(node), dataset)
7925        }
7926        NamedNodePattern::Variable(variable) => GraphScope::named_var(variable.clone(), dataset),
7927    })
7928}
7929
7930/// When `P` uses the GRAPH variable as a term, collect G into a fresh
7931/// `active_var` so SPARQL `?g` is not a solution variable of `P`.
7932fn graph_lower_scope(
7933    inner: &GraphPattern,
7934    scope: GraphScope,
7935) -> (GraphScope, Option<(Variable, Variable)>) {
7936    let GraphScope::NamedVar { variable, window } = &scope else {
7937        return (scope, None);
7938    };
7939    if !pattern_mentions_graph_var(inner, variable) {
7940        return (scope, None);
7941    }
7942    let active_var = mint_graph_active_var(variable);
7943    (
7944        GraphScope::NamedVar {
7945            variable: active_var.clone(),
7946            window: window.clone(),
7947        },
7948        Some((variable.clone(), active_var)),
7949    )
7950}
7951
7952/// Empty `GRAPH <iri> { }` under engine-default named set: catalog membership
7953/// is not known at plan time.
7954fn named_graph_exists_for_unit(
7955    inner: &PlanNode,
7956    scope: &GraphScope,
7957    dataset: &QueryDataset,
7958) -> Option<PlanNode> {
7959    if !matches!(inner, PlanNode::Unit) {
7960        return None;
7961    }
7962    if !matches!(dataset.named, NamedGraphWindow::EngineAllNamed) {
7963        return None;
7964    }
7965    match scope {
7966        GraphScope::NamedIri(graph) => Some(PlanNode::NamedGraphExists {
7967            graph: graph.clone(),
7968        }),
7969        _ => None,
7970    }
7971}
7972
7973/// `?g` appears as a term / VALUES / BIND / FILTER variable inside `P`, not
7974/// as this `GRAPH` node's name. Nested `GRAPH ?h` names are their own scope.
7975fn pattern_mentions_graph_var(pattern: &GraphPattern, var: &Variable) -> bool {
7976    match pattern {
7977        GraphPattern::Bgp { patterns } => patterns.iter().any(|triple| {
7978            term_pattern_mentions(&triple.subject, var)
7979                || named_node_pattern_mentions(&triple.predicate, var)
7980                || term_pattern_mentions(&triple.object, var)
7981        }),
7982        GraphPattern::Path {
7983            subject, object, ..
7984        } => term_pattern_mentions(subject, var) || term_pattern_mentions(object, var),
7985        GraphPattern::Join { left, right }
7986        | GraphPattern::Union { left, right }
7987        | GraphPattern::Minus { left, right } => {
7988            pattern_mentions_graph_var(left, var) || pattern_mentions_graph_var(right, var)
7989        }
7990        GraphPattern::LeftJoin {
7991            left,
7992            right,
7993            expression,
7994        } => {
7995            pattern_mentions_graph_var(left, var)
7996                || pattern_mentions_graph_var(right, var)
7997                || expression
7998                    .as_ref()
7999                    .is_some_and(|expr| variables_in_expression(expr).contains(var))
8000        }
8001        GraphPattern::Filter { expr, inner } => {
8002            variables_in_expression(expr).contains(var) || pattern_mentions_graph_var(inner, var)
8003        }
8004        GraphPattern::Graph { inner, .. }
8005        | GraphPattern::Service { inner, .. }
8006        | GraphPattern::Slice { inner, .. }
8007        | GraphPattern::Distinct { inner }
8008        | GraphPattern::Reduced { inner }
8009        | GraphPattern::Project { inner, .. }
8010        | GraphPattern::OrderBy { inner, .. } => pattern_mentions_graph_var(inner, var),
8011        GraphPattern::Extend {
8012            inner,
8013            variable,
8014            expression,
8015        } => {
8016            variable == var
8017                || variables_in_expression(expression).contains(var)
8018                || pattern_mentions_graph_var(inner, var)
8019        }
8020        GraphPattern::Values { variables, .. } => variables.contains(var),
8021        GraphPattern::Group {
8022            inner, variables, ..
8023        } => variables.contains(var) || pattern_mentions_graph_var(inner, var),
8024    }
8025}
8026
8027fn term_pattern_mentions(term: &TermPattern, var: &Variable) -> bool {
8028    matches!(term, TermPattern::Variable(v) if v == var)
8029}
8030
8031fn named_node_pattern_mentions(name: &NamedNodePattern, var: &Variable) -> bool {
8032    matches!(name, NamedNodePattern::Variable(v) if v == var)
8033}
8034
8035/// Hidden G-slot name: `gact_<16 random chars>_<user>`. Same collision
8036/// rationale as [`mint_scope_prefix`].
8037fn mint_graph_active_var(variable: &Variable) -> Variable {
8038    let sq = mint_scope_prefix();
8039    Variable::new_unchecked(format!(
8040        "gact_{}{}",
8041        sq.strip_prefix("sq_").unwrap_or(&sq),
8042        variable.as_str()
8043    ))
8044}
8045
8046fn empty_plan_like(inner: &PlanNode, scope: &GraphScope) -> PlanNode {
8047    let mut variables = inner.variables();
8048    if let GraphScope::NamedVar { variable, .. } = scope
8049        && !variables.contains(variable)
8050    {
8051        variables.push(variable.clone());
8052    }
8053    PlanNode::Values(ValuesOp {
8054        variables,
8055        rows: Vec::new(),
8056        strings: Vec::new(),
8057        blobs: Vec::new(),
8058    })
8059}
8060
8061/// Attach a named-graph domain when `GRAPH ?g { P }` does not always bind `?g`.
8062///
8063/// SPARQL iterates the named dataset and sets `?g = v` on each evaluation of
8064/// `P` in graph `v`. Scans/paths already project this `?g`; VALUES / BIND /
8065/// empty group / nested GRAPH that binds a different variable do not.
8066/// `FROM NAMED` becomes a plan-time VALUES table (no catalog RPC). Engine
8067/// Collect uses [`PlanNode::NamedGraphs`] at execute time. Empty group
8068/// (`PlanNode::Unit`) is the domain alone — Collect is no longer rewritten
8069/// to 0-row VALUES.
8070/// This is used for `GRAPH ?g { }` and `GRAPH <G> { }` patterns with no catalog
8071/// as well as scan-free inner patterns.
8072fn attach_graph_domain(
8073    inner: PlanNode,
8074    scope: &GraphScope,
8075    profile: Option<&StatsProfile>,
8076    dataset: &QueryDataset,
8077) -> Result<PlanNode, ComputeError> {
8078    let GraphScope::NamedVar { variable, window } = scope else {
8079        return Ok(inner);
8080    };
8081    // Push the domain under FILTER when the child never binds `?g`, so
8082    // `GRAPH ?g { FILTER(?g = :x) }` sees `?g` from the domain. FILTER wrapping
8083    // a BGP still always-binds `?g` and must not cartesian-join the domain.
8084    let inner = if let PlanNode::Filter {
8085        inner: filter_inner,
8086        early,
8087        residual,
8088        exists,
8089        one_to_one,
8090    } = inner
8091    {
8092        if !filter_inner.output_vars().contains(variable) {
8093            let attached = attach_graph_domain(*filter_inner, scope, profile, dataset)?;
8094            return Ok(PlanNode::Filter {
8095                inner: Box::new(attached),
8096                early,
8097                residual,
8098                exists,
8099                one_to_one,
8100            });
8101        }
8102        PlanNode::Filter {
8103            inner: filter_inner,
8104            early,
8105            residual,
8106            exists,
8107            one_to_one,
8108        }
8109    } else {
8110        inner
8111    };
8112    let domain = graph_domain(variable, window, dataset, profile)?;
8113    if matches!(inner, PlanNode::Unit) {
8114        return Ok(domain);
8115    }
8116    let vars = inner.output_vars();
8117    if vars.is_always_bound(variable) {
8118        return Ok(inner);
8119    }
8120    if !vars.contains(variable) {
8121        return Ok(join_nodes(domain, inner, profile));
8122    }
8123    // Maybe-unbound (`OPTIONAL`): SPARQL still emits one row per named graph.
8124    // `GRAPH ?g { OPTIONAL { BGP } }` lowers to LeftJoin(Unit, Scan). Flatten
8125    // the Unit left so the shape is LeftJoin(Domain, Scan) on `?g`, not
8126    // Join(Domain, LeftJoin(Unit, Scan)) (OPTIONAL miss would have no `?g`).
8127    let (mut right, early_filter, residual_filter) = flatten_unit_left_join(inner);
8128    let hash_keys = vec![variable.clone()];
8129    ground_and_recost_broadcasted_arm(&domain, &mut right, &hash_keys, profile);
8130    compose_graph_from_sibling(&domain, &mut right, &hash_keys, profile, true);
8131    let meta = stamp_left_join_meta(
8132        domain.produced_row_count_estimate(),
8133        &domain,
8134        &right,
8135        &hash_keys,
8136        profile,
8137    );
8138    let probe_key_domains = stamp_probe_key_domains(profile, &right, &hash_keys);
8139    let probe_key_overlap_milli = stamp_probe_key_overlaps(profile, &domain, &right, &hash_keys);
8140    Ok(PlanNode::LeftJoin {
8141        left: Box::new(domain),
8142        right: Box::new(right),
8143        hash_keys,
8144        early_filter,
8145        residual_filter,
8146        probe_key_domains,
8147        probe_key_overlap_milli,
8148        meta,
8149    })
8150}
8151
8152/// `GRAPH ?g { OPTIONAL { P } }` is LeftJoin(Unit, P). Drop the Unit left so
8153/// the GRAPH domain can be the required side.
8154fn flatten_unit_left_join(inner: PlanNode) -> (PlanNode, Option<Expression>, Option<Expression>) {
8155    match inner {
8156        PlanNode::LeftJoin {
8157            left,
8158            right,
8159            early_filter,
8160            residual_filter,
8161            ..
8162        } if matches!(left.as_ref(), PlanNode::Unit) => (*right, early_filter, residual_filter),
8163        other => (other, None, None),
8164    }
8165}
8166
8167fn graph_domain(
8168    variable: &Variable,
8169    window: &NamedVarWindow,
8170    dataset: &QueryDataset,
8171    profile: Option<&StatsProfile>,
8172) -> Result<PlanNode, ComputeError> {
8173    match window {
8174        NamedVarWindow::Collect => Ok(PlanNode::NamedGraphs {
8175            variable: variable.clone(),
8176            produced_row_count_estimate: named_graphs_estimated_rows(profile),
8177        }),
8178        NamedVarWindow::Ground(term) => {
8179            graph_domain_values(variable, std::slice::from_ref(term), &dataset.named_strings)
8180        }
8181        NamedVarWindow::Allow(filter) => {
8182            graph_domain_values(variable, filter.terms(), &dataset.named_strings)
8183        }
8184    }
8185}
8186
8187fn graph_domain_values(
8188    variable: &Variable,
8189    terms: &[EncodedTerm],
8190    named_strings: &[(StrHash, String)],
8191) -> Result<PlanNode, ComputeError> {
8192    if terms.len() > GRAPH_FILTER_TERM_CAP as usize {
8193        return Err(ComputeError::UnsupportedSparql(format!(
8194            "FROM NAMED / named-graph-uri list exceeds {GRAPH_FILTER_TERM_CAP} graphs"
8195        )));
8196    }
8197    Ok(PlanNode::Values(ValuesOp {
8198        variables: vec![variable.clone()],
8199        rows: terms.iter().cloned().map(|term| vec![Some(term)]).collect(),
8200        strings: named_strings.to_vec(),
8201        blobs: Vec::new(),
8202    }))
8203}
8204
8205fn empty_pipeline_values(leaves: &[FlatLeaf], scope: &GraphScope) -> PlanNode {
8206    let mut variables = Vec::new();
8207    for leaf in leaves {
8208        match leaf {
8209            FlatLeaf::Triple(pattern)
8210            | FlatLeaf::FilteredTriple {
8211                triple: pattern, ..
8212            } => {
8213                if let TermPattern::Variable(v) = &pattern.subject
8214                    && !variables.contains(v)
8215                {
8216                    variables.push(v.clone());
8217                }
8218                if let NamedNodePattern::Variable(v) = &pattern.predicate
8219                    && !variables.contains(v)
8220                {
8221                    variables.push(v.clone());
8222                }
8223                if let TermPattern::Variable(v) = &pattern.object
8224                    && !variables.contains(v)
8225                {
8226                    variables.push(v.clone());
8227                }
8228            }
8229            FlatLeaf::Values {
8230                variables: vars, ..
8231            } => {
8232                for v in vars {
8233                    if !variables.contains(v) {
8234                        variables.push(v.clone());
8235                    }
8236                }
8237            }
8238            FlatLeaf::Path {
8239                subject, object, ..
8240            } => {
8241                for term in [subject, object] {
8242                    if let TermPattern::Variable(v) = term
8243                        && !variables.contains(v)
8244                    {
8245                        variables.push(v.clone());
8246                    }
8247                }
8248            }
8249        }
8250    }
8251    if let GraphScope::NamedVar { variable, .. } = scope
8252        && !variables.contains(variable)
8253    {
8254        variables.push(variable.clone());
8255    }
8256    PlanNode::Values(ValuesOp {
8257        variables,
8258        rows: Vec::new(),
8259        strings: Vec::new(),
8260        blobs: Vec::new(),
8261    })
8262}
8263
8264/// One flattenable inner-join leaf: a triple pattern, VALUES table, or path.
8265enum FlatLeaf {
8266    Triple(TriplePattern),
8267    /// One triple with a FILTER that sparopt pushed onto it. Kept as one
8268    /// orderable leaf: the scan is the read and the expression is applied by
8269    /// `lower_leaf` after it. The sort key is the scan's estimate — the
8270    /// filter's selectivity is not known before the plugin rewrites, so the
8271    /// leaf orders like its unfiltered scan.
8272    FilteredTriple {
8273        triple: TriplePattern,
8274        expression: Expression,
8275    },
8276    Values {
8277        variables: Vec<Variable>,
8278        bindings: Vec<Vec<Option<GroundTerm>>>,
8279    },
8280    Path {
8281        subject: TermPattern,
8282        path: PropertyPathExpression,
8283        object: TermPattern,
8284    },
8285}
8286
8287/// True when `pattern` is a tree of inner Joins over BGPs, VALUES, paths, and
8288/// single-triple FILTERs (a pushed filter over one scan is still a leaf).
8289fn collect_flat_leaves(pattern: &GraphPattern, out: &mut Vec<FlatLeaf>) -> bool {
8290    match pattern {
8291        GraphPattern::Bgp { patterns } => {
8292            out.extend(patterns.iter().cloned().map(FlatLeaf::Triple));
8293            true
8294        }
8295        GraphPattern::Filter { expr, inner } => match inner.as_ref() {
8296            // A filter pushed onto one triple is still a flat leaf: the scan
8297            // is the read and the expression rides it. EXISTS bodies are
8298            // separate patterns and keep the general lowering path.
8299            GraphPattern::Bgp { patterns }
8300                if patterns.len() == 1 && !expression_contains_exists(expr) =>
8301            {
8302                out.push(FlatLeaf::FilteredTriple {
8303                    triple: patterns[0].clone(),
8304                    expression: expr.clone(),
8305                });
8306                true
8307            }
8308            _ => false,
8309        },
8310        GraphPattern::Values {
8311            variables,
8312            bindings,
8313        } => {
8314            out.push(FlatLeaf::Values {
8315                variables: variables.clone(),
8316                bindings: bindings.clone(),
8317            });
8318            true
8319        }
8320        GraphPattern::Path {
8321            subject,
8322            path,
8323            object,
8324        } => {
8325            out.push(FlatLeaf::Path {
8326                subject: subject.clone(),
8327                path: path.clone(),
8328                object: object.clone(),
8329            });
8330            true
8331        }
8332        GraphPattern::Join { left, right } => {
8333            collect_flat_leaves(left, out) && collect_flat_leaves(right, out)
8334        }
8335        _ => false,
8336    }
8337}
8338
8339fn order_pipeline_leaves(
8340    leaves: Vec<FlatLeaf>,
8341    profile: Option<&StatsProfile>,
8342    incoming: &IncomingBound,
8343    ctx: &QueryContext,
8344    scope: &GraphScope,
8345) -> Result<Vec<FlatLeaf>, ComputeError> {
8346    let mut keyed = Vec::with_capacity(leaves.len());
8347    for leaf in leaves {
8348        let (rows, bound, incoming_slots) = leaf_sort_key(&leaf, profile, incoming, ctx, scope)?;
8349        keyed.push((leaf, rows, bound, incoming_slots));
8350    }
8351    keyed.sort_by(|a, b| {
8352        a.1.cmp(&b.1)
8353            .then_with(|| b.2.cmp(&a.2))
8354            .then_with(|| b.3.cmp(&a.3))
8355    });
8356    Ok(keyed.into_iter().map(|(leaf, _, _, _)| leaf).collect())
8357}
8358
8359fn leaf_sort_key(
8360    leaf: &FlatLeaf,
8361    profile: Option<&StatsProfile>,
8362    incoming: &IncomingBound,
8363    ctx: &QueryContext,
8364    scope: &GraphScope,
8365) -> Result<(u64, usize, usize), ComputeError> {
8366    Ok(match leaf {
8367        FlatLeaf::Triple(pattern)
8368        | FlatLeaf::FilteredTriple {
8369            triple: pattern, ..
8370        } => {
8371            let scan = plan_scan_op(pattern, profile, incoming, ctx, scope)?;
8372            let extra = extra_bound_slots_for(
8373                &scan.subject,
8374                &scan.predicate,
8375                &scan.object,
8376                &scan.graph,
8377                incoming,
8378            );
8379            (
8380                scan.produced_row_count_estimate,
8381                bound_slots(&scan.pattern) + extra.count(),
8382                extra.count(),
8383            )
8384        }
8385        FlatLeaf::Values { bindings, .. } => (bindings.len() as u64, 3, 0),
8386        FlatLeaf::Path {
8387            subject,
8388            path,
8389            object,
8390        } => {
8391            let path_node = lower_path(subject, path, object, profile, incoming, ctx, scope)?;
8392            let PlanNode::Path(op) = path_node else {
8393                unreachable!("lower_path returns Path");
8394            };
8395            let incoming_ends = usize::from(term_incoming_bound(subject, incoming))
8396                + usize::from(term_incoming_bound(object, incoming));
8397            (
8398                op.produced_row_count_estimate,
8399                op.bound_ends() + incoming_ends,
8400                incoming_ends,
8401            )
8402        }
8403    })
8404}
8405
8406fn lower_pipeline(
8407    leaves: Vec<FlatLeaf>,
8408    profile: Option<&StatsProfile>,
8409    incoming: &IncomingBound,
8410    ctx: &QueryContext,
8411    scope: &GraphScope,
8412) -> Result<PlanNode, ComputeError> {
8413    // Missing named graph (`GRAPH <not-in-FROM-NAMED>` / empty named window):
8414    // the whole GRAPH block has no solutions, including inner VALUES.
8415    if matches!(scope, GraphScope::Empty) {
8416        return Ok(empty_pipeline_values(&leaves, scope));
8417    }
8418    if leaves.is_empty() {
8419        return Ok(PlanNode::Unit);
8420    }
8421    let default_empty = matches!(scope, GraphScope::Default)
8422        && matches!(ctx.dataset().default, DefaultGraphWindow::Empty);
8423    let ordered = order_pipeline_leaves(leaves, profile, incoming, ctx, scope)?;
8424    let mut nodes = Vec::with_capacity(ordered.len());
8425    for leaf in ordered {
8426        nodes.push(lower_leaf(
8427            leaf,
8428            profile,
8429            incoming,
8430            ctx,
8431            scope,
8432            default_empty,
8433        )?);
8434    }
8435    // sparopt encodes the empty group `{ }` as a zero-column VALUES singleton.
8436    // That is the join identity (`Unit`); drop it when real leaves exist.
8437    nodes.retain(|node| !matches!(node, PlanNode::Unit));
8438    if nodes.is_empty() {
8439        return Ok(PlanNode::Unit);
8440    }
8441    let mut node = nodes.remove(0);
8442    for right in nodes {
8443        node = join_nodes(node, right, profile);
8444    }
8445    Ok(node)
8446}
8447
8448/// Which arm of a candidate pair drives: the arm whose seating cost wins, or
8449/// on a band tie the arm the legacy `(driver cost, row count)` rule puts
8450/// first. Returns true when the tag-order first arm should be on the left.
8451///
8452/// The pair pre-pass uses this to BUILD the pair in the orientation it priced,
8453/// instead of falling back to tag order and leaving the orientation to the
8454/// later arm swap. The swap keeps the as-built on a band tie, so a tag-order
8455/// build can survive with the expensive arm driving.
8456fn pair_first_drives(
8457    profile: Option<&StatsProfile>,
8458    first: &PlanNode,
8459    second: &PlanNode,
8460    hash_keys: &[Variable],
8461    first_cost: SeatCost,
8462    second_cost: SeatCost,
8463) -> bool {
8464    if seat_beats(second_cost, first_cost) {
8465        return false;
8466    }
8467    if seat_beats(first_cost, second_cost) {
8468        return true;
8469    }
8470    // Band tie: the seat totals are indistinguishable. Use the legacy
8471    // driver-cost order — the seating the arm swap would keep.
8472    let first_rows = driver_whole_read_rows(first, hash_keys, profile);
8473    let second_rows = driver_whole_read_rows(second, hash_keys, profile);
8474    let first_domain =
8475        join_key_domain_for_allow_list(profile, first, second, hash_keys, first_rows);
8476    let second_domain =
8477        join_key_domain_for_allow_list(profile, second, first, hash_keys, second_rows);
8478    (driver_cost(first_rows, first_domain), first_rows)
8479        <= (driver_cost(second_rows, second_domain), second_rows)
8480}
8481
8482/// Whether start b is the same association AND orientation as start a's first
8483/// attachment: the pair's left arm is the seed, and the seed's first
8484/// attachment is the pair's other arm. A pair built with the seed on the
8485/// right is a different seating of the same association and must be run and
8486/// compared. The check is the pair's BUILT orientation, never tag order.
8487fn pair_start_matches_seed_start(
8488    pair_first: usize,
8489    seed_idx: usize,
8490    first_candidate_tag: Option<&str>,
8491    other_tag: &str,
8492) -> bool {
8493    first_candidate_tag == Some(other_tag) && pair_first == seed_idx
8494}
8495
8496/// Cost-based greedy association: build a left-deep tree one join at a time,
8497/// repeatedly attaching whichever remaining operand yields the smallest
8498/// estimated join output. Used by [`reassociate_inner_joins`] to rebuild flat
8499/// inner-join chains after identity folding, when the scans carry their
8500/// grounds and the leaf prices are final for this stage.
8501///
8502/// Every association of the same inner-join operands returns the identical
8503/// result multiset (joins are commutative and associative), so a wrong pick
8504/// costs performance, never results — though it can cost real performance:
8505/// the picked association decides which broadcast claims are reachable, so
8506/// the comparison below must weigh cartesian products against connected
8507/// joins on one scale. Candidates are costed with the same
8508/// [`finalize_inner_join_meta`] that stamps the committed join's meta, so
8509/// the selection metric and the plan's estimates cannot disagree; the commit
8510/// itself goes through [`join_nodes`], which still owns hash keys, swap
8511/// checks, zero-row substitution, Broadcast grounding, and graph
8512/// composition — the greedy chooses which operand joins next, never how.
8513///
8514/// There is no connected-first veto: a candidate sharing no always-bound
8515/// variable with the accumulator is a cartesian product, and
8516/// `finalize_inner_join_meta` prices it as such (`|L| × |R|`), so a cheap
8517/// cartesian legitimately beats an expensive connected join. On the
8518/// worked-example shape (two small type scans joined by a high-fan-out
8519/// edge), that is what preserves the 5 × 100 cartesian driver whose probe
8520/// broadcasts ~200 rows instead of the connected association whose probe broadcasts
8521/// ~9,800. Without a profile a connected candidate prices at
8522/// `min(|L|,|R|) ≤ |L|·|R|`, so connected-first falls out of the arithmetic
8523/// and the order degenerates to the tag-sorted fallback, ties resolved by
8524/// strict `<` on the earliest candidate.
8525///
8526/// Under `--seat-by-total-cost` (`QueryContext::seat_by_total_cost`) the
8527/// pick asks two questions instead of one, each on the scale where that
8528/// question is meaningful — which is how the one-scale requirement above
8529/// survives the currency change: every individual comparison stays
8530/// single-scale, the two scales just answer different questions:
8531///
8532/// 1. ELIGIBILITY — "how big does the accumulator become?" — stays on the
8533///    estimated-output scale. This is the explosion-aware currency:
8534///    downstream joins, the hash product's CPU, and the pages holding the
8535///    intermediate all scale with the accumulator's row count, and a join
8536///    can read very little while producing an enormous intermediate (a
8537///    cartesian reads both sides once and multiplies; a keyed fan-out
8538///    streams a small driver through a wide probe). Any candidate whose
8539///    produced estimate exceeds the best candidate's by more than
8540///    [`SEAT_ASSOC_EXPLOSION_GUARD`] is disqualified outright, whatever it
8541///    reads. The plan-estimate coherence above (candidates costed with the
8542///    same `finalize_inner_join_meta` that stamps the committed join) is
8543///    preserved here: the bar and every eligibility verdict read exactly
8544///    the number the plan will claim.
8545/// 2. RANKING — "what does executing this join actually read?" — moves to
8546///    [`seat_cost_total`] (rows fetched + index seeks, the same comparator
8547///    the `refinalize_joins` arm swap uses), priced under the seating that
8548///    later pass will keep: both orientations are priced and the
8549///    `seat_beats` survivor ranks. The survivor is the honest currency
8550///    because the swap can flip an edge but can never re-attach a
8551///    different operand — the association is permanent, so it must be
8552///    bought with the price of the orientation that will actually run.
8553///    Output rows and
8554///    fetch work genuinely disagree: the per-page refetch of a selective
8555///    probe reads far more than its contribution to the output, and a
8556///    dropped (built-once) probe reads its whole arm once while adding
8557///    nothing per page. Ranking on output rows alone can therefore attach
8558///    the arm whose execution re-fetches on every driver page, and the
8559///    arm swap cannot always recover — it only re-orients joins inside
8560///    the tree this association pass chose.
8561///
8562/// WHY cartesians rank on a different cost than keyed candidates: the seating-cost
8563/// model's per-page machinery exists because of join keys — a key is what
8564/// turns a driver page into a pushed allow-list that filters the probe.
8565/// With no shared variable there is nothing to push, and
8566/// `seat_cost_total` degenerates to "read both sides once" — a fetch
8567/// statement that is blind to the product. That blindness is exactly why
8568/// eligibility runs FIRST: a cartesian survivor has already passed the
8569/// `|L|×|R|` explosion gate, so among survivors "which reads least?" is
8570/// the remaining question, and read-both-sides is its honest answer, on
8571/// the same rows-fetch scale the keyed survivors are ranked on. Comparing
8572/// a cartesian's product against a keyed join's rows-read in one `min()`
8573/// would ask an unanswerable question (is producing 10M rows cheaper
8574/// than reading 200k?); the two-question structure keeps that from ever
8575/// being asked.
8576///
8577/// Tie handling is unchanged in spirit: strict `<` on the output scale
8578/// keeps the earliest tag-sorted candidate, and the cost ranking reuses
8579/// [`seat_beats`] — the swap layer's noise band — so a challenger must
8580/// read fewer rows (outside the band) or match rows and strictly fewer
8581/// seeks to displace an earlier candidate, and band ties keep the
8582/// tag-sorted order too.
8583fn associate_cost_based(
8584    nodes: Vec<JoinableSpineNode>,
8585    profile: Option<&StatsProfile>,
8586    ctx: Option<&crate::context::QueryContext>,
8587) -> PlanNode {
8588    if nodes.len() < 2 {
8589        return nodes
8590            .into_iter()
8591            .next()
8592            .map(JoinableSpineNode::into_plan)
8593            .unwrap_or(PlanNode::Unit);
8594    }
8595    let seat_by_totals = ctx.is_some_and(crate::context::QueryContext::seat_by_total_cost);
8596    // Stable structural keys: neither the start selection nor the candidate
8597    // ties may depend on the order flatten_join_spine produced.
8598    let tags: Vec<String> = nodes
8599        .iter()
8600        .map(|node| crate::explain::plan_node_tag(node.as_plan()))
8601        .collect();
8602    let produced = |idx: usize| nodes[idx].as_plan().produced_row_count_estimate();
8603    // Start a: the smallest final produced operand, with a VALUES table
8604    // winning a produced tie. This is the pre-sort's intent, applied after
8605    // the plugin rewrites and over all operands.
8606    let values_first = |idx: usize| u8::from(!matches!(nodes[idx].as_plan(), PlanNode::Values(_)));
8607    let min_idx = (0..nodes.len())
8608        .min_by(|&i, &j| {
8609            produced(i)
8610                .cmp(&produced(j))
8611                .then_with(|| values_first(i).cmp(&values_first(j)))
8612                .then_with(|| tags[i].cmp(&tags[j]))
8613        })
8614        .expect("nodes is non-empty");
8615    let mut min_remaining = Vec::with_capacity(nodes.len() - 1);
8616    for (idx, node) in nodes.iter().enumerate() {
8617        if idx != min_idx {
8618            min_remaining.push(node.clone());
8619        }
8620    }
8621    let (plan_a, total_a, first_candidate_a) = associate_from_seed(
8622        nodes[min_idx].clone().into_plan(),
8623        min_remaining,
8624        profile,
8625        ctx,
8626        seat_by_totals,
8627    );
8628    // Non-total-cost mode takes no decision from a seating cost. Comparing two
8629    // associations needs a work model: a produced aggregate over the chain is
8630    // decided by the inner joins (the root output is the same for every
8631    // association) and prefers the smaller-intermediate association. That is
8632    // the wrong choice when the association's advantage is the probe
8633    // direction — the tuned ?ds/?sub cartesian has the smaller intermediate
8634    // sum, but its pair start reads a ?sub-driven domain, which is why the
8635    // seat comparison keeps the cartesian. Nothing on the produced scale sees
8636    // that, so this mode builds one association from the seed rules and keeps
8637    // it; the pair start and the comparison are total-cost-mode machinery.
8638    if !seat_by_totals {
8639        return plan_a;
8640    }
8641    let pair_order = |i: usize, j: usize| {
8642        if tags[i] <= tags[j] { (i, j) } else { (j, i) }
8643    };
8644    let pair_tags_less = |i: usize, j: usize, oi: usize, oj: usize| {
8645        let (a, b) = pair_order(i, j);
8646        let (c, d) = pair_order(oi, oj);
8647        (tags[a].as_str(), tags[b].as_str()) < (tags[c].as_str(), tags[d].as_str())
8648    };
8649    // Start b's pair: the eligibility-guarded cheapest pair on the surviving
8650    // seating. The produced bar bounds the cost walk.
8651    let mut pair_produced: Vec<(usize, usize, u64)> =
8652        Vec::with_capacity(nodes.len() * (nodes.len() - 1) / 2);
8653    let mut bar = u64::MAX;
8654    for i in 0..nodes.len() {
8655        for j in (i + 1)..nodes.len() {
8656            let (a, b) = pair_order(i, j);
8657            let keys = hash_keys_for(
8658                &nodes[a].as_plan().output_vars(),
8659                &nodes[b].as_plan().output_vars(),
8660            );
8661            let rows =
8662                finalize_inner_join_meta(nodes[a].as_plan(), nodes[b].as_plan(), &keys, profile).1;
8663            pair_produced.push((i, j, rows));
8664            bar = bar.min(rows);
8665        }
8666    }
8667    let guard = bar.saturating_mul(SEAT_ASSOC_EXPLOSION_GUARD);
8668    // Each pair's priced orientation, not just its price: `true` means the
8669    // tag-order first arm drives. Building the pair in tag order and leaving
8670    // the orientation to the arm swap loses on a band tie, where the swap
8671    // keeps the as-built and the as-built may be the expensive role.
8672    let mut best_pair: Option<(usize, usize, SeatCost, bool)> = None;
8673    for (i, j, pair_rows) in pair_produced {
8674        if pair_rows > guard {
8675            continue;
8676        }
8677        let (a, b) = pair_order(i, j);
8678        let keys = hash_keys_for(
8679            &nodes[a].as_plan().output_vars(),
8680            &nodes[b].as_plan().output_vars(),
8681        );
8682        let a_drives = seat_cost_total(
8683            profile,
8684            nodes[a].as_plan(),
8685            nodes[b].as_plan(),
8686            &keys,
8687            ctx,
8688            None,
8689        );
8690        let b_drives = seat_cost_total(
8691            profile,
8692            nodes[b].as_plan(),
8693            nodes[a].as_plan(),
8694            &keys,
8695            ctx,
8696            None,
8697        );
8698        let first_drives = pair_first_drives(
8699            profile,
8700            nodes[a].as_plan(),
8701            nodes[b].as_plan(),
8702            &keys,
8703            a_drives,
8704            b_drives,
8705        );
8706        // The two orientations price equal: the seat cost cannot choose.
8707        // When the pair contains the produced-rows seed, build it seed-left —
8708        // the shape the seed start builds, and the shape the downstream
8709        // build-once/coverage passes can turn into a dropped (fetch-once)
8710        // probe. A strict orientation win above is untouched, and a pair that
8711        // does not contain the seed keeps the priced/legacy choice.
8712        let first_drives = if (a == min_idx || b == min_idx)
8713            && !seat_beats(a_drives, b_drives)
8714            && !seat_beats(b_drives, a_drives)
8715        {
8716            a == min_idx
8717        } else {
8718            first_drives
8719        };
8720        let cost = if first_drives { a_drives } else { b_drives };
8721        let better = match best_pair {
8722            None => true,
8723            Some((bi, bj, incumbent, _)) => {
8724                if seat_beats(cost, incumbent) {
8725                    true
8726                } else if seat_beats(incumbent, cost) {
8727                    false
8728                } else {
8729                    pair_tags_less(i, j, bi, bj)
8730                }
8731            }
8732        };
8733        if better {
8734            best_pair = Some((i, j, cost, first_drives));
8735        }
8736    }
8737    let (pi, pj, pair_cost, pair_first_drives) =
8738        best_pair.expect("two operands always have a pair");
8739    // Build the pair in the orientation it was priced in. A VALUES table
8740    // overrides: it is the broadcast driver, so it goes on the left whatever
8741    // the price or the tie-break says.
8742    let (pair_first, pair_second) = {
8743        let (first, second) = pair_order(pi, pj);
8744        let table_first = match (
8745            matches!(nodes[first].as_plan(), PlanNode::Values(_)),
8746            matches!(nodes[second].as_plan(), PlanNode::Values(_)),
8747        ) {
8748            (true, false) => Some(true),
8749            (false, true) => Some(false),
8750            _ => None,
8751        };
8752        if table_first.unwrap_or(pair_first_drives) {
8753            (first, second)
8754        } else {
8755            (second, first)
8756        }
8757    };
8758    // Start b's pair-seeded association. The pair is the first join, so its
8759    // seating cost is the first term of the total.
8760    let pair_other = if pi == min_idx {
8761        Some(pj)
8762    } else if pj == min_idx {
8763        Some(pi)
8764    } else {
8765        None
8766    };
8767    // The two starts coincide when start a's first attachment is exactly the
8768    // pair, and the pair was BUILT with the seed on the left — the orientation
8769    // associate_from_seed builds. A pair built with the seed on the right is a
8770    // different orientation of the same association and is run separately.
8771    // Check the built orientation (`pair_first`), not tag order: the pair is
8772    // no longer built in tag order.
8773    let pair_is_run_a_first = pair_other.is_some_and(|other| {
8774        pair_start_matches_seed_start(
8775            pair_first,
8776            min_idx,
8777            first_candidate_a.as_deref(),
8778            tags[other].as_str(),
8779        )
8780    });
8781    let (plan_b, total_b) = if pair_is_run_a_first {
8782        (plan_a.clone(), total_a)
8783    } else {
8784        let mut pair_remaining = Vec::with_capacity(nodes.len().saturating_sub(2));
8785        for (idx, node) in nodes.iter().enumerate() {
8786            if idx != pi && idx != pj {
8787                pair_remaining.push(node.clone());
8788            }
8789        }
8790        let pair_join = join_nodes(
8791            nodes[pair_first].as_plan().clone(),
8792            nodes[pair_second].as_plan().clone(),
8793            profile,
8794        );
8795        let (plan, mut total, _) =
8796            associate_from_seed(pair_join, pair_remaining, profile, ctx, true);
8797        total.rows = total.rows.saturating_add(pair_cost.rows);
8798        total.seeks = total.seeks.saturating_add(pair_cost.seeks);
8799        (plan, total)
8800    };
8801    // Proxy caveat: the total is the sum of the per-join cost estimates, not a
8802    // whole-plan cost. A join's seating cost includes its probe subtree's read, and
8803    // when the accumulator is the driver of the next join that interior can
8804    // be counted again through the driver work. Both starts carry the same
8805    // approximation, so the comparison is like-for-like; an exact total
8806    // needs a cost function over the finished plan. The pair start's first
8807    // term is the seating its pricing chose; a VALUES table can force the
8808    // other seating to be built, so that one term can under-charge the pair
8809    // by the difference between the two seatings.
8810    if seat_beats(total_b, total_a) {
8811        plan_b
8812    } else if seat_beats(total_a, total_b) {
8813        plan_a
8814    } else {
8815        // Band tie: prefer the pair start (the cheaper local first join).
8816        plan_b
8817    }
8818}
8819
8820/// A VALUES arm is a structural driver: its term list is the broadcast
8821/// prefix that grounds the probe scan's slot, and `join_nodes` only builds
8822/// that prefix when the table is the LEFT arm. Built on the right the table
8823/// degenerates to a hash-build arm and the grounding never happens, so the
8824/// association always puts the table on the left.
8825fn values_drives_over(acc: &PlanNode, candidate: &PlanNode) -> bool {
8826    matches!(candidate, PlanNode::Values(_)) && !matches!(acc, PlanNode::Values(_))
8827}
8828
8829/// Choose the operand to attach next, from the accumulator and the
8830/// canonically ordered remaining pool. Returns the chosen index into
8831/// `remaining`, its join output, and its surviving seating.
8832///
8833/// The cost ranking is eligibility-guarded: a candidate whose join output
8834/// exceeds `SEAT_ASSOC_EXPLOSION_GUARD` (4×) the smallest candidate's output
8835/// is excluded from that ranking, so a cheap-reading/huge-producing arm
8836/// cannot become the accumulator at this step. It stays in the pool and is
8837/// attached later, typically once it is the bar-setter itself. The guard
8838/// shapes only the cost pick; the produced pick is the smallest output in
8839/// both modes. A produced tie keeps the earliest entry, which is why the
8840/// caller establishes the canonical order once before the loop.
8841fn pick_attachment(
8842    acc: &PlanNode,
8843    remaining: &[JoinableSpineNode],
8844    profile: Option<&StatsProfile>,
8845    ctx: Option<&crate::context::QueryContext>,
8846    seat_by_totals: bool,
8847) -> (usize, u64, SeatCost) {
8848    let acc_out = acc.output_vars();
8849    let mut priced: Vec<(usize, u64, SeatCost)> = Vec::with_capacity(remaining.len());
8850    for (idx, candidate) in remaining.iter().enumerate() {
8851        let keys = hash_keys_for(&acc_out, &candidate.as_plan().output_vars());
8852        let produced = finalize_inner_join_meta(acc, candidate.as_plan(), &keys, profile).1;
8853        let acc_drives = seat_cost_total(profile, acc, candidate.as_plan(), &keys, ctx, None);
8854        let candidate_drives = seat_cost_total(profile, candidate.as_plan(), acc, &keys, ctx, None);
8855        let cost = if seat_beats(candidate_drives, acc_drives) {
8856            candidate_drives
8857        } else {
8858            acc_drives
8859        };
8860        priced.push((idx, produced, cost));
8861    }
8862    // The candidate list is rebuilt at every attachment (tag formatting per
8863    // candidate), so build it only when someone is reading debug output.
8864    if let Some(ctx) = ctx
8865        && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
8866    {
8867        let entries = priced
8868            .iter()
8869            .map(|(idx, produced, cost)| {
8870                format!(
8871                    "#{} {} produced={} seat={}:{}s",
8872                    idx,
8873                    crate::explain::plan_node_tag(remaining[*idx].as_plan()),
8874                    produced,
8875                    cost.rows,
8876                    cost.seeks,
8877                )
8878            })
8879            .collect::<Vec<_>>()
8880            .join(" | ");
8881        ctx.log(
8882            crate::context::LogLevel::Debug,
8883            &format!(
8884                "assoc-prices: acc={} candidates=[{entries}]",
8885                crate::explain::plan_node_tag(acc),
8886            ),
8887        );
8888    }
8889    let produced_pick = priced
8890        .iter()
8891        .min_by_key(|(_, produced, _)| *produced)
8892        .expect("remaining is non-empty");
8893    let bar = produced_pick.1;
8894    let guard = bar.saturating_mul(SEAT_ASSOC_EXPLOSION_GUARD);
8895    let mut cost_pick: Option<&(usize, u64, SeatCost)> = None;
8896    let mut eligible = 0usize;
8897    for entry in &priced {
8898        if entry.1 > guard {
8899            continue;
8900        }
8901        eligible += 1;
8902        if cost_pick.is_none_or(|incumbent| seat_beats(entry.2, incumbent.2)) {
8903            cost_pick = Some(entry);
8904        }
8905    }
8906    let cost_pick = cost_pick.expect("the produced-bar candidate always clears its own guard");
8907    let pick = if seat_by_totals {
8908        cost_pick
8909    } else {
8910        produced_pick
8911    };
8912    if cost_pick.0 != produced_pick.0
8913        && let Some(ctx) = ctx
8914        && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
8915    {
8916        ctx.log(
8917            crate::context::LogLevel::Debug,
8918            &format!(
8919                "{}: applied=idx{} produced_only=idx{} candidates={} \
8920                 eligible={} produced_bar={} pick(produced={} seat={}:{}) \
8921                 produced_pick(produced={} seat={}:{})",
8922                if seat_by_totals {
8923                    "join-seat-assoc"
8924                } else {
8925                    "join-seat-assoc-shadow"
8926                },
8927                cost_pick.0,
8928                produced_pick.0,
8929                priced.len(),
8930                eligible,
8931                bar,
8932                cost_pick.1,
8933                cost_pick.2.rows,
8934                cost_pick.2.seeks,
8935                produced_pick.1,
8936                produced_pick.2.rows,
8937                produced_pick.2.seeks,
8938            ),
8939        );
8940    }
8941    (pick.0, pick.1, pick.2)
8942}
8943
8944/// One association run from a fixed start: attach the best candidate one at
8945/// a time (the original greedy attachment), summing the surviving seating of
8946/// every join. The remaining operands are sorted by structural tag so the
8947/// candidate list order is canonical and cannot leak the lowering order into
8948/// the tie-breaks.
8949fn associate_from_seed(
8950    mut acc: PlanNode,
8951    mut remaining: Vec<JoinableSpineNode>,
8952    profile: Option<&StatsProfile>,
8953    ctx: Option<&crate::context::QueryContext>,
8954    seat_by_totals: bool,
8955) -> (PlanNode, SeatCost, Option<String>) {
8956    remaining.sort_by(|a, b| {
8957        crate::explain::plan_node_tag(a.as_plan()).cmp(&crate::explain::plan_node_tag(b.as_plan()))
8958    });
8959    let mut total = SeatCost { rows: 0, seeks: 0 };
8960    let mut first_candidate: Option<String> = None;
8961    while !remaining.is_empty() {
8962        let (pick_idx, _pick_produced, pick_cost) =
8963            pick_attachment(&acc, &remaining, profile, ctx, seat_by_totals);
8964        let candidate = remaining.remove(pick_idx);
8965        if first_candidate.is_none() {
8966            first_candidate = Some(crate::explain::plan_node_tag(candidate.as_plan()));
8967        }
8968        total.rows = total.rows.saturating_add(pick_cost.rows);
8969        total.seeks = total.seeks.saturating_add(pick_cost.seeks);
8970        // A VALUES candidate drives, even when the accumulator is not a
8971        // VALUES: the term list is the broadcast prefix that grounds the
8972        // probe scan's slot, and it only exists on the left arm.
8973        let values_drives = values_drives_over(&acc, candidate.as_plan());
8974        let candidate = candidate.into_plan();
8975        acc = if values_drives {
8976            join_nodes(candidate, acc, profile)
8977        } else {
8978            join_nodes(acc, candidate, profile)
8979        };
8980    }
8981    (acc, total, first_candidate)
8982}
8983
8984/// Is this custom cluster POOL-ELIGIBLE — safe for the reassociate pass to
8985/// rebuild the spine AROUND it, taking the cluster as one atomic pool
8986/// operand? Two conditions, both about pricing honestly:
8987///
8988/// - the op carries the execution-cost stamp (`CustomOpCost`): the association pass's
8989///   cost ranking prices a pooled cluster through it (`seat_driver_work_rows`
8990///   / the custom probe branch of `seat_cost_total`), and an unpriced
8991///   cluster would be ranked on its output cardinality — the fiction the cost
8992///   model exists to remove;
8993/// - the op holds no pins: a pinned op's executor contract is one
8994///   ground-unique probe term. Defensive today — pins are stamped by
8995///   `ground_and_recost_broadcasted_arm` inside refinalize, AFTER
8996///   reassociation — but the pass must not reorder around a pin if a
8997///   future pipeline point stamps them earlier.
8998fn custom_cluster_pool_eligible(op: &CustomOp) -> bool {
8999    op.cost.is_some() && op.pinned.is_empty()
9000}
9001
9002/// Does this spine contain a custom cluster that must keep the WHOLE spine
9003/// frozen (the pre-pooling behavior)? An eligible cluster
9004/// ([`custom_cluster_pool_eligible`]) does NOT freeze the spine:
9005/// [`flatten_join_spine`] keeps `Join(CustomNode, key-arm)` whole as ONE
9006/// atomic operand, and the association pass seats the cluster among the spine's
9007/// operands so its selectivity ranks against every arm. An UNPRICED or
9008/// PINNED custom node still freezes the spine — the association pass has no honest
9009/// price for it and must not reorder around it.
9010fn join_spine_has_frozen_custom_cluster(node: &PlanNode) -> bool {
9011    match node {
9012        PlanNode::Join { left, right, .. } => {
9013            join_spine_has_frozen_custom_cluster(left)
9014                || join_spine_has_frozen_custom_cluster(right)
9015        }
9016        PlanNode::CustomNode(op) => !custom_cluster_pool_eligible(op),
9017        _ => false,
9018    }
9019}
9020
9021/// One operand of a flattened inner-join spine.
9022///
9023/// The association pass orders these as units. Most are a bare node. A
9024/// [`Self::TransparentJoin`] is a `Join(Values, X)` pair that stays together:
9025/// the VALUES LCA placement put the table directly above the subtree that
9026/// reads it, and pulling the two apart would re-seat the scan away from its
9027/// broadcast driver. [`Self::Opaque`] is a subtree the flatten emits whole
9028/// and the pair pre-pass never splits: a custom cluster
9029/// (`Join(CustomNode, key-arm)`), or a `Filter` / `SubSelect` boundary that
9030/// tops its own spine. It is ONE operand for ordering, not unvisited —
9031/// [`reassociate_spine_operand`] descends its interior, so a cluster's
9032/// key-arm chain and a nested spine under a boundary still get their own
9033/// association pass.
9034#[derive(Debug, Clone)]
9035enum JoinableSpineNode {
9036    Bare(PlanNode),
9037    TransparentJoin(PlanNode),
9038    Opaque(PlanNode),
9039}
9040
9041impl JoinableSpineNode {
9042    fn as_plan(&self) -> &PlanNode {
9043        match self {
9044            Self::Bare(node) | Self::TransparentJoin(node) | Self::Opaque(node) => node,
9045        }
9046    }
9047
9048    fn into_plan(self) -> PlanNode {
9049        match self {
9050            Self::Bare(node) | Self::TransparentJoin(node) | Self::Opaque(node) => node,
9051        }
9052    }
9053
9054    fn is_unit(&self) -> bool {
9055        matches!(self.as_plan(), PlanNode::Unit)
9056    }
9057}
9058
9059/// A custom cluster: a `Join` with a direct `CustomNode` arm. The flatten
9060/// keeps it whole so the op never dissolves from its key arm.
9061fn is_custom_cluster_pair(left: &PlanNode, right: &PlanNode) -> bool {
9062    matches!(left, PlanNode::CustomNode(_)) || matches!(right, PlanNode::CustomNode(_))
9063}
9064
9065/// A `Join` whose direct child is a `VALUES` table (the nested-pair shape).
9066fn is_values_join(node: &PlanNode) -> bool {
9067    matches!(
9068        node,
9069        PlanNode::Join { left, right, .. }
9070            if matches!(**left, PlanNode::Values(_)) || matches!(**right, PlanNode::Values(_))
9071    )
9072}
9073
9074/// A `Join(Values, X)` pair the flatten keeps together. The table is the
9075/// broadcast driver of X, and the VALUES LCA placement chose that adjacency.
9076/// X must be one operand the flatten would keep whole: not a hard boundary
9077/// (the placement pass treats those as their own region), not a bare table,
9078/// and not a nested pair — a second table is a separate attachment the association pass
9079/// may still make.
9080fn is_transparent_pair(left: &PlanNode, right: &PlanNode) -> bool {
9081    matches!(left, PlanNode::Values(_))
9082        && !matches!(
9083            right,
9084            PlanNode::Values(_) | PlanNode::Filter { .. } | PlanNode::SubSelect(_)
9085        )
9086        && !is_values_join(right)
9087        && !flatten_would_dissolve(right)
9088        // A pair with no shared key is a cartesian, not a broadcast: the
9089        // table cannot drive the right arm, and the lowering's raw leaf sort
9090        // can pair it with the wrong scan. Let the association pass re-decide that pair.
9091        && !hash_keys_for(&left.output_vars(), &right.output_vars()).is_empty()
9092}
9093
9094/// Whether [`flatten_join_spine`] recurses through this node. False for a
9095/// structural unit (a custom cluster or a transparent pair) and for anything
9096/// that is not a `Join`; those are emitted as one operand.
9097fn flatten_would_dissolve(node: &PlanNode) -> bool {
9098    let PlanNode::Join { left, right, .. } = node else {
9099        return false;
9100    };
9101    !is_custom_cluster_pair(left, right) && !is_transparent_pair(left, right)
9102}
9103
9104/// Flatten a Join spine into its owned operand pool. `Unit` operands are the
9105/// join identity and drop out, mirroring `lower_pipeline`.
9106///
9107/// Three shapes stop the split and become one operand:
9108///
9109/// - a custom cluster — a `Join` with a direct `CustomNode` arm (GeoSPARQL's
9110///   injected `Join(geo_scan, key-plan)`): the rewrite's arm order and the
9111///   op's executor contracts (keyed pushes, pins) live inside it;
9112/// - a transparent pair — `Join(Values, X)` where X is one operand the
9113///   flatten would keep whole: the table is the broadcast driver, and the
9114///   VALUES LCA placement put it directly above its reader;
9115/// - a `Filter` / `SubSelect` boundary, which is a hard end and tops its own
9116///   spine.
9117///
9118/// Pooling makes an operand ATOMIC for cost ordering, never unvisited:
9119/// [`reassociate_inner_joins`] descends every pooled operand's interior
9120/// ([`reassociate_spine_operand`]) before the association pass, so a cluster's key-arm
9121/// chain and a Union's arms still get their own cost-based pass.
9122fn flatten_join_spine(node: PlanNode, out: &mut Vec<JoinableSpineNode>) {
9123    if let PlanNode::Join { left, right, .. } = &node {
9124        if is_custom_cluster_pair(left, right) {
9125            out.push(JoinableSpineNode::Opaque(node));
9126            return;
9127        }
9128        if is_transparent_pair(left, right) {
9129            out.push(JoinableSpineNode::TransparentJoin(node));
9130            return;
9131        }
9132        let PlanNode::Join { left, right, .. } = node else {
9133            unreachable!("the match above established a Join");
9134        };
9135        flatten_join_spine(*left, out);
9136        flatten_join_spine(*right, out);
9137        return;
9138    }
9139    match node {
9140        PlanNode::Filter { .. } | PlanNode::SubSelect(_) => {
9141            out.push(JoinableSpineNode::Opaque(node));
9142        }
9143        other => out.push(JoinableSpineNode::Bare(other)),
9144    }
9145}
9146
9147/// Visit one OPAQUE operand's interior before the association pass. A `Join` operand
9148/// here is a custom cluster: `flatten_join_spine` already split everything
9149/// splittable and keeps clusters whole, so descending its arms directly is
9150/// the way to give the key-arm chain its own pass without re-pooling the
9151/// cluster (the single-operand no-op that never reaches it). Every other
9152/// container takes the full pass — a `Union` operand's arms are spines in
9153/// their own right, and this descent is the route that makes the pooling arm
9154/// visit interiors at all.
9155fn reassociate_operand(
9156    operand: &mut PlanNode,
9157    profile: Option<&StatsProfile>,
9158    ctx: Option<&crate::context::QueryContext>,
9159) {
9160    match operand {
9161        PlanNode::Join { left, right, .. } => {
9162            reassociate_inner_joins(left, profile, ctx);
9163            reassociate_inner_joins(right, profile, ctx);
9164        }
9165        _ => reassociate_inner_joins(operand, profile, ctx),
9166    }
9167}
9168
9169/// Visit one pooled operand's interior before the association pass.
9170fn reassociate_spine_operand(
9171    operand: &mut JoinableSpineNode,
9172    profile: Option<&StatsProfile>,
9173    ctx: Option<&crate::context::QueryContext>,
9174) {
9175    match operand {
9176        // A bare node is never a Join (the flatten emits those as
9177        // TransparentJoin or Opaque), so the full pass cannot re-pool it.
9178        JoinableSpineNode::Bare(node) => reassociate_inner_joins(node, profile, ctx),
9179        // Keep the pair together; visit only the non-table child's interior.
9180        JoinableSpineNode::TransparentJoin(node) => {
9181            if let PlanNode::Join { left, right, .. } = node {
9182                let inner = if matches!(**left, PlanNode::Values(_)) {
9183                    right.as_mut()
9184                } else {
9185                    left.as_mut()
9186                };
9187                reassociate_operand(inner, profile, ctx);
9188            }
9189        }
9190        JoinableSpineNode::Opaque(node) => reassociate_operand(node, profile, ctx),
9191    }
9192}
9193
9194/// Re-associate flat inner-join chains by cost.
9195///
9196/// At every `Join` whose spine contains no FROZEN custom cluster, the
9197/// left-deep chain is flattened into its operand pool and rebuilt by
9198/// [`associate_cost_based`]. (A single operand has no association choice;
9199/// the spine is left as built.) Nested spines inside `LeftJoin` /
9200/// `Union` arms and sub-selects are visited on the way — in pooled spines
9201/// by the operand descent ([`reassociate_spine_operand`]), in frozen spines by
9202/// the recursion below; `LeftJoin`,
9203/// `Union`, and `CustomNode` subtrees are atomic operands — and a custom
9204/// CLUSTER (`Join(CustomNode, key-arm)`) whose op carries the cost stamp
9205/// and no pins is an atomic POOL operand: it seats among the spine's
9206/// other arms, so its selectivity ranks against every one of them
9207/// ([`join_spine_has_frozen_custom_cluster`] / [`flatten_join_spine`]).
9208/// Unpriced or pinned clusters freeze the whole spine instead — the
9209/// association pass has no honest price for them.
9210///
9211/// Pipeline position — after `fold_identity_filters` and the plugin
9212/// rewrites, before the first `restamp_broadcast_marks`: identity grounds
9213/// are already baked into the scans (so pricing sees the real prefix reads
9214/// without any pin machinery), plugin-injected joins exist but stay opaque,
9215/// and no broadcast mark exists yet, so the rebuild clears nothing and the
9216/// boundary restamp re-claims the rebuilt shape. Filters that sparopt
9217/// pushed between leaves also stop splitting the pool: once
9218/// `fold_identity_filters` drops a saturated filter node, its scans share
9219/// one spine and one operand pool.
9220///
9221/// The candidate currency follows `QueryContext::seat_by_total_cost`: off
9222/// (default) candidates compete on estimated join output alone and the pass
9223/// keeps the seed association; on, eligibility stays on the output scale and
9224/// the ranking moves to [`seat_cost_total`], and the pass also builds a
9225/// second association from the eligibility-guarded cheapest operand pair and
9226/// keeps the lower accumulated total seating cost — see [`associate_cost_based`] for
9227/// why both scales are needed and why cartesian candidates change currency
9228/// after eligibility.
9229fn reassociate_inner_joins(
9230    node: &mut PlanNode,
9231    profile: Option<&StatsProfile>,
9232    ctx: Option<&crate::context::QueryContext>,
9233) {
9234    match node {
9235        PlanNode::Join { .. } if !join_spine_has_frozen_custom_cluster(node) => {
9236            let taken = std::mem::replace(node, PlanNode::Unit);
9237            let mut operands: Vec<JoinableSpineNode> = Vec::new();
9238            flatten_join_spine(taken, &mut operands);
9239            operands.retain(|operand| !operand.is_unit());
9240            // Interiors before the association pass: the
9241            // pool's atomic operands may hold parse-order spines — a Union
9242            // arm's chain, the cluster's key arm. Descending the OPERANDS
9243            // reaches exactly those; descending the association result would
9244            // miss the single-operand early return below and re-walk the
9245            // association pass's own scaffolding.
9246            for operand in &mut operands {
9247                reassociate_spine_operand(operand, profile, ctx);
9248            }
9249            *node = match operands.len() {
9250                0 => PlanNode::Unit,
9251                1 => operands.remove(0).into_plan(),
9252                _ => associate_cost_based(operands, profile, ctx),
9253            };
9254        }
9255        PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
9256            reassociate_inner_joins(left, profile, ctx);
9257            reassociate_inner_joins(right, profile, ctx);
9258        }
9259        PlanNode::LeftJoin { left, right, .. } => {
9260            reassociate_inner_joins(left, profile, ctx);
9261            reassociate_inner_joins(right, profile, ctx);
9262        }
9263        PlanNode::CustomNode(op) => {
9264            for child in &mut op.children {
9265                reassociate_inner_joins(child, profile, ctx);
9266            }
9267        }
9268        PlanNode::SubSelect(sub) => reassociate_inner_joins(&mut sub.inner, profile, ctx),
9269        PlanNode::Filter { inner, exists, .. } => {
9270            for clause in exists {
9271                reassociate_inner_joins(&mut clause.body, profile, ctx);
9272            }
9273            reassociate_inner_joins(inner, profile, ctx);
9274        }
9275        PlanNode::Extend { inner, .. }
9276        | PlanNode::Slice { inner, .. }
9277        | PlanNode::Distinct { inner, .. }
9278        | PlanNode::Sort { inner, .. }
9279        | PlanNode::Group { inner, .. }
9280        | PlanNode::JoinGraphVar { inner, .. } => reassociate_inner_joins(inner, profile, ctx),
9281        PlanNode::Scan(_)
9282        | PlanNode::Path(_)
9283        | PlanNode::Values(_)
9284        | PlanNode::NamedGraphs { .. }
9285        | PlanNode::NamedGraphExists { .. }
9286        | PlanNode::DomainCounts { .. }
9287        | PlanNode::HeadCounts { .. }
9288        | PlanNode::PatternCount { .. }
9289        | PlanNode::Unit => {}
9290    }
9291}
9292
9293fn lower_leaf(
9294    leaf: FlatLeaf,
9295    profile: Option<&StatsProfile>,
9296    incoming: &IncomingBound,
9297    ctx: &QueryContext,
9298    scope: &GraphScope,
9299    default_empty: bool,
9300) -> Result<PlanNode, ComputeError> {
9301    // Empty SPARQL default graph empties triple/path reads only. VALUES is a
9302    // table; BIND/FILTER/UNION are not flatten leaves. Do not call
9303    // `plan_scan_op`: DefaultGraphWindow::Empty still grounds RDF DefaultGraph.
9304    if default_empty
9305        && matches!(
9306            leaf,
9307            FlatLeaf::Triple(_) | FlatLeaf::FilteredTriple { .. } | FlatLeaf::Path { .. }
9308        )
9309    {
9310        return Ok(empty_pipeline_values(std::slice::from_ref(&leaf), scope));
9311    }
9312    match leaf {
9313        FlatLeaf::Triple(pattern) => Ok(PlanNode::Scan(plan_scan_op(
9314            &pattern, profile, incoming, ctx, scope,
9315        )?)),
9316        FlatLeaf::FilteredTriple { triple, expression } => {
9317            let scan = PlanNode::Scan(plan_scan_op(&triple, profile, incoming, ctx, scope)?);
9318            let (early, residual) = crate::expr::split_filter(&expression)?;
9319            Ok(PlanNode::Filter {
9320                inner: Box::new(scan),
9321                early,
9322                residual,
9323                exists: Vec::new(),
9324                one_to_one: false,
9325            })
9326        }
9327        FlatLeaf::Path {
9328            subject,
9329            path,
9330            object,
9331        } => lower_path(&subject, &path, &object, profile, incoming, ctx, scope),
9332        FlatLeaf::Values {
9333            variables,
9334            bindings,
9335        } => lower_values(variables, bindings),
9336    }
9337}
9338
9339fn lower_values(
9340    variables: Vec<Variable>,
9341    bindings: Vec<Vec<Option<GroundTerm>>>,
9342) -> Result<PlanNode, ComputeError> {
9343    // sparopt's empty singleton (`Values { vars: [], bindings: [[]] }`) is the
9344    // SPARQL join identity: one row, zero columns. Distinguish it from
9345    // `VALUES {}` (zero rows), which must wipe a join.
9346    if is_unit_values(&variables, &bindings) {
9347        return Ok(PlanNode::Unit);
9348    }
9349    let mut strings = Vec::new();
9350    let mut blobs = Vec::new();
9351    let mut rows = Vec::with_capacity(bindings.len());
9352    for binding in bindings {
9353        if binding.len() != variables.len() {
9354            return Err(ComputeError::UnsupportedSparql(
9355                "VALUES row width does not match the variable list".into(),
9356            ));
9357        }
9358        let mut row = Vec::with_capacity(binding.len());
9359        for cell in binding {
9360            match cell {
9361                None => row.push(None),
9362                Some(ground) => {
9363                    let term = ground_term_to_term(ground)?;
9364                    // Mint + seed entries in one step: plugin-owned
9365                    // datatypes (GeoSPARQL) take the encode hook so a
9366                    // VALUES constant becomes the same native term ingest
9367                    // would mint — the one-encode-path rule for user
9368                    // literals. The entries (lexical + payload pairs) ride
9369                    // the ValuesOp carriage (query constants are not store
9370                    // data) and install at execution.
9371                    let (encoded, (cell_strings, cell_blobs)) =
9372                        crate::query::caches::mint_const_entries(&term);
9373                    strings.extend(cell_strings);
9374                    blobs.extend(cell_blobs);
9375                    row.push(Some(encoded));
9376                }
9377            }
9378        }
9379        rows.push(row);
9380    }
9381    Ok(PlanNode::Values(ValuesOp {
9382        variables,
9383        rows,
9384        strings,
9385        blobs,
9386    }))
9387}
9388
9389fn is_unit_values(variables: &[Variable], bindings: &[Vec<Option<GroundTerm>>]) -> bool {
9390    variables.is_empty() && bindings.len() == 1 && bindings[0].iter().all(Option::is_none)
9391}
9392
9393fn ground_term_to_term(ground: GroundTerm) -> Result<Term, ComputeError> {
9394    match ground {
9395        GroundTerm::NamedNode(node) => Ok(Term::NamedNode(node)),
9396        GroundTerm::Literal(literal) => Ok(Term::Literal(literal)),
9397    }
9398}
9399
9400fn join_nodes(left: PlanNode, right: PlanNode, profile: Option<&StatsProfile>) -> PlanNode {
9401    // Do not implement Join(V, LeftJoin(B, C)) → LeftJoin(Join(V, B), C)
9402    // from the ⊆ check alone: that is legal when vacuous (V shares nothing
9403    // with C) and becomes a cartesian on the OPTIONAL left. A correct pass
9404    // also needs vars(X) ∩ vars(B) ≠ ∅, join commute/associate, and
9405    // UNION-copy vs JOIN-move. `delay_optional_through_join` implements
9406    // that condition set at the PlanNode level. See
9407    // docs/modules/ROOT/pages/internals-sparql-optimizations.adoc §2.11.
9408    let (left, right) = replace_named_graphs_with_exists(left, right);
9409    let left_out = left.output_vars();
9410    let right_out = right.output_vars();
9411    let mut hash_keys = hash_keys_for(&left_out, &right_out);
9412    let (left, mut right) = maybe_swap_scan_union(left, right, &hash_keys, profile);
9413    // A zero-row arm (a conflict substitution below this join) or a hash key
9414    // ground-unique on both sides with DIFFERENT terms makes the join
9415    // produce no rows: substitute the zero-row node so neither arm executes.
9416    // Same-term keys are not a conflict — the domain aggregation excludes
9417    // them instead.
9418    if zero_row_arm(&left)
9419        || zero_row_arm(&right)
9420        || (!hash_keys.is_empty() && conflicting_ground_keys(&left, &right, &hash_keys).is_some())
9421    {
9422        return provably_empty_join(&left, &right);
9423    }
9424    let (strategy, mut produced_row_count_estimate, mut own_push_removed_row_count_estimate) =
9425        finalize_inner_join_meta(&left, &right, &hash_keys, profile);
9426    let mut probe_key_domains = stamp_probe_key_domains(profile, &right, &hash_keys);
9427    let mut probe_key_overlap_milli = stamp_probe_key_overlaps(profile, &left, &right, &hash_keys);
9428    // The first hash key is the one the runtime broadcasts first
9429    // (`join_keys_scan_filter` first-suitable) and the one the restamp claim
9430    // names — order the keys by their expected probe return before anything
9431    // consumes `first()`.
9432    // This cannot affect the strategy and estimated rows, so run it after
9433    // `finalize_inner_join_meta`.
9434    reorder_hash_keys_by_probe_return(
9435        &mut hash_keys,
9436        &mut probe_key_domains,
9437        &mut probe_key_overlap_milli,
9438        &left,
9439        &right,
9440        profile,
9441    );
9442    // Ground a ground-unique driver into the probe arm and recost it, so the
9443    // same-pass conflict checks and ancestor costing see the grounded shape.
9444    // Allow-list marks are NOT stamped here — `restamp_broadcast_marks` is
9445    // their sole writer (run after this whole pipeline stage).
9446    if strategy == JoinStrategy::Broadcast && !hash_keys.is_empty() {
9447        ground_and_recost_broadcasted_arm(&left, &mut right, &hash_keys, profile);
9448        // The grounding recosted the probe scan, so the pre-ground estimate
9449        // is stale for every consumer of this join's meta (ancestor costing,
9450        // the reassociation pass's candidate comparator). Re-price on the
9451        // post-ground shapes; the strategy stands — it was chosen on
9452        // pre-ground shapes and the ground only shrinks the probe.
9453        let (_, produced, own_push_removed) =
9454            finalize_inner_join_meta(&left, &right, &hash_keys, profile);
9455        produced_row_count_estimate = produced;
9456        own_push_removed_row_count_estimate = own_push_removed;
9457    }
9458    let (mut left, mut right) = (left, right);
9459    if !hash_keys.is_empty() {
9460        compose_graph_from_sibling(&left, &mut right, &hash_keys, profile, true);
9461        compose_graph_from_sibling(&right, &mut left, &hash_keys, profile, true);
9462    }
9463    // Stamped from the FINAL right arm — after the grounding recost and
9464    // the graph compose, either of which can reshape the probe's scans
9465    // (a grounded slot stops hosting its variable; a composed graph slot
9466    // starts hosting the graph variable).
9467    let rhs_hostable_keys = stamp_rhs_hostable_keys(&right);
9468    PlanNode::Join {
9469        left: Box::new(left),
9470        right: Box::new(right),
9471        hash_keys,
9472        probe_key_domains,
9473        probe_key_overlap_milli,
9474        rhs_hostable_keys,
9475        meta: JoinMeta {
9476            semi_gate: None,
9477            star_arms: None,
9478            strategy,
9479            produced_row_count_estimate,
9480            // The own-push-removed record: finalize prices a direct
9481            // right-arm path/claimed scan at its bare pattern cost
9482            // (`path_arm_own_push_removed_price`) so this field keeps the
9483            // counterfactual even when `produced` carries the push-aware
9484            // bound — see the JoinMeta field docs for the one-level
9485            // limitation.
9486            own_push_removed_row_count_estimate,
9487        },
9488    }
9489}
9490
9491/// `Join(NamedGraphs(?g), unique IRI on ?g)` → catalog membership of that IRI
9492/// (`VALUES` / `BIND` around empty `GRAPH ?g { }`) instead of listing every
9493/// named graph.
9494fn replace_named_graphs_with_exists(left: PlanNode, right: PlanNode) -> (PlanNode, PlanNode) {
9495    if let PlanNode::NamedGraphs { variable, .. } = &left
9496        && let Some(term) = unique_ground_term(&right, variable)
9497    {
9498        return (PlanNode::NamedGraphExists { graph: term }, right);
9499    }
9500    if let PlanNode::NamedGraphs { variable, .. } = &right
9501        && let Some(term) = unique_ground_term(&left, variable)
9502    {
9503        return (left, PlanNode::NamedGraphExists { graph: term });
9504    }
9505    (left, right)
9506}
9507
9508/// Unmatched pass-through rows of an OPTIONAL: `|L| · Π_k (1 − min(1,
9509/// dom_R(k)/dom_L(k)))` over the join keys — the fraction of required-side
9510/// rows whose key exists nowhere on the optional side, under containment.
9511/// A key with an unknown domain on either side contributes factor 1 (no
9512/// information). Integer fraction arithmetic in u128 with saturating
9513/// products; a saturating denominator drives the product to 0, which only
9514/// under-counts the pass-through the `.max(left_rows)` floor in the
9515/// callers then catches from below.
9516fn left_join_unmatched_rows(
9517    left_rows: u64,
9518    left: &PlanNode,
9519    right: &PlanNode,
9520    hash_keys: &[Variable],
9521    profile: Option<&StatsProfile>,
9522) -> u64 {
9523    let mut numer: u128 = 1;
9524    let mut denom: u128 = 1;
9525    for key in hash_keys {
9526        let (Some(dom_l), Some(dom_r)) = (
9527            join_key_domain_for_node(profile, left, key),
9528            join_key_domain_for_node(profile, right, key),
9529        ) else {
9530            continue;
9531        };
9532        if dom_r >= dom_l {
9533            // The optional side covers the whole key space: nothing passes
9534            // through unmatched on this key's account.
9535            return 0;
9536        }
9537        numer = numer.saturating_mul(u128::from(dom_l - dom_r));
9538        denom = denom.saturating_mul(u128::from(dom_l));
9539        if numer == 0 || denom == u128::MAX {
9540            return 0;
9541        }
9542    }
9543    let left_rows = u128::from(left_rows.max(1));
9544    u64::try_from(left_rows * numer / denom).unwrap_or(u64::MAX)
9545}
9546
9547/// Shared matched-product tail of the OPTIONAL stage models:
9548/// `unmatched + estimate_join_rows_multi(|L|, |R|, keys)` — the matched
9549/// pairs under the uniform product, plus the unmatched required-side
9550/// pass-through. Under single-key containment the matched term lands on
9551/// |R| exactly (every optional row matches), so the whole reduces to
9552/// `(|L| − dom_R) + |R|`. Floored at |L| (an OPTIONAL emits at least its
9553/// required side); unkeyed optionals cross-product `|L| × max(1, |R|)`.
9554/// Callers differ only in how they priced the right arm.
9555fn estimate_left_join_rows_product(
9556    left_rows: u64,
9557    left: &PlanNode,
9558    right: &PlanNode,
9559    hash_keys: &[Variable],
9560    right_rows: u64,
9561    profile: Option<&StatsProfile>,
9562) -> u64 {
9563    if hash_keys.is_empty() {
9564        return left_rows.saturating_mul(right_rows.max(1));
9565    }
9566    let probe_key_domains = hash_keys
9567        .iter()
9568        .map(|key| {
9569            (
9570                join_key_domain_for_node(profile, left, key),
9571                join_key_domain_for_node(profile, right, key),
9572            )
9573        })
9574        .collect::<Vec<_>>();
9575    let matched = estimate_join_rows_multi(left_rows, right_rows, &probe_key_domains);
9576    left_join_unmatched_rows(left_rows, left, right, hash_keys, profile)
9577        .saturating_add(matched)
9578        .max(left_rows)
9579}
9580
9581/// OPTIONAL output estimate, stage/decision model (what the arm
9582/// reorder's stage estimates and the in-round `produced` stamp consume):
9583/// the
9584/// matched-product tail with the right arm priced push-aware — the
9585/// OPTIONAL's right arm is the probe by definition, so a path there is a
9586/// bind-join probe priced at the values-broadcast bound, not its unbound leaf
9587/// price (same rule the inner-join side uses).
9588fn estimate_left_join_rows(
9589    left_rows: u64,
9590    left: &PlanNode,
9591    right: &PlanNode,
9592    hash_keys: &[Variable],
9593    profile: Option<&StatsProfile>,
9594) -> u64 {
9595    let left_rows = left_rows.max(1);
9596    let right_rows = path_probe_row_bound(
9597        right,
9598        left,
9599        hash_keys,
9600        right.produced_row_count_estimate(),
9601        profile,
9602    );
9603    estimate_left_join_rows_product(left_rows, left, right, hash_keys, right_rows, profile)
9604}
9605
9606/// OPTIONAL output estimate, own-push-removed model: the same
9607/// matched-product tail, but a right-arm path or claimed scan is priced at
9608/// its bare pattern price (`path_arm_own_push_removed_price`) — the node's
9609/// own stamp is clamp-timing-dependent after
9610/// `clamp_broadcast_probe_estimates`, and this record must never depend on
9611/// that timing. Feeds `LeftJoinMeta::own_push_removed_row_count_estimate`
9612/// (the `(price ~N)` EXPLAIN shows); the OPTIONAL analog of the split
9613/// inside `finalize_inner_join_meta`.
9614///
9615/// This removes the OPTIONAL's own right-arm push only. A non-path right
9616/// subtree and the left arm pass through their produced cells, and a
9617/// non-path child may already carry a deeper or ancestor clamp; this is
9618/// not a general no-push estimate.
9619fn estimate_left_join_rows_own_push_removed(
9620    left_rows: u64,
9621    left: &PlanNode,
9622    right: &PlanNode,
9623    hash_keys: &[Variable],
9624    profile: Option<&StatsProfile>,
9625) -> u64 {
9626    let left_rows = left_rows.max(1);
9627    let right_rows =
9628        path_arm_own_push_removed_price(right, right.produced_row_count_estimate(), profile);
9629    estimate_left_join_rows_product(left_rows, left, right, hash_keys, right_rows, profile)
9630}
9631
9632/// OPTIONAL output estimate, push-aware (end-of-pipeline) model: the
9633/// matched term becomes the probe's settled produced count — post-push,
9634/// every row the marked probe returns matches a driver key by
9635/// construction — with the same unmatched pass-through and |L| floor.
9636fn estimate_left_join_rows_pushed(
9637    left_rows: u64,
9638    left: &PlanNode,
9639    right: &PlanNode,
9640    hash_keys: &[Variable],
9641    profile: Option<&StatsProfile>,
9642) -> u64 {
9643    let left_rows = left_rows.max(1);
9644    // The stage model's probe bound: robust to clamp timing (the path
9645    // node may or may not carry `clamp_broadcast_probe_estimates`' clamp
9646    // yet — the values-broadcast bound is a property of this join). The
9647    // own-push-removed record EXPLAIN displays keeps the bare leaf instead.
9648    let right_rows = path_probe_row_bound(
9649        right,
9650        left,
9651        hash_keys,
9652        right.produced_row_count_estimate(),
9653        profile,
9654    );
9655    if hash_keys.is_empty() {
9656        return left_rows.saturating_mul(right_rows.max(1));
9657    }
9658    left_join_unmatched_rows(left_rows, left, right, hash_keys, profile)
9659        .saturating_add(right_rows)
9660        .max(left_rows)
9661}
9662
9663/// Stamps a fresh [`LeftJoinMeta`] from the two frames of the two-field
9664/// lifecycle: `produced` from the stage model with every active push
9665/// (push-aware when the right arm is a path probe — ancestor costing reads
9666/// this via `PlanNode::produced_row_count_estimate`),
9667/// `own_push_removed` with the right-arm probe push removed (the
9668/// `(price ~N)` EXPLAIN shows).
9669/// Mirrors `finalize_inner_join_meta` (see the struct docs).
9670fn stamp_left_join_meta(
9671    left_rows: u64,
9672    left: &PlanNode,
9673    right: &PlanNode,
9674    hash_keys: &[Variable],
9675    profile: Option<&StatsProfile>,
9676) -> LeftJoinMeta {
9677    let produced = estimate_left_join_rows(left_rows, left, right, hash_keys, profile);
9678    let own_push_removed =
9679        estimate_left_join_rows_own_push_removed(left_rows, left, right, hash_keys, profile);
9680    LeftJoinMeta {
9681        produced_row_count_estimate: produced,
9682        own_push_removed_row_count_estimate: own_push_removed,
9683    }
9684}
9685
9686/// Strategy and join-row estimate for the current left/right shape.
9687///
9688/// Two separate domain channels, on purpose:
9689///
9690/// - **Strategy** consumes the allow-list domains (smallest under-
9691///   [`PUSHDOWN_TERMS_LIMIT`] domain among hash keys that occupy a Scan
9692///   slot on the other side, Union arms included). The threshold skip is
9693///   broadcast *eligibility* — would the executor actually broadcast this list?
9694///
9695/// - **Row estimate** consumes raw per-key domains for every hash key via
9696///   [`estimate_join_rows_multi`] (`|L|·|R| / Π max(dom_L(v), dom_R(v))`,
9697///   known-side-only factors). Cardinality must not inherit the
9698///   eligibility threshold: a key with a 100k-value domain still divides
9699///   the estimate even though no executor would ever push its list.
9700///
9701/// Neither channel uses `hash_keys.first()` (left always-bound / S-P-O
9702/// order). Over-threshold or unknown → `None` for strategy (row estimates
9703/// only; executor would not broadcast).
9704/// Distinct driver values pushed into a path probe — the values-broadcast
9705/// fallback's pushed count. The join output is the intersection of the
9706/// rows matching each keyed end's push, so the smallest pushed set is the
9707/// binding constraint: min over every hash key that is a path end, each
9708/// capped by the driver's rows (an unknown domain falls back to its rows).
9709/// `None` when no hash key is a path end.
9710///
9711/// Shared by [`path_probe_row_bound`] (finalize / swap / association costing) and
9712/// the Path arm of [`clamp_broadcast_probe_estimates`] (the node clamp) so
9713/// the swap's number, the node's clamp, and the end pass's recomputation
9714/// all follow one rule. The scan clamp's claim-variable rule is
9715/// scan-specific — a scan carries one claim mark naming one variable; a
9716/// path carries no mark and no domain, so the honest minimum is available
9717/// and used.
9718fn path_pushed_val_count(
9719    path: &PathOp,
9720    driver: &PlanNode,
9721    hash_keys: &[Variable],
9722    profile: Option<&StatsProfile>,
9723) -> Option<u64> {
9724    hash_keys
9725        .iter()
9726        .filter(|key| path.end_of(key).is_some())
9727        .map(|key| {
9728            join_key_domain_for_node(profile, driver, key)
9729                .map(|d| d.min(driver.produced_row_count_estimate()))
9730                .unwrap_or_else(|| driver.produced_row_count_estimate())
9731        })
9732        .min()
9733        .map(|pushed| pushed.max(1))
9734}
9735
9736/// Push-aware row count of a path operand joined on one of its ends.
9737///
9738/// A path whose end is one of this join's hash keys is a bind-join probe:
9739/// the executor pushes the driver's distinct key values into it, so its
9740/// effective size is the values-broadcast bound — `min(leaf price, pushed
9741/// keys)` — not the both-ends-unbound leaf price (1M per free alt-path
9742/// branch). Paths carry no probe-side key domains
9743/// (`join_key_domain_for_node` → None for Path) and `recost_path` re-prices
9744/// only ground ends, so the node's own produced estimate carries the
9745/// unbound price until `clamp_broadcast_probe_estimates` narrows it with
9746/// the same [`path_pushed_val_count`] rule. Only the RIGHT (probe) arm is
9747/// bounded: a path on the driver side executes unbound, and its honest
9748/// driver size IS the unbound price — clamping it would seat an open path
9749/// walk as a cheap driver. Wrapper-aware (`as_dependent_path`): a path
9750/// under a `FILTER`/`BIND` wrapper is still a probe. Non-path arms, and
9751/// paths whose ends this join does not bind, pass through untouched.
9752fn path_probe_row_bound(
9753    arm: &PlanNode,
9754    other: &PlanNode,
9755    hash_keys: &[Variable],
9756    rows: u64,
9757    profile: Option<&StatsProfile>,
9758) -> u64 {
9759    let Some(path) = arm.as_dependent_path() else {
9760        return rows;
9761    };
9762    let Some(pushed) = path_pushed_val_count(path, other, hash_keys, profile) else {
9763        return rows;
9764    };
9765    rows.min(pushed)
9766}
9767
9768/// The own-push-removed price of a right-hand path or claimed scan: the
9769/// bare pattern price re-derived from the path's own structure
9770/// (`estimate_path_size`) or the scan's unclamped read, ignoring the push
9771/// this join applies to its probe. Never stored;
9772/// `own_push_removed_row_count_estimate` exists precisely so this
9773/// counterfactual survives the push-aware produced stamp.
9774///
9775/// Only a direct right-arm path or claimed scan is re-derived. A non-path
9776/// arm passes its produced count through, and the left arm is never
9777/// touched: this is a one-level own-push removal, not a recursive no-push
9778/// estimate.
9779fn path_arm_own_push_removed_price(
9780    arm: &PlanNode,
9781    rows: u64,
9782    profile: Option<&StatsProfile>,
9783) -> u64 {
9784    match arm.as_dependent_path() {
9785        Some(path) => estimate_path_size(
9786            path.subject_term.is_some(),
9787            &path.path,
9788            path.object_term.is_some(),
9789        ),
9790        None => match arm.as_scan() {
9791            // A CLAIMED scan's cell is push-clamped, and the ancestor
9792            // push bound persistence keeps it clamped across rounds — the
9793            // own-push-removed record re-derives the bare pattern price so it never
9794            // depends on clamp timing (same rule the path branch above
9795            // enforces), WHENEVER a non-empty profile prices the pattern:
9796            // `estimate_unclamped_scan_rows` falls back to the cell with
9797            // no profile, so the protection is profile-gated like every
9798            // estimate. Without a claim the cell stands: specialize and
9799            // lowering can price an unmarked scan below its pattern for
9800            // reasons that are not pushes.
9801            Some(scan) if scan.broadcasted.is_some() => estimate_unclamped_scan_rows(profile, scan),
9802            _ => rows,
9803        },
9804    }
9805}
9806
9807/// Probe-side distinct-value estimate per hash key (0 = unknown), aligned
9808/// with `hash_keys`. Consumed at runtime by the pushdown coverage check
9809/// ([`PushedKeyVals::combine`] / `join_keys_scan_filter`): a pushed list is
9810/// only droppable when it covers the key space of the **probe** — the
9811/// relation the filter is applied to — because then the allow-list selects
9812/// nothing (filtered fetch ≈ unbound fetch). The list's *provenance* is the
9813/// driver, but its *effect* is on the probe: comparing against the driver's
9814/// domain measures page saturation, not selectivity, and would drop
9815/// selective pushes (small driver ⋈ wide probe). Advisory only — the
9816/// estimator never reads this; costing derives from the profile via
9817/// [`join_key_domain_for_node`] directly. Re-stamped by
9818/// [`refinalize_joins`] after every re-seating (the probe is the current
9819/// right arm), like `JoinMeta::strategy`.
9820/// The scan vocabulary a join key binds on `node` — the pattern plus the
9821/// unbound slot — when `node` is a plain scan and the key sits on an
9822/// unbound S/O position. These are the inputs the HLL containment lookup
9823/// needs (`estimate_vocabulary_overlap`). `None` = no vocabulary question:
9824/// not a scan, a ground key (a constant carries no vocabulary; its
9825/// domain-1 short-circuit covers it), or a key on another slot.
9826fn scan_key_vocabulary(
9827    node: &PlanNode,
9828    key: &Variable,
9829) -> Option<(EncodedTriplePattern, JoinKeySlot)> {
9830    let scan = node.as_scan()?;
9831    let slot = if scan.subject.as_ref() == Some(key) {
9832        JoinKeySlot::Subject
9833    } else if scan.object.as_ref() == Some(key) {
9834        JoinKeySlot::Object
9835    } else {
9836        return None;
9837    };
9838    let ground = match slot {
9839        JoinKeySlot::Subject => scan.pattern.subject.is_some(),
9840        JoinKeySlot::Object => scan.pattern.object.is_some(),
9841    };
9842    if ground {
9843        return None;
9844    }
9845    Some((scan.pattern.clone(), slot))
9846}
9847
9848/// ONE overlap resolution for every consumer — the cost gather, the
9849/// fetch-once stamp walk, and the runtime coverage stamps — so the price
9850/// and the stamp can never disagree about the containment fraction.
9851/// Every unknown (no profile, non-scan arms, ground keys, unbound
9852/// predicates, wire-trimmed sketches, the `rdf:type` family) resolves to
9853/// FULL: the count rule's byte-identical historical behavior.
9854fn resolve_key_overlap_milli(
9855    profile: Option<&StatsProfile>,
9856    driver: &PlanNode,
9857    probe: &PlanNode,
9858    key: &Variable,
9859) -> u64 {
9860    let Some(profile) = profile.filter(|p| !p.is_empty()) else {
9861        return VOCABULARY_OVERLAP_FULL_MILLI;
9862    };
9863    let Some((driver_pattern, driver_slot)) = scan_key_vocabulary(driver, key) else {
9864        return VOCABULARY_OVERLAP_FULL_MILLI;
9865    };
9866    let Some((probe_pattern, probe_slot)) = scan_key_vocabulary(probe, key) else {
9867        return VOCABULARY_OVERLAP_FULL_MILLI;
9868    };
9869    estimate_vocabulary_overlap(
9870        profile,
9871        &driver_pattern,
9872        driver_slot,
9873        &probe_pattern,
9874        probe_slot,
9875    )
9876    .unwrap_or(VOCABULARY_OVERLAP_FULL_MILLI)
9877}
9878
9879/// Mirror of [`stamp_probe_key_domains`] for the containment stamps:
9880/// one entry per hash key, 1000 where the vocabulary is unknown, written
9881/// at the same finalize sites so the two vecs stay index-aligned through
9882/// the reorder.
9883fn stamp_probe_key_overlaps(
9884    profile: Option<&StatsProfile>,
9885    driver: &PlanNode,
9886    probe: &PlanNode,
9887    hash_keys: &[Variable],
9888) -> Vec<u64> {
9889    hash_keys
9890        .iter()
9891        .map(|key| resolve_key_overlap_milli(profile, driver, probe, key))
9892        .collect()
9893}
9894fn stamp_probe_key_domains(
9895    profile: Option<&StatsProfile>,
9896    probe: &PlanNode,
9897    hash_keys: &[Variable],
9898) -> Vec<u64> {
9899    hash_keys
9900        .iter()
9901        .map(|key| join_key_domain_for_node(profile, probe, key).unwrap_or(0))
9902        .collect()
9903}
9904
9905fn finalize_inner_join_meta(
9906    left: &PlanNode,
9907    right: &PlanNode,
9908    hash_keys: &[Variable],
9909    profile: Option<&StatsProfile>,
9910) -> (JoinStrategy, u64, u64) {
9911    let left_rows = left.produced_row_count_estimate();
9912    // Only the RIGHT (probe) arm binds: a path on the driver side executes
9913    // unbound, and clamping it would price a fiction (see
9914    // `path_probe_row_bound`).
9915    let right_rows = path_probe_row_bound(
9916        right,
9917        left,
9918        hash_keys,
9919        right.produced_row_count_estimate(),
9920        profile,
9921    );
9922    // The own-push-removed model prices a direct right-arm path or claimed
9923    // scan at its bare pattern cost (`estimate_path_size` for a path, the
9924    // intrinsic pattern price for a claimed scan — the cell is
9925    // push-clamped), never at the clamped produced count. A non-path right
9926    // subtree and the left arm pass through their produced cells; the field
9927    // is not a general no-push estimate (see the JoinMeta field docs).
9928    let right_rows_raw =
9929        path_arm_own_push_removed_price(right, right.produced_row_count_estimate(), profile);
9930    let left_rows_raw = left_rows;
9931    let left_domain = join_key_domain_for_allow_list(profile, left, right, hash_keys, left_rows);
9932    let right_domain = join_key_domain_for_allow_list(profile, right, left, hash_keys, right_rows);
9933    let mut strategy = JoinStrategy::from_cardinalities_and_domains(
9934        left_rows,
9935        right_rows,
9936        left_domain,
9937        right_domain,
9938    );
9939    // Path hops are allow-listed from the join key (`eval_from` / `eval_to`).
9940    // Hash/shuffle would `eval_open` the whole graph first.
9941    if let Some(path) = right.as_dependent_path()
9942        && !hash_keys.is_empty()
9943        && hash_keys.iter().any(|key| path.end_of(key).is_some())
9944    {
9945        strategy = JoinStrategy::Broadcast;
9946    }
9947    // Two frames off the same key domains: `produced` prices the probe arm
9948    // at its push-aware size (what execution does — the bind-join push
9949    // narrows a path probe to the values-broadcast bound);
9950    // `own_push_removed` prices a direct right-arm path/claimed scan at its
9951    // bare pattern cost (the `(price ~N)` EXPLAIN shows). They coincide for
9952    // the current join's own push at this finalize; a non-path child may
9953    // already carry a deeper or ancestor clamp, so the own-push-removed
9954    // value can still equal produced even though the frame names the own
9955    // push.
9956    let (produced_row_count_estimate, own_push_removed_row_count_estimate) = if hash_keys.is_empty()
9957    {
9958        (
9959            left_rows.saturating_mul(right_rows).max(1),
9960            left_rows_raw.saturating_mul(right_rows_raw).max(1),
9961        )
9962    } else {
9963        let probe_key_domains = hash_keys
9964            .iter()
9965            .map(|key| {
9966                (
9967                    join_key_domain_for_node(profile, left, key),
9968                    join_key_domain_for_node(profile, right, key),
9969                )
9970            })
9971            .collect::<Vec<_>>();
9972        (
9973            estimate_join_rows_multi(left_rows, right_rows, &probe_key_domains),
9974            estimate_join_rows_multi(left_rows_raw, right_rows_raw, &probe_key_domains),
9975        )
9976    };
9977    (
9978        strategy,
9979        produced_row_count_estimate,
9980        own_push_removed_row_count_estimate,
9981    )
9982}
9983
9984/// Put the cheaper scan↔Union child on the left (Broadcast's small-left rule).
9985///
9986/// Only this shape: flat BGP leaf order already reorders scan↔scan, and
9987/// `Join(Union, Join(...))` is out of scope. Inner join is commutative; do
9988/// not use this for LeftJoin.
9989fn maybe_swap_scan_union(
9990    mut left: PlanNode,
9991    mut right: PlanNode,
9992    hash_keys: &[Variable],
9993    profile: Option<&StatsProfile>,
9994) -> (PlanNode, PlanNode) {
9995    if hash_keys.is_empty() {
9996        return (left, right);
9997    }
9998    let scan_union = left.as_broadcast_scan().is_some() && right.as_union().is_some();
9999    let union_scan = left.as_union().is_some() && right.as_broadcast_scan().is_some();
10000    if !scan_union && !union_scan {
10001        return (left, right);
10002    }
10003    let left_rows = left.produced_row_count_estimate();
10004    let right_rows = right.produced_row_count_estimate();
10005    let left_domain = join_key_domain_for_allow_list(profile, &left, &right, hash_keys, left_rows);
10006    let right_domain =
10007        join_key_domain_for_allow_list(profile, &right, &left, hash_keys, right_rows);
10008    let left_cost = driver_cost(left_rows, left_domain);
10009    let right_cost = driver_cost(right_rows, right_domain);
10010    if right_cost < left_cost {
10011        std::mem::swap(&mut left, &mut right);
10012    }
10013    (left, right)
10014}
10015
10016fn driver_cost(rows: u64, domain: Option<u64>) -> u64 {
10017    match domain {
10018        Some(d) => d.min(rows).max(1),
10019        None => rows.max(1),
10020    }
10021}
10022
10023/// Whole-read row count of one arm priced for THIS join's driver seat,
10024/// claim-aware:
10025///
10026/// - **No claim mark** — the cell is the whole read (a hand-priced or
10027///   refined estimate; unmarked scans carry no push bound either).
10028/// - **Own claim** (the mark's variable is one of THIS join's hash keys)
10029///   — the clamp conditioned the cell for the PROBE road of this join;
10030///   driving reads the intrinsic pattern price instead, so a clamped
10031///   probe never prices a phantom-cheap driver (the tenant-union flip:
10032///   the probe road's 80-row return is not a driving read of the 50k
10033///   catalog arm). With no profile the intrinsic recompute falls back to
10034///   the cell — the protection is profile-gated, like every estimate.
10035/// - **Foreign claim** (an ancestor's push — the claimer-gate rule) — the
10036///   round-entry recost already bounded the cell at the ancestor push's
10037///   return, which holds in EVERY seating of this join, so the cell is
10038///   the bounded whole read (the transects defect: the ancestor-pushed
10039///   arm must not price at catalog size).
10040///
10041/// Bare scans only: a join-tree arm's read is not a single scan's to
10042/// bound, and a custom op's work is not a row count at all (the custom
10043/// driver's WORK basis is [`seat_driver_work_rows`]; this stays the row
10044/// basis that the page count derives from).
10045fn driver_whole_read_rows(
10046    arm: &PlanNode,
10047    hash_keys: &[Variable],
10048    profile: Option<&StatsProfile>,
10049) -> u64 {
10050    match arm {
10051        PlanNode::Scan(scan) => match &scan.broadcasted {
10052            None => scan.produced_row_count_estimate,
10053            Some((variable, _)) if hash_keys.contains(variable) => {
10054                estimate_unclamped_scan_rows(profile, scan)
10055            }
10056            Some(_) => scan.produced_row_count_estimate,
10057        },
10058        other => other.produced_row_count_estimate(),
10059    }
10060}
10061
10062/// The cost model's driver WORK basis for a bare SCAN or a CUSTOM driver
10063/// (a subtree driver prices [`driver_once_cost`] in `seat_cost_total`
10064/// instead). The rows currency prices work, and a stamped custom op's
10065/// driving work is its keyless sweep ([`CustomOp::sweep_cost`]): the
10066/// candidate drain + relate pass over the window, whose cost is invisible
10067/// to output-based pricing — the low-output-expensive-sweep shape the
10068/// cost model exists for. Unstamped ops price opaquely at the row
10069/// estimate (the pre-cost-model behavior). A scan keeps
10070/// [`driver_whole_read_rows`]: its streamed rows ARE its work, and the
10071/// foreign-claim cell IS the bounded whole read. Deliberately NOT the
10072/// page-count basis — [`seat_probe_shape`] counts pages off the row
10073/// basis, because an op's sweep work does not stream as rows (the drain
10074/// reads window candidates, not output pages).
10075fn seat_driver_work_rows(
10076    driver: &PlanNode,
10077    hash_keys: &[Variable],
10078    profile: Option<&StatsProfile>,
10079) -> u64 {
10080    match driver {
10081        PlanNode::CustomNode(op) => op
10082            .sweep_cost()
10083            .unwrap_or_else(|| driver_whole_read_rows(driver, hash_keys, profile)),
10084        _ => driver_whole_read_rows(driver, hash_keys, profile),
10085    }
10086}
10087
10088/// One seating's price, split into the two currencies the executor pays:
10089/// sequential row work (streamed driver rows + probe rows fetched) and raw
10090/// index-seek count. Compared lexicographically — rows decide, seeks break
10091/// near-ties — so no seek-weighting constant sits in the decision (a
10092/// milli-row equivalent needs recalibrating per transport; the ordering
10093/// does not).
10094#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10095pub(crate) struct SeatCost {
10096    rows: u64,
10097    seeks: u64,
10098}
10099
10100// Planner-work diagnostics for the cost comparator (the item-7 leaf-walk's
10101// planner-time regression gate): one bump per [`seat_cost_total`] call, one
10102// per [`subtree_page_cost`] node visit. Thread-local cells, so concurrent
10103// test threads never see each other's counts and the comparator — single
10104// threaded per query — pays one TLS cell add next to arithmetic doing
10105// orders of magnitude more work. The regression tests pin absolute bounds
10106// on both counters, so comparator-work growth is a deliberate, reviewed
10107// decision rather than a silent pile-up (the 30 ms→sub-millisecond planner
10108// work has no other gate).
10109thread_local! {
10110    static SEAT_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
10111    static WALK_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
10112}
10113
10114fn seat_calls_bump() {
10115    SEAT_CALLS.with(|counter| counter.set(counter.get() + 1));
10116}
10117
10118fn walk_visits_bump() {
10119    WALK_VISITS.with(|counter| counter.set(counter.get() + 1));
10120}
10121
10122thread_local! {
10123    /// Parse-bucket input for the `planner-time:` debug line (emitted at the
10124    /// end of [`LogicalPlan::from_prepared`]): the string-entry constructors
10125    /// time SPARQL parsing and algebra preparation into this cell, in µs.
10126    /// Thread-local like [`SEAT_CALLS`] — planning is synchronous within one
10127    /// query — and reset by the emitter, so a stale parse never leaks into
10128    /// the next query's line.
10129    static PLANNER_PARSE_US: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
10130}
10131
10132/// Seat-swap noise band: a row-work difference inside this fraction is a
10133/// statistical tie — seeks break it, but a challenger that reads MORE rows
10134/// never wins, whatever its seek count. Outside the band, fewer rows
10135/// decides outright and seeks are irrelevant.
10136const SEAT_NOISE_BAND_PCT: u64 = 2;
10137
10138/// Association explosion-guard factor: under `--seat-by-total-cost`, a
10139/// candidate whose estimated join OUTPUT exceeds the best candidate's by
10140/// more than this factor is disqualified before the fetch-cost ranking,
10141/// however little it reads. The seating-cost model prices what a join READS (rows
10142/// fetched + index seeks); a cartesian or high-multiplicity join can read very
10143/// little while producing an intermediate so large that the hash product,
10144/// the pages holding it, and every downstream join pay for it — a cost
10145/// the fetch scale cannot see. 4 is a calibration placeholder, chosen to
10146/// keep the tuned cheap-cartesian plans passing (their products clear the
10147/// bar easily) while blocking the read-cheap/product-huge traps; revisit
10148/// against the LUBM cohort if flag-on picks look explosion-shy.
10149const SEAT_ASSOC_EXPLOSION_GUARD: u64 = 4;
10150
10151fn seat_beats(challenger: SeatCost, incumbent: SeatCost) -> bool {
10152    if challenger.rows > incumbent.rows {
10153        return false;
10154    }
10155    let band = incumbent.rows.saturating_mul(SEAT_NOISE_BAND_PCT) / 100;
10156    if challenger.rows.saturating_add(band) < incumbent.rows {
10157        return true;
10158    }
10159    challenger.seeks < incumbent.seeks
10160}
10161
10162/// Distinct key values on ONE driver page when the page is a contiguous run
10163/// of index order (a bare scan walking its key slot first): each key owns
10164/// `driver_rows / domain` rows, so a page spans `page_rows / fanout` keys.
10165/// This — not the arm's whole domain — is the list the runtime builds from
10166/// a driver chunk and hands to `push_list_covers_domain`. The whole domain
10167/// sits on a page only when the arm fits one page (fanout 1 included),
10168/// which is where the old whole-domain approximation happened to be right.
10169/// A page also cannot hold more distinct values than it has ROWS: a
10170/// partially-filled page (short driver arm) holds at most `driver_rows` of
10171/// them, however large the domain HLL says.
10172pub(crate) fn clustered_page_distinct(driver_rows: u64, domain: u64, page_rows: u64) -> u64 {
10173    if driver_rows == 0 {
10174        return 0;
10175    }
10176    let d = domain.max(1);
10177    let dense = page_rows.saturating_mul(d) / driver_rows;
10178    dense.min(page_rows).min(driver_rows).clamp(1, d)
10179}
10180
10181/// Distinct key values on one driver page when the rows arrive in no key
10182/// order (a join/union output): the page is a `page_rows`-row sample of the
10183/// domain — the occupancy curve `D·(1 − e^(−P/D))`, capped by what a page
10184/// can physically hold. Real mixing lies between this and
10185/// [`clustered_page_distinct`]; the seating decides coverage on the smaller
10186/// bound and prices on the larger, so an unknown order cannot look cheap.
10187fn mixed_page_distinct(domain: u64, page_rows: u64, driver_rows: u64) -> u64 {
10188    let d = domain.max(1) as f64;
10189    let p = page_rows.max(1) as f64;
10190    let mixed = d * (1.0 - (-(p / d)).exp());
10191    ((mixed.ceil() as u64)
10192        .clamp(1, page_rows.max(1))
10193        .min(driver_rows.max(1)))
10194    .min(domain.max(1))
10195}
10196
10197/// Page size the eager join driver actually cuts at: a bare scan driver
10198/// uses [`driver_chunk_rows`] (the stream coalescer's clamp); a
10199/// join-result driver is cut by the query's memory budget against the
10200/// joined page width (`join_chunks`' probe-batch budget). Context-free
10201/// callers (tests, context-free pipelines) fall back to the broadcast
10202/// threshold, the budget-saturated value.
10203fn seat_page_rows(
10204    driver: &PlanNode,
10205    probe: &PlanNode,
10206    ctx: Option<&crate::context::QueryContext>,
10207) -> u64 {
10208    match driver {
10209        PlanNode::Scan(_) => {
10210            let base = ctx.map_or(PUSHDOWN_TERMS_LIMIT as usize, |c| {
10211                c.join_chunk_rows(1, PUSHDOWN_TERMS_LIMIT as usize)
10212            });
10213            crate::join_chunks::driver_chunk_rows(base)
10214        }
10215        _ => {
10216            let width =
10217                crate::join_chunks::join_page_width(driver.output_vars().all().as_slice(), probe)
10218                    .max(1);
10219            ctx.map_or(PUSHDOWN_TERMS_LIMIT, |c| {
10220                c.join_chunk_rows(width, PUSHDOWN_TERMS_LIMIT as usize) as u64
10221            })
10222        }
10223    }
10224}
10225
10226/// Probe-mode broadcast price per driver page, in the two quantities the
10227/// fetch-once predicate folds: the seek list ONE page broadcasts, and the
10228/// matched-row estimate that list returns. The runtime broadcasts exactly one
10229/// list per page: `join_keys_scan_filter` walks `hash_keys` in the stored
10230/// reordered (narrowest-expected-return-first) order and returns the
10231/// FIRST key that is not covered-and-droppable — one `BroadcastFilter`,
10232/// one slot; the other keys' lists never cross the wire (their constraint
10233/// is the hash join itself). The price replicates that pick: the first
10234/// surviving key's list is the broadcast cost and its matched estimate is the
10235/// wire return. The keys arrive already in the runtime reorder's order:
10236/// the gather ([`seat_probe_shape`]) re-derives that ordering itself (same
10237/// cost formula), so each seating orientation prices the pick the runtime
10238/// will broadcast for IT — and the stamp pass, handed the stored (reordered)
10239/// key order, sees the same first survivor the executor picks. Shared by
10240/// [`seat_cost_arithmetic`] (the comparator's probe price) and
10241/// `restamp_fetch_once` (the plan stamp) — ONE price, TWO consumers:
10242/// neither restates the arithmetic, so any difference between the two
10243/// verdicts can only come from their INPUTS, never the math. And the
10244/// inputs CAN differ by moment: the comparator prices during the seating
10245/// rounds, the stamp once more after the final `annotate_liveness`, and
10246/// liveness can move a key domain between the two. The stamp's verdict is
10247/// the authoritative one — it prices the shape the executor runs. The two
10248/// passes are therefore a sequence of gathers, not an enforced fixpoint:
10249/// if the second gather disagrees with the first (a domain moved, a clamp
10250/// landed), the stamp wins and the cost model merely ranked that query's seatings
10251/// on the older shape. Every priced term is an estimate besides — actual
10252/// page contents (keys broadcast, rows matched) can diverge from the
10253/// sketches; the executor's bail-out, not this price, is the correction
10254/// of last resort.
10255/// The surviving broadcast key's page-list size and probe domain: the
10256/// first key in the stored (reordered) order that is not a covered,
10257/// droppable push — `join_keys_scan_filter`'s own pick. ONE definition
10258/// shared by every pricing consumer, so the scan transport price and the
10259/// custom keyed regime price the SAME page list. `None` = every key
10260/// drops (the coverage road's shape).
10261fn first_broadcast_key(
10262    keys: &[(bool, u64, u64, u64)],
10263    coverage_drop_allowed: bool,
10264) -> Option<(u64, u64, u64)> {
10265    keys.iter()
10266        .find(|&&(covered, ..)| !(covered && coverage_drop_allowed))
10267        .map(|&(_, page_val_count, probe_domain, overlap_milli)| {
10268            (page_val_count, probe_domain, overlap_milli)
10269        })
10270}
10271
10272fn probe_broadcast_price(
10273    whole_read_rows: u64,
10274    keys: &[(bool, u64, u64, u64)],
10275    coverage_drop_allowed: bool,
10276) -> (u64, u64) {
10277    // A covered push the drop guard grants broadcasts nothing and the pick
10278    // walks on — the same skip as `join_keys_scan_filter`.
10279    let Some((page_val_count, probe_domain, overlap_milli)) =
10280        first_broadcast_key(keys, coverage_drop_allowed)
10281    else {
10282        // Unreachable from the pricing consumers: the cost model's coverage
10283        // road prices the all-dropped shape (every hash key a covered
10284        // push, `coverage_drop_allowed` granted) as ONE whole read before
10285        // this is called, and `stamp_fetch_once` and the custom keyed
10286        // road decline the same shape before pricing. Kept as the
10287        // no-broadcast price for safety: the probe reads the arm
10288        // unfiltered.
10289        return (0, whole_read_rows);
10290    };
10291    // Unknown probe domain (0) and overflow both fall back to the full
10292    // arm — the documented conservatism. Deliberately NOT the
10293    // driver-side epistemic rule (`fetch_once_verdict` refuses when
10294    // driver domains are unknown): an unknown probe domain degrades to
10295    // what the transport can genuinely return — the runtime never
10296    // covers an unknown domain, so the broadcast list really can match
10297    // the whole arm — whereas an unknown DRIVER domain makes the seeks
10298    // term a guess about lists the runtime builds from actual rows,
10299    // and a guess must not order a whole-arm drain. The full-arm
10300    // fallback is a BOUND, though, so the verdict prices a matched term
10301    // at this basis at the bound rate, not the estimate premium; see
10302    // `FETCH_ONCE_MATCHED_BOUND_EQUIV_MILLI`.
10303    // The matched fraction carries the same containment stamp as the
10304    // coverage verdict: the list matches only the probe rows whose value
10305    // its vocabulary actually reaches — `min(list × r, domain × 1000) /
10306    // (domain × 1000)` of the arm. At r = FULL (1000) the milli factors
10307    // cancel and this is the historical count-only formula, exactly.
10308    // u128 intermediates keep the scaled products far from overflow; the
10309    // old checked-arith whole-read fallback survives only as the
10310    // unknown-domain (0) case, where the runtime genuinely cannot cover.
10311    let matched = if probe_domain == 0 {
10312        whole_read_rows
10313    } else {
10314        // All u128 from the start: the largest term (domain x 1000) is
10315        // below 2^74, so no multiplication here can clamp — widening
10316        // before multiplying is the whole point.
10317        let scaled_list = u128::from(page_val_count) * u128::from(overlap_milli);
10318        let denominator = u128::from(probe_domain) * u128::from(VOCABULARY_OVERLAP_FULL_MILLI);
10319        // The min-clamped numerator bounds the quotient by
10320        // `whole_read_rows` exactly, so the conversion is total;
10321        // `unwrap_or` is a totality guard for that clamp invariant, not
10322        // an overflow backstop.
10323        let quotient = (u128::from(whole_read_rows) * scaled_list.min(denominator)) / denominator;
10324        u64::try_from(quotient).unwrap_or(whole_read_rows)
10325    };
10326    (page_val_count, matched)
10327}
10328
10329/// Whether a probe scan can take the stamped fetch-once branch: a plain
10330/// triple scan (any graph/overlay shape `fetch_whole` serves), NOT one of
10331/// the specialized RPC rewrites — those execute their own cursor protocols
10332/// and emit their own page shapes, and the stamp must not reorder them
10333/// (the scan memo's shape gate and the star's `pageable_scan` make the
10334/// same exclusion). ONE definition, both consumers: the comparator's road
10335/// and the plan stamp read this, so a shape priced as buildable is exactly
10336/// a shape the executor can build.
10337///
10338/// Count scans: `domain_counts` is servable when the walk is list-independent
10339/// — `Rows` mode over one predicate the query binds. See
10340/// [`bound_constraint_count_scan`]; the distinct modes stay excluded because
10341/// their hits carry cardinalities, not terms, so no row table exists to build.
10342pub(crate) fn fetch_once_stampable(scan: &ScanOp) -> bool {
10343    scan.domain_scan.is_none()
10344        && scan.head_scan.is_none()
10345        && (scan.domain_counts.is_none() || bound_constraint_count_scan(scan))
10346        && scan.head_scan_counts.is_none()
10347}
10348
10349/// A count scan whose whole read is list-independent: `domain_counts` in
10350/// `Rows` mode whose constraint is one predicate the query binds.
10351///
10352/// The `DomainScanCounts` request carries a constraint list and **no head
10353/// list**, so such a scan's walk always covers the whole predicate: a pushed
10354/// key list cannot narrow it, because a bound constraint slot takes its term
10355/// from the pattern, not from the push. Every execution of the scan is
10356/// therefore a full walk, which is why it must be built once per query rather
10357/// than once per driver page, and why a rows-per-head measure on it means
10358/// anything at all.
10359///
10360/// The exclusions follow from the request shape: a pushed-predicate arm's list
10361/// *is* its constraint list (so its read is list-dependent), a scan constrained
10362/// by a single subject or object walks one prefix (cheap enough not to care),
10363/// and the distinct modes are fold-only.
10364pub(crate) fn bound_constraint_count_scan(scan: &ScanOp) -> bool {
10365    scan.domain_counts.is_some_and(|kind| {
10366        scan.domain_count_mode() == waratah_storage::DomainCountMode::Rows
10367            && count_scan_covers_one_predicate(scan, kind)
10368    })
10369}
10370
10371/// The predicate-constrained count shapes — `PredicateDomain` and
10372/// `PredicateSubjects` — with the predicate written in the query.
10373pub(crate) fn count_scan_covers_one_predicate(scan: &ScanOp, kind: DomainScanKind) -> bool {
10374    kind.constraint_slot() == PatternSlot::Predicate && scan.pattern.predicate.is_some()
10375}
10376/// Verdict of the priced fetch-once comparison for one (driver, probe)
10377/// seating, in whole row-equivalents (milli-scaled so no float sits in
10378/// the plan path):
10379///
10380/// ```text
10381/// probe price = pages × (broadcast seeks × SEEK_EQUIV_ROWS
10382///                          + matched rows × MATCHED_ROW_EQUIV_ROWS)
10383///               (one list per page: the first surviving key's — the
10384///                runtime's `join_keys_scan_filter` pick)
10385/// build price = MARGIN × whole_read_rows        (the UNCLAMPED whole-arm read)
10386/// ```
10387///
10388/// `matched rows` is priced at `MATCHED_ROW_EQUIV_ROWS` while it is a real
10389/// estimate, and at `MATCHED_BOUND_EQUIV_ROWS` when `matched_is_bound` — the
10390/// probe's key domain was unknown, so `probe_broadcast_price` returned the
10391/// whole arm. That fallback holds for every list, so charging it the full
10392/// premium would let it reach the build bar on its own; the discounted rate
10393/// keeps the real per-row overhead while making the page count carry the
10394/// decision. A known domain whose list covers it keeps the premium: there
10395/// the saturation is exact and the build really is the cheaper road.
10396/// See [`FETCH_ONCE_MATCHED_BOUND_EQUIV_MILLI`].
10397///
10398/// `whole_read_rows` is the arm's unclamped estimate, NOT the push-clamped
10399/// `produced_row_count_estimate`: the build reads the whole arm, and a
10400/// push-clamped number both under-prices the build and under-scales the
10401/// threshold (the canary regression: a 686-row clamp on a 7,659-row arm
10402/// fired the bail-out on a correct drain).
10403///
10404/// The exchange rates are passed in, never read here: they belong ONLY to
10405/// fetch-once-class decisions — the seating
10406/// comparator's own {rows, seeks} order stays rate-free, and this
10407/// predicate is the sole place the two currencies meet.
10408#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10409pub(crate) enum FetchOnceVerdict {
10410    FetchOnce,
10411    PerPage,
10412}
10413
10414#[allow(clippy::too_many_arguments)]
10415fn fetch_once_verdict(
10416    pages: u64,
10417    seeks_per_page: u64,
10418    matched_per_page: u64,
10419    whole_read_rows: u64,
10420    whole_read_rows_known: bool,
10421    driver_domains_known: bool,
10422    matched_is_bound: bool,
10423    seek_equiv_milli: u128,
10424    matched_row_equiv_milli: u128,
10425    matched_bound_equiv_milli: u128,
10426    seek_concurrency_milli: u128,
10427    margin_milli: u128,
10428) -> FetchOnceVerdict {
10429    // Nothing to build: an empty-arm estimate is noise, and a zero-row
10430    // build is what the executor's `Empty` verdict already handles.
10431    if whole_read_rows == 0 || pages == 0 {
10432        return FetchOnceVerdict::PerPage;
10433    }
10434    // No build decision on missing evidence: a missing driver-domain
10435    // sketch prices a full page of seeks per key — the worst-case guess —
10436    // and that guess must not order a whole-arm drain (the same epistemic
10437    // rule the coverage gate applies to its list-length guard). The
10438    // probe-side unknown is the deliberate asymmetry: it degrades to the
10439    // full-arm matched price, which mirrors what the transport can really
10440    // return (see `probe_broadcast_price`). That degradation is a bound,
10441    // though, so the matched term below prices it at the bound rate rather
10442    // than the estimate premium.
10443    if !driver_domains_known {
10444        return FetchOnceVerdict::PerPage;
10445    }
10446    // The same rule on the arm side: without a profile the "unclamped"
10447    // estimate is the clamped `produced_row_count_estimate` fallback — a
10448    // fiction, and a TINY fiction plus a few pages clears the margin and
10449    // stamps a whole-arm drain the estimates never justified (the drain
10450    // then pays the bail-out). A point lookup's single row is structural,
10451    // not estimated, so it stays known.
10452    if !whole_read_rows_known {
10453        return FetchOnceVerdict::PerPage;
10454    }
10455    // The matched-rate choice and the price arithmetic live in
10456    // [`fetch_once_price_milli`], shared with the general semi-join
10457    // admission's diagnostic so both report the same number the verdict
10458    // consumed.
10459    let price = fetch_once_price_milli(
10460        pages,
10461        seeks_per_page,
10462        matched_per_page,
10463        matched_is_bound,
10464        seek_equiv_milli,
10465        matched_row_equiv_milli,
10466        matched_bound_equiv_milli,
10467        seek_concurrency_milli,
10468    );
10469    let threshold = margin_milli.saturating_mul(whole_read_rows as u128);
10470    if price >= threshold {
10471        FetchOnceVerdict::FetchOnce
10472    } else {
10473        FetchOnceVerdict::PerPage
10474    }
10475}
10476
10477/// The priced per-page road of a fetch-once-class decision, in milli
10478/// row-equivalents.
10479///
10480/// An unknown probe key domain makes `probe_broadcast_price` return the
10481/// whole arm as the matched count. That bound is identical for a one-key
10482/// and a million-key list, so it cannot decide the road; charging it the
10483/// estimate premium made a one-page, 16-key probe reach the bar on the
10484/// matched term alone, and the seeks then ordered a whole-store drain. The
10485/// bound rate keeps the per-row overhead and lets the page count (which is
10486/// what a whole-read-per-page road really repeats) decide. A known domain
10487/// that saturates the fraction keeps the premium: there the push really
10488/// does return every row, so the whole read is the cheaper road.
10489///
10490/// Saturating u128 throughout: astronomic estimates must decide, not panic
10491/// (a saturated price simply fires the build). The seek term scales by
10492/// `1000 / seek_concurrency_milli` (1000 milli = the sequential road — one
10493/// seek at a time; > 1000 prices fetch concurrency the executor will
10494/// actually deliver, e.g. a star arm's batched chunk fetches under the
10495/// arm-permit pool; the ×1000/÷milli form keeps fractional concurrency
10496/// like 1.5 exact in integer arithmetic). The matched-rows term never
10497/// divides: matched rows cross the wire exactly once however the fetches
10498/// are scheduled — but each one still costs its own fetch-plus-assembly
10499/// price (`matched_equiv_milli`, the wire row plus decode/intern and
10500/// batch-table build), not the plain streamed-row 1000.
10501#[allow(clippy::too_many_arguments)]
10502fn fetch_once_price_milli(
10503    pages: u64,
10504    seeks_per_page: u64,
10505    matched_per_page: u64,
10506    matched_is_bound: bool,
10507    seek_equiv_milli: u128,
10508    matched_row_equiv_milli: u128,
10509    matched_bound_equiv_milli: u128,
10510    seek_concurrency_milli: u128,
10511) -> u128 {
10512    let matched_equiv_milli = if matched_is_bound {
10513        matched_bound_equiv_milli
10514    } else {
10515        matched_row_equiv_milli
10516    };
10517    (pages as u128).saturating_mul(
10518        (seeks_per_page as u128)
10519            .saturating_mul(seek_equiv_milli)
10520            .saturating_mul(1000)
10521            .saturating_div(seek_concurrency_milli.max(1))
10522            .saturating_add((matched_per_page as u128).saturating_mul(matched_equiv_milli)),
10523    )
10524}
10525
10526/// [`fetch_once_verdict`] on the process tunables — the one read both
10527/// consumers (comparator road and plan stamp) share, so an override moves
10528/// both together.
10529#[allow(clippy::too_many_arguments)]
10530fn fetch_once_verdict_now(
10531    pages: u64,
10532    seeks_per_page: u64,
10533    matched_per_page: u64,
10534    whole_read_rows: u64,
10535    whole_read_rows_known: bool,
10536    driver_domains_known: bool,
10537    matched_is_bound: bool,
10538    seek_concurrency_milli: u128,
10539) -> FetchOnceVerdict {
10540    fetch_once_verdict(
10541        pages,
10542        seeks_per_page,
10543        matched_per_page,
10544        whole_read_rows,
10545        whole_read_rows_known,
10546        driver_domains_known,
10547        matched_is_bound,
10548        crate::query::tunables::fetch_once_seek_equiv_milli(),
10549        crate::query::tunables::fetch_once_matched_row_equiv_milli(),
10550        crate::query::tunables::fetch_once_matched_bound_equiv_milli(),
10551        seek_concurrency_milli,
10552        crate::query::tunables::fetch_once_margin_milli(),
10553    )
10554}
10555
10556/// Seek-price concurrency for the parallel probe road (milli: 1000 =
10557/// sequential — the price for every join the executor will not batch).
10558/// The road dispatches allow-list chunk fetches concurrently under the
10559/// arm-permit pool, and the divisor must price the concurrency the
10560/// executor can fund and form:
10561///
10562/// - the FUNDED FETCH CONCURRENCY: the engine's full fetch concurrency
10563///   (`fetch_concurrency × 1000`) —
10564///   the pool's free permits (`QUERY_FETCH_CONCURRENCY`; the pool holds one
10565///   more for the query root's whole-execution hold). This resolves the
10566///   pricing circularity — plan time cannot know which siblings carry
10567///   FetchOnce verdicts, and the credit cannot wait for them — toward
10568///   the measured corpus case: a batched arm's FetchOnce-built siblings
10569///   hold no batch permits (one whole-read RPC each), so the batched
10570///   arm really runs at the full fetch concurrency, which the A/B measured directly
10571///   (realized 2.16–2.47 on the flagship's shape; pricing that arm at
10572///   an arm-count-divided credit flipped it to the road measured ~58%
10573///   slower). KNOWN BIAS, the mirror of that choice: a spine whose arms
10574///   ALL run wide parallel-probe roads shares the pool at execution, and each is
10575///   then over-credited (by up to the arm count on the seek term). No
10576///   measured corpus arm runs a parallel-probe road in the mispricing band
10577///   today; the chunks gate bounds small arms; the margin absorbs the
10578///   rest. Revisit condition: a measured spine whose arms all take the
10579///   parallel-probe road — the structured fix is two-pass stamping (re-price the
10580///   PerPage arms against the sibling set that stayed PerPage), which
10581///   this stamp walk's structure already permits.
10582/// - the CHUNK gate: the road's concurrency unit is one
10583///   threshold-sized allow-list chunk (`PUSHDOWN_TERMS_LIMIT` terms).
10584///   A batch forming fewer chunks than the engine's fetch concurrency is
10585///   funded at the chunk count — which the measured curve then maps
10586///   sublinearly, one chunk being one RPC, sequential by construction
10587///   (the curve's 1000 floor), and a divisor on it would under-price a
10588///   road that cannot overlap.
10589/// - the MEASURED CURVE: funding `w` permits does not buy a `w`-fold
10590///   wall-clock speedup — the fetch path is part CPU work (decode,
10591///   dedup, table assembly), so realized speedup is sublinear in the
10592///   funded fetch concurrency and saturates near the box's physical core count. The
10593///   funded milli (the engine's fetch concurrency bounded by the chunk count) is mapped
10594///   through `PROBE_SEEK_CONCURRENCY_CURVE`, a measured
10595///   (funded fetch concurrency → realized milli) table.
10596/// - the ENGINE-OFF floor: a configured fetch concurrency below 2 disables the
10597///   parallel-probe engine (every probe road per page, sequential), so
10598///   the divisor is exactly 1000 whatever the stamp says.
10599///
10600/// Gated by the executor's batch membership: a star spine via `star_arms`
10601/// (the spine head's own stamp, or the inherited context down the left
10602/// spine), a batchable single-arm join at arm_count 1 via the shared
10603/// eligibility predicate (`scan_hosts_broadcast_key`), and NOTHING beneath a
10604/// Slice — the slice cursor runs every
10605/// join per-page, so `restamp_fetch_once` passes no arm count at all
10606/// (sequential price). The seating comparator — the predicate's other
10607/// consumer — always passes 1000: its candidate orientations do not exist
10608/// as trees, so the spine's arm count is unknowable there, and cost estimates
10609/// stay bit-identical to the pre-batching planner (see the parallel-probe
10610/// plan's feedback discussion).
10611fn probe_seek_concurrency_milli(
10612    batched: bool,
10613    pages: u64,
10614    seeks_per_page: u64,
10615    fetch_concurrency: u64,
10616) -> u128 {
10617    if !batched {
10618        return 1000;
10619    }
10620    // Engine off (fetch concurrency below 2): the plan-side gate already passes
10621    // `batched = false`; this floor states the same rule at the
10622    // arithmetic, so the divisor can never price concurrency no road
10623    // delivers.
10624    if fetch_concurrency < 2 {
10625        return 1000;
10626    }
10627    let total_seeks = pages.saturating_mul(seeks_per_page);
10628    let chunks = total_seeks.div_ceil(waratah_stats::PUSHDOWN_TERMS_LIMIT);
10629    // A road with no seeks forms no chunks — the no-broadcast mirror
10630    // road prices seeks = 0, so `chunks` can be 0 despite pages ≥ 1.
10631    // There is no batch fetch concurrency to price over an empty chunk
10632    // set, so the divisor keeps its sequential contract instead of
10633    // collapsing to zero.
10634    if chunks == 0 {
10635        return 1000;
10636    }
10637    // Realized fetch concurrency: the engine's full fetch concurrency (see the doc
10638    // above for the circularity resolution and its known bias), bounded
10639    // by the chunk count the batch actually forms (chunks ≥ 1 past the
10640    // zero-chunk guard above), then
10641    // mapped through the measured curve. The outer `min` with the
10642    // funded milli is a totality guard, and the saturating multiply on
10643    // the engine term keeps an unclamped knob value from wrapping the
10644    // funded milli into an arbitrary curve input.
10645    let funded_milli = fetch_concurrency
10646        .saturating_mul(1000)
10647        .min(chunks.saturating_mul(1000));
10648    funded_milli.min(crate::query::tunables::probe_seek_concurrency_realized_milli(funded_milli))
10649        as u128
10650}
10651
10652/// The arithmetic half of [`seat_cost_total`]: per-key lists and coverage
10653/// verdicts are already gathered; this prices the seating. Split out so the
10654/// fixture tests can pin the arithmetic on hand-computed tables without
10655/// building plan nodes.
10656///
10657/// `whole_read_rows` is the ONE row basis for every road: what one whole
10658/// read of the arm returns, and the base the per-page matched fraction
10659/// scales — the matched term and the build threshold price the same fetch,
10660/// so they share the same number.
10661#[allow(clippy::too_many_arguments)]
10662fn seat_cost_arithmetic(
10663    driver_rows: u64,
10664    whole_read_rows: u64,
10665    probe_memoizable: bool,
10666    pages: u64,
10667    keys: &[(bool, u64, u64, u64)],
10668    coverage_drop_allowed: bool,
10669    probe_stampable: bool,
10670    whole_read_rows_known: bool,
10671    driver_domains_known: bool,
10672    probe_count_walk: bool,
10673    subtree_page: Option<SeatCost>,
10674) -> SeatCost {
10675    if driver_rows == 0 {
10676        return SeatCost { rows: 0, seeks: 0 };
10677    }
10678    if keys.is_empty() {
10679        // The interior keys broadcast no list — unshippable positions, or
10680        // a key the gather cannot prove on this arm. Under a containing
10681        // push the ancestor filter still re-applies on every page, so the
10682        // pushed road (`subtree_page` — the walk's or the mirror's
10683        // per-page price) replaces the one unfiltered read; without a
10684        // containing push, one unfiltered read serves every page.
10685        if let Some(road) = subtree_page {
10686            return SeatCost {
10687                rows: driver_rows.saturating_add(pages.saturating_mul(road.rows)),
10688                seeks: pages.saturating_mul(road.seeks),
10689            };
10690        }
10691        return SeatCost {
10692            rows: driver_rows.saturating_add(whole_read_rows),
10693            seeks: 0,
10694        };
10695    }
10696    if keys.iter().all(|&(covered, _, _, _)| covered) && coverage_drop_allowed {
10697        // One unbound probe read serves every page: a memoized scan, or a
10698        // subtree built once and reused. The read IS the whole-arm fetch,
10699        // so it prices at the UNCLAMPED `whole_read_rows` — the same number the
10700        // fetch-once road names for the identical operation; pricing the two
10701        // roads differently would let cost ordering hinge on which road
10702        // happened to fire. A memoizable scan adds one
10703        // read for the refusal-correction risk (an estimate miss costs
10704        // exactly one full-arm fetch, then the filter returns). For a
10705        // subtree probe `whole_read_rows` is the clamp — there is no unclamped
10706        // price — so this only changes scan arms.
10707        let extra = u64::from(probe_memoizable) * whole_read_rows;
10708        return SeatCost {
10709            rows: driver_rows
10710                .saturating_add(whole_read_rows)
10711                .saturating_add(extra),
10712            seeks: 0,
10713        };
10714    }
10715    let (seeks_per_page, matched_per_page) = match subtree_page {
10716        // The leaf-walk price: the subtree's per-page execution
10717        // under the pushed list, already keyed — the broadcast scaling
10718        // below must NOT apply again, or the subtree's selectivity
10719        // double-counts. The walk's own conservatism (an unknown-domain
10720        // leaf prices a full-arm match) is what the parent inherits.
10721        Some(page) => (page.seeks, page.rows),
10722        None => probe_broadcast_price(whole_read_rows, keys, coverage_drop_allowed),
10723    };
10724    // A bound-predicate count walk cannot be keyed: the `DomainScanCounts`
10725    // request takes a constraint list and no head list, so its per-page road
10726    // is one whole walk per page. With more than one page the build is
10727    // strictly cheaper and there is nothing for the priced roads to compare;
10728    // one page ties on the walk and the per-page read still prunes to that
10729    // page's keys, so the priced roads below stay. `stamp_fetch_once` forces
10730    // the same verdict by the same rule, so the cost model and the stamp cannot
10731    // split on which road runs.
10732    if probe_count_walk && pages > 1 {
10733        return SeatCost {
10734            rows: driver_rows.saturating_add(whole_read_rows),
10735            seeks: 0,
10736        };
10737    }
10738    // The SECOND road into the build price: the priced fetch-once
10739    // trigger. The coverage road above needs one
10740    // batch's list to cover the probe domain; this road needs only the
10741    // seek-vs-drain economics to lose for per-page mode — which is the
10742    // shape the coverage rule can never fire on (many small lists, each
10743    // page re-paying seeks and matched rows). `probe_stampable` is the
10744    // executor's ability to honor the stamp (a plain-Scan right arm);
10745    // without it the cost model must price the transport the runtime will
10746    // actually run, not a build it cannot order. The build price is the
10747    // UNCLAMPED `whole_read_rows` (the whole read), with no risk extra — the
10748    // bail-out and the per-query budget bound a wrong estimate, and a
10749    // synthetic +1× extra was measured distorting seatings (the canary
10750    // regression: the extra outweighed whole arms and flipped the seating
10751    // off the pipelined star).
10752    // The matched term is the unknown-domain fallback exactly when the
10753    // broadcast pick's probe domain is unknown — that is the one case
10754    // `probe_broadcast_price` answers with the whole arm. The verdict prices
10755    // that fallback at the bound rate; a known domain that saturates the
10756    // fraction keeps the premium. The leaf-walk's own per-page price is not a
10757    // broadcast fallback, so it never takes the bound rate.
10758    let matched_is_bound = subtree_page.is_none()
10759        && first_broadcast_key(keys, coverage_drop_allowed)
10760            .is_some_and(|(_, probe_domain, _)| probe_domain == 0);
10761    if probe_stampable
10762        && fetch_once_verdict_now(
10763            pages,
10764            seeks_per_page,
10765            matched_per_page,
10766            whole_read_rows,
10767            whole_read_rows_known,
10768            driver_domains_known,
10769            matched_is_bound,
10770            // The comparator is deliberately divisor-free: its candidate
10771            // orientations do not exist as trees, so a spine's arm count —
10772            // the divisor's input — is unknowable here, and cost estimates
10773            // stay bit-identical to the pre-batching planner. The star-aware
10774            // form lives in the final `restamp_fetch_once` pass, on the
10775            // settled tree where the stamp's arm count is a fact.
10776            1000,
10777        ) == FetchOnceVerdict::FetchOnce
10778    {
10779        return SeatCost {
10780            rows: driver_rows.saturating_add(whole_read_rows),
10781            seeks: 0,
10782        };
10783    }
10784    SeatCost {
10785        // Pure row work — seeks are a separate currency, compared only
10786        // inside the swap margin (`seat_beats`), never folded in at an
10787        // implicit weight.
10788        rows: driver_rows.saturating_add(pages.saturating_mul(matched_per_page)),
10789        seeks: pages.saturating_mul(seeks_per_page),
10790    }
10791}
10792
10793/// The gathered half of [`seat_cost_total`]: everything about one
10794/// (driver, probe) seating that the pricing and the fetch-once stamp both
10795/// consume — page count, per-key `(covered, `page_val_count`,
10796/// probe domain)` tuples, and the amortization guard's drop verdict.
10797/// The PAGE basis is the ownership-aware whole read
10798/// (`driver_whole_read_rows`) — the rows the executor actually STREAMS
10799/// and cuts into pages: a scan's read, a subtree's output cell — so a
10800/// claim-clamped driver cell never under-counts the pages. This is a
10801/// different quantity from the cost model's driver WORK for a subtree driver
10802/// (the once-execution interior cost, `driver_once_cost`): pages count
10803/// what the driver streams, the work is what producing the stream
10804/// cost.
10805/// Factored so the plan stamp (`restamp_fetch_once`) runs the SAME
10806/// arithmetic as the comparator — one gather, one price, two consumers.
10807/// The inputs can still differ by moment: the comparator prices during
10808/// the seating rounds, the stamp after the last `annotate_liveness`
10809/// (whose liveness can move a key domain), and the stamp's verdict is
10810/// the one the runtime honors.
10811///
10812/// `driver_row_bound` is the stamp walk's containing-push conditioning:
10813/// when the seating executes inside the keyed probe arm of an ancestor
10814/// join, the ancestor's per-page key push bounds the driver's streamed
10815/// rows (every driver scan hosting the pushed key answers keyed per
10816/// execution), and the standalone basis would page a stream that never
10817/// happens. The bound only ever LOWERS the basis (`min`) — it is an
10818/// estimate-of-estimates (the ancestor's matched-per-page), so it may
10819/// under- or over-shoot the true keyed answer, but it can never inflate
10820/// the standalone geometry. `None` (the comparator's argument) keeps the
10821/// standalone whole-read basis unchanged.
10822struct SeatProbeShape {
10823    pages: u64,
10824    /// Per key in the stored (reordered) order: `(covered, page list size,
10825    /// probe domain, overlap milli)` — the coverage verdict carries the
10826    /// vocabulary containment stamp (`resolve_key_overlap_milli`), the
10827    /// same fraction the matched-rows price scales by.
10828    keys: Vec<(bool, u64, u64, u64)>,
10829    /// The variable the runtime's own pick broadcasts per page —
10830    /// `first_broadcast_key`'s survivor in the reordered key order,
10831    /// recovered as a `Variable` so push-conditioning consumers (the
10832    /// stamp walk's containing-push context) can NAME the push. `None` =
10833    /// every key drops (the coverage road's once shape, which pushes no
10834    /// list at all).
10835    broadcast_key: Option<Variable>,
10836    coverage_drop_allowed: bool,
10837    /// Whether every key's driver-side domain sketch existed. A missing
10838    /// sketch prices a full page of seeks — the conservative guess — and
10839    /// that guess is NOT evidence per-page mode is expensive (the same
10840    /// epistemic rule the coverage gate applies to its length guard). The
10841    /// fetch-once predicate refuses to fire on it.
10842    driver_domains_known: bool,
10843}
10844
10845fn seat_probe_shape(
10846    profile: Option<&StatsProfile>,
10847    driver: &PlanNode,
10848    probe: &PlanNode,
10849    hash_keys: &[Variable],
10850    ctx: Option<&crate::context::QueryContext>,
10851    driver_row_bound: Option<u64>,
10852) -> SeatProbeShape {
10853    // Driver basis: the ownership-aware whole read (`driver_whole_read_rows`)
10854    // — the PAGE basis, the rows the executor streams, never the raw cell. A
10855    // driver scan clamped by its OWN claim carries the probe road's return
10856    // in its cell (e.g. ~80 on a 50k-catalog arm); counting pages off that
10857    // would price ONE page where the driving read streams three, and every
10858    // per-page list/seek/matched price built on the page count under-prices
10859    // the cost model (the phantom-page defect — the tenant-union flip's class).
10860    // Both consumers of this gather — the comparator and the fetch-once
10861    // stamp — take the fix; a foreign claim's cell IS the bounded whole
10862    // read and prices unchanged.
10863    let mut driver_rows = driver_whole_read_rows(driver, hash_keys, profile);
10864    if let Some(bound) = driver_row_bound {
10865        // Containing-push conditioning (see the doc above): min-guarded,
10866        // so the bound can only shrink the standalone basis — a stale
10867        // Build stamp priced on a multi-page standalone driver is what
10868        // this removes; a borderline conditioned geometry keeps its
10869        // stamp through the verdict's own build-side MARGIN.
10870        driver_rows = driver_rows.min(bound);
10871    }
10872    let page_rows = seat_page_rows(driver, probe, ctx);
10873    let pages = driver_rows.div_ceil(page_rows.max(1));
10874    let scan_driver = driver.as_scan().is_some();
10875    // The probe basis is DELIBERATELY the cell (push-clamped), and it feeds
10876    // ONLY the reorder-cost emulation below: the runtime's own pick
10877    // (`reorder_hash_keys_by_probe_return`) sorts on the same cell, and the
10878    // gather must reproduce that pick, not re-price it — the costs are
10879    // discarded after the sort. The cost model's PRICE basis (the arm's unclamped
10880    // whole read) lives in `seat_cost_total` and never enters here.
10881    let probe_rows = probe.produced_row_count_estimate();
10882
10883    // Per key: the list one page holds (cover-decided on the smaller bound,
10884    // priced on the larger), whether the coverage rule would skip it, and
10885    // the runtime reorder's expected-return cost — the gather re-derives
10886    // `reorder_hash_keys_by_probe_return`'s own ordering (same formula)
10887    // before pricing, so the priced pick is the key the runtime broadcasts for
10888    // THIS orientation. The caller's key order cannot matter: the swap
10889    // unwind prices BOTH orientations from one stored order (reordered for
10890    // the as-built shape), and the pick is order-sensitive in a way the
10891    // old sum model was not.
10892    let mut keys: Vec<(bool, u64, u64, u64, Option<u128>, Variable)> =
10893        Vec::with_capacity(hash_keys.len());
10894    let mut driver_domains_known = true;
10895    for key in hash_keys {
10896        let driver_domain = join_key_domain_for_node(profile, driver, key);
10897        let probe_domain_opt = join_key_domain_for_node(profile, probe, key);
10898        let probe_domain = probe_domain_opt.unwrap_or(0);
10899        let reorder_cost = if !probe_scan_has_key(probe, key) {
10900            None
10901        } else {
10902            match (driver_domain, probe_domain_opt) {
10903                (Some(driver_domain), probe_domain) => {
10904                    Some((driver_domain as u128).saturating_mul(match probe_domain {
10905                        Some(domain) => (probe_rows as u128) / domain.max(1) as u128,
10906                        None => 1,
10907                    }))
10908                }
10909                (None, _) => None,
10910            }
10911        };
10912        let (cover_len, page_val_count) = match driver_domain {
10913            // Unknown driver domain: the price stays the expensive guess
10914            // (a full page of seeks — physically bounded by the driver's
10915            // own rows), but the coverage list must FAIL the predicate's
10916            // length guard — a missing sketch is not evidence that a page
10917            // holds enough distinct values to drop the push. The runtime
10918            // builds its list from the rows it actually has.
10919            None => {
10920                driver_domains_known = false;
10921                (1, page_rows.min(driver_rows.max(1)))
10922            }
10923            Some(d) => {
10924                let clustered = clustered_page_distinct(driver_rows, d, page_rows);
10925                if scan_driver {
10926                    (clustered, clustered)
10927                } else {
10928                    let mixed = mixed_page_distinct(d, page_rows, driver_rows);
10929                    (clustered.min(mixed), clustered.max(mixed))
10930                }
10931            }
10932        };
10933        // The containment fraction between the two arms' key vocabularies
10934        // — ONE resolution shared with the stamp walk and the runtime
10935        // stamps (`resolve_key_overlap_milli`). FULL on every unknown, so
10936        // the covered verdict below reduces to the count rule exactly.
10937        let overlap_milli = resolve_key_overlap_milli(profile, driver, probe, key);
10938        let covered = crate::query::pushdown::push_list_covers_domain(
10939            usize::try_from(cover_len).unwrap_or(usize::MAX),
10940            probe_domain,
10941            overlap_milli,
10942        );
10943        keys.push((
10944            covered,
10945            page_val_count,
10946            probe_domain,
10947            overlap_milli,
10948            reorder_cost,
10949            key.clone(),
10950        ));
10951    }
10952    // Stable sort, unknown cost (unhosted or unsizable key) LAST — the
10953    // runtime reorder's own ordering, reproduced.
10954    keys.sort_by_key(|&(_, _, _, _, cost, _)| cost.unwrap_or(u128::MAX));
10955
10956    // The amortization guard decides whether covered pushes really drop;
10957    // denied drops broadcast the (near-whole-domain) list like any other.
10958    let coverage_drop_allowed =
10959        crate::query::pushdown::source_coverage_drop(driver, probe, page_rows);
10960    // The broadcast pick as a VARIABLE: the same survivor
10961    // `first_broadcast_key` finds (the first key of the reorder order
10962    // that is not covered-and-droppable — `join_keys_scan_filter`'s own
10963    // pick), extracted HERE because this is the last moment the tuples
10964    // still carry the variable. The stamp walk's containing-push context
10965    // must name the key the runtime actually pushes, not just any hash
10966    // key, or it would condition drivers on a push that never lands.
10967    let broadcast_key = keys
10968        .iter()
10969        .find(|&&(covered, _, _, _, _, _)| !(covered && coverage_drop_allowed))
10970        .map(|(_, _, _, _, _, key)| key.clone());
10971    let keys: Vec<(bool, u64, u64, u64)> = keys
10972        .into_iter()
10973        .map(|(c, d, p, r, _, _)| (c, d, p, r))
10974        .collect();
10975    SeatProbeShape {
10976        pages,
10977        keys,
10978        broadcast_key,
10979        coverage_drop_allowed,
10980        driver_domains_known,
10981    }
10982}
10983
10984/// Seat pricing for one orientation — "`driver` streams `driver_rows` over
10985/// `pages` pages; the probe answers each page's pushed value lists". The
10986/// arithmetic calls the eager executor's own policy instead of restating it:
10987///
10988/// - the per-page list is what the page actually holds
10989///   ([`clustered_page_distinct`] for a scan driver's index order; any
10990///   other driver prices both mixing bounds — cover-decided on the
10991///   smaller, priced on the larger);
10992/// - coverage is the runtime's own
10993///   [`crate::query::pushdown::push_list_covers_domain`];
10994/// - whether a covered push really drops is the runtime's own
10995///   [`crate::query::pushdown::source_coverage_drop`] amortization guard;
10996/// - an all-dropped probe is fetched once (a memoized scan, or a subtree
10997///   built once and reused — `ProbePushed::Ancestor`); a memoizable scan
10998///   adds one extra read for the runtime's memo-refusal correction;
10999/// - a probe whose priced broadcast cost loses to `MARGIN ×` one whole read is
11000///   BUILT once ([`fetch_once_verdict_now`]) — the same predicate that
11001///   stamps the executor's `ScanOp::fetch_once`, so the cost model prices the
11002///   transport the runtime will actually run;
11003/// - ONE surviving key's list broadcasts per page: the first in the stored
11004///   reordered (narrowest-expected-return-first) key order that is not
11005///   covered-and-droppable — `join_keys_scan_filter`'s own pick, one
11006///   `BroadcastFilter` and one slot on the wire. The price takes that
11007///   pick's list and its matched estimate; the other keys constrain in
11008///   the hash join, after the wire, and cost nothing to broadcast.
11009/// - a STAMPED custom arm takes its own roads (`CustomOpCost`): a custom
11010///   probe answers each page's list with the keyed regime at zero seeks
11011///   (the sweep once, on the keys-empty and coverage roads), and a custom
11012///   driver's work is its sweep — output rows are cardinality, not
11013///   cost. Unstamped ops price at the row estimate, unchanged.
11014///
11015/// The kept-key subtree probe is priced by the LEAF-WALK:
11016/// [`subtree_page_cost`] descends into the subtree and prices its scan
11017/// leaves individually under the lists that reach them, with contained
11018/// joins' drivers re-geometried by the containing push (the same
11019/// `ContainingPush` model the stamp walk conditions its verdicts on —
11020/// one derivation, shared via [`child_push_from_shape`], so the
11021/// conditioned PRICE and the conditioned STAMP cannot drift). Once-roads
11022/// (keys-empty joins, all-covered probes) still price the subtree's
11023/// single execution at its produced clamp. Unknown driver domains never
11024/// cover and price a full page of seeks; unknown probe domains never
11025/// cover and match the whole arm — the runtime's own conservatism on both
11026/// sides, inherited by the walk's leaves.
11027///
11028/// `containing` is the inherited push when this call prices a join INSIDE
11029/// a keyed subtree probe arm (the leaf-walk's recursion); every top-level
11030/// caller passes `None` — the subtree branch derives this join's own push
11031/// from its keyed road.
11032/// The receiving-scan road the executor's filter merge actually runs for
11033/// a bare-scan probe arm under an ancestor push —
11034/// `Some` per-page `(seeks, matched)` when the pushed road replaces the
11035/// interior-keyed road, `None` when it does not: no containing push, the
11036/// probe does not host the key, no broadcastable slot, or — same slot —
11037/// the interior road is the cheaper bound on the intersected lists.
11038/// WHICH road executes is the executor's filter-merge policy
11039/// (`merge_broadcast_filters`), not a price comparison: on DIFFERENT
11040/// slots the ancestor filter always wins (outer-first — a shorter
11041/// interior key never steals the BroadcastFilter), so the ancestor road
11042/// is priced unconditionally, even when the interior road would price
11043/// cheaper; on the SAME slot the two lists intersect, the intersection's
11044/// answer sits below both roads, and the cheaper road stays a safe
11045/// conservative bound. ONE derivation for the two consumers — the cost model's
11046/// per-page price and the fetch-once stamp's verdict inputs — so the
11047/// price and the stamp can never disagree about which road runs.
11048fn probe_side_mirror_road(
11049    profile: Option<&StatsProfile>,
11050    probe: &PlanNode,
11051    hash_keys: &[Variable],
11052    shape_keys: &[(bool, u64, u64, u64)],
11053    coverage_drop_allowed: bool,
11054    containing: Option<&ContainingPush>,
11055) -> Option<SeatCost> {
11056    let scan = probe.as_scan()?;
11057    let push = containing?;
11058    if !probe_scan_has_key(probe, &push.key) {
11059        return None;
11060    }
11061    let ancestor_slot = scan.first_slot_of(&push.key)?;
11062    let whole_read = estimate_unclamped_scan_rows(profile, scan);
11063    let domain = join_key_domain_for_node(profile, probe, &push.key).unwrap_or(0);
11064    // The ancestor list's overlap is unresolved here (the ancestor's
11065    // driver arm is not in scope), so the pushed road prices at FULL —
11066    // the historical behavior for this road; containment v1 covers THIS
11067    // join's own pushed lists.
11068    let pushed_road = probe_broadcast_price(
11069        whole_read,
11070        &[(
11071            false,
11072            push.pushed_val_count,
11073            domain,
11074            VOCABULARY_OVERLAP_FULL_MILLI,
11075        )],
11076        false,
11077    );
11078    // The executor's interior filter is the FIRST SURVIVING broadcast key
11079    // (`join_keys_scan_filter` walks the join's keys in stored order,
11080    // skipping empty lists, lists over the PUSHDOWN_TERMS_LIMIT terms limit, and —
11081    // when the drop guard grants it — lists that cover the probe's key
11082    // domain; the first remaining key with an S/P/O slot becomes the one
11083    // BroadcastFilter). One deliberate divergence: this plan-time walk
11084    // skips over-threshold lists unconditionally, while the eager
11085    // Broadcast-stamped join's executor keeps them (the parallel pushdown
11086    // transports them as chunked fetches), so for an over-threshold-only key
11087    // the plan prices the whole/ancestor road while the executor pushes.
11088    // Advisory-only — the price orders roads, never changes results. `merge_broadcast_filters` then keeps ONE filter:
11089    // the ancestor's whenever that survivor's slot differs from the
11090    // ancestor slot (outer-first — a shorter interior key never steals
11091    // the filter), intersected when they match. Sharing the ancestor's
11092    // slot with some OTHER hash key is not the test — the surviving
11093    // key's slot is.
11094    let survivor_slot =
11095        hash_keys
11096            .iter()
11097            .zip(shape_keys)
11098            .find_map(|(key, &(covered, list, _, _))| {
11099                if list == 0 || list > PUSHDOWN_TERMS_LIMIT || (coverage_drop_allowed && covered) {
11100                    return None;
11101                }
11102                scan.first_slot_of(key)
11103            });
11104    match survivor_slot {
11105        // Same slot: the two lists intersect — the intersection's answer
11106        // sits below both roads, so the cheaper road stays a safe
11107        // conservative bound. (A survivor exists here, so `shape_keys`
11108        // carries a real broadcast key and this price cannot be the
11109        // no-list sentinel.)
11110        Some(slot) if slot == ancestor_slot => {
11111            let own_road = probe_broadcast_price(whole_read, shape_keys, coverage_drop_allowed);
11112            // Rows decide, seeks break ties — SeatCost's own ordering.
11113            ((pushed_road.1, pushed_road.0) < (own_road.1, own_road.0)).then_some(SeatCost {
11114                rows: pushed_road.1,
11115                seeks: pushed_road.0,
11116            })
11117        }
11118        // Different slots, or no surviving interior key (every list
11119        // covered, empty, or over-threshold): `merge(outer, _)` keeps the
11120        // ancestor filter — the ancestor road runs, unconditionally, even
11121        // when the interior road would price cheaper.
11122        _ => Some(SeatCost {
11123            rows: pushed_road.1,
11124            seeks: pushed_road.0,
11125        }),
11126    }
11127}
11128
11129fn seat_cost_total(
11130    profile: Option<&StatsProfile>,
11131    driver: &PlanNode,
11132    probe: &PlanNode,
11133    hash_keys: &[Variable],
11134    ctx: Option<&crate::context::QueryContext>,
11135    containing: Option<&ContainingPush>,
11136) -> SeatCost {
11137    seat_calls_bump();
11138    // The driver's read is ownership-aware (`driver_whole_read_rows`): a foreign
11139    // ancestor push bounds the driver's whole read, this join's own claim
11140    // bound does not (orientation-dependent — same rule as the comparator's
11141    // legacy arm reads). A stamped custom driver prices its sweep WORK
11142    // instead (`seat_driver_work_rows`) — output rows under-count the
11143    // window-wide drain + relate pass. A SUBTREE driver prices its
11144    // once-execution interior work (`driver_once_cost`) — at the
11145    // TOP LEVEL only: the output cell bills the drain inside it as zero,
11146    // the blind basis that ranked the transects cluster-driving seat
11147    // cheapest while the geo op's drain + asWKT read ran uncounted. At
11148    // WALK DEPTH (`containing` is Some — this call prices a join inside a
11149    // keyed subtree probe arm, and the leaf-walk's Join branch is the only
11150    // Some producer) the cell basis stands: the leaf-walk's recursion
11151    // (`subtree_has_join` → `subtree_page_cost`) prices the driver's
11152    // interior there, and the once-cost would count it a second time.
11153    // The once-cost is a full SeatCost — a nested join prices as one
11154    // unpushed seat of itself, and its probe lookups are real seeks
11155    // that ride home on this seating's total cost (every exit below adds
11156    // `driver_seeks`). Bare
11157    // scans keep the ownership-aware streamed read in both cases — for a
11158    // scan the streamed rows ARE the work, and the foreign-claim cell IS
11159    // the bounded whole read.
11160    // A STAMPED custom driver that HOSTS the pushed key answers the keyed
11161    // regime: the pushed terms go straight to
11162    // `execute_custom_op` — the keyless drain never runs — so its
11163    // conditioned work is `keyed_cost(pushed_val_count)`, a work number
11164    // DERIVED FROM the list length. The bound min below must not touch
11165    // this cost estimate: for a hosting op the bound collapses to the bare list
11166    // length (basis = domain = produced), and `min(keyed, list)` priced
11167    // the keyed regime at 1/8th of its cost — the units bug: a count of
11168    // pushed values is an INPUT to the price, never a price itself.
11169    // Unstamped ops and ops that do not emit the pushed key keep the
11170    // sweep / ownership-aware rules (an op that cannot consume the push
11171    // really does sweep once — the bound never fires for it).
11172    let driver_keyed = match (driver, containing) {
11173        (PlanNode::CustomNode(op), Some(push)) if op.variables.contains(&push.key) => {
11174            let pushed_column = op
11175                .variables
11176                .iter()
11177                .position(|variable| variable == &push.key);
11178            op.keyed_cost(push.pushed_val_count, pushed_column)
11179        }
11180        _ => None,
11181    };
11182    let (driver_rows, driver_seeks) = match driver {
11183        PlanNode::Scan(_) | PlanNode::CustomNode(_) if driver_keyed.is_some() => {
11184            (driver_keyed.unwrap(), 0)
11185        }
11186        PlanNode::Scan(_) | PlanNode::CustomNode(_) => {
11187            (seat_driver_work_rows(driver, hash_keys, profile), 0)
11188        }
11189        _ if containing.is_none() => {
11190            let once = driver_once_cost(profile, driver, ctx);
11191            (once.rows, once.seeks)
11192        }
11193        _ => (seat_driver_work_rows(driver, hash_keys, profile), 0),
11194    };
11195    let probe_scan = probe.as_scan().filter(|scan| fetch_once_stampable(scan));
11196    // A bound-predicate count walk is read whole however the keys are pushed
11197    // (the count RPC takes a constraint list and no head list), so a multi-page
11198    // cost estimates it as one build — the same rule the stamp forces with, so the
11199    // two cannot split on which road runs. The stamp is available here because
11200    // this is the second seating round, which runs on the tree the first round's
11201    // `annotate_liveness` already annotated.
11202    let probe_count_walk = probe.as_scan().is_some_and(bound_constraint_count_scan);
11203    // ONE row basis for every road of the cost model and both sides of the
11204    // fetch-once comparison: the arm's UNCLAMPED whole-read estimate — what
11205    // one whole read of the arm returns, and the base the per-page matched
11206    // fraction scales. For a bare-Scan arm this is the same pass-top value
11207    // the seating rounds priced (the reset calls the same function), so
11208    // the stamp's inputs match the comparator's. For subtree probes there
11209    // is no whole-read price: the produced estimate stands in (the build
11210    // road is closed for them anyway — `probe_stampable` false).
11211    let probe_rows = match probe_scan {
11212        Some(scan) => estimate_unclamped_scan_rows(profile, scan),
11213        // A stamped custom probe's UNKEYED execution (the keys-empty and
11214        // coverage roads below) is its keyless sweep — the drain + relate
11215        // pass — not its output count. The per-page keyed work prices in
11216        // the custom branch below.
11217        None => match probe {
11218            PlanNode::CustomNode(op) => op.sweep_cost().unwrap_or(op.produced_row_count_estimate),
11219            _ => probe.produced_row_count_estimate(),
11220        },
11221    };
11222    if driver_rows == 0 {
11223        return SeatCost { rows: 0, seeks: 0 };
11224    }
11225    if hash_keys.is_empty() {
11226        // A keys-empty join (cartesian — the graph-only gather can produce
11227        // empty keys) prices the raw arm sum and returns before the
11228        // containing-push conditioning and the keyed regime below, so
11229        // this road never sees `driver_keyed` or the driver bound. Known
11230        // conservatism: no workload has seated this shape, and the honest
11231        // price needs a pushed-road model this site cannot derive.
11232        // Revisit if a real query seats a keys-empty join under a
11233        // containing push or hosting a custom op.
11234        return SeatCost {
11235            rows: driver_rows.saturating_add(probe_rows),
11236            seeks: driver_seeks,
11237        };
11238    }
11239    // Containing-push conditioning: inside a keyed
11240    // subtree probe arm, a join whose DRIVER hosts the pushed key executes
11241    // once per ancestor page against the keyed answer — the same gate and
11242    // derivation the stamp walk applies to its verdicts, so the price's
11243    // driver work, the shape's page count, and the stamp share one BOUND.
11244    // Their BASES differ by design: the work is the
11245    // once-cost at top level, the page count the streamed cell — the bound
11246    // is the one number both apply. Min-guarded: the bound can only
11247    // shrink the standalone basis, and an unknown driver key domain
11248    // yields no bound (no invented number).
11249    let driver_bound = containing
11250        .filter(|push| probe_scan_has_key(driver, &push.key))
11251        .and_then(|push| {
11252            containing_push_driver_bound(profile, driver, &push.key, push.pushed_val_count)
11253        });
11254    // The keyed regime IS the conditioned answer for a hosting custom
11255    // driver — the bound's list length is keyed_cost's INPUT, not a
11256    // competing price — so the min applies everywhere else
11257    // and is skipped exactly there.
11258    let driver_rows = if driver_keyed.is_some() {
11259        driver_rows
11260    } else {
11261        driver_rows.min(driver_bound.unwrap_or(u64::MAX))
11262    };
11263    let shape = seat_probe_shape(profile, driver, probe, hash_keys, ctx, driver_bound);
11264    // A stamped custom probe arm answers pushes with the KEYED regime,
11265    // not the scan transport: the op carries no index seeks (its work is
11266    // CPU + partition-side walks, already in the rows currency), and the
11267    // work per page is the regime formula over the page's pushed list —
11268    // the conservative all-blob bound; the executor's `take_direct_road`
11269    // re-prices inline points at runtime. The fetch-once road stays
11270    // scan-only (the executor's stamp is a Scan stamp): the op's
11271    // fetch-once economics are the drain memo amortizing the semi-join
11272    // road's drain across pages, which the per-page bound here already
11273    // dominates — `pages × keyed_cost(list)` charges the drain on every
11274    // page that takes the semi-join road, so it can only over-price a
11275    // memoized runtime, never under-price it.
11276    if let PlanNode::CustomNode(op) = probe
11277        && op.cost.is_some()
11278    {
11279        // The coverage road: every key a covered, droppable push —
11280        // the op executes once unfiltered (its keyless sweep), the
11281        // same one-read shape as a dropped subtree arm. Priced
11282        // amortized like subtree arms: an over-limit window the
11283        // drain memo refuses re-drains per chunk — the risk the
11284        // runtime's own drop verdict accepted (`source_coverage_drop`
11285        // grants non-scan arms the drop unconditionally).
11286        if shape.keys.iter().all(|&(covered, _, _, _)| covered) && shape.coverage_drop_allowed {
11287            return SeatCost {
11288                rows: driver_rows.saturating_add(probe_rows),
11289                seeks: driver_seeks,
11290            };
11291        }
11292        // The keyed road: one surviving key's page list (the same
11293        // pick the scan transport prices) at the per-page regime price.
11294        // The drain is a separate term: paid ONCE when the op's drain memo
11295        // admits this window, on EVERY page when it will refuse it and the
11296        // executor must re-drain. Stamped ops always answer
11297        // `probe_page_cost` with Some.
11298        let cost = op.cost.expect("the branch requires a stamped op");
11299        let (list, _, _) =
11300            first_broadcast_key(&shape.keys, shape.coverage_drop_allowed).unwrap_or((0, 0, 0));
11301        // The runtime's pick: the first output variable with a delivered
11302        // list. `broadcast_key` is the key whose list survives the reorder,
11303        // so its position names the pushed column (a multi-key join where
11304        // the op binds several keys could differ; those are not this op).
11305        let pushed_column = shape
11306            .broadcast_key
11307            .as_ref()
11308            .and_then(|key| op.variables.iter().position(|variable| variable == key));
11309        let (per_page, pays_drain) = op
11310            .probe_page_cost(list, pushed_column)
11311            .unwrap_or((0, false));
11312        let drain = if !pays_drain {
11313            0
11314        } else if op.probe_drain_amortized() {
11315            cost.drain_rows
11316        } else {
11317            shape.pages.saturating_mul(cost.drain_rows)
11318        };
11319        return SeatCost {
11320            rows: driver_rows
11321                .saturating_add(drain)
11322                .saturating_add(shape.pages.saturating_mul(per_page)),
11323            seeks: driver_seeks,
11324        };
11325    }
11326    let probe_memoizable = probe.as_scan().is_some_and(scan_memo_eligible)
11327        && probe_rows <= SCAN_MEMO_MAX_ENTRY_ROWS as u64;
11328    // The stamp's reach: only a stampable right arm takes the executor's
11329    // stamped build branch, so only that shape may be PRICED as a
11330    // fetch-once arm (plan/runtime coherence — see `restamp_fetch_once`).
11331    // Epistemics of the price: with no or empty stats the "unclamped"
11332    // estimate is the clamp fallback, and the fetch-once road must not fire on
11333    // it. The flag only matters for scans.
11334    let whole_read_rows_known = probe
11335        .as_scan()
11336        .is_some_and(|scan| whole_read_rows_known(profile, scan));
11337    // The leaf-walk: a kept-key SUBTREE probe (anything but a bare scan,
11338    // an unstamped custom op, or a path — those keep their own roads)
11339    // prices one execution per driver page under this join's pushed list,
11340    // by descending into the subtree. The outermost inherited push wins
11341    // (the stamp walk's own rule); otherwise this join's keyed road
11342    // establishes one. `None` on the once-roads: the arithmetic's
11343    // all-covered road prices the subtree's single execution at the
11344    // produced clamp, unchanged.
11345    let walk_page = if probe.as_scan().is_none()
11346        && !matches!(probe, PlanNode::CustomNode(_) | PlanNode::Path(_))
11347    {
11348        let push = containing
11349            .cloned()
11350            .or_else(|| child_push_from_shape(profile, driver, probe, ctx, &shape));
11351        push.map(|push| {
11352            let mut budget = SUBTREE_WALK_NODE_BUDGET;
11353            subtree_page_cost(profile, probe, &push, ctx, &mut budget)
11354        })
11355    } else {
11356        None
11357    };
11358    // Probe-side mirror (the receiving-scan bound): inside a
11359    // keyed subtree probe arm, a bare-scan probe that HOSTS the ancestor
11360    // push's key is fetched per page through that pushed list — pricing
11361    // only the interior-keyed road charges a per-page answer the ancestor
11362    // push narrows (the asWKT-shaped gap: the association pass's phantom charged ~25K
11363    // matched rows per page for a scan the executor fetches through a
11364    // ~514-term list). The per-page price is the walk's own Scan-leaf
11365    // formula (`probe_broadcast_price` over the pushed list — ONE
11366    // formula, the walk leaf and the cost model), so a receiving scan prices
11367    // identically whether the leaf-walk reaches it inside a subtree or
11368    // the cost model bounds it directly. The road policy lives in
11369    // `probe_side_mirror_road`, shared with the fetch-once stamp — the
11370    // price and the stamp must never disagree about which road runs.
11371    let mirror_road = probe_side_mirror_road(
11372        profile,
11373        probe,
11374        hash_keys,
11375        &shape.keys,
11376        shape.coverage_drop_allowed,
11377        containing,
11378    );
11379    // Disjoint by probe type: the walk prices subtree arms, the mirror
11380    // bare scans. The arithmetic takes their merge (the walk wins — the
11381    // deeper price); the override below branches on each separately.
11382    let mut subtree_page = walk_page;
11383    if subtree_page.is_none() {
11384        subtree_page = mirror_road;
11385    }
11386    // The fetch-once road is only executable when a stamp could be WRITTEN
11387    // for it: the stamp walk's executor-capability guard requires some
11388    // hash key with an S/P/O slot on the scan (the runtime fills a built
11389    // slot only through a broadcastable slot). A join keyed solely on
11390    // unshippable positions never writes the stamp, so the executor never
11391    // takes the build branch — `merged_scan_filter` keeps the ancestor
11392    // filter (or probes unfiltered) and refetches every page — and
11393    // pricing the once-build here charged a road that does not run: the
11394    // seat charged one whole read while the stamp wrote nothing. The
11395    // stamp walk applies the same guard.
11396    let build_stamp_writable = probe_scan.is_some()
11397        && hash_keys.iter().any(|key| {
11398            probe
11399                .as_scan()
11400                .is_some_and(|s| s.first_slot_of(key).is_some())
11401        });
11402    let mut cost = seat_cost_arithmetic(
11403        driver_rows,
11404        probe_rows,
11405        probe_memoizable,
11406        shape.pages,
11407        &shape.keys,
11408        shape.coverage_drop_allowed,
11409        build_stamp_writable,
11410        whole_read_rows_known,
11411        shape.driver_domains_known,
11412        probe_count_walk,
11413        subtree_page,
11414    );
11415    // Coverage-road yield (review MAJOR): on an all-covered shape the
11416    // arithmetic prices the once-read — one unfiltered read feeding the
11417    // built slot. Under a containing push whose mirror road fires, that
11418    // story is not what runs: `merged_scan_filter` keeps the ANCESTOR
11419    // filter (the interior keys are dropped as covered) and re-applies it
11420    // on every page — the built slot never fills, so the arm is fetched
11421    // through the pushed list once per page. Price that road instead of
11422    // the once-read (the review's under-price: `source_coverage_drop`
11423    // judges coverability from the claim-clamped cell, so a huge
11424    // ancestor-filtered scan can masquerade as a once-read while many
11425    // pages of a weakly selective ancestor list pay more). For a SUBTREE
11426    // arm the mirror road is None by probe type, and the walk's page
11427    // takes the split below.
11428    if let Some(road) = mirror_road {
11429        let all_covered = shape.keys.iter().all(|&(covered, _, _, _)| covered);
11430        if all_covered && shape.coverage_drop_allowed {
11431            cost = SeatCost {
11432                rows: driver_rows.saturating_add(shape.pages.saturating_mul(road.rows)),
11433                seeks: shape.pages.saturating_mul(road.seeks),
11434            };
11435        }
11436    } else if let Some(walk) = walk_page {
11437        // The all-covered walk case-split: the same
11438        // once-read story, priced for a subtree arm — and under a
11439        // containing push the executor's push-combine outcome decides how
11440        // many times the subtree actually runs. `probe_right` walks THIS
11441        // join's hash keys against the inherited stack
11442        // (`PushedKeyVals::combine`): a key already ON the stack INTERSECTS
11443        // its list with the driver page's terms and sets `changed` — the
11444        // intersect branch runs BEFORE the coverage skip, so an all-covered
11445        // stack key still combines — and the executor then re-executes the
11446        // subtree per driver page (`ProbePushed::Combined`); the
11447        // intersected list varies per page and no built table stays valid.
11448        // A key NOT on the stack is coverage-skipped on this all-covered
11449        // shape, `changed` stays false, and the executor takes
11450        // `ProbePushed::Ancestor`: the subtree executes ONCE with the
11451        // inherited stack applied (`execute_node(right, …, pushed)`), the
11452        // ancestor filter constant across this join's driver pages. So the
11453        // discriminator is exactly `push.key ∈ hash_keys`:
11454        //
11455        // - Combined → `driver + pages × walk` (the walk's conditioned
11456        //   per-page price; the full ancestor list is a conservative
11457        //   stand-in for the per-page intersected lists, which are its
11458        //   subsets);
11459        // - Ancestor → `driver + walk` ONCE (the walk's own once-cost —
11460        //   the r2 review's "the walk's own once-cost is the missing
11461        //   number" — replacing the once-read AND the memo extra that
11462        //   belonged to it; a conditioned fetch never enters the scan
11463        //   memo, the r2 R4 verdict);
11464        // - no containing push → the arithmetic's once-read stands
11465        //   unchanged (and `child_push_from_shape` declines on an
11466        //   all-covered droppable shape, so a walk page here PROVES the
11467        //   push is the inherited one — the `containing` guard below is
11468        //   the same invariant, kept as a graceful fall-through).
11469        //
11470        // KNOWN APPROXIMATION — the one-key stack collapse: the runtime
11471        // stack accumulates one entry per enclosing join, but the plan's
11472        // `ContainingPush` names only the OUTERMOST push. A deeper stack
11473        // entry whose key IS one of this join's hash keys makes the
11474        // executor combine while this model, looking only at the outermost
11475        // key, prices the Ancestor once-walk — an under-price on that
11476        // shape. Revisit (carry the full stack into the plan) only if a
11477        // real query shows it.
11478        let all_covered = shape.keys.iter().all(|&(covered, _, _, _)| covered);
11479        if all_covered
11480            && shape.coverage_drop_allowed
11481            && let Some(push) = containing
11482        {
11483            cost = if hash_keys.contains(&push.key) {
11484                SeatCost {
11485                    rows: driver_rows.saturating_add(shape.pages.saturating_mul(walk.rows)),
11486                    seeks: shape.pages.saturating_mul(walk.seeks),
11487                }
11488            } else {
11489                SeatCost {
11490                    rows: driver_rows.saturating_add(walk.rows),
11491                    seeks: walk.seeks,
11492                }
11493            };
11494        }
11495    }
11496    // The driver subtree's own probe lookups (a nested join's inner seat
11497    // seeks) ride home on every road above — added last so
11498    // the probe-side overrides, which replace the whole SeatCost, cannot
11499    // drop them.
11500    cost.seeks = cost.seeks.saturating_add(driver_seeks);
11501    cost
11502}
11503
11504/// The node budget for ONE leaf-walk entry ([`subtree_page_cost`]): the
11505/// walk prices at most this many nodes before degrading to the coarse
11506/// produced-estimate price. Bounds the comparator's added work per entry
11507/// deterministically — a pathological subtree degrades to the pre-walk
11508/// price, never to a planning stall. Layer 2 of the planner-time
11509/// regression gate asserts the fallback engages (wide Union arms).
11510const SUBTREE_WALK_NODE_BUDGET: u64 = 64;
11511
11512/// Whether `node` contains a Join anywhere the runtime would execute
11513/// inside this subtree. The leaf-walk recurses into a join's DRIVER only
11514/// when this is true: at WALK DEPTH the cost model's driver work is the output
11515/// cell (the once-cost is top-level only), so this recursion is the only
11516/// place the driver's interior joins
11517/// get priced, and a bare-scan driver's read needs no recursion (its
11518/// streamed read IS its work; recursing into a join-free driver would
11519/// count the same leaf twice). Mirrors `probe_scan_has_key`'s topology.
11520fn subtree_has_join(node: &PlanNode) -> bool {
11521    match node {
11522        PlanNode::Join { .. } | PlanNode::LeftJoin { .. } => true,
11523        PlanNode::Union { left, right } => subtree_has_join(left) || subtree_has_join(right),
11524        PlanNode::Filter { inner, .. }
11525        | PlanNode::Extend { inner, .. }
11526        | PlanNode::Slice { inner, .. }
11527        | PlanNode::Distinct { inner, .. }
11528        | PlanNode::Sort { inner, .. }
11529        | PlanNode::Group { inner, .. }
11530        | PlanNode::JoinGraphVar { inner, .. } => subtree_has_join(inner),
11531        // Leaves and boundaries: no internal join to price. SubSelect
11532        // internals plan in their own scope.
11533        _ => false,
11534    }
11535}
11536
11537/// The leaf-walk: the per-page cost of ONE execution of a
11538/// subtree probe arm under an inherited pushed key list (`push`) — what
11539/// the runtime actually pays when it re-executes the subtree per driver
11540/// page (`execute_node(right, …, pushed)` hands the pushed stack to the
11541/// subtree generically), instead of the output-cardinality fraction the
11542/// comparator priced it at before.
11543///
11544/// The walk mirrors `probe_scan_has_key`'s push-reachability topology —
11545/// the same topology `stamp_fetch_once` conditions stamps on — so the
11546/// PRICE and the STAMP share one model:
11547///
11548/// - containers the runtime pushes through (Filter, Extend, Slice, Union
11549///   arms, …) descend with the same context; a LeftJoin is
11550///   push-transparent (both arms);
11551/// - a Join prices its marginal seat ([`seat_cost_total`] with the
11552///   inherited context — its driver re-geometries iff it hosts the push
11553///   key, the MAJOR-2 bound) plus its DRIVER subtree's own internal joins
11554///   (recursion, guarded by [`subtree_has_join`] — a bare-scan driver's
11555///   read IS its term); the probe arm's internals were already priced by
11556///   the cost model's own subtree branch;
11557/// - a Scan leaf prices one page's keyed answer under the reaching list:
11558///   `pushed_val_count` seeks and the domain-scaled matched fraction, the same
11559///   `probe_broadcast_price` formula the bare-scan transport prices, at
11560///   the leaf;
11561/// - everything the runtime cannot push into (SubSelect, EXISTS bodies,
11562///   Values, the catalog/computed nodes) and everything with its own cost
11563///   story (unstamped custom ops, paths — the tracked unbound path-probe pricing gap) prices
11564///   standalone at its produced estimate, never conditioned.
11565///
11566/// Budget-guarded: past [`SUBTREE_WALK_NODE_BUDGET`] nodes the walk
11567/// degrades to the coarse produced-estimate price (never zero — a
11568/// degraded walk must still price the arm).
11569fn subtree_page_cost(
11570    profile: Option<&StatsProfile>,
11571    node: &PlanNode,
11572    push: &ContainingPush,
11573    ctx: Option<&crate::context::QueryContext>,
11574    budget: &mut u64,
11575) -> SeatCost {
11576    let mut filter_cost_milli = 0;
11577    subtree_page_cost_with_filter(profile, node, push, ctx, budget, &mut filter_cost_milli)
11578}
11579
11580/// [`subtree_page_cost`] with the scalar-FILTER cost reported separately.
11581/// `filter_cost_milli` is the extra milli-row-equivalents of filter
11582/// evaluation over the per-page input rows; the returned `SeatCost.rows`
11583/// includes its integer part, and a consumer that prices matched rows on
11584/// their own (the Semi verdict) can subtract it and charge the filter at
11585/// cost rather than at the matched-row rate.
11586#[allow(clippy::too_many_arguments)]
11587fn subtree_page_cost_with_filter(
11588    profile: Option<&StatsProfile>,
11589    node: &PlanNode,
11590    push: &ContainingPush,
11591    ctx: Option<&crate::context::QueryContext>,
11592    budget: &mut u64,
11593    filter_cost_milli: &mut u64,
11594) -> SeatCost {
11595    let coarse = || SeatCost {
11596        rows: node.produced_row_count_estimate(),
11597        seeks: 0,
11598    };
11599    if *budget == 0 {
11600        return coarse();
11601    }
11602    *budget -= 1;
11603    walk_visits_bump();
11604    match node {
11605        PlanNode::Join {
11606            left,
11607            right,
11608            hash_keys,
11609            ..
11610        } => {
11611            let cost = seat_cost_total(profile, left, right, hash_keys, ctx, Some(push));
11612            let driver_extra = if subtree_has_join(left) {
11613                subtree_page_cost_with_filter(profile, left, push, ctx, budget, filter_cost_milli)
11614            } else {
11615                SeatCost { rows: 0, seeks: 0 }
11616            };
11617            SeatCost {
11618                rows: cost.rows.saturating_add(driver_extra.rows),
11619                seeks: cost.seeks.saturating_add(driver_extra.seeks),
11620            }
11621        }
11622        // Push-transparent at runtime (the stamp walk's MINOR-3 rule): the
11623        // ancestor's pushed stack reaches both arms. No cost term of its
11624        // own — the optional match is not in the read currency.
11625        PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
11626            let left_extra =
11627                subtree_page_cost_with_filter(profile, left, push, ctx, budget, filter_cost_milli);
11628            let right_extra =
11629                subtree_page_cost_with_filter(profile, right, push, ctx, budget, filter_cost_milli);
11630            SeatCost {
11631                rows: left_extra.rows.saturating_add(right_extra.rows),
11632                seeks: left_extra.seeks.saturating_add(right_extra.seeks),
11633            }
11634        }
11635        PlanNode::Scan(scan) => {
11636            let whole_read = estimate_unclamped_scan_rows(profile, scan);
11637            let domain = join_key_domain_for_node(profile, node, &push.key).unwrap_or(0);
11638            // The ancestor push's own overlap is unresolved at walk depth
11639            // (the ancestor driver is out of scope) — FULL, the road's
11640            // historical price.
11641            let (seeks, matched) = probe_broadcast_price(
11642                whole_read,
11643                &[(
11644                    false,
11645                    push.pushed_val_count,
11646                    domain,
11647                    VOCABULARY_OVERLAP_FULL_MILLI,
11648                )],
11649                false,
11650            );
11651            SeatCost {
11652                rows: matched,
11653                seeks,
11654            }
11655        }
11656        PlanNode::Filter {
11657            inner,
11658            early,
11659            residual,
11660            exists,
11661            ..
11662        } => {
11663            let extra =
11664                subtree_page_cost_with_filter(profile, inner, push, ctx, budget, filter_cost_milli);
11665            // EXISTS bodies are correlated sub-evaluations, not
11666            // push-reachable — standalone at their produced estimate.
11667            let exists_rows: u64 = exists
11668                .iter()
11669                .map(|clause| clause.body.produced_row_count_estimate())
11670                .sum();
11671            // Scalar conjuncts evaluate once per input row; the rate is
11672            // per conjunct, so this is a strict extra over the read.
11673            let scalar_cost_milli = extra
11674                .rows
11675                .saturating_mul(filter_row_cost_milli(early.as_ref(), residual.as_ref()));
11676            *filter_cost_milli = filter_cost_milli.saturating_add(scalar_cost_milli);
11677            SeatCost {
11678                rows: extra
11679                    .rows
11680                    .saturating_add(exists_rows)
11681                    .saturating_add(scalar_cost_milli / 1000),
11682                seeks: extra.seeks,
11683            }
11684        }
11685        PlanNode::Extend { inner, .. }
11686        | PlanNode::Slice { inner, .. }
11687        | PlanNode::Distinct { inner, .. }
11688        | PlanNode::Sort { inner, .. }
11689        | PlanNode::Group { inner, .. }
11690        | PlanNode::JoinGraphVar { inner, .. } => {
11691            subtree_page_cost_with_filter(profile, inner, push, ctx, budget, filter_cost_milli)
11692        }
11693        // Plugin-owned (children are never descended — the stamp walk's
11694        // rule), item-8 territory, and push-opaque boundaries: standalone
11695        // at the produced estimate, never conditioned, never zero.
11696        PlanNode::CustomNode(_)
11697        | PlanNode::Path(_)
11698        | PlanNode::SubSelect(_)
11699        | PlanNode::Values(_)
11700        | PlanNode::NamedGraphs { .. }
11701        | PlanNode::NamedGraphExists { .. }
11702        | PlanNode::DomainCounts { .. }
11703        | PlanNode::HeadCounts { .. }
11704        | PlanNode::PatternCount { .. }
11705        | PlanNode::Unit => coarse(),
11706    }
11707}
11708
11709/// The driver-side once-cost: the row work of executing a
11710/// SUBTREE driver arm ONCE, unpushed — the work
11711/// [`driver_whole_read_rows`] cannot see for anything but a bare scan. A
11712/// subtree arm's streamed rows are its OUTPUT (the cell), but the work
11713/// the executor pays to produce that stream is the interior: every scan
11714/// read once, every arm of a join or union once. The blind basis priced
11715/// the transects cluster-driving seat at its output while the geo op's
11716/// drain and the asWKT whole read ran uncounted — the 2.2s plan the
11717/// comparator ranked cheapest.
11718///
11719/// TOP-LEVEL ONLY: `seat_cost_total` reaches this
11720/// function only when `containing` is `None`. At WALK DEPTH (a join
11721/// inside a keyed subtree probe arm — the leaf-walk's Join branch, the
11722/// only `Some` producer) the cost model keeps the output-cell basis, because
11723/// the leaf-walk's own recursion (`subtree_has_join` →
11724/// [`subtree_page_cost`]) prices the driver's interior there and the
11725/// once-cost would count it a second time.
11726///
11727/// Topology mirrors the probe-side leaf-walk ([`subtree_page_cost`]):
11728///
11729/// - a Scan leaf prices its unclamped whole read — the idempotence price
11730///   the claim stamps and the walk leaf already share. The once-cost is
11731///   the UNPUSHED work; the containing-push conditioning stays the
11732///   caller's `driver_bound` min, which can only lower (the r2
11733///   constraint);
11734/// - a Join / LeftJoin sums BOTH arms — one execution runs both, the
11735///   optional side included (the walk's push-transparency rule);
11736/// - a Union sums both arms (both run);
11737/// - the containers the runtime executes through descend;
11738/// - a CustomNode prices its keyless sweep ([`CustomOp::sweep_cost`]) —
11739///   the drain + relate pass, the same rule [`seat_driver_work_rows`]
11740///   applies to a top-level custom driver;
11741/// - the walk's boundaries (SubSelect internals, paths, Values, the
11742///   catalog/computed leaves) price the produced estimate — the same
11743///   coarse stand-in as today's term, never an invented number.
11744///
11745/// Deliberately NOT [`containing_push_basis`] (the r2 constraint): that
11746/// derivation composes the push-bound BASIS for pushed-list conditioning
11747/// and MULTIPLIES join arms (a cross product bounds a join's OUTPUT).
11748/// The once-cost SUMS the arms — one execution reads each arm once; the
11749/// output multiplication is the probe side's business, already priced
11750/// per page by the leaf-walk.
11751///
11752/// Budget-guarded like the walk: past [`SUBTREE_WALK_NODE_BUDGET`] nodes
11753/// the descent degrades to the produced estimate (today's term) — never
11754/// zero, never a planning stall. Visits ride the same `WALK_VISITS`
11755/// counter, so the comparator-work regression gate sees this descent.
11756fn driver_once_cost(
11757    profile: Option<&StatsProfile>,
11758    node: &PlanNode,
11759    ctx: Option<&crate::context::QueryContext>,
11760) -> SeatCost {
11761    let mut budget = SUBTREE_WALK_NODE_BUDGET;
11762    driver_once_work(profile, node, ctx, &mut budget)
11763}
11764
11765/// The recursive body of [`driver_once_cost`] — split so the budget is
11766/// created once at the entry and threaded through the descent, exactly
11767/// like [`subtree_page_cost`]'s `&mut u64`.
11768fn driver_once_work(
11769    profile: Option<&StatsProfile>,
11770    node: &PlanNode,
11771    ctx: Option<&crate::context::QueryContext>,
11772    budget: &mut u64,
11773) -> SeatCost {
11774    let coarse = || SeatCost {
11775        rows: node.produced_row_count_estimate(),
11776        seeks: 0,
11777    };
11778    if *budget == 0 {
11779        return coarse();
11780    }
11781    *budget -= 1;
11782    walk_visits_bump();
11783    match node {
11784        PlanNode::Scan(scan) => SeatCost {
11785            rows: estimate_unclamped_scan_rows(profile, scan),
11786            seeks: 0,
11787        },
11788        PlanNode::CustomNode(op) => SeatCost {
11789            rows: op
11790                .sweep_cost()
11791                .unwrap_or_else(|| node.produced_row_count_estimate()),
11792            seeks: 0,
11793        },
11794        // ONE unpushed execution of this join IS its own seating cost:
11795        // the driver arm's work plus the probe
11796        // arm's per-page (or fetch-once) road. The executor PROBES the
11797        // second arm per driver page — it does not read it whole — and
11798        // the raw arm sum this replaced billed exactly that fictional
11799        // whole read (~800k of phantom asWKT in the transects repro,
11800        // symmetric there, misordering anywhere one side is selective).
11801        // The nested seat recurses through this same function for its
11802        // own subtree drivers, so deep spines price bottom-up, and its
11803        // seeks ride home — the inner probe's lookups were dropped when
11804        // the once-cost was a bare u64. LeftJoin keeps the seating-cost model's
11805        // per-page optional arm (the eager executor
11806        // materializes the required side once and probes once over the
11807        // full table — the Slice-path per-batch re-execution is the
11808        // documented conservatism, unchanged).
11809        PlanNode::Join {
11810            left,
11811            right,
11812            hash_keys,
11813            ..
11814        }
11815        | PlanNode::LeftJoin {
11816            left,
11817            right,
11818            hash_keys,
11819            ..
11820        } => seat_cost_total(profile, left, right, hash_keys, ctx, None),
11821        PlanNode::Union { left, right } => once_work_sum(profile, left, right, ctx, budget),
11822        PlanNode::Filter {
11823            inner,
11824            early,
11825            residual,
11826            ..
11827        } => {
11828            let inner_cost = driver_once_work(profile, inner, ctx, budget);
11829            let filter_rows = inner
11830                .produced_row_count_estimate()
11831                .saturating_mul(filter_row_cost_milli(early.as_ref(), residual.as_ref()))
11832                .saturating_div(1000);
11833            SeatCost {
11834                rows: inner_cost.rows.saturating_add(filter_rows),
11835                seeks: inner_cost.seeks,
11836            }
11837        }
11838        PlanNode::Extend { inner, .. }
11839        | PlanNode::Slice { inner, .. }
11840        | PlanNode::Distinct { inner, .. }
11841        | PlanNode::Sort { inner, .. }
11842        | PlanNode::Group { inner, .. }
11843        | PlanNode::JoinGraphVar { inner, .. } => driver_once_work(profile, inner, ctx, budget),
11844        _ => coarse(),
11845    }
11846}
11847
11848/// Both arms of a union execute in one pass of the subtree; the once-cost
11849/// is their sum (rows and seeks).
11850fn once_work_sum(
11851    profile: Option<&StatsProfile>,
11852    left: &PlanNode,
11853    right: &PlanNode,
11854    ctx: Option<&crate::context::QueryContext>,
11855    budget: &mut u64,
11856) -> SeatCost {
11857    let l = driver_once_work(profile, left, ctx, budget);
11858    let r = driver_once_work(profile, right, ctx, budget);
11859    SeatCost {
11860        rows: l.rows.saturating_add(r.rows),
11861        seeks: l.seeks.saturating_add(r.seeks),
11862    }
11863}
11864
11865/// Smallest under-threshold join-key domain on `producer` that a Scan under
11866/// `probe` can actually take (`slot_of`), including scans inside Union arms
11867/// and inner Joins.
11868///
11869/// Hosted keys are classified first by both-sides ground-unique-ness
11870/// ([`arm_ground_term`]):
11871///
11872/// - **No-op filter** (same single term on both sides): both arms can only
11873///   emit rows already carrying that exact term, so the key's domain-1 must
11874///   not drag the minimum down — it is skipped entirely. When EVERY hosted
11875///   key is a no-op the join is a constant join and the classification falls
11876///   back to the plain minimum below (the join still copies the probe side's
11877///   columns onto the driver rows; an optimized constant-join is future
11878///   work).
11879/// - **Conflict** (different terms): the join cannot produce rows;
11880///   [`conflicting_ground_keys`] + the join-construction sites substitute
11881///   the empty node, so a conflicting key contributes no domain here.
11882/// - Otherwise the key **filters**: its capped domain competes for the
11883///   minimum (the smallest surviving domain wins).
11884///
11885/// Rough stand-in for `join_keys_scan_filter` + min-distinct: executor still
11886/// walks `hash_keys` order / ancestor-first, not min-distinct. Over
11887/// [`PUSHDOWN_TERMS_LIMIT`] after `min(domain, rows)` is treated as no
11888/// allow-list (`None` → row estimates only).
11889fn join_key_domain_for_allow_list(
11890    profile: Option<&StatsProfile>,
11891    producer: &PlanNode,
11892    probe: &PlanNode,
11893    hash_keys: &[Variable],
11894    producer_rows: u64,
11895) -> Option<u64> {
11896    let mut survivors: Vec<u64> = Vec::new();
11897    let mut hosted_keys = 0usize;
11898    let mut noop_keys = 0usize;
11899    for key in hash_keys {
11900        if !probe_scan_has_key(probe, key) {
11901            continue;
11902        }
11903        hosted_keys += 1;
11904        if let (Some(producer_term), Some(probe_term)) =
11905            (arm_ground_term(producer, key), arm_ground_term(probe, key))
11906        {
11907            if producer_term == probe_term {
11908                noop_keys += 1;
11909            }
11910            // A both-sides ground-unique key never filters: same term is a
11911            // no-op, different terms leave an empty join whose domain is
11912            // moot (the construction sites substitute it away).
11913            continue;
11914        }
11915        let Some(raw) = join_key_domain_for_node(profile, producer, key) else {
11916            continue;
11917        };
11918        let capped = raw.min(producer_rows).max(1);
11919        if capped > PUSHDOWN_TERMS_LIMIT {
11920            continue;
11921        }
11922        survivors.push(capped);
11923    }
11924    // Smallest domain first: the head of the ascending sort is the minimum.
11925    if let Some(smallest) = survivors.iter().min() {
11926        return Some(*smallest);
11927    }
11928    if noop_keys > 0 && noop_keys == hosted_keys {
11929        // All join keys are pre-satisfied constants — the join still copies
11930        // the probe side's columns onto the driver rows; an optimized
11931        // constant-join is future work. Fall back to today's aggregation
11932        // (plain minimum over the hosted keys) instead of losing the
11933        // allow-list domain.
11934        let mut best: Option<u64> = None;
11935        for key in hash_keys {
11936            if !probe_scan_has_key(probe, key) {
11937                continue;
11938            }
11939            let Some(raw) = join_key_domain_for_node(profile, producer, key) else {
11940                continue;
11941            };
11942            let capped = raw.min(producer_rows).max(1);
11943            if capped > PUSHDOWN_TERMS_LIMIT {
11944                continue;
11945            }
11946            best = Some(best.map_or(capped, |b| b.min(capped)));
11947        }
11948        return best;
11949    }
11950    None
11951}
11952
11953/// Whether some Scan in `node` has `variable` in an S/P/O slot.
11954///
11955/// Walks Union and Join so `:hasTenant` inside a Union arm is visible.
11956/// Path / Values / LeftJoin are not scans for this estimate.
11957fn probe_scan_has_key(node: &PlanNode, variable: &Variable) -> bool {
11958    match node {
11959        PlanNode::Scan(scan) => {
11960            !scan.slot_of(variable).is_empty() || scan.graph.as_ref() == Some(variable)
11961        }
11962        // A plugin op is a broadcast-able key producer when it emits the
11963        // variable (its own estimate sizes the build side).
11964        PlanNode::CustomNode(op) => op.variables.contains(variable),
11965        PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
11966            probe_scan_has_key(left, variable) || probe_scan_has_key(right, variable)
11967        }
11968        PlanNode::Filter { inner, .. }
11969        | PlanNode::Extend { inner, .. }
11970        | PlanNode::Slice { inner, .. }
11971        | PlanNode::Distinct { inner, .. }
11972        | PlanNode::Sort { inner, .. }
11973        | PlanNode::Group { inner, .. }
11974        | PlanNode::JoinGraphVar { inner, .. } => probe_scan_has_key(inner, variable),
11975        PlanNode::Path(path) => path.graph.as_ref() == Some(variable),
11976        // The boundary is opaque: outer join keys are never probed into the
11977        // subquery's scans, so it cannot host a broadcast key.
11978        PlanNode::SubSelect(_) => false,
11979        // A LeftJoin is push-TRANSPARENT: the
11980        // ancestor's pushed stack reaches both arms at runtime — the
11981        // required side runs `pushed` directly and the optional side
11982        // forwards it through `probe_right` (`ProbePushed::Ancestor`, or
11983        // `Combined` with the required side's join-key values when the
11984        // thresholds fit). The pre-fix `false` priced both arms
11985        // standalone beneath an inherited context while the runtime
11986        // filtered them — stale Build stamps inside OPTIONAL required
11987        // sides.
11988        PlanNode::LeftJoin { left, right, .. } => {
11989            probe_scan_has_key(left, variable) || probe_scan_has_key(right, variable)
11990        }
11991        // Nodes the runtime cannot push-filter: computed rows (Values,
11992        // DomainCounts/HeadCounts/PatternCount), catalog lists, and the
11993        // walk's unit terminator.
11994        PlanNode::Values(_)
11995        | PlanNode::NamedGraphs { .. }
11996        | PlanNode::NamedGraphExists { .. }
11997        | PlanNode::DomainCounts { .. }
11998        | PlanNode::HeadCounts { .. }
11999        | PlanNode::PatternCount { .. }
12000        | PlanNode::Unit => false,
12001    }
12002}
12003
12004/// Collect every variable `node` can consume as a pushed allow-list key:
12005/// the hosted-variable set behind [`probe_scan_has_key`] — the same
12006/// push-transparent topology (Join / Union / LeftJoin / Filter / Extend /
12007/// Slice / Distinct / Sort / Group / JoinGraphVar crossed; SubSelect,
12008/// plugin children, Values, and the count nodes opaque) — gathered
12009/// instead of probed, so the runtime push gate (`PushGate::Hostable`)
12010/// consults one plan-time stamp instead of re-walking the subtree per
12011/// driver page. A scan contributes its live slot variables (S/P/O and
12012/// the graph slot), a custom op its declared outputs (the keyed regime
12013/// consumes pushed values directly). See the `Join` variant's
12014/// `rhs_hostable_keys` field for the stamp's contract.
12015pub fn subtree_hostable_variables(node: &PlanNode) -> Vec<Variable> {
12016    fn walk(node: &PlanNode, out: &mut Vec<Variable>) {
12017        match node {
12018            PlanNode::Scan(scan) => {
12019                for variable in scan.variables() {
12020                    if !out.contains(&variable) {
12021                        out.push(variable);
12022                    }
12023                }
12024            }
12025            PlanNode::CustomNode(op) => {
12026                for variable in &op.variables {
12027                    if !out.contains(variable) {
12028                        out.push(variable.clone());
12029                    }
12030                }
12031            }
12032            PlanNode::Join { left, right, .. }
12033            | PlanNode::Union { left, right }
12034            | PlanNode::LeftJoin { left, right, .. } => {
12035                walk(left, out);
12036                walk(right, out);
12037            }
12038            PlanNode::Filter { inner, .. }
12039            | PlanNode::Extend { inner, .. }
12040            | PlanNode::Slice { inner, .. }
12041            | PlanNode::Distinct { inner, .. }
12042            | PlanNode::Sort { inner, .. }
12043            | PlanNode::Group { inner, .. }
12044            | PlanNode::JoinGraphVar { inner, .. } => walk(inner, out),
12045            PlanNode::Path(path) => {
12046                if let Some(variable) = &path.graph
12047                    && !out.contains(variable)
12048                {
12049                    out.push(variable.clone());
12050                }
12051            }
12052            PlanNode::SubSelect(_)
12053            | PlanNode::Values(_)
12054            | PlanNode::NamedGraphs { .. }
12055            | PlanNode::NamedGraphExists { .. }
12056            | PlanNode::DomainCounts { .. }
12057            | PlanNode::HeadCounts { .. }
12058            | PlanNode::PatternCount { .. }
12059            | PlanNode::Unit => {}
12060        }
12061    }
12062    let mut out = Vec::new();
12063    walk(node, &mut out);
12064    out
12065}
12066
12067/// Stamp the `rhs_hostable_keys` field from the probe arm — the
12068/// hosted-variable set [`subtree_hostable_variables`] gathers. Called at
12069/// the finalize/refinalize sites from the FINAL right arm: after the
12070/// seating swap and after the arm-reshaping passes (broadcast grounding,
12071/// graph compose), so the set describes the arm as it will execute —
12072/// the placement `join_nodes` uses. The key-aligned stamps
12073/// (`probe_key_domains`, `probe_key_overlap_milli`) sit before the
12074/// reshaping instead; hostability differs because the set gates
12075/// admission and pruning for every key, not one key's estimate.
12076fn stamp_rhs_hostable_keys(right: &PlanNode) -> Arc<[Variable]> {
12077    Arc::from(subtree_hostable_variables(right))
12078}
12079
12080fn shape_name(pattern: &GraphPattern) -> &'static str {
12081    match pattern {
12082        GraphPattern::Bgp { .. } => "a basic graph pattern",
12083        GraphPattern::Path { .. } => "a property path",
12084        GraphPattern::Join { .. } => "a join",
12085        GraphPattern::LeftJoin { .. } => "OPTIONAL",
12086        GraphPattern::Filter { .. } => "FILTER",
12087        GraphPattern::Union { .. } => "UNION",
12088        GraphPattern::Graph { .. } => "GRAPH",
12089        GraphPattern::Extend { .. } => "BIND",
12090        GraphPattern::Minus { .. } => "MINUS",
12091        GraphPattern::Values { .. } => "VALUES",
12092        GraphPattern::OrderBy { .. } => "ORDER BY",
12093        GraphPattern::Project { .. } => "a sub-SELECT",
12094        GraphPattern::Distinct { .. } => "DISTINCT",
12095        GraphPattern::Reduced { .. } => "REDUCED",
12096        GraphPattern::Slice { .. } => "LIMIT / OFFSET",
12097        GraphPattern::Group { .. } => "GROUP BY",
12098        GraphPattern::Service { .. } => "SERVICE",
12099    }
12100}
12101
12102fn extra_bound_slots_for(
12103    subject: &Option<Variable>,
12104    predicate: &Option<Variable>,
12105    object: &Option<Variable>,
12106    graph: &Option<Variable>,
12107    incoming: &IncomingBound,
12108) -> ExtraBoundSlots {
12109    ExtraBoundSlots {
12110        subject: subject.as_ref().is_some_and(|v| incoming.contains(v)),
12111        predicate: predicate.as_ref().is_some_and(|v| incoming.contains(v)),
12112        object: object.as_ref().is_some_and(|v| incoming.contains(v)),
12113        graph: graph.as_ref().is_some_and(|v| incoming.contains(v)),
12114    }
12115}
12116
12117/// Variable whose distinct count scales a one-end incoming-bound scan.
12118///
12119/// One extra S or O slot wins over incoming `?p`. Both S and O extra, or no
12120/// extra slot, yields `None` (keep per-key fan-out / mean `|P|`).
12121fn one_end_incoming_var<'a>(
12122    extra: ExtraBoundSlots,
12123    subject: &'a Option<Variable>,
12124    predicate: &'a Option<Variable>,
12125    object: &'a Option<Variable>,
12126) -> Option<&'a Variable> {
12127    if extra.subject != extra.object {
12128        if extra.subject {
12129            subject.as_ref()
12130        } else {
12131            object.as_ref()
12132        }
12133    } else if extra.predicate {
12134        predicate.as_ref()
12135    } else {
12136        None
12137    }
12138}
12139
12140fn term_incoming_bound(pattern: &TermPattern, incoming: &IncomingBound) -> bool {
12141    match pattern {
12142        TermPattern::Variable(variable) => incoming.contains(variable),
12143        _ => false,
12144    }
12145}
12146
12147fn incoming_plus(incoming: &IncomingBound, extra: &IncomingBound) -> IncomingBound {
12148    let mut out = incoming.clone();
12149    out.merge(extra);
12150    out
12151}
12152
12153fn incoming_from_plan_left(
12154    incoming: &IncomingBound,
12155    left: &PlanNode,
12156    profile: Option<&StatsProfile>,
12157) -> IncomingBound {
12158    let rows = left.produced_row_count_estimate();
12159    let mut extra = IncomingBound::default();
12160    for variable in &left.output_vars().always_bound {
12161        let domain = join_key_domain_for_node(profile, left, variable)
12162            .map(|d| d.min(rows))
12163            .unwrap_or(rows);
12164        extra.insert(variable.clone(), Some(domain));
12165    }
12166    incoming_plus(incoming, &extra)
12167}
12168
12169fn plan_scan_op(
12170    pattern: &TriplePattern,
12171    profile: Option<&StatsProfile>,
12172    incoming: &IncomingBound,
12173    ctx: &QueryContext,
12174    scope: &GraphScope,
12175) -> Result<ScanOp, ComputeError> {
12176    let (subject_term, subject) = term_slot(&pattern.subject)?;
12177    let (predicate_term, predicate) = named_node_slot(&pattern.predicate);
12178    let (object_term, object) = term_slot(&pattern.object)?;
12179    let applied = apply_graph_scope(scope, ctx.dataset());
12180
12181    let encoded = EncodedTriplePattern {
12182        subject: subject_term,
12183        predicate: predicate_term,
12184        object: object_term,
12185        graph_name: applied.graph_name,
12186    };
12187    let extra = extra_bound_slots_for(&subject, &predicate, &object, &applied.graph, incoming);
12188    let produced_row_count_estimate = match profile {
12189        Some(p) if !p.is_empty() => {
12190            let per_key = estimate_pattern_with_bound_slots(p, &encoded, extra).max(1);
12191            scale_incoming_scan_estimate(
12192                p,
12193                &encoded,
12194                incoming,
12195                one_end_incoming_var(extra, &subject, &predicate, &object),
12196                per_key,
12197            )
12198        }
12199        _ => (4 - (bound_slots(&encoded) + extra.count()) as u64).max(1) * 1_000_000,
12200    };
12201
12202    let join_domains = JoinDomainStamps::classify(profile, &encoded);
12203
12204    Ok(ScanOp {
12205        fetch_once: None,
12206        ancestor_push_return_bound: None,
12207        pattern: encoded,
12208        subject,
12209        predicate,
12210        object,
12211        graph: applied.graph,
12212        produced_row_count_estimate,
12213        broadcasted: None,
12214        graph_filter: applied.graph_filter,
12215        grounded: Vec::new(),
12216        merge_default_graph: applied.merge_default_graph,
12217        marks: Vec::new(),
12218        domain_scan: None,
12219        head_scan: None,
12220        head_scan_counts: None,
12221        domain_counts: None,
12222        iri_only: Vec::new(),
12223        eager: Vec::new(),
12224        join_domains,
12225    })
12226}
12227
12228/// The four-field graph scope a lowered scan carries: which graphs the
12229/// pattern may read at its plan position. Public so plugins that mint scans
12230/// outside the SPARQL lowering (the text plugin's subject-mode candidates)
12231/// can copy a sibling scan's scope and keep visibility identical to the
12232/// surrounding BGP.
12233#[derive(Clone)]
12234pub struct AppliedGraph {
12235    /// Bound graph name when G is ground (`RdfDefault`, `FROM <g>`,
12236    /// `GRAPH <iri>`); `None` means unbound G (all-graphs or filtered).
12237    pub graph_name: Option<EncodedTerm>,
12238    /// Variable bound by the graph slot (`GRAPH ?g`).
12239    pub graph: Option<Variable>,
12240    /// Residual G allow-list or block-list (`FROM` windows, `GRAPH ?g`).
12241    pub graph_filter: Option<GraphFilter>,
12242    /// Same RDF-merge unique as [`ScanOp::merge_default_graph`].
12243    pub merge_default_graph: bool,
12244}
12245
12246/// The applied scope for a plain pattern at dataset scope (no `GRAPH`
12247/// block): the query's default window mapped exactly as the lowering maps
12248/// it (`RdfDefault` → `Some(DefaultGraph)`, `AllGraphs` → `None`, `FROM`
12249/// windows → their ground / allow shapes, plus the merge-default fixup).
12250pub fn applied_default_graph(dataset: &QueryDataset) -> AppliedGraph {
12251    apply_graph_scope(&GraphScope::Default, dataset)
12252}
12253
12254fn apply_graph_scope(scope: &GraphScope, dataset: &QueryDataset) -> AppliedGraph {
12255    let mut applied = match scope {
12256        GraphScope::Default => match &dataset.default {
12257            DefaultGraphWindow::RdfDefault => AppliedGraph {
12258                graph_name: Some(EncodedTerm::DefaultGraph),
12259                graph: None,
12260                graph_filter: None,
12261                merge_default_graph: false,
12262            },
12263            DefaultGraphWindow::AllGraphs => AppliedGraph {
12264                graph_name: None,
12265                graph: None,
12266                graph_filter: None,
12267                merge_default_graph: false,
12268            },
12269            DefaultGraphWindow::Empty => AppliedGraph {
12270                graph_name: Some(EncodedTerm::DefaultGraph),
12271                graph: None,
12272                graph_filter: None,
12273                merge_default_graph: false,
12274            },
12275            DefaultGraphWindow::Ground(term) => AppliedGraph {
12276                graph_name: Some(term.clone()),
12277                graph: None,
12278                graph_filter: None,
12279                merge_default_graph: false,
12280            },
12281            DefaultGraphWindow::Allow(filter) => AppliedGraph {
12282                graph_name: None,
12283                graph: None,
12284                graph_filter: Some(filter.clone()),
12285                merge_default_graph: false,
12286            },
12287        },
12288        GraphScope::NamedIri(term) => AppliedGraph {
12289            graph_name: Some(term.clone()),
12290            graph: None,
12291            graph_filter: None,
12292            merge_default_graph: false,
12293        },
12294        GraphScope::NamedVar { variable, window } => match window {
12295            NamedVarWindow::Collect => AppliedGraph {
12296                graph_name: None,
12297                graph: Some(variable.clone()),
12298                graph_filter: Some(GraphFilter::exclude_default()),
12299                merge_default_graph: false,
12300            },
12301            NamedVarWindow::Allow(filter) => AppliedGraph {
12302                graph_name: None,
12303                graph: Some(variable.clone()),
12304                graph_filter: Some(filter.clone()),
12305                merge_default_graph: false,
12306            },
12307            NamedVarWindow::Ground(term) => AppliedGraph {
12308                graph_name: Some(term.clone()),
12309                graph: Some(variable.clone()),
12310                graph_filter: None,
12311                merge_default_graph: false,
12312            },
12313        },
12314        GraphScope::Empty => AppliedGraph {
12315            graph_name: Some(EncodedTerm::DefaultGraph),
12316            graph: None,
12317            graph_filter: None,
12318            merge_default_graph: false,
12319        },
12320    };
12321    // Only the SPARQL default graph is an RDF merge. GRAPH keeps G identity.
12322    applied.merge_default_graph =
12323        matches!(scope, GraphScope::Default) && dataset.default.merge_default_graph();
12324    applied
12325}
12326
12327/// Scale a one-end incoming-bound scan by left distinct count.
12328///
12329/// Execution allow-lists every distinct incoming value (capped at 20 000).
12330/// `domain > PUSHDOWN_TERMS_LIMIT` is not pushed, so cost as unbound `|P|`.
12331/// Both ends incoming-bound, or an unknown domain, keep the per-key fan-out.
12332/// Incoming-bound `?p` (S/O not a one-end extra) uses the same scale on mean `|P|`.
12333fn scale_incoming_scan_estimate(
12334    profile: &StatsProfile,
12335    encoded: &EncodedTriplePattern,
12336    incoming: &IncomingBound,
12337    var: Option<&Variable>,
12338    per_key: u64,
12339) -> u64 {
12340    let Some(domain) = var.and_then(|v| incoming.known_domain(v)) else {
12341        return per_key;
12342    };
12343    if domain > PUSHDOWN_TERMS_LIMIT {
12344        return estimate_pattern(profile, encoded).max(1);
12345    }
12346    let unbound = estimate_pattern(profile, encoded).max(1);
12347    unbound.min(per_key.saturating_mul(domain))
12348}
12349
12350fn lower_path(
12351    subject: &TermPattern,
12352    path: &PropertyPathExpression,
12353    object: &TermPattern,
12354    _profile: Option<&StatsProfile>,
12355    incoming: &IncomingBound,
12356    ctx: &QueryContext,
12357    scope: &GraphScope,
12358) -> Result<PlanNode, ComputeError> {
12359    let mut strings = path_end_strings(subject);
12360    strings.extend(path_end_strings(object));
12361    let (subject_term, subject_var) = term_slot(subject)?;
12362    let (object_term, object_var) = term_slot(object)?;
12363    let path = encode_property_path(path);
12364    let applied = apply_graph_scope(scope, ctx.dataset());
12365    let start_bound = subject_term.is_some() || term_incoming_bound(subject, incoming);
12366    let end_bound = object_term.is_some() || term_incoming_bound(object, incoming);
12367    let produced_row_count_estimate = estimate_path_size(start_bound, &path, end_bound);
12368    Ok(PlanNode::Path(PathOp {
12369        subject_term,
12370        subject: subject_var,
12371        path,
12372        object_term,
12373        object: object_var,
12374        produced_row_count_estimate,
12375        strings,
12376        graph: applied.graph,
12377        graph_name: applied.graph_name,
12378        graph_filter: applied.graph_filter,
12379        merge_default_graph: applied.merge_default_graph,
12380    }))
12381}
12382
12383fn path_end_strings(pattern: &TermPattern) -> Vec<(StrHash, String)> {
12384    // One mint-and-seed entry point for every ground shape: path ends
12385    // consume only the lexical half (a scan's seek-union compares encoded
12386    // bytes; payloads would have no reader here), but deriving through
12387    // the predicate keeps the geo-lexical-key arm — a geometry const at a
12388    // path end still decodes to its ORIGINAL lexical downstream.
12389    match pattern {
12390        TermPattern::NamedNode(node) => {
12391            crate::query::caches::mint_const_entries(&Term::NamedNode(node.clone()))
12392                .1
12393                .0
12394        }
12395        TermPattern::Literal(literal) => {
12396            crate::query::caches::mint_const_entries(&Term::Literal(literal.clone()))
12397                .1
12398                .0
12399        }
12400        TermPattern::Variable(_) | TermPattern::BlankNode(_) => Vec::new(),
12401    }
12402}
12403
12404fn encode_property_path(path: &PropertyPathExpression) -> PropertyPath {
12405    match path {
12406        PropertyPathExpression::NamedNode(node) => PropertyPath::Predicate(EncodedTerm::from(node)),
12407        PropertyPathExpression::Reverse(inner) => {
12408            PropertyPath::Reverse(Box::new(encode_property_path(inner)))
12409        }
12410        PropertyPathExpression::Sequence(a, b) => PropertyPath::Sequence(
12411            Box::new(encode_property_path(a)),
12412            Box::new(encode_property_path(b)),
12413        ),
12414        PropertyPathExpression::Alternative(a, b) => PropertyPath::Alternative(
12415            Box::new(encode_property_path(a)),
12416            Box::new(encode_property_path(b)),
12417        ),
12418        PropertyPathExpression::ZeroOrMore(inner) => {
12419            PropertyPath::ZeroOrMore(Box::new(encode_property_path(inner)))
12420        }
12421        PropertyPathExpression::OneOrMore(inner) => {
12422            PropertyPath::OneOrMore(Box::new(encode_property_path(inner)))
12423        }
12424        PropertyPathExpression::ZeroOrOne(inner) => {
12425            PropertyPath::ZeroOrOne(Box::new(encode_property_path(inner)))
12426        }
12427        PropertyPathExpression::NegatedPropertySet(nodes) => {
12428            PropertyPath::NegatedPropertySet(nodes.iter().map(EncodedTerm::from).collect())
12429        }
12430    }
12431}
12432
12433/// Open `*` / `+` (neither end bound) is all-pairs reachability. Cost it above
12434/// any one-end walk or ordinary scan so the pipeline puts a selective leaf
12435/// first and the join can bind a path end.
12436const OPEN_STAR_ROW_ESTIMATE: u64 = u64::MAX / 4;
12437
12438pub(crate) fn estimate_path_size(start_bound: bool, path: &PropertyPath, end_bound: bool) -> u64 {
12439    if !start_bound && !end_bound && path.contains_star_or_plus() {
12440        return OPEN_STAR_ROW_ESTIMATE;
12441    }
12442    match path {
12443        PropertyPath::Predicate(predicate) => {
12444            let base = estimate_path_triple(start_bound, true, end_bound);
12445            // `rdf:type` steps are marginally costlier than other
12446            // predicate-bound scans: the type index lists every subject of
12447            // the type, so its result set skews larger. Matches sparopt's
12448            // +1 on `rdf:type` triple estimates.
12449            if *predicate == RDF_TYPE {
12450                base.saturating_add(1)
12451            } else {
12452                base
12453            }
12454        }
12455        PropertyPath::Reverse(inner) => estimate_path_size(end_bound, inner, start_bound),
12456        PropertyPath::Sequence(a, b) => {
12457            let forward = estimate_path_size(start_bound, a, false)
12458                .saturating_mul(estimate_path_size(true, b, end_bound));
12459            let backward = estimate_path_size(start_bound, a, true)
12460                .saturating_mul(estimate_path_size(false, b, end_bound));
12461            forward.min(backward)
12462        }
12463        PropertyPath::Alternative(a, b) => estimate_path_size(start_bound, a, end_bound)
12464            .saturating_add(estimate_path_size(start_bound, b, end_bound)),
12465        PropertyPath::ZeroOrMore(inner) => {
12466            if start_bound && end_bound {
12467                1
12468            } else if start_bound || end_bound {
12469                estimate_path_size(start_bound, inner, end_bound).saturating_mul(1000)
12470            } else {
12471                OPEN_STAR_ROW_ESTIMATE
12472            }
12473        }
12474        PropertyPath::OneOrMore(inner) => {
12475            if start_bound && end_bound {
12476                1
12477            } else if start_bound || end_bound {
12478                estimate_path_size(start_bound, inner, end_bound).saturating_mul(1000)
12479            } else {
12480                OPEN_STAR_ROW_ESTIMATE
12481            }
12482        }
12483        PropertyPath::ZeroOrOne(inner) => {
12484            if start_bound && end_bound {
12485                1
12486            } else if start_bound || end_bound {
12487                estimate_path_size(start_bound, inner, end_bound)
12488            } else {
12489                1_000_000_000
12490            }
12491        }
12492        PropertyPath::NegatedPropertySet(_) => estimate_path_triple(start_bound, false, end_bound),
12493    }
12494}
12495
12496/// Row estimate for one triple-shaped path step, keyed by which ends are
12497/// bound. Mirrors sparopt's `estimate_triple_pattern_size` calibration —
12498/// sparopt reshapes the algebra upstream of Waratah's planner, so the two
12499/// layers must agree on relative scan selectivity or they will argue about
12500/// which scan to run first. The predicate-and-object-bound and object-only
12501/// rows are sparopt 0.3.9's recalibration: a ground object is far more
12502/// selective than the old numbers assumed.
12503fn estimate_path_triple(subject_bound: bool, predicate_bound: bool, object_bound: bool) -> u64 {
12504    match (subject_bound, predicate_bound, object_bound) {
12505        (true, true, true) => 1,
12506        (true, true, false) => 10,
12507        (true, false, true) => 2,
12508        (false, true, true) => 1_000,
12509        (true, false, false) => 100,
12510        (false, false, false) => 1_000_000_000,
12511        (false, true, false) => 1_000_000,
12512        (false, false, true) => 10_000,
12513    }
12514}
12515
12516fn recost_path(path: &mut PathOp) {
12517    path.produced_row_count_estimate = estimate_path_size(
12518        path.subject_term.is_some(),
12519        &path.path,
12520        path.object_term.is_some(),
12521    );
12522}
12523
12524pub(crate) fn join_key_domain_for(
12525    profile: Option<&StatsProfile>,
12526    scan: &ScanOp,
12527    hash_keys: &[Variable],
12528) -> Option<u64> {
12529    let var = hash_keys.first()?;
12530    if !scan.is_live(var) {
12531        return None;
12532    }
12533    let slot = if scan.subject.as_ref() == Some(var) {
12534        JoinKeySlot::Subject
12535    } else if scan.object.as_ref() == Some(var) {
12536        JoinKeySlot::Object
12537    } else {
12538        return None;
12539    };
12540    let ground = match slot {
12541        JoinKeySlot::Subject => scan.pattern.subject.is_some(),
12542        JoinKeySlot::Object => scan.pattern.object.is_some(),
12543    };
12544    // Plan-time prefix (identity fold / unique BIND): the join key is one
12545    // constant, not the predicate's global HLL.
12546    if ground {
12547        return Some(1);
12548    }
12549    let profile = profile.filter(|p| !p.is_empty())?;
12550    // Only an immutable answer short-circuits; `Deferred` / `UnknownPredicate`
12551    // / `Unavailable` recompute live. `record_grounded` refreshes the stamps
12552    // when a later pass binds a slot, so this fallback is the correctness
12553    // backstop, not the expected hot path.
12554    if let JoinDomainStamp::Known(domain) = scan.join_domains.get(slot) {
12555        return Some(domain);
12556    }
12557    estimate_join_key_domain(profile, &scan.pattern, slot)
12558}
12559
12560/// Guard-rail floor for plan-driven TermDict pre-sizing: below this many
12561/// estimated distinct terms, a mid-query hash-doubling resize costs
12562/// microseconds and pre-allocating is not worth it — default growth only.
12563pub(crate) const TERM_DICT_RESERVE_FLOOR: u64 = 10_000;
12564
12565/// Guard-rail ceiling for plan-driven TermDict pre-sizing: estimates can
12566/// over-count (a variable's per-scan domain upper-bounds its real distinct
12567/// count), and conserving memory outranks avoiding a resize — a query whose
12568/// estimate exceeds this reserves exactly this much and grows past it
12569/// mid-query as needed.
12570pub(crate) const TERM_DICT_RESERVE_MAX: u64 = 1_000_000;
12571
12572/// The TermDict reserve amount an estimate maps to, or `None` to stay on
12573/// default growth (tiny estimates) — the pure core of
12574/// [`reserve_term_dict_from_plan`]'s guard rails.
12575pub(crate) fn term_dict_reserve_amount(estimate: u64) -> Option<u64> {
12576    let amount = estimate.min(TERM_DICT_RESERVE_MAX);
12577    (amount >= TERM_DICT_RESERVE_FLOOR).then_some(amount)
12578}
12579
12580/// March each variable's largest per-scan domain estimate into `maxima`.
12581/// Per-variable maxima, not per-scan sums: one variable appearing in
12582/// several scans still interns one term set. Only plain scans contribute —
12583/// `Values` rows are query-text constants (a handful), `Path` / custom /
12584/// aggregate-scan nodes are either small or not estimable this way.
12585fn estimated_distinct_terms(
12586    node: &PlanNode,
12587    profile: &StatsProfile,
12588    maxima: &mut Vec<(Variable, u64)>,
12589) {
12590    match node {
12591        PlanNode::Scan(scan) => {
12592            let slots = [
12593                (&scan.subject, scan.pattern.subject.is_none()),
12594                (&scan.object, scan.pattern.object.is_none()),
12595            ];
12596            for (slot, unbound) in slots {
12597                let Some(variable) = slot else { continue };
12598                if !unbound || !scan.is_live(variable) {
12599                    continue;
12600                }
12601                let domain =
12602                    join_key_domain_for(Some(profile), scan, std::slice::from_ref(variable))
12603                        .unwrap_or(0);
12604                if domain == 0 {
12605                    continue;
12606                }
12607                match maxima.iter_mut().find(|(v, _)| v == variable) {
12608                    Some(entry) => entry.1 = entry.1.max(domain),
12609                    None => maxima.push((variable.clone(), domain)),
12610                }
12611            }
12612        }
12613        PlanNode::Join { left, right, .. }
12614        | PlanNode::LeftJoin { left, right, .. }
12615        | PlanNode::Union { left, right } => {
12616            estimated_distinct_terms(left, profile, maxima);
12617            estimated_distinct_terms(right, profile, maxima);
12618        }
12619        PlanNode::NamedGraphs {
12620            variable,
12621            produced_row_count_estimate,
12622        } => {
12623            // The catalog graph IRIs all intern into the dict.
12624            if *produced_row_count_estimate > 0 {
12625                match maxima.iter_mut().find(|(v, _)| v == variable) {
12626                    Some(entry) => entry.1 = entry.1.max(*produced_row_count_estimate),
12627                    None => maxima.push((variable.clone(), *produced_row_count_estimate)),
12628                }
12629            }
12630        }
12631        PlanNode::Filter { inner, .. }
12632        | PlanNode::JoinGraphVar { inner, .. }
12633        | PlanNode::Extend { inner, .. }
12634        | PlanNode::Slice { inner, .. }
12635        | PlanNode::Distinct { inner, .. }
12636        | PlanNode::Sort { inner, .. }
12637        | PlanNode::Group { inner, .. } => estimated_distinct_terms(inner, profile, maxima),
12638        PlanNode::SubSelect(sub) => estimated_distinct_terms(&sub.inner, profile, maxima),
12639        PlanNode::CustomNode(_)
12640        | PlanNode::Path(_)
12641        | PlanNode::Values(_)
12642        | PlanNode::NamedGraphExists { .. }
12643        | PlanNode::DomainCounts { .. }
12644        | PlanNode::HeadCounts { .. }
12645        | PlanNode::PatternCount { .. }
12646        | PlanNode::Unit => {}
12647    }
12648}
12649
12650/// Plan-driven TermDict pre-sizing: reserve the estimated distinct-term
12651/// count up front so page materialization cannot trigger a mid-query
12652/// hash-doubling rehash — a one-time full-table relocation under the dict
12653/// mutex, profiled as a 38–196ms stall when a query crossed the
12654/// 458,752-entry boundary (7/8 × 2^19 buckets) mid-driver-page. Advisory
12655/// only: no profile, a tiny estimate, or a huge estimate all leave the
12656/// dict on its default (or clamped) behavior.
12657pub(crate) fn reserve_term_dict_from_plan(
12658    plan: &LogicalPlan,
12659    profile: Option<&StatsProfile>,
12660    ctx: &QueryContext,
12661) {
12662    // Guard rail 1: without stats there is no basis to pre-size on.
12663    let Some(profile) = profile else {
12664        return;
12665    };
12666    let mut maxima = Vec::new();
12667    estimated_distinct_terms(&plan.root, profile, &mut maxima);
12668    let estimate: u64 = maxima.iter().map(|(_, domain)| domain).sum();
12669    // Guard rails 2 and 3 live in the pure mapping.
12670    if let Some(amount) = term_dict_reserve_amount(estimate) {
12671        ctx.term_dict().reserve(amount as usize);
12672    }
12673}
12674
12675// Plan-time cache of merged Union key-vocabulary cardinalities.
12676//
12677// The merge is a register-max over every contributing arm sketch (a few
12678// thousand registers each) and `join_key_domain_for_node` is consulted many
12679// times per plan, so the merged number is memoized. The key is the
12680// contributing (predicate hash, slot) pairs plus the profile's `total_puts`;
12681// `LogicalPlan::from_prepared` clears the map at plan entry so a later query
12682// never inherits an earlier profile's number.
12683/// Key of the merged-union-cardinality cache: the profile's `total_puts`, then
12684/// the sorted contributing `(predicate hash, slot)` pairs.
12685type UnionDomainCacheKey = (u64, Vec<(StrHash, u8)>);
12686
12687thread_local! {
12688    static UNION_DOMAIN_CACHE: std::cell::RefCell<FxHashMap<UnionDomainCacheKey, u64>> =
12689        std::cell::RefCell::new(FxHashMap::default());
12690}
12691
12692fn clear_union_domain_cache() {
12693    UNION_DOMAIN_CACHE.with(|cache| cache.borrow_mut().clear());
12694}
12695
12696/// The mergeable vocabulary gathered from a Union's arms.
12697///
12698/// Sharing one [`HyperLogLog`](waratah_stats::HyperLogLog) per arm lets the
12699/// union's distinct-key count be one register-max merge instead of a sum
12700/// that counts an entity once per arm. A `rdf:type` arm answers from the
12701/// exact class map, which has no sketch; its count is added under the
12702/// disjointness assumption, an upper bound — the direction the domain
12703/// contract requires. The class-variable term describes one shared universe
12704/// and is added once whatever the arm count.
12705#[derive(Default)]
12706struct UnionVocabulary<'a> {
12707    /// Borrowed per-predicate sketches, one per contributing scan arm.
12708    sketches: Vec<&'a waratah_stats::HyperLogLog>,
12709    /// `(predicate hash, slot)` per sketch, the cache key's variable half.
12710    fingerprint: Vec<(StrHash, u8)>,
12711    /// Sum of the arms' cached cardinalities. An upper bound on the merged
12712    /// cardinality, used for the per-node row clamp and the join-arm
12713    /// comparison without re-reading registers.
12714    sketch_sum: u64,
12715    /// Exact counts summed across arms (ground-class `rdf:type` subjects).
12716    exact_add: u64,
12717    /// An exact count of one shared universe, added once per union (the
12718    /// `rdf:type` class variable).
12719    exact_once: u64,
12720}
12721
12722impl UnionVocabulary<'_> {
12723    /// A merge-free size proxy for choosing between two join arms; the final
12724    /// domain uses the merged cardinality, not this.
12725    fn size_proxy(&self) -> u64 {
12726        self.sketch_sum
12727            .saturating_add(self.exact_add)
12728            .saturating_add(self.exact_once)
12729    }
12730}
12731
12732/// One node's verdict for a union key: mergeable vocabulary, no binding of
12733/// the variable, or a binding whose vocabulary cannot be sketched.
12734enum UnionVocabularyWalk<'a> {
12735    Value(UnionVocabulary<'a>),
12736    /// The node does not bind the variable at all.
12737    Absent,
12738    /// The node binds the variable but its key set is not sketchable (a
12739    /// `Path`, `Values`, a missing sketch, or a grounded slot).
12740    Unknown,
12741}
12742
12743/// Gather `node`'s mergeable key vocabulary for `variable`.
12744///
12745/// Structural wrappers pass through; a join's key set cannot exceed either
12746/// arm's, so the tighter arm wins (the scalar rule's `min`); a union of
12747/// vocabularies merges. Every unrecognised or unsketchable shape is
12748/// `Unknown`, which makes the caller fall back to the scalar sum and keeps
12749/// this walker's contract conservative: it never fabricates a small domain.
12750fn union_vocabulary_for<'a>(
12751    profile: &'a StatsProfile,
12752    node: &PlanNode,
12753    variable: &Variable,
12754) -> UnionVocabularyWalk<'a> {
12755    match node {
12756        PlanNode::Scan(scan) => {
12757            let Some((pattern, slot)) = scan_key_vocabulary(node, variable) else {
12758                // A grounded key slot prices as domain 1 on the scalar path;
12759                // bail rather than mix a constant into a merged set.
12760                return if scan.subject.as_ref() == Some(variable)
12761                    || scan.object.as_ref() == Some(variable)
12762                {
12763                    UnionVocabularyWalk::Unknown
12764                } else {
12765                    UnionVocabularyWalk::Absent
12766                };
12767            };
12768            let Some(predicate) = pattern.predicate.as_ref().and_then(named_node_hash) else {
12769                return UnionVocabularyWalk::Unknown;
12770            };
12771            if pattern.predicate.as_ref() == Some(&RDF_TYPE) {
12772                if slot == JoinKeySlot::Subject
12773                    && let Some(object) = pattern.object.as_ref()
12774                    && let Some(class) = named_node_hash(object)
12775                    && let Some(&count) = profile.class_counts.get(&class)
12776                    && count > 0
12777                {
12778                    return UnionVocabularyWalk::Value(UnionVocabulary {
12779                        exact_add: count,
12780                        ..UnionVocabulary::default()
12781                    });
12782                }
12783                if slot == JoinKeySlot::Object && !profile.class_counts.is_empty() {
12784                    return UnionVocabularyWalk::Value(UnionVocabulary {
12785                        exact_once: profile.class_counts.len() as u64,
12786                        ..UnionVocabulary::default()
12787                    });
12788                }
12789            }
12790            let sketch = match slot {
12791                JoinKeySlot::Subject => profile.subjects_per_predicate.get(&predicate),
12792                JoinKeySlot::Object => profile.objects_per_predicate.get(&predicate),
12793            };
12794            match sketch {
12795                Some(sketch) => {
12796                    let cardinality = match slot {
12797                        JoinKeySlot::Subject => profile.subject_domain(&predicate),
12798                        JoinKeySlot::Object => profile.object_domain(&predicate),
12799                    }
12800                    .unwrap_or_else(|| sketch.cardinality());
12801                    UnionVocabularyWalk::Value(UnionVocabulary {
12802                        sketches: vec![sketch],
12803                        fingerprint: vec![(predicate, slot as u8)],
12804                        sketch_sum: cardinality,
12805                        ..UnionVocabulary::default()
12806                    })
12807                }
12808                None => UnionVocabularyWalk::Unknown,
12809            }
12810        }
12811        PlanNode::Extend { inner, .. }
12812        | PlanNode::Filter { inner, .. }
12813        | PlanNode::Slice { inner, .. }
12814        | PlanNode::Distinct { inner, .. }
12815        | PlanNode::Sort { inner, .. }
12816        | PlanNode::Group { inner, .. }
12817        | PlanNode::JoinGraphVar { inner, .. } => union_vocabulary_for(profile, inner, variable),
12818        PlanNode::Join { left, right, .. } => {
12819            let picked = match (
12820                union_vocabulary_for(profile, left, variable),
12821                union_vocabulary_for(profile, right, variable),
12822            ) {
12823                (UnionVocabularyWalk::Value(a), UnionVocabularyWalk::Value(b)) => {
12824                    if a.size_proxy() <= b.size_proxy() {
12825                        UnionVocabularyWalk::Value(a)
12826                    } else {
12827                        UnionVocabularyWalk::Value(b)
12828                    }
12829                }
12830                // The join's keys are a subset of either arm's, so one arm's
12831                // vocabulary is a sound upper bound.
12832                (UnionVocabularyWalk::Value(value), _) | (_, UnionVocabularyWalk::Value(value)) => {
12833                    UnionVocabularyWalk::Value(value)
12834                }
12835                (UnionVocabularyWalk::Absent, UnionVocabularyWalk::Absent) => {
12836                    UnionVocabularyWalk::Absent
12837                }
12838                _ => UnionVocabularyWalk::Unknown,
12839            };
12840            clamp_join_vocabulary_to_rows(picked, node.produced_row_count_estimate())
12841        }
12842        PlanNode::Union { left, right } => {
12843            match (
12844                union_vocabulary_for(profile, left, variable),
12845                union_vocabulary_for(profile, right, variable),
12846            ) {
12847                (UnionVocabularyWalk::Value(mut left), UnionVocabularyWalk::Value(right)) => {
12848                    left.sketches.extend(right.sketches);
12849                    left.fingerprint.extend(right.fingerprint);
12850                    left.sketch_sum = left.sketch_sum.saturating_add(right.sketch_sum);
12851                    left.exact_add = left.exact_add.saturating_add(right.exact_add);
12852                    left.exact_once = left.exact_once.max(right.exact_once);
12853                    UnionVocabularyWalk::Value(left)
12854                }
12855                // An arm that does not bind the key keeps the scalar rule's
12856                // whole-union `None` (a `Path` may bind unseen), and an
12857                // unsketchable arm cannot be merged around without dropping
12858                // keys from the domain.
12859                _ => UnionVocabularyWalk::Unknown,
12860            }
12861        }
12862        _ => UnionVocabularyWalk::Unknown,
12863    }
12864}
12865
12866/// Cap a join's key vocabulary at its emitted rows.
12867///
12868/// Only a join does this. A join's output is the filtered intersection of its
12869/// arms, so its emitted rows are a genuine bound on the surviving keys — the
12870/// motivating shape is a global predicate domain (5.4M `isPartOf` subjects)
12871/// behind a 452-row catalog join, where keeping the sketch would dominate a
12872/// union merge. A pushed scan or a union carries a push-clamped cell that is
12873/// smaller than the key space it stands in for, so clamping those would
12874/// shrink a probe's domain below its true key space. A sketch set that sums
12875/// far above the bound cannot be clamped register-wise; it becomes an exact
12876/// additive term at the row count (sound: the key set is at most the rows,
12877/// and the caller treats adds as disjoint). The 2x margin keeps HLL error
12878/// (~1-2%) and estimate noise out of the decision.
12879fn clamp_join_vocabulary_to_rows<'a>(
12880    walked: UnionVocabularyWalk<'a>,
12881    rows: u64,
12882) -> UnionVocabularyWalk<'a> {
12883    let UnionVocabularyWalk::Value(vocabulary) = walked else {
12884        return walked;
12885    };
12886    let rows = rows.max(1);
12887    if vocabulary.size_proxy() > rows.saturating_mul(2) {
12888        UnionVocabularyWalk::Value(UnionVocabulary {
12889            exact_add: rows,
12890            ..UnionVocabulary::default()
12891        })
12892    } else {
12893        UnionVocabularyWalk::Value(vocabulary)
12894    }
12895}
12896
12897/// A Union's merged distinct-key domain, when every arm's vocabulary is
12898/// either sketchable or an exact `rdf:type` count.
12899///
12900/// `None` falls back to the scalar sum/mixed rule: an unsketchable arm, a
12901/// missing sketch, a grounded slot, or an arm that does not bind the key.
12902fn union_domain_from_vocabularies(
12903    profile: Option<&StatsProfile>,
12904    node: &PlanNode,
12905    variable: &Variable,
12906) -> Option<u64> {
12907    let profile = profile.filter(|profile| !profile.is_empty())?;
12908    let UnionVocabularyWalk::Value(vocabulary) = union_vocabulary_for(profile, node, variable)
12909    else {
12910        return None;
12911    };
12912    let merged = if vocabulary.sketches.is_empty() {
12913        0
12914    } else {
12915        let mut fingerprint = vocabulary.fingerprint.clone();
12916        fingerprint.sort_unstable();
12917        let key = (profile.total_puts, fingerprint);
12918        match UNION_DOMAIN_CACHE.with(|cache| cache.borrow().get(&key).copied()) {
12919            Some(cardinality) => cardinality,
12920            None => {
12921                let mut merged = vocabulary.sketches[0].clone();
12922                for sketch in &vocabulary.sketches[1..] {
12923                    merged.merge(sketch).ok()?;
12924                }
12925                let cardinality = merged.cardinality();
12926                UNION_DOMAIN_CACHE.with(|cache| {
12927                    cache.borrow_mut().insert(key, cardinality);
12928                });
12929                cardinality
12930            }
12931        }
12932    };
12933    Some(
12934        merged
12935            .saturating_add(vocabulary.exact_add)
12936            .saturating_add(vocabulary.exact_once)
12937            .max(1),
12938    )
12939}
12940
12941/// Domain (distinct bound terms) of `variable` in `node`'s output, when the
12942/// node can supply one. Crate-visible, not public: the planner's own
12943/// cardinality estimates and the EXPLAIN estimate render are the only
12944/// callers. A plugin rewrite in another crate prices a join it constructs
12945/// from `produced_row_count_estimate` / `estimate_join_rows_multi` instead,
12946/// because it has no profile handle to ask for a domain.
12947pub(crate) fn join_key_domain_for_node(
12948    profile: Option<&StatsProfile>,
12949    node: &PlanNode,
12950    variable: &Variable,
12951) -> Option<u64> {
12952    match node {
12953        PlanNode::Scan(scan) => join_key_domain_for(profile, scan, std::slice::from_ref(variable)),
12954        PlanNode::Path(_) => None,
12955        // Each CustomOp row carries a distinct output term (geo_scan emits
12956        // distinct ?g candidates), so the variable's domain is the row count.
12957        PlanNode::CustomNode(op) => op
12958            .variables
12959            .contains(variable)
12960            .then_some(op.produced_row_count_estimate),
12961        PlanNode::Values(values) => values.distinct_key_count(variable),
12962        // Every emitted row carries a distinct head term, so the head
12963        // variable's domain is the node's own row estimate.
12964        PlanNode::DomainCounts {
12965            head,
12966            produced_row_count_estimate,
12967            ..
12968        } if head == variable => Some(*produced_row_count_estimate),
12969        PlanNode::DomainCounts { .. } => None,
12970        PlanNode::HeadCounts { .. } | PlanNode::PatternCount { .. } => None,
12971        PlanNode::Join { left, right, .. } => {
12972            // Joined distinct keys cannot exceed either child's domain, so
12973            // both known → `min` (intersection upper bound). One unknown
12974            // child still yields a valid upper bound from the known side
12975            // (`None` is missing HLL / Path, not an empty domain).
12976            match (
12977                join_key_domain_for_node(profile, left, variable),
12978                join_key_domain_for_node(profile, right, variable),
12979            ) {
12980                (Some(a), Some(b)) => Some(a.min(b)),
12981                (a, b) => a.or(b),
12982            }
12983        }
12984        // Required side only: OPTIONAL does not add always-bound join keys.
12985        PlanNode::LeftJoin { left, .. } => join_key_domain_for_node(profile, left, variable),
12986        PlanNode::Union { left, right } => {
12987            // Merge the arms' sketches when every arm is sketchable or an
12988            // exact rdf:type count. The sum below counts an entity once per
12989            // arm (a subject with three facet predicates three times); the
12990            // sketches are mergeable, so the union's distinct-key count is
12991            // one register-max merge. Falls through to the sum when an arm
12992            // cannot be sketched, preserving the scalar contract.
12993            if let Some(domain) = union_domain_from_vocabularies(profile, node, variable) {
12994                return Some(domain);
12995            }
12996            // `None` is unknown (Path, missing HLL — including one the wire
12997            // trim dropped), not an empty arm. Both known: the union's key
12998            // domain is the sum, itself an upper bound (arms may share
12999            // values). ONE known: the unknown arm contributes its ROW
13000            // ESTIMATE when it hosts the key — every row carries at most
13001            // one distinct key value, so `known + rows` is a sound upper
13002            // bound, and a sketchless 1-row arm beside an 8M-row sketched
13003            // arm no longer discards the known sketch (the old
13004            // both-or-nothing rule poisoned the union's whole domain, and
13005            // the seating-cost model's unknown-domain fallback priced every pushed
13006            // page as a full-arm match). An arm that does not even host
13007            // the key keeps `None`: `probe_scan_has_key` cannot see every
13008            // hosting shape (a `Path` binds its slots), and fabricating a
13009            // SMALL domain is the unsafe direction. Both unknown: `None`,
13010            // the same contract as a sketchless bare scan.
13011            let left_domain = join_key_domain_for_node(profile, left, variable);
13012            let right_domain = join_key_domain_for_node(profile, right, variable);
13013            match (left_domain, right_domain) {
13014                (Some(a), Some(b)) => Some(a.saturating_add(b)),
13015                (Some(a), None) if probe_scan_has_key(right, variable) => {
13016                    Some(a.saturating_add(right.produced_row_count_estimate()))
13017                }
13018                (None, Some(b)) if probe_scan_has_key(left, variable) => {
13019                    Some(b.saturating_add(left.produced_row_count_estimate()))
13020                }
13021                _ => None,
13022            }
13023        }
13024        PlanNode::Filter {
13025            inner,
13026            early,
13027            residual,
13028            exists,
13029            ..
13030        } => {
13031            // A FILTER emits at most its inner's rows, and its surviving
13032            // distinct keys cannot outnumber those rows. A global
13033            // selectivity factor says nothing about WHICH keys survive, so
13034            // the output-row bound is the sound domain hook for the filter
13035            // model. Only clamp when a factor is present: with `None` the
13036            // inner row cell may itself be a push clamp, and the
13037            // containment-push basis must still see through it.
13038            let inner_domain = join_key_domain_for_node(profile, inner, variable)?;
13039            match filter_selectivity_milli(early.as_ref(), residual.as_ref(), exists) {
13040                Some(selectivity) => Some(filter_domain_bound(
13041                    inner_domain,
13042                    inner.produced_row_count_estimate(),
13043                    selectivity,
13044                )),
13045                None => Some(inner_domain),
13046            }
13047        }
13048        PlanNode::Extend { inner, .. }
13049        | PlanNode::Slice { inner, .. }
13050        | PlanNode::Distinct { inner, .. }
13051        | PlanNode::Sort { inner, .. }
13052        | PlanNode::Group { inner, .. }
13053        | PlanNode::JoinGraphVar { inner, .. } => {
13054            join_key_domain_for_node(profile, inner, variable)
13055        }
13056        // The boundary has no key-domain stats for its output; `None` keeps
13057        // row-estimate-only costing (never fabricates a small domain).
13058        PlanNode::SubSelect(_) => None,
13059        PlanNode::NamedGraphs {
13060            produced_row_count_estimate,
13061            ..
13062        } => Some(*produced_row_count_estimate),
13063        PlanNode::Unit | PlanNode::NamedGraphExists { .. } => None,
13064    }
13065}
13066
13067/// Order a keyed join's `hash_keys` by the rows each key's pushed list is
13068/// expected to return from the probe: `driver key domain × probe fan-out`,
13069/// where fan-out is `probe rows / probe key domain` — all from the stats
13070/// profile. The FIRST key is load-bearing twice: the runtime broadcasts it first
13071/// (`join_keys_scan_filter` first-suitable, `PushedKeyVals` entry order) and the
13072/// restamp claim names it — so a structurally-first key with a tiny domain
13073/// but huge fan-out (5 datasets × ~23k `isPartOf` rows each) must not
13074/// silently beat a larger list with near-key selectivity (~100 subjects ×
13075/// ~2 rows). Costing model: broadcasting N keys is cheap for storage (N prefix
13076/// seeks, capped at [`PUSHDOWN_TERMS_LIMIT`] either way) while the rows
13077/// they let through all cross the wire and pay again in the compute-side
13078/// join — so minimize expected return, not list size.
13079///
13080/// Keys with an unknown cost (no profile, a key the probe subtree does not
13081/// host in any scan slot — the runtime could never broadcast it — or an unknown
13082/// DRIVER-side domain, i.e. an unsizable list) sort LAST, and the sort is
13083/// stable: with no information the order is exactly the structural order
13084/// this function replaced. An unknown PROBE-side fan-out defaults to 1:
13085/// the list size (driver domain) is what multiplies wire cost, so ranking
13086/// by list size alone is the right degenerate — this keeps a ground-unique
13087/// 1-term driver (driver domain 1) ranked first even when the probe side
13088/// has no sketch for that key, preserving construction-time grounding.
13089/// The join kernels themselves treat the key list as a set (`join_layout`
13090/// matches columns by name), so reordering is semantically inert for them.
13091fn reorder_hash_keys_by_probe_return(
13092    hash_keys: &mut [Variable],
13093    probe_key_domains: &mut [u64],
13094    probe_key_overlap_milli: &mut [u64],
13095    left: &PlanNode,
13096    right: &PlanNode,
13097    profile: Option<&StatsProfile>,
13098) {
13099    if hash_keys.len() < 2 {
13100        return;
13101    }
13102    // The two stamps ride `hash_keys` as one unit: either full-length or
13103    // empty (placeholder vecs from transform-built nodes). A
13104    // shorter-but-nonempty slice would mis-pair with its key after the
13105    // sort.
13106    debug_assert!(
13107        probe_key_domains.is_empty() || probe_key_domains.len() == hash_keys.len(),
13108        "domain stamps must be empty or key-aligned"
13109    );
13110    debug_assert!(
13111        probe_key_overlap_milli.is_empty() || probe_key_overlap_milli.len() == hash_keys.len(),
13112        "overlap stamps must be empty or key-aligned"
13113    );
13114    let probe_rows = right.produced_row_count_estimate() as u128;
13115    let cost = |key: &Variable| -> Option<u128> {
13116        if !probe_scan_has_key(right, key) {
13117            return None;
13118        }
13119        let driver_domain = join_key_domain_for_node(profile, left, key)? as u128;
13120        let fan_out = match join_key_domain_for_node(profile, right, key) {
13121            Some(domain) => probe_rows / domain.max(1) as u128,
13122            None => 1,
13123        };
13124        Some(driver_domain * fan_out)
13125    };
13126    // Sort keys and their stamped domains as one unit so the two stay
13127    // aligned (`probe_key_domains[i]` documents `hash_keys[i]`). A shorter/empty
13128    // domain slice is tolerated: missing entries ride along as unknown (0).
13129    let mut paired: Vec<(Variable, u64, u64, Option<u128>)> = hash_keys
13130        .iter()
13131        .enumerate()
13132        .map(|(i, key)| {
13133            (
13134                key.clone(),
13135                probe_key_domains.get(i).copied().unwrap_or(0),
13136                probe_key_overlap_milli.get(i).copied().unwrap_or(0),
13137                cost(key),
13138            )
13139        })
13140        .collect();
13141    // Unknown cost (None) sorts LAST — `hash_keys.first()` is what the
13142    // restamp claim names and what broadcasts as the first allow-list, and an
13143    // unsizable key must not preempt a shippable one. (`Option`'s own
13144    // ordering would sort `None` first.)
13145    paired.sort_by_key(|(_, _, _, order)| (*order).unwrap_or(u128::MAX));
13146    for (i, (key, domain, overlap, _)) in paired.into_iter().enumerate() {
13147        hash_keys[i] = key;
13148        if i < probe_key_domains.len() {
13149            probe_key_domains[i] = domain;
13150        }
13151        if i < probe_key_overlap_milli.len() {
13152            probe_key_overlap_milli[i] = overlap;
13153        }
13154    }
13155}
13156
13157/// Bind `term` into `slot` on `pattern` (broadcast allow-list / plan specialization).
13158pub(crate) fn bind_pattern_slot(
13159    mut pattern: EncodedTriplePattern,
13160    slot: PatternSlot,
13161    term: &EncodedTerm,
13162) -> EncodedTriplePattern {
13163    match slot {
13164        PatternSlot::Subject => pattern.subject = Some(term.clone()),
13165        PatternSlot::Predicate => pattern.predicate = Some(term.clone()),
13166        PatternSlot::Object => pattern.object = Some(term.clone()),
13167    }
13168    pattern
13169}
13170
13171fn pattern_slot_term(pattern: &EncodedTriplePattern, slot: PatternSlot) -> Option<&EncodedTerm> {
13172    match slot {
13173        PatternSlot::Subject => pattern.subject.as_ref(),
13174        PatternSlot::Predicate => pattern.predicate.as_ref(),
13175        PatternSlot::Object => pattern.object.as_ref(),
13176    }
13177}
13178
13179/// Fold identity-safe `sameTerm` / `=` FILTERs into hexastore ground slots,
13180/// and `!sameTerm(?g, iri)` into GRAPH block-lists.
13181///
13182/// Keeps `ScanOp` variable names so projection still sees the column. Numeric
13183/// `=` is left as a Filter (SPARQL value equality is not encoded identity).
13184/// Grounding / G-exclusion is still applied when the compared variable may be
13185/// unbound (`OPTIONAL` miss, `UNION`, `VALUES` UNDEF, `GROUP BY` of those);
13186/// the Filter / HAVING node is kept in that case so unbound rows still fail.
13187/// Note, this only folds downwards/inwards from this Node. Never up.
13188fn fold_identity_filters(node: &mut PlanNode, profile: Option<&StatsProfile>) {
13189    if matches!(node, PlanNode::Filter { .. }) {
13190        let PlanNode::Filter {
13191            inner,
13192            mut early,
13193            mut residual,
13194            mut exists,
13195            ..
13196        } = std::mem::replace(node, PlanNode::Unit)
13197        else {
13198            unreachable!("Filter arm");
13199        };
13200        let mut inner = *inner;
13201        fold_identity_filters(&mut inner, profile);
13202        for clause in &mut exists {
13203            fold_identity_filters(&mut clause.body, profile);
13204        }
13205        if let Some(expr) = early.take() {
13206            let inner_vars = inner.output_vars();
13207            let mut kept = Vec::new();
13208            for conjunct in flatten_and(&expr) {
13209                match identity_safe_equality(&conjunct, &inner) {
13210                    Some(IdentityFold::Bind(eq)) => {
13211                        let grounding = ground_identity_term(
13212                            &mut inner,
13213                            &eq.variable,
13214                            &eq.term,
13215                            profile,
13216                            &eq.strings,
13217                        );
13218                        for clause in &mut exists {
13219                            let _ = ground_identity_term(
13220                                &mut clause.body,
13221                                &eq.variable,
13222                                &eq.term,
13223                                profile,
13224                                &eq.strings,
13225                            );
13226                        }
13227                        // Prefix scans even when a UNION/VALUES producer still
13228                        // disagrees. Only drop the conjunct when every producer
13229                        // of this variable is locked to `term` (and the var is
13230                        // always-bound — OPTIONAL miss / UNION omit / UNDEF).
13231                        if grounding.producers_constrained
13232                            && inner_vars.is_always_bound(&eq.variable)
13233                        {
13234                            continue;
13235                        }
13236                        // Keep FILTER/HAVING. Grounding a scan does not remove
13237                        // OPTIONAL-miss (or UNION / UNDEF) rows, so a maybe-unbound
13238                        // `variable` can still arrive here. SPARQL comparison on
13239                        // unbound is a type error; FILTER/HAVING treat that as false
13240                        // and drop the row. Deleting this predicate would keep that
13241                        // extra unbound solution.
13242                        kept.push(conjunct);
13243                    }
13244                    Some(IdentityFold::AlwaysTrue { a, b }) => {
13245                        if inner_vars.is_always_bound(&a) && inner_vars.is_always_bound(&b) {
13246                            continue;
13247                        }
13248                        kept.push(conjunct);
13249                    }
13250                    None => kept.push(conjunct),
13251                }
13252            }
13253            // Ground single-value producers into the KEPT early conjuncts
13254            // too — `VALUES ?a { 5 } FILTER(?a < ?b)` evaluates the
13255            // comparison per row either way, but a pushed-in constant lets
13256            // the encoded compare fold one side at plan time. Runs AFTER the
13257            // identity loop so an `?a = term` conjunct still grounds scans
13258            // before its variable disappears.
13259            let mut grounded_kept = Vec::with_capacity(kept.len());
13260            for mut conjunct in kept {
13261                substitute_ground_variables(&mut conjunct, &inner, &inner_vars);
13262                grounded_kept.push(conjunct);
13263            }
13264            early = and_fold(grounded_kept);
13265            // Push `!sameTerm(?g, iri)` into GRAPH block-lists even when `?g`
13266            // may be unbound. Drop the residual only when every output row
13267            // binds `?g`: OPTIONAL miss / UNION omit would otherwise survive
13268            // (`sameTerm` on unbound is a type error → FILTER false).
13269            if let Some(expr) = early.as_ref()
13270                && let Some((variable, extra)) = collect_not_same_term_graph(expr)
13271            {
13272                let applied = apply_graph_exclusions(&mut inner, &variable, &extra);
13273                if applied && inner_vars.is_always_bound(&variable) {
13274                    early = None;
13275                }
13276            }
13277        }
13278        for clause in &mut exists {
13279            for variable in &clause.correlation {
13280                if let Some(term) = unique_ground_term(&inner, variable) {
13281                    let _ = ground_identity_term(&mut clause.body, variable, &term, profile, &[]);
13282                }
13283            }
13284        }
13285        // Ground single-value producers into RESIDUAL conjuncts as well: a
13286        // fully-bound single-value VALUES column or a ground BIND feeding a
13287        // residual custom function (GeoSPARQL `geof:*`) must look like the
13288        // inline constant the same FILTER text would carry, or a datatype
13289        // plugin's rewrite never fires. Guards mirror the early fold: the
13290        // variable must be always-bound and every producer locked to one
13291        // term, so the substitution cannot change which rows survive.
13292        let inner_vars = inner.output_vars();
13293        if let Some(expr) = residual.take() {
13294            let conjuncts = flatten_and(&expr);
13295            let mut kept = Vec::with_capacity(conjuncts.len());
13296            for mut conjunct in conjuncts {
13297                ground_residual_conjunct(
13298                    &mut conjunct,
13299                    &inner,
13300                    &inner_vars,
13301                    &producer_keeps_variable,
13302                );
13303                kept.push(conjunct);
13304            }
13305            residual = and_fold(kept);
13306        }
13307        // Early could now be empty, due to folding grounded terms.
13308        // So if there is also no residulal then the filter can
13309        // be able to be completely removed.
13310        if early.is_none() && residual.is_none() && exists.is_empty() {
13311            *node = inner;
13312        } else {
13313            // Make a new Filter based on the possibly modified filter ops.
13314            *node = PlanNode::Filter {
13315                inner: Box::new(inner),
13316                early,
13317                residual,
13318                exists,
13319                one_to_one: false,
13320            };
13321        }
13322        return;
13323    }
13324    // Not a Filter, we can keep drilling until we find a Filter.
13325    // fold_identity_filters is recursive (above) once it hits a filter.
13326    match node {
13327        PlanNode::CustomNode(op) => {
13328            for child in &mut op.children {
13329                fold_identity_filters(child, profile);
13330            }
13331        }
13332        PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
13333            fold_identity_filters(left, profile);
13334            fold_identity_filters(right, profile);
13335        }
13336        PlanNode::LeftJoin {
13337            left,
13338            right,
13339            early_filter,
13340            residual_filter: _,
13341            ..
13342        } => {
13343            fold_identity_filters(left, profile);
13344            fold_identity_filters(right, profile);
13345            fold_left_join_early_into_right(right, early_filter, profile);
13346        }
13347        // The subquery is a scope boundary: filters *inside* it fold against
13348        // inner scans (scope-local), but an outer filter's grounding walk
13349        // (`ground_identity_walk`) must never reach through the boundary.
13350        PlanNode::SubSelect(sub) => fold_identity_filters(&mut sub.inner, profile),
13351        PlanNode::Extend { inner, .. }
13352        | PlanNode::Slice { inner, .. }
13353        | PlanNode::Distinct { inner, .. }
13354        | PlanNode::Sort { inner, .. }
13355        | PlanNode::Group { inner, .. }
13356        | PlanNode::JoinGraphVar { inner, .. } => {
13357            fold_identity_filters(inner, profile);
13358        }
13359        PlanNode::Filter { .. } => unreachable!("Filter handled above"),
13360        PlanNode::Scan(_)
13361        | PlanNode::Path(_)
13362        | PlanNode::Values(_)
13363        | PlanNode::NamedGraphs { .. }
13364        | PlanNode::NamedGraphExists { .. }
13365        | PlanNode::DomainCounts { .. }
13366        | PlanNode::HeadCounts { .. }
13367        | PlanNode::PatternCount { .. }
13368        | PlanNode::Unit => {}
13369    }
13370}
13371
13372fn fold_left_join_early_into_right(
13373    right: &mut PlanNode,
13374    early_filter: &mut Option<Expression>,
13375    profile: Option<&StatsProfile>,
13376) {
13377    let Some(expr) = early_filter.take() else {
13378        return;
13379    };
13380    let right_vars = right.output_vars().all();
13381    let mut kept = Vec::new();
13382    for conjunct in flatten_and(&expr) {
13383        let all_on_right = variables_in_expression(&conjunct)
13384            .iter()
13385            .all(|v| right_vars.contains(v));
13386        // Prefix scans even when a UNION/VALUES producer still disagrees;
13387        // only drop `early_filter` when every producer of the variable is
13388        // locked to `term`.
13389        let folded = all_on_right
13390            && match identity_safe_equality(&conjunct, right) {
13391                Some(IdentityFold::Bind(eq)) => {
13392                    ground_identity_term(right, &eq.variable, &eq.term, profile, &eq.strings)
13393                        .producers_constrained
13394                }
13395                Some(IdentityFold::AlwaysTrue { .. }) => true,
13396                None => false,
13397            };
13398        if !folded {
13399            kept.push(conjunct);
13400        }
13401    }
13402    *early_filter = and_fold(kept);
13403}
13404
13405struct IdentityEquality {
13406    variable: Variable,
13407    term: EncodedTerm,
13408    strings: Vec<(StrHash, String)>,
13409}
13410
13411enum IdentityFold {
13412    Bind(IdentityEquality),
13413    AlwaysTrue { a: Variable, b: Variable },
13414}
13415
13416fn identity_safe_equality(expr: &Expression, node: &PlanNode) -> Option<IdentityFold> {
13417    let (a, b, equal_not_same_term) = match expr {
13418        Expression::SameTerm(a, b) => (a.as_ref(), b.as_ref(), false),
13419        Expression::Equal(a, b) => (a.as_ref(), b.as_ref(), true),
13420        _ => return None,
13421    };
13422    match (a, b) {
13423        (Expression::Variable(va), Expression::Variable(vb)) => {
13424            identity_safe_var_var(va, vb, equal_not_same_term, node)
13425        }
13426        (Expression::Variable(v), c) | (c, Expression::Variable(v)) => {
13427            let (term, strings) = encoded_ground_expr(c)?;
13428            identity_bind_if_safe(v, term, strings, equal_not_same_term)
13429        }
13430        _ => None,
13431    }
13432}
13433
13434fn identity_safe_var_var(
13435    va: &Variable,
13436    vb: &Variable,
13437    equal_not_same_term: bool,
13438    node: &PlanNode,
13439) -> Option<IdentityFold> {
13440    let ground_a = unique_ground_with_strings(node, va);
13441    let ground_b = unique_ground_with_strings(node, vb);
13442    match (ground_a, ground_b) {
13443        (Some((term, strings)), None) => {
13444            identity_bind_if_safe(vb, term, strings, equal_not_same_term)
13445        }
13446        (None, Some((term, strings))) => {
13447            identity_bind_if_safe(va, term, strings, equal_not_same_term)
13448        }
13449        (Some((ta, _)), Some((tb, _))) if ta == tb => {
13450            if equal_not_same_term && !sparql_equal_is_encoded_identity(&ta) {
13451                return None;
13452            }
13453            Some(IdentityFold::AlwaysTrue {
13454                a: va.clone(),
13455                b: vb.clone(),
13456            })
13457        }
13458        (Some(_), Some(_)) => None,
13459        (None, None) => {
13460            // TODO: multi-row VALUES unification — Join(Values(?c), Scan(?b))
13461            // plus sameTerm(?b, ?c) should become a shared join key / allow-list
13462            // so a small table can broadcast into the scan. Out of scope here:
13463            // unique_ground_term only fires for a single agreeing cell.
13464            None
13465        }
13466    }
13467}
13468
13469fn identity_bind_if_safe(
13470    variable: &Variable,
13471    term: EncodedTerm,
13472    strings: Vec<(StrHash, String)>,
13473    equal_not_same_term: bool,
13474) -> Option<IdentityFold> {
13475    if equal_not_same_term && !sparql_equal_is_encoded_identity(&term) {
13476        return None;
13477    }
13478    Some(IdentityFold::Bind(IdentityEquality {
13479        variable: variable.clone(),
13480        term,
13481        strings,
13482    }))
13483}
13484
13485fn encoded_ground_expr(expr: &Expression) -> Option<(EncodedTerm, Vec<(StrHash, String)>)> {
13486    // Same one-entry-point rule as `path_end_strings`: mint through the
13487    // shared helper and keep the lexical half (payloads have no reader on
13488    // this path), so a ground geometry const carries its ORIGINAL lexical
13489    // under the geo key like every other seeded const.
13490    match expr {
13491        Expression::NamedNode(node) => {
13492            let (encoded, (strings, _payloads)) =
13493                crate::query::caches::mint_const_entries(&Term::NamedNode(node.clone()));
13494            Some((encoded, strings))
13495        }
13496        Expression::Literal(literal) => {
13497            let (encoded, (strings, _payloads)) =
13498                crate::query::caches::mint_const_entries(&Term::Literal(literal.clone()));
13499            Some((encoded, strings))
13500        }
13501        _ => None,
13502    }
13503}
13504
13505fn sparql_equal_is_encoded_identity(term: &EncodedTerm) -> bool {
13506    matches!(
13507        term,
13508        EncodedTerm::NamedNode { .. }
13509            | EncodedTerm::SmallStringLiteral(_)
13510            | EncodedTerm::BigStringLiteral { .. }
13511            | EncodedTerm::SmallSmallLangStringLiteral { .. }
13512            | EncodedTerm::SmallBigLangStringLiteral { .. }
13513            | EncodedTerm::BigSmallLangStringLiteral { .. }
13514            | EncodedTerm::BigBigLangStringLiteral { .. }
13515            | EncodedTerm::BooleanLiteral(_)
13516    )
13517}
13518
13519/// Outcome of pushing an identity term through a plan subtree (one walk).
13520///
13521/// `rewrote_scan` is the “did we prefix a Scan/Path?” fact (`||` over arms).
13522/// `producers_constrained` is the drop-FILTER fact: at least one producer of
13523/// `variable` exists, and every such producer emits `term` (`&&` over
13524/// producers; non-producers are ignored).
13525struct IdentityGrounding {
13526    /// True if a Scan/Path slot was prefixed (or already matched `term`).
13527    /// UNION/Join report this with `||` so a scan arm can be grounded even
13528    /// when a VALUES arm disagrees and the FILTER stays.
13529    #[allow(dead_code)]
13530    rewrote_scan: bool,
13531    producers_constrained: bool,
13532}
13533
13534/// Internal walk: vacuous nodes are not producers (`all_ok` stays true).
13535struct IdentityWalk {
13536    rewrote_scan: bool,
13537    saw_producer: bool,
13538    all_ok: bool,
13539}
13540
13541impl IdentityWalk {
13542    fn vacuous() -> Self {
13543        Self {
13544            rewrote_scan: false,
13545            saw_producer: false,
13546            all_ok: true,
13547        }
13548    }
13549
13550    fn producer(rewrote_scan: bool, constrained: bool) -> Self {
13551        Self {
13552            rewrote_scan,
13553            saw_producer: true,
13554            all_ok: constrained,
13555        }
13556    }
13557
13558    fn combine(self, other: Self) -> Self {
13559        Self {
13560            rewrote_scan: self.rewrote_scan || other.rewrote_scan,
13561            saw_producer: self.saw_producer || other.saw_producer,
13562            all_ok: self.all_ok && other.all_ok,
13563        }
13564    }
13565
13566    fn finish(self) -> IdentityGrounding {
13567        IdentityGrounding {
13568            rewrote_scan: self.rewrote_scan,
13569            producers_constrained: self.saw_producer && self.all_ok,
13570        }
13571    }
13572}
13573
13574/// Prefix Scan/Path slots with `term` and report whether every producer of
13575/// `variable` is constrained to that term (safe to drop an identity FILTER).
13576fn ground_identity_term(
13577    node: &mut PlanNode,
13578    variable: &Variable,
13579    term: &EncodedTerm,
13580    profile: Option<&StatsProfile>,
13581    strings: &[(StrHash, String)],
13582) -> IdentityGrounding {
13583    ground_identity_walk(node, variable, term, profile, strings).finish()
13584}
13585
13586fn ground_identity_walk(
13587    node: &mut PlanNode,
13588    variable: &Variable,
13589    term: &EncodedTerm,
13590    profile: Option<&StatsProfile>,
13591    strings: &[(StrHash, String)],
13592) -> IdentityWalk {
13593    match node {
13594        // A plugin op producing the variable IS a producer but cannot be
13595        // constrained to one term without running it — the identity FILTER
13596        // must stay (all_ok = false keeps it).
13597        PlanNode::CustomNode(op) => {
13598            if op.variables.contains(variable) {
13599                IdentityWalk::producer(false, false)
13600            } else {
13601                IdentityWalk::vacuous()
13602            }
13603        }
13604        PlanNode::Scan(scan) => {
13605            if scan.slot_of(variable).is_empty() && scan.graph.as_ref() != Some(variable) {
13606                return IdentityWalk::vacuous();
13607            }
13608            let ok = bind_scan_equality(scan, variable, term, profile);
13609            IdentityWalk::producer(ok, ok)
13610        }
13611        PlanNode::Path(path) => {
13612            if path.end_of(variable).is_none() && path.graph.as_ref() != Some(variable) {
13613                return IdentityWalk::vacuous();
13614            }
13615            let ok = bind_path_equality(path, variable, term, strings);
13616            IdentityWalk::producer(ok, ok)
13617        }
13618        PlanNode::Values(values) => {
13619            if !values.variables.contains(variable) {
13620                return IdentityWalk::vacuous();
13621            }
13622            let ok = values.unique_term(variable).as_ref() == Some(term);
13623            IdentityWalk::producer(false, ok)
13624        }
13625        PlanNode::Join { left, right, .. }
13626        | PlanNode::Union { left, right }
13627        | PlanNode::LeftJoin { left, right, .. } => {
13628            // `rewrote_scan` is `||` (prefix every scan/path). Producer
13629            // constraint is `&&`, but a child that does not produce `variable`
13630            // is vacuous and must not fail the AND.
13631            let a = ground_identity_walk(left, variable, term, profile, strings);
13632            let b = ground_identity_walk(right, variable, term, profile, strings);
13633            a.combine(b)
13634        }
13635        PlanNode::Extend {
13636            inner,
13637            variable: bound,
13638            expression,
13639            ..
13640        } => {
13641            let inner_walk = ground_identity_walk(inner, variable, term, profile, strings);
13642            if bound != variable {
13643                return inner_walk;
13644            }
13645            let expr_ok = extend_expression_is_term(inner, expression, term);
13646            IdentityWalk::producer(false, expr_ok).combine(inner_walk)
13647        }
13648        PlanNode::Filter { inner, exists, .. } => {
13649            // EXISTS bodies are not producers of the outer variable; apply
13650            // grounding as a side-effect of substitution without AND-ing
13651            // their producer constraint into the outer fold.
13652            for clause in exists {
13653                let _ = ground_identity_walk(&mut clause.body, variable, term, profile, strings);
13654            }
13655            ground_identity_walk(inner, variable, term, profile, strings)
13656        }
13657        PlanNode::Slice { inner, .. }
13658        | PlanNode::Distinct { inner, .. }
13659        | PlanNode::Sort { inner, .. }
13660        | PlanNode::Group { inner, .. }
13661        | PlanNode::JoinGraphVar { inner, .. } => {
13662            ground_identity_walk(inner, variable, term, profile, strings)
13663        }
13664        PlanNode::NamedGraphs {
13665            variable: bound, ..
13666        } => {
13667            if bound != variable {
13668                return IdentityWalk::vacuous();
13669            }
13670            IdentityWalk::producer(false, false)
13671        }
13672        // Produced columns of a count scan can never be locked to a term
13673        // from outside: the identity conjunct stays in the outer FILTER.
13674        PlanNode::DomainCounts { head, count, .. } => {
13675            if head == variable || count == variable {
13676                IdentityWalk::producer(false, false)
13677            } else {
13678                IdentityWalk::vacuous()
13679            }
13680        }
13681        PlanNode::HeadCounts {
13682            counted,
13683            group,
13684            count,
13685            ..
13686        } => {
13687            if counted == variable || group.as_ref() == Some(variable) || count == variable {
13688                IdentityWalk::producer(false, false)
13689            } else {
13690                IdentityWalk::vacuous()
13691            }
13692        }
13693        PlanNode::PatternCount {
13694            count,
13695            counted,
13696            subject,
13697            predicate,
13698            object,
13699            ..
13700        } => {
13701            let on_scan = [subject, predicate, object, counted]
13702                .into_iter()
13703                .flatten()
13704                .any(|v| v == variable);
13705            if count == variable || on_scan {
13706                IdentityWalk::producer(false, false)
13707            } else {
13708                IdentityWalk::vacuous()
13709            }
13710        }
13711        // Scope boundary: the subquery may produce `variable` (projected
13712        // names), but its producers can never be locked to `term` from
13713        // outside — the identity conjunct must stay in the outer FILTER.
13714        PlanNode::SubSelect(sub) => {
13715            if sub.variables.contains(variable) {
13716                IdentityWalk::producer(false, false)
13717            } else {
13718                IdentityWalk::vacuous()
13719            }
13720        }
13721        PlanNode::Unit | PlanNode::NamedGraphExists { .. } => IdentityWalk::vacuous(),
13722    }
13723}
13724
13725fn extend_expression_is_term(
13726    inner: &PlanNode,
13727    expression: &Expression,
13728    term: &EncodedTerm,
13729) -> bool {
13730    match expression {
13731        Expression::NamedNode(node) => EncodedTerm::from(node) == *term,
13732        Expression::Literal(literal) => crate::plugin::encode_user_literal(literal) == *term,
13733        Expression::Variable(source) => unique_ground_term(inner, source).as_ref() == Some(term),
13734        _ => false,
13735    }
13736}
13737
13738fn bind_scan_equality(
13739    scan: &mut ScanOp,
13740    variable: &Variable,
13741    term: &EncodedTerm,
13742    profile: Option<&StatsProfile>,
13743) -> bool {
13744    let mut hit = false;
13745    if scan.graph.as_ref() == Some(variable) {
13746        if !push_graph_terms(
13747            &mut scan.pattern.graph_name,
13748            &mut scan.graph_filter,
13749            std::slice::from_ref(term),
13750        ) {
13751            return false;
13752        }
13753        hit = true;
13754    }
13755    let slots = scan.slot_of(variable);
13756    if slots.is_empty() && !hit {
13757        return false;
13758    }
13759    for slot in slots {
13760        if let Some(existing) = pattern_slot_term(&scan.pattern, slot) {
13761            if existing != term {
13762                return false;
13763            }
13764            scan.record_grounded(variable, slot, profile);
13765            hit = true;
13766            continue;
13767        }
13768        scan.pattern = bind_pattern_slot(scan.pattern.clone(), slot, term);
13769        scan.record_grounded(variable, slot, profile);
13770        hit = true;
13771    }
13772    if hit {
13773        scan.produced_row_count_estimate = estimate_bound_scan(profile, &scan.pattern, 1);
13774    }
13775    hit
13776}
13777
13778fn bind_path_equality(
13779    path: &mut PathOp,
13780    variable: &Variable,
13781    term: &EncodedTerm,
13782    strings: &[(StrHash, String)],
13783) -> bool {
13784    let mut hit = false;
13785    if path.graph.as_ref() == Some(variable) {
13786        if !push_graph_terms(
13787            &mut path.graph_name,
13788            &mut path.graph_filter,
13789            std::slice::from_ref(term),
13790        ) {
13791            return false;
13792        }
13793        hit = true;
13794    }
13795    let Some(end) = path.end_of(variable) else {
13796        if hit {
13797            path.strings.extend(strings.iter().cloned());
13798            recost_path(path);
13799        }
13800        return hit;
13801    };
13802    if matches!(end, PathEnd::Start | PathEnd::Both) {
13803        if let Some(existing) = &path.subject_term {
13804            if existing != term {
13805                return false;
13806            }
13807            hit = true;
13808        } else {
13809            path.subject_term = Some(term.clone());
13810            hit = true;
13811        }
13812    }
13813    if matches!(end, PathEnd::End | PathEnd::Both) {
13814        if let Some(existing) = &path.object_term {
13815            if existing != term {
13816                return false;
13817            }
13818            hit = true;
13819        } else {
13820            path.object_term = Some(term.clone());
13821            hit = true;
13822        }
13823    }
13824    if hit {
13825        path.strings.extend(strings.iter().cloned());
13826        recost_path(path);
13827    }
13828    hit
13829}
13830
13831/// Intersect a sibling's `?g` domain into scans/paths that already carry a
13832/// graph constraint (`FROM NAMED`, `{DefaultGraph}` block-list, prior allow).
13833/// Runs on both join children so VALUES ⋈ GRAPH still composes when the
13834/// scan sits on the left (Hash/Shuffle).
13835fn compose_graph_from_sibling(
13836    source: &PlanNode,
13837    target: &mut PlanNode,
13838    hash_keys: &[Variable],
13839    profile: Option<&StatsProfile>,
13840    ground_unique: bool,
13841) {
13842    match target {
13843        PlanNode::Scan(scan) => {
13844            let Some(variable) = scan.graph.clone() else {
13845                return;
13846            };
13847            if !hash_keys.iter().any(|key| key == &variable) {
13848                return;
13849            }
13850            if ground_unique && let Some(term) = unique_ground_term(source, &variable) {
13851                let _ = push_graph_terms(
13852                    &mut scan.pattern.graph_name,
13853                    &mut scan.graph_filter,
13854                    std::slice::from_ref(&term),
13855                );
13856                scan.produced_row_count_estimate = estimate_bound_scan(profile, &scan.pattern, 1);
13857            } else if let Some(terms) = allow_list_from_node(source, &variable) {
13858                let _ = push_graph_terms(
13859                    &mut scan.pattern.graph_name,
13860                    &mut scan.graph_filter,
13861                    terms.as_ref(),
13862                );
13863                scan.produced_row_count_estimate =
13864                    join_key_domain_for_node(profile, source, &variable)
13865                        .unwrap_or_else(|| source.produced_row_count_estimate())
13866                        .max(1);
13867            }
13868        }
13869        PlanNode::Path(path) => {
13870            let Some(variable) = path.graph.clone() else {
13871                return;
13872            };
13873            if !hash_keys.iter().any(|key| key == &variable) {
13874                return;
13875            }
13876            if ground_unique
13877                && let Some((term, strings)) = unique_ground_with_strings(source, &variable)
13878            {
13879                let _ = bind_path_equality(path, &variable, &term, &strings);
13880            } else if let Some(terms) = allow_list_from_node(source, &variable) {
13881                let _ =
13882                    push_graph_terms(&mut path.graph_name, &mut path.graph_filter, terms.as_ref());
13883                path.produced_row_count_estimate =
13884                    join_key_domain_for_node(profile, source, &variable)
13885                        .unwrap_or_else(|| source.produced_row_count_estimate())
13886                        .max(1);
13887            }
13888        }
13889        PlanNode::Union { left: a, right: b }
13890        | PlanNode::Join {
13891            left: a, right: b, ..
13892        } => {
13893            compose_graph_from_sibling(source, a, hash_keys, profile, ground_unique);
13894            compose_graph_from_sibling(source, b, hash_keys, profile, ground_unique);
13895        }
13896        PlanNode::LeftJoin {
13897            left: nested_left,
13898            right: nested_right,
13899            ..
13900        } => {
13901            compose_graph_from_sibling(source, nested_left, hash_keys, profile, ground_unique);
13902            compose_graph_from_sibling(source, nested_right, hash_keys, profile, ground_unique);
13903        }
13904        PlanNode::Filter { inner, .. }
13905        | PlanNode::Extend { inner, .. }
13906        | PlanNode::Slice { inner, .. }
13907        | PlanNode::Distinct { inner, .. }
13908        | PlanNode::Sort { inner, .. }
13909        | PlanNode::Group { inner, .. }
13910        | PlanNode::JoinGraphVar { inner, .. } => {
13911            compose_graph_from_sibling(source, inner, hash_keys, profile, ground_unique);
13912        }
13913        _ => {}
13914    }
13915}
13916
13917/// Walk the right side of a bind-join (OPTIONAL, or inner Join after
13918/// Broadcast is chosen). For scans/paths that bind the join key: prefix a
13919/// unique left term into `pattern` (`grounded`) or annotate a runtime
13920/// allow-list (`broadcast`), and recost `produced_row_count_estimate`. CustomNodes that
13921/// bind the join key take the ground-unique driver's term as a `pinned`
13922/// binding (list drivers need no mark — runtime key delivery reaches them).
13923/// Only a one-column op becomes a point read: a multi-column op keeps its
13924/// row estimate, because the pin fixes one column while the others still
13925/// range.
13926/// Ground a Broadcast join's probe arm from a ground-unique driver and recost
13927/// the grounded scans/paths. Ground-only: the allow-list mark half of the old
13928/// `specialize_broadcast_probe` now lives in [`restamp_broadcast_marks`], the
13929/// sole writer of [`ScanOp::broadcasted`]; probe estimate clamping lives in
13930/// [`clamp_broadcast_probe_estimates`]. This function only bakes a known
13931/// single-term driver value into probe patterns — structural work that the
13932/// same-pass ground-conflict checks and ancestor costing consume. Every
13933/// hash key is considered, not just the first: grounding is
13934/// key-order-independent (ANY ground-unique driver key can bake its term
13935/// wherever the probe hosts it, and each bind re-prices for the next),
13936/// while the allow-list claim stays first-suitable — the sort order steers
13937/// delivery, grounding follows ground-uniqueness, and the two decisions no
13938/// longer share one key.
13939fn ground_and_recost_broadcasted_arm(
13940    left: &PlanNode,
13941    right: &mut PlanNode,
13942    hash_keys: &[Variable],
13943    profile: Option<&StatsProfile>,
13944) {
13945    match right {
13946        PlanNode::Scan(scan) => {
13947            for variable in hash_keys {
13948                if scan.graph.as_ref() == Some(variable)
13949                    && let Some(term) = unique_ground_term(left, variable)
13950                {
13951                    let _ = push_graph_terms(
13952                        &mut scan.pattern.graph_name,
13953                        &mut scan.graph_filter,
13954                        std::slice::from_ref(&term),
13955                    );
13956                    scan.produced_row_count_estimate =
13957                        estimate_bound_scan(profile, &scan.pattern, 1);
13958                }
13959                let slots = scan.slot_of(variable);
13960                if slots.is_empty() {
13961                    continue;
13962                }
13963                if let Some(term) = unique_ground_term(left, variable) {
13964                    for slot in slots {
13965                        scan.pattern = bind_pattern_slot(scan.pattern.clone(), slot, &term);
13966                        scan.record_grounded(variable, slot, profile);
13967                    }
13968                    scan.produced_row_count_estimate =
13969                        estimate_bound_scan(profile, &scan.pattern, 1);
13970                    // Grounding a slot changes the shape `annotate_liveness`
13971                    // proved the rewrite on. A grounded slot the RPC cannot see
13972                    // (bare head slots, DomainScan head/dead slots) would be
13973                    // silently dropped from the result, so the rewrite must go.
13974                    scan.domain_scan = None;
13975                    scan.head_scan = None;
13976                    // The pinned term is exact (prefix-enforced), so any IRI-only
13977                    // fact about the variable is now moot.
13978                    scan.iri_only.retain(|v| v != variable);
13979                }
13980            }
13981        }
13982        PlanNode::Path(path) => {
13983            for variable in hash_keys {
13984                if path.end_of(variable).is_none() && path.graph.as_ref() != Some(variable) {
13985                    continue;
13986                }
13987                if path.graph.as_ref() == Some(variable)
13988                    && let Some((term, strings)) = unique_ground_with_strings(left, variable)
13989                {
13990                    let _ = bind_path_equality(path, variable, &term, &strings);
13991                }
13992                if path.end_of(variable).is_none() {
13993                    continue;
13994                }
13995                if let Some((term, strings)) = unique_ground_with_strings(left, variable) {
13996                    let _ = bind_path_equality(path, variable, &term, &strings);
13997                }
13998            }
13999        }
14000        PlanNode::Union { left: a, right: b }
14001        | PlanNode::Join {
14002            left: a, right: b, ..
14003        } => {
14004            ground_and_recost_broadcasted_arm(left, a, hash_keys, profile);
14005            ground_and_recost_broadcasted_arm(left, b, hash_keys, profile);
14006        }
14007        PlanNode::LeftJoin {
14008            left: nested_left,
14009            right: nested_right,
14010            hash_keys: nested_keys,
14011            ..
14012        } => {
14013            ground_and_recost_broadcasted_arm(left, nested_left, hash_keys, profile);
14014            ground_and_recost_broadcasted_arm(nested_left, nested_right, nested_keys, profile);
14015        }
14016        PlanNode::CustomNode(op) => {
14017            for variable in hash_keys {
14018                // Only an op that binds the join key can take the driver's term,
14019                // and only when that key is not already pinned by an earlier
14020                // specialization pass.
14021                if !op.variables.contains(variable)
14022                    || op.pinned.iter().any(|(pinned, _)| pinned == variable)
14023                {
14024                    continue;
14025                }
14026                if let Some(term) = unique_ground_term(left, variable) {
14027                    // Generic emulation of the Scan grounding above: pin the
14028                    // driver's single term into the op — the executor relates
14029                    // exactly it instead of sweeping. Non-ground (list) drivers
14030                    // need no mark: runtime key delivery reaches the op through
14031                    // the join's pushed-values path.
14032                    op.pinned.push((variable.clone(), term));
14033                    // A ONE-COLUMN op that binds the join key becomes a point:
14034                    // the pinned term is its only output value. A multi-column
14035                    // op (the text subject resolve carrying its graph column)
14036                    // still emits one row per remaining output value — pinning
14037                    // the graph does not make a subject window a point read —
14038                    // so its row estimate must survive. Pricing it at 1 would
14039                    // make every join above it a one-row arm, and the cost model can
14040                    // then re-orient around a phantom point read.
14041                    if op.variables.len() == 1 {
14042                        op.produced_row_count_estimate = 1;
14043                    }
14044                }
14045            }
14046        }
14047        PlanNode::Extend { inner, .. }
14048        | PlanNode::Filter { inner, .. }
14049        | PlanNode::Slice { inner, .. }
14050        | PlanNode::Distinct { inner, .. }
14051        | PlanNode::Sort { inner, .. }
14052        | PlanNode::Group { inner, .. }
14053        | PlanNode::JoinGraphVar { inner, .. } => {
14054            ground_and_recost_broadcasted_arm(left, inner, hash_keys, profile);
14055        }
14056        _ => {}
14057    }
14058}
14059
14060/// Re-derive `ScanOp::broadcasted` marks for a settled tree: the **sole
14061/// writer** of those marks (the sole remover is the swap-time
14062/// `clear_broadcast_marks` inside `refinalize_joins`).
14063///
14064/// Pre-order (outermost join first): at every inner join whose strategy is
14065/// Broadcast with non-empty keys, claim the right subtree's unmarked scans
14066/// hosting the first hash key — stamp `(variable, slot)` and clamp the
14067/// estimate to the driver's key domain (monotone `min`, never raises; point
14068/// lookups are exempt, their price is already exact). A claim is skipped when
14069/// the scan already carries a mark: pre-order guarantees an existing mark can
14070/// only be an outer join's claim, which matches runtime key-delivery
14071/// precedence (`PushedKeyVals` entries are ordered outer-first and
14072/// `merge_broadcast_filters` prefers the ancestor). OPTIONAL right sides are
14073/// claimed with the LeftJoin's own keys, mirroring runtime per-page probing.
14074///
14075/// Claim descent never crosses a [`PlanNode::SubSelect`] boundary — outer
14076/// join keys do not — but the walk descends into subquery bodies so their own
14077/// Broadcast joins are claimed within their scope.
14078///
14079/// Runs immediately after every structural pass that can move arms
14080/// (construction + identity fold, each `refinalize_joins` pass) and is always
14081/// paired with `annotate_liveness` right after: liveness re-derives the
14082/// rewrite stamps (`domain_scan` / `domain_counts` / head scans) from the
14083/// settled marks, so those stamps are invalid between the two calls. No
14084/// threshold gate: the strategy pick already consumed the domain evidence on
14085/// the same arms, and runtime (`join_keys_scan_filter`) is the real arbiter
14086/// of delivered list size.
14087fn restamp_broadcast_marks(node: &mut PlanNode, profile: Option<&StatsProfile>) {
14088    match node {
14089        PlanNode::Join {
14090            left,
14091            right,
14092            hash_keys,
14093            probe_key_domains: _,
14094            probe_key_overlap_milli: _,
14095            rhs_hostable_keys: _,
14096            meta,
14097        } => {
14098            if meta.strategy == JoinStrategy::Broadcast && !hash_keys.is_empty() {
14099                claim_broadcast_probe(left, right, hash_keys, profile);
14100            }
14101            restamp_broadcast_marks(left, profile);
14102            restamp_broadcast_marks(right, profile);
14103        }
14104        PlanNode::LeftJoin {
14105            left,
14106            right,
14107            hash_keys,
14108            ..
14109        } => {
14110            claim_broadcast_probe(left, right, hash_keys, profile);
14111            restamp_broadcast_marks(left, profile);
14112            restamp_broadcast_marks(right, profile);
14113        }
14114        PlanNode::Union { left, right } => {
14115            restamp_broadcast_marks(left, profile);
14116            restamp_broadcast_marks(right, profile);
14117        }
14118        PlanNode::CustomNode(op) => {
14119            for child in &mut op.children {
14120                restamp_broadcast_marks(child, profile);
14121            }
14122        }
14123        PlanNode::Filter { inner, exists, .. } => {
14124            restamp_broadcast_marks(inner, profile);
14125            for clause in exists {
14126                restamp_broadcast_marks(&mut clause.body, profile);
14127            }
14128        }
14129        PlanNode::Extend { inner, .. }
14130        | PlanNode::Slice { inner, .. }
14131        | PlanNode::Distinct { inner, .. }
14132        | PlanNode::Sort { inner, .. }
14133        | PlanNode::Group { inner, .. }
14134        | PlanNode::JoinGraphVar { inner, .. } => {
14135            restamp_broadcast_marks(inner, profile);
14136        }
14137        // The subquery boundary is opaque to outer claims (descent above
14138        // never crosses it), but its own Broadcast joins are claimed in scope.
14139        PlanNode::SubSelect(sub) => restamp_broadcast_marks(&mut sub.inner, profile),
14140        _ => {}
14141    }
14142}
14143
14144/// Claim walk under one join's right arm: stamp `(variable, slots[0])` on
14145/// every unmarked scan hosting `hash_keys.first()`. First claim wins — see
14146/// [`restamp_broadcast_marks`] for the pre-order guarantee.
14147fn claim_broadcast_probe(
14148    left: &PlanNode,
14149    right: &mut PlanNode,
14150    hash_keys: &[Variable],
14151    profile: Option<&StatsProfile>,
14152) {
14153    match right {
14154        PlanNode::Scan(scan) => {
14155            let Some(variable) = hash_keys.first() else {
14156                return;
14157            };
14158            // Claim-skip: an existing mark is an outer join's claim.
14159            if scan.broadcasted.is_some() {
14160                return;
14161            }
14162            // Grounding supersedes marking: a ground-unique driver already
14163            // baked its term into the pattern, so a delivered allow-list for
14164            // this variable would be a no-op.
14165            if scan.grounded.iter().any(|(v, _)| v == variable) {
14166                return;
14167            }
14168            let slots = scan.slot_of(variable);
14169            if slots.is_empty() {
14170                return;
14171            }
14172            if pattern_is_point_lookup(&scan.pattern) {
14173                return;
14174            }
14175            // The pushed list carries at most min(domain, driver rows)
14176            // distinct values — the dom ≤ rows hygiene every list-size
14177            // consumer shares (`pushed_val_count`).
14178            let estimated_pushed_val_count = pushed_val_count(profile, left, variable);
14179            scan.broadcasted = Some((variable.clone(), slots[0]));
14180            let price = estimate_unclamped_scan_rows(profile, scan);
14181            let bound = pushed_scan_return_bound(
14182                estimated_pushed_val_count,
14183                price,
14184                scan,
14185                variable,
14186                profile,
14187            );
14188            scan.produced_row_count_estimate = scan.produced_row_count_estimate.min(bound);
14189            // Mark and bound land as a PAIR here too — the same push-return
14190            // bound `clamp_broadcast_probe_estimates` writes. A freshly
14191            // re-claimed scan (a swap cleared the pair mid-round; the
14192            // boundary restamp claims it again) carries its bound
14193            // immediately, so `ancestor_push_return_bound`'s "lifetime is
14194            // exactly the mark's" holds at every point a mark exists.
14195            scan.ancestor_push_return_bound = Some(bound);
14196        }
14197        PlanNode::Union { left: a, right: b }
14198        | PlanNode::Join {
14199            left: a, right: b, ..
14200        } => {
14201            claim_broadcast_probe(left, a, hash_keys, profile);
14202            claim_broadcast_probe(left, b, hash_keys, profile);
14203        }
14204        PlanNode::LeftJoin {
14205            left: nested_left,
14206            right: nested_right,
14207            hash_keys: nested_keys,
14208            ..
14209        } => {
14210            claim_broadcast_probe(left, nested_left, hash_keys, profile);
14211            claim_broadcast_probe(nested_left, nested_right, nested_keys, profile);
14212        }
14213        PlanNode::Extend { inner, .. }
14214        | PlanNode::Filter { inner, .. }
14215        | PlanNode::Slice { inner, .. }
14216        | PlanNode::Distinct { inner, .. }
14217        | PlanNode::Sort { inner, .. }
14218        | PlanNode::Group { inner, .. }
14219        | PlanNode::JoinGraphVar { inner, .. } => {
14220            claim_broadcast_probe(left, inner, hash_keys, profile);
14221        }
14222        // Values / Path / Unit / NamedGraphs / NamedGraphExists /
14223        // DomainCounts / HeadCounts host no claimable scan; CustomNode is an
14224        // opaque leaf for claims (its children belong to the plugin's scope).
14225        _ => {}
14226    }
14227}
14228
14229/// Plan-time writer of `ScanOp::fetch_once` stamps: the
14230/// sole writer, run once after the LAST seating round — the orientation
14231/// this pass sees is the orientation the executor runs. For every inner
14232/// join whose right arm is a bare Scan, it prices the probe arm with the
14233/// SAME gather ([`seat_probe_shape`]) and the SAME price
14234/// ([`probe_broadcast_price`]) the seating comparator used, asks the SAME
14235/// predicate ([`fetch_once_verdict_now`]) the comparator's fetch-once road
14236/// asked, and stamps when it says `Build` — one predicate, two consumers.
14237/// The arithmetic cannot diverge; the INPUTS can by moment (the
14238/// comparator prices during the seating rounds, this pass runs after the
14239/// final `annotate_liveness`), and this pass's verdict is the one the
14240/// runtime honors.
14241///
14242/// Residency is not this pass's decision: a stamped arm the executor
14243/// finds over the query memory budget joins through cached Grace
14244/// partitions (`BuiltProbeArm::right_parts`), so a FetchOnce verdict always writes
14245/// and the RAM opinion lives in one place — `join_should_spill`'s
14246/// byte comparison.
14247///
14248/// Exclusions, each an executor capability, not a shape opinion (the
14249/// predicate itself is a pure price — no shape rules):
14250/// - OPTIONAL right arms: `execute_left_join` has no built slot yet
14251///   (Phase 2b);
14252/// - joins with no hash key hosted on a shippable slot of the right scan
14253///   (`first_slot_of` covers S/P/O; a graph-position key broadcasts no list —
14254///   reachable with a Values or geo_scan driver, whose `?g` domains are
14255///   sketch-known): the arm probes unfiltered regardless, so the stamp
14256///   could only suppress memoization and spend budget. Point-lookup arms
14257///   (all four slots ground) carry no variables at all and never reach
14258///   pricing — no shared variable, no hash key.
14259/// - non-Scan right arms (subtrees, paths): the stamped executor branch
14260///   exists only for `right.as_scan()`. A subtree probe keeps the
14261///   coverage/`Ancestor` machinery.
14262///
14263/// A stamped arm skips `merged_scan_filter` at runtime — it never enters
14264/// `join_keys_scan_filter`, skips the coverage machinery, and creates no
14265/// memo entries. Rows are identical either way (the whole read is a
14266/// superset of any page's filtered read; the join keys drop the rest).
14267///
14268/// `sliced` (the query's root is a Slice) suppresses the verdict's
14269/// fetch-concurrency divisor entirely: the slice cursor runs every join
14270/// per-page — the slice star through its own demand-priced `detect` — so
14271/// no batch fetch concurrency exists to price and every arm prices
14272/// sequentially. The star-arm stamp still writes for EXPLAIN and for
14273/// eagerly-drained subtrees beneath the Slice (an `EXISTS` body promoted
14274/// to the hash semijoin keeps the eager road and its assert), but no
14275/// divisor follows it on the slice path.
14276fn restamp_fetch_once(
14277    node: &mut PlanNode,
14278    profile: Option<&StatsProfile>,
14279    ctx: Option<&crate::context::QueryContext>,
14280    sliced: bool,
14281) {
14282    clear_fetch_once_marks(node);
14283    stamp_fetch_once(node, profile, ctx, None, None, sliced);
14284}
14285
14286/// Stamp each star-spine HEAD join with its arm count
14287/// ([`JoinMeta::star_arms`]).
14288///
14289/// The derivation IS the executor's own `concurrent_star::detect`, called
14290/// with the eager path's parameters (`slice_path = false`,
14291/// `eager_star_page_rows()`): one definition, two consumers, so the stamp
14292/// and the executor cannot drift apart by construction. Every input
14293/// `detect` reads on the eager path — tree shape, `hash_keys`, the
14294/// plan-stamped `probe_key_domains`, `meta.strategy`, the scan estimates —
14295/// is a field of this tree, settled before this pass runs (see the
14296/// pipeline position below). The slice path is deliberately NOT stamped:
14297/// its viability gate prices demand-bounded pages, which plan time cannot
14298/// reproduce, so an OpenNode star may run without a stamp (and the
14299/// executor-side agreement assert lives on the eager call site only).
14300///
14301/// Pipeline position: immediately BEFORE [`restamp_fetch_once`], both
14302/// after the LAST seating round AND after the root wraps (Distinct /
14303/// Sort / Slice — the wraps add only nodes above the root, and the Slice
14304/// wrap's small-slice broadcast flip lands before pricing, so both
14305/// passes price the final tree; beneath a Slice `restamp_fetch_once`
14306/// suppresses the divisor). The verdict's fetch-concurrency divisor
14307/// consumes this stamp, so the stamp must describe the tree the price
14308/// runs on (stamp/price coherence). Nothing structural follows either
14309/// pass, so the stamp cannot go stale and needs no clear pass.
14310///
14311/// Readers: EXPLAIN (the star rendering) and the fetch-once verdict's
14312/// fetch-concurrency input (the batch credit, through
14313/// `probe_seek_concurrency_milli`). Nothing structural consumes it:
14314/// seating and swaps run strictly earlier.
14315pub(crate) fn stamp_star_join_shapes(node: &mut PlanNode) {
14316    if let PlanNode::Join {
14317        left,
14318        right,
14319        hash_keys,
14320        probe_key_domains,
14321        probe_key_overlap_milli,
14322        rhs_hostable_keys: _,
14323        meta,
14324    } = node
14325    {
14326        // Same predicate, same eager parameters as the executor's eager
14327        // `detect` call (join_chunks' JoinChunkSource::new): agreement is
14328        // structural, and the executor debug-asserts it. The result borrows
14329        // `left`/`right` immutably; extract the owned arm count before the
14330        // mutable recursion below.
14331        let arms = crate::concurrent_star::detect(
14332            left,
14333            right,
14334            hash_keys,
14335            probe_key_domains,
14336            probe_key_overlap_milli,
14337            meta.strategy,
14338            false,
14339            crate::concurrent_star::eager_star_page_rows(),
14340        )
14341        .map(|star| star.probes.len() as u8);
14342        meta.star_arms = arms;
14343        stamp_star_join_shapes(left);
14344        stamp_star_join_shapes(right);
14345        return;
14346    }
14347    // Non-join nodes and LeftJoin subtrees: recurse the same shapes
14348    // `clear_fetch_once_marks` walks, so a star nested under a
14349    // Filter/Extend/Union/etc. still stamps. A LeftJoin's own arms never
14350    // form an eager star (detect matches PlanNode::Join spines only), but
14351    // its subtree may contain plain joins that do.
14352    match node {
14353        PlanNode::Join { .. } => unreachable!("handled above"),
14354        PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
14355            stamp_star_join_shapes(left);
14356            stamp_star_join_shapes(right);
14357        }
14358        PlanNode::CustomNode(op) => {
14359            for child in &mut op.children {
14360                stamp_star_join_shapes(child);
14361            }
14362        }
14363        PlanNode::Filter { inner, exists, .. } => {
14364            stamp_star_join_shapes(inner);
14365            for clause in exists {
14366                stamp_star_join_shapes(&mut clause.body);
14367            }
14368        }
14369        PlanNode::Extend { inner, .. }
14370        | PlanNode::Slice { inner, .. }
14371        | PlanNode::Distinct { inner, .. }
14372        | PlanNode::Sort { inner, .. }
14373        | PlanNode::Group { inner, .. }
14374        | PlanNode::JoinGraphVar { inner, .. } => stamp_star_join_shapes(inner),
14375        PlanNode::SubSelect(sub) => stamp_star_join_shapes(&mut sub.inner),
14376        _ => {}
14377    }
14378}
14379
14380/// A keyed ancestor's per-page push, carried down [`stamp_fetch_once`]'s
14381/// recursion into a subtree probe arm so contained joins price their
14382/// drivers at push-conditioned geometry.
14383///
14384/// Born when the walk crosses a keyed join whose probe arm is a SUBTREE
14385/// (not a bare scan) executing on the per-page keyed road: at runtime
14386/// that subtree re-executes once per driver page, every scan inside
14387/// hosting the pushed key answers keyed, and every join inside sees a
14388/// driver of roughly the keyed answer — never the standalone multi-page
14389/// stream the local estimates describe. The OUTERMOST keyed subtree
14390/// probe wins (one context, not a stack): an inner keyed join's own push
14391/// is already bounded by the outer push's per-page return, and a single
14392/// context keeps the conditioning conservative and explainable.
14393///
14394/// `pushed_val_count` is the length of ONE page's pushed list — the ancestor
14395/// page's row bound, clamped by the establishing driver's key domain when
14396/// that domain is known. It is deliberately NOT any node's row count:
14397/// contained joins derive their own driver bounds from it against their
14398/// OWN driver facts ([`containing_push_driver_bound`]). The pre-fix bound
14399/// was the ancestor subtree's OUTPUT, and inner joins only reduce — the
14400/// output systematically understates every intermediate driver, so a
14401/// selective join late in the subtree understated the real keyed return
14402/// by orders of magnitude and un-stamped arms into per-page drains.
14403/// Hosting on the right (probe)
14404/// side conditions nothing here: the push keys that arm's fetches, not
14405/// this join's driver — only a contained join whose DRIVER hosts `key`
14406/// re-geometries (the `probe_scan_has_key(left, key)` gate).
14407#[derive(Clone, Debug)]
14408struct ContainingPush {
14409    key: Variable,
14410    pushed_val_count: u64,
14411}
14412
14413/// The push-bound BASIS: the driver's UNCAPPED whole read. A push bound
14414/// derives from the operand's OWN intrinsic facts, never from a cell
14415/// already conditioned by another push — a foreign-claimed scan's cell
14416/// (an ancestor's push; the claimer-gate rule) is THAT push's answer, and
14417/// dividing it by the full key domain again double-discounts it (the
14418/// transects defect: a claimed 514-row geometry cell over an 817,201-key
14419/// domain priced a 500-key containing push at 1 row — the dishonest
14420/// 9-row walk price that masked the driver-side blind spot). The same
14421/// idempotence rule the claim stamps follow (`pushed_scan_return_bound`
14422/// takes `estimate_unclamped_scan_rows` explicitly as its price). The
14423/// the cost model's own row basis keeps `driver_whole_read_rows` — there the
14424/// foreign-claim cell IS the bounded whole read (the ancestor push holds
14425/// in every seating); only the DERIVATION changes basis here.
14426/// Profile-gated like every protection: without a profile there is no
14427/// catalog recompute and the cell stands.
14428/// The push-bound BASIS for a driver subtree: the read whose rows-per-key
14429/// the pushed list scales, composed from every arm of the subtree. A
14430/// claim mark makes a scan's cell ANOTHER push's answer — the intrinsic
14431/// read replaces it here exactly as it does for a bare-scan driver
14432/// (unmarked: the cell IS the whole read). A Join's output pairs every
14433/// left row with right rows, so the arms' reads MULTIPLY (saturating) —
14434/// the SUM this replaced was smaller than ONE key's output, because
14435/// rows-per-key multiply across the arms: a 1,000-row arm and a 500-row
14436/// arm over a 10-key domain emit ~5,000 rows per key, and the sum priced
14437/// 1,500 in total — so the caller's `min` adopted the short bound and
14438/// threw away the honest join cell. A Union's arms BOTH run: their reads
14439/// sum. Containers descend. Opaque leaves (customs, paths, catalog
14440/// nodes, SubSelect) contribute their produced estimate — unpushed
14441/// by the claim machinery, so no double-discount rides on it, and their
14442/// rows multiply a join's output exactly as a scan's rows do. Every
14443/// factor is a real estimate, so there is no stand-down and no invented
14444/// number; an astronomic product simply degrades to the caller's
14445/// standalone `min`.
14446fn containing_push_basis(driver: &PlanNode, profile: Option<&StatsProfile>) -> u64 {
14447    match driver {
14448        PlanNode::Scan(scan) => match &scan.broadcasted {
14449            Some(_) => estimate_unclamped_scan_rows(profile, scan),
14450            None => scan.produced_row_count_estimate,
14451        },
14452        PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
14453            containing_push_basis(left, profile)
14454                .saturating_mul(containing_push_basis(right, profile))
14455        }
14456        PlanNode::Union { left, right } => containing_push_basis(left, profile)
14457            .saturating_add(containing_push_basis(right, profile)),
14458        PlanNode::Filter { inner, .. }
14459        | PlanNode::Extend { inner, .. }
14460        | PlanNode::Slice { inner, .. }
14461        | PlanNode::Distinct { inner, .. }
14462        | PlanNode::Sort { inner, .. }
14463        | PlanNode::Group { inner, .. }
14464        | PlanNode::JoinGraphVar { inner, .. } => containing_push_basis(inner, profile),
14465        _ => driver.produced_row_count_estimate(),
14466    }
14467}
14468
14469/// The containing-push bound for ONE contained join, derived from the
14470/// contained driver's OWN facts: the driver's rows distribute
14471/// over its key domain, one ancestor page pushes `pushed_val_count` distinct
14472/// values, so the keyed answer per page is `pushed_val_count × rows-per-key`.
14473/// Sydney's shape reproduces exactly (8M rows / 8M domain = 1 row per key
14474/// × 24,576 = the benched `push_bound=24576`); the counterexample — a
14475/// selective join late in the subtree collapsing the OUTPUT to tens of
14476/// thousands while the driver's keyed return runs ~2M per page — now
14477/// prices ~2M instead of the output's ~24K. The arithmetic is the SAME
14478/// core the claim stamps use (`pushed_return_bound_core`): the total
14479/// product rounded UP once (never zero, never understating, error under
14480/// one row total), containment-bounded by the basis — so the hypothesis
14481/// the comparator prices and the stamp the claim machinery writes agree
14482/// by construction. Unknown driver key domain →
14483/// `None`: the standalone geometry stands, no invented number (the
14484/// caller `min`s against it, so the bound can only lower). The BASIS is
14485/// the driver subtree's composed read (`containing_push_basis`): scans
14486/// contribute their intrinsic reads, Join arms multiply, Union arms sum —
14487/// a foreign-claimed cell is ANOTHER push's answer and never feeds back
14488/// as a derivation basis — the idempotence rule the stamps follow with
14489/// their explicit unclamped price.
14490fn containing_push_driver_bound(
14491    profile: Option<&StatsProfile>,
14492    driver: &PlanNode,
14493    pushed_key: &Variable,
14494    pushed_val_count: u64,
14495) -> Option<u64> {
14496    let domain = join_key_domain_for_node(profile, driver, pushed_key);
14497    let basis = containing_push_basis(driver, profile);
14498    pushed_return_bound_core(pushed_val_count, basis, domain)
14499}
14500
14501/// The containing-push context ONE join's keyed road establishes for its
14502/// subtree probe arm: the runtime's own broadcast key (the gather's
14503/// reorder-order survivor) plus the per-page pushed value count.
14504/// Shared by the stamp walk (`stamp_fetch_once`) and the comparator's
14505/// leaf-walk branch (`seat_cost_total`) so the conditioned STAMP and the
14506/// conditioned PRICE cannot drift — the same "one gather, one price, two
14507/// consumers" rule as `seat_probe_shape`. `None` on the once-roads (zero
14508/// pages; every key a covered, droppable push — the subtree executes
14509/// exactly once and prices standalone) and when the survivor key's page
14510/// list would be empty.
14511fn child_push_from_shape(
14512    profile: Option<&StatsProfile>,
14513    driver: &PlanNode,
14514    probe: &PlanNode,
14515    ctx: Option<&crate::context::QueryContext>,
14516    shape: &SeatProbeShape,
14517) -> Option<ContainingPush> {
14518    if shape.pages == 0
14519        || (shape.coverage_drop_allowed && shape.keys.iter().all(|(covered, _, _, _)| *covered))
14520    {
14521        return None;
14522    }
14523    let key = shape.broadcast_key.clone()?;
14524    // The per-page pushed value count: the runtime pushes
14525    // one key list per driver page, so a page carries at most the page's
14526    // row bound and at most the establishing driver's whole key domain.
14527    // Contained drivers derive their own bounds from this — the subtree's
14528    // OUTPUT prices nobody's driver (inner joins only reduce; the pre-fix
14529    // bound read it here).
14530    let page_rows = seat_page_rows(driver, probe, ctx);
14531    // The per-page list is the pusher's REALISTIC value count —
14532    // min(domain, the pusher's OWN rows, page rows) — the same
14533    // `pushed_val_count` derivation the claim stamps use. The pusher's
14534    // row bound is the transects lesson: a 500-row driver pushes at most
14535    // 500 keys per page, never a page-sized 24,576-key list, and a bound
14536    // derived from a page-sized list overstates everything downstream of
14537    // it by the rows/page ratio.
14538    let pushed_val_count = pushed_val_count(profile, driver, &key).min(page_rows);
14539    (pushed_val_count > 0).then_some(ContainingPush {
14540        key,
14541        pushed_val_count,
14542    })
14543}
14544
14545/// Depth-first stamp walk under one node. Recurses through every container
14546/// (Union arms, FILTER/BIND wrappers, SubSelect bodies; CustomNode children
14547/// belong to the plugin's scope and are left alone).
14548///
14549/// The walk carries `containing`: inside a keyed subtree probe arm,
14550/// contained joins price their drivers at the ancestor push's per-page
14551/// geometry (`ContainingPush`) — the fix for the stale standalone stamp
14552/// (a subtree re-executes per driver page, so a contained join's driver
14553/// is the keyed answer, not the standalone stream; priced standalone, a
14554/// many-page driver verdict stamps a Build whose whole read then repeats
14555/// per execution). The context crosses exactly the containers
14556/// `probe_scan_has_key` walks — the modeled push-reachability topology —
14557/// and stops at its boundaries (SubSelect, EXISTS bodies, plugin
14558/// children): what the runtime cannot push into must price standalone.
14559/// A LeftJoin is crossed: push-transparent at
14560/// runtime — the ancestor's stack reaches both arms — so both price
14561/// conditioned beneath an inherited context.
14562fn stamp_fetch_once(
14563    node: &mut PlanNode,
14564    profile: Option<&StatsProfile>,
14565    ctx: Option<&crate::context::QueryContext>,
14566    containing: Option<&ContainingPush>,
14567    star_ctx: Option<u8>,
14568    sliced: bool,
14569) {
14570    match node {
14571        PlanNode::Join {
14572            left,
14573            right,
14574            hash_keys,
14575            meta,
14576            ..
14577        } => {
14578            // Parallel-probe-road membership for this join's probe arm,
14579            // feeding the verdict's fetch-concurrency divisor — MEMBERSHIP
14580            // only: every batched arm prices the engine's fetch concurrency, so the
14581            // arm-count value itself no longer divides anything (the
14582            // count still travels for diagnostics). Two
14583            // sources: (1) star spines — the head's own `star_arms` stamp,
14584            // or the context inherited down the left spine (spine members
14585            // carry no stamp of their own; detect admits only at the
14586            // head); (2) single-arm (non-star) joins the executor will batch
14587            // on the eager path — the shared eligibility predicate (a scan
14588            // right hosting a broadcast-slot key), not under a Slice (the slice
14589            // cursor keeps the per-page road). `None` everywhere else
14590            // keeps the sequential price.
14591            //
14592            // The engine-off state (a configured fetch concurrency below 2) suppresses
14593            // BOTH sources, mirroring `fill_parallel_probe`'s entry gate:
14594            // with the engine off no arm batches, so no arm may price
14595            // batch fetch concurrency — every arm prices sequentially,
14596            // matching the per-page roads the executor runs.
14597            let engine_on = crate::context::parallel_probe_engine_enabled();
14598            let star_arms = if engine_on {
14599                meta.star_arms.or(star_ctx)
14600            } else {
14601                None
14602            };
14603            let batchable = engine_on
14604                && !sliced
14605                && crate::query::parallel_probe::scan_hosts_broadcast_key(right, hash_keys);
14606            // Beneath a Slice the cursor runs every join per-page (the
14607            // slice star through its own demand-priced `detect`), so NO
14608            // batch fetch concurrency exists to price: the divisor is
14609            // suppressed entirely and every arm prices sequentially. A
14610            // star head's `star_arms` stamp describes the eager road and
14611            // must not leak a divisor onto the slice path.
14612            let batch_arms = if sliced {
14613                None
14614            } else if batchable {
14615                star_arms.or(Some(1))
14616            } else {
14617                star_arms
14618            };
14619            // Push-conditioned driver bound: inside a containing push, a
14620            // join whose DRIVER hosts the pushed key executes once per
14621            // ancestor page against the keyed answer, so the standalone
14622            // driver geometry below (an 8M-row stream over hundreds of
14623            // pages) prices an execution that never happens. The bound is
14624            // DERIVED from the contained driver's own facts — pushed_val_count ×
14625            // (driver rows / driver key domain), rounded up — because the
14626            // ancestor subtree's OUTPUT, the pre-fix bound, understates
14627            // every intermediate: inner joins only reduce. The gather
14628            // `min`s it against the
14629            // standalone basis, so it can only shrink; an unknown driver
14630            // key domain keeps the standalone geometry (no invented
14631            // number).
14632            let driver_bound = containing
14633                .filter(|push| probe_scan_has_key(left, &push.key))
14634                .and_then(|push| {
14635                    containing_push_driver_bound(profile, left, &push.key, push.pushed_val_count)
14636                });
14637            if !hash_keys.is_empty()
14638                && let Some(scan) = right.as_scan()
14639                && fetch_once_stampable(scan)
14640                // Executor-capability guard: a stamp
14641                // the runtime can never consume must not be written NOR
14642                // charged — pre-order grants mean an inert stamp here
14643                // displaces a real one later. The runtime broadcasts a key list
14644                // only to a Subject/Predicate/Object slot
14645                // (`first_slot_of`); a join keyed solely on a position the
14646                // scan cannot broadcast (a graph-position key — reachable when
14647                // the driver is a Values row set or a geo_scan CustomNode,
14648                // whose `?g` domains are sketch-known) probes unfiltered
14649                // regardless, so the stamp could only suppress
14650                // memoization and spend budget. Point-lookup arms (all
14651                // four slots ground) carry no variables at all and never
14652                // reach pricing: no shared variable, no hash key.
14653                && hash_keys
14654                    .iter()
14655                    .any(|key| scan.first_slot_of(key).is_some())
14656            {
14657                // ONE basis for the whole priced comparison: the arm's
14658                // UNCLAMPED whole-read estimate — what one whole read of
14659                // the arm returns, and the base the per-page matched
14660                // fraction scales. c9d5149's canary established the
14661                // unclamped number as the honest drain basis for grounded
14662                // arms (the clamp was the lie: a 686-row clamp on a
14663                // 7,659-row drain); the matched term follows the same
14664                // basis, so this pass's inputs match the seating rounds'
14665                // pass-top inputs and the two consumers cannot disagree
14666                // about the arm's size. The clamped produced estimate is
14667                // kept for the log line only.
14668                let produced = scan.produced_row_count_estimate;
14669                let whole_read_rows = estimate_unclamped_scan_rows(profile, scan);
14670                let shape = seat_probe_shape(profile, left, right, hash_keys, ctx, driver_bound);
14671                // All-dropped shape: every hash key is a covered push and
14672                // the amortization guard granted the drop, so the coverage
14673                // rule broadcasts no filter and the runtime executes this
14674                // arm ONCE — the first fill feeds the built slot, every
14675                // later batch reuses it. The cost model's coverage road prices
14676                // exactly that (one whole read). `probe_broadcast_price`'s
14677                // per-page contract cannot express "once total, not once
14678                // per page": priced through it, the verdict sees
14679                // pages × whole reads and stamps FetchOnce — for a road the
14680                // runtime cannot take, suppressing the scan memo for zero
14681                // gain. Decline without pricing (the #5(a) pattern: a
14682                // degenerate comparison must not run, and a stamp that
14683                // changes no read must not be written). keys
14684                // holds one entry per hash key (seat_probe_shape pushes
14685                // per key, and the outer guard requires a shippable key),
14686                // so `all` on it is never vacuously true here.
14687                if shape.coverage_drop_allowed
14688                    && shape.keys.iter().all(|(covered, _, _, _)| *covered)
14689                {
14690                    if let Some(ctx) = ctx {
14691                        ctx.log(
14692                            crate::LogLevel::Debug,
14693                            &format!(
14694                                "fetch-once-stamp: {} pages={} produced(clamped)={} whole_read_rows={} -> skipped (all-dropped probe: the probe executes once via the built slot; no build decision)",
14695                                crate::explain::scan_pattern_tag(scan),
14696                                shape.pages,
14697                                produced,
14698                                whole_read_rows
14699                            ),
14700                        );
14701                    }
14702                } else {
14703                    // The receiving-scan road, SHARED with the cost model
14704                    // (review MAJOR: stamp/seat coherence): when the
14705                    // executor's filter merge keeps the ancestor filter
14706                    // on this arm, the per-page verdict inputs are the
14707                    // pushed road's — the same substitution
14708                    // `seat_cost_total` prices — so the stamp and the
14709                    // cost model can never split on which road runs. No
14710                    // containing push (or a same-slot interior win)
14711                    // keeps the interior-keyed pair, as before.
14712                    let mirror_road = probe_side_mirror_road(
14713                        profile,
14714                        right,
14715                        hash_keys,
14716                        &shape.keys,
14717                        shape.coverage_drop_allowed,
14718                        containing,
14719                    );
14720                    let (seeks_per_page, matched_per_page) = match mirror_road {
14721                        Some(road) => (road.seeks, road.rows),
14722                        None => probe_broadcast_price(
14723                            whole_read_rows,
14724                            &shape.keys,
14725                            shape.coverage_drop_allowed,
14726                        ),
14727                    };
14728                    // The bound rate applies only to the broadcast price's
14729                    // unknown-domain fallback. The mirror road prices a real
14730                    // pushed list, and a known domain that saturates the
14731                    // fraction is an exact covering match — both keep the
14732                    // estimate premium.
14733                    let matched_is_bound = mirror_road.is_none()
14734                        && first_broadcast_key(&shape.keys, shape.coverage_drop_allowed)
14735                            .is_some_and(|(_, probe_domain, _)| probe_domain == 0);
14736                    let count_walk_build_once =
14737                        bound_constraint_count_scan(scan) && shape.pages > 1;
14738                    let verdict = if count_walk_build_once {
14739                        // A count walk's request has no head list, so the
14740                        // per-page road re-walks the whole arm once per driver
14741                        // page. There is nothing to compare — pages × walk
14742                        // against one walk — so the priced verdict is
14743                        // degenerate and the build wins. The one-page case is
14744                        // excluded: it ties on the walk and its per-page read
14745                        // still prunes to that page's keys, so the priced roads
14746                        // decide there. The seating comparator applies the same
14747                        // rule (`seat_cost_arithmetic`'s `probe_count_walk`),
14748                        // so the cost model and the stamp cannot split. The calibrate
14749                        // knob cannot measure anything for this shape either:
14750                        // the per-page road takes no seeks.
14751                        FetchOnceVerdict::FetchOnce
14752                    } else if crate::query::tunables::calibration_force_probe() {
14753                        // Calibration knob (WARATAH_CALIBRATION_FORCE_PROBE,
14754                        // set by scripts/calibrate_seek_ratio.py
14755                        // --realworld): stamp PerPage so the executor runs the
14756                        // per-page allow-list (seek) road, letting the
14757                        // calibration measure real-store seek cost against
14758                        // the whole-read baseline. Advisory-safe — both roads
14759                        // return identical rows — and deliberately
14760                        // stamp-only: the cost model keeps pricing both roads by
14761                        // its own arithmetic, so the executed road diverges
14762                        // from the priced road only under this explicit
14763                        // operator knob.
14764                        FetchOnceVerdict::PerPage
14765                    } else {
14766                        fetch_once_verdict_now(
14767                            shape.pages,
14768                            seeks_per_page,
14769                            matched_per_page,
14770                            whole_read_rows,
14771                            whole_read_rows_known(profile, scan),
14772                            shape.driver_domains_known,
14773                            matched_is_bound,
14774                            probe_seek_concurrency_milli(
14775                                batch_arms.is_some(),
14776                                shape.pages,
14777                                seeks_per_page,
14778                                crate::context::query_fetch_concurrency() as u64,
14779                            ),
14780                        )
14781                    };
14782                    // Receipt for bench logs: which driver basis this
14783                    // verdict priced when a containing push conditions it
14784                    // (absent = the standalone basis, as before). The
14785                    // `matched_bound` flag records that the matched term was
14786                    // the unknown-domain fallback rather than an estimate —
14787                    // the one input the rest of the line cannot reveal,
14788                    // because the fallback prints as the whole arm.
14789                    let push_bound_tag = driver_bound
14790                        .map(|bound| format!(" push_bound={bound}"))
14791                        .unwrap_or_default();
14792                    if let Some(ctx) = ctx {
14793                        ctx.log(
14794                            crate::LogLevel::Debug,
14795                            &format!(
14796                                "fetch-once-stamp: {} pages={}{} seeks/page={} matched/page={} produced(clamped)={} whole_read_rows={} matched_bound={} arm_known={} domains_known={} -> {:?}{}",
14797                                crate::explain::scan_pattern_tag(scan),
14798                                shape.pages,
14799                                push_bound_tag,
14800                                seeks_per_page,
14801                                matched_per_page,
14802                                produced,
14803                                whole_read_rows,
14804                                matched_is_bound,
14805                                whole_read_rows_known(profile, scan),
14806                                shape.driver_domains_known,
14807                                verdict,
14808                                if count_walk_build_once {
14809                                    " (bound-constraint count walk: one walk, built once)"
14810                                } else {
14811                                    ""
14812                                }
14813                            ),
14814                        );
14815                    }
14816                    // No budget gate: a FetchOnce verdict always writes the
14817                    // mark. WHERE the build lives is the executor's
14818                    // per-join decision — `join_should_spill` degrades an
14819                    // over-memory arm to cached Grace partitions — so the
14820                    // planner keeps no second, row-based RAM opinion.
14821                    if verdict == FetchOnceVerdict::FetchOnce {
14822                        right.as_scan_mut().expect("as_scan held").fetch_once =
14823                            Some(whole_read_rows);
14824                    }
14825                }
14826            }
14827            // Child context for the probe arm's subtree. The push the
14828            // RUNTIME delivers into this join's right subtree is this
14829            // join's own keyed road — one broadcast-key list per driver
14830            // page — so a subtree probe arm (anything but a bare scan,
14831            // which contains no joins) establishes the containing-push
14832            // context for everything beneath it. Outermost wins: an
14833            // inherited context is kept untouched. The once-roads
14834            // establish nothing — an all-dropped probe (every key a
14835            // covered, droppable push: `ProbePushed::Ancestor`) or an
14836            // empty driver (zero pages) executes the subtree exactly
14837            // ONCE, so contained joins price standalone there. The
14838            // subtree's whole-read basis is its produced clamp — the same
14839            // basis `seat_cost_total` prices subtree arms at (no
14840            // unclamped price exists for them).
14841            let child_containing = containing.cloned().or_else(|| {
14842                if hash_keys.is_empty() || right.as_scan().is_some() {
14843                    return None;
14844                }
14845                let shape = seat_probe_shape(profile, left, right, hash_keys, ctx, driver_bound);
14846                child_push_from_shape(profile, left, right, ctx, &shape)
14847            });
14848            stamp_fetch_once(left, profile, ctx, containing, star_arms, sliced);
14849            stamp_fetch_once(right, profile, ctx, child_containing.as_ref(), None, sliced);
14850        }
14851        PlanNode::LeftJoin { left, right, .. } => {
14852            // No built slot in `execute_left_join` (Phase 2b): never stamp
14853            // an OPTIONAL arm — descend only. The containing push is
14854            // TRANSPARENT here: at runtime the
14855            // ancestor's pushed stack reaches BOTH arms — the required
14856            // side runs `pushed` directly and the optional side forwards
14857            // it through `probe_right` — so both price conditioned
14858            // beneath an inherited context. The pre-fix `None` to both
14859            // arms priced a required-side chain standalone while the
14860            // runtime filtered it per page: stale Build stamps inside
14861            // OPTIONAL required sides, the exact defect the conditioning
14862            // removes.
14863            stamp_fetch_once(left, profile, ctx, containing, None, sliced);
14864            stamp_fetch_once(right, profile, ctx, containing, None, sliced);
14865        }
14866        PlanNode::Union { left, right } => {
14867            stamp_fetch_once(left, profile, ctx, containing, None, sliced);
14868            stamp_fetch_once(right, profile, ctx, containing, None, sliced);
14869        }
14870        PlanNode::CustomNode(op) => {
14871            // Plugin children own their evaluation; whether an ancestor
14872            // push descends into them is the plugin's business, so the
14873            // context stops at the op (the op ITSELF still hosts keys —
14874            // a CustomNode driver conditions through `op.variables`).
14875            for child in &mut op.children {
14876                stamp_fetch_once(child, profile, ctx, None, None, sliced);
14877            }
14878        }
14879        PlanNode::Filter { inner, exists, .. } => {
14880            stamp_fetch_once(inner, profile, ctx, containing, None, sliced);
14881            // EXISTS bodies are correlated sub-evaluations, not
14882            // push-reachable arms — price standalone.
14883            for clause in exists {
14884                stamp_fetch_once(&mut clause.body, profile, ctx, None, None, sliced);
14885            }
14886        }
14887        // A Slice subtree executes through the OpenNode cursor (the
14888        // demand-bounded path): its joins keep the per-page road, so the
14889        // batch divisor does not apply beneath it.
14890        PlanNode::Slice { inner, .. } => {
14891            stamp_fetch_once(inner, profile, ctx, containing, None, true);
14892        }
14893        PlanNode::Extend { inner, .. }
14894        | PlanNode::Distinct { inner, .. }
14895        | PlanNode::Sort { inner, .. }
14896        | PlanNode::Group { inner, .. }
14897        | PlanNode::JoinGraphVar { inner, .. } => {
14898            stamp_fetch_once(inner, profile, ctx, containing, None, sliced);
14899        }
14900        // The subquery's own body stamps within its scope; the budget is
14901        // query-global, so it threads through the boundary. The
14902        // containing push does NOT: the boundary is opaque to outer
14903        // pushes (`probe_scan_has_key`'s own rule — outer join keys are
14904        // never probed into the subquery's scans), so the body prices
14905        // standalone.
14906        PlanNode::SubSelect(sub) => {
14907            stamp_fetch_once(&mut sub.inner, profile, ctx, None, None, sliced);
14908        }
14909        _ => {}
14910    }
14911}
14912
14913/// Clear every `fetch_once` stamp under `node` — the pass recomputes from
14914/// scratch each run, so a re-finalized tree never carries a stale stamp
14915/// from an earlier shape.
14916fn count_stamps_after_restamp(node: &PlanNode) -> usize {
14917    match node {
14918        PlanNode::Scan(scan) => usize::from(scan.fetch_once.is_some()),
14919        PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
14920            count_stamps_after_restamp(left) + count_stamps_after_restamp(right)
14921        }
14922        PlanNode::Union { left, right } => {
14923            count_stamps_after_restamp(left) + count_stamps_after_restamp(right)
14924        }
14925        PlanNode::CustomNode(op) => op.children.iter().map(count_stamps_after_restamp).sum(),
14926        PlanNode::Filter { inner, exists, .. } => {
14927            count_stamps_after_restamp(inner)
14928                + exists
14929                    .iter()
14930                    .map(|clause| count_stamps_after_restamp(&clause.body))
14931                    .sum::<usize>()
14932        }
14933        PlanNode::Extend { inner, .. }
14934        | PlanNode::Slice { inner, .. }
14935        | PlanNode::Distinct { inner, .. }
14936        | PlanNode::Sort { inner, .. }
14937        | PlanNode::Group { inner, .. }
14938        | PlanNode::JoinGraphVar { inner, .. } => count_stamps_after_restamp(inner),
14939        PlanNode::SubSelect(sub) => count_stamps_after_restamp(&sub.inner),
14940        _ => 0,
14941    }
14942}
14943
14944fn clear_fetch_once_marks(node: &mut PlanNode) {
14945    match node {
14946        PlanNode::Scan(scan) => scan.fetch_once = None,
14947        PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
14948            clear_fetch_once_marks(left);
14949            clear_fetch_once_marks(right);
14950        }
14951        PlanNode::Union { left, right } => {
14952            clear_fetch_once_marks(left);
14953            clear_fetch_once_marks(right);
14954        }
14955        PlanNode::CustomNode(op) => {
14956            for child in &mut op.children {
14957                clear_fetch_once_marks(child);
14958            }
14959        }
14960        PlanNode::Filter { inner, exists, .. } => {
14961            clear_fetch_once_marks(inner);
14962            for clause in exists {
14963                clear_fetch_once_marks(&mut clause.body);
14964            }
14965        }
14966        PlanNode::Extend { inner, .. }
14967        | PlanNode::Slice { inner, .. }
14968        | PlanNode::Distinct { inner, .. }
14969        | PlanNode::Sort { inner, .. }
14970        | PlanNode::Group { inner, .. }
14971        | PlanNode::JoinGraphVar { inner, .. } => clear_fetch_once_marks(inner),
14972        PlanNode::SubSelect(sub) => clear_fetch_once_marks(&mut sub.inner),
14973        _ => {}
14974    }
14975}
14976
14977/// Fully unpushed output-row estimate for a subtree: what the node emits
14978/// with **no** driver or ancestor key push applied, and with every internal
14979/// join's probe push removed too. Derived from the profile and the tree
14980/// shape; it ignores `broadcasted`, `ancestor_push_return_bound`, and the
14981/// staged `produced` cells.
14982///
14983/// This is the "no pushes anywhere" frame. It is a sanity bound and the
14984/// basis for an unfiltered whole-subtree build. It is **not** the driver
14985/// page count (active pushes make the real stream smaller) and **not** the
14986/// domain-pushed Semi build (which keeps the current driver's key list and
14987/// any ancestor pushes).
14988///
14989/// Container nodes pass their inner estimate through (an upper bound:
14990/// filter/group/distinct selectivity is not modeled). Joins use the
14991/// uniform multi-key product with the profile's key domains; an OPTIONAL
14992/// uses the left-join product. Plugin/catalog/count/boundary leaves use
14993/// their own produced estimate.
14994fn unpushed_row_count_estimate(
14995    profile: Option<&StatsProfile>,
14996    node: &PlanNode,
14997    budget: &mut u64,
14998) -> Option<u64> {
14999    if *budget == 0 {
15000        return None;
15001    }
15002    *budget -= 1;
15003    match node {
15004        PlanNode::Scan(scan) => {
15005            if !whole_read_rows_known(profile, scan) {
15006                return None;
15007            }
15008            Some(estimate_unclamped_scan_rows(profile, scan))
15009        }
15010        PlanNode::Path(path) => Some(estimate_path_size(
15011            path.subject_term.is_some(),
15012            &path.path,
15013            path.object_term.is_some(),
15014        )),
15015        PlanNode::Union { left, right } => Some(
15016            unpushed_row_count_estimate(profile, left, budget)?
15017                .saturating_add(unpushed_row_count_estimate(profile, right, budget)?),
15018        ),
15019        PlanNode::Join {
15020            left,
15021            right,
15022            hash_keys,
15023            ..
15024        } => {
15025            let left_rows = unpushed_row_count_estimate(profile, left, budget)?;
15026            let right_rows = unpushed_row_count_estimate(profile, right, budget)?;
15027            if hash_keys.is_empty() {
15028                return Some(left_rows.saturating_mul(right_rows).max(1));
15029            }
15030            let domains = hash_keys
15031                .iter()
15032                .map(|key| {
15033                    (
15034                        join_key_domain_for_node(profile, left, key),
15035                        join_key_domain_for_node(profile, right, key),
15036                    )
15037                })
15038                .collect::<Vec<_>>();
15039            Some(estimate_join_rows_multi(left_rows, right_rows, &domains))
15040        }
15041        PlanNode::LeftJoin {
15042            left,
15043            right,
15044            hash_keys,
15045            ..
15046        } => {
15047            let left_rows = unpushed_row_count_estimate(profile, left, budget)?;
15048            let right_rows = unpushed_row_count_estimate(profile, right, budget)?;
15049            Some(estimate_left_join_rows_product(
15050                left_rows, left, right, hash_keys, right_rows, profile,
15051            ))
15052        }
15053        PlanNode::Filter {
15054            inner,
15055            early,
15056            residual,
15057            exists,
15058            ..
15059        } => {
15060            let inner_rows = unpushed_row_count_estimate(profile, inner, budget)?;
15061            Some(apply_filter_selectivity(
15062                inner_rows,
15063                early.as_ref(),
15064                residual.as_ref(),
15065                exists,
15066            ))
15067        }
15068        PlanNode::Extend { inner, .. }
15069        | PlanNode::Slice { inner, .. }
15070        | PlanNode::Distinct { inner, .. }
15071        | PlanNode::Sort { inner, .. }
15072        | PlanNode::Group { inner, .. }
15073        | PlanNode::JoinGraphVar { inner, .. } => {
15074            unpushed_row_count_estimate(profile, inner, budget)
15075        }
15076        _ => Some(node.produced_row_count_estimate()),
15077    }
15078}
15079
15080/// Fully unpushed read-row estimate for a subtree: the store rows one
15081/// execution reads with no driver or ancestor key push, and with internal
15082/// joins' probe pushes removed. A scan leaf contributes its unclamped whole
15083/// read; a join sums both arm reads (raw read volume — not its output and
15084/// not probe-side overhead); containers pass through. `Values` / `Unit`
15085/// read nothing. Shapes whose read is not a scan-read sum return `None`.
15086///
15087/// This is the unfiltered-build basis: a build that drains the right
15088/// subtree without pushing the current driver's key list. The build
15089/// estimator prices the ancestor-pushes-only drain (or, in the future, the
15090/// domain-pushed drain); both are different from this fully unpushed read.
15091fn unpushed_read_rows(
15092    profile: Option<&StatsProfile>,
15093    node: &PlanNode,
15094    budget: &mut u64,
15095) -> Option<u64> {
15096    if *budget == 0 {
15097        return None;
15098    }
15099    *budget -= 1;
15100    match node {
15101        PlanNode::Scan(scan) => {
15102            if !whole_read_rows_known(profile, scan) {
15103                return None;
15104            }
15105            Some(estimate_unclamped_scan_rows(profile, scan))
15106        }
15107        PlanNode::Path(path) => Some(estimate_path_size(
15108            path.subject_term.is_some(),
15109            &path.path,
15110            path.object_term.is_some(),
15111        )),
15112        PlanNode::Union { left, right } => Some(
15113            unpushed_read_rows(profile, left, budget)?
15114                .saturating_add(unpushed_read_rows(profile, right, budget)?),
15115        ),
15116        PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => Some(
15117            unpushed_read_rows(profile, left, budget)?
15118                .saturating_add(unpushed_read_rows(profile, right, budget)?),
15119        ),
15120        PlanNode::Filter { inner, exists, .. } if exists.is_empty() => {
15121            unpushed_read_rows(profile, inner, budget)
15122        }
15123        PlanNode::Filter { .. } => None,
15124        PlanNode::Extend { inner, .. }
15125        | PlanNode::Slice { inner, .. }
15126        | PlanNode::Distinct { inner, .. }
15127        | PlanNode::Sort { inner, .. }
15128        | PlanNode::Group { inner, .. }
15129        | PlanNode::JoinGraphVar { inner, .. } => unpushed_read_rows(profile, inner, budget),
15130        PlanNode::CustomNode(op) => Some(op.sweep_cost().unwrap_or(op.produced_row_count_estimate)),
15131        PlanNode::SubSelect(sub) => unpushed_read_rows(profile, &sub.inner, budget),
15132        PlanNode::Values(_) | PlanNode::Unit => Some(0),
15133        _ => None,
15134    }
15135}
15136
15137/// One ancestor join's key list, active while the semijoin's right subtree
15138/// executes. `list` is the number of distinct values the ancestor pushes
15139/// (its driver key domain bounded by its own rows); the per-leaf domain is
15140/// derived from the scan's profile sketch. The vector is ordered
15141/// outer-first, matching the runtime push stack: only the first hosted
15142/// entry per scan is applied.
15143#[derive(Debug, Clone)]
15144pub(crate) struct AncestorPushKey {
15145    key: Variable,
15146    list: u64,
15147}
15148
15149/// Add an ancestor push, merging a repeated key by the smaller list. Two
15150/// ancestors pushing the same key compose by intersection; with only list
15151/// lengths the smaller list is a sound upper bound.
15152fn add_ancestor_push(pushes: &mut Vec<AncestorPushKey>, key: &Variable, list: u64) {
15153    if list == 0 {
15154        return;
15155    }
15156    if let Some(existing) = pushes.iter_mut().find(|push| &push.key == key) {
15157        existing.list = existing.list.min(list);
15158    } else {
15159        pushes.push(AncestorPushKey {
15160            key: key.clone(),
15161            list,
15162        });
15163    }
15164}
15165
15166/// Which key lists the semijoin build pushes into the right subtree.
15167#[derive(Debug, Clone, Copy)]
15168enum SemiBuildPushSource<'a> {
15169    /// One drain with only the inherited ancestor key lists. The current
15170    /// join's driver keys are not pushed. This is the regular executor's
15171    /// build.
15172    AncestorPushesOnly,
15173    /// The inherited ancestor lists plus the current driver's full distinct
15174    /// key domain. This is the future domain-pushed build; it is exercised
15175    /// by unit tests only until that executor lands.
15176    #[allow(dead_code)]
15177    AncestorPushesAndDriverDomain { key: &'a Variable, domain: u64 },
15178}
15179
15180impl SemiBuildPushSource<'_> {
15181    fn label(&self) -> &'static str {
15182        match self {
15183            Self::AncestorPushesOnly => "ancestor-pushes-only",
15184            Self::AncestorPushesAndDriverDomain { .. } => "ancestor-pushes-and-driver-domain",
15185        }
15186    }
15187}
15188
15189/// Estimate of one build drain over the right subtree: the rows its leaves
15190/// return under the build's effective push lists, the pushed terms, the
15191/// chunked fetch count, and the scalar FILTER cost. `read_rows` is the
15192/// filter input, not the emitted key set.
15193#[derive(Debug, Clone, Copy)]
15194struct SemiBuildDrainEstimate {
15195    /// Rows the build's scan leaves return under the effective push lists.
15196    /// This is what the subtree's filters consume, not the final key set.
15197    read_rows: u64,
15198    /// List terms pushed into hosting scan leaves. The seek price's
15199    /// per-term cost applies to this number.
15200    pushed_terms: u64,
15201    /// Chunked fetch RPCs: one per `PUSHDOWN_TERMS_LIMIT` terms per hosting
15202    /// leaf. Drives the build's fetch concurrency.
15203    chunk_fetches: u64,
15204    /// Extra milli-row-equivalents for scalar FILTER evaluation over the
15205    /// read rows. The build pays it once; the per-page road pays its
15206    /// equivalent through `subtree_page_cost`.
15207    filter_eval_milli: u64,
15208}
15209
15210/// Estimate the build drain over the right subtree under `source`.
15211///
15212/// `AncestorPushesOnly` is the regular executor's build: one drain with only
15213/// the inherited ancestor key lists, no current-join driver keys. A leaf with
15214/// no hosted ancestor list reads its whole arm. `AncestorPushesAndDriverDomain`
15215/// adds the current driver's full distinct key domain (the future
15216/// domain-pushed build); the driver list is used only where no ancestor list
15217/// is hosted, because the runtime applies one filter per scan.
15218///
15219/// A pushed list reaches a hosting scan leaf in `PUSHDOWN_TERMS_LIMIT`
15220/// chunks, so the leaf returns the fraction of its arm that the list
15221/// reaches. The first cut prices full vocabulary overlap: the driver may be
15222/// a join or union whose key vocabulary `scan_key_vocabulary` cannot
15223/// resolve, and pricing less than full would understate the build read.
15224/// Ancestor pushes are included when known, but the runtime applies only
15225/// the **first**
15226/// hosted entry per scan (`PushedKeyVals::broadcast_for`, ancestor entries
15227/// outer-first), so this prices one effective list per leaf: an ancestor
15228/// key wins over the build's driver key unless they are the same key, where
15229/// the lists intersect (the smaller list is a sound upper bound). A covering
15230/// list (list >= domain) contributes no read reduction, mirroring the
15231/// runtime coverage rule. The fully
15232/// unfiltered alternative — a drain with no driver key list — is
15233/// [`unpushed_read_rows`]; this function is the domain-pushed frame and the
15234/// one the verdict uses.
15235///
15236/// Shapes whose build work is not a sum of scan reads (joins, plugin ops,
15237/// Values, catalog/count nodes, SubSelect boundaries, EXISTS bodies) return
15238/// `None`; an unknown build price must not order a build. The budget bounds
15239/// planner work on a pathological subtree, and exhausting it is an unknown
15240/// estimate, not a coarse one.
15241fn estimate_semi_build_drain(
15242    profile: Option<&StatsProfile>,
15243    node: &PlanNode,
15244    source: SemiBuildPushSource<'_>,
15245    ancestors: &[AncestorPushKey],
15246    budget: &mut u64,
15247) -> Option<SemiBuildDrainEstimate> {
15248    if *budget == 0 {
15249        return None;
15250    }
15251    *budget -= 1;
15252    match node {
15253        PlanNode::Scan(scan) => {
15254            if scan.has_specialized_rpc() || !whole_read_rows_known(profile, scan) {
15255                return None;
15256            }
15257            let whole = estimate_unclamped_scan_rows(profile, scan);
15258            // The runtime applies at most ONE push filter per scan:
15259            // `PushedKeyVals::broadcast_for` takes the first entry whose
15260            // variable occupies a scan slot, and ancestor entries are
15261            // outer-first. Mirror that pick rather than multiplying every
15262            // hosted key: an ancestor key wins over the build's driver key
15263            // unless they are the same key, where the two lists intersect
15264            // (the smaller list is a sound upper bound).
15265            let driver = match source {
15266                SemiBuildPushSource::AncestorPushesAndDriverDomain { key, domain }
15267                    if !scan.slot_of(key).is_empty() || scan.graph.as_ref() == Some(key) =>
15268                {
15269                    Some((key, domain))
15270                }
15271                _ => None,
15272            };
15273            let effective = ancestors
15274                .iter()
15275                .find(|ancestor| {
15276                    !scan.slot_of(&ancestor.key).is_empty()
15277                        || scan.graph.as_ref() == Some(&ancestor.key)
15278                })
15279                .map(|ancestor| {
15280                    let domain =
15281                        join_key_domain_for(profile, scan, std::slice::from_ref(&ancestor.key))
15282                            .unwrap_or(0);
15283                    let list = match driver {
15284                        Some((driver_key, driver_domain)) if ancestor.key == *driver_key => {
15285                            ancestor.list.min(driver_domain)
15286                        }
15287                        _ => ancestor.list,
15288                    };
15289                    (list, domain)
15290                })
15291                .or_else(|| {
15292                    driver.map(|(driver_key, driver_domain)| {
15293                        let domain =
15294                            join_key_domain_for(profile, scan, std::slice::from_ref(driver_key))
15295                                .unwrap_or(0);
15296                        (driver_domain, domain)
15297                    })
15298                });
15299            let Some((list, domain)) = effective else {
15300                return Some(SemiBuildDrainEstimate {
15301                    read_rows: whole,
15302                    pushed_terms: 0,
15303                    chunk_fetches: 0,
15304                    filter_eval_milli: 0,
15305                });
15306            };
15307            let matched = if domain > 0 && list < domain {
15308                u64::try_from(
15309                    u128::from(whole)
15310                        .saturating_mul(u128::from(list))
15311                        .saturating_div(u128::from(domain)),
15312                )
15313                .unwrap_or(whole)
15314            } else {
15315                whole
15316            };
15317            Some(SemiBuildDrainEstimate {
15318                read_rows: matched,
15319                pushed_terms: list,
15320                chunk_fetches: list.div_ceil(PUSHDOWN_TERMS_LIMIT),
15321                filter_eval_milli: 0,
15322            })
15323        }
15324        PlanNode::Filter {
15325            inner,
15326            early,
15327            residual,
15328            exists,
15329            ..
15330        } if exists.is_empty() => {
15331            let inner = estimate_semi_build_drain(profile, inner, source, ancestors, budget)?;
15332            let filter_eval_milli = inner
15333                .read_rows
15334                .saturating_mul(filter_row_cost_milli(early.as_ref(), residual.as_ref()));
15335            Some(SemiBuildDrainEstimate {
15336                filter_eval_milli: inner.filter_eval_milli.saturating_add(filter_eval_milli),
15337                ..inner
15338            })
15339        }
15340        // An EXISTS body runs per surviving inner row; its work is not a
15341        // scan-read sum this estimator can prove.
15342        PlanNode::Filter { .. } => None,
15343        PlanNode::Union { left, right } => {
15344            let left = estimate_semi_build_drain(profile, left, source, ancestors, budget)?;
15345            let right = estimate_semi_build_drain(profile, right, source, ancestors, budget)?;
15346            Some(SemiBuildDrainEstimate {
15347                read_rows: left.read_rows.saturating_add(right.read_rows),
15348                pushed_terms: left.pushed_terms.saturating_add(right.pushed_terms),
15349                chunk_fetches: left.chunk_fetches.saturating_add(right.chunk_fetches),
15350                filter_eval_milli: left
15351                    .filter_eval_milli
15352                    .saturating_add(right.filter_eval_milli),
15353            })
15354        }
15355        PlanNode::Extend { inner, .. }
15356        | PlanNode::Slice { inner, .. }
15357        | PlanNode::Distinct { inner, .. }
15358        | PlanNode::Sort { inner, .. }
15359        | PlanNode::Group { inner, .. }
15360        | PlanNode::JoinGraphVar { inner, .. } => {
15361            estimate_semi_build_drain(profile, inner, source, ancestors, budget)
15362        }
15363        _ => None,
15364    }
15365}
15366
15367/// Whether the right subtree contains a specialized scan RPC. Its output is
15368/// not the pattern's rows, so neither the payload proof nor the key-set
15369/// build's read estimate describes it.
15370fn subtree_has_specialized_scan(node: &PlanNode) -> bool {
15371    match node {
15372        PlanNode::Scan(scan) => scan.has_specialized_rpc(),
15373        PlanNode::Join { left, right, .. }
15374        | PlanNode::LeftJoin { left, right, .. }
15375        | PlanNode::Union { left, right, .. } => {
15376            subtree_has_specialized_scan(left) || subtree_has_specialized_scan(right)
15377        }
15378        PlanNode::Filter { inner, exists, .. } => {
15379            subtree_has_specialized_scan(inner)
15380                || exists
15381                    .iter()
15382                    .any(|clause| subtree_has_specialized_scan(&clause.body))
15383        }
15384        PlanNode::CustomNode(op) => op.children.iter().any(subtree_has_specialized_scan),
15385        PlanNode::Extend { inner, .. }
15386        | PlanNode::Slice { inner, .. }
15387        | PlanNode::Distinct { inner, .. }
15388        | PlanNode::Sort { inner, .. }
15389        | PlanNode::Group { inner, .. }
15390        | PlanNode::JoinGraphVar { inner, .. } => subtree_has_specialized_scan(inner),
15391        PlanNode::SubSelect(sub) => subtree_has_specialized_scan(&sub.inner),
15392        _ => false,
15393    }
15394}
15395
15396/// The priced general `Semi` build decision: one domain-pushed pass over the
15397/// right subtree and a key-set build, against the current road's per-page
15398/// re-execution with each page's keys pushed into the subtree.
15399///
15400/// This is intentionally **not** [`fetch_once_verdict`]. Fetch-once prices a
15401/// whole *scan* whose table can be memoized and carries every column;
15402/// the general `Semi` build reads a **filtered subtree** (no scan memo) and
15403/// keeps only the join key set, and it can push the driver's full key domain
15404/// into the subtree's leaves. The per-page arithmetic still shares
15405/// [`fetch_once_price_milli`], but the build basis, the key-set term and the
15406/// margin are Semi-specific (`SEMI_BUILD_MARGIN_MILLI`,
15407/// `SEMI_KEY_SET_ROW_EQUIV_MILLI` in `query/tunables.rs`).
15408#[derive(Debug, Clone, Copy)]
15409struct SemiBuildPrice {
15410    // Per-page road: one re-execution per driver page, each pushing that
15411    // page's key list through the subtree.
15412    pages: u64,
15413    driver_rows: u64,
15414    page_rows: u64,
15415    seeks_per_page: u64,
15416    matched_per_page: u64,
15417    /// Component of `per_page_price_milli` from scalar FILTER evaluation.
15418    per_page_filter_cost_milli: u64,
15419    per_page_price_milli: u128,
15420    // Build road: one pass with the driver's whole key domain pushed.
15421    build_read_rows: u64,
15422    build_source: &'static str,
15423    build_seek_terms: u64,
15424    build_rpcs: u64,
15425    build_output_rows: u64,
15426    /// Distinct-key upper bound the key set retains. Logged for the A/B and
15427    /// future memory pricing; the output-row term above prices the insert
15428    /// and dedup work, and the margin covers the residual key-set memory.
15429    build_keys: u64,
15430    build_price_milli: u128,
15431    build_bar_milli: u128,
15432    /// Component of `build_price_milli` from scalar FILTER evaluation.
15433    build_filter_cost_milli: u64,
15434    /// Fully unfiltered read basis for the same subtree (the alternative
15435    /// build policy), and its fully unfiltered output upper bound. Both are
15436    /// diagnostic/sanity values; the verdict never reads them.
15437    unpushed_read_rows: Option<u64>,
15438    unpushed_output_rows: Option<u64>,
15439    /// Ancestor key lists that actually reach this right subtree.
15440    ancestor_keys: usize,
15441    // Shared facts.
15442    driver_domain: u64,
15443    probe_domain_known: bool,
15444}
15445
15446/// Render an optional row estimate for the debug line ("unknown" on None).
15447fn option_rows(rows: Option<u64>) -> String {
15448    rows.map_or_else(|| "unknown".to_owned(), |rows| rows.to_string())
15449}
15450
15451impl SemiBuildPrice {
15452    fn summary(&self) -> String {
15453        format!(
15454            "pages={} driver_rows={} page_rows={} per_page_seeks={} per_page_matched={} \
15455             per_page_filter_cost={} per_page_price={} build_read={} build_source={} \
15456             build_seeks={} build_rpcs={} \
15457             build_output={} build_keys={} filter_cost={} build_price={} build_bar={} \
15458             unpushed_read={} unpushed_out={} ancestors={} \
15459             driver_domain={} probe_domain_known={}",
15460            self.pages,
15461            self.driver_rows,
15462            self.page_rows,
15463            self.seeks_per_page,
15464            self.matched_per_page,
15465            self.per_page_filter_cost_milli / 1000,
15466            self.per_page_price_milli / 1000,
15467            self.build_read_rows,
15468            self.build_source,
15469            self.build_seek_terms,
15470            self.build_rpcs,
15471            self.build_output_rows,
15472            self.build_keys,
15473            self.build_filter_cost_milli / 1000,
15474            self.build_price_milli / 1000,
15475            self.build_bar_milli / 1000,
15476            option_rows(self.unpushed_read_rows),
15477            option_rows(self.unpushed_output_rows),
15478            self.ancestor_keys,
15479            self.driver_domain,
15480            self.probe_domain_known,
15481        )
15482    }
15483}
15484
15485/// Which road the general `Semi` cost comparison chose.
15486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15487enum SemiBuildVerdict {
15488    Build,
15489    PerPage,
15490}
15491
15492/// Compare the per-page road's total price against the domain-pushed build's
15493/// price after the Semi margin.
15494///
15495/// `build_bar_milli` already carries the margin; keeping the comparison here
15496/// means the diagnostic and any future stamp consume one predicate. An empty
15497/// driver or an empty build read has nothing to amortize, so it stays on the
15498/// per-page road.
15499fn semi_build_verdict(price: &SemiBuildPrice) -> SemiBuildVerdict {
15500    if price.pages == 0 || price.build_read_rows == 0 {
15501        return SemiBuildVerdict::PerPage;
15502    }
15503    if price.per_page_price_milli >= price.build_bar_milli {
15504        SemiBuildVerdict::Build
15505    } else {
15506        SemiBuildVerdict::PerPage
15507    }
15508}
15509
15510/// Why a subtree-right inner join did not admit the general `Semi`
15511/// strategy. Variants are ordered the way the admission tests them, so the
15512/// diagnostic names the first fact that failed.
15513#[derive(Debug, Clone)]
15514enum SemiRefusal {
15515    StarArm,
15516    SlicedSubtree,
15517    MultiKey(usize),
15518    KeyNotBoundLeft(Variable),
15519    KeyNotBoundRight(Variable),
15520    SpecializedScan,
15521    Payload,
15522    CountStar,
15523    RowMultiplicity,
15524    BuildEstimateUnknown,
15525    DriverDomainUnknown,
15526    PerPage(Box<SemiBuildPrice>),
15527}
15528
15529impl SemiRefusal {
15530    fn describe(&self) -> String {
15531        match self {
15532            Self::StarArm => "star arm".to_owned(),
15533            Self::SlicedSubtree => "the Slice path runs through OpenNode".to_owned(),
15534            Self::MultiKey(count) => format!("{count} join keys (first cut admits one)"),
15535            Self::KeyNotBoundLeft(key) => {
15536                format!("key {key} is not always bound on the left")
15537            }
15538            Self::KeyNotBoundRight(key) => {
15539                format!("key {key} is not always bound on the right")
15540            }
15541            Self::SpecializedScan => "specialized scan in the right subtree".to_owned(),
15542            Self::Payload => "right payload above the join".to_owned(),
15543            Self::CountStar => "plain COUNT(*) above the join".to_owned(),
15544            Self::RowMultiplicity => "row multiplicity is observed above the join".to_owned(),
15545            Self::BuildEstimateUnknown => "build read estimate unknown".to_owned(),
15546            Self::DriverDomainUnknown => "driver key domain unknown".to_owned(),
15547            Self::PerPage(price) => format!("per-page road is cheaper ({})", price.summary()),
15548        }
15549    }
15550}
15551
15552/// The general subtree-right `Semi` admission predicate.
15553///
15554/// A semi join keeps the left rows whose key is present in the right and
15555/// emits only left columns. It is sound only when:
15556///
15557/// - the right contributes no column anything above the join consumes
15558///   except the join key (a right payload would disappear);
15559/// - the right's key is always bound, so a key-set membership test is the
15560///   same predicate as the join's compatibility test;
15561/// - the left's key is always bound, so every surviving row can be tested;
15562/// - nothing above the join observes row multiplicity, because duplicate
15563///   right keys multiply every left column (plain `COUNT(*)` is refused
15564///   explicitly even when every live mark is insensitive);
15565/// - the right subtree's domain-pushed build read is profile-backed and the
15566///   build-once road beats the current per-page road under the Semi build
15567///   verdict's own margin.
15568///
15569/// The first cut admits one key. A key-unique scan right whose fetch-once
15570/// verdict chose the whole read is claimed by E1's
15571/// [`JoinStrategy::SemiScan`] first; the general road takes any scan the
15572/// promotion left, plus every non-scan right subtree. A multi-key build waits
15573/// until the key-set kernel and the multiplicity proof are exercised on the
15574/// one-key shape.
15575#[allow(clippy::too_many_arguments)]
15576fn semi_join_admission(
15577    left: &PlanNode,
15578    right: &PlanNode,
15579    hash_keys: &[Variable],
15580    meta: &JoinMeta,
15581    facts: &SemiGateFacts,
15582    ancestors: &[AncestorPushKey],
15583    sliced: bool,
15584    profile: Option<&StatsProfile>,
15585    ctx: Option<&crate::context::QueryContext>,
15586) -> Result<SemiBuildPrice, SemiRefusal> {
15587    if meta.star_arms.is_some() {
15588        // The gate runs after `stamp_star_join_shapes`, so this is a live
15589        // check: a star arm is never a semi build, and its probe is a scan
15590        // the subtree-only rule would refuse anyway. The two claims must not
15591        // overlap.
15592        return Err(SemiRefusal::StarArm);
15593    }
15594    if sliced {
15595        return Err(SemiRefusal::SlicedSubtree);
15596    }
15597    if hash_keys.len() != 1 {
15598        return Err(SemiRefusal::MultiKey(hash_keys.len()));
15599    }
15600    let key = &hash_keys[0];
15601    if !left.output_vars().is_always_bound(key) {
15602        return Err(SemiRefusal::KeyNotBoundLeft(key.clone()));
15603    }
15604    if !right.output_vars().is_always_bound(key) {
15605        return Err(SemiRefusal::KeyNotBoundRight(key.clone()));
15606    }
15607    if subtree_has_specialized_scan(right) {
15608        return Err(SemiRefusal::SpecializedScan);
15609    }
15610    if facts.count_star {
15611        return Err(SemiRefusal::CountStar);
15612    }
15613    if facts.right_payload {
15614        return Err(SemiRefusal::Payload);
15615    }
15616    if facts.row_multiplicity_observed {
15617        return Err(SemiRefusal::RowMultiplicity);
15618    }
15619    let driver_domain =
15620        join_key_domain_for_node(profile, left, key).ok_or(SemiRefusal::DriverDomainUnknown)?;
15621    let driver_rows = driver_whole_read_rows(left, hash_keys, profile);
15622    let page_rows = seat_page_rows(left, right, ctx).max(1);
15623    let pages = driver_rows.div_ceil(page_rows);
15624    // One page's key list: the driver's index order bounds a scan driver,
15625    // while a join/union driver prices the larger of the clustered and
15626    // mixed occupancy estimates — the same price basis the seating
15627    // comparator uses for a non-scan driver.
15628    let clustered = clustered_page_distinct(driver_rows, driver_domain, page_rows);
15629    let mixed = mixed_page_distinct(driver_domain, page_rows, driver_rows);
15630    let page_val_count = if left.as_scan().is_some() {
15631        clustered
15632    } else {
15633        clustered.max(mixed)
15634    };
15635    let probe_domain = join_key_domain_for_node(profile, right, key);
15636    let probe_domain_known = probe_domain.is_some();
15637    let mut page_budget = SUBTREE_WALK_NODE_BUDGET;
15638    let mut page_filter_cost_milli = 0u64;
15639    let page = subtree_page_cost_with_filter(
15640        profile,
15641        right,
15642        &ContainingPush {
15643            key: key.clone(),
15644            pushed_val_count: page_val_count,
15645        },
15646        ctx,
15647        &mut page_budget,
15648        &mut page_filter_cost_milli,
15649    );
15650    // `page.rows` includes the filter cost's integer part; the matched-row
15651    // term must price only the matched rows, and the filter cost is charged
15652    // once per page at its own rate.
15653    let matched_per_page = page.rows.saturating_sub(page_filter_cost_milli / 1000);
15654    // The per-page road is the subtree re-execution the runtime actually
15655    // runs today: the page's list reaches every scan leaf, and the
15656    // fetch-once batched-probe road does not apply to a subtree probe.
15657    let page_batched = crate::context::parallel_probe_engine_enabled()
15658        && !sliced
15659        && crate::query::parallel_probe::scan_hosts_broadcast_key(right, hash_keys);
15660    let page_seek_concurrency = probe_seek_concurrency_milli(
15661        page_batched,
15662        pages,
15663        page.seeks,
15664        crate::context::query_fetch_concurrency() as u64,
15665    );
15666    // An unknown probe key domain prices the matched term at its bound rate
15667    // instead of the estimate premium — the same distinction the scan
15668    // fetch-once verdict makes.
15669    let matched_is_bound = !probe_domain_known;
15670    let per_page_price_milli = fetch_once_price_milli(
15671        pages,
15672        page.seeks,
15673        matched_per_page,
15674        matched_is_bound,
15675        crate::query::tunables::fetch_once_seek_equiv_milli(),
15676        crate::query::tunables::fetch_once_matched_row_equiv_milli(),
15677        crate::query::tunables::fetch_once_matched_bound_equiv_milli(),
15678        page_seek_concurrency,
15679    )
15680    .saturating_add(u128::from(pages).saturating_mul(u128::from(page_filter_cost_milli)));
15681    // Build road: one pass with the driver's whole distinct key set pushed
15682    // into the right scans. The leaves' chunked fetches share the same
15683    // fetch pool as the parallel-probe road, so the build's seek price
15684    // divides by the realized concurrency of its chunk count.
15685    let mut build_budget = SUBTREE_WALK_NODE_BUDGET;
15686    let build_source = SemiBuildPushSource::AncestorPushesOnly;
15687    let build =
15688        estimate_semi_build_drain(profile, right, build_source, ancestors, &mut build_budget)
15689            .ok_or(SemiRefusal::BuildEstimateUnknown)?;
15690    let build_seek_concurrency =
15691        if crate::context::parallel_probe_engine_enabled() && build.chunk_fetches >= 2 {
15692            let funded = (crate::context::query_fetch_concurrency() as u64)
15693                .saturating_mul(1000)
15694                .min(build.chunk_fetches.saturating_mul(1000));
15695            crate::query::tunables::probe_seek_concurrency_realized_milli(funded) as u128
15696        } else {
15697            1000
15698        };
15699    // The build pass uses the same row/seek currency as one page, but pays
15700    // the estimate matched rate unconditionally: its matched count is a
15701    // full-domain-push fraction, not the unknown-domain fallback.
15702    let build_pass_milli = fetch_once_price_milli(
15703        1,
15704        build.pushed_terms,
15705        build.read_rows,
15706        false,
15707        crate::query::tunables::fetch_once_seek_equiv_milli(),
15708        crate::query::tunables::fetch_once_matched_row_equiv_milli(),
15709        crate::query::tunables::fetch_once_matched_bound_equiv_milli(),
15710        build_seek_concurrency,
15711    )
15712    .saturating_add(u128::from(build.filter_eval_milli));
15713    // Keys the build keeps and the rows it inspects to keep them. A
15714    // subtree's output estimate is an upper bound (a Filter reports its
15715    // inner's estimate), so clamp it to the rows the pushed read can
15716    // return; a filter's unmodeled selectivity can only lower the real
15717    // key-set work.
15718    let build_output_rows = right
15719        .produced_row_count_estimate()
15720        .min(build.read_rows)
15721        .max(1);
15722    let build_keys = join_key_domain_for_node(profile, right, key)
15723        .unwrap_or(build_output_rows)
15724        .min(build_output_rows)
15725        .max(1);
15726    let build_price_milli =
15727        build_pass_milli.saturating_add(u128::from(build_output_rows).saturating_mul(u128::from(
15728            crate::query::tunables::SEMI_KEY_SET_ROW_EQUIV_MILLI,
15729        )));
15730    let build_bar_milli = build_price_milli
15731        .saturating_mul(u128::from(crate::query::tunables::SEMI_BUILD_MARGIN_MILLI))
15732        .saturating_div(1000);
15733    // The fully unpushed frames are the comparison/sanity basis, not the
15734    // verdict: the domain-pushed build above keeps the driver's key list.
15735    let mut unpushed_read_budget = SUBTREE_WALK_NODE_BUDGET;
15736    let unpushed_read_rows = unpushed_read_rows(profile, right, &mut unpushed_read_budget);
15737    let mut unpushed_output_budget = SUBTREE_WALK_NODE_BUDGET;
15738    let unpushed_output_rows =
15739        unpushed_row_count_estimate(profile, right, &mut unpushed_output_budget);
15740    debug_assert!(
15741        unpushed_read_rows.is_none_or(|unpushed| build.read_rows <= unpushed),
15742        "the domain-pushed build read must not exceed the fully unpushed read: \
15743         build={} unpushed={:?}",
15744        build.read_rows,
15745        unpushed_read_rows,
15746    );
15747    let ancestor_keys = ancestors
15748        .iter()
15749        .filter(|push| probe_scan_has_key(right, &push.key))
15750        .count();
15751    let price = SemiBuildPrice {
15752        pages,
15753        driver_rows,
15754        page_rows,
15755        seeks_per_page: page.seeks,
15756        matched_per_page,
15757        per_page_filter_cost_milli: page_filter_cost_milli,
15758        per_page_price_milli,
15759        build_read_rows: build.read_rows,
15760        build_source: build_source.label(),
15761        build_seek_terms: build.pushed_terms,
15762        build_rpcs: build.chunk_fetches,
15763        build_output_rows,
15764        build_keys,
15765        build_price_milli,
15766        build_bar_milli,
15767        build_filter_cost_milli: build.filter_eval_milli,
15768        unpushed_read_rows,
15769        unpushed_output_rows,
15770        ancestor_keys,
15771        driver_domain,
15772        probe_domain_known,
15773    };
15774    match semi_build_verdict(&price) {
15775        SemiBuildVerdict::Build => Ok(price),
15776        SemiBuildVerdict::PerPage => Err(SemiRefusal::PerPage(Box::new(price))),
15777    }
15778}
15779
15780/// Whether the general `Semi` gate records and runs for this join.
15781///
15782/// Any inner join with a join key is a candidate, scan right included. The
15783/// `SemiScan` promotion gets first claim on a key-unique scan whose fetch-once
15784/// verdict chose the whole read; the general gate runs on whatever it left.
15785pub(crate) fn semi_gate_candidate(hash_keys: &[Variable], meta: &JoinMeta) -> bool {
15786    !hash_keys.is_empty() && !matches!(meta.strategy, JoinStrategy::Semi | JoinStrategy::SemiScan)
15787}
15788
15789/// Record the liveness-dependent half of one join's semi gate.
15790///
15791/// Called from the final liveness round's `Join` arm, the only place the
15792/// boundary capture exists. The payload set is computed here rather than in
15793/// the gate because it needs that capture; the names are logged here because
15794/// [`SemiGateFacts`] cannot carry a `Vec` and stay `Copy`.
15795pub(crate) fn record_semi_gate_facts(
15796    right: &PlanNode,
15797    hash_keys: &[Variable],
15798    semi: &JoinSemiContext,
15799    ctx: Option<&crate::context::QueryContext>,
15800) -> SemiGateFacts {
15801    // Structural, not the live schema: a bare `COUNT(DISTINCT ?v)` argument
15802    // is `Counted`, and `ScanOp::variables()` omits both `Counted` and `Dead`
15803    // slots. `inner_variables()` recurses to `ScanOp::slot_variables()`, the
15804    // liveness-independent S/P/O/G set, so the counted column is visible.
15805    let right_produced = right.inner_variables();
15806    let mut payload: Vec<&Variable> = Vec::new();
15807    // `right_required` is the right child's own requirement map: it names
15808    // every right column liveness proved something below or above the join
15809    // reads. Only the names also live above the join (and not the hash keys)
15810    // would be dropped by the semi join's left-only schema.
15811    for name in semi.right_required.keys() {
15812        if hash_keys.contains(name) || !semi.above_required.contains(name) {
15813            continue;
15814        }
15815        if !payload.contains(&name) {
15816            payload.push(name);
15817        }
15818    }
15819    // A bare `COUNT(DISTINCT ?v)` argument never enters the parent's
15820    // requirement map, but a right-only one is still consumed above the
15821    // join.
15822    for name in &semi.counted_distinct {
15823        if hash_keys.contains(name) || !right_produced.contains(name) {
15824            continue;
15825        }
15826        if !payload.contains(&name) {
15827            payload.push(name);
15828        }
15829    }
15830    if !payload.is_empty()
15831        && let Some(ctx) = ctx
15832        && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
15833    {
15834        let names = payload
15835            .iter()
15836            .map(|name| name.to_string())
15837            .collect::<Vec<_>>()
15838            .join(",");
15839        ctx.log(
15840            crate::context::LogLevel::Debug,
15841            &format!(
15842                "semi-payload: {} keys={hash_keys:?} payload=[{names}]",
15843                crate::explain::plan_node_tag(right)
15844            ),
15845        );
15846    }
15847    SemiGateFacts {
15848        right_payload: !payload.is_empty(),
15849        row_multiplicity_observed: semi.row_multiplicity_observed,
15850        count_star: semi.count_star,
15851    }
15852}
15853
15854/// Run one join's general `Semi` admission and log the verdict.
15855///
15856/// Called by [`stamp_semi_join_strategy`] only for a join whose
15857/// [`JoinMeta::semi_gate`] record exists. The gate therefore runs after the
15858/// `SemiScan` promotion and the star stamp, on the tree the executor runs.
15859#[allow(clippy::too_many_arguments)]
15860fn admit_semi_join(
15861    left: &PlanNode,
15862    right: &PlanNode,
15863    hash_keys: &[Variable],
15864    meta: &JoinMeta,
15865    facts: &SemiGateFacts,
15866    ancestors: &[AncestorPushKey],
15867    sliced: bool,
15868    profile: Option<&StatsProfile>,
15869    ctx: Option<&crate::context::QueryContext>,
15870) -> bool {
15871    let tag = crate::explain::plan_node_tag(right);
15872    match semi_join_admission(
15873        left, right, hash_keys, meta, facts, ancestors, sliced, profile, ctx,
15874    ) {
15875        Ok(price) => {
15876            if let Some(ctx) = ctx
15877                && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
15878            {
15879                ctx.log(
15880                    crate::context::LogLevel::Debug,
15881                    &format!(
15882                        "semi-admit: {tag} keys={hash_keys:?} -> admit ({})",
15883                        price.summary()
15884                    ),
15885                );
15886            }
15887            true
15888        }
15889        Err(SemiRefusal::PerPage(price)) if ctx.is_some_and(|ctx| ctx.force_semi()) => {
15890            // Benchmark switch: only the price loses its veto. Every
15891            // semantic gate (payload, multiplicity, keys, specialized scan)
15892            // already passed to reach `PerPage`.
15893            if let Some(ctx) = ctx
15894                && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
15895            {
15896                ctx.log(
15897                    crate::context::LogLevel::Debug,
15898                    &format!(
15899                        "semi-admit: {tag} keys={hash_keys:?} -> forced semi ({})",
15900                        price.summary()
15901                    ),
15902                );
15903            }
15904            true
15905        }
15906        Err(refusal) => {
15907            if let Some(ctx) = ctx
15908                && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
15909            {
15910                ctx.log(
15911                    crate::context::LogLevel::Debug,
15912                    &format!(
15913                        "semi-admit: {tag} keys={hash_keys:?} -> refuse: {}",
15914                        refusal.describe()
15915                    ),
15916                );
15917            }
15918            false
15919        }
15920    }
15921}
15922
15923/// The ancestor push list a join hands to its right subtree.
15924///
15925/// This is the list the build drain is priced under
15926/// (`SemiBuildPushSource::AncestorPushesOnly`): the inherited ancestor keys
15927/// plus this join's own first key the runtime's `rhs_hostable_keys` gate
15928/// admits, and nothing derived from a driver page. Using the runtime's own
15929/// hostable set, rather than the structural `probe_scan_has_key`, keeps the
15930/// priced build and the executed build on the same push list. A
15931/// semi-strategy ancestor contributes no list, because it builds its right
15932/// once instead of re-pushing per page.
15933fn semi_join_right_pushes(
15934    left: &PlanNode,
15935    hash_keys: &[Variable],
15936    meta: &JoinMeta,
15937    profile: Option<&StatsProfile>,
15938    ancestors: &[AncestorPushKey],
15939    hostable: &[Variable],
15940) -> Vec<AncestorPushKey> {
15941    let mut pushes = ancestors.to_vec();
15942    if !matches!(meta.strategy, JoinStrategy::Semi | JoinStrategy::SemiScan)
15943        && let Some(key) = hash_keys.iter().find(|key| hostable.contains(key))
15944    {
15945        let list = pushed_val_count(profile, left, key);
15946        add_ancestor_push(&mut pushes, key, list);
15947    }
15948    pushes
15949}
15950
15951/// Apply the two build-once claims to inner joins: [`JoinStrategy::SemiScan`]
15952/// for a scan right the fetch-once verdict already chose, then
15953/// [`JoinStrategy::Semi`] for the general build-once road, scan or subtree
15954/// right.
15955///
15956/// `SemiScan` claims first. The general gate runs only for joins the
15957/// specialized promotion and the star stamp left alone, so the two roads never
15958/// overlap and a shape the specialized road owns is never priced twice.
15959///
15960/// The general gate's liveness-dependent half was recorded by the final
15961/// liveness round in [`JoinMeta::semi_gate`]; see [`SemiGateFacts`] for why
15962/// that record cannot go stale. Everything structural or profile-based — key
15963/// binding, specialized scan, driver domain, page count, price — is evaluated
15964/// here, on the tree the executor runs.
15965///
15966/// The `SemiScan` cost decision is not repeated: [`restamp_fetch_once`] has
15967/// just written [`ScanOp::fetch_once`] from the calibrated
15968/// broadcast-versus-whole read price, and this pass only reads that verdict.
15969/// What it adds is the eligibility half — every column the right scan
15970/// materializes is a join key, and the key multiplicity above the join either
15971/// cannot matter or cannot occur:
15972///
15973/// - **Cannot matter:** the key is bag-insensitive above the join. Liveness
15974///   writes that mark for a `DISTINCT` projection, `COUNT(DISTINCT *)`, a
15975///   grouped key under `COUNT(DISTINCT ?key)`, or a `MIN`/`MAX`/`SAMPLE`
15976///   input. A non-key `COUNT(DISTINCT ?v)` does not: the variable is routed
15977///   through `count_vars` rather than the required map, so a join key
15978///   defaults to the conservative `Sensitive` mark.
15979/// - **Cannot occur:** the pattern binds the key at most once per row
15980///   (`?r p <ground>`).
15981///
15982/// Pipeline position: after [`restamp_fetch_once`] (the verdict must exist)
15983/// and before [`restamp_joins_produced_row_count_estimate`]. Both price frames
15984/// read the in-round produced-row estimate, which is why the gate must not
15985/// move past that restamp. A `Slice` suppresses the stamps below it (a root
15986/// `Slice` skips the whole pass): the Slice path executes through
15987/// `OpenNode`, which does not consult `JoinStrategy`, so a stamp there would
15988/// name a road the executor never takes. An `EXISTS` body is evaluated
15989/// through `OpenNode` as well and is suppressed for the same reason. A
15990/// *small* slice still gets [`prefer_broadcast_for_small_slice`] on its own
15991/// condition, because a tiny demand is cheaper served by pushing its few
15992/// keys into storage.
15993///
15994/// Single-shot: the pass assumes a freshly lowered plan in which no join
15995/// carries `Semi` or `SemiScan`, and it only ever promotes. It never demotes
15996/// a stale stamp, so a caller that re-stamps an already-promoted tree must
15997/// clear the strategy first. `from_prepared` calls it once, after the final
15998/// fetch-once restamp and before the produced-row restamp; both claims run
15999/// here so a join is stamped exactly once and its `semi_gate` record is
16000/// consumed.
16001fn stamp_semi_join_strategy(
16002    node: &mut PlanNode,
16003    profile: Option<&StatsProfile>,
16004    sliced: bool,
16005    ctx: Option<&crate::context::QueryContext>,
16006    ancestor_pushes: &[AncestorPushKey],
16007) {
16008    match node {
16009        PlanNode::Join {
16010            left,
16011            right,
16012            hash_keys,
16013            rhs_hostable_keys,
16014            meta,
16015            ..
16016        } => {
16017            let right_scan = right.as_scan();
16018            let stamped = right_scan.is_some_and(|scan| scan.fetch_once.is_some());
16019            let eligible = right_scan.is_some_and(|scan| semi_eligible_scan_right(scan, hash_keys));
16020            let promote = meta.star_arms.is_none() && stamped && eligible;
16021            // The general gate runs only on a recorded candidate the
16022            // specialized promotion and the star stamp did not claim. The
16023            // record is consumed either way.
16024            let recorded = meta.semi_gate.take();
16025            let general = !promote
16026                && meta.star_arms.is_none()
16027                && recorded.is_some_and(|facts| {
16028                    admit_semi_join(
16029                        left,
16030                        right,
16031                        hash_keys,
16032                        meta,
16033                        &facts,
16034                        ancestor_pushes,
16035                        sliced,
16036                        profile,
16037                        ctx,
16038                    )
16039                });
16040            if stamped
16041                && let Some(ctx) = ctx
16042                && ctx.log_sink().enabled_at(crate::context::LogLevel::Debug)
16043            {
16044                let tag = right_scan.map_or_else(String::new, crate::explain::scan_pattern_tag);
16045                ctx.log(
16046                    crate::context::LogLevel::Debug,
16047                    &format!(
16048                        "semi-scan: {tag} keys={hash_keys:?} eligible={eligible} star={} -> {}",
16049                        meta.star_arms.is_some(),
16050                        if promote { "Semi" } else { "unchanged" }
16051                    ),
16052                );
16053            }
16054            if promote {
16055                meta.strategy = JoinStrategy::SemiScan;
16056            } else if general {
16057                meta.strategy = JoinStrategy::Semi;
16058            }
16059            // The right subtree inherits this join's first hostable key only
16060            // when this join did not become a build-once arm: a semi ancestor
16061            // drains its right with the inherited pushes alone, not with its
16062            // own driver keys.
16063            let right_pushes = semi_join_right_pushes(
16064                left,
16065                hash_keys,
16066                meta,
16067                profile,
16068                ancestor_pushes,
16069                rhs_hostable_keys.as_ref(),
16070            );
16071            stamp_semi_join_strategy(left, profile, sliced, ctx, ancestor_pushes);
16072            stamp_semi_join_strategy(right, profile, sliced, ctx, &right_pushes);
16073        }
16074        PlanNode::LeftJoin { left, right, .. } => {
16075            stamp_semi_join_strategy(left, profile, sliced, ctx, ancestor_pushes);
16076            stamp_semi_join_strategy(right, profile, sliced, ctx, ancestor_pushes);
16077        }
16078        PlanNode::Union { left, right } => {
16079            stamp_semi_join_strategy(left, profile, sliced, ctx, ancestor_pushes);
16080            stamp_semi_join_strategy(right, profile, sliced, ctx, ancestor_pushes);
16081        }
16082        PlanNode::CustomNode(op) => {
16083            for child in &mut op.children {
16084                stamp_semi_join_strategy(child, profile, sliced, ctx, ancestor_pushes);
16085            }
16086        }
16087        PlanNode::Filter { inner, exists, .. } => {
16088            stamp_semi_join_strategy(inner, profile, sliced, ctx, ancestor_pushes);
16089            for clause in exists {
16090                // EXISTS is evaluated through OpenNode, which does not
16091                // consult JoinStrategy; no build-once stamp below it.
16092                stamp_semi_join_strategy(&mut clause.body, profile, true, ctx, &[]);
16093            }
16094        }
16095        PlanNode::Extend { inner, .. }
16096        | PlanNode::Distinct { inner, .. }
16097        | PlanNode::Sort { inner, .. }
16098        | PlanNode::Group { inner, .. }
16099        | PlanNode::JoinGraphVar { inner, .. } => {
16100            stamp_semi_join_strategy(inner, profile, sliced, ctx, ancestor_pushes)
16101        }
16102        PlanNode::Slice { inner, .. } => {
16103            // `execute_slice` runs through OpenNode when no ancestor push is
16104            // active; OpenNode ignores JoinStrategy. Suppress the build-once
16105            // stamps below the Slice, as the root Slice already does.
16106            stamp_semi_join_strategy(inner, profile, true, ctx, ancestor_pushes)
16107        }
16108        PlanNode::SubSelect(sub) => {
16109            // A SubSelect's inner executes eagerly; a Slice inside it is
16110            // caught by the arm above.
16111            stamp_semi_join_strategy(&mut sub.inner, profile, sliced, ctx, &[])
16112        }
16113        _ => {}
16114    }
16115}
16116
16117/// Test-only entry to the build-once stamp pass: the executor fixtures build
16118/// the tree by hand and need the same pass `from_prepared` runs, without the
16119/// planner's seating.
16120#[cfg(test)]
16121pub(crate) fn stamp_semi_join_strategy_for_test(
16122    root: &mut PlanNode,
16123    profile: Option<&StatsProfile>,
16124    sliced: bool,
16125    ctx: Option<&crate::context::QueryContext>,
16126) {
16127    stamp_semi_join_strategy(root, profile, sliced, ctx, &[]);
16128}
16129
16130/// Whether a scan standing on a join's right side may be replaced by a
16131/// semi-join key set.
16132///
16133/// Two independent facts:
16134///
16135/// - **No payload:** every column the scan would materialize — live *and*
16136///   counted — is a join key. Counted columns are kept because a count above
16137///   the join depends on their multiplicity.
16138/// - **The right produces at most one row per key:** the scan is key-unique
16139///   (see [`scan_is_key_unique`]). The semi join removes the right's row
16140///   multiplicity from the whole left row, so a key's bag mark alone is not
16141///   enough: a repeated right key multiplies every left column, and a plain
16142///   `COUNT` of a left column observes that multiplication. Key-uniqueness is
16143///   the proof that no multiplicity is removed.
16144///
16145/// Plain `COUNT(*)` needs no separate gate. A non-key-unique right has a
16146/// second name slot, dead or live, so key-uniqueness refuses it; a key-unique
16147/// right has no row multiplicity to lose, so `COUNT(*)` is row-identical. As a
16148/// second guard, liveness promotes a dead right payload to `Counted` under
16149/// `COUNT(*)`, and `materialized_variables` includes counted columns.
16150///
16151/// A specialized scan (`domain_scan`, `head_scan`, `domain_counts`,
16152/// `head_scan_counts` — [`ScanOp::has_specialized_rpc`]) is excluded even
16153/// though [`fetch_once_stampable`] admits one count shape: its output is not
16154/// the pattern's rows, so neither the payload nor the uniqueness argument
16155/// applies.
16156///
16157/// The key count is capped at the hash kernel's eight-column limit: beyond it
16158/// the hash road returns `ExecError::JoinKeyTooWide`, while `SemiJoinSet` has
16159/// a wide form. The strategy must not make a join representable that its
16160/// fallback road would reject.
16161fn semi_eligible_scan_right(scan: &ScanOp, hash_keys: &[Variable]) -> bool {
16162    if hash_keys.is_empty() || hash_keys.len() > 8 || scan.has_specialized_rpc() {
16163        return false;
16164    }
16165    let materialized = scan.materialized_variables();
16166    if !materialized
16167        .iter()
16168        .all(|variable| hash_keys.contains(variable))
16169    {
16170        return false;
16171    }
16172    scan_is_key_unique(scan, hash_keys)
16173}
16174
16175/// Whether the scan can bind its join key at most once per row.
16176///
16177/// A single triple pattern whose key occupies exactly one slot and whose other
16178/// name slots are ground is a set of distinct triples, so one key value appears
16179/// at most once per fixed graph.
16180///
16181/// The graph must be fixed. A ground graph name or the default graph passes;
16182/// a **one-term allow-list** is a statically fixed graph and passes, including
16183/// when a graph variable is present but confined by that filter. An
16184/// unconstrained graph variable, a multi-term allow-list, and a block-list can
16185/// expose the same triple in several graphs and are refused.
16186/// [`ScanOp::merge_default_graph`] is refused because the merge can surface the
16187/// same triple once per named graph; the multi-graph windows already set it,
16188/// but the uniqueness claim keeps its own guard rather than depending on that.
16189fn scan_is_key_unique(scan: &ScanOp, hash_keys: &[Variable]) -> bool {
16190    let [key] = hash_keys else {
16191        return false;
16192    };
16193    let fixed_by_filter = scan
16194        .graph_filter
16195        .as_ref()
16196        .is_some_and(|filter| !filter.is_exclude() && filter.len() == 1);
16197    let fixed_default = scan.graph.is_none() && scan.graph_filter.is_none();
16198    if scan.merge_default_graph || !(fixed_by_filter || fixed_default) {
16199        return false;
16200    }
16201    let mut key_slots = 0usize;
16202    for slot in [&scan.subject, &scan.predicate, &scan.object] {
16203        match slot {
16204            Some(variable) if variable == key => key_slots += 1,
16205            Some(_) => return false,
16206            None => {}
16207        }
16208    }
16209    key_slots == 1
16210}
16211
16212/// Estimated distinct head terms of a domain / head-scan rewrite.
16213///
16214/// Predicate heads use the exact predicate map size (the whole named-node
16215/// predicate namespace this profile observed). Term heads use the
16216/// per-predicate HLL, which requires the scan to name its predicate — shapes
16217/// with an unbound predicate (`SubjectDomain`, the bare scans) have no head
16218/// sketch and return `None`.
16219pub(crate) fn head_domain_estimate(
16220    profile: &StatsProfile,
16221    scan: &ScanOp,
16222    head_slot: PatternSlot,
16223) -> Option<u64> {
16224    match head_slot {
16225        PatternSlot::Predicate => {
16226            let predicates = profile.predicate_counts.len() as u64;
16227            (predicates > 0).then_some(predicates)
16228        }
16229        PatternSlot::Object | PatternSlot::Subject => {
16230            let predicate = named_node_hash(scan.pattern.predicate.as_ref()?)?;
16231            match head_slot {
16232                PatternSlot::Subject => profile.subject_domain(&predicate),
16233                _ => profile.object_domain(&predicate),
16234            }
16235        }
16236    }
16237}
16238
16239fn estimate_bound_scan(
16240    profile: Option<&StatsProfile>,
16241    pattern: &EncodedTriplePattern,
16242    fallback_rows: u64,
16243) -> u64 {
16244    if pattern_is_point_lookup(pattern) {
16245        return 1;
16246    }
16247    match profile {
16248        Some(p) if !p.is_empty() => estimate_pattern(p, pattern).max(1),
16249        _ => fallback_rows.max(1),
16250    }
16251}
16252
16253pub(crate) fn estimate_unclamped_scan_rows(profile: Option<&StatsProfile>, scan: &ScanOp) -> u64 {
16254    if let Some(kind) = scan.domain_scan {
16255        return scan_head_estimated_rows(profile, scan, kind.head_slot());
16256    }
16257    if let Some(kind) = scan.head_scan {
16258        return scan_head_estimated_rows(profile, scan, kind.head_slot());
16259    }
16260    if scan.will_collapse() {
16261        let keys = scan.collapse_keys();
16262        let rows = estimate_bound_scan(profile, &scan.pattern, scan.produced_row_count_estimate);
16263        // DISTINCT ON output is bounded by both the pre-collapse row count and
16264        // the key domain. The pattern-aware estimate stays authoritative when
16265        // other bound slots are selective (e.g. `?class a <owl:Class>`: the
16266        // key `?class` reads the global rdf:type subject HLL, the ground
16267        // object reads the exact class map — `min` keeps 843, not 74M).
16268        // The domain may only sharpen a single live key; extra keys add
16269        // distinctness no single-var HLL sees (distinct pairs >= distinct
16270        // first-key values), so a multi-key collapse keeps the row count.
16271        let cost = match keys.as_slice() {
16272            [only] => join_key_domain_for(profile, scan, std::slice::from_ref(only))
16273                .map_or(rows, |domain| domain.min(rows)),
16274            _ => rows,
16275        };
16276        return cost.max(1);
16277    }
16278    estimate_bound_scan(profile, &scan.pattern, scan.produced_row_count_estimate)
16279}
16280
16281/// Whether the arm's whole-read estimate is EVIDENCE rather than a
16282/// fallback. A point lookup's single row is structural, not estimated.
16283/// Otherwise the profile must be non-empty AND carry a sketch for the
16284/// pattern's own bound predicate: `estimate_pattern` reports a
16285/// never-observed predicate as **1** — a fictional arm size — so a
16286/// profile sketching OTHER predicates must not stamp (or price) this arm
16287/// on that number (the sparse-profile hole a bare `!is_empty` check
16288/// leaves open). Unbound `?p` prices from the store-level uniform model,
16289/// which any non-empty profile carries. Both fetch-once consumers gate
16290/// on this through `fetch_once_verdict`, so a sparse-stats plan cannot
16291/// stamp (or price) a whole-arm drain on a fictional arm size.
16292pub(crate) fn whole_read_rows_known(profile: Option<&StatsProfile>, scan: &ScanOp) -> bool {
16293    pattern_is_point_lookup(&scan.pattern)
16294        || profile.is_some_and(|p| !p.is_empty() && p.has_predicate_sketch(&scan.pattern))
16295}
16296
16297/// Estimated output rows of a domain / head-scan rewrite: the join-key domain
16298/// of the head variable (per-constraint object HLL, per-subject predicate
16299/// HLL, class map, ...) when the profile carries one, else the pattern
16300/// estimate.
16301fn scan_head_estimated_rows(
16302    profile: Option<&StatsProfile>,
16303    scan: &ScanOp,
16304    head_slot: PatternSlot,
16305) -> u64 {
16306    if let Some(head) = scan_slot_variable(scan, head_slot)
16307        && let Some(domain) = join_key_domain_for(profile, scan, std::slice::from_ref(head))
16308    {
16309        return domain.max(1);
16310    }
16311    estimate_bound_scan(profile, &scan.pattern, scan.produced_row_count_estimate).max(1)
16312}
16313
16314/// Slot variable for a `PatternSlot` (no graph variant: head scans never
16315/// project G).
16316pub(crate) fn scan_slot_variable(scan: &ScanOp, slot: PatternSlot) -> Option<&Variable> {
16317    match slot {
16318        PatternSlot::Subject => scan.subject.as_ref(),
16319        PatternSlot::Predicate => scan.predicate.as_ref(),
16320        PatternSlot::Object => scan.object.as_ref(),
16321    }
16322}
16323
16324/// Every variable mentioned anywhere in `node`: output slots plus every
16325/// expression (filters, EXISTS bodies, BIND, sort/group/aggregate inputs).
16326///
16327/// Over-approximation on purpose — the OPTIONAL arm reorder uses it to
16328/// prove an optional arm cannot reference the sibling arm's first-bound
16329/// variables, and a false "mentions" only loses an optimization, never
16330/// correctness.
16331fn collect_subtree_variables(node: &PlanNode, out: &mut Vec<Variable>) {
16332    fn push_var(out: &mut Vec<Variable>, variable: Variable) {
16333        if !out.contains(&variable) {
16334            out.push(variable);
16335        }
16336    }
16337    let vars = node.output_vars();
16338    for bound in vars.always_bound.iter().chain(vars.maybe_unbound.iter()) {
16339        push_var(out, bound.clone());
16340    }
16341    match node {
16342        PlanNode::Filter {
16343            inner,
16344            early,
16345            residual,
16346            exists,
16347            ..
16348        } => {
16349            for expression in early.iter().chain(residual.iter()) {
16350                out.extend(variables_in_expression(expression));
16351            }
16352            for clause in exists {
16353                collect_subtree_variables(&clause.body, out);
16354            }
16355            collect_subtree_variables(inner, out);
16356        }
16357        PlanNode::LeftJoin {
16358            left,
16359            right,
16360            early_filter,
16361            residual_filter,
16362            ..
16363        } => {
16364            for expression in early_filter.iter().chain(residual_filter.iter()) {
16365                out.extend(variables_in_expression(expression));
16366            }
16367            collect_subtree_variables(left, out);
16368            collect_subtree_variables(right, out);
16369        }
16370        PlanNode::Extend {
16371            inner, expression, ..
16372        } => {
16373            out.extend(variables_in_expression(expression));
16374            collect_subtree_variables(inner, out);
16375        }
16376        PlanNode::Sort { inner, keys } => {
16377            for key in keys {
16378                out.extend(variables_in_expression(&key.expression));
16379            }
16380            collect_subtree_variables(inner, out);
16381        }
16382        PlanNode::Group {
16383            inner,
16384            variables,
16385            aggregates,
16386            ..
16387        } => {
16388            for variable in variables {
16389                push_var(out, variable.clone());
16390            }
16391            for (variable, aggregate) in aggregates {
16392                push_var(out, variable.clone());
16393                match aggregate {
16394                    AggregateExpression::CountSolutions { .. } => {}
16395                    AggregateExpression::FunctionCall { expr, .. } => {
16396                        out.extend(variables_in_expression(expr));
16397                    }
16398                }
16399            }
16400            collect_subtree_variables(inner, out);
16401        }
16402        PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
16403            collect_subtree_variables(left, out);
16404            collect_subtree_variables(right, out);
16405        }
16406        PlanNode::SubSelect(sub) => collect_subtree_variables(&sub.inner, out),
16407        PlanNode::CustomNode(op) => {
16408            for variable in &op.variables {
16409                push_var(out, variable.clone());
16410            }
16411            for child in &op.children {
16412                collect_subtree_variables(child, out);
16413            }
16414        }
16415        _ => {}
16416    }
16417}
16418
16419/// Whether two OPTIONAL arms over the same required core may sit in
16420/// EITHER relative order: both arms' join keys are bound by the
16421/// REQUIRED core (`keys ⊆ always_bound(L)` — any order still binds
16422/// them), and the LATER arm's scope — its traveling filters plus every
16423/// variable mentioned in its subtree — contains no variable FIRST-
16424/// PRODUCED by the earlier arm, whether that arm binds it always or
16425/// maybe (a maybe-bound output — e.g. from a nested OPTIONAL inside
16426/// the earlier arm — read by the later arm's FILTER evaluates
16427/// differently across the swap: bound-then-filtered in query order,
16428/// error-and-always-miss once the later arm runs first). The earlier
16429/// arm's scope cannot mention the later arm's variables (it was
16430/// lowered with them out of scope), so the one direction suffices.
16431/// Used pairwise by [`reorder_independent_optional_arms`] to find the
16432/// maximal independent top run of a LeftJoin spine. Key ⊆ core matters
16433/// in both directions because a reordered arm joins above whatever
16434/// runs before it, which only preserves the core's always-bound
16435/// variables.
16436fn optional_pair_rotation_safe(
16437    core: &PlanNode,
16438    arm_a: &PlanNode,
16439    keys_a: &[Variable],
16440    arm_b: &PlanNode,
16441    keys_b: &[Variable],
16442    b_scope_expressions: [&Option<Expression>; 2],
16443) -> bool {
16444    let core_bound = &core.output_vars().always_bound;
16445    if !keys_a.iter().all(|key| core_bound.contains(key))
16446        || !keys_b.iter().all(|key| core_bound.contains(key))
16447    {
16448        return false;
16449    }
16450    // First-produced by A = every variable A's output can bind (always
16451    // OR maybe — `all()`), minus the core's always-bound. A variable A
16452    // can produce is a real dependency when the later arm's scope
16453    // mentions it, even bound-only-sometimes: "maybe" is exactly what
16454    // changes evaluation across the swap. A producing nothing new
16455    // cannot be depended on.
16456    let a_all = arm_a.output_vars().all();
16457    let a_first: Vec<&Variable> = a_all.iter().filter(|v| !core_bound.contains(*v)).collect();
16458    if a_first.is_empty() {
16459        return true;
16460    }
16461    let mut b_mentions: Vec<Variable> = Vec::new();
16462    for expression in b_scope_expressions.into_iter().flatten() {
16463        b_mentions.extend(variables_in_expression(expression));
16464    }
16465    collect_subtree_variables(arm_b, &mut b_mentions);
16466    a_first.iter().all(|v| !b_mentions.contains(*v))
16467}
16468
16469/// OPTIONAL reorder materiality: the reordered shape's summed stage
16470/// sizes (inner intermediate + final output) — the suffix-greedy arm
16471/// reorder, or the delay-through-join rewrite — must beat the current
16472/// shape's by this many percent, so refinalize's second round can never
16473/// flip a rewrite back (strict-improvement ratchet — no ping-pong).
16474const LEFTJOIN_REORDER_MARGIN_PERCENT: u64 = 15;
16475
16476/// Reorder independent OPTIONAL arms on a shared required core. Flatten
16477/// the LeftJoin spine `LeftJoin(...(core, A1), …, Ak)` into its core and
16478/// arms (query order, A1 first), find the maximal TOP run of
16479/// pairwise-independent arms ([`optional_pair_rotation_safe`] per
16480/// ordered pair — for i < j, arm_j's scope must not mention any
16481/// variable arm_i first-PRODUCES, always- or maybe-bound, the one
16482/// direction SPARQL scoping leaves to check), and rebuild that run in
16483/// greedy stage order: repeatedly
16484/// attach the arm whose `estimate_left_join_rows` stage is smallest, so
16485/// the big-fan-out emission stage runs against the smallest
16486/// intermediate — put the small-fan-out optional first. Commits only
16487/// when the greedy order differs from query order and its summed
16488/// stages beat the query order's by [`LEFTJOIN_REORDER_MARGIN_PERCENT`]
16489/// — one margin on the whole reorder (the old adjacent-pair rotation
16490/// needed every single swap to clear the margin alone, which blocked
16491/// multi-step improvements the pipeline's two rounds could not bubble
16492/// through). Arms below the run stay in query order: a dependent pair
16493/// is frozen in relative order, and only the arms above it — which
16494/// never read what it first-binds — are free to move. Every arm torn
16495/// down is marks-cleared before the rebuild (stale marks travel with
16496/// the arms and claim-skip would keep them, so only a cleaned scan
16497/// lets the boundary restamp re-claim); the sub-chain below the run is
16498/// left intact, marks and stamped metas included. For two arms this is
16499/// exactly the old rotation's decision on the same numbers. Returns
16500/// whether a reorder happened (the caller then gives the fresh inner
16501/// join its refinalize pass).
16502fn reorder_independent_optional_arms(node: &mut PlanNode, profile: Option<&StatsProfile>) -> bool {
16503    // Probe on borrows: flatten the spine, find the run, cost both
16504    // orders. Nothing is taken apart until the margin says yes.
16505    let (run_start, order);
16506    {
16507        struct ArmRef<'a> {
16508            right: &'a PlanNode,
16509            hash_keys: &'a [Variable],
16510            early_filter: &'a Option<Expression>,
16511            residual_filter: &'a Option<Expression>,
16512        }
16513        // Walk the left spine collecting arms outermost-first, plus the
16514        // spine nodes so the run's required-side starting rows read off
16515        // the node that stays below it (spine[i] = the node after
16516        // peeling i arms; spine.last() = the core).
16517        let mut arms_desc: Vec<ArmRef> = Vec::new();
16518        let mut spine: Vec<&PlanNode> = Vec::new();
16519        let mut cursor: &PlanNode = node;
16520        while let PlanNode::LeftJoin {
16521            left,
16522            right,
16523            hash_keys,
16524            early_filter,
16525            residual_filter,
16526            ..
16527        } = cursor
16528        {
16529            spine.push(cursor);
16530            arms_desc.push(ArmRef {
16531                right,
16532                hash_keys,
16533                early_filter,
16534                residual_filter,
16535            });
16536            cursor = left;
16537        }
16538        let core = cursor;
16539        spine.push(core);
16540        // Query order: arms[0] is the FIRST optional (innermost).
16541        arms_desc.reverse();
16542        let arms = arms_desc;
16543        let k = arms.len();
16544        if k < 2 {
16545            return false;
16546        }
16547        // Maximal top run arms[m..k]: extend downward from the outermost
16548        // arm while the candidate is pairwise independent with every arm
16549        // already collected. An arm whose keys are not core-bound also
16550        // fails its pairs (the gate checks both arms' keys), which keeps
16551        // it — and anything it depends on — below the run.
16552        let mut m = k;
16553        'extend: while m > 0 {
16554            let candidate = m - 1;
16555            for j in candidate + 1..k {
16556                if !optional_pair_rotation_safe(
16557                    core,
16558                    arms[candidate].right,
16559                    arms[candidate].hash_keys,
16560                    arms[j].right,
16561                    arms[j].hash_keys,
16562                    [arms[j].early_filter, arms[j].residual_filter],
16563                ) {
16564                    break 'extend;
16565                }
16566            }
16567            m = candidate;
16568        }
16569        if k - m < 2 {
16570            return false;
16571        }
16572        // The required side the run builds on: spine[k - m] is the node
16573        // below the run (its right arm is arms[m]).
16574        let below = spine[k - m];
16575        // Query-order stages across the run. The core serves as the
16576        // stage model's domain stand-in — a LeftJoin's key domains flow
16577        // from its required side, so every intermediate LeftJoin in the
16578        // chain resolves to the core's domains (the rotation's
16579        // documented equivalence, now used uniformly).
16580        let mut rows = below.produced_row_count_estimate();
16581        let mut current_sum = 0u64;
16582        for arm in &arms[m..] {
16583            let e = estimate_left_join_rows(rows, core, arm.right, arm.hash_keys, profile);
16584            current_sum = current_sum.saturating_add(e);
16585            rows = e;
16586        }
16587        // Greedy order: repeatedly attach the smallest next stage (ties
16588        // keep query order — strict < over the remaining list).
16589        let mut remaining: Vec<usize> = (m..k).collect();
16590        let mut greedy_order: Vec<usize> = Vec::new();
16591        let mut greedy_sum = 0u64;
16592        let mut rows = below.produced_row_count_estimate();
16593        while !remaining.is_empty() {
16594            let mut best: Option<(usize, u64)> = None;
16595            for &idx in &remaining {
16596                let e = estimate_left_join_rows(
16597                    rows,
16598                    core,
16599                    arms[idx].right,
16600                    arms[idx].hash_keys,
16601                    profile,
16602                );
16603                if best.is_none_or(|(_, best_e)| e < best_e) {
16604                    best = Some((idx, e));
16605                }
16606            }
16607            let (idx, e) = best.expect("remaining is non-empty");
16608            remaining.retain(|&r| r != idx);
16609            greedy_order.push(idx);
16610            greedy_sum = greedy_sum.saturating_add(e);
16611            rows = e;
16612        }
16613        if greedy_order == (m..k).collect::<Vec<_>>()
16614            || greedy_sum.saturating_mul(100)
16615                >= current_sum.saturating_mul(100 - LEFTJOIN_REORDER_MARGIN_PERCENT)
16616        {
16617            return false;
16618        }
16619        run_start = m;
16620        order = greedy_order;
16621    }
16622    // Commit: peel the run's arms off the owned chain — the sub-chain
16623    // below stays intact (marks and stamped metas untouched) — clear
16624    // each peeled arm, and rebuild in greedy order with placeholder
16625    // metas (the caller's refinalize recursion stamps the two frames
16626    // after the children settle).
16627    let taken = std::mem::replace(node, PlanNode::Unit);
16628    let mut below = taken;
16629    // One peeled OPTIONAL arm: its subtree, join keys, and traveling
16630    // filters, kept together through the reorder.
16631    type PeeledArm = (
16632        PlanNode,
16633        Vec<Variable>,
16634        Option<Expression>,
16635        Option<Expression>,
16636    );
16637    let mut peeled: Vec<PeeledArm> = Vec::new();
16638    for _ in 0..order.len() {
16639        let PlanNode::LeftJoin {
16640            left,
16641            right,
16642            hash_keys,
16643            early_filter,
16644            residual_filter,
16645            ..
16646        } = below
16647        else {
16648            unreachable!("spine shape checked above");
16649        };
16650        peeled.push((*right, hash_keys, early_filter, residual_filter));
16651        below = *left;
16652    }
16653    peeled.reverse(); // query order within the run
16654    let mut slots = peeled.into_iter().map(Some).collect::<Vec<_>>();
16655    let mut inner = below;
16656    for &idx in &order {
16657        let (mut arm, hash_keys, early_filter, residual_filter) = slots[idx - run_start]
16658            .take()
16659            .expect("each greedy index used once");
16660        clear_broadcast_marks(&mut arm);
16661        inner = PlanNode::LeftJoin {
16662            left: Box::new(inner),
16663            right: Box::new(arm),
16664            hash_keys,
16665            early_filter,
16666            residual_filter,
16667            // Placeholder — refinalize re-stamps the driver-side domains
16668            // with the settled arm (same pass that stamps the models).
16669            probe_key_domains: Vec::new(),
16670            probe_key_overlap_milli: Vec::new(),
16671            meta: LeftJoinMeta {
16672                produced_row_count_estimate: 1,
16673                own_push_removed_row_count_estimate: 1,
16674            },
16675        };
16676    }
16677    *node = inner;
16678    true
16679}
16680
16681/// Whether `Join(LeftJoin(L, O), R)` may delay to
16682/// `LeftJoin(Join(L, R), O)`: the OPTIONAL's keys are bound by the
16683/// required side L alone, and every variable that crosses between the
16684/// OPTIONAL's scope (O's subtree plus its traveling filters) and R's
16685/// subtree is always-bound in L — docs/modules/ROOT/pages/internals-sparql-optimizations.adoc §2.11's
16686/// `vars(X) ∩ vars(C) ⊆ vars(B)`. That last condition is the
16687/// load-bearing semantic gate: with it, the only bindings O's arm and
16688/// R's subtree share are variables L already pins, so the rewrite
16689/// changes only the ORDER rows merge in, never WHICH rows meet — the
16690/// join key sets are identical on both sides of the rewrite
16691/// (`left_join_output_vars` keeps the required side's always-bound set,
16692/// so `hash_keys_for` derives the same keys for the outer join and for
16693/// `Join(L, R)`), and an always-bound-L variable both sides read
16694/// carries the same value either way because the shared-key join
16695/// equates it. O's first-bound variables are the case the gate exists
16696/// for: an R that reads one would execute before O binds it once
16697/// delayed.
16698fn optional_delay_through_join_safe(
16699    l: &PlanNode,
16700    o: &PlanNode,
16701    o_filter_expressions: [&Option<Expression>; 2],
16702    keys_o: &[Variable],
16703    r: &PlanNode,
16704) -> bool {
16705    let l_bound = &l.output_vars().always_bound;
16706    // The delayed OPTIONAL probes Join(L, R) on keys the required side
16707    // alone must bind (the hash-key construction guarantees this for
16708    // lowered trees; the check keeps hand-built and graph-lowered keys
16709    // honest).
16710    if !keys_o.iter().all(|key| l_bound.contains(key)) {
16711        return false;
16712    }
16713    // §2.11's C = the OPTIONAL arm plus its traveling filters (the
16714    // rotation's scope-collection pattern).
16715    let mut o_scope: Vec<Variable> = Vec::new();
16716    for expression in o_filter_expressions.into_iter().flatten() {
16717        o_scope.extend(variables_in_expression(expression));
16718    }
16719    collect_subtree_variables(o, &mut o_scope);
16720    let mut r_mentions: Vec<Variable> = Vec::new();
16721    collect_subtree_variables(r, &mut r_mentions);
16722    o_scope
16723        .iter()
16724        .filter(|v| r_mentions.contains(*v))
16725        .all(|v| l_bound.contains(v))
16726}
16727
16728/// Delay an independent OPTIONAL through this join:
16729/// `Join(LeftJoin(L, O), R)` ⇒ `LeftJoin(Join(L, R), O)` (either
16730/// orientation — the arm swap may leave the LeftJoin on the right). A
16731/// required pattern written after an OPTIONAL joins against the
16732/// OPTIONAL's inflated output (matched fan-out plus pass-through rows);
16733/// the rewrite lets the required side finish first, and re-unites L
16734/// with R for the arm swap, Broadcast grounding, and ancestor costing
16735/// the lowering-time fold could not give them (a LeftJoin is an
16736/// association barrier there). Gates:
16737/// [`optional_delay_through_join_safe`] plus the §2.11 vacuous-share
16738/// guard (the outer join must have hash keys — an R sharing nothing
16739/// with L would become a cartesian on the OPTIONAL's required side,
16740/// where its rows also form the pass-through floor), plus a strict
16741/// summed-stage improvement under the shared reorder margin. Every
16742/// subtree that moves or dissolves a claiming join (L, O, and R) is
16743/// marks-cleared: the dissolved outer join may have claimed scans in
16744/// any of them (a Broadcast outer join with the LeftJoin as its probe
16745/// claims into L via `claim_broadcast_probe`'s LeftJoin descent), and
16746/// the boundary restamp is claim-skip — it never replaces an existing
16747/// mark, so re-derivation only works on a cleaned scan. Internal
16748/// claims (joins inside L that still exist after the rewrite) are
16749/// re-claimed by that same restamp. Returns whether the rewrite
16750/// fired — the caller then gives the fresh LeftJoin this round's
16751/// LeftJoin-arm treatment by recursing.
16752fn delay_optional_through_join(node: &mut PlanNode, profile: Option<&StatsProfile>) -> bool {
16753    let candidate;
16754    {
16755        let PlanNode::Join {
16756            left,
16757            right,
16758            hash_keys,
16759            ..
16760        } = node
16761        else {
16762            return false;
16763        };
16764        // One LeftJoin arm (left wins when both — one delay per node per
16765        // round; deeper nestings bubble across the pipeline's rounds).
16766        let (lj, r, lj_on_left) = match (left.as_ref(), right.as_ref()) {
16767            (PlanNode::LeftJoin { .. }, _) => (left.as_ref(), right.as_ref(), true),
16768            (_, PlanNode::LeftJoin { .. }) => (right.as_ref(), left.as_ref(), false),
16769            _ => return false,
16770        };
16771        let PlanNode::LeftJoin {
16772            left: l,
16773            right: o,
16774            hash_keys: keys_o,
16775            probe_key_domains: _,
16776            probe_key_overlap_milli: _,
16777            meta: lj_meta,
16778            early_filter,
16779            residual_filter,
16780        } = lj
16781        else {
16782            unreachable!("the LeftJoin arm matched above");
16783        };
16784        // §2.11 vacuous-share guard: R must actually join with L. Empty
16785        // outer hash keys mean this join is already a cartesian; delaying
16786        // would seat that cartesian on the OPTIONAL's required side,
16787        // where its rows also form the pass-through floor.
16788        if hash_keys.is_empty() {
16789            return false;
16790        }
16791        if !optional_delay_through_join_safe(l, o, [early_filter, residual_filter], keys_o, r) {
16792            return false;
16793        }
16794        // Cost, the rotation's summed-stage comparison: current = the
16795        // OPTIONAL's stage + the required join against its output;
16796        // swapped = the re-united required join + the OPTIONAL probing
16797        // it.
16798        let current_final = finalize_inner_join_meta(lj, r, hash_keys, profile).1;
16799        let current_sum = lj_meta
16800            .produced_row_count_estimate
16801            .saturating_add(current_final);
16802        // Pricing the swapped side requires CONSTRUCTING `Join(L, R)`,
16803        // not estimating it in place: `estimate_left_join_rows` needs a
16804        // real `&PlanNode` of the new required side (its key domains
16805        // come from `join_key_domain_for_node`'s Join arm, which
16806        // min-combines the two arms — passing L alone would skip R's
16807        // domain), and the honest price includes the constructor's own
16808        // treatment (arm swap, Broadcast grounding, graph composition),
16809        // all of which change the produced count.
16810        //
16811        // `join_nodes` takes its arms BY VALUE and mutates them, but
16812        // this is the probe phase: the margin gate below can still say
16813        // no, and on "no" the caller expects this tree untouched, so
16814        // the originals stay parked inside `node` (borrowed) and the
16815        // candidate is built from clones. The clone-free alternative —
16816        // disassemble, price, reassemble the original on a decline —
16817        // would have to perfectly restore the old node's metas,
16818        // filters, and key order on the failure path; clone-and-drop
16819        // is the obviously-correct version of the same speculation
16820        // (and the commit below reuses the priced node verbatim, so
16821        // the number the margin compared is the final tree). The
16822        // clones are paid only after the cheap gates above have
16823        // already passed.
16824        //
16825        // Both clones are marks-cleared BEFORE construction: the
16826        // dissolved outer join may have claimed scans under L or R (a
16827        // Broadcast outer join with the LeftJoin side as probe claims
16828        // through `claim_broadcast_probe`'s LeftJoin descent into
16829        // BOTH nested arms), and `restamp_broadcast_marks` is
16830        // claim-skip — an existing `broadcasted` mark is left alone
16831        // and blocks a new claim, never replaced. Clearing here is the
16832        // only way those claims die; the boundary restamp then
16833        // re-derives what the NEW tree justifies (internal claims of
16834        // joins that survived, the new inner join's own probe).
16835        let mut l_clone = (**l).clone();
16836        clear_broadcast_marks(&mut l_clone);
16837        let mut r_clone = r.clone();
16838        clear_broadcast_marks(&mut r_clone);
16839        let join_lr = if lj_on_left {
16840            join_nodes(l_clone, r_clone, profile)
16841        } else {
16842            join_nodes(r_clone, l_clone, profile)
16843        };
16844        let swapped_first = join_lr.produced_row_count_estimate();
16845        let swapped_sum = swapped_first.saturating_add(estimate_left_join_rows(
16846            swapped_first,
16847            &join_lr,
16848            o,
16849            keys_o,
16850            profile,
16851        ));
16852        if swapped_sum.saturating_mul(100)
16853            >= current_sum.saturating_mul(100 - LEFTJOIN_REORDER_MARGIN_PERCENT)
16854        {
16855            return false;
16856        }
16857        // Belt-and-braces on the boundary contract: the delayed shape's
16858        // output variables must match the current node's (set-wise — the
16859        // maybe-unbound ORDER can legitimately differ). The gate proof
16860        // above says they always do; this keeps a future node kind from
16861        // silently breaking it.
16862        fn same_var_set(a: &[Variable], b: &[Variable]) -> bool {
16863            a.len() == b.len() && a.iter().all(|v| b.contains(v))
16864        }
16865        // The current node's schema from its arms (the `PlanNode::Join`
16866        // arm of `output_vars` verbatim) — the probe's mutable bindings
16867        // preclude borrowing `node` itself here.
16868        let original_out = join_output_vars(&left.output_vars(), &right.output_vars());
16869        let delayed_out = left_join_output_vars(&join_lr.output_vars(), &o.output_vars());
16870        if !same_var_set(&original_out.always_bound, &delayed_out.always_bound)
16871            || !same_var_set(&original_out.maybe_unbound, &delayed_out.maybe_unbound)
16872        {
16873            return false;
16874        }
16875        candidate = join_lr;
16876    }
16877    // Commit: O (with its traveling filters and keys) moves above the
16878    // candidate join. O is the one subtree moved as its ORIGINAL (not a
16879    // clone), so its clear happens here rather than before construction;
16880    // same reason as the clones — the dissolved join's LeftJoin-probe
16881    // descent may have claimed scans inside it, and claim-skip means
16882    // only `clear_broadcast_marks` retires a mark. L's and R's originals
16883    // drop entirely — their pre-cleared clones live in the candidate.
16884    let taken = std::mem::replace(node, PlanNode::Unit);
16885    let PlanNode::Join { left, right, .. } = taken else {
16886        unreachable!("shape checked above");
16887    };
16888    let lj = if matches!(*left, PlanNode::LeftJoin { .. }) {
16889        left
16890    } else {
16891        right
16892    };
16893    let PlanNode::LeftJoin {
16894        right: mut o,
16895        hash_keys: keys_o,
16896        early_filter,
16897        residual_filter,
16898        ..
16899    } = *lj
16900    else {
16901        unreachable!("shape checked above");
16902    };
16903    clear_broadcast_marks(&mut o);
16904    // Placeholder meta and coverage domains — the caller's refinalize
16905    // recursion stamps the two frames and the driver-side key domains after
16906    // the candidate join settles (the rotation's pattern).
16907    *node = PlanNode::LeftJoin {
16908        left: Box::new(candidate),
16909        right: o,
16910        hash_keys: keys_o,
16911        early_filter,
16912        residual_filter,
16913        probe_key_domains: Vec::new(),
16914        probe_key_overlap_milli: Vec::new(),
16915        meta: LeftJoinMeta {
16916            produced_row_count_estimate: 1,
16917            own_push_removed_row_count_estimate: 1,
16918        },
16919    };
16920    true
16921}
16922
16923/// Physical planning pass after identity fold: recost, maybe swap inner-join
16924/// arms, refresh [`JoinStrategy`], and ground Broadcast probe arms
16925/// (ground-only; allow-list marks are re-derived afterwards by
16926/// [`restamp_broadcast_marks`], their sole writer).
16927///
16928/// Execute and EXPLAIN share this tree; it is not EXPLAIN-only.
16929#[cfg(test)]
16930fn refinalize_joins_without_ctx(node: &mut PlanNode, profile: Option<&StatsProfile>) {
16931    refinalize_joins(node, profile, None)
16932}
16933
16934/// Same pass with an optional query context, for the `join-seat-shadow`
16935/// debug log (the wrapper above is the context-less entry the tests and the
16936/// context-free pipelines use).
16937fn refinalize_joins(
16938    node: &mut PlanNode,
16939    profile: Option<&StatsProfile>,
16940    ctx: Option<&crate::context::QueryContext>,
16941) {
16942    match node {
16943        // Opaque leaf: the op's estimate is static (the plugin stamped it at
16944        // rewrite time); children (future wrapping ops) still recost.
16945        PlanNode::CustomNode(op) => {
16946            for child in &mut op.children {
16947                refinalize_joins(child, profile, ctx);
16948            }
16949        }
16950        PlanNode::Scan(scan) => {
16951            // Recost to the intrinsic pattern estimate, then bound at any
16952            // ancestor push's return bound (`ancestor_push_return_bound`):
16953            // that bound is the true whole read for EVERY seating of joins
16954            // below the claimer, so an inner join must not re-price an
16955            // ancestor-pushed arm at catalog size. Bounding at the stored
16956            // value (not min-with-the-old-cell) keeps the reset honest — a
16957            // clamp whose claim mark vanished is gone with it
16958            // (`clear_broadcast_marks` removed the bound too).
16959            let unclamped = estimate_unclamped_scan_rows(profile, scan);
16960            scan.produced_row_count_estimate =
16961                unclamped.min(scan.ancestor_push_return_bound.unwrap_or(u64::MAX));
16962        }
16963        PlanNode::Path(path) => recost_path(path),
16964        PlanNode::Join {
16965            left,
16966            right,
16967            hash_keys,
16968            probe_key_domains,
16969            probe_key_overlap_milli,
16970            rhs_hostable_keys,
16971            meta,
16972        } => {
16973            refinalize_joins(left, profile, ctx);
16974            refinalize_joins(right, profile, ctx);
16975            let taken_left = std::mem::replace(left.as_mut(), PlanNode::Unit);
16976            let taken_right = std::mem::replace(right.as_mut(), PlanNode::Unit);
16977            let (mut taken_left, mut taken_right) =
16978                maybe_swap_scan_union(taken_left, taken_right, hash_keys, profile);
16979            // The driver's read is ownership-aware (`driver_whole_read_rows`): a
16980            // foreign ancestor push bounds the arm's whole read in every
16981            // seating, while this join's OWN claim bound is
16982            // orientation-dependent and must not price a phantom-cheap
16983            // driver (the tenant-union flip: the probe road's 80-row return
16984            // is not a driving read of the 50k catalog arm).
16985            let left_rows = driver_whole_read_rows(&taken_left, hash_keys, profile);
16986            let right_rows = driver_whole_read_rows(&taken_right, hash_keys, profile);
16987            let left_domain = join_key_domain_for_allow_list(
16988                profile,
16989                &taken_left,
16990                &taken_right,
16991                hash_keys,
16992                left_rows,
16993            );
16994            let right_domain = join_key_domain_for_allow_list(
16995                profile,
16996                &taken_right,
16997                &taken_left,
16998                hash_keys,
16999                right_rows,
17000            );
17001            let mut swapped = false;
17002            // Allow-list size first (Broadcast small-left), then estimated
17003            // rows: after identity fold both arms can share domain 1 while
17004            // one is a 910k class scan and the other is a point lookup.
17005            let left_cost = driver_cost(left_rows, left_domain);
17006            let right_cost = driver_cost(right_rows, right_domain);
17007            let right_is_point = taken_right
17008                .as_scan()
17009                .is_some_and(|s| pattern_is_point_lookup(&s.pattern));
17010            let left_is_point = taken_left
17011                .as_scan()
17012                .is_some_and(|s| pattern_is_point_lookup(&s.pattern));
17013            // SEAT COSTS (both seatings, always priced): the whole-seating
17014            // model — page-sized driver chunks, per-page key lists, the
17015            // runtime's own coverage predicate and drop guard. Off (the
17016            // context default) it shadows the legacy `driver_cost`
17017            // decision and logs disagreements as `join-seat-shadow`; on it
17018            // DECIDES, with the structural point-lookup override kept on
17019            // top (the totals may only agree with it), and divergent seats
17020            // log as `join-seat-totals`. See `seat_cost_total`.
17021            let seat_by_totals =
17022                ctx.is_some_and(crate::context::QueryContext::seat_by_total_cost);
17023            let (left_seat, right_seat) = if !hash_keys.is_empty() {
17024                (
17025                    seat_cost_total(profile, &taken_left, &taken_right, hash_keys, ctx, None),
17026                    seat_cost_total(profile, &taken_right, &taken_left, hash_keys, ctx, None),
17027                )
17028            } else {
17029                (SeatCost { rows: 0, seeks: 0 }, SeatCost { rows: 0, seeks: 0 })
17030            };
17031            let totals_prefers_right = !hash_keys.is_empty() && seat_beats(right_seat, left_seat);
17032            let old_swaps = !hash_keys.is_empty()
17033                && ((right_cost, right_rows) < (left_cost, left_rows)
17034                    || (right_is_point && !left_is_point));
17035            let totals_swaps = totals_prefers_right || (right_is_point && !left_is_point);
17036            if seat_by_totals
17037                && !hash_keys.is_empty()
17038                && totals_swaps != old_swaps
17039                && let Some(ctx) = ctx
17040            {
17041                ctx.log(
17042                    crate::context::LogLevel::Debug,
17043                    &format!(
17044                        "join-seat-totals: keys={hash_keys:?} applied={} \
17045                         old_would={} driver_costs(l={left_cost} r={right_cost}) \
17046                         totals(left={}:{}s right={}:{}s) rows(l={left_rows} \
17047                         r={right_rows})",
17048                        if totals_swaps { "right" } else { "left" },
17049                        if old_swaps { "right" } else { "left" },
17050                        left_seat.rows,
17051                        left_seat.seeks,
17052                        right_seat.rows,
17053                        right_seat.seeks,
17054                    ),
17055                );
17056            }
17057            if !seat_by_totals
17058                && totals_prefers_right != old_swaps
17059                && let Some(ctx) = ctx
17060            {
17061                ctx.log(
17062                    crate::context::LogLevel::Debug,
17063                    &format!(
17064                        "join-seat-shadow: keys={hash_keys:?} old={} new={} \
17065                         driver_costs(l={left_cost} r={right_cost}) \
17066                         totals(left={}:{}s right={}:{}s) rows(l={left_rows} \
17067                         r={right_rows})",
17068                        if old_swaps { "right" } else { "left" },
17069                        if totals_prefers_right { "right" } else { "left" },
17070                        left_seat.rows,
17071                        left_seat.seeks,
17072                        right_seat.rows,
17073                        right_seat.seeks,
17074                    ),
17075                );
17076            }
17077            let swaps = if seat_by_totals && !hash_keys.is_empty() {
17078                totals_swaps
17079            } else {
17080                old_swaps
17081            };
17082            if swaps {
17083                std::mem::swap(&mut taken_left, &mut taken_right);
17084                swapped = true;
17085            }
17086            if swapped {
17087                // Old probe arm is now LEFT — drop allow-list marks, keep grounded.
17088                clear_broadcast_marks(&mut taken_left);
17089            }
17090            let (strategy, produced, own_push_removed) =
17091                finalize_inner_join_meta(&taken_left, &taken_right, hash_keys, profile);
17092            meta.strategy = strategy;
17093            meta.produced_row_count_estimate = produced;
17094            // Each field keeps its own frame: `produced` prices a path
17095            // probe at the values-broadcast bound (the push narrows it),
17096            // `own_push_removed` prices a direct right-arm path/claimed scan
17097            // at its bare pattern cost — the `(price ~N)` EXPLAIN shows.
17098            // See the JoinMeta field docs for the one-level limitation.
17099            meta.own_push_removed_row_count_estimate = own_push_removed;
17100            // Re-derive the key order on the post-swap arms: the swap can
17101            // flip which side drives, and the first key is what the runtime
17102            // broadcasts first and the restamp claim names.
17103            reorder_hash_keys_by_probe_return(
17104                hash_keys,
17105                probe_key_domains,
17106                probe_key_overlap_milli,
17107                &taken_left,
17108                &taken_right,
17109                profile);
17110            // The stamped coverage domains follow the seating: the probe is
17111            // the current right arm — the relation the pushed lists filter.
17112            *probe_key_domains = stamp_probe_key_domains(profile, &taken_right, hash_keys);
17113            // The containment stamps follow the seating too — the overlap
17114            // is a DRIVER∩PROBE pair property, so the swap re-resolves it
17115            // for the new orientation (one resolution, the shared helper).
17116            *probe_key_overlap_milli =
17117                stamp_probe_key_overlaps(profile, &taken_left, &taken_right, hash_keys);
17118            // Unconditional under the final strategy — swap or not, previously
17119            // Broadcast or not: grounding is structural work whose grounds the
17120            // conflict re-check below and ancestor costing consume in this
17121            // same unwind. Allow-list marks are re-derived by
17122            // `restamp_broadcast_marks` at the pass boundary (sole writer).
17123            if strategy == JoinStrategy::Broadcast && !hash_keys.is_empty() {
17124                ground_and_recost_broadcasted_arm(&taken_left, &mut taken_right, hash_keys, profile);
17125            }
17126            if !hash_keys.is_empty() {
17127                compose_graph_from_sibling(&taken_left, &mut taken_right, hash_keys, profile, true);
17128                compose_graph_from_sibling(&taken_right, &mut taken_left, hash_keys, profile, true);
17129            }
17130            clamp_broadcast_probe_estimates(&taken_left, &mut taken_right, hash_keys, profile);
17131            // Stamped from the FINAL right arm — after the grounding and
17132            // the graph compose above, either of which can reshape the
17133            // probe's scans (a grounded slot stops hosting its variable;
17134            // a composed graph slot starts hosting the graph variable) —
17135            // so the set describes the arm as it will execute. A stamp
17136            // taken before the reshaping would go stale in both
17137            // directions: admitting pushes with no consumer (dead wire
17138            // weight) and declining pushes the new arm could have
17139            // consumed. The set follows the seating as well: a swapped
17140            // probe subtree hosts a different variable set, and the
17141            // runtime push gate must not push keys the new right cannot
17142            // consume (nor prune entries it can).
17143            *rhs_hostable_keys = stamp_rhs_hostable_keys(&taken_right);
17144            // Grounds can materialize via recost-time specializations (the
17145            // Broadcast probe grounding above and in `join_nodes`), so the
17146            // both-sides ground-unique conflict is re-checked here, along
17147            // with a zero-row arm (a substitution below this join): the
17148            // collapse stays stable across passes.
17149            if zero_row_arm(&taken_left)
17150                || zero_row_arm(&taken_right)
17151                || (!hash_keys.is_empty()
17152                    && conflicting_ground_keys(&taken_left, &taken_right, hash_keys).is_some())
17153            {
17154                *node = provably_empty_join(&taken_left, &taken_right);
17155                return;
17156            }
17157            **left = taken_left;
17158            **right = taken_right;
17159            // Delay-through-join: an independent OPTIONAL under this join
17160            // moves above it (Join(LeftJoin(L, O), R) ⇒ LeftJoin(Join(L, R),
17161            // O)) when the §2.11 gates pass and the summed stages improve.
17162            // On success the node became a LeftJoin — recurse so it gets this
17163            // round's LeftJoin-arm treatment (children pass, arm-reorder
17164            // try,
17165            // meta stamp, clamp) before the parent prices against it.
17166            if delay_optional_through_join(node, profile) {
17167                refinalize_joins(node, profile, ctx);
17168            }
17169        }
17170        PlanNode::LeftJoin { .. } => {
17171            if let PlanNode::LeftJoin { left, right, .. } = node {
17172                refinalize_joins(left, profile, ctx);
17173                refinalize_joins(right, profile, ctx);
17174            }
17175            // Independent-optional arm reorder on the settled children
17176            // (suffix-greedy: the flattest arms go first). On success the
17177            // fresh inner chain gets its own pass this round — children,
17178            // meta stamp, clamp — before the outer node prices against it.
17179            if reorder_independent_optional_arms(node, profile)
17180                && let PlanNode::LeftJoin { left, .. } = node
17181            {
17182                refinalize_joins(left, profile, ctx);
17183            }
17184            // Both meta models on the children's post-recost prices, BEFORE
17185            // the in-round clamp — mirroring the inner-join round order
17186            // (finalize ahead of clamp). The own-push-removed model
17187            // re-derives a direct right-arm path/claimed scan from shape, so
17188            // that record is clamp-order-independent for the shapes it
17189            // handles.
17190            if let PlanNode::LeftJoin {
17191                left,
17192                right,
17193                hash_keys,
17194                probe_key_domains,
17195                probe_key_overlap_milli,
17196                meta,
17197                ..
17198            } = node
17199            {
17200                *meta = stamp_left_join_meta(
17201                    left.produced_row_count_estimate(),
17202                    left,
17203                    right,
17204                    hash_keys,
17205                    profile,
17206                );
17207                *probe_key_domains = stamp_probe_key_domains(profile, right, hash_keys);
17208                // The containment stamps follow the OPTIONAL's settled
17209                // arms too — the OPTIONAL-delay/rotation transforms build
17210                // this node with empty coverage vecs as placeholders, and
17211                // without this re-stamp the runtime would count-coverage
17212                // those arms forever while `seat_cost_total` (which
17213                // resolves freshly inside `seat_probe_shape` when a
17214                // LeftJoin is priced as a subtree arm) priced them with
17215                // containment — the price/stamp drift the shared resolver
17216                // exists to prevent.
17217                *probe_key_overlap_milli =
17218                    stamp_probe_key_overlaps(profile, left, right, hash_keys);
17219                clamp_broadcast_probe_estimates(left, right, hash_keys, profile);
17220            }
17221        }
17222        PlanNode::Union { left, right } => {
17223            refinalize_joins(left, profile, ctx);
17224            refinalize_joins(right, profile, ctx);
17225        }
17226        PlanNode::Filter { inner, exists, .. } => {
17227            refinalize_joins(inner, profile, ctx);
17228            for clause in exists {
17229                refinalize_joins(&mut clause.body, profile, ctx);
17230            }
17231        }
17232        PlanNode::Extend { inner, .. }
17233        | PlanNode::Slice { inner, .. }
17234        | PlanNode::Distinct { inner, .. }
17235        | PlanNode::Sort { inner, .. }
17236        | PlanNode::Group { inner, .. }
17237        | PlanNode::JoinGraphVar { inner, .. } => {
17238            refinalize_joins(inner, profile, ctx);
17239        }
17240        // Recost inner joins too — the subquery body is scope-internal and
17241        // moving the boundary never invalidates its own annotations.
17242        PlanNode::SubSelect(sub) => refinalize_joins(&mut sub.inner, profile, ctx),
17243        PlanNode::Values(_)
17244        | PlanNode::NamedGraphs { .. }
17245        | PlanNode::NamedGraphExists { .. }
17246        // Counts estimates are fixed at construction; nothing to recost.
17247        | PlanNode::DomainCounts { .. }
17248        | PlanNode::HeadCounts { .. }
17249        | PlanNode::PatternCount { .. }
17250            | PlanNode::Unit => {}
17251    }
17252}
17253
17254/// Drop runtime allow-list annotations. Identity-fold `grounded` slots stay.
17255///
17256/// A swapped probe arm can lose the broadcast list a `DomainScan` reads as its
17257/// constraint terms; drop the rewrite with it so execution never scans an
17258/// empty constraint list. Bare head scans have no broadcast dependency and
17259/// survive.
17260fn clear_broadcast_marks(node: &mut PlanNode) {
17261    match node {
17262        PlanNode::Scan(scan) => {
17263            scan.broadcasted = None;
17264            // The ancestor push return bound's lifetime is exactly the
17265            // claim mark's — the claimer re-derives both together
17266            // (`clamp_broadcast_probe_estimates` writes the pair, the
17267            // swap-time clear removes it). Clearing the mark without the
17268            // bound would leave an unowned bound pricing a full read.
17269            scan.ancestor_push_return_bound = None;
17270            scan.domain_scan = None;
17271            // The bag count-scan rewrite can read a broadcast constraint
17272            // list just like the distinct one — lose the list, lose it too.
17273            scan.domain_counts = None;
17274        }
17275        PlanNode::Join { left, right, .. }
17276        | PlanNode::Union { left, right }
17277        | PlanNode::LeftJoin { left, right, .. } => {
17278            clear_broadcast_marks(left);
17279            clear_broadcast_marks(right);
17280        }
17281        PlanNode::Filter { inner, .. }
17282        | PlanNode::Extend { inner, .. }
17283        | PlanNode::Slice { inner, .. }
17284        | PlanNode::Distinct { inner, .. }
17285        | PlanNode::Sort { inner, .. }
17286        | PlanNode::Group { inner, .. }
17287        | PlanNode::JoinGraphVar { inner, .. } => clear_broadcast_marks(inner),
17288        _ => {}
17289    }
17290}
17291
17292/// Keep allow-listed probe scans/paths at the left join-key domain when the
17293/// encoded pattern is still unbound (specialize already did this; recost from
17294/// the pattern alone would restore catalog cardinality).
17295/// The pushed value count ONE pusher's list can carry on `variable`:
17296/// min(the pusher's key domain, the pusher's own row estimate). A list
17297/// cannot hold more distinct values than the domain offers, nor more than
17298/// the pusher has rows to carry them (dom ≤ rows hygiene, the same rule
17299/// at every consumer). Unknown domain → the row estimate itself (every
17300/// row may carry a distinct key). ONE derivation, all three consumers —
17301/// both claim-stamp sites (`clamp_broadcast_probe_estimates`,
17302/// `claim_broadcast_probe`) and the walk's per-page count
17303/// (`child_push_from_shape`) — so the list size the plan-time claim
17304/// machinery stamps and the list size the comparator hypothesizes can
17305/// never disagree. The driver-rows bound is the transects lesson: a
17306/// 500-row driver pushes at most 500 keys, never a full page-sized list.
17307fn pushed_val_count(profile: Option<&StatsProfile>, pusher: &PlanNode, variable: &Variable) -> u64 {
17308    join_key_domain_for_node(profile, pusher, variable)
17309        .map(|domain| domain.min(pusher.produced_row_count_estimate()))
17310        .unwrap_or_else(|| pusher.produced_row_count_estimate())
17311        .max(1)
17312}
17313
17314/// The shared core of "rows a node returns under a push of `pushed_val_count`
17315/// values": `pushed_val_count × basis / domain`, the TOTAL product rounded UP
17316/// once (`div_ceil` — the bound is never zero and never understates the
17317/// true expectation, with an error under one row TOTAL, not per key),
17318/// containment-bounded by the basis (the matched keys' rows are the whole
17319/// read at most, which also absorbs the over-estimate when only some
17320/// pushed values match). ONE formula, both plan-time consumers — the claim
17321/// stamps (through `pushed_scan_return_bound`) and the walk's hypothesis
17322/// (`containing_push_driver_bound`) — so the number the claim machinery
17323/// stamps and the number the comparator hypothesizes agree by
17324/// construction, never by coincidence. The rounding reconciles the two
17325/// policies this replaced: the stamps' total-floor could understate, and
17326/// the walk's per-key-ceil overstated by up to a row per key (a
17327/// 2.06-rows-per-key probe priced 3.0 — +45%). Unknown domain → `None`:
17328/// the core invents nothing. The callers apply their own documented
17329/// policies on `None` — the stamps must write a number (the values-broadcast
17330/// fallback), the hypothesis must not (the standalone geometry stands).
17331fn pushed_return_bound_core(pushed_val_count: u64, basis: u64, domain: Option<u64>) -> Option<u64> {
17332    let basis = basis.max(1);
17333    let domain = domain?.max(1);
17334    let total = u128::from(pushed_val_count) * u128::from(basis);
17335    let bound = u64::try_from(total.div_ceil(u128::from(domain)))
17336        .unwrap_or(basis)
17337        .min(basis);
17338    Some(bound.max(1))
17339}
17340
17341/// Expected rows a marked probe scan returns under its push: the pushed
17342/// list (driver key domain bounded by driver rows — computed by the
17343/// callers) times the scan's own average rows per key value
17344/// (`price / key_domain`, the domain from the probe's side), bounded by the
17345/// scan's price (containment — the matched keys' rows are the whole scan
17346/// at most, which also absorbs the over-estimate when only some pushed
17347/// keys match). `price` is the scan's UNCLAMPED whole-read estimate
17348/// (`estimate_unclamped_scan_rows`) passed explicitly — NOT the
17349/// push-clamped cell: the bound must be IDEMPOTENT under a clamped cell,
17350/// because `ancestor_push_return_bound` persistence keeps clamped values
17351/// in the cell across rounds and recomputing from a clamped price
17352/// compounds the clamp (a 100-key × 2-rows/key probe would decay
17353/// 206 → 1 in one round). Unknown probe-side domain (no HLL/exact count
17354/// for that slot) → fan-out 1: the values-broadcast bound
17355/// `min(price, pushed_val_count)`.
17356fn pushed_scan_return_bound(
17357    pushed_val_count: u64,
17358    price: u64,
17359    scan: &ScanOp,
17360    variable: &Variable,
17361    profile: Option<&StatsProfile>,
17362) -> u64 {
17363    let domain = join_key_domain_for(profile, scan, std::slice::from_ref(variable));
17364    pushed_return_bound_core(pushed_val_count, price, domain)
17365        .unwrap_or_else(|| pushed_val_count.min(price.max(1)))
17366        .max(1)
17367}
17368
17369fn clamp_broadcast_probe_estimates(
17370    left: &PlanNode,
17371    right: &mut PlanNode,
17372    hash_keys: &[Variable],
17373    profile: Option<&StatsProfile>,
17374) {
17375    match right {
17376        PlanNode::Scan(scan) => {
17377            if pattern_is_point_lookup(&scan.pattern) {
17378                return;
17379            }
17380            let Some((variable, _)) = &scan.broadcasted else {
17381                return;
17382            };
17383            // Claimer-gate: an outer join's claim may sit on a scan inside
17384            // this arm — clamp it there, against THAT join's driver. This
17385            // join's left may not even bind the variable (cartesian arm
17386            // under a VALUES), and the rows-fallback below would clamp on
17387            // nonsense.
17388            if !hash_keys.contains(variable) {
17389                return;
17390            }
17391            // The pushed list carries at most min(domain, driver rows)
17392            // distinct values — the dom ≤ rows hygiene every list-size
17393            // consumer shares (`pushed_val_count`).
17394            let pushed_val_count = pushed_val_count(profile, left, variable);
17395            let price = estimate_unclamped_scan_rows(profile, scan);
17396            let bound = pushed_scan_return_bound(pushed_val_count, price, scan, variable, profile);
17397            scan.produced_row_count_estimate = scan.produced_row_count_estimate.min(bound);
17398            // Record the bound for every join BELOW the claimer: it is not
17399            // locally recomputable there (the driver domain lives in a
17400            // subtree above), so it rides the scan until the claim mark
17401            // that owns it is cleared. The claimer's own decision in this
17402            // round already ran (the clamp is post-decision); its own
17403            // next-round reads are ownership-aware (`driver_whole_read_rows`) —
17404            // the cell keeps the bound, the driver work re-derives the
17405            // intrinsic. See the field doc.
17406            scan.ancestor_push_return_bound = Some(bound);
17407        }
17408        // Paths keep the values-broadcast bound: a PathOp carries no
17409        // probe-side domain (`join_key_domain_for_node` → None for Path),
17410        // so the fan-out is unknowable here. The pushed count is the min
17411        // over every binding key (`path_pushed_val_count`) — the same rule
17412        // `path_probe_row_bound` uses at finalize, so the number the swap
17413        // decided on and the number recomputed from this node agree
17414        // regardless of which key sorts first. (The scan arm's
17415        // claim-variable rule is scan-specific: a scan carries one claim
17416        // mark; a path carries none.)
17417        PlanNode::Path(path) => {
17418            if path.subject_term.is_some() && path.object_term.is_some() {
17419                return;
17420            }
17421            let Some(pushed) = path_pushed_val_count(path, left, hash_keys, profile) else {
17422                return;
17423            };
17424            path.produced_row_count_estimate = path.produced_row_count_estimate.min(pushed);
17425        }
17426        PlanNode::Union { left: a, right: b }
17427        | PlanNode::Join {
17428            left: a, right: b, ..
17429        } => {
17430            clamp_broadcast_probe_estimates(left, a, hash_keys, profile);
17431            clamp_broadcast_probe_estimates(left, b, hash_keys, profile);
17432        }
17433        PlanNode::LeftJoin {
17434            left: nested_left,
17435            right: nested_right,
17436            hash_keys: nested_keys,
17437            ..
17438        } => {
17439            clamp_broadcast_probe_estimates(left, nested_left, hash_keys, profile);
17440            clamp_broadcast_probe_estimates(nested_left, nested_right, nested_keys, profile);
17441        }
17442        PlanNode::Filter { inner, .. }
17443        | PlanNode::Extend { inner, .. }
17444        | PlanNode::Slice { inner, .. }
17445        | PlanNode::Distinct { inner, .. }
17446        | PlanNode::Sort { inner, .. }
17447        | PlanNode::Group { inner, .. } => {
17448            clamp_broadcast_probe_estimates(left, inner, hash_keys, profile);
17449        }
17450        _ => {}
17451    }
17452}
17453
17454/// Join keys whose runtime push is already stamped on a probe scan under
17455/// `node` — the `(variable, slot)` marks written by
17456/// [`restamp_broadcast_marks`]. Claim-scoped like the claim walk itself:
17457/// does not descend into `SubSelect` (outer claims never crossed it) or
17458/// `CustomNode` (plugin-owned children).
17459fn pushed_join_keys(node: &PlanNode, hash_keys: &[Variable]) -> Vec<Variable> {
17460    let mut pushed = Vec::new();
17461    match node {
17462        PlanNode::Scan(scan) => {
17463            if let Some((variable, _)) = &scan.broadcasted
17464                && hash_keys.contains(variable)
17465                && !pushed.iter().any(|v: &Variable| v == variable)
17466            {
17467                pushed.push(variable.clone());
17468            }
17469        }
17470        PlanNode::Union { left: a, right: b }
17471        | PlanNode::Join {
17472            left: a, right: b, ..
17473        } => {
17474            pushed.extend(pushed_join_keys(a, hash_keys));
17475            pushed.extend(pushed_join_keys(b, hash_keys));
17476        }
17477        PlanNode::LeftJoin {
17478            left: nested_left,
17479            right: nested_right,
17480            ..
17481        } => {
17482            pushed.extend(pushed_join_keys(nested_left, hash_keys));
17483            pushed.extend(pushed_join_keys(nested_right, hash_keys));
17484        }
17485        PlanNode::Filter { inner, .. }
17486        | PlanNode::Extend { inner, .. }
17487        | PlanNode::Slice { inner, .. }
17488        | PlanNode::Distinct { inner, .. }
17489        | PlanNode::Sort { inner, .. }
17490        | PlanNode::Group { inner, .. }
17491        | PlanNode::JoinGraphVar { inner, .. } => {
17492            pushed.extend(pushed_join_keys(inner, hash_keys));
17493        }
17494        _ => {}
17495    }
17496    pushed
17497}
17498
17499/// Final estimate-only restamp, run after the last [`restamp_broadcast_marks`]:
17500/// marks are settled and no structural pass follows, so every planned push
17501/// can condition its join's [`JoinMeta::produced_row_count_estimate`].
17502///
17503/// Push-aware formula: for a join key whose runtime push is stamped on a
17504/// probe scan, the probe rows that come back already match a driver value
17505/// on that key by construction, so the divisor becomes the DRIVER-side
17506/// domain alone (`(dom_L, None)` — [`estimate_join_rows_multi`]'s
17507/// known-side-only rule) instead of the pre-push containment bound
17508/// `max(dom_L, dom_R)`; the pre-push probability that the two value sets
17509/// intersect at all is exactly what the push removed. Unmarked keys keep
17510/// the standard pair. Row counts are the settled post-clamp produced
17511/// values, and children are restamped before parents (post-order) so
17512/// ancestors compose from push-aware child counts. Writes only
17513/// [`JoinMeta::produced_row_count_estimate`] — no structure, no marks, and
17514/// [`JoinMeta::own_push_removed_row_count_estimate`] stays as finalize
17515/// recorded it — so it cannot violate the refinalize-before-restamp
17516/// ordering the structural passes rely on.
17517fn restamp_joins_produced_row_count_estimate(node: &mut PlanNode, profile: Option<&StatsProfile>) {
17518    match node {
17519        PlanNode::Join {
17520            left,
17521            right,
17522            hash_keys,
17523            meta,
17524            ..
17525        } => {
17526            restamp_joins_produced_row_count_estimate(left, profile);
17527            restamp_joins_produced_row_count_estimate(right, profile);
17528            let left_rows = left.produced_row_count_estimate();
17529            let right_rows = right.produced_row_count_estimate();
17530            meta.produced_row_count_estimate = if hash_keys.is_empty() {
17531                left_rows.saturating_mul(right_rows).max(1)
17532            } else {
17533                let pushed = pushed_join_keys(right, hash_keys);
17534                let probe_key_domains = hash_keys
17535                    .iter()
17536                    .map(|key| {
17537                        if pushed.contains(key) {
17538                            (
17539                                join_key_domain_for_node(profile, left, key),
17540                                // None: see the push-aware rule above; an
17541                                // unknown driver domain drops the factor
17542                                // entirely (over-estimate direction).
17543                                None,
17544                            )
17545                        } else {
17546                            (
17547                                join_key_domain_for_node(profile, left, key),
17548                                join_key_domain_for_node(profile, right, key),
17549                            )
17550                        }
17551                    })
17552                    .collect::<Vec<_>>();
17553                estimate_join_rows_multi(left_rows, right_rows, &probe_key_domains)
17554            };
17555        }
17556        PlanNode::Union { left, right } => {
17557            restamp_joins_produced_row_count_estimate(left, profile);
17558            restamp_joins_produced_row_count_estimate(right, profile);
17559        }
17560        PlanNode::LeftJoin {
17561            left,
17562            right,
17563            hash_keys,
17564            meta,
17565            ..
17566        } => {
17567            restamp_joins_produced_row_count_estimate(left, profile);
17568            restamp_joins_produced_row_count_estimate(right, profile);
17569            // Push-aware overwrite: the unmatched term and |L| floor are
17570            // unchanged by the push — only the matched term swaps to the
17571            // probe's settled post-push return count (every returned row
17572            // matches a driver key by construction).
17573            meta.produced_row_count_estimate = estimate_left_join_rows_pushed(
17574                left.produced_row_count_estimate(),
17575                left,
17576                right,
17577                hash_keys,
17578                profile,
17579            );
17580        }
17581        PlanNode::SubSelect(sub) => {
17582            restamp_joins_produced_row_count_estimate(&mut sub.inner, profile);
17583        }
17584        PlanNode::CustomNode(op) => {
17585            for child in &mut op.children {
17586                restamp_joins_produced_row_count_estimate(child, profile);
17587            }
17588        }
17589        PlanNode::Filter { inner, .. }
17590        | PlanNode::Extend { inner, .. }
17591        | PlanNode::Slice { inner, .. }
17592        | PlanNode::Distinct { inner, .. }
17593        | PlanNode::Sort { inner, .. }
17594        | PlanNode::Group { inner, .. }
17595        | PlanNode::JoinGraphVar { inner, .. } => {
17596            restamp_joins_produced_row_count_estimate(inner, profile);
17597        }
17598        _ => {}
17599    }
17600}
17601
17602fn allow_list_from_node(node: &PlanNode, variable: &Variable) -> Option<Arc<[EncodedTerm]>> {
17603    match node {
17604        PlanNode::Values(values) => {
17605            let terms = values.distinct_terms(variable)?;
17606            if terms.is_empty() || terms.len() > GRAPH_FILTER_TERM_CAP as usize {
17607                None
17608            } else {
17609                Some(Arc::from(terms))
17610            }
17611        }
17612        PlanNode::Join { left, right, .. } => {
17613            allow_list_from_node(left, variable).or_else(|| allow_list_from_node(right, variable))
17614        }
17615        PlanNode::Filter { inner, .. }
17616        | PlanNode::Extend { inner, .. }
17617        | PlanNode::Slice { inner, .. }
17618        | PlanNode::Distinct { inner, .. }
17619        | PlanNode::Sort { inner, .. }
17620        | PlanNode::Group { inner, .. } => allow_list_from_node(inner, variable),
17621        _ => None,
17622    }
17623}
17624
17625fn collect_not_same_term_graph(expr: &Expression) -> Option<(Variable, Vec<EncodedTerm>)> {
17626    let mut variable: Option<Variable> = None;
17627    let mut terms = Vec::new();
17628    for conjunct in flatten_and(expr) {
17629        let (found, term) = not_same_term_ground(&conjunct)?;
17630        match &variable {
17631            None => variable = Some(found),
17632            Some(existing) if existing != &found => return None,
17633            _ => {}
17634        }
17635        if !terms.iter().any(|existing| existing == &term) {
17636            terms.push(term);
17637        }
17638    }
17639    if terms.is_empty() || terms.len() > GRAPH_FILTER_TERM_CAP as usize {
17640        return None;
17641    }
17642    Some((variable?, terms))
17643}
17644
17645fn not_same_term_ground(expr: &Expression) -> Option<(Variable, EncodedTerm)> {
17646    let Expression::Not(inner) = expr else {
17647        return None;
17648    };
17649    let (a, b, equal_not_same_term) = match inner.as_ref() {
17650        Expression::SameTerm(a, b) => (a.as_ref(), b.as_ref(), false),
17651        Expression::Equal(a, b) => (a.as_ref(), b.as_ref(), true),
17652        _ => return None,
17653    };
17654    let (variable, constant) = match (a, b) {
17655        (Expression::Variable(v), c) | (c, Expression::Variable(v)) => (v, c),
17656        _ => return None,
17657    };
17658    let (term, _) = encoded_ground_expr(constant)?;
17659    if equal_not_same_term && !sparql_equal_is_encoded_identity(&term) {
17660        return None;
17661    }
17662    Some((variable.clone(), term))
17663}
17664
17665/// Push `extra` onto GRAPH `variable` producers. `true` means at least one
17666/// producer accepted the exclusion (`Applied`). The caller still keeps the
17667/// residual `FILTER` unless `variable` is always bound.
17668fn apply_graph_exclusions(node: &mut PlanNode, variable: &Variable, extra: &[EncodedTerm]) -> bool {
17669    matches!(
17670        apply_graph_exclusion_status(node, variable, extra),
17671        ExclusionStatus::Applied
17672    )
17673}
17674
17675/// Whether a subtree contains GRAPH producers of `variable` that accepted the
17676/// extra block/subtract. Vacuous subtrees (no GRAPH `?g`) must not count as
17677/// success — otherwise `FILTER(?o != "x")` would drop after a default-graph
17678/// scan returns true.
17679#[derive(Clone, Copy, PartialEq, Eq)]
17680enum ExclusionStatus {
17681    Vacuous,
17682    Applied,
17683    Failed,
17684}
17685
17686fn merge_exclusion(left: ExclusionStatus, right: ExclusionStatus) -> ExclusionStatus {
17687    use ExclusionStatus::*;
17688    match (left, right) {
17689        (Failed, _) | (_, Failed) => Failed,
17690        (Applied, Vacuous) | (Vacuous, Applied) | (Applied, Applied) => Applied,
17691        (Vacuous, Vacuous) => Vacuous,
17692    }
17693}
17694
17695fn apply_graph_exclusion_status(
17696    node: &mut PlanNode,
17697    variable: &Variable,
17698    extra: &[EncodedTerm],
17699) -> ExclusionStatus {
17700    match node {
17701        // Scope boundary: a projected `?g` producer can never take the
17702        // exclusion (Failed keeps the FILTER), anything else is vacuous.
17703        PlanNode::SubSelect(sub) => {
17704            if sub.variables.contains(variable) {
17705                ExclusionStatus::Failed
17706            } else {
17707                ExclusionStatus::Vacuous
17708            }
17709        }
17710        // A plugin op producing the graph variable cannot take a G exclusion
17711        // (it does not seek a G slot) — keep the FILTER.
17712        PlanNode::CustomNode(op) => {
17713            if op.variables.contains(variable) {
17714                ExclusionStatus::Failed
17715            } else {
17716                ExclusionStatus::Vacuous
17717            }
17718        }
17719        PlanNode::Scan(scan) => {
17720            if scan.graph.as_ref() != Some(variable) {
17721                return ExclusionStatus::Vacuous;
17722            }
17723            if apply_scan_graph_exclusions(scan, extra) {
17724                ExclusionStatus::Applied
17725            } else {
17726                ExclusionStatus::Failed
17727            }
17728        }
17729        PlanNode::Path(path) => {
17730            if path.graph.as_ref() != Some(variable) {
17731                return ExclusionStatus::Vacuous;
17732            }
17733            if apply_path_graph_exclusions(path, extra) {
17734                ExclusionStatus::Applied
17735            } else {
17736                ExclusionStatus::Failed
17737            }
17738        }
17739        PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => merge_exclusion(
17740            apply_graph_exclusion_status(left, variable, extra),
17741            apply_graph_exclusion_status(right, variable, extra),
17742        ),
17743        PlanNode::LeftJoin { left, right, .. } => merge_exclusion(
17744            apply_graph_exclusion_status(left, variable, extra),
17745            apply_graph_exclusion_status(right, variable, extra),
17746        ),
17747        PlanNode::Filter { inner, .. }
17748        | PlanNode::Extend { inner, .. }
17749        | PlanNode::Slice { inner, .. }
17750        | PlanNode::Distinct { inner, .. }
17751        | PlanNode::Sort { inner, .. }
17752        | PlanNode::Group { inner, .. }
17753        | PlanNode::JoinGraphVar { inner, .. } => {
17754            apply_graph_exclusion_status(inner, variable, extra)
17755        }
17756        PlanNode::Values(_)
17757        | PlanNode::NamedGraphs { .. }
17758        | PlanNode::NamedGraphExists { .. }
17759        // A count scan's graph window is a bound name / residual filter —
17760        // never a projected `?g` producer — so graph exclusions are vacuous.
17761        | PlanNode::DomainCounts { .. }
17762        | PlanNode::HeadCounts { .. }
17763        | PlanNode::PatternCount { .. }
17764            | PlanNode::Unit => ExclusionStatus::Vacuous,
17765    }
17766}
17767
17768fn apply_scan_graph_exclusions(scan: &mut ScanOp, extra: &[EncodedTerm]) -> bool {
17769    apply_graph_filter_exclusions(&mut scan.pattern.graph_name, &mut scan.graph_filter, extra)
17770}
17771
17772fn apply_path_graph_exclusions(path: &mut PathOp, extra: &[EncodedTerm]) -> bool {
17773    apply_graph_filter_exclusions(&mut path.graph_name, &mut path.graph_filter, extra)
17774}
17775
17776/// Fold `FILTER (!sameTerm(?g, …))` into the residual G constraint.
17777///
17778/// `None` from [`GraphFilter::subtract_allow`] / [`GraphFilter::union_exclude`]
17779/// means over-threshold or wrong polarity: leave the original filter in place.
17780/// An empty allow remainder is [`ComposedGraph::Empty`], not `None`.
17781/// [`ComposedGraph::Filter`] only replaces `graph_filter` so a grounded IRI
17782/// is not wiped.
17783fn apply_graph_filter_exclusions(
17784    graph_name: &mut Option<EncodedTerm>,
17785    graph_filter: &mut Option<GraphFilter>,
17786    extra: &[EncodedTerm],
17787) -> bool {
17788    match graph_filter.as_ref() {
17789        Some(filter) if filter.is_exclude() => match filter.union_exclude(extra) {
17790            Some(composed) => {
17791                apply_exclusion_composed(graph_name, graph_filter, composed);
17792                true
17793            }
17794            None => false,
17795        },
17796        Some(filter) => match filter.subtract_allow(extra) {
17797            Some(composed) => {
17798                apply_exclusion_composed(graph_name, graph_filter, composed);
17799                true
17800            }
17801            None => false,
17802        },
17803        None if graph_name.is_some() => !extra.iter().any(|term| graph_name.as_ref() == Some(term)),
17804        None => match GraphFilter::exclude_default().union_exclude(extra) {
17805            Some(ComposedGraph::Filter(filter)) => {
17806                *graph_filter = Some(filter);
17807                true
17808            }
17809            Some(_) => false,
17810            None => false,
17811        },
17812    }
17813}
17814
17815fn apply_exclusion_composed(
17816    graph_name: &mut Option<EncodedTerm>,
17817    graph_filter: &mut Option<GraphFilter>,
17818    composed: ComposedGraph,
17819) {
17820    match composed {
17821        ComposedGraph::Filter(filter) => {
17822            *graph_filter = Some(filter);
17823        }
17824        other => {
17825            let (name, filter) = other.into_slots();
17826            *graph_name = name;
17827            *graph_filter = filter;
17828        }
17829    }
17830}
17831
17832fn unique_ground_from_scan(scan: &ScanOp, variable: &Variable) -> Option<EncodedTerm> {
17833    if scan.graph.as_ref() == Some(variable) {
17834        return scan.pattern.graph_name.clone();
17835    }
17836    let slots = scan.slot_of(variable);
17837    if slots.is_empty() {
17838        return None;
17839    }
17840    let mut found: Option<EncodedTerm> = None;
17841    for slot in slots {
17842        let term = pattern_slot_term(&scan.pattern, slot)?.clone();
17843        match &found {
17844            None => found = Some(term),
17845            Some(existing) if existing != &term => return None,
17846            _ => {}
17847        }
17848    }
17849    found
17850}
17851
17852/// Substitute every always-bound variable with a unique single-term producer
17853/// (a fully-bound single-value `VALUES` column, or a ground `BIND`) by that
17854/// producer's ORIGINAL query term, in place. Residual custom functions then
17855/// see the same inline constant an inline FILTER literal would carry; the
17856/// GeoSPARQL rewrite depends on this so `VALUES ?poly { … }
17857/// FILTER(geof:sfContains(?poly, ?g))` indexes exactly like the inline form.
17858fn substitute_ground_variables(
17859    expression: &mut Expression,
17860    node: &PlanNode,
17861    inner_vars: &OutputVars,
17862) {
17863    match expression {
17864        Expression::Variable(variable) => {
17865            if inner_vars.is_always_bound(variable)
17866                && let Some(ground) = unique_ground_expression(node, variable)
17867            {
17868                *expression = ground;
17869            }
17870        }
17871        Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
17872            substitute_ground_variables(inner, node, inner_vars);
17873        }
17874        Expression::And(left, right)
17875        | Expression::Or(left, right)
17876        | Expression::SameTerm(left, right)
17877        | Expression::Equal(left, right)
17878        | Expression::Greater(left, right)
17879        | Expression::Less(left, right)
17880        | Expression::GreaterOrEqual(left, right)
17881        | Expression::LessOrEqual(left, right)
17882        | Expression::Add(left, right)
17883        | Expression::Subtract(left, right)
17884        | Expression::Multiply(left, right)
17885        | Expression::Divide(left, right) => {
17886            substitute_ground_variables(left, node, inner_vars);
17887            substitute_ground_variables(right, node, inner_vars);
17888        }
17889        Expression::If(cond, then_branch, else_branch) => {
17890            substitute_ground_variables(cond, node, inner_vars);
17891            substitute_ground_variables(then_branch, node, inner_vars);
17892            substitute_ground_variables(else_branch, node, inner_vars);
17893        }
17894        Expression::Coalesce(args) | Expression::FunctionCall(_, args) => {
17895            for arg in args {
17896                substitute_ground_variables(arg, node, inner_vars);
17897            }
17898        }
17899        Expression::In(left, args) => {
17900            substitute_ground_variables(left, node, inner_vars);
17901            for arg in args {
17902                substitute_ground_variables(arg, node, inner_vars);
17903            }
17904        }
17905        // EXISTS bodies ground through their own correlation pass.
17906        Expression::NamedNode(_)
17907        | Expression::Literal(_)
17908        | Expression::Bound(_)
17909        | Expression::Exists(_) => {}
17910    }
17911}
17912
17913/// Whether a planner plugin claims `expression` as a candidate producer that
17914/// needs its filtered variable kept through the lowering's ground-value
17915/// substitution — the production answer [`ground_residual_conjunct`] consumes.
17916///
17917/// Both questions are asked about the **source** expression: the plugin claims
17918/// the shape it will rewrite, and for a shape-sensitive predicate (text's
17919/// `STRSTARTS` / `STRENDS` / anchored `REGEX`) the substituted form no longer
17920/// matches.
17921/// Geo's predicate is IRI-only, so the two shapes answer alike there.
17922fn producer_keeps_variable(expression: &Expression) -> bool {
17923    crate::plugin::process_plugins()
17924        .planner_plugins()
17925        .any(|plugin| {
17926            plugin.pins_through_optimizer(expression)
17927                && plugin.keeps_variable_when_ground(expression)
17928        })
17929}
17930
17931/// Ground a residual conjunct's unique-value producers, keeping the conjunct
17932/// rewritable.
17933///
17934/// A candidate producer that joins its variable back to the store needs that
17935/// variable to survive: geo joins the covered geometry back to it, and
17936/// `text:query` joins its candidate set back to the subject/literal, so
17937/// grounding the conjunct's **last** variable would leave a call with nothing
17938/// to join on. `keeps_variable` answers for the source expression
17939/// ([`producer_keeps_variable`] in production) and is captured **before** the
17940/// substitution, because the substituted shape may no longer match the
17941/// plugin's predicate. Every other conjunct grounds as before.
17942fn ground_residual_conjunct(
17943    conjunct: &mut Expression,
17944    inner: &PlanNode,
17945    inner_vars: &OutputVars,
17946    keeps_variable: &dyn Fn(&Expression) -> bool,
17947) {
17948    let keeps = keeps_variable(conjunct);
17949    let mut grounded = conjunct.clone();
17950    substitute_ground_variables(&mut grounded, inner, inner_vars);
17951    if variables_in_expression(&grounded).is_empty() && keeps {
17952        return;
17953    }
17954    *conjunct = grounded;
17955}
17956
17957/// The ORIGINAL query expression behind a variable whose every producer is a
17958/// one-row `VALUES` column or a ground `BIND` — the substitution source for
17959/// residual grounding. Built on [`unique_ground_term`]: VALUES columns decode
17960/// their unique term back into the query's own constant (the storage decoder
17961/// for inline/strings-resolvable variants, the node-carried original lexical
17962/// for plugin-encoded blob-backed terms); ground `BIND`s replay their own
17963/// expression. Scan/path grounds are skipped: their terms carry no plan-time
17964/// lexical, and constants originate in query text anyway.
17965fn unique_ground_expression(node: &PlanNode, variable: &Variable) -> Option<Expression> {
17966    match node {
17967        PlanNode::Values(values) => values
17968            .unique_term(variable)
17969            .and_then(|term| const_term_to_expression(&term, &values.strings)),
17970        PlanNode::Extend {
17971            inner,
17972            variable: bound,
17973            expression,
17974            ..
17975        } => {
17976            if bound == variable {
17977                ground_extend_expression(expression, inner)
17978            } else {
17979                unique_ground_expression(inner, variable)
17980            }
17981        }
17982        PlanNode::Join { left, right, .. } => unique_ground_expression(left, variable)
17983            .or_else(|| unique_ground_expression(right, variable)),
17984        PlanNode::LeftJoin { left, .. } => unique_ground_expression(left, variable),
17985        PlanNode::Filter { inner, .. }
17986        | PlanNode::Slice { inner, .. }
17987        | PlanNode::Distinct { inner, .. }
17988        | PlanNode::Sort { inner, .. }
17989        | PlanNode::Group { inner, .. }
17990        | PlanNode::JoinGraphVar { inner, .. } => unique_ground_expression(inner, variable),
17991        // Union arms / plugin op outputs are not single-term producers.
17992        PlanNode::Scan(_)
17993        | PlanNode::Path(_)
17994        | PlanNode::Unit
17995        | PlanNode::Union { .. }
17996        | PlanNode::NamedGraphs { .. }
17997        | PlanNode::NamedGraphExists { .. }
17998        | PlanNode::DomainCounts { .. }
17999        | PlanNode::HeadCounts { .. }
18000        | PlanNode::PatternCount { .. }
18001        | PlanNode::CustomNode(_)
18002        | PlanNode::SubSelect(_) => None,
18003    }
18004}
18005
18006/// Decode a plan-time constant `EncodedTerm` back into its query expression.
18007/// Inline and strings-resolvable variants go through the storage decoder;
18008/// a plugin-encoded blob-backed term has no registry string (query constants
18009/// are not data), so its ORIGINAL lexical comes from the producing node's
18010/// strings entries under the term's geo lexical key — the full-term hash,
18011/// because distinct terms (same geometry, two ingest CRSs) can share one
18012/// content-addressed blob but need their own lexical renderings. The
18013/// producing node's blob entries cannot answer this lookup: they are
18014/// content-addressed payloads keyed by blob id, and the blob id cannot
18015/// address a lexical.
18016fn const_term_to_expression(
18017    term: &EncodedTerm,
18018    strings: &[(StrHash, String)],
18019) -> Option<Expression> {
18020    if let Ok(decoded) = waratah_storage::decode_term(term, &StringsSliceResolver(strings)) {
18021        return term_to_expression(decoded);
18022    }
18023    let key = waratah_storage::geo_lexical_key(term)?;
18024    let datatype = match term {
18025        EncodedTerm::LiteralGeometry { geo_datatype, .. } => geo_datatype.iri().to_owned(),
18026        EncodedTerm::BlobLiteral { datatype_id, .. } => strings
18027            .iter()
18028            .find(|(id, _)| id == datatype_id)
18029            .map(|(_, iri)| iri.clone())?,
18030        _ => return None,
18031    };
18032    // Geo consts carry no string hashes, so the storage decoder above
18033    // cannot resolve them — the ORIGINAL lexical rides the strings list
18034    // under the geo lexical key (the seeding predicate's geo arm). The
18035    // blob list cannot answer this: its entries are content-addressed
18036    // payload bytes under the blob id, and the blob id cannot address a
18037    // lexical (distinct terms share one blob).
18038    let lexical = strings
18039        .iter()
18040        .find(|(id, _)| *id == key)
18041        .map(|(_, raw)| raw.as_str())?;
18042    Some(Expression::Literal(oxrdf::Literal::new_typed_literal(
18043        lexical,
18044        oxrdf::NamedNode::new_unchecked(datatype),
18045    )))
18046}
18047
18048fn term_to_expression(term: Term) -> Option<Expression> {
18049    match term {
18050        Term::NamedNode(node) => Some(Expression::NamedNode(node)),
18051        Term::Literal(literal) => Some(Expression::Literal(literal)),
18052        Term::BlankNode(_) => None,
18053    }
18054}
18055
18056/// [`waratah_storage::StrResolver`] over a plan node's `strings` entries,
18057/// so the storage decoder can resolve a constant's hashed lexical/IRI
18058/// without touching the registry.
18059struct StringsSliceResolver<'a>(&'a [(StrHash, String)]);
18060
18061impl waratah_storage::StrResolver for StringsSliceResolver<'_> {
18062    fn resolve(&self, hash: StrHash) -> Option<&str> {
18063        self.0
18064            .iter()
18065            .find(|(id, _)| *id == hash)
18066            .map(|(_, raw)| raw.as_str())
18067    }
18068}
18069
18070/// The original expression of a ground BIND (the shapes
18071/// [`ground_bind_term`] accepts), with variable chains resolved through
18072/// `inner`.
18073fn ground_extend_expression(expression: &Expression, inner: &PlanNode) -> Option<Expression> {
18074    match expression {
18075        Expression::NamedNode(_) | Expression::Literal(_) => Some(expression.clone()),
18076        Expression::Variable(source) => unique_ground_expression(inner, source),
18077        _ => None,
18078    }
18079}
18080
18081/// Plugin-rewrite surface of the private broadcast grounding: the one
18082/// ground term a plan binds to `variable`, if the driver binds it uniquely.
18083/// A plugin probe arm (e.g. the geo scan) pins this term into its op the
18084/// same way [`ground_and_recost_broadcasted_arm`] grounds a Scan's pattern
18085/// slot.
18086pub fn ground_unique_probe_term(node: &PlanNode, variable: &Variable) -> Option<EncodedTerm> {
18087    unique_ground_term(node, variable)
18088}
18089
18090/// The one ground term a join arm binds `variable` to, for join-key
18091/// classification in [`join_key_domain_for_allow_list`] /
18092/// [`conflicting_ground_keys`].
18093///
18094/// A bare Scan reads its materialized bound slot (`first_slot_of` →
18095/// `pattern_slot_term` — what explain prints as `(grounded ?cls object)`):
18096/// the grounding machinery (broadcast specialization, the sameTerm/`=` fold,
18097/// join-time grounding) physically writes the constant there, so the slot is
18098/// the cheap ground truth. Every other shape uses the recursive
18099/// [`unique_ground_term`] proof (Values all-rows-agree, Extend constants /
18100/// aliases, Join either side, wrappers, LeftJoin left, Path endpoints).
18101fn arm_ground_term(node: &PlanNode, variable: &Variable) -> Option<EncodedTerm> {
18102    match node {
18103        PlanNode::Scan(scan) => {
18104            let slot = scan.first_slot_of(variable)?;
18105            pattern_slot_term(&scan.pattern, slot).cloned()
18106        }
18107        _ => unique_ground_term(node, variable),
18108    }
18109}
18110
18111/// First hash key both sides bind to DIFFERENT single ground terms, if any.
18112///
18113/// Ground-unique on both sides means every row either arm can emit already
18114/// carries its side's term; different terms ⇒ the equijoin keys never match
18115/// ⇒ the join produces zero rows. (The SAME-term case is the no-op filter
18116/// [`join_key_domain_for_allow_list`] excludes from its aggregation.)
18117fn conflicting_ground_keys(
18118    left: &PlanNode,
18119    right: &PlanNode,
18120    hash_keys: &[Variable],
18121) -> Option<(Variable, EncodedTerm, EncodedTerm)> {
18122    for key in hash_keys {
18123        if let (Some(left_term), Some(right_term)) =
18124            (arm_ground_term(left, key), arm_ground_term(right, key))
18125            && left_term != right_term
18126        {
18127            return Some((key.clone(), left_term, right_term));
18128        }
18129    }
18130    None
18131}
18132
18133/// Zero-row result of a join that [`conflicting_ground_keys`] proved empty.
18134///
18135/// `Values` with no rows executes to an empty solution set without touching
18136/// either arm — neither scan runs. Joins with a zero-row arm collapse to
18137/// this node too ([`zero_row_arm`]), so the substitution propagates up
18138/// through parent cartesians that would otherwise still execute the
18139/// surviving arm.
18140///
18141/// The node DECLARES the union of both arms' output variables. Zero rows
18142/// project to zero rows, but the schema still matters above: a zero-column
18143/// node would demote every surviving variable to maybe-unbound in
18144/// `union_output_vars` (a variable is always-bound only if every arm always
18145/// binds it), and `hash_keys_for` then stops hash-joining on it — a real
18146/// plan regression hiding behind correct results. Declared variables keep
18147/// `UNION`'s always-bound view intact; `zero_row_arm` still recognizes the
18148/// node, so propagation is unchanged.
18149fn provably_empty_join(left: &PlanNode, right: &PlanNode) -> PlanNode {
18150    let mut variables = left.output_vars().all();
18151    for variable in right.output_vars().all() {
18152        if !variables.contains(&variable) {
18153            variables.push(variable);
18154        }
18155    }
18156    PlanNode::Values(ValuesOp {
18157        variables,
18158        rows: Vec::new(),
18159        strings: Vec::new(),
18160        blobs: Vec::new(),
18161    })
18162}
18163
18164/// Whether `node` is the zero-row substitution (or any other zero-row
18165/// `VALUES`): an inner join with such an arm produces no rows.
18166fn zero_row_arm(node: &PlanNode) -> bool {
18167    matches!(node, PlanNode::Values(values) if values.rows.is_empty())
18168}
18169
18170/// Return the unique ground term for a variable in a plan node.
18171fn unique_ground_term(node: &PlanNode, variable: &Variable) -> Option<EncodedTerm> {
18172    match node {
18173        PlanNode::Scan(scan) => unique_ground_from_scan(scan, variable),
18174        PlanNode::Values(values) => values.unique_term(variable),
18175        PlanNode::Extend {
18176            inner,
18177            variable: bound,
18178            expression,
18179            ..
18180        } => {
18181            if bound == variable {
18182                ground_bind_term(inner, expression)
18183            } else {
18184                unique_ground_term(inner, variable)
18185            }
18186        }
18187        PlanNode::Join { left, right, .. } => {
18188            unique_ground_term(left, variable).or_else(|| unique_ground_term(right, variable))
18189        }
18190        PlanNode::Filter { inner, .. }
18191        | PlanNode::Slice { inner, .. }
18192        | PlanNode::Distinct { inner, .. }
18193        | PlanNode::Sort { inner, .. }
18194        | PlanNode::Group { inner, .. }
18195        | PlanNode::JoinGraphVar { inner, .. } => unique_ground_term(inner, variable),
18196        PlanNode::LeftJoin { left, .. } => unique_ground_term(left, variable),
18197        PlanNode::Path(path) => {
18198            if path.graph.as_ref() == Some(variable) {
18199                return path.graph_name.clone();
18200            }
18201            match path.end_of(variable)? {
18202                PathEnd::Start | PathEnd::Both => path.subject_term.clone(),
18203                PathEnd::End => path.object_term.clone(),
18204            }
18205        }
18206        _ => None,
18207    }
18208}
18209
18210/// Ground an Extend (BIND) expression into a constant term.
18211fn ground_bind_term(inner: &PlanNode, expression: &Expression) -> Option<EncodedTerm> {
18212    match expression {
18213        Expression::NamedNode(node) => Some(EncodedTerm::from(node)),
18214        // Plugin-owned datatypes (GeoSPARQL) take the encode hook so a BIND
18215        // constant becomes the same native term ingest would mint — the
18216        // one-encode-path rule for user literals, identical to
18217        // `lower_values` / `encoded_ground_expr`. Raw `EncodedTerm::from`
18218        // would mint a hashed typed literal whose bytes never match the
18219        // stored native encoding, silently emptying join / scan equality.
18220        // The original lexical rides the query caches via seeding at Extend
18221        // execution (`execute_extend`), mirroring `execute_values`.
18222        Expression::Literal(literal) => Some(crate::plugin::encode_user_literal(literal)),
18223        Expression::Variable(source) => unique_ground_term(inner, source),
18224        // Expressions like functions or other values determined at query time
18225        // are not groundable.
18226        _ => None,
18227    }
18228}
18229
18230/// Unique ground term plus registry pairs for [`PathOp::strings`].
18231///
18232/// `*` / `?` can emit a zero-length `(t, t)` whose IRI never went through a
18233/// store write, so materialize cannot ask the registry. Scans, VALUES, and
18234/// BIND already carry those strings elsewhere; this copy is only so a var-var
18235/// fold onto a path end matches `encoded_ground_expr` + `bind_path_equality`.
18236fn unique_ground_with_strings(
18237    node: &PlanNode,
18238    variable: &Variable,
18239) -> Option<(EncodedTerm, Vec<(StrHash, String)>)> {
18240    match node {
18241        PlanNode::Scan(scan) => {
18242            let term = unique_ground_from_scan(scan, variable)?;
18243            Some((term, Vec::new()))
18244        }
18245        PlanNode::Values(values) => {
18246            let term = values.unique_term(variable)?;
18247            Some((term, values.strings.clone()))
18248        }
18249        PlanNode::Extend {
18250            inner,
18251            variable: bound,
18252            expression,
18253            ..
18254        } => {
18255            if bound == variable {
18256                ground_extend_with_strings(inner, expression)
18257            } else {
18258                unique_ground_with_strings(inner, variable)
18259            }
18260        }
18261        PlanNode::Join { left, right, .. } => unique_ground_with_strings(left, variable)
18262            .or_else(|| unique_ground_with_strings(right, variable)),
18263        PlanNode::Filter { inner, .. }
18264        | PlanNode::Slice { inner, .. }
18265        | PlanNode::Distinct { inner, .. }
18266        | PlanNode::Sort { inner, .. }
18267        | PlanNode::Group { inner, .. }
18268        | PlanNode::JoinGraphVar { inner, .. } => unique_ground_with_strings(inner, variable),
18269        PlanNode::LeftJoin { left, .. } => unique_ground_with_strings(left, variable),
18270        PlanNode::Path(path) => {
18271            if path.graph.as_ref() == Some(variable) {
18272                return path
18273                    .graph_name
18274                    .clone()
18275                    .map(|term| (term, path.strings.clone()));
18276            }
18277            let term = match path.end_of(variable)? {
18278                PathEnd::Start | PathEnd::Both => path.subject_term.clone()?,
18279                PathEnd::End => path.object_term.clone()?,
18280            };
18281            Some((term, path.strings.clone()))
18282        }
18283        _ => None,
18284    }
18285}
18286
18287fn ground_extend_with_strings(
18288    inner: &PlanNode,
18289    expression: &Expression,
18290) -> Option<(EncodedTerm, Vec<(StrHash, String)>)> {
18291    match expression {
18292        Expression::NamedNode(_) | Expression::Literal(_) => encoded_ground_expr(expression),
18293        Expression::Variable(source) => unique_ground_with_strings(inner, source),
18294        _ => None,
18295    }
18296}
18297
18298fn is_join_identity_pattern(pattern: &GraphPattern) -> bool {
18299    match pattern {
18300        GraphPattern::Bgp { patterns } => patterns.is_empty(),
18301        GraphPattern::Values {
18302            variables,
18303            bindings,
18304        } => is_unit_values(variables, bindings),
18305        _ => false,
18306    }
18307}
18308
18309fn ground_expression_to_term(expression: &Expression) -> Option<GroundTerm> {
18310    match expression {
18311        Expression::NamedNode(node) => Some(GroundTerm::NamedNode(node.clone())),
18312        Expression::Literal(literal) => Some(GroundTerm::Literal(literal.clone())),
18313        _ => None,
18314    }
18315}
18316
18317/// Copy a sibling VALUES table into each UNION arm (join distributes over union).
18318fn push_values_into_union(pattern: GraphPattern) -> GraphPattern {
18319    match pattern {
18320        GraphPattern::Join { left, right } => {
18321            let left = push_values_into_union(*left);
18322            let right = push_values_into_union(*right);
18323            distribute_values_over_union(left, right)
18324        }
18325        GraphPattern::Union { left, right } => GraphPattern::Union {
18326            left: Box::new(push_values_into_union(*left)),
18327            right: Box::new(push_values_into_union(*right)),
18328        },
18329        GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
18330            expr,
18331            inner: Box::new(push_values_into_union(*inner)),
18332        },
18333        GraphPattern::LeftJoin {
18334            left,
18335            right,
18336            expression,
18337        } => GraphPattern::LeftJoin {
18338            left: Box::new(push_values_into_union(*left)),
18339            right: Box::new(push_values_into_union(*right)),
18340            expression,
18341        },
18342        GraphPattern::Extend {
18343            inner,
18344            variable,
18345            expression,
18346        } => {
18347            let inner = push_values_into_union(*inner);
18348            if is_join_identity_pattern(&inner)
18349                && let Some(ground) = ground_expression_to_term(&expression)
18350            {
18351                GraphPattern::Values {
18352                    variables: vec![variable],
18353                    bindings: vec![vec![Some(ground)]],
18354                }
18355            } else {
18356                // Ground BIND over a non-empty pattern stays an Extend (a
18357                // detached VALUES would seed hash-key-less cross joins in
18358                // plans with no subselect). [`push_groundings_into_subselects`]
18359                // treats such Extends as virtual VALUES when a subselect
18360                // boundary can use the binding.
18361                GraphPattern::Extend {
18362                    inner: Box::new(inner),
18363                    variable,
18364                    expression,
18365                }
18366            }
18367        }
18368        GraphPattern::Slice {
18369            inner,
18370            start,
18371            length,
18372        } => GraphPattern::Slice {
18373            inner: Box::new(push_values_into_union(*inner)),
18374            start,
18375            length,
18376        },
18377        GraphPattern::Group {
18378            inner,
18379            variables,
18380            aggregates,
18381        } => GraphPattern::Group {
18382            inner: Box::new(push_values_into_union(*inner)),
18383            variables,
18384            aggregates,
18385        },
18386        other => other,
18387    }
18388}
18389
18390fn distribute_values_over_union(left: GraphPattern, right: GraphPattern) -> GraphPattern {
18391    // Do not implement Join(V, LeftJoin(B, C)) → LeftJoin(Join(V, B), C)
18392    // from the ⊆ check alone: that is legal when vacuous (V shares nothing
18393    // with C) and becomes a cartesian on the OPTIONAL left. A correct pass
18394    // also needs vars(X) ∩ vars(B) ≠ ∅, join commute/associate, and
18395    // UNION-copy vs JOIN-move. See docs/modules/ROOT/pages/internals-sparql-optimizations.adoc §2.11.
18396    match (&left, &right) {
18397        (GraphPattern::Values { .. }, GraphPattern::Union { left: a, right: b }) => {
18398            let values = left;
18399            push_values_into_union(GraphPattern::Union {
18400                left: Box::new(GraphPattern::Join {
18401                    left: Box::new(values.clone()),
18402                    right: a.clone(),
18403                }),
18404                right: Box::new(GraphPattern::Join {
18405                    left: Box::new(values),
18406                    right: b.clone(),
18407                }),
18408            })
18409        }
18410        (GraphPattern::Union { left: a, right: b }, GraphPattern::Values { .. }) => {
18411            let values = right;
18412            push_values_into_union(GraphPattern::Union {
18413                left: Box::new(GraphPattern::Join {
18414                    left: a.clone(),
18415                    right: Box::new(values.clone()),
18416                }),
18417                right: Box::new(GraphPattern::Join {
18418                    left: b.clone(),
18419                    right: Box::new(values),
18420                }),
18421            })
18422        }
18423        _ => GraphPattern::Join {
18424            left: Box::new(left),
18425            right: Box::new(right),
18426        },
18427    }
18428}
18429
18430/// Move `VALUES` bindings down to the lowest common ancestor of the sites that
18431/// use each column.
18432///
18433/// The optimizer flattens a WHERE clause into one left-deep join spine, so a
18434/// `VALUES` at the top of the query can be seated beside a relation that never
18435/// reads its columns (the t4 shape: the selector `VALUES` rides the
18436/// dataset-kind scan) while the actual consumers live in a `UNION` elsewhere.
18437/// [`push_values_into_union`] only distributes a `VALUES` that is already a
18438/// direct sibling of the `UNION`; it cannot find a binding separated from its
18439/// consumers by a join spine.
18440///
18441/// This pass removes every top-level `VALUES`, computes each column's consumer
18442/// sites with the same [`collect_binding_sites`] / [`common_path_prefix`] logic
18443/// the pinned-FILTER sink uses, and re-inserts the binding at that LCA.
18444/// One-row tables may be split by column; multi-row tables are moved whole to
18445/// the LCA of their used columns, preserving row multiplicity. A column that
18446/// nothing outside its own table names is dropped; a reader inside a FILTER
18447/// EXISTS body counts, because the walk descends into the body's pattern. A
18448/// correlated `EXISTS` body passes the enclosing plan's variables as live
18449/// names, so a body column the probe can join on is kept. A
18450/// named UNDEF column stays in scope as a maybe-unbound output. A column with
18451/// no binding site but a reader (an expression, or a projection in an
18452/// enclosing scope) keeps the table at its original seat. A column whose LCA
18453/// crosses a scope barrier seats the join at the barrier instead (see
18454/// [`safe_join_target`]).
18455///
18456/// The pass only strips within one join region: a `VALUES` behind a `FILTER`
18457/// or BIND body, a `Group` or `Project` body, a `UNION` arm, an OPTIONAL or
18458/// MINUS side, or a `GRAPH`/`SERVICE` body keeps its original scope, and each
18459/// such child is processed as its own region. Stripping across those barriers
18460/// would change what the barrier means — a `UNION` arm's rows must not
18461/// multiply its siblings, a filter or BIND expression must keep reading the
18462/// binding it has, and a variable hidden by a `Group` or `Project` cannot be
18463/// bound from outside.
18464/// The `VALUES` placement pass with the names an enclosing scope can read.
18465/// Such a name keeps its column even when nothing inside `pattern` uses it: a
18466/// projected `VALUES ?o { … }` body has no other reference, but dropping the
18467/// column would drop the answer.
18468fn place_values_at_lca_with_live(pattern: GraphPattern, live_above: &[Variable]) -> GraphPattern {
18469    // Count every name the query writes anywhere: pattern slots, expression
18470    // operands, projections, group keys, GRAPH/SERVICE names, and VALUES
18471    // columns. A column whose name occurs only in its own table is unread and
18472    // unjoined; any second occurrence (another table's column included) means
18473    // the column can be observed or constrains a join. The enclosing scope's
18474    // names count too.
18475    let mut mentions = Vec::new();
18476    collect_mentions(&pattern, &mut mentions);
18477    for variable in live_above {
18478        bump_mention(&mut mentions, variable);
18479    }
18480    place_values_with_mentions(pattern, &mentions)
18481}
18482
18483fn bump_mention(out: &mut Vec<(Variable, usize)>, variable: &Variable) {
18484    if let Some((_, count)) = out.iter_mut().find(|(name, _)| name == variable) {
18485        *count += 1;
18486    } else {
18487        out.push((variable.clone(), 1));
18488    }
18489}
18490
18491fn mention_count(out: &[(Variable, usize)], variable: &Variable) -> usize {
18492    out.iter()
18493        .find(|(name, _)| name == variable)
18494        .map_or(0, |(_, count)| *count)
18495}
18496
18497fn bump_term_pattern_mentions(out: &mut Vec<(Variable, usize)>, term: &TermPattern) {
18498    if let TermPattern::Variable(variable) = term {
18499        bump_mention(out, variable);
18500    }
18501}
18502
18503fn bump_named_node_pattern_mentions(out: &mut Vec<(Variable, usize)>, term: &NamedNodePattern) {
18504    if let NamedNodePattern::Variable(variable) = term {
18505        bump_mention(out, variable);
18506    }
18507}
18508
18509/// Every name an expression can read, including the pattern of an `EXISTS`.
18510///
18511/// [`variables_in_expression`] deliberately stops at `Expression::Exists`
18512/// because several passes treat an EXISTS body as opaque (it is lowered by its
18513/// own correlation path). The mention walk cannot: a column read only inside
18514/// the body still has to survive placement, and a body can name a sibling
18515/// table's column as a join. This walker mirrors the shared helper and hands
18516/// the body to [`collect_mentions`], which walks its slots, projections, and
18517/// nested `VALUES` tables.
18518fn collect_expression_mentions(out: &mut Vec<(Variable, usize)>, expression: &Expression) {
18519    match expression {
18520        Expression::Variable(variable) | Expression::Bound(variable) => bump_mention(out, variable),
18521        Expression::NamedNode(_) | Expression::Literal(_) => {}
18522        Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
18523            collect_expression_mentions(out, inner)
18524        }
18525        Expression::And(left, right)
18526        | Expression::Or(left, right)
18527        | Expression::SameTerm(left, right)
18528        | Expression::Equal(left, right)
18529        | Expression::Greater(left, right)
18530        | Expression::GreaterOrEqual(left, right)
18531        | Expression::Less(left, right)
18532        | Expression::LessOrEqual(left, right)
18533        | Expression::Add(left, right)
18534        | Expression::Subtract(left, right)
18535        | Expression::Multiply(left, right)
18536        | Expression::Divide(left, right) => {
18537            collect_expression_mentions(out, left);
18538            collect_expression_mentions(out, right);
18539        }
18540        Expression::FunctionCall(_, args) => {
18541            for arg in args {
18542                collect_expression_mentions(out, arg);
18543            }
18544        }
18545        Expression::If(cond, then_branch, else_branch) => {
18546            collect_expression_mentions(out, cond);
18547            collect_expression_mentions(out, then_branch);
18548            collect_expression_mentions(out, else_branch);
18549        }
18550        Expression::Coalesce(args) => {
18551            for arg in args {
18552                collect_expression_mentions(out, arg);
18553            }
18554        }
18555        Expression::In(inner, args) => {
18556            collect_expression_mentions(out, inner);
18557            for arg in args {
18558                collect_expression_mentions(out, arg);
18559            }
18560        }
18561        Expression::Exists(pattern) => collect_mentions(pattern, out),
18562    }
18563}
18564
18565fn collect_mentions(pattern: &GraphPattern, out: &mut Vec<(Variable, usize)>) {
18566    match pattern {
18567        GraphPattern::Bgp { patterns } => {
18568            for triple in patterns {
18569                bump_term_pattern_mentions(out, &triple.subject);
18570                bump_named_node_pattern_mentions(out, &triple.predicate);
18571                bump_term_pattern_mentions(out, &triple.object);
18572            }
18573        }
18574        GraphPattern::Path {
18575            subject, object, ..
18576        } => {
18577            bump_term_pattern_mentions(out, subject);
18578            bump_term_pattern_mentions(out, object);
18579        }
18580        GraphPattern::Values { variables, .. } => {
18581            for variable in variables {
18582                bump_mention(out, variable);
18583            }
18584        }
18585        GraphPattern::Extend {
18586            inner,
18587            variable,
18588            expression,
18589        } => {
18590            bump_mention(out, variable);
18591            collect_expression_mentions(out, expression);
18592            collect_mentions(inner, out);
18593        }
18594        GraphPattern::Filter { expr, inner } => {
18595            collect_expression_mentions(out, expr);
18596            collect_mentions(inner, out);
18597        }
18598        GraphPattern::Join { left, right }
18599        | GraphPattern::Union { left, right }
18600        | GraphPattern::Minus { left, right } => {
18601            collect_mentions(left, out);
18602            collect_mentions(right, out);
18603        }
18604        GraphPattern::LeftJoin {
18605            left,
18606            right,
18607            expression,
18608        } => {
18609            if let Some(expression) = expression {
18610                collect_expression_mentions(out, expression);
18611            }
18612            collect_mentions(left, out);
18613            collect_mentions(right, out);
18614        }
18615        GraphPattern::Group {
18616            inner,
18617            variables,
18618            aggregates,
18619        } => {
18620            for key in variables {
18621                bump_mention(out, key);
18622            }
18623            for (_, aggregate) in aggregates {
18624                match aggregate {
18625                    AggregateExpression::FunctionCall { expr, .. } => {
18626                        collect_expression_mentions(out, expr)
18627                    }
18628                    AggregateExpression::CountSolutions { .. } => {}
18629                }
18630            }
18631            collect_mentions(inner, out);
18632        }
18633        GraphPattern::Project { inner, variables } => {
18634            for variable in variables {
18635                bump_mention(out, variable);
18636            }
18637            collect_mentions(inner, out);
18638        }
18639        GraphPattern::OrderBy { inner, expression } => {
18640            for key in expression {
18641                let expr = match key {
18642                    OrderExpression::Asc(expr) | OrderExpression::Desc(expr) => expr,
18643                };
18644                collect_expression_mentions(out, expr);
18645            }
18646            collect_mentions(inner, out);
18647        }
18648        GraphPattern::Distinct { inner }
18649        | GraphPattern::Reduced { inner }
18650        | GraphPattern::Slice { inner, .. } => collect_mentions(inner, out),
18651        GraphPattern::Graph { name, inner } => {
18652            bump_named_node_pattern_mentions(out, name);
18653            collect_mentions(inner, out);
18654        }
18655        GraphPattern::Service { name, inner, .. } => {
18656            bump_named_node_pattern_mentions(out, name);
18657            collect_mentions(inner, out);
18658        }
18659    }
18660}
18661
18662fn place_values_with_mentions(
18663    pattern: GraphPattern,
18664    mentions: &[(Variable, usize)],
18665) -> GraphPattern {
18666    let mut tables = Vec::new();
18667    let stripped = strip_top_level_values(pattern, &mut tables);
18668    // Process nested scopes before seating this region's tables: their
18669    // insertions change paths inside a barrier, and the paths used below must
18670    // describe the tree they are inserted into.
18671    let mut result = place_values_in_children(stripped, mentions);
18672    let mut placements: Vec<(Vec<usize>, GraphPattern)> = Vec::new();
18673    for (origin, variables, mut rows) in tables {
18674        if rows.len() == 1 {
18675            collect_one_row_placements(
18676                &result,
18677                &origin,
18678                variables,
18679                rows.pop().unwrap_or_default(),
18680                mentions,
18681                &mut placements,
18682            );
18683        } else {
18684            collect_multi_row_placement(
18685                &result,
18686                &origin,
18687                variables,
18688                rows,
18689                mentions,
18690                &mut placements,
18691            );
18692        }
18693    }
18694    // Deepest first: a later ancestor insertion does not invalidate a path
18695    // already consumed inside the subtree.
18696    placements.sort_by_key(|(target, _)| std::cmp::Reverse(target.len()));
18697    for (target, values) in placements {
18698        result = insert_binding_at(result, &target, values);
18699    }
18700    result
18701}
18702
18703fn place_values_in_children(pattern: GraphPattern, mentions: &[(Variable, usize)]) -> GraphPattern {
18704    let place = |child: GraphPattern| Box::new(place_values_with_mentions(child, mentions));
18705    match pattern {
18706        GraphPattern::Join { left, right } => GraphPattern::Join {
18707            left: place(*left),
18708            right: place(*right),
18709        },
18710        GraphPattern::Union { left, right } => GraphPattern::Union {
18711            left: place(*left),
18712            right: place(*right),
18713        },
18714        GraphPattern::Minus { left, right } => GraphPattern::Minus {
18715            left: place(*left),
18716            right: place(*right),
18717        },
18718        GraphPattern::LeftJoin {
18719            left,
18720            right,
18721            expression,
18722        } => GraphPattern::LeftJoin {
18723            left: place(*left),
18724            right: place(*right),
18725            expression,
18726        },
18727        GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
18728            expr,
18729            inner: place(*inner),
18730        },
18731        GraphPattern::Extend {
18732            inner,
18733            variable,
18734            expression,
18735        } => GraphPattern::Extend {
18736            inner: place(*inner),
18737            variable,
18738            expression,
18739        },
18740        GraphPattern::Group {
18741            inner,
18742            variables,
18743            aggregates,
18744        } => GraphPattern::Group {
18745            inner: place(*inner),
18746            variables,
18747            aggregates,
18748        },
18749        GraphPattern::Project { inner, variables } => GraphPattern::Project {
18750            inner: place(*inner),
18751            variables,
18752        },
18753        GraphPattern::OrderBy { inner, expression } => GraphPattern::OrderBy {
18754            inner: place(*inner),
18755            expression,
18756        },
18757        GraphPattern::Distinct { inner } => GraphPattern::Distinct {
18758            inner: place(*inner),
18759        },
18760        GraphPattern::Reduced { inner } => GraphPattern::Reduced {
18761            inner: place(*inner),
18762        },
18763        GraphPattern::Slice {
18764            inner,
18765            start,
18766            length,
18767        } => GraphPattern::Slice {
18768            inner: place(*inner),
18769            start,
18770            length,
18771        },
18772        GraphPattern::Graph { name, inner } => GraphPattern::Graph {
18773            name,
18774            inner: place(*inner),
18775        },
18776        GraphPattern::Service {
18777            name,
18778            inner,
18779            silent,
18780        } => GraphPattern::Service {
18781            name,
18782            inner: place(*inner),
18783            silent,
18784        },
18785        GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => {
18786            pattern
18787        }
18788    }
18789}
18790
18791type StrippedTable = (Vec<usize>, Vec<Variable>, Vec<Vec<Option<GroundTerm>>>);
18792
18793fn strip_top_level_values(pattern: GraphPattern, out: &mut Vec<StrippedTable>) -> GraphPattern {
18794    strip_top_level_values_at(pattern, &mut Vec::new(), out)
18795}
18796
18797fn strip_top_level_values_at(
18798    pattern: GraphPattern,
18799    path: &mut Vec<usize>,
18800    out: &mut Vec<StrippedTable>,
18801) -> GraphPattern {
18802    match pattern {
18803        GraphPattern::Values {
18804            variables,
18805            bindings,
18806        } if !bindings.is_empty() => {
18807            out.push((path.clone(), variables, bindings));
18808            empty_bgp()
18809        }
18810        GraphPattern::Join { left, right } => {
18811            path.push(0);
18812            let left = strip_top_level_values_at(*left, path, out);
18813            path.pop();
18814            path.push(1);
18815            let right = strip_top_level_values_at(*right, path, out);
18816            path.pop();
18817            GraphPattern::Join {
18818                left: Box::new(left),
18819                right: Box::new(right),
18820            }
18821        }
18822        // A UNION arm is its own scope: a VALUES inside one arm must not be
18823        // hoisted to the UNION, where joining it would multiply the other
18824        // arms' rows. Each arm is processed as a nested region instead.
18825        GraphPattern::Union { left, right } => GraphPattern::Union { left, right },
18826        // A FILTER's expression may read the table's columns. Stripping the
18827        // table across the filter's boundary would leave that expression
18828        // unbound (the optimizer copies filters into both join inputs), so the
18829        // filter body is processed as its own region and the table stays under
18830        // the copy that reads it.
18831        GraphPattern::Filter { .. } => pattern,
18832        // A BIND expression has the same relationship to its input: the table
18833        // must not be stripped out from under a reader. The body is its own
18834        // region.
18835        GraphPattern::Extend { .. } => pattern,
18836        other => other,
18837    }
18838}
18839
18840fn empty_bgp() -> GraphPattern {
18841    GraphPattern::Bgp {
18842        patterns: Vec::new(),
18843    }
18844}
18845
18846fn collect_one_row_placements(
18847    pattern: &GraphPattern,
18848    origin: &[usize],
18849    variables: Vec<Variable>,
18850    row: Vec<Option<GroundTerm>>,
18851    mentions: &[(Variable, usize)],
18852    out: &mut Vec<(Vec<usize>, GraphPattern)>,
18853) {
18854    if variables.len() != row.len() {
18855        return;
18856    }
18857    let mut groups: std::collections::BTreeMap<Vec<usize>, Vec<(Variable, Option<GroundTerm>)>> =
18858        std::collections::BTreeMap::new();
18859    for (variable, cell) in variables.into_iter().zip(row) {
18860        let mut sites = Vec::new();
18861        collect_binding_sites(
18862            pattern,
18863            std::slice::from_ref(&variable),
18864            &mut Vec::new(),
18865            &mut sites,
18866        );
18867        let target = if sites.is_empty() {
18868            if mention_count(mentions, &variable) <= 1 {
18869                // Nothing can read the column; a one-row column can be
18870                // dropped without changing row multiplicity.
18871                continue;
18872            }
18873            // Expression-only, enclosing-scope use, or an UNDEF column that
18874            // is projected: keep it where the original table lived so the
18875            // variable stays in scope (unbound if the cell is UNDEF).
18876            origin.to_vec()
18877        } else {
18878            let target = common_path_prefix(&sites).unwrap_or_default();
18879            safe_join_target(pattern, &target)
18880        };
18881        groups.entry(target).or_default().push((variable, cell));
18882    }
18883    for (target, columns) in groups {
18884        let values = GraphPattern::Values {
18885            variables: columns
18886                .iter()
18887                .map(|(variable, _)| variable.clone())
18888                .collect(),
18889            bindings: vec![columns.iter().map(|(_, term)| term.clone()).collect()],
18890        };
18891        out.push((target, values));
18892    }
18893}
18894
18895fn collect_multi_row_placement(
18896    pattern: &GraphPattern,
18897    origin: &[usize],
18898    variables: Vec<Variable>,
18899    rows: Vec<Vec<Option<GroundTerm>>>,
18900    mentions: &[(Variable, usize)],
18901    out: &mut Vec<(Vec<usize>, GraphPattern)>,
18902) {
18903    // Columns of a multi-row table are correlated: move the table whole to
18904    // the LCA of its used columns, preserving row multiplicity. A column
18905    // nothing can read is unobservable, so it is dropped before the LCA and
18906    // cannot force the whole table to stay high. A named column is kept even
18907    // when every cell is UNDEF: it carries the variable into scope as a
18908    // maybe-unbound output.
18909    let mut kept_variables = Vec::new();
18910    let mut kept_rows: Vec<Vec<Option<GroundTerm>>> = vec![Vec::new(); rows.len()];
18911    for (index, variable) in variables.iter().enumerate() {
18912        if mention_count(mentions, variable) <= 1 {
18913            continue;
18914        }
18915        kept_variables.push(variable.clone());
18916        for (row_index, row) in rows.iter().enumerate() {
18917            kept_rows[row_index].push(row.get(index).cloned().flatten());
18918        }
18919    }
18920    if kept_variables.is_empty() {
18921        // Even with no observable column the table multiplies rows, so it
18922        // keeps its original seat and its original shape.
18923        out.push((
18924            origin.to_vec(),
18925            GraphPattern::Values {
18926                variables,
18927                bindings: rows,
18928            },
18929        ));
18930        return;
18931    }
18932    let mut sites = Vec::new();
18933    let mut needs_origin = false;
18934    for variable in &kept_variables {
18935        let before = sites.len();
18936        collect_binding_sites(
18937            pattern,
18938            std::slice::from_ref(variable),
18939            &mut Vec::new(),
18940            &mut sites,
18941        );
18942        if sites.len() == before && mention_count(mentions, variable) > 1 {
18943            // A reader with no pattern binding site (an expression or an
18944            // enclosing projection) must see the binding, so the table cannot
18945            // leave its original seat.
18946            needs_origin = true;
18947        }
18948    }
18949    let target = if sites.is_empty() || needs_origin {
18950        origin.to_vec()
18951    } else {
18952        let target = common_path_prefix(&sites).unwrap_or_default();
18953        safe_join_target(pattern, &target)
18954    };
18955    out.push((
18956        target,
18957        GraphPattern::Values {
18958            variables: kept_variables,
18959            bindings: kept_rows,
18960        },
18961    ));
18962}
18963
18964fn insert_binding_at(
18965    pattern: GraphPattern,
18966    target: &[usize],
18967    binding: GraphPattern,
18968) -> GraphPattern {
18969    let Some((&index, rest)) = target.split_first() else {
18970        return GraphPattern::Join {
18971            left: Box::new(binding),
18972            right: Box::new(pattern),
18973        };
18974    };
18975    replace_algebra_child(pattern, index, &mut |child| {
18976        insert_binding_at(child, rest, binding.clone())
18977    })
18978}
18979
18980/// In-scope variables of a lowered-shape algebra pattern (over-approximation
18981/// is fine: callers only use it to decide whether a name is *definitely*
18982/// unbound). A nested `Project` contributes only its projected names — the
18983/// sub-SELECT boundary.
18984pub(crate) fn algebra_in_scope_vars(pattern: &GraphPattern, out: &mut Vec<Variable>) {
18985    let push_term = |out: &mut Vec<Variable>, term: &TermPattern| {
18986        if let TermPattern::Variable(v) = term
18987            && !out.contains(v)
18988        {
18989            out.push(v.clone());
18990        }
18991    };
18992    match pattern {
18993        GraphPattern::Bgp { patterns } => {
18994            for triple in patterns {
18995                push_term(out, &triple.subject);
18996                if let NamedNodePattern::Variable(v) = &triple.predicate
18997                    && !out.contains(v)
18998                {
18999                    out.push(v.clone());
19000                }
19001                push_term(out, &triple.object);
19002            }
19003        }
19004        GraphPattern::Path {
19005            subject, object, ..
19006        } => {
19007            push_term(out, subject);
19008            push_term(out, object);
19009        }
19010        GraphPattern::Join { left, right }
19011        | GraphPattern::Union { left, right }
19012        | GraphPattern::Minus { left, right }
19013        | GraphPattern::LeftJoin { left, right, .. } => {
19014            algebra_in_scope_vars(left, out);
19015            algebra_in_scope_vars(right, out);
19016        }
19017        GraphPattern::Filter { inner, .. } => algebra_in_scope_vars(inner, out),
19018        GraphPattern::Graph { name, inner } => {
19019            if let NamedNodePattern::Variable(v) = name
19020                && !out.contains(v)
19021            {
19022                out.push(v.clone());
19023            }
19024            algebra_in_scope_vars(inner, out);
19025        }
19026        GraphPattern::Extend {
19027            inner, variable, ..
19028        } => {
19029            algebra_in_scope_vars(inner, out);
19030            if !out.contains(variable) {
19031                out.push(variable.clone());
19032            }
19033        }
19034        GraphPattern::Values { variables, .. } => {
19035            for v in variables {
19036                if !out.contains(v) {
19037                    out.push(v.clone());
19038                }
19039            }
19040        }
19041        GraphPattern::OrderBy { inner, .. }
19042        | GraphPattern::Slice { inner, .. }
19043        | GraphPattern::Distinct { inner }
19044        | GraphPattern::Reduced { inner }
19045        | GraphPattern::Service { inner, .. } => algebra_in_scope_vars(inner, out),
19046        GraphPattern::Group {
19047            inner,
19048            variables,
19049            aggregates,
19050        } => {
19051            algebra_in_scope_vars(inner, out);
19052            for v in variables {
19053                if !out.contains(v) {
19054                    out.push(v.clone());
19055                }
19056            }
19057            for (result, _) in aggregates {
19058                if !out.contains(result) {
19059                    out.push(result.clone());
19060                }
19061            }
19062        }
19063        // Subselect boundary: only the SELECT list is in scope outside.
19064        GraphPattern::Project { variables, .. } => {
19065            for v in variables {
19066                if !out.contains(v) {
19067                    out.push(v.clone());
19068                }
19069            }
19070        }
19071    }
19072}
19073
19074/// Copy sibling VALUES tables into qualifying sub-SELECT bodies.
19075///
19076/// Runs after [`push_values_into_union`] so detached ground BINDs flow
19077/// through the same mechanism. A subquery qualifies when every VALUES
19078/// variable is in its `SELECT` list and its modifier spine is Slice-only —
19079/// the clone then joins **below the bottom-most spine Slice**
19080/// (`Project(Slice(Join(Values, body)))`), constraining the inner scans
19081/// before the subquery's own LIMIT selects from them. Conformance: an
19082/// unordered slice may select any n rows, so every answer of
19083/// `any-n-of(filter(B))` is a legal answer of `filter(any-n-of(B))`.
19084/// Distinct / Group spines are guarded out in v1 (dedup domain / aggregate
19085/// values). OPTIONAL sides are structural barriers: outer siblings never see
19086/// inner subqueries through [`flatten_join_tree`], so an outer Values can
19087/// never filter an OPTIONAL's input (which would change miss rows, not just
19088/// surviving rows).
19089///
19090/// FILTER conjuncts need no equivalent here: the sparopt roundtrip already
19091/// pushes deterministic outer filters into sub-SELECT bodies (soundly,
19092/// slice-aware), and [`fold_identity_filters`] then grounds the inner scans.
19093///
19094/// VALUES are cloned, never moved: the outer table stays in place and
19095/// remains a (near-free) join leaf for other patterns and the projection.
19096fn push_groundings_into_subselects(pattern: GraphPattern) -> GraphPattern {
19097    match pattern {
19098        GraphPattern::Join { left, right } => {
19099            // Flatten the WHOLE join tree before any rewriting: processing
19100            // inner join levels first (and re-flattening their output at
19101            // outer levels) would re-insert clones into subqueries that
19102            // already carry one. Each join tree is handled exactly once,
19103            // here at its root.
19104            let mut nodes = Vec::new();
19105            flatten_join_tree(*left, &mut nodes);
19106            flatten_join_tree(*right, &mut nodes);
19107            let mut values = Vec::new();
19108            let mut rest = Vec::new();
19109            for node in nodes {
19110                if matches!(node, GraphPattern::Values { .. }) {
19111                    values.push(node);
19112                } else {
19113                    rest.push(node);
19114                }
19115            }
19116            let mut rest_out = Vec::with_capacity(rest.len());
19117            for node in rest {
19118                rest_out.push(rewrite_subselect_join_context(node));
19119            }
19120            let mut rest = rest_out;
19121            // Ground BIND siblings act as virtual one-row VALUES: push a
19122            // clone into qualifying subqueries but keep the Extend — it is
19123            // still what binds the variable for the outer query.
19124            let mut virtual_values: Vec<(GraphPattern, Vec<Variable>)> = Vec::new();
19125            for node in &rest {
19126                if let GraphPattern::Extend {
19127                    inner,
19128                    variable,
19129                    expression,
19130                } = node
19131                    && let Some(ground) = ground_expression_to_term(expression)
19132                {
19133                    let mut scope = Vec::new();
19134                    algebra_in_scope_vars(inner, &mut scope);
19135                    if !scope.contains(variable) {
19136                        virtual_values.push((
19137                            GraphPattern::Values {
19138                                variables: vec![variable.clone()],
19139                                bindings: vec![vec![Some(ground)]],
19140                            },
19141                            vec![variable.clone()],
19142                        ));
19143                    }
19144                }
19145            }
19146            for subquery in &mut rest {
19147                for table in &values {
19148                    let GraphPattern::Values { variables, .. } = table else {
19149                        unreachable!("only Values collected");
19150                    };
19151                    try_push_values_into_subselect(subquery, table, variables);
19152                }
19153                for (table, variables) in &virtual_values {
19154                    try_push_values_into_subselect(subquery, table, variables);
19155                }
19156            }
19157            // Clone, never move: the original tables stay in the join.
19158            let mut out = Vec::with_capacity(rest.len() + values.len());
19159            out.extend(values);
19160            out.extend(rest);
19161            rebuild_join_tree(out)
19162        }
19163        GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
19164            expr,
19165            inner: Box::new(push_groundings_into_subselects(*inner)),
19166        },
19167        GraphPattern::Union { left, right } => GraphPattern::Union {
19168            left: Box::new(push_groundings_into_subselects(*left)),
19169            right: Box::new(push_groundings_into_subselects(*right)),
19170        },
19171        // An OPTIONAL blocks insertion from outside (an outer Values can never
19172        // cross into it — filtering before the join changes miss rows), but
19173        // its own internals are a join context of their own. The barrier is
19174        // structural: `flatten_join_tree` never descends through the
19175        // LeftJoin node, so outer siblings never see inner subqueries.
19176        GraphPattern::LeftJoin {
19177            left,
19178            right,
19179            expression,
19180        } => GraphPattern::LeftJoin {
19181            left: Box::new(push_groundings_into_subselects(*left)),
19182            right: Box::new(push_groundings_into_subselects(*right)),
19183            expression,
19184        },
19185        GraphPattern::Extend {
19186            inner,
19187            variable,
19188            expression,
19189        } => GraphPattern::Extend {
19190            inner: Box::new(push_groundings_into_subselects(*inner)),
19191            variable,
19192            expression,
19193        },
19194        GraphPattern::Graph { name, inner } => GraphPattern::Graph {
19195            name,
19196            inner: Box::new(push_groundings_into_subselects(*inner)),
19197        },
19198        // Nested sub-SELECT internals get their own treatment: a Values
19199        // joined with a nested boundary inside this body qualifies the same way.
19200        GraphPattern::Project { inner, variables } => GraphPattern::Project {
19201            inner: Box::new(push_groundings_into_subselects(*inner)),
19202            variables,
19203        },
19204        GraphPattern::Slice {
19205            inner,
19206            start,
19207            length,
19208        } => GraphPattern::Slice {
19209            inner: Box::new(push_groundings_into_subselects(*inner)),
19210            start,
19211            length,
19212        },
19213        GraphPattern::Distinct { inner } => GraphPattern::Distinct {
19214            inner: Box::new(push_groundings_into_subselects(*inner)),
19215        },
19216        GraphPattern::Reduced { inner } => GraphPattern::Reduced {
19217            inner: Box::new(push_groundings_into_subselects(*inner)),
19218        },
19219        GraphPattern::Group {
19220            inner,
19221            variables,
19222            aggregates,
19223        } => GraphPattern::Group {
19224            inner: Box::new(push_groundings_into_subselects(*inner)),
19225            variables,
19226            aggregates,
19227        },
19228        other => other,
19229    }
19230}
19231
19232/// Flatten a left-/right-nested inner-join tree into its operands.
19233fn flatten_join_tree(pattern: GraphPattern, out: &mut Vec<GraphPattern>) {
19234    match pattern {
19235        GraphPattern::Join { left, right } => {
19236            flatten_join_tree(*left, out);
19237            flatten_join_tree(*right, out);
19238        }
19239        other => out.push(other),
19240    }
19241}
19242
19243/// Recurse into a flattened join operand's non-Join internals: nested
19244/// sub-SELECT bodies, UNION arms, and OPTIONAL sides are join contexts of
19245/// their own and get the full treatment. (`GraphPattern::Join` cannot appear
19246/// here — the caller flattened this level.)
19247fn rewrite_subselect_join_context(node: GraphPattern) -> GraphPattern {
19248    match node {
19249        GraphPattern::Project { inner, variables } => GraphPattern::Project {
19250            inner: Box::new(push_groundings_into_subselects(*inner)),
19251            variables,
19252        },
19253        GraphPattern::Union { left, right } => GraphPattern::Union {
19254            left: Box::new(push_groundings_into_subselects(*left)),
19255            right: Box::new(push_groundings_into_subselects(*right)),
19256        },
19257        // An OPTIONAL's own internals are a join context of their own; the
19258        // barrier that matters is at THIS level, where `try_push_values_into_
19259        // subquery` never matches the LeftJoin operand itself.
19260        GraphPattern::LeftJoin {
19261            left,
19262            right,
19263            expression,
19264        } => GraphPattern::LeftJoin {
19265            left: Box::new(push_groundings_into_subselects(*left)),
19266            right: Box::new(push_groundings_into_subselects(*right)),
19267            expression,
19268        },
19269        GraphPattern::Extend {
19270            inner,
19271            variable,
19272            expression,
19273        } => GraphPattern::Extend {
19274            inner: Box::new(push_groundings_into_subselects(*inner)),
19275            variable,
19276            expression,
19277        },
19278        GraphPattern::Filter { expr, inner } => GraphPattern::Filter {
19279            expr,
19280            inner: Box::new(push_groundings_into_subselects(*inner)),
19281        },
19282        GraphPattern::Graph { name, inner } => GraphPattern::Graph {
19283            name,
19284            inner: Box::new(push_groundings_into_subselects(*inner)),
19285        },
19286        GraphPattern::Slice {
19287            inner,
19288            start,
19289            length,
19290        } => GraphPattern::Slice {
19291            inner: Box::new(push_groundings_into_subselects(*inner)),
19292            start,
19293            length,
19294        },
19295        GraphPattern::Distinct { inner } => GraphPattern::Distinct {
19296            inner: Box::new(push_groundings_into_subselects(*inner)),
19297        },
19298        GraphPattern::Reduced { inner } => GraphPattern::Reduced {
19299            inner: Box::new(push_groundings_into_subselects(*inner)),
19300        },
19301        GraphPattern::Group {
19302            inner,
19303            variables,
19304            aggregates,
19305        } => GraphPattern::Group {
19306            inner: Box::new(push_groundings_into_subselects(*inner)),
19307            variables,
19308            aggregates,
19309        },
19310        other => other,
19311    }
19312}
19313
19314fn rebuild_join_tree(nodes: Vec<GraphPattern>) -> GraphPattern {
19315    let mut nodes = nodes.into_iter();
19316    let Some(first) = nodes.next() else {
19317        // Empty join: the SPARQL join identity.
19318        return GraphPattern::Bgp {
19319            patterns: Vec::new(),
19320        };
19321    };
19322    nodes.fold(first, |left, right| GraphPattern::Join {
19323        left: Box::new(left),
19324        right: Box::new(right),
19325    })
19326}
19327
19328/// Insert a VALUES clone into `pattern` when it is a qualifying subquery
19329/// spine (`Slice* Project(body)`). True when rewritten.
19330fn try_push_values_into_subselect(
19331    pattern: &mut GraphPattern,
19332    values: &GraphPattern,
19333    variables: &[Variable],
19334) -> bool {
19335    match pattern {
19336        GraphPattern::Slice { inner, .. } => {
19337            try_push_values_into_subselect(inner, values, variables)
19338        }
19339        GraphPattern::Project {
19340            inner,
19341            variables: projection,
19342        } => {
19343            if !variables.iter().all(|v| projection.contains(v)) {
19344                return false;
19345            }
19346            let clone = values.clone();
19347            let body = std::mem::replace(
19348                inner.as_mut(),
19349                GraphPattern::Bgp {
19350                    patterns: Vec::new(),
19351                },
19352            );
19353            **inner = GraphPattern::Join {
19354                left: Box::new(clone),
19355                right: Box::new(body),
19356            };
19357            true
19358        }
19359        // Distinct / Reduced / anything else: guarded out in v1.
19360        _ => false,
19361    }
19362}
19363
19364fn term_slot(
19365    pattern: &TermPattern,
19366) -> Result<(Option<EncodedTerm>, Option<Variable>), ComputeError> {
19367    Ok(match pattern {
19368        TermPattern::NamedNode(node) => (Some(EncodedTerm::from(node)), None),
19369        TermPattern::Literal(literal) => (Some(crate::plugin::encode_user_literal(literal)), None),
19370        TermPattern::Variable(variable) => (None, Some(variable.clone())),
19371        // Sparopt rewrites query blank nodes to variables before lowering.
19372        // Hitting this arm means a pattern bypassed that conversion — do not
19373        // encode the label as a stored blank-node id.
19374        TermPattern::BlankNode(node) => {
19375            return Err(ComputeError::UnsupportedSparql(format!(
19376                "blank node {node} in a query pattern is not supported"
19377            )));
19378        }
19379    })
19380}
19381
19382fn named_node_slot(pattern: &NamedNodePattern) -> (Option<EncodedTerm>, Option<Variable>) {
19383    match pattern {
19384        NamedNodePattern::NamedNode(node) => (Some(EncodedTerm::from(node)), None),
19385        NamedNodePattern::Variable(variable) => (None, Some(variable.clone())),
19386    }
19387}
19388
19389/// The count-split's emitted subtree, shared by the execution probes: a
19390/// [`PlanNode::DomainCounts`] op as a NON-ROOT join arm, a collapse
19391/// `Group` over the site-side join, and the sum-of-products combine
19392/// above both. The shape cannot be expressed in SPARQL until the rewrite
19393/// exists, so tests build it directly. The joins are constructed with the
19394/// BGP fold's own [`join_nodes`], so the meta under test is what
19395/// production plans carry. On [`crate::query::fixtures::count_split_quads`]
19396/// the answer is exactly 23: r1 3·2 + r2 5·3 + r3 2·1, with r4 (sites,
19397/// no occurrences) and r5 (occurrences, no sites) dropping at the inner
19398/// join of the two count relations.
19399#[cfg(test)]
19400pub(crate) mod count_split_probe {
19401    use spargebra::algebra::{AggregateExpression, AggregateFunction, Expression};
19402    use waratah_storage::{EncodedTerm, EncodedTriplePattern, NamedNode, Variable};
19403
19404    use super::{DomainScanKind, PlanNode, join_nodes};
19405    use crate::query::fixtures::count_split_scan;
19406
19407    fn var(name: &str) -> Variable {
19408        Variable::new(name).unwrap()
19409    }
19410
19411    fn term(iri: &str) -> EncodedTerm {
19412        EncodedTerm::from(&NamedNode::new(iri).unwrap())
19413    }
19414
19415    const P_IBRA: &str = "http://ex/ibraRegion";
19416    const P_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
19417    const C_SITE: &str = "https://w3id.org/tern/Site";
19418    const P_WITHIN: &str = "http://ex/withinIBRA";
19419
19420    pub(crate) fn root() -> PlanNode {
19421        // Site arm: `?site a tern:Site` joined with `?site withinIBRA ?r`
19422        // on ?site, collapsed to per-?r pair counts. The collapse counts
19423        // PAIRS (CountStar): a two-region site contributes once per
19424        // region — count-distinct here would undercount it.
19425        let type_scan = PlanNode::Scan(count_split_scan(
19426            EncodedTriplePattern {
19427                subject: None,
19428                predicate: Some(term(P_TYPE)),
19429                object: Some(term(C_SITE)),
19430                graph_name: None,
19431            },
19432            Some(var("site")),
19433            None,
19434            6,
19435        ));
19436        let within_scan = PlanNode::Scan(count_split_scan(
19437            EncodedTriplePattern {
19438                subject: None,
19439                predicate: Some(term(P_WITHIN)),
19440                object: None,
19441                graph_name: None,
19442            },
19443            Some(var("site")),
19444            Some(var("r")),
19445            7,
19446        ));
19447        let site_counts = PlanNode::Group {
19448            inner: Box::new(join_nodes(type_scan, within_scan, None)),
19449            variables: vec![var("r")],
19450            aggregates: vec![(
19451                var("cs_nsite"),
19452                AggregateExpression::CountSolutions { distinct: false },
19453            )],
19454            const_strings: Vec::new(),
19455            const_blobs: Vec::new(),
19456        };
19457
19458        // Occurrence arm: the count relation read at storage — constraint
19459        // P, head ?r (the join key), dead ?occ contributing only its run
19460        // length. Whole-domain read: the region restriction rides in the
19461        // OTHER relation and applies at the join's intersection.
19462        let domain_counts = PlanNode::DomainCounts {
19463            kind: DomainScanKind::PredicateDomain,
19464            constraints: vec![term(P_IBRA)],
19465            constraint_multiplicity: vec![1],
19466            constraint_var: None,
19467            head: var("r"),
19468            count: var("cs_nocc"),
19469            dead: Some(var("occ")),
19470            count_star: true,
19471            count_distinct: false,
19472            graph_name: None,
19473            graph_filter: None,
19474            merge_default_graph: false,
19475            iri_only: false,
19476            produced_row_count_estimate: 4,
19477        };
19478
19479        // Sum-of-products combine: the equijoin cardinality identity
19480        // Σ_k a(k)·b(k) evaluated exactly — join the relations on ?r,
19481        // multiply per region, sum. `SUM` over a plain variable matches
19482        // what the aggregate folding accepts; the product itself must be
19483        // an `Extend` column.
19484        let count_join = join_nodes(domain_counts, site_counts, None);
19485        let product = PlanNode::Extend {
19486            inner: Box::new(count_join),
19487            variable: var("cs_prod"),
19488            expression: Expression::Multiply(
19489                Box::new(Expression::Variable(var("cs_nocc"))),
19490                Box::new(Expression::Variable(var("cs_nsite"))),
19491            ),
19492            const_strings: Vec::new(),
19493            const_blobs: Vec::new(),
19494        };
19495        let sum = PlanNode::Group {
19496            inner: Box::new(product),
19497            variables: Vec::new(),
19498            aggregates: vec![(
19499                var("cs_sum"),
19500                AggregateExpression::FunctionCall {
19501                    name: AggregateFunction::Sum,
19502                    expr: Expression::Variable(var("cs_prod")),
19503                    distinct: false,
19504                },
19505            )],
19506            const_strings: Vec::new(),
19507            const_blobs: Vec::new(),
19508        };
19509        PlanNode::Extend {
19510            inner: Box::new(sum),
19511            variable: var("n"),
19512            expression: Expression::Variable(var("cs_sum")),
19513            const_strings: Vec::new(),
19514            const_blobs: Vec::new(),
19515        }
19516    }
19517}
19518
19519#[cfg(test)]
19520mod tests {
19521    use super::*;
19522    use crate::explain::ExplainFormat;
19523    use pretty_assertions::assert_eq;
19524    use spargebra::SparqlParser;
19525    use waratah_stats::{LiveQuadsProfile, StatsProfile, observe_quad};
19526    use waratah_storage::{CompareOp, Literal, NamedNode, PartitionAxis, StorageOp, encode_quad};
19527
19528    const DEMO: &str = r#"
19529        SELECT ?person ?weather WHERE {
19530          ?person <http://ex/livesIn> ?city .
19531          ?city <http://ex/hasWeather> ?weather .
19532        }
19533    "#;
19534
19535    fn var(name: &str) -> Variable {
19536        Variable::new(name).unwrap()
19537    }
19538
19539    /// Minimal payload for the cost-model unit tests: opaque, no plugin
19540    /// machinery behind it.
19541    #[derive(Debug)]
19542    struct CostTestPayload;
19543    impl crate::plugin::PluginPayload for CostTestPayload {
19544        fn plugin_id(&self) -> &'static str {
19545            "cost-test"
19546        }
19547        // The default dyn_eq is "never equal" — without this, any plan
19548        // tree holding the payload fails PartialEq even against its own
19549        // clone (the idempotence test compares a cloned tree).
19550        fn dyn_eq(&self, other: &dyn crate::plugin::PluginPayload) -> bool {
19551            other.as_any().downcast_ref::<CostTestPayload>().is_some()
19552        }
19553    }
19554
19555    fn cost_test_op(rows: u64, cost: Option<CustomOpCost>) -> CustomOp {
19556        CustomOp {
19557            plugin_id: "cost-test",
19558            op_id: "op",
19559            payload: crate::plugin::PluginPayloadBox::new(CostTestPayload),
19560            children: Vec::new(),
19561            variables: vec![var("g")],
19562            produced_row_count_estimate: rows,
19563            cost,
19564            pinned: Vec::new(),
19565        }
19566    }
19567
19568    fn probe_cost(memo_rows: u64) -> CustomOpCost {
19569        CustomOpCost {
19570            drain_rows: 2_000_000,
19571            per_key_unit: 1,
19572            inline_point_unit: 1,
19573            direct_probe: false,
19574            probe_keyed_columns: 0,
19575            probe_filter_unit: 1,
19576            probe_memo_entry_rows: memo_rows,
19577        }
19578    }
19579
19580    #[test]
19581    fn a_scan_filter_probe_examines_the_whole_output() {
19582        // An op with no keyed column is driven by its own query; a pushed
19583        // key cannot narrow it, so a page examines the whole drain output.
19584        let op = cost_test_op(2_000_000, Some(probe_cost(262_144)));
19585        assert_eq!(op.probe_page_cost(500, Some(0)), Some((2_000_000, true)));
19586        assert_eq!(op.probe_page_cost(500, None), Some((2_000_000, true)));
19587        // No direct road: the cheap per-key arm is not available.
19588        let direct = CustomOpCost {
19589            direct_probe: true,
19590            probe_keyed_columns: 0b1,
19591            probe_filter_unit: 1,
19592            ..probe_cost(262_144)
19593        };
19594        let op = cost_test_op(2_000_000, Some(direct));
19595        assert_eq!(op.probe_page_cost(500, Some(0)), Some((500, false)));
19596    }
19597
19598    /// The subject resolve's two-column shape: subject keyed, graph not.
19599    /// One mask prices both pushes correctly, which a single bool could not
19600    /// — a graph push has no index in a subject-sorted window.
19601    #[test]
19602    fn a_keyed_column_prices_per_key_while_an_unkeyed_one_scans() {
19603        let cost = CustomOpCost {
19604            direct_probe: false,
19605            probe_keyed_columns: 0b1,
19606            probe_filter_unit: 1,
19607            ..probe_cost(16_777_216)
19608        };
19609        let mut op = cost_test_op(2_000_000, Some(cost));
19610        op.variables = vec![var("s"), var("g")];
19611        // Subject push: one membership decision per key.
19612        assert_eq!(op.probe_page_cost(1_000, Some(0)), Some((1_000, true)));
19613        assert_eq!(op.keyed_cost(1_000, Some(0)), Some(2_000_000 + 1_000));
19614        // Graph push: no graph index, the whole window scans.
19615        assert_eq!(op.probe_page_cost(1_000, Some(1)), Some((2_000_000, true)));
19616        // An out-of-range or unknown pushed column prices as a scan, never
19617        // as a keyed lookup.
19618        assert_eq!(op.probe_page_cost(1_000, Some(9)), Some((2_000_000, true)));
19619        assert_eq!(op.probe_page_cost(1_000, None), Some((2_000_000, true)));
19620    }
19621
19622    #[test]
19623    fn the_drain_is_amortized_only_when_the_window_fits_the_memo() {
19624        // A window over the memo's admission limit re-drains per page.
19625        let op = cost_test_op(2_000_000, Some(probe_cost(262_144)));
19626        assert!(!op.probe_drain_amortized());
19627        // A window inside it pays the drain once.
19628        let op = cost_test_op(200_000, Some(probe_cost(262_144)));
19629        assert!(op.probe_drain_amortized());
19630        // A zero limit never assumes amortization.
19631        let op = cost_test_op(200_000, Some(probe_cost(0)));
19632        assert!(!op.probe_drain_amortized());
19633    }
19634
19635    #[test]
19636    fn the_custom_probe_seat_charges_once_or_per_page_by_memo_fit() {
19637        // Both seatings price the same join; the probe op is the right arm.
19638        // With the drain over the memo limit, the probe price carries the
19639        // drain on every page; inside the limit it is paid once.
19640        let seat = |produced: u64| {
19641            let probe = PlanNode::CustomNode(cost_test_op(produced, Some(probe_cost(262_144))));
19642            // A 500k-row driver gives several pages, so per-page and
19643            // once-time drain prices differ measurably.
19644            let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p", Some("o"), 500_000));
19645            seat_cost_total(None, &driver, &probe, &[var("g")], None, None)
19646        };
19647        let per_page = seat(2_000_000);
19648        let once = seat(200_000);
19649        assert!(
19650            per_page.rows > once.rows,
19651            "an over-budget window must price higher: per-page {} vs once {}",
19652            per_page.rows,
19653            once.rows
19654        );
19655    }
19656
19657    #[test]
19658    fn opaque_op_prices_at_none() {
19659        // cost: None is the legacy shape: both regime formulas refuse, and
19660        // every consumer falls back to pricing at the row estimate.
19661        let op = cost_test_op(1000, None);
19662        assert_eq!(op.sweep_cost(), None);
19663        assert_eq!(op.keyed_cost(10, None), None);
19664    }
19665
19666    /// Calibration pin: the sydney shape through the pure
19667    /// derivation. A driver whose row count equals its pushed-key domain
19668    /// returns one row per key, so the bound IS the page's key width —
19669    /// the benched `push_bound=24576`, reproduced exactly (CustomNode
19670    /// domain = row count, no sketch wobble).
19671    #[test]
19672    fn containing_push_bound_reproduces_sydney() {
19673        let driver = PlanNode::CustomNode(cost_test_op(8_000_000, None));
19674        let bound = containing_push_driver_bound(None, &driver, &var("g"), 24_576);
19675        assert_eq!(bound, Some(24_576), "1 row per key × 24,576 page keys");
19676    }
19677
19678    /// The counterexample's arithmetic: a driver whose rows
19679    /// heavily reuse a small key domain (~98K distinct keys over 8M rows)
19680    /// returns ~82 rows PER KEY — the honest bound is ~2M per page, two
19681    /// orders of magnitude above the subtree-output bound (~24K) that
19682    /// un-stamped arms into per-page drains. Wide band: the HLL domain
19683    /// estimate wobbles ~2%, the conclusion must not.
19684    #[test]
19685    fn containing_push_bound_prices_the_dense_keyed_return() {
19686        let mut profile = StatsProfile::default();
19687        let mut subjects = waratah_stats::HyperLogLog::default_params();
19688        for i in 0..98_000u128 {
19689            subjects.add(i);
19690        }
19691        profile
19692            .subjects_per_predicate
19693            .insert(waratah_storage::StrHash::new("http://ex/dense"), subjects);
19694        profile
19695            .predicate_counts
19696            .insert(waratah_storage::StrHash::new("http://ex/dense"), 8_000_000);
19697        let driver = PlanNode::Scan(var_scan(
19698            Some("feature"),
19699            "http://ex/dense",
19700            Some("v"),
19701            8_000_000,
19702        ));
19703        let bound = containing_push_driver_bound(Some(&profile), &driver, &var("feature"), 24_576);
19704        let b = bound.expect("the subject HLL gives the domain");
19705        assert!(
19706            (1_500_000..3_000_000).contains(&b),
19707            "the keyed return is ~2M per page, not the subtree output's ~24K (got {b})"
19708        );
19709    }
19710
19711    /// A Join driver's bound is a DELIBERATE no-op for realistic subtrees:
19712    /// the basis is the composed keyed-return READ (Join arms multiply),
19713    /// not the join's output, so the product lands far above the output and
19714    /// the caller's `min` keeps the standalone (unpushed) page count.
19715    ///
19716    /// Why it acts that way: a bare scan's rows distribute over its key
19717    /// domain, so `pushed × rows / domain` is its honest keyed return. A
19718    /// join's basis multiplies its arms' reads because the interior is
19719    /// re-read per key — the quantity the fetch-once stamps need (see
19720    /// `containing_push_bound_prices_the_dense_keyed_return`: an output
19721    /// basis under-stamped a 2M-row keyed return to the ~24K output). For
19722    /// the cost model this means a contained join under an ancestor push keeps
19723    /// its unpushed page count; its interior is still priced per page by
19724    /// `subtree_page_cost`'s leaf walk, so the cost model over-prices the
19725    /// contained join rather than under-pricing it. That conservatism is
19726    /// intended until the two consumers can use separate bases.
19727    #[test]
19728    fn containing_push_bound_on_a_join_driver_keeps_the_unpushed_page_count() {
19729        let mut profile = StatsProfile::default();
19730        for (pred, rows, subjects) in [
19731            ("http://ex/keyed", 244_793_u64, 241_786_u128),
19732            ("http://ex/other", 400_000, 400_000),
19733        ] {
19734            profile.predicate_counts.insert(StrHash::new(pred), rows);
19735            profile
19736                .subjects_per_predicate
19737                .insert(StrHash::new(pred), hll_with_n(subjects));
19738        }
19739        let keyed = PlanNode::Scan(var_scan(Some("r"), "http://ex/keyed", Some("v"), 244_793));
19740        // The BARE SCAN road: rows distribute over the ~241,786-key domain,
19741        // so one 24,576-key page returns ~24.9K rows — the honest keyed
19742        // return, far below its 244,793-row whole read.
19743        let scan_bound = containing_push_driver_bound(Some(&profile), &keyed, &var("r"), 24_576)
19744            .expect("the subject HLL gives the domain");
19745        assert!(
19746            (24_500..=25_200).contains(&scan_bound),
19747            "a scan driver returns ~pushed × rows/domain (got {scan_bound})"
19748        );
19749
19750        // The JOIN road: basis = keyed read × other arm's read
19751        // (244,793 × 400,000), divided by the same key domain — landing far
19752        // above the join's 244,793-row output. The min cannot narrow, so
19753        // the contained join keeps its unpushed page count.
19754        let joined = PlanNode::Join {
19755            left: Box::new(keyed),
19756            right: Box::new(PlanNode::Scan(var_scan(
19757                Some("z"),
19758                "http://ex/other",
19759                Some("q"),
19760                400_000,
19761            ))),
19762            hash_keys: Vec::new(),
19763            probe_key_domains: Vec::new(),
19764            probe_key_overlap_milli: Vec::new(),
19765            rhs_hostable_keys: Vec::new().into(),
19766            meta: JoinMeta {
19767                semi_gate: None,
19768                star_arms: None,
19769                strategy: JoinStrategy::Broadcast,
19770                produced_row_count_estimate: 244_793,
19771                own_push_removed_row_count_estimate: 244_793,
19772            },
19773        };
19774        let join_bound = containing_push_driver_bound(Some(&profile), &joined, &var("r"), 24_576)
19775            .expect("the key domain is still known through the join");
19776        assert!(
19777            join_bound > 1_000_000_000,
19778            "the composed-read product dwarfs the output (got {join_bound})"
19779        );
19780        assert!(
19781            join_bound > scan_bound,
19782            "the join bound is a no-op above its output, not a narrowing"
19783        );
19784    }
19785
19786    /// The soundness path: a driver that does not produce the pushed key
19787    /// has no key domain, and the derivation stands down — `None` means
19788    /// the caller keeps the standalone geometry instead of inventing a
19789    /// bound from a missing sketch.
19790    #[test]
19791    fn containing_push_bound_unknown_domain_stands_down() {
19792        let driver = PlanNode::Scan(var_scan(
19793            Some("feature"),
19794            "http://ex/other",
19795            Some("x"),
19796            8_000_000,
19797        ));
19798        assert_eq!(
19799            containing_push_driver_bound(None, &driver, &var("geom"), 24_576),
19800            None,
19801            "no domain, no bound — standalone pricing"
19802        );
19803    }
19804
19805    /// The containing-push bound derives from the
19806    /// driver's UNCAPPED whole read, never from a cell already
19807    /// conditioned by another push. The transects shape: a geometry scan
19808    /// (817,201 rows over an 817,201-key domain, ~1 row per key) whose
19809    /// cell a foreign claim clamped to 514 — the claim's answer for its
19810    /// OWN ~500-key push — must price a 500-key containing push at ~500
19811    /// rows. The pre-fix basis divided the claimed cell by the full
19812    /// domain (ceil(500 × 514 / 817,201) = 1), and the total-ceil core
19813    /// compressed that double-discount into the dishonest 9-row walk
19814    /// price that masked the driver-side blind spot. Idempotence pin:
19815    /// the hypothesis on the PRISTINE scan and on the CLAIMED scan are
19816    /// the same number — a claim cannot change the prediction.
19817    #[test]
19818    fn containing_push_basis_is_unclamped_under_foreign_claim() {
19819        let mut profile = StatsProfile::default();
19820        profile
19821            .predicate_counts
19822            .insert(StrHash::new("http://ex/asWKT"), 817_201);
19823        profile
19824            .subjects_per_predicate
19825            .insert(StrHash::new("http://ex/asWKT"), hll_with_n(817_201));
19826        // The claimed driver: cell clamped to 514 (the foreign claim's
19827        // answer), mark on ?g — foreign to this join, which keys on ?wkt.
19828        let mut claimed = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 514));
19829        let slots = match &claimed {
19830            PlanNode::Scan(scan) => scan.slot_of(&var("g")),
19831            _ => unreachable!("driver is a scan"),
19832        };
19833        assert_eq!(slots.len(), 1, "the subject slot hosts ?g");
19834        if let PlanNode::Scan(scan) = &mut claimed {
19835            scan.broadcasted = Some((var("g"), slots[0]));
19836        }
19837        let keys = [var("wkt")];
19838        // The cost model's ROW basis keeps the clamped cell (the ancestor push
19839        // holds in every seating); only the derivation switches basis.
19840        assert_eq!(
19841            driver_whole_read_rows(&claimed, &keys, Some(&profile)),
19842            514,
19843            "the cost model's row basis stays the foreign-claim cell"
19844        );
19845        // The dishonest number, for the record: the pre-fix cell basis
19846        // collapses 500 keys to 1 row through the shared core.
19847        assert_eq!(
19848            pushed_return_bound_core(500, 514, Some(817_201)),
19849            Some(1),
19850            "the double-discounted cell basis is the 9-row walk's source"
19851        );
19852        // Honest: ~1 row per key over the ~817,201-key domain (the HLL
19853        // wobbles ~1%, the conclusion must not).
19854        let bound = containing_push_driver_bound(Some(&profile), &claimed, &var("g"), 500);
19855        let b = bound.expect("the ?g domain is sketched");
19856        assert!(
19857            (480..=520).contains(&b),
19858            "500 keys × ~1 row/key ≈ 500, not the claimed cell's 1 (got {b})"
19859        );
19860        // Idempotence: the pristine scan predicts the same number — the
19861        // claim cannot change the hypothesis.
19862        let pristine = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 817_201));
19863        assert_eq!(
19864            containing_push_driver_bound(Some(&profile), &pristine, &var("g"), 500),
19865            Some(b),
19866            "same facts, same bound — the claim does not move it"
19867        );
19868    }
19869
19870    /// Review CRITICAL 2: the basis rule holds through the subtree, not
19871    /// just on a bare scan. A `Filter` around the foreign-claimed
19872    /// geometry scan used to fall through to the wrapper's cell (the
19873    /// inner claimed cell unchanged) while the domain walk still saw the
19874    /// full HLL — the double-discount resurrected one level up. A `Join`
19875    /// driver composed its meta from child cells the same way. The
19876    /// recursion prices every hosting scan's intrinsic read, and a Union
19877    /// of two hosting arms sums their reads against the summed domain.
19878    #[test]
19879    fn containing_push_basis_holds_through_containers() {
19880        let mut profile = StatsProfile::default();
19881        for (pred, rows, subjects, objects) in [
19882            ("http://ex/asWKT", 817_201_u64, 817_201_u128, 795_534_u128),
19883            ("http://ex/other", 400_000, 400_000, 400_000),
19884        ] {
19885            profile.predicate_counts.insert(StrHash::new(pred), rows);
19886            profile
19887                .subjects_per_predicate
19888                .insert(StrHash::new(pred), hll_with_n(subjects));
19889            profile
19890                .objects_per_predicate
19891                .insert(StrHash::new(pred), hll_with_n(objects));
19892        }
19893        // The foreign-claimed geometry scan: cell 514 (another push's
19894        // answer), mark on ?g, ~817K intrinsic rows over an ~817K domain.
19895        let mut claimed = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 514));
19896        let slots = match &claimed {
19897            PlanNode::Scan(scan) => scan.slot_of(&var("g")),
19898            _ => unreachable!("claimed is a scan"),
19899        };
19900        if let PlanNode::Scan(scan) = &mut claimed {
19901            scan.broadcasted = Some((var("g"), slots[0]));
19902        }
19903        let expect_honest_bound = |label: &str, driver: &PlanNode| {
19904            let bound = containing_push_driver_bound(Some(&profile), driver, &var("g"), 500);
19905            let b = bound.unwrap_or_else(|| panic!("{label}: the ?g domain is known"));
19906            assert!(
19907                (480..=520).contains(&b),
19908                "{label}: ~1 row per key over the ~817K domain, not the claimed cell's 1 (got {b})"
19909            );
19910        };
19911        // A `Filter` around the claimed scan: the wrapper's cell is the
19912        // inner claimed cell — the pre-fix basis — and the bound
19913        // collapsed to 1. The recursion sees through it.
19914        let filtered = PlanNode::Filter {
19915            inner: Box::new(claimed.clone()),
19916            early: None,
19917            residual: None,
19918            exists: Vec::new(),
19919            one_to_one: false,
19920        };
19921        expect_honest_bound("filter-wrapped", &filtered);
19922        // A `Join` driver: the claimed scan on one arm, a non-hosting
19923        // scan on the other. The join's output pairs every left row with
19924        // right rows, so the basis is the PRODUCT of the arms' reads —
19925        // the sum this replaced was smaller than ONE key's output
19926        // (rows-per-key multiply across the arms), and the caller's `min`
19927        // adopted that short bound over the honest composed cell. The
19928        // product lands far ABOVE the cell, so the bound is a deliberate
19929        // no-op: the caller's `min` keeps the standalone geometry, and
19930        // the r2 under-price (a bound below the cell) cannot recur.
19931        let joined = PlanNode::Join {
19932            left: Box::new(claimed.clone()),
19933            right: Box::new(PlanNode::Scan(var_scan(
19934                Some("z"),
19935                "http://ex/other",
19936                Some("q"),
19937                400_000,
19938            ))),
19939            hash_keys: Vec::new(),
19940            probe_key_domains: Vec::new(),
19941            probe_key_overlap_milli: Vec::new(),
19942            rhs_hostable_keys: Vec::new().into(),
19943            meta: JoinMeta {
19944                semi_gate: None,
19945                star_arms: None,
19946                strategy: JoinStrategy::Broadcast,
19947                produced_row_count_estimate: 514,
19948                own_push_removed_row_count_estimate: 514,
19949            },
19950        };
19951        let join_bound = containing_push_driver_bound(Some(&profile), &joined, &var("g"), 500)
19952            .expect("the ?g domain is known");
19953        assert!(
19954            join_bound >= 514,
19955            "the join-driver bound no longer collapses below the honest composed cell (got {join_bound})"
19956        );
19957        // A `Union` of two hosting arms: the executor reads BOTH, so the
19958        // basis sums their reads — one claimed (intrinsic ~817K), one
19959        // unclaimed (cell = whole read 400K). The domain walk merges the
19960        // arms' sketches: `other`'s subjects are a subset of the claimed
19961        // arm's in this fixture, so the honest domain is ~817K, not the
19962        // ~1.2M sum. The bound is therefore the summed reads over the
19963        // merged domain (~1.5 rows per key), still far above the claimed
19964        // cell's 1. (A Union with a non-hosting arm stands down at the
19965        // domain walk — it refuses to fabricate a domain for an arm that
19966        // cannot prove hosting — so the merge rule is pinned here.)
19967        let union = PlanNode::Union {
19968            left: Box::new(claimed),
19969            right: Box::new(PlanNode::Scan(var_scan(
19970                Some("g"),
19971                "http://ex/other",
19972                Some("q"),
19973                400_000,
19974            ))),
19975        };
19976        let union_bound = containing_push_driver_bound(Some(&profile), &union, &var("g"), 500)
19977            .expect("the ?g domain is known");
19978        // The two subject sketches merge; `other`'s subjects are a subset of
19979        // the claimed arm's in this fixture, so the honest domain is ~817K,
19980        // not the ~1.2M sum. The bound is the summed reads (~1.2M) over that
19981        // domain — ~1.5 rows per key, ~750 over a 500-key list — still far
19982        // above the claimed cell's 1. (The claimed scan keeps its sketch: the
19983        // row clamp belongs to joins, where the emitted rows really do bound
19984        // the surviving keys; a pushed scan's cell is smaller than the key
19985        // space it stands in for.)
19986        assert!(
19987            (700..=800).contains(&union_bound),
19988            "the union-driver bound is the summed reads over the merged domain (got {union_bound})"
19989        );
19990    }
19991
19992    /// The receiving-scan mirror: a bare-scan probe that hosts
19993    /// the ancestor push's key prices the road the executor actually
19994    /// fetches, per the filter-merge policy: on DIFFERENT slots the
19995    /// ancestor filter wins outright (outer-first), on the SAME slot the
19996    /// lists intersect and the cheaper road bounds the intersection from
19997    /// above. The phantom shape at unit scale: a 36,862-row wkt driver
19998    /// (2 pages, ~24,576-key lists) probing an 817,201-row geometry scan
19999    /// keyed on `?wkt` — the interior road matches ~25,245 rows per page,
20000    /// while the ancestor's ~514-term `?g` list matches ~514. The cost model
20001    /// must take the ancestor road (different slots), and it must stand
20002    /// down entirely when the probe does not host the pushed key.
20003    #[test]
20004    fn probe_side_mirror_keys_the_receiving_scan() {
20005        let mut profile = StatsProfile::default();
20006        for (pred, rows, subjects, objects) in [
20007            ("http://ex/wktDriver", 36_862_u64, 795_534_u128, 36_862_u128),
20008            ("http://ex/asWKT", 817_201, 817_201, 795_534),
20009        ] {
20010            profile.predicate_counts.insert(StrHash::new(pred), rows);
20011            profile
20012                .subjects_per_predicate
20013                .insert(StrHash::new(pred), hll_with_n(subjects));
20014            profile
20015                .objects_per_predicate
20016                .insert(StrHash::new(pred), hll_with_n(objects));
20017        }
20018        let driver = PlanNode::Scan(var_scan(
20019            Some("wkt"),
20020            "http://ex/wktDriver",
20021            Some("x"),
20022            36_862,
20023        ));
20024        let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 817_201));
20025        let keys = [var("wkt")];
20026        let standalone = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
20027        // The interior road at unit scale reproduces the association pass's phantom
20028        // probe half: ~25K matched rows per page (over a ~24,576-key page
20029        // list against the ~795K `?wkt` domain), whichever transport the
20030        // verdict picks — both price the arm well above the pushed road.
20031        assert!(
20032            standalone.rows > 80_000,
20033            "the interior-keyed road prices the phantom's probe half (got {})",
20034            standalone.rows
20035        );
20036        // The ancestor's ~514-term `?g` list: ~514 matched rows and ~514
20037        // seeks per page (1 row per key over the ~817K `?g` domain — HLL
20038        // wobble ~1%, the conclusion must not).
20039        let push = ContainingPush {
20040            key: var("g"),
20041            pushed_val_count: 514,
20042        };
20043        let mirrored = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&push));
20044        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
20045        let pages = 36_862u64.div_ceil(page);
20046        assert!(
20047            mirrored.rows > 36_862 + pages * 495 && mirrored.rows < 36_862 + pages * 540,
20048            "the probe work is the ~514-row pushed road per page (got {})",
20049            mirrored.rows
20050        );
20051        assert!(
20052            mirrored.seeks > pages * 495 && mirrored.seeks < pages * 540,
20053            "the pushed road seeks once per pushed term per page (got {})",
20054            mirrored.seeks
20055        );
20056        assert!(
20057            mirrored.rows < standalone.rows,
20058            "the mirror only ever lowers the cost estimate"
20059        );
20060        // The gate: a pushed key the probe does not host conditions
20061        // nothing — the cost estimate is byte-identical to the standalone price.
20062        let foreign = ContainingPush {
20063            key: var("zz"),
20064            pushed_val_count: 514,
20065        };
20066        let stands_down =
20067            seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&foreign));
20068        assert_eq!(
20069            (stands_down.rows, stands_down.seeks),
20070            (standalone.rows, standalone.seeks),
20071            "a foreign key establishes no receiving-scan bound"
20072        );
20073    }
20074
20075    /// Review MAJOR, stamp/seat coherence: the fetch-once stamp's verdict
20076    /// inputs are the SAME mirrored road the cost model prices. The shape: a
20077    /// 2,000,000-row wkt driver over a 100,000-key `?wkt` domain (each
20078    /// 24,576-row page carries ~1,229 distinct keys, so the
20079    /// interior-keyed road matches ~5K of the arm's 20K rows per page
20080    /// and the interior verdict is Build) probing a small 20,000-row
20081    /// geometry arm
20082    /// that also hosts the ancestor key `?g`. Under the ancestor's
20083    /// 10-term `?g` list (different slots — the executor keeps the
20084    /// ancestor filter), the mirrored road matches ~10 rows per page and
20085    /// the verdict is Probe. The stamp must
20086    /// refuse exactly as the mirrored seat does — and must still stamp
20087    /// when the ancestor push is absent, where the interior road is the
20088    /// road that runs.
20089    #[test]
20090    fn fetch_once_stamp_matches_the_mirrored_seat() {
20091        // The stamp walk reads the process-global fetch concurrency for
20092        // the batch credit; pin the default so an ambient
20093        // WARATAH_QUERY_FETCH_CONCURRENCY=0/1 cannot flip the expected
20094        // stamps.
20095        let _fc = crate::context::FetchConcurrencyPin::set(crate::context::QUERY_FETCH_CONCURRENCY);
20096        let mut profile = StatsProfile::default();
20097        for (pred, rows, subjects, objects) in [
20098            (
20099                "http://ex/wktDriver",
20100                2_000_000_u64,
20101                100_000_u128,
20102                2_000_000_u128,
20103            ),
20104            ("http://ex/asWKT", 20_000, 20_000, 5_000),
20105        ] {
20106            profile.predicate_counts.insert(StrHash::new(pred), rows);
20107            profile
20108                .subjects_per_predicate
20109                .insert(StrHash::new(pred), hll_with_n(subjects));
20110            profile
20111                .objects_per_predicate
20112                .insert(StrHash::new(pred), hll_with_n(objects));
20113        }
20114        let driver = PlanNode::Scan(var_scan(
20115            Some("wkt"),
20116            "http://ex/wktDriver",
20117            Some("x"),
20118            2_000_000,
20119        ));
20120        let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 20_000));
20121        let keys = [var("wkt")];
20122        // the cost model prices the mirrored road: the probe work stays below
20123        // one whole read of the arm (the PerPage verdict's own price), and
20124        // it is cheaper than the interior-keyed seat.
20125        let push = ContainingPush {
20126            key: var("g"),
20127            pushed_val_count: 10,
20128        };
20129        let mirrored_seat =
20130            seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&push));
20131        assert!(
20132            mirrored_seat.rows > 2_000_000 && mirrored_seat.rows < 2_020_000,
20133            "the cost model prices the mirrored ~10-row road per page, under one whole read (got {})",
20134            mirrored_seat.rows
20135        );
20136        // The stamp agrees: the mirrored verdict is Probe, no stamp.
20137        let mut mirrored_tree = PlanNode::Join {
20138            left: Box::new(driver.clone()),
20139            right: Box::new(probe.clone()),
20140            hash_keys: keys.to_vec(),
20141            probe_key_domains: Vec::new(),
20142            probe_key_overlap_milli: Vec::new(),
20143            rhs_hostable_keys: Vec::new().into(),
20144            meta: JoinMeta {
20145                semi_gate: None,
20146                star_arms: None,
20147                strategy: JoinStrategy::Broadcast,
20148                produced_row_count_estimate: 20_000,
20149                own_push_removed_row_count_estimate: 20_000,
20150            },
20151        };
20152        stamp_fetch_once(
20153            &mut mirrored_tree,
20154            Some(&profile),
20155            None,
20156            Some(&push),
20157            None,
20158            false,
20159        );
20160        let mirrored_stamp = match &mirrored_tree {
20161            PlanNode::Join { right, .. } => right.as_scan().and_then(|s| s.fetch_once),
20162            _ => unreachable!("tree is a join"),
20163        };
20164        assert_eq!(
20165            mirrored_stamp, None,
20166            "the stamp refuses Build on the mirrored road, exactly as the cost model's price does"
20167        );
20168        // Without the ancestor push the interior road runs and Builds —
20169        // the cost model prices one whole read on top of the driver (the build
20170        // road) and the stamp writes the stamp. The push is what flipped
20171        // the road, and both consumers flipped together.
20172        let mut plain_tree = PlanNode::Join {
20173            left: Box::new(driver),
20174            right: Box::new(probe),
20175            hash_keys: keys.to_vec(),
20176            probe_key_domains: Vec::new(),
20177            probe_key_overlap_milli: Vec::new(),
20178            rhs_hostable_keys: Vec::new().into(),
20179            meta: JoinMeta {
20180                semi_gate: None,
20181                star_arms: None,
20182                strategy: JoinStrategy::Broadcast,
20183                produced_row_count_estimate: 20_000,
20184                own_push_removed_row_count_estimate: 20_000,
20185            },
20186        };
20187        stamp_fetch_once(&mut plain_tree, Some(&profile), None, None, None, false);
20188        let plain_stamp = match &plain_tree {
20189            PlanNode::Join { right, .. } => right.as_scan().and_then(|s| s.fetch_once),
20190            _ => unreachable!("tree is a join"),
20191        };
20192        assert_eq!(
20193            plain_stamp,
20194            Some(20_000),
20195            "without the push the interior road Builds and the stamp writes it"
20196        );
20197    }
20198
20199    /// Review MAJOR, coverage-road discard: on an all-covered shape the
20200    /// arithmetic's early return prices the once-read and never reads the
20201    /// mirror — but under a containing push the executor's merged filter
20202    /// is the ANCESTOR's (the interior keys are dropped as covered), and
20203    /// it re-applies on every page: the built slot never fills, so the
20204    /// arm is fetched through the pushed list once per page. The cost model
20205    /// must price that road instead of the once-read. The shape: a
20206    /// 100,000-row wkt driver whose ~1,229-key page list covers the
20207    /// probe's 1,000-key `?wkt` domain (all-covered, drop granted) and a
20208    /// 20,000-row geometry arm — the once-read prices driver + whole read
20209    /// plus the memo-refusal extra, while the ancestor's 10-term `?g`
20210    /// list fetches ~10 rows per page.
20211    #[test]
20212    fn coverage_road_yields_to_the_ancestor_push() {
20213        let mut profile = StatsProfile::default();
20214        // The driver's ?wkt subject vocabulary EQUALS the probe's ?wkt
20215        // object vocabulary (both hll_with_n(5_000) — identical value
20216        // sets, containment r = 1000), and one driver page (20k rows on a
20217        // 24,576-row page basis) carries the whole 5k-key domain — so the
20218        // count rule AND the containment stamp agree: covered, the
20219        // all-covered road the assertions price is honest.
20220        for (pred, rows, subjects, objects) in [
20221            ("http://ex/wktDriver", 20_000_u64, 5_000_u128, 20_000_u128),
20222            ("http://ex/asWKT", 20_000, 20_000, 5_000),
20223        ] {
20224            profile.predicate_counts.insert(StrHash::new(pred), rows);
20225            profile
20226                .subjects_per_predicate
20227                .insert(StrHash::new(pred), hll_with_n(subjects));
20228            profile
20229                .objects_per_predicate
20230                .insert(StrHash::new(pred), hll_with_n(objects));
20231        }
20232        let driver = PlanNode::Scan(var_scan(
20233            Some("wkt"),
20234            "http://ex/wktDriver",
20235            Some("x"),
20236            20_000,
20237        ));
20238        let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 20_000));
20239        let keys = [var("wkt")];
20240        // Without the push: the all-covered road — driver + one whole
20241        // read + the memo-refusal extra, zero seeks. Exact: no sketch
20242        // wobble enters this road.
20243        let standalone = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
20244        assert_eq!(
20245            (standalone.rows, standalone.seeks),
20246            (60_000, 0),
20247            "the once-read prices driver + whole read + memo extra, seeks-free"
20248        );
20249        // Under the ancestor's 10-term `?g` list: one page, the pushed
20250        // list matches a handful of the ~5k-key arm (the unclamped estimate
20251        // already divides the arm by the 20,000-key subject domain) at ~10
20252        // seeks
20253        // — the pushed road, not the once-read.
20254        let push = ContainingPush {
20255            key: var("g"),
20256            pushed_val_count: 10,
20257        };
20258        let yielded = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&push));
20259        assert!(
20260            yielded.rows > 20_000 + 2 && yielded.rows < 20_000 + 60,
20261            "the pushed road replaces the once-read: a small matched price (got {})",
20262            yielded.rows
20263        );
20264        assert!(
20265            yielded.seeks > 5 && yielded.seeks < 15,
20266            "one seek per pushed term per page (got {})",
20267            yielded.seeks
20268        );
20269        assert!(
20270            yielded.rows < standalone.rows,
20271            "the strongly selective ancestor list beats the once-read here — and the road switched"
20272        );
20273    }
20274
20275    /// The spaceport shape — the query class the containment stamp
20276    /// exists for. A 300-town `:fromTown` driver pushes into a 3-town
20277    /// `:hasSpacePort` probe: the vocabularies are disjoint (different
20278    /// predicates, unrelated value sets), so the pushed list prunes the
20279    /// probe to ~nothing even though its LENGTH saturates the 3-key
20280    /// domain. The count rule read 300 >= 0.9 x 3 as "covered" and priced
20281    /// the whole arm; the containment-priced cost estimate must keep the push and
20282    /// price the per-page matched fraction near zero.
20283    #[test]
20284    fn disjoint_vocabularies_never_take_the_coverage_road() {
20285        let mut profile = StatsProfile::default();
20286        for (pred, rows, subjects, objects) in [
20287            // ?me :fromTown ?town — 300 distinct towns in the object slot.
20288            ("http://ex/fromTown", 300_u64, 300_u128, 300_u128),
20289            // ?sp :hasSpacePort ?town — 3 distinct towns, unrelated values
20290            // (hll_with_n fills {0..n}; the driver sketch holds {0..300},
20291            // the probe {0..3}: the probe's towns ARE inside the driver's
20292            // range, so to model DISJOINT sets the probe's HLL is filled
20293            // by hand with an offset domain).
20294            ("http://ex/hasSpacePort", 3, 3, 3),
20295        ] {
20296            profile.predicate_counts.insert(StrHash::new(pred), rows);
20297            profile
20298                .subjects_per_predicate
20299                .insert(StrHash::new(pred), hll_with_n(subjects));
20300            profile
20301                .objects_per_predicate
20302                .insert(StrHash::new(pred), hll_with_n(objects));
20303        }
20304        // Disjoint the two object vocabularies: the spaceport towns are
20305        // 1_000_000+i, outside the fromTown range.
20306        let mut ports = waratah_stats::HyperLogLog::default_params();
20307        for i in 0..3u128 {
20308            ports.add(1_000_000 + i);
20309        }
20310        profile
20311            .objects_per_predicate
20312            .insert(StrHash::new("http://ex/hasSpacePort"), ports);
20313        let driver = PlanNode::Scan(var_scan(
20314            Some("me"),
20315            "http://ex/fromTown",
20316            Some("town"),
20317            300,
20318        ));
20319        let probe = PlanNode::Scan(var_scan(
20320            Some("sp"),
20321            "http://ex/hasSpacePort",
20322            Some("town"),
20323            30_000,
20324        ));
20325        let keys = [var("town")];
20326        // Containment ~0: the overlap stamp must resolve low.
20327        let overlap = resolve_key_overlap_milli(Some(&profile), &driver, &probe, &keys[0]);
20328        assert!(overlap <= 30, "disjoint vocabularies, got {overlap} milli");
20329        // the cost model prices the probe's per-page answer through the pushed
20330        // list, NOT one whole read: a page list of ~300 values with ~0
20331        // containment matches ~nothing, so the cost model's rows stay near the
20332        // driver's own read instead of driver + whole arm.
20333        let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
20334        assert!(
20335            seat.rows < 30_000 + 300 + 10,
20336            "the disjoint push prunes the 30k arm to ~nothing (got {})",
20337            seat.rows
20338        );
20339    }
20340
20341    /// M2's contract: the OPTIONAL transforms build `LeftJoin` nodes with
20342    /// EMPTY coverage vecs as placeholders, and the refinalize LeftJoin arm
20343    /// must re-stamp the containment stamps alongside the domains —
20344    /// otherwise the runtime count-covers those arms forever while
20345    /// `seat_cost_total` (pricing a LeftJoin as a subtree arm) resolves
20346    /// containment freshly: the price/stamp drift the shared resolver
20347    /// exists to prevent.
20348    #[test]
20349    fn refinalize_restamps_leftjoin_overlap_stamps() {
20350        let mut profile = StatsProfile::default();
20351        for (pred, rows, subjects, objects) in [
20352            ("http://ex/required", 300_u64, 300_u128, 300_u128),
20353            ("http://ex/optional", 30_000, 3_u128, 3_u128),
20354        ] {
20355            // A non-vacuous profile: `resolve_key_overlap_milli` declines
20356            // an is_empty() profile (total_puts == 0, no predicate
20357            // counts) before any sketch lookup.
20358            profile.predicate_counts.insert(StrHash::new(pred), rows);
20359            profile
20360                .subjects_per_predicate
20361                .insert(StrHash::new(pred), hll_with_n(subjects));
20362            profile
20363                .objects_per_predicate
20364                .insert(StrHash::new(pred), hll_with_n(objects));
20365        }
20366        let left = PlanNode::Scan(var_scan(Some("a"), "http://ex/required", Some("k"), 300));
20367        let right = PlanNode::Scan(var_scan(Some("b"), "http://ex/optional", Some("k"), 30_000));
20368        let keys = vec![var("k")];
20369        // The transform placeholder shape: domains stamped, overlaps empty.
20370        let mut node = PlanNode::LeftJoin {
20371            left: Box::new(left),
20372            right: Box::new(right.clone()),
20373            hash_keys: keys.clone(),
20374            early_filter: None,
20375            residual_filter: None,
20376            probe_key_domains: Vec::new(),
20377            probe_key_overlap_milli: Vec::new(),
20378            meta: LeftJoinMeta {
20379                produced_row_count_estimate: 1,
20380                own_push_removed_row_count_estimate: 1,
20381            },
20382        };
20383        refinalize_joins(&mut node, Some(&profile), None);
20384        let PlanNode::LeftJoin {
20385            hash_keys,
20386            probe_key_domains,
20387            probe_key_overlap_milli,
20388            ..
20389        } = &node
20390        else {
20391            panic!("expected LeftJoin, got {node:?}")
20392        };
20393        assert_eq!(
20394            probe_key_overlap_milli.len(),
20395            hash_keys.len(),
20396            "one overlap stamp per hash key"
20397        );
20398        // The stamped value must be the SAME the cost model's shared resolver
20399        // produces for these arms — the no-drift property. The disjoint
20400        // required/optional vocabularies resolve well under full.
20401        let expected = resolve_key_overlap_milli(
20402            Some(&profile),
20403            &PlanNode::Scan(var_scan(Some("a"), "http://ex/required", Some("k"), 300)),
20404            &PlanNode::Scan(var_scan(Some("b"), "http://ex/optional", Some("k"), 30_000)),
20405            &keys[0],
20406        );
20407        assert_eq!(
20408            probe_key_overlap_milli[0], expected,
20409            "runtime stamp and seat resolver must agree"
20410        );
20411        assert!(
20412            expected < VOCABULARY_OVERLAP_FULL_MILLI,
20413            "disjoint vocabularies: the stamp engaged, got {expected} milli"
20414        );
20415        // And the domains this arm carries are the probe-side domains the
20416        // same pass stamps — vecs stay index-aligned.
20417        assert_eq!(probe_key_domains.len(), hash_keys.len());
20418    }
20419
20420    /// Review r2 MAJOR, the unshippable-key stamp split: the fetch-once
20421    /// stamp's executor-capability guard skips its whole block when no
20422    /// hash key has an S/P/O slot on the scan (a stamp the runtime cannot
20423    /// consume), but the cost model's fetch-once road had no such gate — it priced
20424    /// the once-build while `merged_scan_filter` keeps the ancestor
20425    /// filter and refetches every page. The shape: a join keyed solely on
20426    /// a graph-position variable (unshippable) under a containing push
20427    /// whose ancestor road matches ~10 rows per page. The cost model must price
20428    /// the per-page pushed road (the probe_stampable gate now requires a
20429    /// writable stamp), and the stamp must write nothing — the executor
20430    /// never takes the build branch on this arm.
20431    #[test]
20432    fn unshippable_keys_never_price_the_build_road() {
20433        let mut profile = StatsProfile::default();
20434        for (pred, rows, subjects, objects) in [
20435            (
20436                "http://ex/wktDriver",
20437                2_000_000_u64,
20438                500_u128,
20439                2_000_000_u128,
20440            ),
20441            ("http://ex/asWKT", 20_000, 20_000, 5_000),
20442        ] {
20443            profile.predicate_counts.insert(StrHash::new(pred), rows);
20444            profile
20445                .subjects_per_predicate
20446                .insert(StrHash::new(pred), hll_with_n(subjects));
20447            profile
20448                .objects_per_predicate
20449                .insert(StrHash::new(pred), hll_with_n(objects));
20450        }
20451        let mut driver = PlanNode::Scan(var_scan(
20452            Some("wkt"),
20453            "http://ex/wktDriver",
20454            Some("x"),
20455            2_000_000,
20456        ));
20457        let mut probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 20_000));
20458        // The join key lives ONLY in the graph position of both scans —
20459        // no S/P/O slot, so the runtime can neither broadcast a list for
20460        // it nor fill a built slot through it.
20461        if let PlanNode::Scan(scan) = &mut driver {
20462            scan.graph = Some(var("graph_name"));
20463        }
20464        if let PlanNode::Scan(scan) = &mut probe {
20465            scan.graph = Some(var("graph_name"));
20466        }
20467        let keys = [var("graph_name")];
20468        // The ancestor's 10-term `?g` list (the probe's Subject slot is
20469        // shippable): ~10 matched rows and ~10 seeks per page.
20470        let push = ContainingPush {
20471            key: var("g"),
20472            pushed_val_count: 10,
20473        };
20474        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
20475        let pages = 2_000_000u64.div_ceil(page);
20476        let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, Some(&push));
20477        assert!(
20478            seat.rows > 2_000_000 + pages * 8 && seat.rows < 2_000_000 + pages * 15,
20479            "the per-page pushed road is priced, not the once-build (got {})",
20480            seat.rows
20481        );
20482        assert!(
20483            seat.seeks > pages * 8 && seat.seeks < pages * 15,
20484            "one seek per pushed term per page (got {})",
20485            seat.seeks
20486        );
20487        // The stamp agrees: an unshippable key writes no stamp — the
20488        // executor never takes the build branch on this arm.
20489        let mut tree = PlanNode::Join {
20490            left: Box::new(driver),
20491            right: Box::new(probe),
20492            hash_keys: keys.to_vec(),
20493            probe_key_domains: Vec::new(),
20494            probe_key_overlap_milli: Vec::new(),
20495            rhs_hostable_keys: Vec::new().into(),
20496            meta: JoinMeta {
20497                semi_gate: None,
20498                star_arms: None,
20499                strategy: JoinStrategy::Broadcast,
20500                produced_row_count_estimate: 20_000,
20501                own_push_removed_row_count_estimate: 20_000,
20502            },
20503        };
20504        stamp_fetch_once(&mut tree, Some(&profile), None, Some(&push), None, false);
20505        let stamp = match &tree {
20506            PlanNode::Join { right, .. } => right.as_scan().and_then(|s| s.fetch_once),
20507            _ => unreachable!("tree is a join"),
20508        };
20509        assert_eq!(
20510            stamp, None,
20511            "an unshippable key writes no stamp — the executor refetches per page"
20512        );
20513    }
20514
20515    /// Review r2 finding, the all-covered walk case-split: on an
20516    /// all-covered shape the arithmetic prices the once-read, but under a
20517    /// containing push the executor's push-combine outcome decides the
20518    /// subtree arm's multiplicity. `PushedKeyVals::combine` intersects a
20519    /// stack key with each driver page BEFORE the coverage skip —
20520    /// `push.key ∈ hash_keys` → `ProbePushed::Combined`, the subtree
20521    /// re-executes per driver page — while an off-stack key is
20522    /// coverage-skipped and the inherited filter is page-constant →
20523    /// `ProbePushed::Ancestor`, the subtree executes once with the
20524    /// inherited push applied. The cost model must price the walk's conditioned
20525    /// page (per page, or once), not the unpushed once-read. Asserted
20526    /// by COMPOSITION: the fixture recomputes the walk page
20527    /// (`subtree_page_cost`, same push), the conditioned driver work, and
20528    /// the page count from the same primitives the cost model uses, then
20529    /// requires exact equality — no hand-derived price bands.
20530    #[test]
20531    fn all_covered_walk_splits_on_the_push_combine_outcome() {
20532        let mut profile = StatsProfile::default();
20533        for (pred, rows, subjects, objects) in [
20534            // The outer driver: ?wkt <p1> ?y — hosts BOTH the push key
20535            // (?wkt, subject) and the Ancestor case's join key (?y, object).
20536            ("http://ex/p1", 100_000_u64, 5_000_u128, 80_000_u128),
20537            // The inner subtree: ?wkt <p2> ?m (driver), ?m <p3> ?y (probe)
20538            // — exposing ?wkt for the Combined key and ?y for the Ancestor
20539            // key, and hosting the push key so the walk conditions it.
20540            ("http://ex/p2", 2_000, 1_000, 2_000),
20541            ("http://ex/p3", 1_000, 2_000, 5_000),
20542        ] {
20543            profile.predicate_counts.insert(StrHash::new(pred), rows);
20544            profile
20545                .subjects_per_predicate
20546                .insert(StrHash::new(pred), hll_with_n(subjects));
20547            profile
20548                .objects_per_predicate
20549                .insert(StrHash::new(pred), hll_with_n(objects));
20550        }
20551        let driver = PlanNode::Scan(var_scan(Some("wkt"), "http://ex/p1", Some("y"), 100_000));
20552        let inner = PlanNode::Join {
20553            left: Box::new(PlanNode::Scan(var_scan(
20554                Some("wkt"),
20555                "http://ex/p2",
20556                Some("m"),
20557                2_000,
20558            ))),
20559            right: Box::new(PlanNode::Scan(var_scan(
20560                Some("m"),
20561                "http://ex/p3",
20562                Some("y"),
20563                1_000,
20564            ))),
20565            hash_keys: vec![var("m")],
20566            probe_key_domains: Vec::new(),
20567            probe_key_overlap_milli: Vec::new(),
20568            rhs_hostable_keys: Vec::new().into(),
20569            meta: JoinMeta {
20570                semi_gate: None,
20571                star_arms: None,
20572                strategy: JoinStrategy::Broadcast,
20573                produced_row_count_estimate: 1_500,
20574                own_push_removed_row_count_estimate: 1_500,
20575            },
20576        };
20577        // The inherited push: the driver's FULL ?wkt domain (5,000 terms —
20578        // an ancestor list covering the driver's whole key domain), which
20579        // makes the conditioning bound its own no-op (pushed_val_count == domain
20580        // → bound == basis) and keeps the driver's standalone multi-page
20581        // geometry — the shape where Combined and Ancestor actually
20582        // differ.
20583        let push = ContainingPush {
20584            key: var("wkt"),
20585            pushed_val_count: 5_000,
20586        };
20587        // The composed expectation — the same primitives the cost model uses.
20588        let page_rows = seat_page_rows(&driver, &inner, None);
20589        let walk = {
20590            let mut budget = SUBTREE_WALK_NODE_BUDGET;
20591            subtree_page_cost(Some(&profile), &inner, &push, None, &mut budget)
20592        };
20593        // Both cases ride the all-covered road: ?wkt page-distinct
20594        // 24,576·5,000/100,000 = 1,228 ≥ 9/10 × 1,000 (the inner
20595        // subtree's ?wkt domain); ?y page-distinct 19,660 ≥ 9/10 × 5,000
20596        // (the inner probe's ?y domain). Drop allowed: a subtree arm
20597        // always is (`source_coverage_drop`).
20598        //
20599        // COMBINED: the push key IS this join's hash key.
20600        let keys = [var("wkt")];
20601        let driver_rows = seat_driver_work_rows(&driver, &keys, Some(&profile)).min(
20602            containing_push_driver_bound(Some(&profile), &driver, &push.key, push.pushed_val_count)
20603                .unwrap_or(u64::MAX),
20604        );
20605        let pages = driver_rows.div_ceil(page_rows);
20606        assert!(pages > 1, "the fixture needs a multi-page driver");
20607        let combined = seat_cost_total(Some(&profile), &driver, &inner, &keys, None, Some(&push));
20608        assert_eq!(
20609            combined,
20610            SeatCost {
20611                rows: driver_rows + pages * walk.rows,
20612                seeks: pages * walk.seeks,
20613            },
20614            "Combined: the subtree re-executes per driver page"
20615        );
20616        // The override replaced the arithmetic's once-read, not reproduced
20617        // it (the pre-fix price).
20618        assert_ne!(
20619            combined.rows,
20620            driver_rows + inner.produced_row_count_estimate(),
20621            "the all-covered road must not stay the unpushed once-read"
20622        );
20623        // ANCESTOR: the push key is OFF this join's keys — the subtree
20624        // executes once, conditioned by the inherited list.
20625        let keys = [var("y")];
20626        let driver_rows = seat_driver_work_rows(&driver, &keys, Some(&profile)).min(
20627            containing_push_driver_bound(Some(&profile), &driver, &push.key, push.pushed_val_count)
20628                .unwrap_or(u64::MAX),
20629        );
20630        let ancestor = seat_cost_total(Some(&profile), &driver, &inner, &keys, None, Some(&push));
20631        assert_eq!(
20632            ancestor,
20633            SeatCost {
20634                rows: driver_rows + walk.rows,
20635                seeks: walk.seeks,
20636            },
20637            "Ancestor: one conditioned execution serves every page"
20638        );
20639    }
20640
20641    /// A top-level Join driver's once-cost is ONE
20642    /// unpushed seat of that join — the inner probe answers its
20643    /// per-page (or fetch-once) road, it is not read whole — and the
20644    /// inner cost model's seeks ride home (they were dropped when the
20645    /// once-cost was a bare u64). The shape is the live hasGeom stamp
20646    /// itself (pages=1, seeks/page=500, matched/page=514 -> per-page).
20647    #[test]
20648    fn join_driver_once_cost_prices_one_unpushed_seat() {
20649        let mut profile = StatsProfile::default();
20650        for (pred, rows, subjects, objects) in [
20651            ("http://ex/type", 500_u64, 500_u128, 500_u128),
20652            ("http://ex/hasGeom", 817_201, 793_204, 817_201),
20653        ] {
20654            profile.predicate_counts.insert(StrHash::new(pred), rows);
20655            profile
20656                .subjects_per_predicate
20657                .insert(StrHash::new(pred), hll_with_n(subjects));
20658            profile
20659                .objects_per_predicate
20660                .insert(StrHash::new(pred), hll_with_n(objects));
20661        }
20662        let type_scan = PlanNode::Scan(var_scan(Some("tr"), "http://ex/type", None, 500));
20663        let geom_scan = PlanNode::Scan(var_scan(
20664            Some("tr"),
20665            "http://ex/hasGeom",
20666            Some("g"),
20667            817_201,
20668        ));
20669        let inner = PlanNode::Join {
20670            left: Box::new(type_scan.clone()),
20671            right: Box::new(geom_scan.clone()),
20672            hash_keys: vec![var("tr")],
20673            probe_key_domains: Vec::new(),
20674            probe_key_overlap_milli: Vec::new(),
20675            rhs_hostable_keys: Vec::new().into(),
20676            meta: JoinMeta {
20677                semi_gate: None,
20678                star_arms: None,
20679                strategy: JoinStrategy::Broadcast,
20680                produced_row_count_estimate: 515,
20681                own_push_removed_row_count_estimate: 515,
20682            },
20683        };
20684        // Delegation: the once-cost IS the join's own seat, rows and seeks.
20685        let once = driver_once_cost(Some(&profile), &inner, None);
20686        let seat = seat_cost_total(
20687            Some(&profile),
20688            &type_scan,
20689            &geom_scan,
20690            &[var("tr")],
20691            None,
20692            None,
20693        );
20694        assert_eq!(
20695            once, seat,
20696            "the once-cost delegates to ONE unpushed seat of the join"
20697        );
20698        // The phantom whole read is gone: the inner probe answers keyed
20699        // (~514 matched rows on one page), it is not read whole — the raw
20700        // arm sum this replaced billed all 817,201.
20701        assert!(
20702            once.rows < 500 + 817_201,
20703            "the once-cost must not bill the inner probe's whole read (got {})",
20704            once.rows
20705        );
20706        // The inner cost model's probe seeks ride home.
20707        assert!(
20708            once.seeks > 0,
20709            "the inner seating's probe seeks must ride home"
20710        );
20711    }
20712
20713    /// A stamped custom driver that HOSTS
20714    /// the pushed key answers the keyed regime — the pushed terms go
20715    /// straight to `execute_custom_op`, the keyless drain never runs — so
20716    /// its conditioned work is `keyed_cost(pushed_val_count)`, a work
20717    /// number derived from the list length. The old price was
20718    /// `min(sweep, pushed_val_count)`: a work number min'd against the
20719    /// bare list length (the bound collapses to the list for a hosting
20720    /// op, basis = domain = produced), pricing a 500-value push at 500
20721    /// where the executor pays 4,000 relate units. Asserted by
20722    /// composition: the cost estimate equals the keyed driver term plus the mirror
20723    /// road's one-page answer (the probe hosts the pushed key on a
20724    /// different slot, so the ancestor road runs — the walk leaf's own
20725    /// formula), and an op that does NOT emit the pushed key keeps the
20726    /// unpushed sweep (the bound never fires for it).
20727    #[test]
20728    fn hosting_custom_driver_prices_the_keyed_regime() {
20729        let mut profile = StatsProfile::default();
20730        for (pred, rows, subjects, objects) in [
20731            ("http://ex/geoCand", 36_862_u64, 36_862_u128, 36_862_u128),
20732            ("http://ex/asWKT", 817_201, 817_201, 795_534),
20733        ] {
20734            profile.predicate_counts.insert(StrHash::new(pred), rows);
20735            profile
20736                .subjects_per_predicate
20737                .insert(StrHash::new(pred), hll_with_n(subjects));
20738            profile
20739                .objects_per_predicate
20740                .insert(StrHash::new(pred), hll_with_n(objects));
20741        }
20742        // A candidate-emitting geo op: ?g candidates with their WKTs — it
20743        // HOSTS the pushed key ?g (the keyspace comment's own shape).
20744        let op_cost = CustomOpCost {
20745            drain_rows: 36_862,
20746            per_key_unit: 8,
20747            inline_point_unit: 1,
20748            direct_probe: true,
20749            probe_keyed_columns: 0b1,
20750            probe_filter_unit: 8,
20751            probe_memo_entry_rows: 0,
20752        };
20753        let inner_op = CustomOp {
20754            plugin_id: "cost-test",
20755            op_id: "op",
20756            payload: crate::plugin::PluginPayloadBox::new(CostTestPayload),
20757            children: Vec::new(),
20758            variables: vec![var("g"), var("wkt")],
20759            produced_row_count_estimate: 36_862,
20760            cost: Some(op_cost),
20761            pinned: Vec::new(),
20762        };
20763        // The regime price: direct relate (500 × 8) vs drain + semi-join —
20764        // the direct road wins here, 4,000 work units.
20765        let push = ContainingPush {
20766            key: var("g"),
20767            pushed_val_count: 500,
20768        };
20769        let keyed = inner_op.keyed_cost(push.pushed_val_count, Some(0)).unwrap();
20770        let geo_op = PlanNode::CustomNode(inner_op);
20771        let geom_scan =
20772            PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 817_201));
20773        let keys = [var("wkt")];
20774        let seat = seat_cost_total(
20775            Some(&profile),
20776            &geo_op,
20777            &geom_scan,
20778            &keys,
20779            None,
20780            Some(&push),
20781        );
20782        // The composed expectation: the keyed driver term plus the mirror
20783        // road's one-page answer, from the same primitives the cost model uses —
20784        // the pushed ?g list priced against ?g's OWN domain on the probe
20785        // (the shape pages off min(cell, bound) = 500 → one page).
20786        let domain = join_key_domain_for_node(Some(&profile), &geom_scan, &push.key).unwrap();
20787        let (probe_seeks, probe_matched) = probe_broadcast_price(
20788            817_201,
20789            &[(false, push.pushed_val_count, domain, 1_000)],
20790            false,
20791        );
20792        assert_eq!(
20793            seat,
20794            SeatCost {
20795                rows: keyed + probe_matched,
20796                seeks: probe_seeks,
20797            },
20798            "the conditioned custom driver prices keyed_cost, not the list length"
20799        );
20800        // The discriminator: the old min priced the driver term at the
20801        // bare list length (500) — the keyed regime's work must survive.
20802        assert!(
20803            seat.rows > push.pushed_val_count + probe_matched,
20804            "the keyed driver term must exceed the bare list length (got {})",
20805            seat.rows
20806        );
20807        // An op that does NOT emit the pushed key cannot consume the push:
20808        // the bound never fires and the unpushed sweep is billed.
20809        let unhosted = ContainingPush {
20810            key: var("zz"),
20811            pushed_val_count: 500,
20812        };
20813        let seat_unhosted = seat_cost_total(
20814            Some(&profile),
20815            &geo_op,
20816            &geom_scan,
20817            &keys,
20818            None,
20819            Some(&unhosted),
20820        );
20821        assert!(
20822            seat_unhosted.rows > 331_758,
20823            "an unhosted custom driver keeps the sweep (got {})",
20824            seat_unhosted.rows
20825        );
20826    }
20827
20828    /// Review r2 CRITICAL: "same slot" is the slot of the FIRST SURVIVING
20829    /// broadcast key — the same walk `join_keys_scan_filter` runs (stored
20830    /// key order, skipping empty, over-threshold, and domain-covering
20831    /// lists) — not merely "some hash key shares the ancestor's slot".
20832    /// Pinned at the helper level with the exact roads: Case A — a join
20833    /// keyed `[?wkt, ?g]` under a wide ancestor `?g` push: `?wkt`
20834    /// survives first (its 148-key page list does not cover the probe's
20835    /// ~1,011-key `?wkt` domain) on the Object slot, the ancestor key
20836    /// sits on Subject, so the executor keeps the ANCESTOR filter and the
20837    /// helper prices the wide ancestor road (whole arm per page) — the
20838    /// old `any`-key test saw `?g` sharing the ancestor slot, called it
20839    /// same-slot, and let the cheap interior road stand. Case B — a
20840    /// same-slot key that is domain-COVERED survives nothing: the
20841    /// ancestor road runs unconditionally there too, even though the
20842    /// interior road's price would be the no-list sentinel. Case C — the
20843    /// same-slot contrast: an uncovered same-slot key intersects with the
20844    /// ancestor list, and when the interior road is the cheaper bound the
20845    /// helper keeps it.
20846    #[test]
20847    fn same_slot_walks_hash_keys_in_order() {
20848        let mut profile = StatsProfile::default();
20849        for (pred, rows, subjects, objects) in [
20850            ("http://ex/asWKT", 20_000_u64, 1_000_u128, 1_000_u128),
20851            ("http://ex/wktDriver", 100_000, 500, 30_000),
20852            ("http://ex/gDriver", 100_000, 5_000, 100_000),
20853        ] {
20854            profile.predicate_counts.insert(StrHash::new(pred), rows);
20855            profile
20856                .subjects_per_predicate
20857                .insert(StrHash::new(pred), hll_with_n(subjects));
20858            profile
20859                .objects_per_predicate
20860                .insert(StrHash::new(pred), hll_with_n(objects));
20861        }
20862        let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 20_000));
20863        // The WIDE ancestor: {g, 24,576} over the probe's ~1,011-key `?g`
20864        // domain — the pushed road matches the whole arm per page.
20865        let wide_push = ContainingPush {
20866            key: var("g"),
20867            pushed_val_count: 24_576,
20868        };
20869        // Case A — multi-key join, `?wkt` survives first: the driver
20870        // hosts both keys; the `?wkt` page list (~148 keys over the
20871        // driver's 500-key domain) does not cover the probe's ~1,011-key
20872        // `?wkt` domain, so `?wkt` survives and its slot (Object) differs
20873        // from the ancestor slot (Subject). The executor fetches through
20874        // the ancestor's 24,576-term `?g` list, which covers the probe's
20875        // whole `?g` domain — the whole arm, per page.
20876        let shape_keys_a = [(false, 148, 1_011, 1_000), (true, 8_890, 1_011, 1_000)];
20877        let road_a = probe_side_mirror_road(
20878            Some(&profile),
20879            &probe,
20880            &[var("wkt"), var("g")],
20881            &shape_keys_a,
20882            true,
20883            Some(&wide_push),
20884        );
20885        assert_eq!(
20886            road_a,
20887            Some(SeatCost {
20888                rows: 20_000,
20889                seeks: 24_576,
20890            }),
20891            "the surviving interior key sits on another slot: the wide ancestor road, priced"
20892        );
20893        // Case B — same-slot and domain-covered: the `?g` key shares the
20894        // ancestor slot AND its page list (~1,229 keys) covers the probe's
20895        // ~1,011-key `?g` domain, so it survives nothing and the ancestor
20896        // road runs unconditionally — the no-list sentinel must not stand
20897        // the mirror down.
20898        let shape_keys_b = [(true, 1_229, 1_011, 1_000)];
20899        let road_b = probe_side_mirror_road(
20900            Some(&profile),
20901            &probe,
20902            &[var("g")],
20903            &shape_keys_b,
20904            true,
20905            Some(&wide_push),
20906        );
20907        assert_eq!(
20908            road_b,
20909            Some(SeatCost {
20910                rows: 20_000,
20911                seeks: 24_576,
20912            }),
20913            "a covered same-slot key still leaves the ancestor road"
20914        );
20915        // Case C — the same-slot contrast: an uncovered same-slot key
20916        // intersects with the ancestor list, and when the interior road is
20917        // the cheaper bound the helper keeps it (the executor probes the
20918        // intersected list, which sits below both roads).
20919        let shape_keys_c = [(false, 122, 1_011, 1_000)];
20920        let road_c = probe_side_mirror_road(
20921            Some(&profile),
20922            &probe,
20923            &[var("g")],
20924            &shape_keys_c,
20925            true,
20926            Some(&wide_push),
20927        );
20928        assert_eq!(
20929            road_c, None,
20930            "the cheaper interior road bounds the intersected lists — keep it"
20931        );
20932    }
20933
20934    /// Review CRITICAL 1, the executor-faithful half of the mirror: the
20935    /// executor's filter merge (`merge_broadcast_filters`) keeps the
20936    /// ANCESTOR filter whenever the two keys land on different slots —
20937    /// outer-first, a shorter interior key never steals the
20938    /// BroadcastFilter — so the ancestor road is priced even when the
20939    /// interior road would be the cheaper fetch. The old min-guard priced
20940    /// the cheap interior road here while execution paid the wide
20941    /// ancestor list. Same slot is the contrast: the lists intersect, and
20942    /// the interior road (the cheaper one) bounds the intersection from
20943    /// above. The same numbers, opposite slot placements, distinguish the
20944    /// two policies.
20945    #[test]
20946    fn probe_side_mirror_prefers_the_ancestor_road_across_slots() {
20947        let mut profile = StatsProfile::default();
20948        for (pred, rows, subjects, objects) in [
20949            ("http://ex/wktDriver", 500_u64, 500_u128, 500_u128),
20950            ("http://ex/gDriver", 500, 500, 500),
20951            ("http://ex/asWKT", 817_201, 817_201, 795_534),
20952        ] {
20953            profile.predicate_counts.insert(StrHash::new(pred), rows);
20954            profile
20955                .subjects_per_predicate
20956                .insert(StrHash::new(pred), hll_with_n(subjects));
20957            profile
20958                .objects_per_predicate
20959                .insert(StrHash::new(pred), hll_with_n(objects));
20960        }
20961        let probe = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("wkt"), 817_201));
20962        // The WIDE ancestor: {g, 24,576} against a ~500-key interior list.
20963        let wide_push = ContainingPush {
20964            key: var("g"),
20965            pushed_val_count: 24_576,
20966        };
20967        // Case A — different slots: the interior key ?wkt sits on the
20968        // probe's Object, the ancestor key ?g on its Subject. The
20969        // executor fetches through the ancestor's 24,576-term list; the
20970        // interior road (~514 matched) never runs. The old min-guard
20971        // priced ~514 here — the under-price this fixture kills.
20972        let driver_wkt =
20973            PlanNode::Scan(var_scan(Some("wkt"), "http://ex/wktDriver", Some("x"), 500));
20974        let keys_wkt = [var("wkt")];
20975        let across = seat_cost_total(
20976            Some(&profile),
20977            &driver_wkt,
20978            &probe,
20979            &keys_wkt,
20980            None,
20981            Some(&wide_push),
20982        );
20983        assert!(
20984            across.rows > 500 + 24_000 && across.rows < 500 + 25_200,
20985            "the ancestor road is priced across slots: ~24,576 matched per page (got {})",
20986            across.rows
20987        );
20988        assert!(
20989            across.seeks > 24_000 && across.seeks < 25_200,
20990            "one seek per ancestor term per page (got {})",
20991            across.seeks
20992        );
20993        let standalone =
20994            seat_cost_total(Some(&profile), &driver_wkt, &probe, &keys_wkt, None, None);
20995        assert!(
20996            across.rows > standalone.rows,
20997            "the executor-faithful price is the WIDER road here — the interior road never runs"
20998        );
20999        // Case B — same slot: the interior key ?g and the ancestor key ?g
21000        // both sit on the probe's Subject. The executor intersects the
21001        // lists (⊆ the driver's ~500 terms), so the interior road bounds
21002        // the intersection from above and the wide ancestor list must NOT
21003        // be priced.
21004        let driver_g = PlanNode::Scan(var_scan(Some("g"), "http://ex/gDriver", Some("y"), 500));
21005        let keys_g = [var("g")];
21006        let same = seat_cost_total(
21007            Some(&profile),
21008            &driver_g,
21009            &probe,
21010            &keys_g,
21011            None,
21012            Some(&wide_push),
21013        );
21014        assert!(
21015            same.rows > 500 + 400 && same.rows < 500 + 600,
21016            "same slot intersects: the interior road (~500 matched) bounds the fetch (got {})",
21017            same.rows
21018        );
21019        assert!(
21020            same.seeks > 400 && same.seeks < 600,
21021            "the intersection fetches on the interior list, not the ancestor's (got {})",
21022            same.seeks
21023        );
21024    }
21025
21026    #[test]
21027    fn sweep_cost_is_drain_plus_every_candidate() {
21028        let op = cost_test_op(
21029            1000,
21030            Some(CustomOpCost {
21031                drain_rows: 90,
21032                per_key_unit: 8,
21033                inline_point_unit: 1,
21034                direct_probe: true,
21035                probe_keyed_columns: 0b1,
21036                probe_filter_unit: 8,
21037                probe_memo_entry_rows: 0,
21038            }),
21039        );
21040        assert_eq!(op.sweep_cost(), Some(90 + 1000 * 8));
21041    }
21042
21043    #[test]
21044    fn keyed_cost_picks_direct_until_the_drain_pays_off() {
21045        let op = cost_test_op(
21046            1000,
21047            Some(CustomOpCost {
21048                drain_rows: 900,
21049                per_key_unit: 8,
21050                inline_point_unit: 1,
21051                direct_probe: true,
21052                probe_keyed_columns: 0b1,
21053                probe_filter_unit: 8,
21054                probe_memo_entry_rows: 0,
21055            }),
21056        );
21057        // Direct beats the drain while keys are few: 10×8 = 80 against
21058        // 900 + 10×8 = 980, and the same at 200 keys (1600 vs 2500).
21059        assert_eq!(op.keyed_cost(10, Some(0)), Some(80));
21060        assert_eq!(op.keyed_cost(200, Some(0)), Some(1600));
21061        // At 2000 keys direct is 16000 against drain + min(2000, 1000)
21062        // survivors × 8 = 8900 — the semi-join road wins, and the survivor
21063        // bound is the op's sweep OUTPUT, not the key count.
21064        assert_eq!(op.keyed_cost(2000, Some(0)), Some(8900));
21065    }
21066
21067    #[test]
21068    fn keyed_cost_zero_keys_is_free_and_arithmetic_saturates() {
21069        let op = cost_test_op(
21070            u64::MAX,
21071            Some(CustomOpCost {
21072                drain_rows: u64::MAX,
21073                per_key_unit: 8,
21074                inline_point_unit: 1,
21075                direct_probe: true,
21076                probe_keyed_columns: 0b1,
21077                probe_filter_unit: 8,
21078                probe_memo_entry_rows: 0,
21079            }),
21080        );
21081        assert_eq!(op.keyed_cost(0, Some(0)), Some(0));
21082        // No overflow on the sweep: drain + MAX×8 saturates.
21083        assert_eq!(op.sweep_cost(), Some(u64::MAX));
21084    }
21085
21086    /// A real lowered scan binding `?g` as its object, with the estimate
21087    /// set by hand (refinement's output, simulated).
21088    fn location_scan(estimate: u64) -> PlanNode {
21089        fn first_scan(node: &PlanNode) -> Option<PlanNode> {
21090            match node {
21091                PlanNode::Scan(_) => Some(node.clone()),
21092                PlanNode::Join { left, right, .. }
21093                | PlanNode::Union { left, right }
21094                | PlanNode::LeftJoin { left, right, .. } => {
21095                    first_scan(left).or_else(|| first_scan(right))
21096                }
21097                PlanNode::Filter { inner, .. }
21098                | PlanNode::Extend { inner, .. }
21099                | PlanNode::Slice { inner, .. }
21100                | PlanNode::Distinct { inner, .. }
21101                | PlanNode::Sort { inner, .. }
21102                | PlanNode::Group { inner, .. }
21103                | PlanNode::JoinGraphVar { inner, .. } => first_scan(inner),
21104                PlanNode::CustomNode(op) => op.children.first().and_then(first_scan),
21105                _ => None,
21106            }
21107        }
21108        let plan = LogicalPlan::parse("SELECT ?g WHERE { ?s <http://ex/hasLocation> ?g }").unwrap();
21109        let mut scan = first_scan(&plan.root).expect("single-pattern plan has a scan");
21110        if let PlanNode::Scan(scan_op) = &mut scan {
21111            scan_op.produced_row_count_estimate = estimate;
21112        } else {
21113            panic!("expected a scan");
21114        }
21115        scan
21116    }
21117
21118    fn custom_op_node(estimate: u64) -> PlanNode {
21119        PlanNode::CustomNode(cost_test_op(estimate, None))
21120    }
21121
21122    /// The rewrite's injected shape: `Join(op LEFT, inner, [?g])` under a
21123    /// Broadcast stamp — the orientation `geo_rows <= inner_rows` produces
21124    /// on pre-refinement estimates.
21125    fn op_left_join(op_est: u64, inner_est: u64) -> PlanNode {
21126        PlanNode::Join {
21127            left: Box::new(custom_op_node(op_est)),
21128            right: Box::new(location_scan(inner_est)),
21129            hash_keys: vec![var("g")],
21130            probe_key_domains: Vec::new(),
21131            probe_key_overlap_milli: Vec::new(),
21132            rhs_hostable_keys: Vec::new().into(),
21133            meta: JoinMeta {
21134                semi_gate: None,
21135                star_arms: None,
21136                strategy: JoinStrategy::Broadcast,
21137                produced_row_count_estimate: op_est,
21138                own_push_removed_row_count_estimate: op_est,
21139            },
21140        }
21141    }
21142
21143    #[test]
21144    fn ancestor_push_return_bound_flips_the_comparator_itself() {
21145        // The transects defect at the comparator level, no corrective pass
21146        // involved: the join was seated op-drives because the inner arm
21147        // priced at catalog size; the ancestor push's return bound carried
21148        // on the scan is that arm's true whole read in every seating of
21149        // THIS join, and the round-entry recost bounds the cell at it — so
21150        // refinalize's own swap rule flips the seating. The claim's
21151        // variable (?tr) is foreign to this join's key (?g): the push
21152        // comes from a join above and applies regardless of the seating.
21153        let mut join = op_left_join(5350, 7_827_555);
21154        let PlanNode::Join { right, .. } = &mut join else {
21155            panic!("still a join");
21156        };
21157        let PlanNode::Scan(scan) = &mut **right else {
21158            panic!("right arm is the scan");
21159        };
21160        scan.broadcasted = Some((var("tr"), PatternSlot::Subject));
21161        scan.ancestor_push_return_bound = Some(1525);
21162        refinalize_joins_without_ctx(&mut join, None);
21163        let PlanNode::Join { left, right, .. } = &join else {
21164            panic!("still a join");
21165        };
21166        assert!(
21167            matches!(&**left, PlanNode::Scan(_)),
21168            "inner drives: {left:?}"
21169        );
21170        assert!(matches!(&**right, PlanNode::CustomNode(_)), "op probes");
21171    }
21172
21173    #[test]
21174    fn comparator_keeps_a_pinned_op_on_the_probe_side() {
21175        // The pinned-op invariant, pinned at the COMPARATOR level so it
21176        // survives the placement pass's deletion: the comparator never
21177        // reads `pinned`; the safety is structural. A pin arises only
21178        // when this join's shared key is ground-unique on the driver,
21179        // which prices BOTH arms at ~1 (the op relates exactly that one
21180        // term; the driver scan is a point read) — and ties keep the
21181        // as-built seating, so the pinned probe shape never moves. The
21182        // structural point-lookup override cannot fire either: it swaps
21183        // only a point-lookup SCAN out of the driver seat, and the op is
21184        // not a scan.
21185        let mut op = cost_test_op(1, None);
21186        op.pinned
21187            .push((var("g"), EncodedTerm::from(&Literal::from(1))));
21188        let mut join = PlanNode::Join {
21189            left: Box::new(location_scan(1)),
21190            right: Box::new(PlanNode::CustomNode(op)),
21191            hash_keys: vec![var("g")],
21192            probe_key_domains: Vec::new(),
21193            probe_key_overlap_milli: Vec::new(),
21194            rhs_hostable_keys: Vec::new().into(),
21195            meta: JoinMeta {
21196                semi_gate: None,
21197                star_arms: None,
21198                strategy: JoinStrategy::Broadcast,
21199                produced_row_count_estimate: 1,
21200                own_push_removed_row_count_estimate: 1,
21201            },
21202        };
21203        refinalize_joins_without_ctx(&mut join, None);
21204        let PlanNode::Join { left, right, .. } = &join else {
21205            panic!("still a join")
21206        };
21207        assert!(
21208            matches!(&**left, PlanNode::Scan(_)),
21209            "the point-read driver stays: {left:?}"
21210        );
21211        let PlanNode::CustomNode(op) = &**right else {
21212            panic!("the pinned op stays on the probe side")
21213        };
21214        assert_eq!(op.pinned.len(), 1, "the pin itself survives");
21215    }
21216
21217    #[test]
21218    fn recost_without_a_bound_keeps_today_reset_semantics() {
21219        // No ancestor bound carried: the recost keeps the plain intrinsic
21220        // reset — an unmarked scan's cell is whatever the pattern prices,
21221        // and a scan whose bound was cleared with its claim mark resets to
21222        // intrinsic rather than inheriting a stale clamp.
21223        let mut join = op_left_join(5350, 7_827_555);
21224        refinalize_joins_without_ctx(&mut join, None);
21225        let PlanNode::Join { left, right, .. } = &join else {
21226            panic!("still a join");
21227        };
21228        // No bound: the op (5,350) is the smaller driver and keeps driving.
21229        assert!(
21230            matches!(&**left, PlanNode::CustomNode(_)),
21231            "op still drives"
21232        );
21233        let PlanNode::Scan(scan) = &**right else {
21234            panic!("right arm is the scan");
21235        };
21236        assert_eq!(scan.produced_row_count_estimate, 7_827_555);
21237        assert!(scan.ancestor_push_return_bound.is_none());
21238    }
21239
21240    #[test]
21241    fn clear_broadcast_marks_removes_the_bound_with_the_claim() {
21242        // The bound's lifetime is exactly the claim mark's — the swap-time
21243        // clearer removes the pair together, so a vanished claim can never
21244        // leave an unowned bound pricing a full read.
21245        let mut node = location_scan(1000);
21246        let PlanNode::Scan(scan) = &mut node else {
21247            panic!("location_scan builds a scan");
21248        };
21249        scan.broadcasted = Some((var("tr"), PatternSlot::Subject));
21250        scan.ancestor_push_return_bound = Some(100);
21251        clear_broadcast_marks(&mut node);
21252        let PlanNode::Scan(scan) = &node else {
21253            panic!("still a scan");
21254        };
21255        assert!(scan.broadcasted.is_none());
21256        assert!(scan.ancestor_push_return_bound.is_none());
21257    }
21258
21259    fn explain_est(sparql: &str, profile: Option<&StatsProfile>) -> String {
21260        LogicalPlan::explain(sparql, ExplainFormat::Estimate, false, profile).unwrap()
21261    }
21262
21263    fn explain_sse(sparql: &str, pretty: bool) -> String {
21264        LogicalPlan::explain(sparql, ExplainFormat::Sse, pretty, None).unwrap()
21265    }
21266
21267    fn explain_optimised(sparql: &str) -> String {
21268        LogicalPlan::explain(sparql, ExplainFormat::Optimised, false, None).unwrap()
21269    }
21270
21271    fn explain_optimised_sparql(sparql: &str) -> String {
21272        LogicalPlan::explain(sparql, ExplainFormat::OptimisedSparql, false, None).unwrap()
21273    }
21274
21275    fn domain_on_line(text: &str, line_contains: &str, variable: &str) -> Option<u64> {
21276        let start_at = text.find(line_contains)?;
21277        let slice = &text[start_at..];
21278        let needle = format!("(domain {variable} ");
21279        let start = slice.find(&needle)? + needle.len();
21280        let rest = &slice[start..];
21281        if rest.starts_with('?') {
21282            return None;
21283        }
21284        let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
21285        digits.parse().ok()
21286    }
21287
21288    /// The `~N` row estimate of a scan line matched by `line_contains`.
21289    fn rows_on_line(text: &str, line_contains: &str) -> u64 {
21290        let start_at = text
21291            .find(line_contains)
21292            .unwrap_or_else(|| panic!("no line containing {line_contains:?}: {text}"));
21293        let slice = &text[start_at..];
21294        let needle = "~";
21295        let start = slice.find(needle).expect("scan line prints ~N") + needle.len();
21296        let digits: String = slice[start..]
21297            .chars()
21298            .take_while(|c| c.is_ascii_digit())
21299            .collect();
21300        digits.parse().expect("numeric estimate")
21301    }
21302
21303    #[test]
21304    fn two_pattern_query_produces_two_scans_and_one_join() {
21305        let plan = LogicalPlan::parse(DEMO).unwrap();
21306        let scans = plan.scans().unwrap();
21307        assert_eq!(scans.len(), 2);
21308        let joins = plan.join_ops().unwrap();
21309        assert_eq!(joins.len(), 1);
21310        assert_eq!(joins[0].hash_keys, vec![var("city")]);
21311        assert_eq!(plan.projection, vec![var("person"), var("weather")]);
21312    }
21313
21314    #[test]
21315    fn selective_pattern_is_scanned_first() {
21316        let plan = LogicalPlan::parse(
21317            r#"
21318            SELECT ?person ?city WHERE {
21319              ?person <http://ex/livesIn> ?city .
21320              ?city <http://ex/hasWeather> "Sunny" .
21321            }
21322        "#,
21323        )
21324        .unwrap();
21325
21326        let scans = plan.scans().unwrap();
21327        assert_eq!(scans[0].bound_slots(), 3);
21328        assert_eq!(
21329            scans[0].pattern.object,
21330            Some(EncodedTerm::from(&Literal::from("Sunny")))
21331        );
21332        assert_eq!(
21333            waratah_router::select_axis(&scans[0].pattern).unwrap(),
21334            PartitionAxis::O
21335        );
21336        assert_eq!(scans[1].bound_slots(), 2);
21337    }
21338
21339    #[test]
21340    fn profile_reorders_selective_before_broad() {
21341        let mut live = LiveQuadsProfile::default();
21342        let person = NamedNode::new("http://ex/Person").unwrap();
21343        let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
21344        let hometown = NamedNode::new("http://ex/hasHometown").unwrap();
21345        let brisbane = NamedNode::new("http://ex/Brisbane").unwrap();
21346
21347        for i in 0..100 {
21348            let s = NamedNode::new(format!("http://ex/p{i}")).unwrap();
21349            observe_quad(
21350                &mut live,
21351                &encode_quad(&waratah_storage::Quad::new(
21352                    s.clone(),
21353                    type_pred.clone(),
21354                    person.clone(),
21355                    waratah_storage::GraphName::DefaultGraph,
21356                ))
21357                .unwrap(),
21358                StorageOp::Put,
21359            );
21360            if i < 5 {
21361                observe_quad(
21362                    &mut live,
21363                    &encode_quad(&waratah_storage::Quad::new(
21364                        s,
21365                        hometown.clone(),
21366                        brisbane.clone(),
21367                        waratah_storage::GraphName::DefaultGraph,
21368                    ))
21369                    .unwrap(),
21370                    StorageOp::Put,
21371                );
21372            }
21373        }
21374        let profile = StatsProfile::from(live);
21375
21376        let plan = LogicalPlan::parse_with_profile(
21377            r#"
21378            SELECT ?person WHERE {
21379              ?person <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex/Person> .
21380              ?person <http://ex/hasHometown> <http://ex/Brisbane> .
21381            }
21382            "#,
21383            Some(&profile),
21384        )
21385        .unwrap();
21386
21387        let scans = plan.scans().unwrap();
21388        assert_eq!(scans[0].pattern.object, Some(EncodedTerm::from(&brisbane)));
21389        assert_eq!(scans[0].produced_row_count_estimate, 5);
21390        assert_eq!(
21391            scans[1].subject.as_ref().map(Variable::as_str),
21392            Some("person"),
21393            "type scan should stay the probe: {:?}",
21394            scans[1]
21395        );
21396        assert!(
21397            matches!(
21398                &scans[1].broadcasted,
21399                Some((v, PatternSlot::Subject)) if v.as_str() == "person"
21400            ),
21401            "Broadcast probe should annotate the type scan, got {:?}",
21402            scans[1].broadcasted
21403        );
21404        assert_eq!(
21405            plan.join_ops().unwrap()[0].meta.strategy,
21406            JoinStrategy::Broadcast,
21407            "small left side should hint broadcast"
21408        );
21409    }
21410
21411    #[test]
21412    fn hll_domain_selects_broadcast_despite_large_row_estimates() {
21413        let mut profile = StatsProfile::default();
21414        let pred_lives = waratah_storage::StrHash::new("http://ex/livesIn");
21415        let pred_weather = waratah_storage::StrHash::new("http://ex/hasWeather");
21416
21417        profile.total_puts = 200_000;
21418        profile.predicate_counts.insert(pred_lives, 100_000);
21419        profile.predicate_counts.insert(pred_weather, 50_000);
21420
21421        let mut cities = waratah_stats::HyperLogLog::default_params();
21422        for i in 0..40u128 {
21423            cities.add(i);
21424        }
21425        profile.objects_per_predicate.insert(pred_lives, cities);
21426        let mut weather_objs = waratah_stats::HyperLogLog::default_params();
21427        for i in 0..30u128 {
21428            weather_objs.add(i + 1_000);
21429        }
21430        profile
21431            .objects_per_predicate
21432            .insert(pred_weather, weather_objs);
21433        let mut weather_subjects = waratah_stats::HyperLogLog::default_params();
21434        for i in 0..40u128 {
21435            weather_subjects.add(i);
21436        }
21437        profile
21438            .subjects_per_predicate
21439            .insert(pred_weather, weather_subjects);
21440
21441        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
21442        profile.object_cms.add(waratah_stats::term_key(&sunny), 80);
21443
21444        let plan = LogicalPlan::parse_with_profile(
21445            r#"
21446            SELECT ?person ?city WHERE {
21447              ?person <http://ex/livesIn> ?city .
21448              ?city <http://ex/hasWeather> "Sunny" .
21449            }
21450            "#,
21451            Some(&profile),
21452        )
21453        .unwrap();
21454
21455        let scans = plan.scans().unwrap();
21456        assert_eq!(
21457            scans[0].pattern.object,
21458            Some(EncodedTerm::from(&Literal::from("Sunny"))),
21459            "Sunny pattern should lead, got {:?}",
21460            scans[0]
21461        );
21462        assert!(
21463            matches!(
21464                &scans[1].broadcasted,
21465                Some((v, PatternSlot::Object)) if v.as_str() == "city"
21466            ),
21467            "Broadcast probe should annotate livesIn on ?city, got {:?}",
21468            scans[1].broadcasted
21469        );
21470        assert_eq!(
21471            plan.join_ops().unwrap()[0].meta.strategy,
21472            JoinStrategy::Broadcast,
21473            "small HLL join-key domain should hint broadcast; got {:?}",
21474            plan.join_ops().unwrap()[0].meta.strategy
21475        );
21476    }
21477
21478    #[test]
21479    fn hll_domain_selects_shuffle_when_both_sides_large() {
21480        let mut profile = StatsProfile::default();
21481        let pred_a = waratah_storage::StrHash::new("http://ex/a");
21482        let pred_b = waratah_storage::StrHash::new("http://ex/b");
21483        profile.total_puts = 500_000;
21484        profile.predicate_counts.insert(pred_a, 200_000);
21485        profile.predicate_counts.insert(pred_b, 200_000);
21486
21487        let mut big = waratah_stats::HyperLogLog::default_params();
21488        for i in 0..50_000u128 {
21489            big.add(i);
21490        }
21491        profile.objects_per_predicate.insert(pred_a, big.clone());
21492        profile.subjects_per_predicate.insert(pred_b, big);
21493
21494        let plan = LogicalPlan::parse_with_profile(
21495            r#"
21496            SELECT ?s ?o WHERE {
21497              ?s <http://ex/a> ?x .
21498              ?x <http://ex/b> ?o .
21499            }
21500            "#,
21501            Some(&profile),
21502        )
21503        .unwrap();
21504
21505        assert_eq!(
21506            plan.join_ops().unwrap()[0].meta.strategy,
21507            JoinStrategy::Shuffle,
21508            "large HLL domains on both sides should hint shuffle"
21509        );
21510        let mut annotated = false;
21511        for_each_scan(&plan.root, &mut |scan| {
21512            if scan.broadcasted.is_some() {
21513                annotated = true;
21514            }
21515        });
21516        assert!(
21517            !annotated,
21518            "Shuffle must not annotate probe scans: {:?}",
21519            plan.root
21520        );
21521    }
21522
21523    #[test]
21524    fn join_intersection_domain_selects_broadcast_not_first_child() {
21525        // Left-deep Join(Join(:p, :q), :r) on ?x. :p is scanned first (fewer
21526        // rows) with a *large* distinct-?x HLL; :q has more rows but only ~10
21527        // distinct subjects. `or_else` would keep :p's domain and miss
21528        // broadcast into :r; `min` of the two children is the bound.
21529        let mut profile = StatsProfile::default();
21530        let pred_p = StrHash::new("http://ex/p");
21531        let pred_q = StrHash::new("http://ex/q");
21532        let pred_r = StrHash::new("http://ex/r");
21533        profile.total_puts = 400_000;
21534        profile.predicate_counts.insert(pred_p, 50_000);
21535        profile.predicate_counts.insert(pred_q, 100_000);
21536        profile.predicate_counts.insert(pred_r, 200_000);
21537        profile
21538            .subjects_per_predicate
21539            .insert(pred_p, hll_with_n(50_000));
21540        profile
21541            .objects_per_predicate
21542            .insert(pred_p, hll_with_n(50_000));
21543        profile
21544            .subjects_per_predicate
21545            .insert(pred_q, hll_with_n(10));
21546        profile
21547            .objects_per_predicate
21548            .insert(pred_q, hll_with_n(100_000));
21549        profile
21550            .subjects_per_predicate
21551            .insert(pred_r, hll_with_n(80_000));
21552        profile
21553            .objects_per_predicate
21554            .insert(pred_r, hll_with_n(80_000));
21555
21556        let sparql = r#"
21557            SELECT ?x WHERE {
21558              ?x <http://ex/p> ?a .
21559              ?x <http://ex/q> ?b .
21560              ?x <http://ex/r> ?c .
21561            }
21562        "#;
21563        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
21564        let joins = plan.join_ops().unwrap();
21565        assert_eq!(joins.len(), 2, "left-deep three-scan join, got {joins:?}");
21566        assert_eq!(
21567            joins[1].meta.strategy,
21568            JoinStrategy::Broadcast,
21569            "inner join's ?x domain should be min(50k, 10), so the join into :r broadcasts; got {:?}",
21570            joins[1].meta.strategy
21571        );
21572
21573        let text = explain_est(sparql, Some(&profile));
21574        let outer = domain_on_line(&text, "(broadcast ?x)", "?x");
21575        assert!(
21576            outer.is_some_and(|n| n > 1 && n < 5_000),
21577            "Join should print the intersection ?x domain, not :p's 50k, got {outer:?}: {text}"
21578        );
21579    }
21580
21581    #[test]
21582    fn allow_list_domain_prefers_smallest_under_threshold_key_not_first() {
21583        // `?k` is hash_keys[0] (left subject) with a huge domain; `?x` is small
21584        // and occupies a slot on the right scan. Cost the allow-list on ?x.
21585        let mut profile = StatsProfile::default();
21586        let pred_p = StrHash::new("http://ex/p");
21587        let pred_q = StrHash::new("http://ex/q");
21588        profile.total_puts = 200_000;
21589        profile.predicate_counts.insert(pred_p, 90_000);
21590        profile.predicate_counts.insert(pred_q, 100_000);
21591        profile
21592            .subjects_per_predicate
21593            .insert(pred_p, hll_with_n(50_000));
21594        profile.objects_per_predicate.insert(pred_p, hll_with_n(10));
21595        profile
21596            .subjects_per_predicate
21597            .insert(pred_q, hll_with_n(10));
21598        profile
21599            .objects_per_predicate
21600            .insert(pred_q, hll_with_n(50_000));
21601
21602        let plan = LogicalPlan::parse_with_profile(
21603            r#"
21604            SELECT ?k ?x WHERE {
21605              ?k <http://ex/p> ?x .
21606              ?x <http://ex/q> ?k .
21607            }
21608            "#,
21609            Some(&profile),
21610        )
21611        .unwrap();
21612
21613        let PlanNode::Join {
21614            left,
21615            hash_keys,
21616            meta,
21617            ..
21618        } = &plan.root
21619        else {
21620            panic!("expected Join, got {:?}", plan.root);
21621        };
21622        assert!(
21623            hash_keys.len() >= 2,
21624            "expected two join keys, got {hash_keys:?}"
21625        );
21626        assert_eq!(hash_keys[0].as_str(), "k", "left S-P-O puts ?k first");
21627        assert!(
21628            left.as_scan().is_some(),
21629            "p-scan should stay left (source order, equal rows): {left:?}"
21630        );
21631        assert_eq!(
21632            meta.strategy,
21633            JoinStrategy::Broadcast,
21634            "small ?x domain should hint broadcast, not first-key ?k shuffle; got {:?}",
21635            meta.strategy
21636        );
21637    }
21638
21639    // ---- constant join keys: no-op exclusion / conflict short-circuit ------
21640
21641    const RDF_TYPE_IRI: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
21642
21643    /// The join whose arm is a bare Scan grounding `term` on `?cls` — the
21644    /// parent join of the grounded scan.
21645    fn join_of_grounded_scan<'a>(node: &'a PlanNode, term: &EncodedTerm) -> Option<&'a PlanNode> {
21646        fn grounds_cls(scan: &ScanOp, term: &EncodedTerm) -> bool {
21647            scan.object.as_ref().map(|v| v.as_str()) == Some("cls")
21648                && scan.pattern.object.as_ref() == Some(term)
21649        }
21650        match node {
21651            PlanNode::Join { left, right, .. } => {
21652                if left.as_scan().is_some_and(|scan| grounds_cls(scan, term))
21653                    || right.as_scan().is_some_and(|scan| grounds_cls(scan, term))
21654                {
21655                    return Some(node);
21656                }
21657                join_of_grounded_scan(left, term).or_else(|| join_of_grounded_scan(right, term))
21658            }
21659            PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
21660                join_of_grounded_scan(left, term).or_else(|| join_of_grounded_scan(right, term))
21661            }
21662            PlanNode::Filter { inner, .. }
21663            | PlanNode::Extend { inner, .. }
21664            | PlanNode::Distinct { inner, .. }
21665            | PlanNode::Sort { inner, .. }
21666            | PlanNode::Group { inner, .. }
21667            | PlanNode::JoinGraphVar { inner, .. } => join_of_grounded_scan(inner, term),
21668            PlanNode::CustomNode(op) => op
21669                .children
21670                .iter()
21671                .find_map(|child| join_of_grounded_scan(child, term)),
21672            PlanNode::SubSelect(sub) => join_of_grounded_scan(&sub.inner, term),
21673            _ => None,
21674        }
21675    }
21676
21677    /// A bare `?feature a <cls>` scan grounding `?cls` (object var kept for
21678    /// projection, encoded term in the pattern slot).
21679    fn grounded_class_scan(class: &EncodedTerm, rows: u64) -> PlanNode {
21680        PlanNode::Scan(ScanOp {
21681            ancestor_push_return_bound: None,
21682            fetch_once: None,
21683            pattern: EncodedTriplePattern {
21684                subject: None,
21685                predicate: Some(EncodedTerm::from(&NamedNode::new(RDF_TYPE_IRI).unwrap())),
21686                object: Some(class.clone()),
21687                graph_name: None,
21688            },
21689            subject: Some(var("feature")),
21690            predicate: None,
21691            object: Some(var("cls")),
21692            graph: None,
21693            produced_row_count_estimate: rows,
21694            broadcasted: None,
21695            graph_filter: None,
21696            grounded: vec![(var("cls"), PatternSlot::Object)],
21697            merge_default_graph: false,
21698            marks: Vec::new(),
21699            domain_scan: None,
21700            head_scan: None,
21701            head_scan_counts: None,
21702            domain_counts: None,
21703            iri_only: Vec::new(),
21704            eager: Vec::new(),
21705            join_domains: crate::plan::JoinDomainStamps::default(),
21706        })
21707    }
21708
21709    /// `cartesian(VALUES ?cls {term}, ?feature a Feature ~9_000)` — the
21710    /// failing shape's left arm.
21711    fn class_values_cartesian(term: &EncodedTerm) -> PlanNode {
21712        let values = PlanNode::Values(ValuesOp {
21713            variables: vec![var("cls")],
21714            rows: vec![vec![Some(term.clone())]],
21715            strings: Vec::new(),
21716            blobs: Vec::new(),
21717        });
21718        let feature_scan = PlanNode::Scan(ScanOp {
21719            ancestor_push_return_bound: None,
21720            fetch_once: None,
21721            pattern: EncodedTriplePattern {
21722                subject: None,
21723                predicate: Some(EncodedTerm::from(&NamedNode::new(RDF_TYPE_IRI).unwrap())),
21724                object: Some(EncodedTerm::from(
21725                    &NamedNode::new("http://ex/Feature").unwrap(),
21726                )),
21727                graph_name: None,
21728            },
21729            subject: Some(var("feature")),
21730            predicate: None,
21731            object: None,
21732            graph: None,
21733            produced_row_count_estimate: 9_000,
21734            broadcasted: None,
21735            graph_filter: None,
21736            grounded: Vec::new(),
21737            merge_default_graph: false,
21738            marks: Vec::new(),
21739            domain_scan: None,
21740            head_scan: None,
21741            head_scan_counts: None,
21742            domain_counts: None,
21743            iri_only: Vec::new(),
21744            eager: Vec::new(),
21745            join_domains: crate::plan::JoinDomainStamps::default(),
21746        });
21747        PlanNode::Join {
21748            left: Box::new(values),
21749            right: Box::new(feature_scan),
21750            hash_keys: Vec::new(),
21751            probe_key_domains: Vec::new(),
21752            probe_key_overlap_milli: Vec::new(),
21753            rhs_hostable_keys: Vec::new().into(),
21754            meta: JoinMeta {
21755                semi_gate: None,
21756                star_arms: None,
21757                strategy: JoinStrategy::Hash,
21758                produced_row_count_estimate: 9_000,
21759                own_push_removed_row_count_estimate: 9_000,
21760            },
21761        }
21762    }
21763
21764    fn type_domain_profile() -> StatsProfile {
21765        let mut profile = StatsProfile {
21766            total_puts: 200_000,
21767            ..Default::default()
21768        };
21769        profile
21770            .predicate_counts
21771            .insert(StrHash::new(RDF_TYPE_IRI), 190_000);
21772        profile
21773            .subjects_per_predicate
21774            .insert(StrHash::new(RDF_TYPE_IRI), hll_with_n(100_000));
21775        profile
21776            .class_counts
21777            .insert(StrHash::new("http://ex/Feature"), 9_000);
21778        profile
21779            .class_counts
21780            .insert(StrHash::new("http://ex/FerryRoute"), 938);
21781        profile
21782    }
21783
21784    #[test]
21785    fn constant_class_key_lets_the_smaller_type_scan_drive_the_join() {
21786        // The failing shape: cartesian(VALUES ?cls{FerryRoute}, ?feature a
21787        // Feature ~9000) joined with (?feature a FerryRoute ~938, ?cls
21788        // grounded). ?cls is ground-unique on BOTH sides with the SAME term
21789        // — a no-op filter — so its domain-1 must not win the per-side
21790        // minimum: pre-fix the 9,000-row Feature arm looked like the cheap
21791        // driver (domain 1) and the join estimated 9,000; post-fix the
21792        // 938-row FerryRoute scan drives and the join estimates 938.
21793        let profile = type_domain_profile();
21794        let ferry = EncodedTerm::from(&NamedNode::new("http://ex/FerryRoute").unwrap());
21795        let sparql = r#"
21796            SELECT ?feature WHERE {
21797              VALUES ?cls { <http://ex/FerryRoute> }
21798              ?feature a <http://ex/Feature> .
21799              ?feature a ?cls .
21800            }
21801        "#;
21802        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
21803        let join = join_of_grounded_scan(&plan.root, &ferry)
21804            .expect("join over the grounded FerryRoute scan in plan");
21805        let PlanNode::Join {
21806            left, right, meta, ..
21807        } = join
21808        else {
21809            panic!("expected a Join, got {join:?}");
21810        };
21811        // The greedy association pass connects the 1-row VALUES to the ?cls-keyed scan
21812        // FIRST (the Feature scan shares no variable with VALUES), so the
21813        // Broadcast ground lands on the probe arm at association time: the 1-row
21814        // VALUES drives and the grounded 938-row FerryRoute scan probes.
21815        // Same work as the old swapped orientation, one boundary earlier.
21816        let ferry_scan = match (left.as_ref(), right.as_ref()) {
21817            (_, PlanNode::Scan(scan)) if scan.pattern.object.as_ref() == Some(&ferry) => scan,
21818            _ => panic!(
21819                "expected the grounded FerryRoute scan as the VALUES join's probe, got {join:?}"
21820            ),
21821        };
21822        assert_eq!(ferry_scan.produced_row_count_estimate, 938);
21823        assert_eq!(ferry_scan.pattern.object.as_ref(), Some(&ferry));
21824        // `ground_and_recost_broadcasted_arm` binds ?cls and must refresh the
21825        // scan's stamps: the free ?cls left the rdf:type subject stamp
21826        // `Deferred`; binding it to FerryRoute makes the exact class count
21827        // usable. Removing that refresh would leave Deferred here.
21828        assert_eq!(
21829            ferry_scan.join_domains.get(JoinKeySlot::Subject),
21830            JoinDomainStamp::Known(938),
21831            "broadcast grounding must promote the rdf:type subject stamp"
21832        );
21833        assert_eq!(
21834            meta.produced_row_count_estimate, 938,
21835            "join estimate must follow the driving scan, not the 9,000-row arm"
21836        );
21837        assert_eq!(
21838            meta.own_push_removed_row_count_estimate, 938,
21839            "the recorded pre-push stamp agrees here: the near-key ?feature \
21840             factor (9,000 distinct subjects among 9,000 rows) already models \
21841             the multiplicity the push conditions"
21842        );
21843        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
21844    }
21845
21846    /// A pinned join key makes a CustomNode a POINT only when the op has one
21847    /// output column. A multi-column op (the text subject resolve with its
21848    /// graph column) keeps emitting one row per remaining output value, so
21849    /// its estimate must survive the pin; collapsing it to 1 prices every
21850    /// join above it as a one-row arm and can re-orient the plan around a
21851    /// phantom point read. The pin itself still lands — the executor uses it
21852    /// as a filter — only the estimate is guarded.
21853    #[test]
21854    fn pinning_a_key_does_not_make_a_multi_column_custom_op_a_point() {
21855        let graph = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
21856        let driver = PlanNode::Values(ValuesOp {
21857            variables: vec![var("g")],
21858            rows: vec![vec![Some(graph.clone())]],
21859            strings: Vec::new(),
21860            blobs: Vec::new(),
21861        });
21862
21863        let mut two_column = cost_test_op(1_000, None);
21864        two_column.variables = vec![var("s"), var("g")];
21865        let mut right = PlanNode::CustomNode(two_column);
21866        ground_and_recost_broadcasted_arm(&driver, &mut right, &[var("g")], None);
21867        let PlanNode::CustomNode(op) = &right else {
21868            panic!("expected the CustomNode");
21869        };
21870        assert_eq!(
21871            op.pinned,
21872            vec![(var("g"), graph)],
21873            "the grounded key still pins"
21874        );
21875        assert_eq!(
21876            op.produced_row_count_estimate, 1_000,
21877            "the free subject column keeps the window's cardinality"
21878        );
21879
21880        // Control: one output column fixed by the pin IS a point.
21881        let mut one_column = cost_test_op(1_000, None);
21882        one_column.variables = vec![var("g")];
21883        let mut right = PlanNode::CustomNode(one_column);
21884        ground_and_recost_broadcasted_arm(&driver, &mut right, &[var("g")], None);
21885        let PlanNode::CustomNode(op) = &right else {
21886            panic!("expected the CustomNode");
21887        };
21888        assert_eq!(op.produced_row_count_estimate, 1);
21889    }
21890
21891    #[test]
21892    fn constant_key_excluded_from_allow_list_domain_aggregation() {
21893        // Direct look at `join_key_domain_for_allow_list` on the failing
21894        // shape's arms: the ?cls no-op key must be skipped, so the surviving
21895        // ?feature domain (9,000, capped at the producer's rows) wins the
21896        // minimum instead of the constant key's domain-1.
21897        let profile = type_domain_profile();
21898        let ferry = EncodedTerm::from(&NamedNode::new("http://ex/FerryRoute").unwrap());
21899        let cartesian = class_values_cartesian(&ferry);
21900        let ferry_scan = grounded_class_scan(&ferry, 938);
21901        let keys = [var("cls"), var("feature")];
21902        let producer_domain = join_key_domain_for_allow_list(
21903            Some(&profile),
21904            &cartesian,
21905            &ferry_scan,
21906            &keys,
21907            cartesian.produced_row_count_estimate(),
21908        );
21909        assert_eq!(
21910            producer_domain,
21911            Some(9_000),
21912            "?cls is a no-op filter and must not drag the minimum to 1"
21913        );
21914        let probe_domain = join_key_domain_for_allow_list(
21915            Some(&profile),
21916            &ferry_scan,
21917            &cartesian,
21918            &keys,
21919            ferry_scan.produced_row_count_estimate(),
21920        );
21921        assert_eq!(probe_domain, Some(938));
21922    }
21923
21924    #[test]
21925    fn conflicting_ground_join_keys_substitute_a_zero_row_node() {
21926        // Same shape, but the right scan grounds ?cls to a DIFFERENT term:
21927        // the equijoin keys can never match, so the join is replaced by the
21928        // zero-row node and neither arm executes.
21929        let ferry = EncodedTerm::from(&NamedNode::new("http://ex/FerryRoute").unwrap());
21930        let bus = EncodedTerm::from(&NamedNode::new("http://ex/BusRoute").unwrap());
21931        let cartesian = class_values_cartesian(&ferry);
21932
21933        // join_nodes substitutes at construction time …
21934        let built = join_nodes(cartesian.clone(), grounded_class_scan(&bus, 938), None);
21935        let PlanNode::Values(values) = &built else {
21936            panic!("expected the zero-row substitution, got {built:?}");
21937        };
21938        // Schema-preserving: zero ROWS, but the arms' output variables stay
21939        // declared so a UNION above keeps them always-bound (a zero-column
21940        // node would demote ?cls/?feature to maybe-unbound and strip them
21941        // from the next join's hash keys).
21942        assert!(values.rows.is_empty());
21943        assert_eq!(
21944            values
21945                .variables
21946                .iter()
21947                .map(Variable::as_str)
21948                .collect::<Vec<_>>(),
21949            vec!["cls", "feature"],
21950            "the union of both arms' output variables"
21951        );
21952        assert_eq!(built.produced_row_count_estimate(), 0);
21953
21954        // … and refinalize_joins substitutes a Join that reached it
21955        // un-substituted (grounds can materialize via recost-time
21956        // specializations), so the rewrite is stable across passes.
21957        let mut node = PlanNode::Join {
21958            left: Box::new(cartesian),
21959            right: Box::new(grounded_class_scan(&bus, 938)),
21960            hash_keys: vec![var("cls"), var("feature")],
21961            probe_key_domains: Vec::new(),
21962            probe_key_overlap_milli: Vec::new(),
21963            rhs_hostable_keys: Vec::new().into(),
21964            meta: JoinMeta {
21965                semi_gate: None,
21966                star_arms: None,
21967                strategy: JoinStrategy::Broadcast,
21968                produced_row_count_estimate: 9_000,
21969                own_push_removed_row_count_estimate: 9_000,
21970            },
21971        };
21972        refinalize_joins_without_ctx(&mut node, None);
21973        assert!(
21974            matches!(node, PlanNode::Values(ref values) if values.rows.is_empty()),
21975            "expected the zero-row substitution after refinalize, got {node:?}"
21976        );
21977        assert_eq!(node.produced_row_count_estimate(), 0);
21978    }
21979
21980    /// The emptied union arm must stay schema-preserving all the way up.
21981    /// The first arm joins two single-row VALUES binding ?b to DIFFERENT
21982    /// terms — `conflicting_ground_keys` proves it empty and
21983    /// `provably_empty_join` replaces it with a zero-row node that DECLARES
21984    /// the arm's variables — so ?b stays always-bound above the UNION and a
21985    /// join above the union hash-joins on ?b instead of degrading to a
21986    /// cartesian with soft reconciliation. (Without pins this is the
21987    /// reachable trigger: `bind_scan_equality` refuses to overwrite an
21988    /// existing ground, so scan-side conflicts cannot materialize, but two
21989    /// disagreeing VALUES producers collide directly.)
21990    #[test]
21991    fn emptied_union_arm_keeps_hash_join_above() {
21992        let plan = LogicalPlan::parse(
21993            r#"SELECT ?s ?y WHERE {
21994              {
21995                VALUES ?b { <http://ex/crow> }
21996                VALUES ?b { <http://ex/other> }
21997                ?s <http://ex/p> ?y .
21998              }
21999              UNION
22000              {
22001                VALUES ?b { <http://ex/crow> }
22002                ?s <http://ex/q> ?y .
22003              }
22004              ?y <http://ex/rel> ?b .
22005            }"#,
22006        )
22007        .unwrap();
22008        let PlanNode::Join {
22009            hash_keys,
22010            left: root_left,
22011            right: root_right,
22012            ..
22013        } = &plan.root
22014        else {
22015            panic!("expected the root join over the union, got {:?}", plan.root)
22016        };
22017        // The commutative swap may seat either side as driver; find the union.
22018        let union = match (root_left.as_ref(), root_right.as_ref()) {
22019            (PlanNode::Union { .. }, _) => root_left,
22020            (_, PlanNode::Union { .. }) => root_right,
22021            _ => panic!(
22022                "expected the union under the root join, got {:?}",
22023                plan.root
22024            ),
22025        };
22026        // Both arms' patterns bind ?y, so the root join keys are [?b, ?y].
22027        // The regression signal is ?b's PRESENCE: with a zero-column empty
22028        // arm, the union demotes ?b to maybe-unbound and the keys degrade
22029        // to [?y] — a cartesian on ?b with soft reconciliation.
22030        let key_names: Vec<&str> = hash_keys.iter().map(Variable::as_str).collect();
22031        assert!(
22032            key_names.contains(&"b"),
22033            "?b stays always-bound above the union, so the join above is a \
22034             hash join on ?b, got keys {hash_keys:?}"
22035        );
22036        let PlanNode::Union { left, right, .. } = union.as_ref() else {
22037            panic!("expected the union on the left, got {union:?}")
22038        };
22039        let empty = [&**left, &**right].into_iter().find_map(|arm| {
22040            let mut node = arm;
22041            while let PlanNode::Filter { inner, .. } = node {
22042                node = inner;
22043            }
22044            match node {
22045                PlanNode::Values(values) if values.rows.is_empty() => Some(values),
22046                _ => None,
22047            }
22048        });
22049        let empty =
22050            empty.unwrap_or_else(|| panic!("expected one collapsed zero-row arm, got {union:?}"));
22051        assert!(
22052            empty.variables.iter().any(|v| v.as_str() == "b"),
22053            "the zero-row arm declares ?b, got {:?}",
22054            empty.variables
22055        );
22056        assert_eq!(
22057            empty.produced_row_count_estimate(),
22058            0,
22059            "the arm is still empty: zero rows execute"
22060        );
22061    }
22062
22063    /// A path operand joined on one of its ends is priced at the
22064    /// values-broadcast bound — `min(leaf price, driver's distinct values)` — not
22065    /// its both-ends-unbound leaf price. Before the clamp, a join whose
22066    /// probe side is an alt-path stamped `finalize`'s estimate with the
22067    /// unbound price (1M per free branch), and every consumer before the
22068    /// end-pass clamp saw it: the reassociation pass's later comparisons and
22069    /// the `refinalize_joins` swap seated the wrong driver.
22070    #[test]
22071    fn path_probe_joined_on_its_end_prices_broadcast_keys() {
22072        // Left: the 1-row VALUES driver. Right: an alt-path with both ends
22073        // open, leaf price 2M (1M per branch) — joined on its start end.
22074        let values = PlanNode::Values(ValuesOp {
22075            variables: vec![var("f")],
22076            rows: vec![vec![Some(EncodedTerm::from(
22077                &NamedNode::new("http://ex/FerryRoute").unwrap(),
22078            ))]],
22079            strings: Vec::new(),
22080            blobs: Vec::new(),
22081        });
22082        let branch = || {
22083            PropertyPath::Predicate(EncodedTerm::from(
22084                &NamedNode::new("http://ex/edge").unwrap(),
22085            ))
22086        };
22087        let path = PlanNode::Path(PathOp {
22088            subject_term: None,
22089            subject: Some(var("f")),
22090            path: PropertyPath::Alternative(Box::new(branch()), Box::new(branch())),
22091            object_term: None,
22092            object: Some(var("g")),
22093            produced_row_count_estimate: 2_000_000,
22094            strings: Vec::new(),
22095            graph: None,
22096            graph_name: None,
22097            graph_filter: None,
22098            merge_default_graph: false,
22099        });
22100        let keys = [var("f")];
22101        let (strategy, produced, own_push_removed) =
22102            finalize_inner_join_meta(&values, &path, &keys, None);
22103        assert_eq!(
22104            produced, 1,
22105            "the path is probed with the driver's 1 distinct key: the \
22106             values-broadcast bound, not the 2M unbound leaf price"
22107        );
22108        assert_eq!(
22109            own_push_removed, 2_000_000,
22110            "the own-push-removed record keeps the bare pattern price — the \
22111             (price ~N) EXPLAIN shows"
22112        );
22113        assert_eq!(strategy, JoinStrategy::Broadcast);
22114        // A path whose ends this join does not bind passes through
22115        // unclamped: a cartesian pays the full leaf price, and both models
22116        // coincide.
22117        let (_, estimate, own_push_removed) = finalize_inner_join_meta(&values, &path, &[], None);
22118        assert_eq!(estimate, 2_000_000);
22119        assert_eq!(own_push_removed, 2_000_000);
22120        // The 1-row VALUES driver always broadcasts, clamped or not.
22121        assert_eq!(strategy, JoinStrategy::Broadcast);
22122    }
22123
22124    /// The both-ends-keyed divergence: the path's START and END are both
22125    /// join keys, the driver pushes 375 distinct ?geom values and 10,000
22126    /// distinct ?feature values. The join output is the intersection of
22127    /// the rows matching each keyed end's push, so the values-broadcast bound
22128    /// is the SMALLER pushed set (375) — the min over binding keys. The
22129    /// old first-key clamp would clamp to 10,000 when the expensive key
22130    /// sorts first, leaving the node (and the end pass's recomputation)
22131    /// looser than the bound the swap decided on. Both consumers now
22132    /// follow one rule (`path_pushed_val_count`) and agree.
22133    #[test]
22134    fn path_probe_bound_and_clamp_agree_on_both_ends_keyed_paths() {
22135        // Driver: two one-column VALUES tables joined cartesian — ?geom
22136        // with 375 distinct values, ?feature with 10,000.
22137        let geoms = PlanNode::Values(ValuesOp {
22138            variables: vec![var("geom")],
22139            rows: (0..375)
22140                .map(|i| {
22141                    vec![Some(EncodedTerm::from(
22142                        &NamedNode::new(format!("http://ex/g{i}")).unwrap(),
22143                    ))]
22144                })
22145                .collect(),
22146            strings: Vec::new(),
22147            blobs: Vec::new(),
22148        });
22149        let features = PlanNode::Values(ValuesOp {
22150            variables: vec![var("feature")],
22151            rows: (0..10_000)
22152                .map(|i| {
22153                    vec![Some(EncodedTerm::from(
22154                        &NamedNode::new(format!("http://ex/f{i}")).unwrap(),
22155                    ))]
22156                })
22157                .collect(),
22158            strings: Vec::new(),
22159            blobs: Vec::new(),
22160        });
22161        let driver = join_nodes(geoms, features, None);
22162        let branch = || {
22163            PropertyPath::Predicate(EncodedTerm::from(
22164                &NamedNode::new("http://ex/edge").unwrap(),
22165            ))
22166        };
22167        let path = PathOp {
22168            subject_term: None,
22169            subject: Some(var("feature")),
22170            path: PropertyPath::Alternative(Box::new(branch()), Box::new(branch())),
22171            object_term: None,
22172            object: Some(var("geom")),
22173            produced_row_count_estimate: 2_000_000,
22174            strings: Vec::new(),
22175            graph: None,
22176            graph_name: None,
22177            graph_filter: None,
22178            merge_default_graph: false,
22179        };
22180        // The expensive key first: the divergence case.
22181        let keys = [var("feature"), var("geom")];
22182        let bounded = path_probe_row_bound(
22183            &PlanNode::Path(path.clone()),
22184            &driver,
22185            &keys,
22186            2_000_000,
22187            None,
22188        );
22189        assert_eq!(
22190            bounded, 375,
22191            "the min over binding keys: the 375-element ?geom push is the \
22192             binding constraint, not the 10,000-element ?feature push that \
22193             sorts first"
22194        );
22195        // The node clamp follows the same rule — the number the swap used
22196        // and the number the end pass recomputes from this node agree.
22197        let mut path_node = PlanNode::Path(path.clone());
22198        clamp_broadcast_probe_estimates(&driver, &mut path_node, &keys, None);
22199        let PlanNode::Path(clamped) = &path_node else {
22200            unreachable!("clamped a path");
22201        };
22202        assert_eq!(
22203            clamped.produced_row_count_estimate, 375,
22204            "the node clamp uses the same min-over-binding-keys rule the \
22205             swap's bound used"
22206        );
22207    }
22208
22209    /// An OPTIONAL whose right arm is a path gets the same probe bound in
22210    /// its in-round stamp: the path is probed with the left's distinct
22211    /// keys, so the matched term is the values-broadcast size, not the 2M
22212    /// unbound leaf price. The two-field stamp splits the frames:
22213    /// `produced` carries the bound (the stage model),
22214    /// `own_push_removed` keeps the bare leaf price (the `(price ~N)`
22215    /// EXPLAIN shows).
22216    #[test]
22217    fn optional_path_right_arm_prices_broadcast_keys() {
22218        let left = PlanNode::Values(ValuesOp {
22219            variables: vec![var("f")],
22220            rows: (0..5)
22221                .map(|i| {
22222                    vec![Some(EncodedTerm::from(
22223                        &NamedNode::new(format!("http://ex/f{i}")).unwrap(),
22224                    ))]
22225                })
22226                .collect(),
22227            strings: Vec::new(),
22228            blobs: Vec::new(),
22229        });
22230        let branch = || {
22231            PropertyPath::Predicate(EncodedTerm::from(
22232                &NamedNode::new("http://ex/edge").unwrap(),
22233            ))
22234        };
22235        let path = PlanNode::Path(PathOp {
22236            subject_term: None,
22237            subject: Some(var("f")),
22238            path: PropertyPath::Alternative(Box::new(branch()), Box::new(branch())),
22239            object_term: None,
22240            object: Some(var("g")),
22241            produced_row_count_estimate: 2_000_000,
22242            strings: Vec::new(),
22243            graph: None,
22244            graph_name: None,
22245            graph_filter: None,
22246            merge_default_graph: false,
22247        });
22248        let keys = [var("f")];
22249        // unmatched = |L| = 5 (the path reports no end domain, so no
22250        // containment reduction); matched = |L| · |R_bound| / dom_L =
22251        // 5 · 5 / 5 = 5 — the 5 pushed values bound the path's return.
22252        let estimate = estimate_left_join_rows(5, &left, &path, &keys, None);
22253        assert_eq!(
22254            estimate, 10,
22255            "5 pass-through rows + 5 values-broadcast matched rows, not the \
22256             2M unbound leaf price"
22257        );
22258        // The stamped meta pair on the same shape. produced = the stage
22259        // model's 10; own-push-removed prices the probe at its bare leaf —
22260        // the alt of two predicate branches re-derives to 2 × 1M from
22261        // shape — so matched = 5 · 2,000,000 / 5 = 2M: unmatched 5 +
22262        // matched 2,000,000 = 2,000,005. Not the values-broadcast bound.
22263        let meta = stamp_left_join_meta(5, &left, &path, &keys, None);
22264        assert_eq!(
22265            meta.produced_row_count_estimate, 10,
22266            "produced: the stage model (values-broadcast bound)"
22267        );
22268        assert_eq!(
22269            meta.own_push_removed_row_count_estimate, 2_000_005,
22270            "own-push-removed: the bare leaf price"
22271        );
22272    }
22273
22274    #[test]
22275    fn all_keys_constant_falls_back_to_todays_join() {
22276        // Every join key ground-unique-same on both sides: no substitution
22277        // (the join still copies the probe side's columns onto the driver
22278        // rows) and the domain aggregation falls back to today's plain
22279        // minimum instead of returning `None`.
22280        let a = EncodedTerm::from(&NamedNode::new("http://ex/A").unwrap());
22281        let b = EncodedTerm::from(&NamedNode::new("http://ex/B").unwrap());
22282        let values = PlanNode::Values(ValuesOp {
22283            variables: vec![var("cls"), var("k")],
22284            rows: vec![vec![Some(a.clone()), Some(b.clone())]],
22285            strings: Vec::new(),
22286            blobs: Vec::new(),
22287        });
22288        let scan = PlanNode::Scan(ScanOp {
22289            ancestor_push_return_bound: None,
22290            fetch_once: None,
22291            pattern: EncodedTriplePattern {
22292                subject: Some(b),
22293                predicate: Some(EncodedTerm::from(
22294                    &NamedNode::new("http://ex/pred").unwrap(),
22295                )),
22296                object: Some(a.clone()),
22297                graph_name: None,
22298            },
22299            subject: Some(var("k")),
22300            predicate: None,
22301            object: Some(var("cls")),
22302            graph: None,
22303            produced_row_count_estimate: 5,
22304            broadcasted: None,
22305            graph_filter: None,
22306            grounded: Vec::new(),
22307            merge_default_graph: false,
22308            marks: Vec::new(),
22309            domain_scan: None,
22310            head_scan: None,
22311            head_scan_counts: None,
22312            domain_counts: None,
22313            iri_only: Vec::new(),
22314            eager: Vec::new(),
22315            join_domains: crate::plan::JoinDomainStamps::default(),
22316        });
22317        let keys = [var("cls"), var("k")];
22318        // Both hosted keys are no-ops: the fallback still yields their
22319        // domain-1 minimum (without the fallback this would be `None`).
22320        assert_eq!(
22321            join_key_domain_for_allow_list(
22322                None,
22323                &values,
22324                &scan,
22325                &keys,
22326                values.produced_row_count_estimate()
22327            ),
22328            Some(1)
22329        );
22330        let built = join_nodes(values, scan, None);
22331        let PlanNode::Join { left, meta, .. } = &built else {
22332            panic!("the constant join must stay intact, got {built:?}");
22333        };
22334        assert!(
22335            matches!(left.as_ref(), PlanNode::Values(_)),
22336            "the 1-row VALUES arm drives, got {:?}",
22337            left
22338        );
22339        // Post-ground re-stamp: this probe's pattern is FULLY ground
22340        // (subject and object terms on both keys), so the Broadcast
22341        // grounding's recost prices it as the point lookup it is — 1 row —
22342        // and join_nodes re-stamps the meta on the post-ground shapes
22343        // (finalize stamped 5 on the pre-ground fixture price; consumers
22344        // must never see that stale number). 1-row driver × 1-row probe = 1.
22345        assert_eq!(
22346            meta.produced_row_count_estimate, 1,
22347            "the join meta follows the grounded point-lookup probe, not the \
22348             stale pre-ground price"
22349        );
22350    }
22351
22352    const TENANT_UNION: &str = r#"
22353        SELECT ?tenant ?x WHERE {
22354          ?tenant a <http://ex/Tenant> .
22355          {
22356            ?x <http://ex/hasTenant> ?tenant .
22357            ?x a <http://ex/Server> .
22358          } UNION {
22359            ?x <http://ex/hasTenant> ?tenant .
22360            ?x a <http://ex/VM> .
22361          }
22362        }
22363    "#;
22364
22365    fn hll_with_n(n: u128) -> waratah_stats::HyperLogLog {
22366        let mut hll = waratah_stats::HyperLogLog::default_params();
22367        for i in 0..n {
22368            hll.add(i);
22369        }
22370        hll
22371    }
22372
22373    #[test]
22374    fn term_dict_reserve_amount_guard_rails() {
22375        use super::{TERM_DICT_RESERVE_FLOOR, TERM_DICT_RESERVE_MAX, term_dict_reserve_amount};
22376        // Below the floor: a mid-query resize at this size costs
22377        // microseconds — default growth, no forced tiny reserve.
22378        assert_eq!(term_dict_reserve_amount(0), None);
22379        assert_eq!(term_dict_reserve_amount(10), None);
22380        assert_eq!(term_dict_reserve_amount(TERM_DICT_RESERVE_FLOOR - 1), None);
22381        // In range: reserve exactly the estimate.
22382        assert_eq!(
22383            term_dict_reserve_amount(TERM_DICT_RESERVE_FLOOR),
22384            Some(TERM_DICT_RESERVE_FLOOR)
22385        );
22386        assert_eq!(term_dict_reserve_amount(758_327), Some(758_327));
22387        // Over the ceiling: clamp — estimates can over-count, and
22388        // conserving memory outranks avoiding a resize.
22389        assert_eq!(
22390            term_dict_reserve_amount(2_000_000),
22391            Some(TERM_DICT_RESERVE_MAX)
22392        );
22393        assert_eq!(
22394            term_dict_reserve_amount(u64::MAX),
22395            Some(TERM_DICT_RESERVE_MAX)
22396        );
22397    }
22398
22399    #[test]
22400    fn path_triple_estimates_track_sparopt_calibration() {
22401        // sparopt reshapes the algebra before Waratah plans over it, so the
22402        // row estimates must agree on relative scan selectivity. These pin
22403        // the rows that sparopt 0.3.9 recalibrated 10× downward (a ground
22404        // object is far more selective than previously assumed), plus the
22405        // unchanged anchors.
22406        assert_eq!(estimate_path_triple(true, true, true), 1);
22407        assert_eq!(estimate_path_triple(false, true, true), 1_000);
22408        assert_eq!(estimate_path_triple(false, false, true), 10_000);
22409        assert_eq!(estimate_path_triple(true, true, false), 10);
22410        assert_eq!(estimate_path_triple(false, false, false), 1_000_000_000);
22411    }
22412
22413    #[test]
22414    fn rdf_type_path_estimate_gets_the_plus_one() {
22415        let type_pred = EncodedTerm::from(&NamedNode::new(RDF_TYPE_IRI).unwrap());
22416        let other_pred = EncodedTerm::from(&NamedNode::new("http://ex/knows").unwrap());
22417        let base = estimate_path_triple(false, true, true);
22418        assert_eq!(
22419            estimate_path_size(false, &PropertyPath::Predicate(type_pred), true),
22420            base + 1,
22421            "an `rdf:type` predicate adds one to the base estimate"
22422        );
22423        assert_eq!(
22424            estimate_path_size(false, &PropertyPath::Predicate(other_pred), true),
22425            base,
22426            "any other predicate keeps the plain estimate"
22427        );
22428    }
22429
22430    #[test]
22431    fn estimated_distinct_terms_takes_per_variable_maxima() {
22432        use super::estimated_distinct_terms;
22433        // Two scans sharing ?samp with different subject domains, plus an
22434        // ?occ with no object-side domain in the profile: the estimate is
22435        // the per-variable maximum (?samp = 700), not a per-scan sum.
22436        let mut profile = StatsProfile::default();
22437        profile
22438            .subjects_per_predicate
22439            .insert(StrHash::new("http://ex/pA"), hll_with_n(100));
22440        profile
22441            .subjects_per_predicate
22442            .insert(StrHash::new("http://ex/pB"), hll_with_n(700));
22443        profile.total_puts = 800;
22444        let root = PlanNode::Union {
22445            left: Box::new(PlanNode::Scan(var_scan(
22446                Some("samp"),
22447                "http://ex/pA",
22448                Some("occ"),
22449                100_000,
22450            ))),
22451            right: Box::new(PlanNode::Scan(var_scan(
22452                Some("samp"),
22453                "http://ex/pB",
22454                Some("proc"),
22455                700_000,
22456            ))),
22457        };
22458        let mut maxima = Vec::new();
22459        estimated_distinct_terms(&root, &profile, &mut maxima);
22460        let estimate: u64 = maxima.iter().map(|(_, domain)| domain).sum();
22461        // HLL cardinalities land within ~1% of the inserted count, so the
22462        // pin is the profile's own read — what proves the mechanism is
22463        // that the estimate is the ?samp MAXIMUM (one HLL read), not the
22464        // per-scan sum (both reads).
22465        let expected = profile
22466            .subjects_per_predicate
22467            .get(&StrHash::new("http://ex/pB"))
22468            .expect("pB subjects HLL")
22469            .cardinality();
22470        assert_eq!(estimate, expected, "maxima were {maxima:?}");
22471        assert_eq!(
22472            maxima.len(),
22473            1,
22474            "no object-side domains in the profile: only ?samp contributes"
22475        );
22476    }
22477
22478    /// Many Tenant instances; few distinct `:hasTenant` objects so the Union
22479    /// join-key domain is small even when Union row estimates are huge.
22480    fn tenant_union_small_has_tenant_domain() -> StatsProfile {
22481        let mut profile = StatsProfile::default();
22482        let rdf_type = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
22483        let has_tenant = StrHash::new("http://ex/hasTenant");
22484        profile.total_puts = 300_000;
22485        profile
22486            .class_counts
22487            .insert(StrHash::new("http://ex/Tenant"), 50_000);
22488        profile
22489            .class_counts
22490            .insert(StrHash::new("http://ex/Server"), 100_000);
22491        profile
22492            .class_counts
22493            .insert(StrHash::new("http://ex/VM"), 100_000);
22494        profile.predicate_counts.insert(rdf_type, 250_000);
22495        profile.predicate_counts.insert(has_tenant, 100_000);
22496        profile
22497            .subjects_per_predicate
22498            .insert(rdf_type, hll_with_n(50_000));
22499        profile
22500            .objects_per_predicate
22501            .insert(rdf_type, hll_with_n(3));
22502        profile
22503            .subjects_per_predicate
22504            .insert(has_tenant, hll_with_n(80_000));
22505        profile
22506            .objects_per_predicate
22507            .insert(has_tenant, hll_with_n(40));
22508        profile
22509    }
22510
22511    /// Few Tenant instances; huge `:hasTenant` object domain.
22512    fn tenant_union_small_type_scan_domain() -> StatsProfile {
22513        let mut profile = StatsProfile::default();
22514        let rdf_type = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
22515        let has_tenant = StrHash::new("http://ex/hasTenant");
22516        profile.total_puts = 300_000;
22517        profile
22518            .class_counts
22519            .insert(StrHash::new("http://ex/Tenant"), 20);
22520        profile
22521            .class_counts
22522            .insert(StrHash::new("http://ex/Server"), 100_000);
22523        profile
22524            .class_counts
22525            .insert(StrHash::new("http://ex/VM"), 100_000);
22526        profile.predicate_counts.insert(rdf_type, 200_020);
22527        profile.predicate_counts.insert(has_tenant, 100_000);
22528        profile
22529            .subjects_per_predicate
22530            .insert(rdf_type, hll_with_n(20));
22531        profile
22532            .objects_per_predicate
22533            .insert(rdf_type, hll_with_n(3));
22534        profile
22535            .subjects_per_predicate
22536            .insert(has_tenant, hll_with_n(80_000));
22537        profile
22538            .objects_per_predicate
22539            .insert(has_tenant, hll_with_n(50_000));
22540        profile
22541    }
22542
22543    fn assert_join_scan_union(root: &PlanNode, union_on_left: bool) {
22544        let PlanNode::Join {
22545            left,
22546            right,
22547            hash_keys,
22548            probe_key_domains: _,
22549            probe_key_overlap_milli: _,
22550            rhs_hostable_keys: _,
22551            meta,
22552        } = root
22553        else {
22554            panic!("expected Join at root, got {root:?}");
22555        };
22556        assert_eq!(
22557            hash_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
22558            ["tenant"]
22559        );
22560        if union_on_left {
22561            assert!(
22562                left.as_union().is_some(),
22563                "expected Union on the left, got {left:?}"
22564            );
22565            assert!(
22566                right.as_broadcast_scan().is_some(),
22567                "expected Scan on the right, got {right:?}"
22568            );
22569            assert_eq!(meta.strategy, JoinStrategy::Broadcast);
22570        } else {
22571            assert!(
22572                left.as_broadcast_scan().is_some(),
22573                "expected Scan on the left, got {left:?}"
22574            );
22575            assert!(
22576                right.as_union().is_some(),
22577                "expected Union on the right, got {right:?}"
22578            );
22579        }
22580    }
22581
22582    #[test]
22583    fn join_scan_union_swaps_when_union_join_key_domain_is_smaller() {
22584        let plan = LogicalPlan::parse_with_profile(
22585            TENANT_UNION,
22586            Some(&tenant_union_small_has_tenant_domain()),
22587        )
22588        .unwrap();
22589        assert_join_scan_union(&plan.root, true);
22590    }
22591
22592    #[test]
22593    fn join_scan_union_keeps_scan_left_when_type_domain_is_smaller() {
22594        let plan = LogicalPlan::parse_with_profile(
22595            TENANT_UNION,
22596            Some(&tenant_union_small_type_scan_domain()),
22597        )
22598        .unwrap();
22599        assert_join_scan_union(&plan.root, false);
22600    }
22601
22602    #[test]
22603    fn join_scan_union_broadcast_annotates_has_tenant_scans() {
22604        let profile = tenant_union_small_type_scan_domain();
22605        let plan = LogicalPlan::parse_with_profile(TENANT_UNION, Some(&profile)).unwrap();
22606        assert_join_scan_union(&plan.root, false);
22607        let PlanNode::Join { right, meta, .. } = &plan.root else {
22608            panic!("expected Join at root, got {:?}", plan.root);
22609        };
22610        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
22611        let mut has_tenant = Vec::new();
22612        for_each_scan(right, &mut |scan| {
22613            if scan.object.as_ref().is_some_and(|v| v.as_str() == "tenant") {
22614                has_tenant.push(scan);
22615            }
22616        });
22617        assert_eq!(
22618            has_tenant.len(),
22619            2,
22620            "two :hasTenant scans in UNION arms: {right:?}"
22621        );
22622        for scan in &has_tenant {
22623            assert!(
22624                matches!(
22625                    scan.broadcasted,
22626                    Some((ref v, PatternSlot::Object)) if v.as_str() == "tenant"
22627                ),
22628                "expected object broadcast on ?tenant, got {:?}",
22629                scan.broadcasted
22630            );
22631            assert!(
22632                scan.produced_row_count_estimate < 1_000,
22633                "allow-listed :hasTenant scan must not use catalog rows: {}",
22634                scan.produced_row_count_estimate
22635            );
22636        }
22637        // The arm joins seat the :hasTenant scan as the DRIVER. The root's
22638        // ?tenant push (20 tenants × ~2 rows/key ≈ 39) is a FOREIGN claim
22639        // for the arm joins (?tenant is not their hash key ?x), so the
22640        // ancestor push return bound prices hasTenant's whole read at ~39
22641        // rows in every arm seating — it beats the 100k-catalog Server/VM
22642        // scans as the driver, which demotes those scans to Broadcast
22643        // probes: claimed on ?x and seeked per pushed value (~39 values), not
22644        // read whole into a hash build. Before the ancestor bound, the
22645        // arm seating was blind to the root's push and seated the 100k
22646        // type scans as drivers.
22647        let mut arm_type_broadcasts = 0;
22648        for_each_scan(right, &mut |scan| {
22649            if scan.subject.as_ref().is_some_and(|v| v.as_str() == "x")
22650                && scan.object.is_none()
22651                && scan.broadcasted.is_some()
22652            {
22653                assert!(
22654                    matches!(
22655                        scan.broadcasted,
22656                        Some((ref v, PatternSlot::Subject)) if v.as_str() == "x"
22657                    ),
22658                    "arm type probe carries its arm join's ?x claim, got {:?}",
22659                    scan.broadcasted
22660                );
22661                assert!(
22662                    scan.produced_row_count_estimate < 1_000,
22663                    "claimed arm type probe must not read catalog rows: {}",
22664                    scan.produced_row_count_estimate
22665                );
22666                arm_type_broadcasts += 1;
22667            }
22668        });
22669        assert_eq!(
22670            arm_type_broadcasts, 2,
22671            "both Server/VM type scans are arm-join probes now: {right:?}"
22672        );
22673        let text = explain_est(TENANT_UNION, Some(&profile));
22674        assert!(
22675            text.matches("(broadcast ?tenant object)").count() >= 2,
22676            "EXPLAIN should annotate both :hasTenant scans: {text}"
22677        );
22678    }
22679
22680    #[test]
22681    fn join_scan_union_broadcast_annotates_type_scan() {
22682        let profile = tenant_union_small_has_tenant_domain();
22683        let plan = LogicalPlan::parse_with_profile(TENANT_UNION, Some(&profile)).unwrap();
22684        assert_join_scan_union(&plan.root, true);
22685        let PlanNode::Join { right, .. } = &plan.root else {
22686            panic!("expected Join at root, got {:?}", plan.root);
22687        };
22688        let scan = right
22689            .as_broadcast_scan()
22690            .expect("type scan should be the probe");
22691        assert!(
22692            matches!(
22693                scan.broadcasted,
22694                Some((ref v, PatternSlot::Subject)) if v.as_str() == "tenant"
22695            ),
22696            "expected subject broadcast on ?tenant, got {:?}",
22697            scan.broadcasted
22698        );
22699        assert!(
22700            scan.produced_row_count_estimate < 1_000,
22701            "allow-listed type scan must not use catalog rows: {}",
22702            scan.produced_row_count_estimate
22703        );
22704        let text = explain_est(TENANT_UNION, Some(&profile));
22705        assert!(
22706            text.contains("(broadcast ?tenant subject)"),
22707            "EXPLAIN should annotate the type scan: {text}"
22708        );
22709    }
22710
22711    /// One big class with a ground-object scan (`?x a <Big>`), one small class
22712    /// with a distinct projection, plus a two-variable join-pattern predicate.
22713    ///
22714    /// The global rdf:type subject HLL (74,083,307 in the field report) must
22715    /// never leak into a ground-object scan's row estimate: the exact class
22716    /// map is the sharper bound, and `min` must pick it.
22717    fn collapse_recost_profile() -> StatsProfile {
22718        let mut profile = StatsProfile::default();
22719        let rdf_type = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
22720        let label = StrHash::new("http://ex/label");
22721        profile.total_puts = 300_000;
22722        // Exact class maps — the "before" path.
22723        profile
22724            .class_counts
22725            .insert(StrHash::new("http://ex/Big"), 10_000);
22726        profile
22727            .class_counts
22728            .insert(StrHash::new("http://ex/Sub"), 843);
22729        // Realism contract: class_counts is COMPLETE — every class the
22730        // objects HLL counts carries an exact entry (collectors populate
22731        // both from the same quads), so the object-slot
22732        // `class_counts.len()` shortcut and the HLL must tell the same
22733        // story. Two entries against a 1k-distinct HLL would be a profile
22734        // no collector can produce.
22735        for i in 0..998u32 {
22736            profile
22737                .class_counts
22738                .insert(StrHash::new(&format!("http://ex/Filler{i}")), 1);
22739        }
22740        profile.predicate_counts.insert(rdf_type, 250_000);
22741        profile.predicate_counts.insert(label, 200_000);
22742        // Global marginal HLLs — the regressed path when used as row counts.
22743        profile
22744            .subjects_per_predicate
22745            .insert(rdf_type, hll_with_n(74_083_307));
22746        profile
22747            .objects_per_predicate
22748            .insert(rdf_type, hll_with_n(1_000));
22749        profile
22750            .subjects_per_predicate
22751            .insert(label, hll_with_n(10_000));
22752        // Realism contract (same as the class map above): 200k rows cannot
22753        // carry 370k distinct objects — a collector-produced profile keeps
22754        // objects-HLL ≤ rows, and the full-extent estimate's
22755        // rows-≥-max(HLLs) invariant clamp enforces exactly that. Keep the
22756        // label objects near-row-count (labels are near-unique per row)
22757        // but under it, so the clamp stays a no-op and the pattern row
22758        // count remains the honest DISTINCT bound this fixture pins.
22759        profile
22760            .objects_per_predicate
22761            .insert(label, hll_with_n(190_000));
22762        profile
22763    }
22764
22765    #[test]
22766    fn distinct_ground_object_scan_keeps_class_map_rows() {
22767        let profile = collapse_recost_profile();
22768        let text = explain_est(
22769            "SELECT DISTINCT ?x WHERE { ?x a <http://ex/Sub> }",
22770            Some(&profile),
22771        );
22772        assert_eq!(
22773            rows_on_line(&text, "(scan "),
22774            843,
22775            "ground object + single collapse key must use the exact class map, not the global HLL: {text}"
22776        );
22777    }
22778
22779    #[test]
22780    fn distinct_dead_subject_scan_uses_object_domain_rows() {
22781        let profile = collapse_recost_profile();
22782        // SELECT DISTINCT ?o over ?s a ?o: ?s dead, ?o insensitive → bare
22783        // TSG classes scan (the type arm prefers the narrower index over the
22784        // POSG domain scan); its row estimate is the exact distinct-class
22785        // count (class_counts.len() — the same answer the object HLL
22786        // approximates), not the 250k type triples.
22787        let text = explain_est("SELECT DISTINCT ?o WHERE { ?s a ?o }", Some(&profile));
22788        assert!(
22789            text.contains("(head_scan classes@tsg)"),
22790            "dead S + insensitive O on rdf:type must rewrite to the TSG head scan: {text}"
22791        );
22792        let rows = rows_on_line(&text, "(scan ");
22793        assert_eq!(
22794            rows,
22795            profile.class_counts.len() as u64,
22796            "domain_scan rows come from the exact class count: {text}"
22797        );
22798        assert!(
22799            rows < 2_000,
22800            "distinct classes (~1k) must beat the 250k triple count: {text}"
22801        );
22802    }
22803
22804    // ---- broadcasted marks × liveness rewrite flags -----------------------
22805
22806    /// A `PredicateDomain`-annotated scan over `<http://ex/p1>` (head O).
22807    fn predicate_domain_scan() -> ScanOp {
22808        let p1 = EncodedTerm::from(&NamedNode::new("http://ex/p1").unwrap());
22809        ScanOp {
22810            ancestor_push_return_bound: None,
22811            fetch_once: None,
22812            pattern: EncodedTriplePattern {
22813                subject: None,
22814                predicate: Some(p1.clone()),
22815                object: None,
22816                graph_name: None,
22817            },
22818            subject: None,
22819            predicate: None,
22820            object: None,
22821            graph: None,
22822            produced_row_count_estimate: 1,
22823            broadcasted: None,
22824            graph_filter: None,
22825            grounded: Vec::new(),
22826            merge_default_graph: false,
22827            marks: Vec::new(),
22828            domain_scan: Some(DomainScanKind::PredicateDomain),
22829            head_scan: None,
22830            head_scan_counts: None,
22831            domain_counts: None,
22832            iri_only: Vec::new(),
22833            eager: Vec::new(),
22834            join_domains: crate::plan::JoinDomainStamps::default(),
22835        }
22836    }
22837
22838    fn stamped_head_scan_profile() -> StatsProfile {
22839        let mut profile = StatsProfile::default();
22840        let p1 = StrHash::new("http://ex/p1");
22841        profile.predicate_counts.insert(p1, 9);
22842        profile.objects_per_predicate.insert(p1, hll_with_n(500));
22843        profile
22844    }
22845
22846    #[test]
22847    fn join_domain_stamp_is_known_for_bound_predicate_slots() {
22848        let mut profile = StatsProfile::default();
22849        let p = StrHash::new("http://ex/p");
22850        profile.predicate_counts.insert(p, 100);
22851        profile.subjects_per_predicate.insert(p, hll_with_n(500));
22852        profile.objects_per_predicate.insert(p, hll_with_n(50));
22853
22854        let scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
22855        let stamps = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
22856        // Both answers read only the predicate and the profile, so a free
22857        // subject/object slot cannot change them.
22858        assert_eq!(
22859            stamps.get(JoinKeySlot::Subject),
22860            JoinDomainStamp::Known(profile.subject_domain(&p).unwrap())
22861        );
22862        assert_eq!(
22863            stamps.get(JoinKeySlot::Object),
22864            JoinDomainStamp::Known(profile.object_domain(&p).unwrap())
22865        );
22866    }
22867
22868    #[test]
22869    fn known_stamp_is_returned_without_a_live_lookup() {
22870        let mut scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
22871        scan.join_domains = JoinDomainStamps {
22872            subject: JoinDomainStamp::Known(7),
22873            object: JoinDomainStamp::Known(9),
22874        };
22875        // A non-empty profile proves the stamp wins over the live sketch
22876        // value (which would be ~500 for the subject).
22877        let mut profile = StatsProfile::default();
22878        let p = StrHash::new("http://ex/p");
22879        profile.predicate_counts.insert(p, 1);
22880        profile.subjects_per_predicate.insert(p, hll_with_n(500));
22881        assert_eq!(
22882            join_key_domain_for(Some(&profile), &scan, &[var("s")]),
22883            Some(7)
22884        );
22885        assert_eq!(
22886            join_key_domain_for(Some(&profile), &scan, &[var("o")]),
22887            Some(9)
22888        );
22889    }
22890
22891    #[test]
22892    fn with_pattern_drops_join_domain_stamps() {
22893        let mut profile = StatsProfile::default();
22894        let p = StrHash::new("http://ex/p");
22895        profile.predicate_counts.insert(p, 1);
22896        profile.objects_per_predicate.insert(p, hll_with_n(50));
22897
22898        let mut scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
22899        scan.join_domains = JoinDomainStamps {
22900            subject: JoinDomainStamp::Known(7),
22901            object: JoinDomainStamp::Known(9),
22902        };
22903        let mut pattern = scan.pattern.clone();
22904        pattern.subject = Some(EncodedTerm::from(
22905            &NamedNode::new("http://ex/grounded-s").unwrap(),
22906        ));
22907        let grounded = scan.with_pattern(pattern);
22908        assert_eq!(
22909            grounded.join_domains,
22910            JoinDomainStamps::default(),
22911            "a rewritten pattern must not keep the old stamp"
22912        );
22913        // ?o is still free, so pricing must read the live object HLL; the
22914        // stale stamp would have answered 9.
22915        assert_eq!(
22916            join_key_domain_for(Some(&profile), &grounded, &[var("o")]),
22917            Some(profile.object_domain(&p).unwrap())
22918        );
22919        assert_ne!(
22920            join_key_domain_for(Some(&profile), &grounded, &[var("o")]),
22921            Some(9)
22922        );
22923    }
22924
22925    #[test]
22926    fn grounded_slot_still_wins_over_a_known_stamp() {
22927        // The constant-slot answer is 1 by plan-time convention; a stamp must
22928        // never override it.
22929        let mut scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
22930        scan.pattern.subject = Some(EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()));
22931        scan.join_domains = JoinDomainStamps {
22932            subject: JoinDomainStamp::Known(999),
22933            object: JoinDomainStamp::Known(9),
22934        };
22935        assert_eq!(join_key_domain_for(None, &scan, &[var("s")]), Some(1));
22936    }
22937
22938    #[test]
22939    fn grounding_rdf_type_object_promotes_deferred_subject_stamp() {
22940        let mut profile = StatsProfile::default();
22941        let class = EncodedTerm::from(&NamedNode::new("http://ex/Student").unwrap());
22942        let class_hash = named_node_hash(&class).unwrap();
22943        profile.class_counts.insert(class_hash, 42);
22944
22945        let mut scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
22946        scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
22947        assert_eq!(
22948            scan.join_domains.get(JoinKeySlot::Subject),
22949            JoinDomainStamp::Deferred,
22950            "a free rdf:type object can change the subject answer"
22951        );
22952
22953        // Ground ?c the way `bind_scan_equality` does.
22954        scan.pattern.object = Some(class);
22955        scan.record_grounded(&var("c"), PatternSlot::Object, Some(&profile));
22956        assert_eq!(
22957            scan.join_domains.get(JoinKeySlot::Subject),
22958            JoinDomainStamp::Known(42)
22959        );
22960        assert_eq!(
22961            join_key_domain_for(Some(&profile), &scan, &[var("s")]),
22962            Some(42)
22963        );
22964    }
22965
22966    #[test]
22967    fn bind_scan_equality_promotes_rdf_type_subject_stamp() {
22968        let mut profile = StatsProfile::default();
22969        let class = EncodedTerm::from(&NamedNode::new("http://ex/Student").unwrap());
22970        let class_hash = named_node_hash(&class).unwrap();
22971        profile.class_counts.insert(class_hash, 42);
22972
22973        let mut scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
22974        scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
22975        assert_eq!(
22976            scan.join_domains.get(JoinKeySlot::Subject),
22977            JoinDomainStamp::Deferred,
22978            "a free rdf:type object can change the subject answer"
22979        );
22980
22981        assert!(
22982            bind_scan_equality(&mut scan, &var("c"), &class, Some(&profile)),
22983            "identity grounding must bind the free rdf:type object"
22984        );
22985        assert_eq!(
22986            scan.join_domains.get(JoinKeySlot::Subject),
22987            JoinDomainStamp::Known(42),
22988            "bind_scan_equality must refresh the stamps after rebuilding the pattern"
22989        );
22990
22991        // The already-pinned branch must refresh too: a scan can carry a
22992        // `Deferred` stamp from an earlier classification even when its
22993        // pattern already names the class.
22994        let mut prebound = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
22995        prebound.join_domains = JoinDomainStamps::classify(Some(&profile), &prebound.pattern);
22996        prebound.pattern.object = Some(class.clone());
22997        assert!(
22998            bind_scan_equality(&mut prebound, &var("c"), &class, Some(&profile)),
22999            "an already-pinned rdf:type object must still count as grounded"
23000        );
23001        assert_eq!(
23002            prebound.join_domains.get(JoinKeySlot::Subject),
23003            JoinDomainStamp::Known(42),
23004            "the existing-term branch must refresh the stamps too"
23005        );
23006    }
23007
23008    #[test]
23009    fn rdf_type_subject_stays_deferred_while_object_free() {
23010        let mut profile = StatsProfile::default();
23011        profile
23012            .class_counts
23013            .insert(StrHash::new("http://ex/Student"), 42);
23014        let mut scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
23015        scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
23016        assert_eq!(
23017            scan.join_domains.get(JoinKeySlot::Subject),
23018            JoinDomainStamp::Deferred,
23019            "with class_counts present, a free rdf:type object can change the subject answer"
23020        );
23021        // A refresh that still sees the free object must not promote the
23022        // stamp; only grounding ?c completes the subject answer's inputs.
23023        scan.refresh_join_domains(Some(&profile));
23024        assert_eq!(
23025            scan.join_domains.get(JoinKeySlot::Subject),
23026            JoinDomainStamp::Deferred
23027        );
23028    }
23029
23030    #[test]
23031    fn deferred_rdf_type_subject_prices_as_live_subject_hll() {
23032        let pred = StrHash::new(RDF_TYPE_IRI);
23033        let mut profile = StatsProfile::default();
23034        profile
23035            .class_counts
23036            .insert(StrHash::new("http://ex/Student"), 42);
23037        profile.subjects_per_predicate.insert(pred, hll_with_n(123));
23038        let mut scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
23039        scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
23040        assert_eq!(
23041            scan.join_domains.get(JoinKeySlot::Subject),
23042            JoinDomainStamp::Deferred,
23043            "with class_counts present, a free rdf:type object can change the subject answer"
23044        );
23045        // Until ?c is plan-time grounded, the stamp must not answer. Pricing
23046        // recomputes live and therefore reads the rdf:type subject HLL — not
23047        // `class_counts[Student]`, which only becomes valid once ?c is bound.
23048        let live_subject = profile.subject_domain(&pred).unwrap();
23049        assert_eq!(
23050            join_key_domain_for(Some(&profile), &scan, &[var("s")]),
23051            Some(live_subject)
23052        );
23053        assert_ne!(
23054            join_key_domain_for(Some(&profile), &scan, &[var("s")]),
23055            Some(42)
23056        );
23057    }
23058
23059    #[test]
23060    fn rdf_type_object_stamp_uses_exact_classes_then_object_hll() {
23061        let scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
23062
23063        // With class counts, the object answer is the number of known
23064        // classes, not the rdf:type object HLL (which counts class terms
23065        // weighted by their instances).
23066        let mut exact = StatsProfile::default();
23067        exact.class_counts.insert(StrHash::new("http://ex/A"), 10);
23068        exact.class_counts.insert(StrHash::new("http://ex/B"), 20);
23069        let stamps = JoinDomainStamps::classify(Some(&exact), &scan.pattern);
23070        assert_eq!(
23071            stamps.get(JoinKeySlot::Object),
23072            JoinDomainStamp::Known(exact.class_counts.len() as u64)
23073        );
23074        assert_eq!(stamps.get(JoinKeySlot::Subject), JoinDomainStamp::Deferred);
23075
23076        // Empty class_counts falls through to the rdf:type object HLL; with
23077        // no subject HLL the subject answer is Unavailable, not Deferred,
23078        // because object grounding cannot select a class count.
23079        let pred = StrHash::new(RDF_TYPE_IRI);
23080        let mut fallback = StatsProfile::default();
23081        fallback.predicate_counts.insert(pred, 100);
23082        fallback.objects_per_predicate.insert(pred, hll_with_n(77));
23083        let stamps = JoinDomainStamps::classify(Some(&fallback), &scan.pattern);
23084        assert_eq!(
23085            stamps.get(JoinKeySlot::Object),
23086            JoinDomainStamp::Known(fallback.object_domain(&pred).unwrap())
23087        );
23088        assert_eq!(
23089            stamps.get(JoinKeySlot::Subject),
23090            JoinDomainStamp::Unavailable,
23091            "no class_counts means object grounding cannot promote the subject stamp"
23092        );
23093    }
23094
23095    #[test]
23096    fn rdf_type_subject_without_class_counts_uses_subject_hll() {
23097        let pred = StrHash::new(RDF_TYPE_IRI);
23098        let mut profile = StatsProfile::default();
23099        profile.predicate_counts.insert(pred, 100);
23100        profile.subjects_per_predicate.insert(pred, hll_with_n(123));
23101        let scan = var_scan(Some("s"), RDF_TYPE_IRI, Some("c"), 1);
23102        let stamps = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
23103        assert_eq!(
23104            stamps.get(JoinKeySlot::Subject),
23105            JoinDomainStamp::Known(profile.subject_domain(&pred).unwrap()),
23106            "without class_counts the subject answer cannot change on object grounding"
23107        );
23108        assert_eq!(
23109            stamps.get(JoinKeySlot::Object),
23110            JoinDomainStamp::Unavailable,
23111            "no rdf:type object HLL to cache"
23112        );
23113    }
23114
23115    #[test]
23116    fn grounding_predicate_promotes_unknown_predicate_stamp() {
23117        let mut profile = StatsProfile::default();
23118        let p = StrHash::new("http://ex/p");
23119        profile.predicate_counts.insert(p, 10);
23120        profile.subjects_per_predicate.insert(p, hll_with_n(77));
23121        profile.objects_per_predicate.insert(p, hll_with_n(33));
23122
23123        let mut scan = var_scan(Some("s"), "http://ex/unused", Some("o"), 1);
23124        scan.pattern.predicate = None;
23125        scan.predicate = Some(var("p"));
23126        scan.join_domains = JoinDomainStamps::classify(Some(&profile), &scan.pattern);
23127        assert_eq!(
23128            scan.join_domains.get(JoinKeySlot::Subject),
23129            JoinDomainStamp::UnknownPredicate
23130        );
23131        assert_eq!(
23132            scan.join_domains.get(JoinKeySlot::Object),
23133            JoinDomainStamp::UnknownPredicate
23134        );
23135
23136        scan.pattern.predicate = Some(EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()));
23137        scan.predicate = None;
23138        scan.record_grounded(&var("p"), PatternSlot::Predicate, Some(&profile));
23139        assert_eq!(
23140            scan.join_domains.get(JoinKeySlot::Subject),
23141            JoinDomainStamp::Known(profile.subject_domain(&p).unwrap())
23142        );
23143        assert_eq!(
23144            scan.join_domains.get(JoinKeySlot::Object),
23145            JoinDomainStamp::Known(profile.object_domain(&p).unwrap())
23146        );
23147    }
23148
23149    #[test]
23150    fn missing_profile_or_sketch_falls_back_live() {
23151        let scan = var_scan(Some("s"), "http://ex/p", Some("o"), 1);
23152        assert_eq!(
23153            JoinDomainStamps::classify(None, &scan.pattern).get(JoinKeySlot::Subject),
23154            JoinDomainStamp::NoProfile
23155        );
23156        let empty = StatsProfile::default();
23157        assert_eq!(
23158            JoinDomainStamps::classify(Some(&empty), &scan.pattern).get(JoinKeySlot::Subject),
23159            JoinDomainStamp::NoProfile
23160        );
23161        assert_eq!(join_key_domain_for(None, &scan, &[var("s")]), None);
23162        assert_eq!(join_key_domain_for(Some(&empty), &scan, &[var("s")]), None);
23163
23164        // Bound predicate, non-empty profile, but no HLL for it.
23165        let mut other = StatsProfile::default();
23166        other
23167            .predicate_counts
23168            .insert(StrHash::new("http://ex/other"), 1);
23169        let stamps = JoinDomainStamps::classify(Some(&other), &scan.pattern);
23170        assert_eq!(
23171            stamps.get(JoinKeySlot::Subject),
23172            JoinDomainStamp::Unavailable
23173        );
23174        assert_eq!(
23175            stamps.get(JoinKeySlot::Object),
23176            JoinDomainStamp::Unavailable
23177        );
23178        assert_eq!(join_key_domain_for(Some(&other), &scan, &[var("s")]), None);
23179    }
23180
23181    #[test]
23182    fn predicate_head_domain_estimate_is_the_predicate_map_size() {
23183        let profile = stamped_head_scan_profile();
23184        let mut scan = predicate_domain_scan();
23185        scan.domain_scan = Some(DomainScanKind::SubjectPreds);
23186        assert_eq!(
23187            head_domain_estimate(&profile, &scan, PatternSlot::Predicate),
23188            Some(1),
23189            "the exact predicate map size bounds the distinct predicate heads"
23190        );
23191        // With no predicate map the estimate is unknown.
23192        assert_eq!(
23193            head_domain_estimate(&StatsProfile::default(), &scan, PatternSlot::Predicate),
23194            None
23195        );
23196    }
23197
23198    #[test]
23199    fn distinct_two_key_collapse_keeps_pattern_rows() {
23200        let profile = collapse_recost_profile();
23201        // DISTINCT ON (?s ?label): no joint sketch sees tuple distinctness,
23202        // and distinct pairs >= distinct first-key values, so the pattern
23203        // row count (label predicate count) is the honest bound — not the
23204        // ~10k subject domain.
23205        let text = explain_est(
23206            "SELECT DISTINCT ?s ?label WHERE { ?s <http://ex/label> ?label }",
23207            Some(&profile),
23208        );
23209        assert_eq!(
23210            rows_on_line(&text, "(scan "),
23211            200_000,
23212            "multi-key collapse must keep the pre-collapse row count: {text}"
23213        );
23214    }
23215
23216    #[test]
23217    fn distinct_single_key_collapse_takes_the_min_of_rows_and_domain() {
23218        let profile = collapse_recost_profile();
23219        // Single key ?s, unbound O: pattern rows = label predicate count
23220        // (200k), subject HLL ~10.3k → min picks the domain.
23221        let text = explain_est(
23222            "SELECT DISTINCT ?s WHERE { ?s <http://ex/label> ?o }",
23223            Some(&profile),
23224        );
23225        let expected = collapse_recost_profile()
23226            .subjects_per_predicate
23227            .get(&StrHash::new("http://ex/label"))
23228            .map(|hll| hll.cardinality())
23229            .expect("label subject HLL");
23230        assert_eq!(
23231            rows_on_line(&text, "(scan "),
23232            expected,
23233            "single-key collapse output is bounded by the key domain: {text}"
23234        );
23235        assert!(
23236            rows_on_line(&text, "(scan ") < 200_000,
23237            "min(rows, domain) must beat the pattern count here: {text}"
23238        );
23239    }
23240
23241    #[test]
23242    fn left_join_scan_union_does_not_swap() {
23243        let sparql = r#"
23244            SELECT ?tenant ?x WHERE {
23245              ?tenant a <http://ex/Tenant> .
23246              OPTIONAL {
23247                { ?x <http://ex/hasTenant> ?tenant . ?x a <http://ex/Server> }
23248                UNION
23249                { ?x <http://ex/hasTenant> ?tenant . ?x a <http://ex/VM> }
23250              }
23251            }
23252        "#;
23253        let plan =
23254            LogicalPlan::parse_with_profile(sparql, Some(&tenant_union_small_has_tenant_domain()))
23255                .unwrap();
23256        let PlanNode::LeftJoin { left, right, .. } = &plan.root else {
23257            panic!("expected LeftJoin at root, got {:?}", plan.root);
23258        };
23259        assert!(
23260            left.as_broadcast_scan().is_some(),
23261            "OPTIONAL must keep the required scan on the left, got {left:?}"
23262        );
23263        assert!(
23264            right.as_union().is_some(),
23265            "OPTIONAL Union must stay on the right, got {right:?}"
23266        );
23267    }
23268
23269    #[test]
23270    fn explain_estimates_prints_join_key_domains_with_profile() {
23271        let profile = tenant_union_small_has_tenant_domain();
23272        let text = explain_est(TENANT_UNION, Some(&profile));
23273        assert!(text.contains("(join "), "{text}");
23274        assert!(text.contains("(union "), "{text}");
23275        let union_tenant = domain_on_line(&text, "(union ", "?tenant");
23276        assert!(
23277            union_tenant.is_some_and(|n| n > 1 && n < 5_000),
23278            "Union should print a small numeric ?tenant domain, got {union_tenant:?}: {text}"
23279        );
23280        let join_tenant = domain_on_line(&text, "(join ", "?tenant");
23281        assert!(
23282            join_tenant.is_some_and(|n| n > 1),
23283            "Join should print a numeric ?tenant domain, got {join_tenant:?}: {text}"
23284        );
23285        let type_scan = text
23286            .lines()
23287            .find(|line| line.contains("(scan ") && line.contains("?tenant a"))
23288            .expect("type scan line");
23289        assert!(
23290            type_scan.contains("(domain ?tenant ") && !type_scan.contains("(domain ?tenant ?)"),
23291            "type scan should print an rdf:type subject domain: {text}"
23292        );
23293    }
23294
23295    #[test]
23296    fn explain_estimates_prints_unknown_domains_without_profile() {
23297        let text = explain_est(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o }"#, None);
23298        assert!(text.contains("(path "), "{text}");
23299        assert!(
23300            text.contains("(domain ?s ?)") && text.contains("(domain ?o ?)"),
23301            "Path ends have no HLL: {text}"
23302        );
23303        let join_text = explain_est(
23304            r#"SELECT ?s WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?x }"#,
23305            None,
23306        );
23307        assert!(
23308            join_text.contains("(domain ?s ?)"),
23309            "missing profile should print ?v=?: {join_text}"
23310        );
23311    }
23312
23313    #[test]
23314    fn explain_estimates_omits_domain_on_grounded_path() {
23315        let text = explain_est(
23316            r#"ASK WHERE { <http://ex/a> <http://ex/p>* <http://ex/b> }"#,
23317            None,
23318        );
23319        let path_line = text
23320            .lines()
23321            .find(|line| line.contains("(path "))
23322            .unwrap_or(text.as_str());
23323        assert!(
23324            !path_line.contains("(domain"),
23325            "grounded path has no variable domain to print: {text}"
23326        );
23327    }
23328
23329    #[test]
23330    fn constants_are_encoded_and_variables_are_named() {
23331        let plan =
23332            LogicalPlan::parse("SELECT ?city WHERE { ?city <http://ex/hasWeather> \"Sunny\" }")
23333                .unwrap();
23334        let scan = plan.scans().unwrap()[0];
23335        assert_eq!(scan.subject, Some(var("city")));
23336        assert_eq!(scan.predicate, None);
23337        assert_eq!(
23338            scan.pattern.predicate,
23339            Some(EncodedTerm::from(
23340                &NamedNode::new("http://ex/hasWeather").unwrap()
23341            ))
23342        );
23343        assert_eq!(scan.pattern.graph_name, Some(EncodedTerm::DefaultGraph));
23344        assert_eq!(scan.variables(), vec![var("city")]);
23345    }
23346
23347    #[test]
23348    fn select_star_projects_every_pattern_variable() {
23349        let plan = LogicalPlan::parse("SELECT * WHERE { ?s <http://ex/livesIn> ?o }").unwrap();
23350        let mut projected: Vec<_> = plan.projection.iter().map(Variable::as_str).collect();
23351        projected.sort_unstable();
23352        assert_eq!(projected, ["o", "s"]);
23353    }
23354
23355    #[test]
23356    fn filter_and_optional_are_planned() {
23357        // Use a residual function filter: it has no scan-side authority, so
23358        // the Filter node stays in the plan.
23359        let filter_plan = LogicalPlan::parse(
23360            r#"SELECT ?s WHERE { ?s <http://ex/p> ?o FILTER(CONTAINS(STR(?o), "x")) }"#,
23361        )
23362        .unwrap();
23363        assert!(
23364            matches!(filter_plan.root, PlanNode::Filter { .. }),
23365            "got {:?}",
23366            filter_plan.root
23367        );
23368
23369        let opt_plan = LogicalPlan::parse(
23370            r#"SELECT ?s ?r WHERE { ?s <http://ex/p> ?o OPTIONAL { ?s <http://ex/q> ?r } }"#,
23371        )
23372        .unwrap();
23373        assert!(matches!(opt_plan.root, PlanNode::LeftJoin { .. }));
23374
23375        let union_plan = LogicalPlan::parse(
23376            r#"SELECT ?s WHERE { { ?s <http://ex/p> ?o } UNION { ?s <http://ex/q> ?o } }"#,
23377        )
23378        .unwrap();
23379        assert!(
23380            matches!(union_plan.root, PlanNode::Union { .. }),
23381            "got {:?}",
23382            union_plan.root
23383        );
23384    }
23385
23386    #[test]
23387    fn exact_comparison_keeps_the_compared_slot_materialized() {
23388        // ?y is not projected, but the eager authority needs its column on
23389        // the post-intern road; the scan must keep it live.
23390        let plan =
23391            LogicalPlan::parse(r#"SELECT ?r WHERE { ?r <http://ex/year> ?y FILTER(?y >= 1967) }"#)
23392                .unwrap();
23393        let PlanNode::Scan(scan) = &plan.root else {
23394            panic!("expected the scan root, got {:?}", plan.root);
23395        };
23396        assert!(
23397            scan.materialized_variables().contains(&var("y")),
23398            "compared slot must stay materialized: {:?}",
23399            scan.materialized_variables()
23400        );
23401        assert!(!plan.projection.contains(&var("y")));
23402    }
23403
23404    #[test]
23405    fn filter_comparisons_are_attached_to_the_scan() {
23406        let plan = LogicalPlan::parse(
23407            r#"SELECT ?r WHERE {
23408                 ?r <http://ex/year> ?y
23409                 FILTER(?y >= 1967 && ?y <= 1971)
23410               }"#,
23411        )
23412        .unwrap();
23413        // The exact range conjuncts are authoritative at the scan, so the
23414        // Filter node is gone and the scan carries them.
23415        let PlanNode::Scan(scan) = &plan.root else {
23416            panic!(
23417                "expected the exact filter to move into the scan, got {:?}",
23418                plan.root
23419            );
23420        };
23421        assert_eq!(scan.eager.len(), 2, "{:?}", scan.eager);
23422        // `sparopt` may reorder the conjuncts; the wire list is a
23423        // conjunction, so only membership matters.
23424        assert!(scan.eager.contains(&SlotComparison {
23425            slot: QuadSlot::Object,
23426            op: CompareOp::Ge,
23427            term: EncodedTerm::from(&Literal::from(1967i64)),
23428        }));
23429        assert!(scan.eager.contains(&SlotComparison {
23430            slot: QuadSlot::Object,
23431            op: CompareOp::Le,
23432            term: EncodedTerm::from(&Literal::from(1971i64)),
23433        }));
23434    }
23435
23436    #[test]
23437    fn values_parameterised_filter_reaches_the_year_scan() {
23438        // The koenigsnet driver query parameterises the range with a
23439        // single-row VALUES. `fold_identity_filters` substitutes the two
23440        // constants into the conjuncts, so the comparison pass sees
23441        // `variable OP literal` and stamps the year scan.
23442        let plan = LogicalPlan::parse(
23443            r#"
23444            PREFIX sdo: <https://schema.org/>
23445            PREFIX scr: <https://koenigsnet/scraper-vocab/>
23446            PREFIX kn: <https://koenigsnet/ont/>
23447
23448            SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
23449              VALUES (?yearFrom ?yearTo) { (1967 1971) }
23450              ?r scr:datasetKind <https://koenigsnet/scraper-vocab/concept/dataset-kind/record> .
23451              ?r kn:year ?_y .
23452              FILTER(?_y >= ?yearFrom && ?_y <= ?yearTo)
23453              { ?r sdo:isPartOf ?v . ?v a sdo:DataCatalog . BIND(kn:catalog AS ?dim) }
23454              UNION
23455              { ?r scr:documentType ?v . BIND(scr:documentType AS ?dim) }
23456              UNION
23457              { ?r scr:subject ?v . BIND(scr:subject AS ?dim) }
23458            }
23459            GROUP BY ?dim ?v
23460            "#,
23461        )
23462        .unwrap();
23463        let year = EncodedTerm::from(&NamedNode::new("https://koenigsnet/ont/year").unwrap());
23464        let scan = find_scan(&plan.root, &year).expect("the year scan is in the plan");
23465        assert_eq!(scan.eager.len(), 2, "{:?}", scan.eager);
23466        assert!(scan.eager.contains(&SlotComparison {
23467            slot: QuadSlot::Object,
23468            op: CompareOp::Ge,
23469            term: EncodedTerm::from(&Literal::from(1967i64)),
23470        }));
23471        assert!(scan.eager.contains(&SlotComparison {
23472            slot: QuadSlot::Object,
23473            op: CompareOp::Le,
23474            term: EncodedTerm::from(&Literal::from(1971i64)),
23475        }));
23476    }
23477
23478    fn find_scan<'a>(node: &'a PlanNode, predicate: &EncodedTerm) -> Option<&'a ScanOp> {
23479        if let PlanNode::Scan(scan) = node {
23480            return (scan.pattern.predicate.as_ref() == Some(predicate)).then_some(scan);
23481        }
23482        let mut children: Vec<&PlanNode> = Vec::new();
23483        match node {
23484            PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
23485                children.push(left);
23486                children.push(right);
23487            }
23488            PlanNode::LeftJoin { left, right, .. } => {
23489                children.push(left);
23490                children.push(right);
23491            }
23492            PlanNode::Filter { inner, .. }
23493            | PlanNode::Slice { inner, .. }
23494            | PlanNode::Distinct { inner, .. }
23495            | PlanNode::Sort { inner, .. }
23496            | PlanNode::Group { inner, .. }
23497            | PlanNode::Extend { inner, .. }
23498            | PlanNode::JoinGraphVar { inner, .. } => children.push(inner),
23499            PlanNode::SubSelect(sub) => children.push(&sub.inner),
23500            PlanNode::CustomNode(op) => children.extend(op.children.iter()),
23501            _ => {}
23502        }
23503        children
23504            .into_iter()
23505            .find_map(|child| find_scan(child, predicate))
23506    }
23507
23508    #[test]
23509    fn exists_and_not_exists_peel_and_classify() {
23510        let and_plan = LogicalPlan::parse(
23511            r#"SELECT ?s ?p ?o WHERE {
23512              ?s ?p ?o
23513              FILTER(EXISTS { ?s ?p <http://ex/brisbane> } && ?o != <http://ex/skip>)
23514            }"#,
23515        )
23516        .unwrap();
23517        let PlanNode::Filter { exists, early, .. } = &and_plan.root else {
23518            panic!("expected Filter, got {:?}", and_plan.root);
23519        };
23520        assert_eq!(exists.len(), 1);
23521        assert!(!exists[0].negated);
23522        assert_eq!(exists[0].kind, ExistsKind::SemiJoin);
23523        assert!(early.is_some(), "ordinary conjunct stays in early");
23524
23525        let ground = LogicalPlan::parse(
23526            r#"SELECT ?s WHERE {
23527              ?s <http://ex/livesIn> ?city
23528              FILTER EXISTS { <http://ex/alice> <http://ex/livesIn> <http://ex/brisbane> }
23529            }"#,
23530        )
23531        .unwrap();
23532        let PlanNode::Filter { exists, .. } = &ground.root else {
23533            panic!("expected Filter, got {:?}", ground.root);
23534        };
23535        assert_eq!(exists[0].kind, ExistsKind::Uncorrelated);
23536        assert!(exists[0].correlation.is_empty());
23537
23538        let nested = LogicalPlan::parse(
23539            r#"SELECT ?s WHERE {
23540              ?s <http://ex/p> <http://ex/o>
23541              FILTER EXISTS { ?s <http://ex/p> <http://ex/o1>
23542                FILTER EXISTS { ?s <http://ex/p> <http://ex/o2> } }
23543            }"#,
23544        )
23545        .unwrap();
23546        let PlanNode::Filter { exists, .. } = &nested.root else {
23547            panic!("expected Filter, got {:?}", nested.root);
23548        };
23549        assert_eq!(exists[0].kind, ExistsKind::NestedProbe);
23550        assert!(
23551            !exists[0].body.as_ref().inner_variables().is_empty()
23552                || matches!(exists[0].body.as_ref(), PlanNode::Filter { .. }),
23553            "nested EXISTS stays inside the body: {:?}",
23554            exists[0].body
23555        );
23556
23557        let not_plan = LogicalPlan::parse(
23558            r#"SELECT ?s WHERE {
23559              ?s <http://ex/livesIn> ?city
23560              FILTER NOT EXISTS { ?city <http://ex/hasWeather> "Sunny" }
23561            }"#,
23562        )
23563        .unwrap();
23564        let PlanNode::Filter { exists, .. } = &not_plan.root else {
23565            panic!("expected Filter, got {:?}", not_plan.root);
23566        };
23567        assert!(exists[0].negated);
23568        assert_eq!(exists[0].kind, ExistsKind::SemiJoin);
23569    }
23570
23571    #[test]
23572    fn exists_in_bind_having_or_stays_unsupported() {
23573        let bind = LogicalPlan::parse(
23574            r#"SELECT ?s ?e WHERE {
23575              ?s <http://ex/p> ?o
23576              BIND(EXISTS { ?s <http://ex/q> ?x } AS ?e)
23577            }"#,
23578        );
23579        assert!(
23580            matches!(bind, Err(ComputeError::UnsupportedSparql(_))),
23581            "{bind:?}"
23582        );
23583        let having = LogicalPlan::parse(
23584            r#"SELECT ?p (COUNT(*) AS ?c) WHERE { ?s ?p ?o } GROUP BY ?p
23585               HAVING EXISTS { ?s <http://ex/q> ?o }"#,
23586        );
23587        assert!(
23588            matches!(having, Err(ComputeError::UnsupportedSparql(_))),
23589            "{having:?}"
23590        );
23591        let or_exists = LogicalPlan::parse(
23592            r#"SELECT ?s WHERE {
23593              ?s <http://ex/p> ?o
23594              FILTER(EXISTS { ?s <http://ex/q> ?x } || ?o = <http://ex/y>)
23595            }"#,
23596        );
23597        assert!(
23598            matches!(or_exists, Err(ComputeError::UnsupportedSparql(_))),
23599            "{or_exists:?}"
23600        );
23601    }
23602
23603    #[test]
23604    fn exists_expr_only_outer_var_is_nested_probe() {
23605        let plan = LogicalPlan::parse(
23606            r#"SELECT ?person ?tag WHERE {
23607              ?person <http://ex/tag> ?tag .
23608              FILTER EXISTS { ?person <http://ex/livesIn> ?city .
23609                              ?city <http://ex/hasWeather> ?w .
23610                              FILTER(?w = ?tag) }
23611            }"#,
23612        )
23613        .unwrap();
23614        let PlanNode::Filter { exists, .. } = &plan.root else {
23615            panic!("expected Filter, got {:?}", plan.root);
23616        };
23617        assert_eq!(exists[0].kind, ExistsKind::NestedProbe);
23618        let names: Vec<_> = exists[0].correlation.iter().map(Variable::as_str).collect();
23619        assert!(names.contains(&"person"), "{names:?}");
23620        assert!(names.contains(&"tag"), "{names:?}");
23621    }
23622
23623    #[test]
23624    fn exists_grounded_scans_with_outer_filter_var_is_nested_probe() {
23625        let plan = LogicalPlan::parse(
23626            r#"SELECT ?person WHERE {
23627              ?person <http://ex/livesIn> ?city .
23628              FILTER EXISTS { <http://ex/brisbane> <http://ex/hasWeather> "Sunny" .
23629                              FILTER(?city = <http://ex/brisbane>) }
23630            }"#,
23631        )
23632        .unwrap();
23633        let PlanNode::Filter { exists, .. } = &plan.root else {
23634            panic!("expected Filter, got {:?}", plan.root);
23635        };
23636        assert_eq!(exists[0].kind, ExistsKind::NestedProbe);
23637        assert_eq!(
23638            exists[0]
23639                .correlation
23640                .iter()
23641                .map(Variable::as_str)
23642                .collect::<Vec<_>>(),
23643            ["city"]
23644        );
23645    }
23646
23647    #[test]
23648    fn exists_filter_on_body_column_stays_semijoin() {
23649        let plan = LogicalPlan::parse(
23650            r#"SELECT ?person WHERE {
23651              ?person <http://ex/livesIn> ?city .
23652              FILTER EXISTS { ?person <http://ex/livesIn> ?c
23653                              FILTER(?person != <http://ex/carol>) }
23654            }"#,
23655        )
23656        .unwrap();
23657        let PlanNode::Filter { exists, .. } = &plan.root else {
23658            panic!("expected Filter, got {:?}", plan.root);
23659        };
23660        assert_eq!(exists[0].kind, ExistsKind::SemiJoin);
23661        assert_eq!(
23662            exists[0]
23663                .correlation
23664                .iter()
23665                .map(Variable::as_str)
23666                .collect::<Vec<_>>(),
23667            ["person"]
23668        );
23669    }
23670
23671    #[test]
23672    fn exists_correlated_subselect_is_unsupported() {
23673        let err = LogicalPlan::parse(
23674            r#"SELECT ?person WHERE {
23675              ?person <http://ex/livesIn> ?city .
23676              FILTER EXISTS { { SELECT ?x WHERE { ?person <http://ex/tag> ?x } } }
23677            }"#,
23678        );
23679        assert!(
23680            matches!(err, Err(ComputeError::UnsupportedSparql(ref msg)) if msg.contains("sub-SELECT")),
23681            "{err:?}"
23682        );
23683    }
23684
23685    #[test]
23686    fn exists_uncorrelated_subselect_plans() {
23687        let plan = LogicalPlan::parse(
23688            r#"SELECT ?s WHERE {
23689              ?s <http://ex/p> ?o
23690              FILTER EXISTS { { SELECT ?x WHERE { <http://ex/a> <http://ex/p> ?x } } }
23691            }"#,
23692        )
23693        .unwrap();
23694        let PlanNode::Filter { exists, .. } = &plan.root else {
23695            panic!("expected Filter, got {:?}", plan.root);
23696        };
23697        assert!(exists[0].correlation.is_empty());
23698        assert_eq!(exists[0].kind, ExistsKind::Uncorrelated);
23699    }
23700
23701    #[test]
23702    fn exists_explain_prints_kind() {
23703        let text = LogicalPlan::explain(
23704            r#"SELECT ?s WHERE {
23705              ?s <http://ex/livesIn> ?city
23706              FILTER EXISTS { ?city <http://ex/hasWeather> "Sunny" }
23707            }"#,
23708            crate::explain::ExplainFormat::Planned,
23709            false,
23710            None,
23711        )
23712        .unwrap();
23713        assert!(
23714            text.contains("(exists") && text.contains("semijoin"),
23715            "EXPLAIN should name EXISTS mode: {text}"
23716        );
23717    }
23718
23719    #[test]
23720    fn union_output_vars_intersect_always_bound() {
23721        let plan = LogicalPlan::parse(
23722            r#"SELECT ?s ?x ?r WHERE {
23723              { ?s <http://ex/p> ?x } UNION { ?s <http://ex/q> ?r }
23724            }"#,
23725        )
23726        .unwrap();
23727        let out = plan.root.output_vars();
23728        assert_eq!(
23729            out.always_bound
23730                .iter()
23731                .map(Variable::as_str)
23732                .collect::<Vec<_>>(),
23733            ["s"]
23734        );
23735        let maybe: Vec<_> = out.maybe_unbound.iter().map(Variable::as_str).collect();
23736        assert!(maybe.contains(&"x"), "{maybe:?}");
23737        assert!(maybe.contains(&"r"), "{maybe:?}");
23738    }
23739
23740    #[test]
23741    fn union_schema_is_left_to_right_without_duplicates() {
23742        let plan = LogicalPlan::parse(
23743            r#"SELECT ?s ?x ?r WHERE {
23744              { ?s <http://ex/p> ?x }
23745              UNION { ?s <http://ex/q> ?r }
23746              UNION { ?x <http://ex/r> ?r }
23747            }"#,
23748        )
23749        .unwrap();
23750        let arms = union_arms(&plan.root);
23751        assert_eq!(arms.len(), 3, "left-deep spine flattens to three arms");
23752        assert_eq!(
23753            union_schema(&arms)
23754                .iter()
23755                .map(Variable::as_str)
23756                .collect::<Vec<_>>(),
23757            ["s", "x", "r"],
23758            "arm order fixed, repeated names kept once"
23759        );
23760    }
23761
23762    #[test]
23763    fn join_after_union_hashes_only_shared_always_bound() {
23764        let plan = LogicalPlan::parse(
23765            r#"SELECT ?s ?o ?x ?r WHERE {
23766              ?s <http://ex/p> ?o .
23767              { ?s <http://ex/q> ?x } UNION { ?s <http://ex/r> ?r }
23768            }"#,
23769        )
23770        .unwrap();
23771        let PlanNode::Join {
23772            left,
23773            right,
23774            hash_keys,
23775            ..
23776        } = &plan.root
23777        else {
23778            panic!("expected Join at root, got {:?}", plan.root);
23779        };
23780        assert!(
23781            matches!(left.as_ref(), PlanNode::Union { .. })
23782                || matches!(right.as_ref(), PlanNode::Union { .. }),
23783            "expected a Union child, got left={left:?} right={right:?}"
23784        );
23785        assert_eq!(
23786            hash_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
23787            ["s"],
23788            "only always-bound ?s should be a hash key: {hash_keys:?}"
23789        );
23790        assert!(!hash_keys.iter().any(|v| v.as_str() == "x"));
23791        assert!(!hash_keys.iter().any(|v| v.as_str() == "r"));
23792    }
23793
23794    #[test]
23795    fn optional_then_join_on_optional_var_excludes_it_from_hash_keys() {
23796        let plan = LogicalPlan::parse(
23797            r#"SELECT ?s ?x ?y WHERE {
23798              ?s <http://ex/p> ?o .
23799              OPTIONAL { ?s <http://ex/q> ?x }
23800              ?x <http://ex/r> ?y .
23801            }"#,
23802        )
23803        .unwrap();
23804
23805        let PlanNode::Join { hash_keys, .. } = &plan.root else {
23806            panic!("expected Join at root, got {:?}", plan.root);
23807        };
23808        assert!(
23809            !hash_keys.iter().any(|v| v.as_str() == "x"),
23810            "maybe-unbound ?x must not be a hard hash key: {hash_keys:?}"
23811        );
23812
23813        // Which side the OPTIONAL's LeftJoin occupies is a seating decision;
23814        // the property is that the OPTIONAL's arm is what can leave ?x
23815        // unbound, wherever the association put it.
23816        let outer = outermost_left_join(&plan.root);
23817        let PlanNode::LeftJoin { .. } = outer else {
23818            panic!("expected the OPTIONAL's LeftJoin, got {:#?}", plan.root);
23819        };
23820        let lj_out = outer.output_vars();
23821        assert!(
23822            lj_out.maybe_unbound.iter().any(|v| v.as_str() == "x"),
23823            "LeftJoin must expose ?x as maybe-unbound: {lj_out:?}"
23824        );
23825
23826        let out = plan.root.output_vars();
23827        assert!(out.always_bound.iter().any(|v| v.as_str() == "s"));
23828        // The required `?x <r> ?y` arm always binds ?x, so the Join promotes
23829        // it out of maybe-unbound regardless of which side that arm sits on.
23830        assert!(
23831            out.always_bound.iter().any(|v| v.as_str() == "x"),
23832            "Join with an always-bound ?x arm should promote: {out:?}"
23833        );
23834        assert!(!out.maybe_unbound.iter().any(|v| v.as_str() == "x"));
23835    }
23836
23837    fn walk_plan<'a>(node: &'a PlanNode, visit: &mut impl FnMut(&'a PlanNode)) {
23838        visit(node);
23839        match node {
23840            PlanNode::Join { left, right, .. }
23841            | PlanNode::LeftJoin { left, right, .. }
23842            | PlanNode::Union { left, right } => {
23843                walk_plan(left, visit);
23844                walk_plan(right, visit);
23845            }
23846            PlanNode::Filter { inner, exists, .. } => {
23847                walk_plan(inner, visit);
23848                for clause in exists {
23849                    walk_plan(&clause.body, visit);
23850                }
23851            }
23852            PlanNode::Extend { inner, .. }
23853            | PlanNode::Slice { inner, .. }
23854            | PlanNode::Distinct { inner, .. }
23855            | PlanNode::Sort { inner, .. }
23856            | PlanNode::Group { inner, .. }
23857            | PlanNode::JoinGraphVar { inner, .. } => walk_plan(inner, visit),
23858            PlanNode::SubSelect(sub) => walk_plan(&sub.inner, visit),
23859            PlanNode::CustomNode(custom) => {
23860                for child in &custom.children {
23861                    walk_plan(child, visit);
23862                }
23863            }
23864            PlanNode::Scan(_)
23865            | PlanNode::Path(_)
23866            | PlanNode::Values(_)
23867            | PlanNode::NamedGraphs { .. }
23868            | PlanNode::NamedGraphExists { .. }
23869            | PlanNode::DomainCounts { .. }
23870            | PlanNode::HeadCounts { .. }
23871            | PlanNode::PatternCount { .. }
23872            | PlanNode::Unit => {}
23873        }
23874    }
23875
23876    /// Every `VALUES` in the plan, including tables inside a lowered EXISTS
23877    /// body. [`walk_plan`] owns the traversal so this cannot drift from the
23878    /// other plan walkers.
23879    fn values_in_plan(node: &PlanNode) -> Vec<&crate::plan::ValuesOp> {
23880        let mut out = Vec::new();
23881        walk_plan(node, &mut |current| {
23882            if let PlanNode::Values(values) = current {
23883                out.push(values);
23884            }
23885        });
23886        out
23887    }
23888
23889    fn has_left_join(node: &PlanNode) -> bool {
23890        let mut found = false;
23891        walk_plan(node, &mut |current| {
23892            if matches!(current, PlanNode::LeftJoin { .. }) {
23893                found = true;
23894            }
23895        });
23896        found
23897    }
23898
23899    /// First `Filter.residual` expression in the tree (test helper).
23900    fn first_residual(node: &PlanNode) -> Option<&Expression> {
23901        match node {
23902            PlanNode::Filter { residual, .. } => residual.as_ref(),
23903            PlanNode::Join { left, right, .. }
23904            | PlanNode::LeftJoin { left, right, .. }
23905            | PlanNode::Union { left, right } => {
23906                first_residual(left).or_else(|| first_residual(right))
23907            }
23908            PlanNode::CustomNode(custom) => custom.children.iter().find_map(first_residual),
23909            PlanNode::Extend { inner, .. }
23910            | PlanNode::Slice { inner, .. }
23911            | PlanNode::Distinct { inner, .. }
23912            | PlanNode::Sort { inner, .. }
23913            | PlanNode::Group { inner, .. }
23914            | PlanNode::JoinGraphVar { inner, .. } => first_residual(inner),
23915            PlanNode::SubSelect(sub) => first_residual(&sub.inner),
23916            PlanNode::Scan(_)
23917            | PlanNode::Path(_)
23918            | PlanNode::Values(_)
23919            | PlanNode::Unit
23920            | PlanNode::NamedGraphs { .. }
23921            | PlanNode::NamedGraphExists { .. }
23922            | PlanNode::DomainCounts { .. }
23923            | PlanNode::HeadCounts { .. }
23924            | PlanNode::PatternCount { .. } => None,
23925        }
23926    }
23927
23928    #[test]
23929    fn single_value_values_grounds_early_conjuncts() {
23930        // `?a < ?b` is MaybeEncoded → early. The one-row VALUES column must
23931        // push its constant into the comparison so the encoded compare sees
23932        // one ground side (same guards as the residual grounding).
23933        let plan = LogicalPlan::parse(
23934            r#"SELECT ?b WHERE {
23935              VALUES ?a { 5 }
23936              ?s <http://ex/count> ?b .
23937              FILTER(?a < ?b)
23938            }"#,
23939        )
23940        .unwrap();
23941        // The one-row VALUES column substitutes its constant into the
23942        // comparison, making it exact (`5 < ?b`); the scan owns the verdict.
23943        assert!(
23944            !contains_filter(&plan.root),
23945            "the substituted integer comparison should move into the scan: {:?}",
23946            plan.root
23947        );
23948        let mut scans = Vec::new();
23949        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
23950        assert_eq!(scans.len(), 1);
23951        assert!(
23952            scans[0].eager.contains(&SlotComparison {
23953                slot: QuadSlot::Object,
23954                op: CompareOp::Gt,
23955                term: EncodedTerm::from(&Literal::from(5i64)),
23956            }),
23957            "the VALUES constant must reach the eager comparison: {:?}",
23958            scans[0].eager
23959        );
23960        assert!(
23961            scans[0].pattern.object.is_none(),
23962            "VALUES grounds the comparison, not the pattern: {:?}",
23963            scans[0]
23964        );
23965    }
23966
23967    #[test]
23968    fn single_value_values_grounds_residual_conjuncts() {
23969        // `contains` is AlwaysResolve, so the conjunct lowers into
23970        // `residual`. The one-row VALUES column must substitute into it
23971        // BEFORE the plugin hook runs: a datatype plugin's rewrite
23972        // (GeoSPARQL geof:*) only matches inline constants.
23973        let plan = LogicalPlan::parse(
23974            r#"SELECT ?s WHERE {
23975              VALUES ?needle { "Brisbane" }
23976              ?s <http://ex/name> ?n .
23977              FILTER(contains(?needle, "isbane"))
23978            }"#,
23979        )
23980        .unwrap();
23981        let residual = format!(
23982            "{:?}",
23983            first_residual(&plan.root).expect("plan carries a residual filter")
23984        );
23985        assert!(
23986            residual.contains("Brisbane"),
23987            "grounded residual: {residual}"
23988        );
23989        assert!(
23990            !residual.contains("needle"),
23991            "grounded residual: {residual}"
23992        );
23993    }
23994
23995    #[test]
23996    fn multi_row_values_does_not_ground_residual_conjuncts() {
23997        // Two different bindings: substitution would change which rows the
23998        // FILTER drops, so the conjunct must keep the variable.
23999        let plan = LogicalPlan::parse(
24000            r#"SELECT ?s WHERE {
24001              VALUES ?needle { "Brisbane" "Ipswich" }
24002              ?s <http://ex/name> ?n .
24003              FILTER(contains(?needle, "isbane"))
24004            }"#,
24005        )
24006        .unwrap();
24007        let residual = format!(
24008            "{:?}",
24009            first_residual(&plan.root).expect("plan carries a residual filter")
24010        );
24011        assert!(
24012            residual.contains("needle"),
24013            "ungrounded residual: {residual}"
24014        );
24015    }
24016
24017    fn has_hash_key(node: &PlanNode, name: &str) -> bool {
24018        let mut found = false;
24019        walk_plan(node, &mut |current| {
24020            if let PlanNode::Join { hash_keys, .. } = current
24021                && hash_keys.iter().any(|key| key.as_str() == name)
24022            {
24023                found = true;
24024            }
24025        });
24026        found
24027    }
24028
24029    #[test]
24030    fn strstarts_on_optional_var_becomes_inner_join() {
24031        let plan = LogicalPlan::parse(
24032            r#"SELECT ?inst ?search1 WHERE {
24033              OPTIONAL { ?inst <http://ex/label> ?search1 }
24034              FILTER(strstarts(str(?search1), "Brisbane"))
24035              { ?inst a <http://ex/City> }
24036            }"#,
24037        )
24038        .unwrap();
24039        assert!(
24040            !has_left_join(&plan.root),
24041            "OPTIONAL should be an inner join, got {:?}",
24042            plan.root
24043        );
24044        assert!(
24045            has_hash_key(&plan.root, "inst"),
24046            "city and label should join on ?inst, got {:?}",
24047            plan.root
24048        );
24049    }
24050
24051    #[test]
24052    fn nested_select_strstarts_optional_becomes_inner_join() {
24053        let plan = LogicalPlan::parse(
24054            r#"SELECT ?inst WHERE {
24055              {
24056                SELECT DISTINCT ?inst ?search1 WHERE {
24057                  OPTIONAL { ?inst <http://ex/label> ?search1 }
24058                  FILTER(strstarts(str(?search1), "Brisbane"))
24059                  { ?inst a <http://ex/City> }
24060                } LIMIT 100
24061              }
24062            }"#,
24063        )
24064        .unwrap();
24065        let PlanNode::SubSelect(sub) = &plan.root else {
24066            panic!("expected subselect, got {:?}", plan.root);
24067        };
24068        assert!(
24069            !has_left_join(&sub.inner),
24070            "inner OPTIONAL should be an inner join, got {:?}",
24071            sub.inner
24072        );
24073        assert!(
24074            has_hash_key(&sub.inner, "inst"),
24075            "inner city and label should join on ?inst, got {:?}",
24076            sub.inner
24077        );
24078    }
24079
24080    #[test]
24081    fn filter_wrapped_only_around_optional_still_becomes_inner_join() {
24082        let plan = LogicalPlan::parse(
24083            r#"SELECT ?inst ?search1 WHERE {
24084              { ?inst a <http://ex/City> }
24085              {
24086                OPTIONAL { ?inst <http://ex/label> ?search1 }
24087                FILTER(strstarts(str(?search1), "Brisbane"))
24088              }
24089            }"#,
24090        )
24091        .unwrap();
24092        assert!(
24093            !has_left_join(&plan.root),
24094            "OPTIONAL under its own FILTER should still become an inner join, got {:?}",
24095            plan.root
24096        );
24097        assert!(has_hash_key(&plan.root, "inst"), "got {:?}", plan.root);
24098    }
24099
24100    #[test]
24101    fn optional_then_join_with_strstarts_keeps_left_join() {
24102        // The `:r` pattern binds `?x` before the FILTER runs, so a failed
24103        // optional can still be an answer.
24104        let plan = LogicalPlan::parse(
24105            r#"SELECT ?s ?x ?y WHERE {
24106              ?s <http://ex/p> ?o .
24107              OPTIONAL { ?s <http://ex/q> ?x }
24108              ?x <http://ex/r> ?y .
24109              FILTER(strstarts(str(?x), "a"))
24110            }"#,
24111        )
24112        .unwrap();
24113        assert!(
24114            has_left_join(&plan.root),
24115            "OPTIONAL must stay, got {:?}",
24116            plan.root
24117        );
24118        assert!(
24119            !has_hash_key(&plan.root, "x"),
24120            "?x is empty when the optional misses: {plan:?}"
24121        );
24122    }
24123
24124    #[test]
24125    fn optional_without_filter_stays_left_join() {
24126        let plan = LogicalPlan::parse(
24127            r#"SELECT ?inst ?search1 WHERE {
24128              OPTIONAL { ?inst <http://ex/label> ?search1 }
24129              { ?inst a <http://ex/City> }
24130            }"#,
24131        )
24132        .unwrap();
24133        assert!(has_left_join(&plan.root), "got {:?}", plan.root);
24134    }
24135
24136    #[test]
24137    fn or_with_isiri_keeps_left_join() {
24138        let plan = LogicalPlan::parse(
24139            r#"SELECT ?inst ?search1 WHERE {
24140              OPTIONAL { ?inst <http://ex/label> ?search1 }
24141              FILTER(strstarts(str(?search1), "Brisbane") || isIRI(?inst))
24142              { ?inst a <http://ex/City> }
24143            }"#,
24144        )
24145        .unwrap();
24146        assert!(has_left_join(&plan.root), "got {:?}", plan.root);
24147    }
24148
24149    #[test]
24150    fn coalesce_regex_keeps_left_join() {
24151        let plan = LogicalPlan::parse(
24152            r#"SELECT ?inst ?search1 WHERE {
24153              OPTIONAL { ?inst <http://ex/label> ?search1 }
24154              FILTER(regex(coalesce(str(?search1), str(?extractedLabel)), "Brisbane", "i"))
24155              { ?inst a <http://ex/City> }
24156            }"#,
24157        )
24158        .unwrap();
24159        assert!(has_left_join(&plan.root), "got {:?}", plan.root);
24160    }
24161
24162    #[test]
24163    fn later_pattern_that_binds_filtered_var_keeps_left_join() {
24164        let plan = LogicalPlan::parse(
24165            r#"SELECT ?inst ?search1 ?o WHERE {
24166              OPTIONAL { ?inst <http://ex/label> ?search1 }
24167              { ?inst a <http://ex/City> }
24168              { ?search1 <http://ex/p> ?o }
24169              FILTER(strstarts(str(?search1), "Brisbane"))
24170            }"#,
24171        )
24172        .unwrap();
24173        assert!(
24174            has_left_join(&plan.root),
24175            "the :p pattern can fill ?search1, got {:?}",
24176            plan.root
24177        );
24178    }
24179
24180    #[test]
24181    fn unsupported_syntax_returns_typed_errors() {
24182        for (query, expected) in [
24183            (
24184                "SELECT ?s WHERE { ?s <http://ex/p> ?o . MINUS { ?s <http://ex/q> ?o } }",
24185                "MINUS",
24186            ),
24187            (
24188                "ASK WHERE { ?s <http://ex/p> ?o }",
24189                "only SELECT queries are supported",
24190            ),
24191        ] {
24192            let error = LogicalPlan::parse(query).unwrap_err();
24193            let message = error.to_string();
24194            assert!(
24195                message.contains(expected),
24196                "{query}\n  expected {expected:?} in {message:?}"
24197            );
24198            assert!(matches!(error, ComputeError::UnsupportedSparql(_)));
24199        }
24200    }
24201
24202    #[test]
24203    fn malformed_sparql_is_a_syntax_error() {
24204        let error = LogicalPlan::parse("SELECT ?s WHERE {").unwrap_err();
24205        assert!(matches!(error, ComputeError::Sparql(_)), "{error}");
24206    }
24207
24208    #[test]
24209    fn grouped_select_of_non_key_is_a_clear_syntax_error() {
24210        let error = LogicalPlan::parse(
24211            r#"SELECT ?b ?p (SAMPLE(?o) AS ?s) WHERE {
24212                  BIND(<http://ex/s> AS ?b)
24213                  ?b ?p ?o .
24214                }
24215                GROUP BY ?o"#,
24216        )
24217        .unwrap_err();
24218        let text = error.to_string();
24219        assert!(matches!(error, ComputeError::Sparql(_)), "{text}");
24220        assert!(
24221            text.contains("grouping keys and aggregate results"),
24222            "{text}"
24223        );
24224        assert!(!text.contains("expected one of"), "{text}");
24225    }
24226
24227    #[test]
24228    fn blank_node_in_bgp_becomes_an_unprojected_join_var() {
24229        let plan = LogicalPlan::parse("SELECT ?o WHERE { _:b <http://ex/p> ?o }").unwrap();
24230        assert_eq!(plan.projection, vec![var("o")]);
24231        let scans = plan.scans().unwrap();
24232        assert_eq!(scans.len(), 1);
24233        let scan = scans[0];
24234        assert_eq!(scan.object, Some(var("o")));
24235        let subject = scan
24236            .subject
24237            .as_ref()
24238            .expect("blank node becomes a variable");
24239        assert_ne!(subject, &var("o"));
24240        assert!(!plan.projection.contains(subject));
24241    }
24242
24243    #[test]
24244    fn blank_node_property_list_is_three_scans_joining_on_the_anon() {
24245        let plan = LogicalPlan::parse(
24246            r#"
24247            SELECT ?s ?c WHERE {
24248              ?s <http://ex/livesIn> [ <http://ex/hasWeather> "sunny"; <http://ex/hasName> ?c ]
24249            }
24250            "#,
24251        )
24252        .unwrap();
24253        assert_eq!(plan.projection, vec![var("s"), var("c")]);
24254        let scans = plan.scans().unwrap();
24255        assert_eq!(scans.len(), 3);
24256        assert_eq!(
24257            scans[0].pattern.object,
24258            Some(EncodedTerm::from(&Literal::from("sunny"))),
24259            "bound weather literal should lead the BGP"
24260        );
24261        let joins = plan.join_ops().unwrap();
24262        assert_eq!(joins.len(), 2);
24263        let anon = scans[0]
24264            .subject
24265            .as_ref()
24266            .expect("property list focus is a variable");
24267        assert!(!plan.projection.contains(anon));
24268        assert!(
24269            joins.iter().any(|edge| edge.hash_keys.contains(anon)),
24270            "anonymous node should be a join key: {joins:?}"
24271        );
24272    }
24273
24274    #[test]
24275    fn labeled_blank_node_coreference_shares_one_join_key() {
24276        let plan = LogicalPlan::parse(
24277            r#"
24278            SELECT ?o1 ?o2 WHERE {
24279              _:a <http://ex/p1> ?o1 .
24280              _:a <http://ex/p2> ?o2 .
24281            }
24282            "#,
24283        )
24284        .unwrap();
24285        assert_eq!(plan.projection, vec![var("o1"), var("o2")]);
24286        let scans = plan.scans().unwrap();
24287        assert_eq!(scans.len(), 2);
24288        let left = scans[0].subject.as_ref().expect("subject is a variable");
24289        let right = scans[1].subject.as_ref().expect("subject is a variable");
24290        assert_eq!(left, right, "same _:a label must be one variable");
24291        assert!(!plan.projection.contains(left));
24292        let joins = plan.join_ops().unwrap();
24293        assert_eq!(joins.len(), 1);
24294        assert_eq!(joins[0].hash_keys, vec![left.clone()]);
24295    }
24296
24297    #[test]
24298    fn select_star_does_not_project_blank_nodes() {
24299        let plan = LogicalPlan::parse("SELECT * WHERE { [] <http://ex/p> <http://ex/q> }").unwrap();
24300        assert!(
24301            plan.projection.is_empty(),
24302            "blank nodes are not in-scope for SELECT *: {:?}",
24303            plan.projection
24304        );
24305        let scans = plan.scans().unwrap();
24306        assert_eq!(scans.len(), 1);
24307        assert!(scans[0].subject.is_some());
24308    }
24309
24310    #[test]
24311    fn collection_lowers_to_rdf_first_rest_scans() {
24312        let plan =
24313            LogicalPlan::parse("SELECT ?x WHERE { ( ?x ) <http://ex/p> <http://ex/z> }").unwrap();
24314        assert_eq!(plan.projection, vec![var("x")]);
24315        let scans = plan.scans().unwrap();
24316        assert_eq!(scans.len(), 3, "rdf:first, rdf:rest rdf:nil, and :p :z");
24317        let first = EncodedTerm::from(
24318            &NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#first").unwrap(),
24319        );
24320        let rest = EncodedTerm::from(
24321            &NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest").unwrap(),
24322        );
24323        let p = EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap());
24324        let predicates: Vec<_> = scans.iter().map(|s| s.pattern.predicate.clone()).collect();
24325        assert!(predicates.contains(&Some(first)), "{predicates:?}");
24326        assert!(predicates.contains(&Some(rest)), "{predicates:?}");
24327        assert!(predicates.contains(&Some(p)), "{predicates:?}");
24328        assert!(
24329            scans.iter().any(|s| s.object == Some(var("x"))),
24330            "rdf:first object should be ?x"
24331        );
24332    }
24333
24334    #[test]
24335    fn explain_sse_is_jena_s_expression() {
24336        let sse = explain_optimised(
24337            r#"
24338            SELECT ?person ?city WHERE {
24339              ?person <http://ex/livesIn> ?city .
24340              ?city <http://ex/hasWeather> "Sunny" .
24341            }
24342            "#,
24343        );
24344        // Bound "Sunny" pattern is more selective → Sparopt leads the BGP.
24345        assert!(sse.contains("(project"), "expected project wrapper: {sse}");
24346        assert!(sse.contains("(bgp"), "expected bgp: {sse}");
24347        assert!(
24348            sse.find("Sunny").unwrap() < sse.find("livesIn").unwrap(),
24349            "Sunny pattern should be ordered first: {sse}"
24350        );
24351    }
24352
24353    #[test]
24354    fn explain_sparql_uses_display_syntax() {
24355        let text =
24356            explain_optimised_sparql(r#"SELECT ?s WHERE { ?s <http://ex/p> ?o FILTER(?o = 1) }"#);
24357        assert!(text.contains("SELECT"), "{text}");
24358        assert!(text.contains("FILTER"), "{text}");
24359        assert!(!text.contains("(project"), "{text}");
24360    }
24361
24362    #[test]
24363    fn explain_ask_shows_existence_slice() {
24364        let sse = explain_sse(r#"ASK WHERE { ?s <http://ex/p> ?o }"#, false);
24365        assert!(sse.contains("(ask"), "expected ask wrapper: {sse}");
24366        assert!(
24367            !sse.contains("(slice"),
24368            "L0 ASK should not inject LIMIT 1: {sse}"
24369        );
24370        assert!(sse.contains("(bgp"), "expected bgp: {sse}");
24371
24372        let l1 = explain_optimised(r#"ASK WHERE { ?s <http://ex/p> ?o }"#);
24373        assert!(l1.contains("(slice"), "L1 ASK should show LIMIT 1: {l1}");
24374
24375        let text = explain_est(r#"ASK WHERE { ?s <http://ex/p> ?o }"#, None);
24376        assert!(text.contains("(slice ~"), "{text}");
24377        assert!(
24378            text.contains("(scan ") || text.contains("(triple"),
24379            "{text}"
24380        );
24381
24382        let sparql = explain_optimised_sparql(r#"ASK WHERE { ?s <http://ex/p> ?o }"#);
24383        assert!(sparql.contains("ASK"), "{sparql}");
24384        assert!(!sparql.contains("(ask"), "{sparql}");
24385    }
24386
24387    #[test]
24388    fn explain_construct_keeps_template_and_where_plan() {
24389        let sse = explain_sse(
24390            r#"CONSTRUCT { ?s <http://ex/p> ?o } WHERE { ?s <http://ex/p> ?o }"#,
24391            false,
24392        );
24393        assert!(
24394            sse.contains("(construct"),
24395            "expected construct wrapper: {sse}"
24396        );
24397        assert!(sse.contains("(bgp"), "expected WHERE bgp: {sse}");
24398
24399        let text = explain_est(
24400            r#"CONSTRUCT { ?s <http://ex/p> ?o } WHERE { ?s <http://ex/p> ?o }"#,
24401            None,
24402        );
24403        assert!(
24404            text.contains("(scan ") || text.contains("(triple"),
24405            "{text}"
24406        );
24407        assert!(text.starts_with("(construct"), "{text}");
24408
24409        let sparql = explain_optimised_sparql(
24410            r#"CONSTRUCT { ?s <http://ex/p> ?o } WHERE { ?s <http://ex/p> ?o }"#,
24411        );
24412        assert!(sparql.contains("CONSTRUCT"), "{sparql}");
24413        assert!(!sparql.contains("(construct"), "{sparql}");
24414    }
24415
24416    #[test]
24417    fn explain_estimates_annotates_plan_nodes() {
24418        let text = explain_est(
24419            r#"
24420            SELECT ?person ?city WHERE {
24421              ?person <http://ex/livesIn> ?city .
24422              ?city <http://ex/hasWeather> "Sunny" .
24423            }
24424            "#,
24425            None,
24426        );
24427        assert!(text.starts_with("(project ~"), "{text}");
24428        assert!(
24429            text.contains("(join ~") && text.contains("(shuffle ?city)"),
24430            "{text}"
24431        );
24432        assert!(text.contains("(domain ?city ?)"), "{text}");
24433        assert!(text.contains("\"Sunny\""), "{text}");
24434        // Bound literal pattern is more selective → scanned first under no profile.
24435        let first_scan = text.find("(scan ").expect("first Scan");
24436        let second_scan = text[first_scan + 1..]
24437            .find("(scan ")
24438            .map(|i| i + first_scan + 1)
24439            .expect("second Scan");
24440        assert!(
24441            text[first_scan..second_scan].contains("\"Sunny\""),
24442            "Sunny scan should be first child: {text}"
24443        );
24444        assert!(
24445            text[second_scan..].contains("?person"),
24446            "livesIn scan should follow: {text}"
24447        );
24448    }
24449
24450    #[test]
24451    fn explain_estimates_renders_rdf_type_as_a() {
24452        let text = explain_est(
24453            r#"SELECT * WHERE { ?sub ?pred ?obj . OPTIONAL { ?sub a ?c } }"#,
24454            None,
24455        );
24456        assert!(
24457            text.contains("?sub a ?c") || text.contains("(triple ?sub a ?c)"),
24458            "rdf:type should render as SPARQL `a`: {text}"
24459        );
24460        assert!(
24461            !text.contains("?sub <#"),
24462            "optional type scan should not use a hash placeholder: {text}"
24463        );
24464    }
24465
24466    #[test]
24467    fn explain_estimates_optional_bind_broadcasts_without_copying_extend() {
24468        let sparql = r#"
24469            SELECT * WHERE {
24470              BIND(<http://ex/brisbane> AS ?b)
24471              ?b ?p ?o .
24472              OPTIONAL { ?s1 ?p2 ?b }
24473            }
24474        "#;
24475        let plan = LogicalPlan::parse(sparql).unwrap();
24476        let PlanNode::LeftJoin {
24477            right, hash_keys, ..
24478        } = &plan.root
24479        else {
24480            panic!("expected LeftJoin at root, got {:?}", plan.root);
24481        };
24482        assert!(
24483            hash_keys.iter().any(|v| v.as_str() == "b"),
24484            "optional join key should be ?b: {hash_keys:?}"
24485        );
24486        let PlanNode::Scan(scan) = right.as_ref() else {
24487            panic!("optional arm must stay a Scan, not Join(Extend, Scan): {right:?}");
24488        };
24489        assert!(
24490            scan.produced_row_count_estimate < 1_000_000,
24491            "bound optional scan must not use unbound ~3e6: {}",
24492            scan.produced_row_count_estimate
24493        );
24494        assert!(
24495            scan.pattern.object.is_some(),
24496            "single BIND IRI should ground the optional object slot"
24497        );
24498        assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("b"));
24499        assert!(
24500            scan.broadcasted.is_none(),
24501            "unique BIND should not stamp broadcast, got {:?}",
24502            scan.broadcasted
24503        );
24504        assert_eq!(
24505            grounded_of(scan),
24506            vec![("b", PatternSlot::Object)],
24507            "expected grounded object on ?b, got {:?}",
24508            scan.grounded
24509        );
24510
24511        let text = explain_est(sparql, None);
24512        assert!(
24513            text.contains("(grounded ?b object)"),
24514            "EXPLAIN should annotate the optional scan: {text}"
24515        );
24516    }
24517
24518    #[test]
24519    fn ground_unit_bind_lowers_to_values() {
24520        let plan = LogicalPlan::parse(r#"SELECT ?c WHERE { BIND("hello" AS ?c) }"#).unwrap();
24521        match &plan.root {
24522            PlanNode::Values(values) => {
24523                assert_eq!(values.variables, vec![var("c")]);
24524                assert_eq!(values.rows.len(), 1);
24525            }
24526            other => panic!("expected Values from ground unit BIND, got {other:?}"),
24527        }
24528        assert_eq!(plan.projection, vec![var("c")]);
24529    }
24530
24531    #[test]
24532    fn bind_copy_after_scan_stays_extend() {
24533        let plan =
24534            LogicalPlan::parse(r#"SELECT ?c WHERE { ?s <http://ex/p> ?o . BIND(?s AS ?c) }"#)
24535                .unwrap();
24536        let mut found = false;
24537        fn walk(node: &PlanNode, found: &mut bool) {
24538            match node {
24539                PlanNode::Extend { .. } => *found = true,
24540                PlanNode::Join { left, right, .. }
24541                | PlanNode::Union { left, right }
24542                | PlanNode::LeftJoin { left, right, .. } => {
24543                    walk(left, found);
24544                    walk(right, found);
24545                }
24546                PlanNode::Filter { inner, .. }
24547                | PlanNode::Slice { inner, .. }
24548                | PlanNode::Distinct { inner, .. }
24549                | PlanNode::Sort { inner, .. }
24550                | PlanNode::Group { inner, .. } => {
24551                    walk(inner, found);
24552                }
24553                _ => {}
24554            }
24555        }
24556        walk(&plan.root, &mut found);
24557        assert!(
24558            found,
24559            "BIND of a variable after a scan must stay Extend, got {:?}",
24560            plan.root
24561        );
24562    }
24563
24564    #[test]
24565    fn values_alone_is_a_values_node() {
24566        let plan =
24567            LogicalPlan::parse(r#"SELECT ?x WHERE { VALUES ?x { <http://ex/a> <http://ex/b> } }"#)
24568                .unwrap();
24569        let PlanNode::Values(values) = &plan.root else {
24570            panic!("expected Values, got {:?}", plan.root);
24571        };
24572        assert_eq!(values.variables, vec![var("x")]);
24573        assert_eq!(values.rows.len(), 2);
24574        assert_eq!(values.produced_row_count_estimate(), 2);
24575    }
24576
24577    #[test]
24578    fn values_undef_column_is_maybe_unbound() {
24579        let plan = LogicalPlan::parse(
24580            r#"SELECT ?x ?y WHERE { VALUES (?x ?y) { (<http://ex/a> UNDEF) } }"#,
24581        )
24582        .unwrap();
24583        let out = plan.root.output_vars();
24584        assert_eq!(
24585            out.always_bound
24586                .iter()
24587                .map(Variable::as_str)
24588                .collect::<Vec<_>>(),
24589            ["x"]
24590        );
24591        assert_eq!(
24592            out.maybe_unbound
24593                .iter()
24594                .map(Variable::as_str)
24595                .collect::<Vec<_>>(),
24596            ["y"]
24597        );
24598    }
24599
24600    #[test]
24601    fn small_values_sorts_left_of_a_scan_and_hints_broadcast() {
24602        let plan = LogicalPlan::parse(
24603            r#"
24604            SELECT ?person WHERE {
24605              ?person <http://ex/livesIn> ?city .
24606              VALUES ?city { <http://ex/brisbane> <http://ex/sydney> }
24607            }
24608            "#,
24609        )
24610        .unwrap();
24611        let PlanNode::Join {
24612            left,
24613            right,
24614            hash_keys,
24615            probe_key_domains: _,
24616            probe_key_overlap_milli: _,
24617            rhs_hostable_keys: _,
24618            meta,
24619        } = &plan.root
24620        else {
24621            panic!("expected Join, got {:?}", plan.root);
24622        };
24623        assert!(
24624            matches!(left.as_ref(), PlanNode::Values(_)),
24625            "small VALUES should be the left build side, got {left:?}"
24626        );
24627        assert!(matches!(right.as_ref(), PlanNode::Scan(_)));
24628        assert_eq!(hash_keys, &vec![var("city")]);
24629        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
24630        let PlanNode::Scan(scan) = right.as_ref() else {
24631            unreachable!("asserted Scan");
24632        };
24633        assert!(
24634            scan.pattern.object.is_none(),
24635            "multi-row VALUES must not prefix the scan slot, got {scan:?}"
24636        );
24637        assert_eq!(
24638            scan.broadcasted
24639                .as_ref()
24640                .map(|(v, slot)| (v.as_str(), *slot)),
24641            Some(("city", PatternSlot::Object))
24642        );
24643    }
24644
24645    #[test]
24646    fn singleton_values_prefixes_broadcast_scan_object() {
24647        let brisbane = NamedNode::new("http://ex/brisbane").unwrap();
24648        let plan = LogicalPlan::parse(
24649            r#"
24650            SELECT ?person WHERE {
24651              ?person <http://ex/livesIn> ?city .
24652              VALUES ?city { <http://ex/brisbane> }
24653            }
24654            "#,
24655        )
24656        .unwrap();
24657        let PlanNode::Join {
24658            left,
24659            right,
24660            hash_keys,
24661            probe_key_domains: _,
24662            probe_key_overlap_milli: _,
24663            rhs_hostable_keys: _,
24664            meta,
24665        } = &plan.root
24666        else {
24667            panic!("expected Join, got {:?}", plan.root);
24668        };
24669        assert!(matches!(left.as_ref(), PlanNode::Values(_)));
24670        assert_eq!(hash_keys, &vec![var("city")]);
24671        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
24672        let PlanNode::Scan(scan) = right.as_ref() else {
24673            panic!("expected Scan probe, got {right:?}");
24674        };
24675        assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("city"));
24676        assert_eq!(scan.pattern.object, Some(EncodedTerm::from(&brisbane)));
24677        assert!(
24678            scan.broadcasted.is_none(),
24679            "unique VALUES should not stamp broadcast, got {:?}",
24680            scan.broadcasted
24681        );
24682        assert_eq!(
24683            grounded_of(scan),
24684            vec![("city", PatternSlot::Object)],
24685            "expected grounded object on ?city, got {:?}",
24686            scan.grounded
24687        );
24688    }
24689
24690    /// A `Join(Values, Scan)` pair the VALUES placement chose stays one
24691    /// operand: the association pass may seat it among the other arms, but it
24692    /// never pulls the scan away from the table that drives it.
24693    ///
24694    /// The fixture keeps that claim falsifiable. The table is multi-row, so
24695    /// it is not the seed, and a second keyed scan is cheaper than the pair's
24696    /// own scan. A split pool would therefore seat the table on the cheaper
24697    /// arm and leave `ferry` unpaired; only the transparent-pair rule keeps
24698    /// the table directly above `ferry`.
24699    #[test]
24700    fn a_values_scan_pair_stays_together_through_reassociation() {
24701        fn values_joined_to(node: &PlanNode, predicate: &EncodedTerm) -> bool {
24702            match node {
24703                PlanNode::Join { left, right, .. } => {
24704                    (matches!(**left, PlanNode::Values(_))
24705                        && matches!(right.as_ref(), PlanNode::Scan(scan)
24706                            if scan.pattern.predicate.as_ref() == Some(predicate)))
24707                        || values_joined_to(left, predicate)
24708                        || values_joined_to(right, predicate)
24709                }
24710                _ => false,
24711            }
24712        }
24713        let routes: Vec<String> = (0..100).map(|i| format!("http://ex/route{i}")).collect();
24714        let route_refs: Vec<&str> = routes.iter().map(String::as_str).collect();
24715        let values = values_node("cls", &route_refs);
24716        let ferry_predicate = EncodedTerm::from(&NamedNode::new("http://ex/type").unwrap());
24717        let ferry = PlanNode::Scan(var_scan(
24718            Some("feature"),
24719            "http://ex/type",
24720            Some("cls"),
24721            900,
24722        ));
24723        // Cheaper than `ferry`, so a split pool would let the table drive this
24724        // arm and the placement choice would be lost.
24725        let cheaper = PlanNode::Scan(var_scan(Some("feature"), "http://ex/kind", Some("cls"), 50));
24726        let mut tree = test_join(test_join(values, ferry), cheaper);
24727        reassociate_inner_joins(&mut tree, None, None);
24728        assert!(
24729            values_joined_to(&tree, &ferry_predicate),
24730            "the table must stay directly above the placement-chosen scan: {}",
24731            crate::explain::plan_node_tag(&tree)
24732        );
24733    }
24734
24735    /// A transparent pair's interior is visited through the pair operand. A
24736    /// `UNION` as the pair's right arm keeps the pair intact (the flatten
24737    /// emits it whole), so the arm's own spine is reachable only by the
24738    /// operand descent from `reassociate_spine_operand`'s pair arm. The arm
24739    /// is built with a cartesian inner pair that the pool's seed cannot
24740    /// reproduce, so a missed descent leaves the construction order behind.
24741    #[test]
24742    fn a_transparent_pairs_union_arm_is_reassociated() {
24743        fn directly_joins(node: &PlanNode, first: &EncodedTerm, second: &EncodedTerm) -> bool {
24744            let is = |candidate: &PlanNode, predicate: &EncodedTerm| {
24745                matches!(candidate, PlanNode::Scan(scan)
24746                    if scan.pattern.predicate.as_ref() == Some(predicate))
24747            };
24748            match node {
24749                PlanNode::Join { left, right, .. } => {
24750                    (is(left, first) && is(right, second))
24751                        || (is(left, second) && is(right, first))
24752                        || directly_joins(left, first, second)
24753                        || directly_joins(right, first, second)
24754                }
24755                _ => false,
24756            }
24757        }
24758        let type_predicate = EncodedTerm::from(&NamedNode::new("http://ex/type").unwrap());
24759        let tag_predicate = EncodedTerm::from(&NamedNode::new("http://ex/tag").unwrap());
24760        let values = values_node("cls", &["http://ex/FerryRoute"]);
24761        // Built as `Join(Join(type, tag), name)`: the inner pair shares no
24762        // variable. The 3-row `tag` scan is the pool's seed, so a visited arm
24763        // pairs `tag` with `name` (5 x 3 = 15 rows) instead of with `type`
24764        // (900 x 3 = 2,700 rows), and the direct `type` x `tag` join is gone.
24765        let typed = PlanNode::Scan(var_scan(
24766            Some("feature"),
24767            "http://ex/type",
24768            Some("cls"),
24769            900,
24770        ));
24771        let tagged = PlanNode::Scan(var_scan(Some("ds"), "http://ex/tag", Some("dt"), 3));
24772        let named = PlanNode::Scan(var_scan(Some("feature"), "http://ex/name", Some("name"), 5));
24773        let arm = test_join(test_join(typed, tagged), named);
24774        let alias = PlanNode::Scan(var_scan(
24775            Some("feature"),
24776            "http://ex/alias",
24777            Some("cls"),
24778            100,
24779        ));
24780        let union = PlanNode::Union {
24781            left: Box::new(arm),
24782            right: Box::new(alias),
24783        };
24784        let mut tree = test_join(values, union);
24785        reassociate_inner_joins(&mut tree, None, None);
24786        let PlanNode::Join { left, right, .. } = &tree else {
24787            panic!("expected the transparent pair, got {tree:?}");
24788        };
24789        assert!(
24790            matches!(**left, PlanNode::Values(_)),
24791            "the table must stay the pair's left arm: {tree:?}"
24792        );
24793        let PlanNode::Union { left: arm, .. } = right.as_ref() else {
24794            panic!("expected the pair's UNION arm, got {right:?}");
24795        };
24796        assert!(
24797            !directly_joins(arm, &type_predicate, &tag_predicate),
24798            "the UNION arm must be reassociated out of its construction order: {}",
24799            crate::explain::plan_node_tag(arm)
24800        );
24801    }
24802
24803    /// A table with no shared key is a cartesian, not a broadcast pair: the
24804    /// lowering's raw leaf sort can pair it with the wrong scan, so the association pass
24805    /// must be free to re-decide. A keyed table-scan pair stays together.
24806    #[test]
24807    fn only_a_keyed_values_scan_pair_is_transparent() {
24808        let values = values_node("cls", &["http://ex/FerryRoute"]);
24809        let keyed = PlanNode::Scan(var_scan(
24810            Some("feature"),
24811            "http://ex/type",
24812            Some("cls"),
24813            900,
24814        ));
24815        let cartesian = PlanNode::Scan(var_scan(Some("feature"), "http://ex/feature", None, 9_000));
24816        assert!(is_transparent_pair(&values, &keyed));
24817        assert!(!is_transparent_pair(&values, &cartesian));
24818    }
24819
24820    /// Two tables placed at the same site nest as `Join(V2, Join(V1, X))`.
24821    /// The inner pair stays whole; the outer table is a bare operand the association pass
24822    /// may seat on its own.
24823    #[test]
24824    fn a_nested_values_pair_is_split() {
24825        let outer_values = values_node("other", &["http://ex/other"]);
24826        let inner_values = values_node("cls", &["http://ex/FerryRoute"]);
24827        let scan = PlanNode::Scan(var_scan(
24828            Some("feature"),
24829            "http://ex/type",
24830            Some("cls"),
24831            900,
24832        ));
24833        let inner = test_join(inner_values, scan);
24834        let outer = test_join(outer_values, inner);
24835        let mut operands = Vec::new();
24836        flatten_join_spine(outer, &mut operands);
24837        assert_eq!(
24838            operands.len(),
24839            2,
24840            "expected a bare table and the inner pair"
24841        );
24842        assert!(matches!(operands[0], JoinableSpineNode::Bare(_)));
24843        assert!(matches!(operands[1], JoinableSpineNode::TransparentJoin(_)));
24844    }
24845
24846    #[test]
24847    fn ground_bind_prefixes_broadcast_scan_object() {
24848        let brisbane = NamedNode::new("http://ex/brisbane").unwrap();
24849        let plan = LogicalPlan::parse(
24850            r#"
24851            SELECT ?person WHERE {
24852              BIND(<http://ex/brisbane> AS ?city)
24853              ?person <http://ex/livesIn> ?city .
24854            }
24855            "#,
24856        )
24857        .unwrap();
24858        let mut scans = Vec::new();
24859        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
24860        assert_eq!(scans.len(), 1);
24861        assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("city"));
24862        assert_eq!(scans[0].pattern.object, Some(EncodedTerm::from(&brisbane)));
24863    }
24864
24865    #[test]
24866    fn singleton_values_prefixes_broadcast_path_end() {
24867        let brisbane = NamedNode::new("http://ex/brisbane").unwrap();
24868        let plan = LogicalPlan::parse(
24869            r#"
24870            SELECT ?person WHERE {
24871              VALUES ?city { <http://ex/brisbane> }
24872              ?person <http://ex/livesIn>* ?city .
24873            }
24874            "#,
24875        )
24876        .unwrap();
24877        let mut paths = Vec::new();
24878        for_each_path(&plan.root, &mut |path| paths.push(path));
24879        assert_eq!(paths.len(), 1, "expected a Path probe, got {:?}", plan.root);
24880        assert_eq!(paths[0].object.as_ref().map(Variable::as_str), Some("city"));
24881        assert_eq!(paths[0].object_term, Some(EncodedTerm::from(&brisbane)));
24882    }
24883
24884    #[test]
24885    fn bind_of_in_scope_variable_is_rejected() {
24886        // spargebra rejects `BIND` to an in-scope var at parse time. Defend the
24887        // same rule in `lower_pattern` for algebra that arrives another way
24888        // (tests, future rewrites).
24889        let s = var("s");
24890        let o = var("o");
24891        let inner = GraphPattern::Bgp {
24892            patterns: vec![TriplePattern {
24893                subject: TermPattern::Variable(s.clone()),
24894                predicate: NamedNodePattern::NamedNode(NamedNode::new("http://ex/p").unwrap()),
24895                object: TermPattern::Variable(o),
24896            }],
24897        };
24898        let pattern = GraphPattern::Extend {
24899            inner: Box::new(inner),
24900            variable: s,
24901            expression: Expression::Literal(Literal::new_simple_literal("x")),
24902        };
24903        let error = lower_pattern(
24904            &pattern,
24905            None,
24906            &IncomingBound::default(),
24907            &QueryContext::from_snapshot(SnapshotId::latest()),
24908            &GraphScope::Default,
24909        )
24910        .unwrap_err();
24911        let message = error.to_string();
24912        assert!(message.contains("already in-scope"), "{message}");
24913        assert!(matches!(error, ComputeError::UnsupportedSparql(_)));
24914    }
24915
24916    #[test]
24917    fn select_expr_as_is_extend() {
24918        let plan =
24919            LogicalPlan::parse(r#"SELECT (?o AS ?c) WHERE { ?s <http://ex/livesIn> ?o }"#).unwrap();
24920        assert!(
24921            matches!(plan.root, PlanNode::Extend { .. }),
24922            "got {:?}",
24923            plan.root
24924        );
24925        assert_eq!(plan.projection, vec![var("c")]);
24926    }
24927
24928    #[test]
24929    fn projected_unbound_variable_is_allowed() {
24930        let plan = LogicalPlan::parse(r#"SELECT ?missing WHERE { ?s ?p ?o }"#).unwrap();
24931        assert_eq!(plan.projection, vec![var("missing")]);
24932    }
24933
24934    #[test]
24935    fn explain_sparql_keeps_values_in_a_join_tree() {
24936        let text = explain_optimised_sparql(
24937            r#"
24938            SELECT ?person WHERE {
24939              ?person <http://ex/livesIn> ?city .
24940              VALUES ?city { <http://ex/brisbane> }
24941            }
24942            "#,
24943        );
24944        assert!(
24945            text.contains("VALUES"),
24946            "VALUES must not be dropped: {text}"
24947        );
24948        assert!(text.contains("livesIn"), "{text}");
24949    }
24950
24951    #[test]
24952    fn values_is_copied_into_both_union_arms() {
24953        let text = explain_optimised_sparql(
24954            r#"
24955            SELECT ?s WHERE {
24956              VALUES ?city { <http://ex/brisbane> }
24957              { ?s <http://ex/livesIn> ?city }
24958              UNION
24959              { ?s <http://ex/hasWeather> ?city }
24960            }
24961            "#,
24962        );
24963        let count = text.matches("VALUES").count();
24964        assert!(
24965            count >= 2,
24966            "expected VALUES inside both UNION arms, got {count} in {text}"
24967        );
24968        let plan = LogicalPlan::parse(
24969            r#"
24970            SELECT ?s WHERE {
24971              VALUES ?city { <http://ex/brisbane> }
24972              { ?s <http://ex/livesIn> ?city }
24973              UNION
24974              { ?s <http://ex/hasWeather> ?city }
24975            }
24976            "#,
24977        )
24978        .unwrap();
24979        assert!(
24980            matches!(plan.root, PlanNode::Union { .. }),
24981            "root should be Union after VALUES push, got {:?}",
24982            plan.root
24983        );
24984    }
24985
24986    #[test]
24987    fn bind_is_copied_into_both_union_arms() {
24988        let sparql = r#"
24989            SELECT ?s WHERE {
24990              BIND(<http://ex/brisbane> AS ?b)
24991              { { ?s <http://ex/livesIn> ?b } UNION { ?b <http://ex/hasWeather> ?w } }
24992            }
24993        "#;
24994        let plan = LogicalPlan::parse(sparql).unwrap();
24995        assert!(
24996            matches!(plan.root, PlanNode::Union { .. }),
24997            "root should be Union after BIND→VALUES push, got {:?}",
24998            plan.root
24999        );
25000        assert_eq!(
25001            count_values_nodes(&plan.root),
25002            2,
25003            "expected VALUES in both UNION arms: {:?}",
25004            plan.root
25005        );
25006        let text = explain_optimised_sparql(sparql);
25007        assert!(
25008            text.matches("VALUES").count() >= 2,
25009            "EXPLAIN should show VALUES in both arms: {text}"
25010        );
25011    }
25012
25013    #[test]
25014    fn nested_union_three_arms_copies_values() {
25015        let plan = LogicalPlan::parse(
25016            r#"
25017            SELECT ?s WHERE {
25018              VALUES ?city { <http://ex/brisbane> }
25019              { ?s <http://ex/livesIn> ?city }
25020              UNION
25021              { ?s <http://ex/hasWeather> ?city }
25022              UNION
25023              { ?city <http://ex/hasWeather> ?s }
25024            }
25025            "#,
25026        )
25027        .unwrap();
25028        assert_eq!(
25029            count_values_nodes(&plan.root),
25030            3,
25031            "VALUES should reach all three UNION arms, got {:?}",
25032            plan.root
25033        );
25034    }
25035
25036    #[test]
25037    fn nested_union_three_arms_copies_bind() {
25038        let plan = LogicalPlan::parse(
25039            r#"
25040            SELECT ?s WHERE {
25041              BIND(<http://ex/brisbane> AS ?city)
25042              { ?s <http://ex/livesIn> ?city }
25043              UNION
25044              { ?s <http://ex/hasWeather> ?city }
25045              UNION
25046              { ?city <http://ex/hasWeather> ?s }
25047            }
25048            "#,
25049        )
25050        .unwrap();
25051        assert_eq!(
25052            count_values_nodes(&plan.root),
25053            3,
25054            "BIND→VALUES should reach all three UNION arms, got {:?}",
25055            plan.root
25056        );
25057    }
25058
25059    #[test]
25060    fn explain_optional_union_broadcasts_both_scans() {
25061        let sparql = r#"
25062            SELECT * WHERE {
25063              BIND(<http://ex/brisbane> AS ?b)
25064              OPTIONAL {
25065                { ?s <http://ex/livesIn> ?b }
25066                UNION
25067                { ?s <http://ex/hasWeather> ?b }
25068              }
25069            }
25070        "#;
25071        let plan = LogicalPlan::parse(sparql).unwrap();
25072        let PlanNode::LeftJoin { right, .. } = &plan.root else {
25073            panic!("expected LeftJoin at root, got {:?}", plan.root);
25074        };
25075        let mut grounded = Vec::new();
25076        for_each_scan(right, &mut |scan| {
25077            if !scan.grounded.is_empty() {
25078                grounded.push(scan);
25079            }
25080        });
25081        assert_eq!(
25082            grounded.len(),
25083            2,
25084            "both UNION optional scans should be grounded, got {right:?}"
25085        );
25086        for scan in &grounded {
25087            assert!(
25088                scan.broadcasted.is_none(),
25089                "unique BIND should not stamp broadcast, got {:?}",
25090                scan.broadcasted
25091            );
25092            assert_eq!(
25093                grounded_of(scan),
25094                vec![("b", PatternSlot::Object)],
25095                "expected grounded object on ?b, got {:?}",
25096                scan.grounded
25097            );
25098            assert!(
25099                scan.produced_row_count_estimate < 1_000_000,
25100                "bound optional scan must not use unbound ~3e6: {}",
25101                scan.produced_row_count_estimate
25102            );
25103        }
25104        let text = explain_est(sparql, None);
25105        assert!(
25106            text.matches("(grounded ?b object)").count() >= 2,
25107            "EXPLAIN should annotate both UNION scans: {text}"
25108        );
25109    }
25110
25111    #[test]
25112    fn explain_optional_join_broadcasts_the_key_scan() {
25113        let sparql = r#"
25114            SELECT * WHERE {
25115              BIND("Sunny" AS ?b)
25116              OPTIONAL {
25117                ?s1 <http://ex/livesIn> ?s2 .
25118                ?s2 <http://ex/hasWeather> ?b
25119              }
25120            }
25121        "#;
25122        let plan = LogicalPlan::parse(sparql).unwrap();
25123        let PlanNode::LeftJoin { right, .. } = &plan.root else {
25124            panic!("expected LeftJoin at root, got {:?}", plan.root);
25125        };
25126        let mut key_scans = Vec::new();
25127        for_each_scan(right, &mut |scan| {
25128            if scan.object.as_ref().is_some_and(|v| v.as_str() == "b") {
25129                key_scans.push(scan);
25130            }
25131        });
25132        assert_eq!(key_scans.len(), 1, "one scan should bind ?b: {right:?}");
25133        assert!(
25134            key_scans[0].broadcasted.is_none(),
25135            "unique BIND should not stamp broadcast, got {:?}",
25136            key_scans[0].broadcasted
25137        );
25138        assert_eq!(
25139            grounded_of(key_scans[0]),
25140            vec![("b", PatternSlot::Object)],
25141            "the ?b scan should be grounded, got {:?}",
25142            key_scans[0].grounded
25143        );
25144    }
25145
25146    #[test]
25147    fn explain_nested_optional_broadcasts_outer_key() {
25148        let sparql = r#"
25149            SELECT * WHERE {
25150              BIND(<http://ex/brisbane> AS ?b)
25151              OPTIONAL {
25152                ?s ?p ?b .
25153                OPTIONAL { ?s <http://ex/hasWeather> ?n }
25154              }
25155            }
25156        "#;
25157        let plan = LogicalPlan::parse(sparql).unwrap();
25158        let PlanNode::LeftJoin { right, .. } = &plan.root else {
25159            panic!("expected LeftJoin at root, got {:?}", plan.root);
25160        };
25161        let mut found = false;
25162        for_each_scan(right, &mut |scan| {
25163            if scan.object.as_ref().is_some_and(|v| v.as_str() == "b") {
25164                found = scan.broadcasted.is_none()
25165                    && grounded_of(scan) == vec![("b", PatternSlot::Object)];
25166            }
25167        });
25168        assert!(
25169            found,
25170            "outer ?b should reach the nested required scan: {right:?}"
25171        );
25172    }
25173
25174    fn optional_right_join(node: &PlanNode) -> &PlanNode {
25175        let PlanNode::LeftJoin { right, .. } = node else {
25176            panic!("expected LeftJoin, got {node:?}");
25177        };
25178        right
25179    }
25180
25181    #[test]
25182    fn optional_fk_pattern_ordered_before_type_with_profile() {
25183        // Oxigraph #1883 / #1733 shape: OPTIONAL { ?server a :Server ; :locatedIn ?rack }
25184        // with ?rack bound on the left. 100 racks × fan-out 10 → scaled
25185        // min(1000, 1000) ties :Server 1000; incoming-slot tie-break still
25186        // puts :locatedIn first.
25187        let mut live = LiveQuadsProfile::default();
25188        let rack_class = NamedNode::new("http://ex/Rack").unwrap();
25189        let server_class = NamedNode::new("http://ex/Server").unwrap();
25190        let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
25191        let located_in = NamedNode::new("http://ex/locatedIn").unwrap();
25192
25193        for i in 0..100 {
25194            let rack = NamedNode::new(format!("http://ex/rack{i}")).unwrap();
25195            observe_quad(
25196                &mut live,
25197                &encode_quad(&waratah_storage::Quad::new(
25198                    rack,
25199                    type_pred.clone(),
25200                    rack_class.clone(),
25201                    waratah_storage::GraphName::DefaultGraph,
25202                ))
25203                .unwrap(),
25204                StorageOp::Put,
25205            );
25206        }
25207        for i in 0..1000 {
25208            let server = NamedNode::new(format!("http://ex/server{i}")).unwrap();
25209            let rack = NamedNode::new(format!("http://ex/rack{}", i % 100)).unwrap();
25210            observe_quad(
25211                &mut live,
25212                &encode_quad(&waratah_storage::Quad::new(
25213                    server.clone(),
25214                    type_pred.clone(),
25215                    server_class.clone(),
25216                    waratah_storage::GraphName::DefaultGraph,
25217                ))
25218                .unwrap(),
25219                StorageOp::Put,
25220            );
25221            observe_quad(
25222                &mut live,
25223                &encode_quad(&waratah_storage::Quad::new(
25224                    server,
25225                    located_in.clone(),
25226                    rack,
25227                    waratah_storage::GraphName::DefaultGraph,
25228                ))
25229                .unwrap(),
25230                StorageOp::Put,
25231            );
25232        }
25233        let profile = StatsProfile::from(live);
25234
25235        let plan = LogicalPlan::parse_with_profile(
25236            r#"
25237            SELECT ?rack ?server WHERE {
25238              ?rack a <http://ex/Rack> .
25239              OPTIONAL {
25240                ?server a <http://ex/Server> .
25241                ?server <http://ex/locatedIn> ?rack .
25242              }
25243            }
25244            "#,
25245            Some(&profile),
25246        )
25247        .unwrap();
25248        let PlanNode::Join { left, right, .. } = optional_right_join(&plan.root) else {
25249            panic!(
25250                "expected Join on OPTIONAL right, got {:?}",
25251                optional_right_join(&plan.root)
25252            );
25253        };
25254        let driver = left.as_scan().expect("inner join left should be a scan");
25255        assert_eq!(
25256            driver.object.as_ref().map(Variable::as_str),
25257            Some("rack"),
25258            "FK :locatedIn ?rack should drive, got {left:?}"
25259        );
25260        let probe = right.as_scan().expect("inner join right should be a scan");
25261        assert!(
25262            probe.pattern.object.is_some() && probe.object.is_none(),
25263            "type scan should be the probe, got {right:?}"
25264        );
25265    }
25266
25267    #[test]
25268    fn optional_large_incoming_domain_lets_small_type_scan_drive() {
25269        // Many distinct racks, small :Server class, :locatedIn ≈ |racks| so
25270        // scaled FK ≫ type and the type scan must drive the inner join.
25271        let mut live = LiveQuadsProfile::default();
25272        let rack_class = NamedNode::new("http://ex/Rack").unwrap();
25273        let server_class = NamedNode::new("http://ex/Server").unwrap();
25274        let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
25275        let located_in = NamedNode::new("http://ex/locatedIn").unwrap();
25276
25277        for i in 0..2000 {
25278            let rack = NamedNode::new(format!("http://ex/rack{i}")).unwrap();
25279            observe_quad(
25280                &mut live,
25281                &encode_quad(&waratah_storage::Quad::new(
25282                    rack.clone(),
25283                    type_pred.clone(),
25284                    rack_class.clone(),
25285                    waratah_storage::GraphName::DefaultGraph,
25286                ))
25287                .unwrap(),
25288                StorageOp::Put,
25289            );
25290            let server = NamedNode::new(format!("http://ex/host{i}")).unwrap();
25291            observe_quad(
25292                &mut live,
25293                &encode_quad(&waratah_storage::Quad::new(
25294                    server,
25295                    located_in.clone(),
25296                    rack,
25297                    waratah_storage::GraphName::DefaultGraph,
25298                ))
25299                .unwrap(),
25300                StorageOp::Put,
25301            );
25302        }
25303        for i in 0..100 {
25304            let server = NamedNode::new(format!("http://ex/server{i}")).unwrap();
25305            observe_quad(
25306                &mut live,
25307                &encode_quad(&waratah_storage::Quad::new(
25308                    server,
25309                    type_pred.clone(),
25310                    server_class.clone(),
25311                    waratah_storage::GraphName::DefaultGraph,
25312                ))
25313                .unwrap(),
25314                StorageOp::Put,
25315            );
25316        }
25317        let profile = StatsProfile::from(live);
25318
25319        let plan = LogicalPlan::parse_with_profile(
25320            r#"
25321            SELECT ?rack ?server WHERE {
25322              ?rack a <http://ex/Rack> .
25323              OPTIONAL {
25324                ?server a <http://ex/Server> .
25325                ?server <http://ex/locatedIn> ?rack .
25326              }
25327            }
25328            "#,
25329            Some(&profile),
25330        )
25331        .unwrap();
25332        let PlanNode::Join { left, right, .. } = optional_right_join(&plan.root) else {
25333            panic!(
25334                "expected Join on OPTIONAL right, got {:?}",
25335                optional_right_join(&plan.root)
25336            );
25337        };
25338        let driver = left.as_scan().expect("inner join left should be a scan");
25339        assert!(
25340            driver.pattern.object.is_some() && driver.object.is_none(),
25341            "small :Server type scan should drive, got {left:?}"
25342        );
25343        let probe = right.as_scan().expect("inner join right should be a scan");
25344        assert_eq!(
25345            probe.object.as_ref().map(Variable::as_str),
25346            Some("rack"),
25347            "scaled :locatedIn should be the probe, got {right:?}"
25348        );
25349    }
25350
25351    #[test]
25352    fn incoming_domain_scales_scan_and_unbound_over_allow_list_cap() {
25353        // per-key ~100, |P| 2e6. Domain 20_000 → min(|P|, 100×20k) not leftover
25354        // per-key 100. Domain 20_001 → unbound |P| (over allow-list cap).
25355        let mut profile = StatsProfile::default();
25356        let located_in = NamedNode::new("http://ex/locatedIn").unwrap();
25357        let pred = waratah_storage::StrHash::new("http://ex/locatedIn");
25358        profile.total_puts = 2_000_000;
25359        profile.predicate_counts.insert(pred, 2_000_000);
25360        let mut objects = waratah_stats::HyperLogLog::default_params();
25361        for i in 0..20_000u128 {
25362            objects.add(i);
25363        }
25364        profile.objects_per_predicate.insert(pred, objects);
25365
25366        let pattern = TriplePattern {
25367            subject: TermPattern::Variable(var("server")),
25368            predicate: NamedNodePattern::NamedNode(located_in),
25369            object: TermPattern::Variable(var("rack")),
25370        };
25371
25372        let mut per_key_incoming = IncomingBound::default();
25373        per_key_incoming.insert(var("rack"), None);
25374        let per_key_scan = plan_scan_op(
25375            &pattern,
25376            Some(&profile),
25377            &per_key_incoming,
25378            &QueryContext::from_snapshot(SnapshotId::latest()),
25379            &GraphScope::Default,
25380        )
25381        .unwrap();
25382        // `plan_scan_op` is where a real plan gets its stamps; pin the
25383        // classifier wiring here so a direct `JoinDomainStamps::classify`
25384        // unit test cannot mask a missing call on the construction path.
25385        assert_eq!(
25386            per_key_scan.join_domains.get(JoinKeySlot::Object),
25387            JoinDomainStamp::Known(profile.object_domain(&pred).unwrap()),
25388            "bound predicate + object HLL must stamp the object slot"
25389        );
25390        assert_eq!(
25391            per_key_scan.join_domains.get(JoinKeySlot::Subject),
25392            JoinDomainStamp::Unavailable,
25393            "no subject HLL for :locatedIn -> live fallback"
25394        );
25395        let per_key = per_key_scan.produced_row_count_estimate;
25396        assert!(
25397            (50..=200).contains(&per_key),
25398            "expected ~100 fan-out, got {per_key}"
25399        );
25400
25401        let mut at_cap = IncomingBound::default();
25402        at_cap.insert(var("rack"), Some(PUSHDOWN_TERMS_LIMIT));
25403        let at_cap_rows = plan_scan_op(
25404            &pattern,
25405            Some(&profile),
25406            &at_cap,
25407            &QueryContext::from_snapshot(SnapshotId::latest()),
25408            &GraphScope::Default,
25409        )
25410        .unwrap()
25411        .produced_row_count_estimate;
25412        let expected_scaled = 2_000_000.min(per_key.saturating_mul(PUSHDOWN_TERMS_LIMIT));
25413        assert_eq!(
25414            at_cap_rows, expected_scaled,
25415            "domain 20k should scale per-key, not leave {per_key}"
25416        );
25417        assert!(
25418            at_cap_rows > per_key,
25419            "scaled estimate must exceed per-key fan-out: {at_cap_rows} vs {per_key}"
25420        );
25421
25422        let mut over_cap = IncomingBound::default();
25423        over_cap.insert(var("rack"), Some(PUSHDOWN_TERMS_LIMIT + 1));
25424        let over_cap_rows = plan_scan_op(
25425            &pattern,
25426            Some(&profile),
25427            &over_cap,
25428            &QueryContext::from_snapshot(SnapshotId::latest()),
25429            &GraphScope::Default,
25430        )
25431        .unwrap()
25432        .produced_row_count_estimate;
25433        assert_eq!(
25434            over_cap_rows, 2_000_000,
25435            "domain 20_001 should cost unbound |P|, got {over_cap_rows}"
25436        );
25437    }
25438
25439    #[test]
25440    fn incoming_bound_predicate_uses_mean_count_and_scales_by_domain() {
25441        // 10 predicates, 100k puts → mean |P| = 10k. Domain 3 → 30k.
25442        // Over allow-list cap → unbound total_puts.
25443        let mut profile = StatsProfile {
25444            total_puts: 100_000,
25445            ..StatsProfile::default()
25446        };
25447        for i in 0..10 {
25448            profile.predicate_counts.insert(
25449                waratah_storage::StrHash::new(&format!("http://ex/p{i}")),
25450                10_000,
25451            );
25452        }
25453
25454        let pattern = TriplePattern {
25455            subject: TermPattern::Variable(var("s")),
25456            predicate: NamedNodePattern::Variable(var("p")),
25457            object: TermPattern::Variable(var("o")),
25458        };
25459
25460        let mut per_key_incoming = IncomingBound::default();
25461        per_key_incoming.insert(var("p"), None);
25462        let per_key = plan_scan_op(
25463            &pattern,
25464            Some(&profile),
25465            &per_key_incoming,
25466            &QueryContext::from_snapshot(SnapshotId::latest()),
25467            &GraphScope::Default,
25468        )
25469        .unwrap()
25470        .produced_row_count_estimate;
25471        assert_eq!(per_key, 10_000, "unknown domain keeps mean |P|");
25472
25473        let mut scaled_incoming = IncomingBound::default();
25474        scaled_incoming.insert(var("p"), Some(3));
25475        let scaled = plan_scan_op(
25476            &pattern,
25477            Some(&profile),
25478            &scaled_incoming,
25479            &QueryContext::from_snapshot(SnapshotId::latest()),
25480            &GraphScope::Default,
25481        )
25482        .unwrap()
25483        .produced_row_count_estimate;
25484        assert_eq!(scaled, 30_000, "domain 3 should scale mean |P|");
25485
25486        let mut over_cap = IncomingBound::default();
25487        over_cap.insert(var("p"), Some(PUSHDOWN_TERMS_LIMIT + 1));
25488        let over_cap_rows = plan_scan_op(
25489            &pattern,
25490            Some(&profile),
25491            &over_cap,
25492            &QueryContext::from_snapshot(SnapshotId::latest()),
25493            &GraphScope::Default,
25494        )
25495        .unwrap()
25496        .produced_row_count_estimate;
25497        assert_eq!(
25498            over_cap_rows, 100_000,
25499            "over allow-list cap should cost unbound total_puts"
25500        );
25501    }
25502
25503    #[test]
25504    fn optional_fk_pattern_ordered_before_type_without_profile() {
25505        // No sketches: type and incoming-bound :locatedIn both have 2 bound
25506        // slots and the 1e6 fallback. Incoming-slot count must break the tie.
25507        let plan = LogicalPlan::parse(
25508            r#"
25509            SELECT ?rack ?server WHERE {
25510              ?rack a <http://ex/Rack> .
25511              OPTIONAL {
25512                ?server a <http://ex/Server> .
25513                ?server <http://ex/locatedIn> ?rack .
25514              }
25515            }
25516            "#,
25517        )
25518        .unwrap();
25519        let PlanNode::Join { left, .. } = optional_right_join(&plan.root) else {
25520            panic!(
25521                "expected Join on OPTIONAL right, got {:?}",
25522                optional_right_join(&plan.root)
25523            );
25524        };
25525        let driver = left.as_scan().expect("inner join left should be a scan");
25526        assert_eq!(
25527            driver.object.as_ref().map(Variable::as_str),
25528            Some("rack"),
25529            "incoming-slot tie-break should put :locatedIn first, got {left:?}"
25530        );
25531    }
25532
25533    #[test]
25534    fn nested_optional_left_bgp_sees_outer_key() {
25535        let plan = LogicalPlan::parse(
25536            r#"
25537            SELECT * WHERE {
25538              ?x a <http://ex/X> .
25539              OPTIONAL {
25540                ?y a <http://ex/Y> .
25541                ?y <http://ex/locatedIn> ?x .
25542                OPTIONAL { ?z <http://ex/p> ?y }
25543              }
25544            }
25545            "#,
25546        )
25547        .unwrap();
25548        let nested = optional_right_join(&plan.root);
25549        let PlanNode::LeftJoin { left, .. } = nested else {
25550            panic!("expected nested LeftJoin, got {nested:?}");
25551        };
25552        let PlanNode::Join {
25553            left: driver_node, ..
25554        } = left.as_ref()
25555        else {
25556            panic!("expected Join on nested OPTIONAL left, got {left:?}");
25557        };
25558        let driver = driver_node
25559            .as_scan()
25560            .expect("nested left BGP driver should be a scan");
25561        assert_eq!(
25562            driver.object.as_ref().map(Variable::as_str),
25563            Some("x"),
25564            "outer ?x should order :locatedIn first on the nested left BGP, got {left:?}"
25565        );
25566    }
25567
25568    #[test]
25569    fn optional_maybe_unbound_does_not_leak_into_later_optional() {
25570        // ?y is maybe-unbound after the first OPTIONAL; the second OPTIONAL
25571        // right must not cost ?y as incoming-bound.
25572        let plan = LogicalPlan::parse(
25573            r#"
25574            SELECT * WHERE {
25575              ?s <http://ex/p> ?x .
25576              OPTIONAL { ?x <http://ex/q> ?y }
25577              OPTIONAL { ?y <http://ex/r> ?z }
25578            }
25579            "#,
25580        )
25581        .unwrap();
25582        let scan = optional_right_join(&plan.root)
25583            .as_scan()
25584            .expect("second OPTIONAL right should be a scan");
25585        assert_eq!(
25586            scan.produced_row_count_estimate, 2_000_000,
25587            "P-only fallback; incoming ?y would drop this to 1e6: {scan:?}"
25588        );
25589        assert!(
25590            scan.broadcasted.is_none(),
25591            "no join key with the required side, got {:?}",
25592            scan.broadcasted
25593        );
25594    }
25595
25596    fn count_values_nodes(node: &PlanNode) -> usize {
25597        match node {
25598            PlanNode::Values(_) => 1,
25599            PlanNode::Join { left, right, .. }
25600            | PlanNode::Union { left, right }
25601            | PlanNode::LeftJoin { left, right, .. } => {
25602                count_values_nodes(left) + count_values_nodes(right)
25603            }
25604            PlanNode::Filter { inner, .. }
25605            | PlanNode::Extend { inner, .. }
25606            | PlanNode::Slice { inner, .. }
25607            | PlanNode::Distinct { inner, .. }
25608            | PlanNode::Sort { inner, .. }
25609            | PlanNode::Group { inner, .. } => count_values_nodes(inner),
25610            _ => 0,
25611        }
25612    }
25613
25614    fn for_each_scan<'a>(node: &'a PlanNode, f: &mut impl FnMut(&'a ScanOp)) {
25615        match node {
25616            PlanNode::Scan(scan) => f(scan),
25617            PlanNode::Join { left, right, .. }
25618            | PlanNode::Union { left, right }
25619            | PlanNode::LeftJoin { left, right, .. } => {
25620                for_each_scan(left, f);
25621                for_each_scan(right, f);
25622            }
25623            PlanNode::Filter { inner, .. }
25624            | PlanNode::Extend { inner, .. }
25625            | PlanNode::Slice { inner, .. }
25626            | PlanNode::Distinct { inner, .. }
25627            | PlanNode::Sort { inner, .. }
25628            | PlanNode::Group { inner, .. } => for_each_scan(inner, f),
25629            _ => {}
25630        }
25631    }
25632
25633    fn grounded_of(scan: &ScanOp) -> Vec<(&str, PatternSlot)> {
25634        scan.grounded
25635            .iter()
25636            .map(|(variable, slot)| (variable.as_str(), *slot))
25637            .collect()
25638    }
25639
25640    fn find_inner_join(node: &PlanNode) -> &PlanNode {
25641        match node {
25642            PlanNode::Join { .. } => node,
25643            PlanNode::Extend { inner, .. }
25644            | PlanNode::Filter { inner, .. }
25645            | PlanNode::Slice { inner, .. }
25646            | PlanNode::Distinct { inner, .. }
25647            | PlanNode::Sort { inner, .. }
25648            | PlanNode::Group { inner, .. } => find_inner_join(inner),
25649            PlanNode::LeftJoin { left, .. } => find_inner_join(left),
25650            other => panic!("expected Join under wrappers, got {other:?}"),
25651        }
25652    }
25653
25654    fn for_each_path<'a>(node: &'a PlanNode, f: &mut impl FnMut(&'a PathOp)) {
25655        match node {
25656            PlanNode::Path(path) => f(path),
25657            PlanNode::Join { left, right, .. }
25658            | PlanNode::Union { left, right }
25659            | PlanNode::LeftJoin { left, right, .. } => {
25660                for_each_path(left, f);
25661                for_each_path(right, f);
25662            }
25663            PlanNode::Filter { inner, .. }
25664            | PlanNode::Extend { inner, .. }
25665            | PlanNode::Slice { inner, .. }
25666            | PlanNode::Distinct { inner, .. }
25667            | PlanNode::Sort { inner, .. }
25668            | PlanNode::Group { inner, .. } => for_each_path(inner, f),
25669            _ => {}
25670        }
25671    }
25672
25673    #[test]
25674    fn empty_values_has_zero_rows() {
25675        let plan = LogicalPlan::parse(r#"SELECT ?x WHERE { VALUES ?x { } }"#).unwrap();
25676        let PlanNode::Values(values) = &plan.root else {
25677            panic!("expected Values, got {:?}", plan.root);
25678        };
25679        assert!(values.rows.is_empty());
25680        assert_eq!(values.produced_row_count_estimate(), 0);
25681    }
25682
25683    #[test]
25684    fn limit_and_offset_lower_to_slice() {
25685        let plan = LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 10 OFFSET 3")
25686            .unwrap();
25687        match &plan.root {
25688            PlanNode::Slice {
25689                start,
25690                length,
25691                inner,
25692            } => {
25693                assert_eq!(*start, 3);
25694                assert_eq!(*length, Some(10));
25695                assert!(matches!(inner.as_ref(), PlanNode::Scan(_)));
25696            }
25697            other => panic!("expected Slice, got {other:?}"),
25698        }
25699    }
25700
25701    #[test]
25702    fn limit_zero_is_empty_slice() {
25703        let plan = LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 0").unwrap();
25704        match &plan.root {
25705            PlanNode::Slice { start, length, .. } => {
25706                assert_eq!(*start, 0);
25707                assert_eq!(*length, Some(0));
25708            }
25709            other => panic!("expected Slice, got {other:?}"),
25710        }
25711    }
25712
25713    #[test]
25714    fn small_limit_rewrites_scan_join_to_broadcast() {
25715        let unlimited = LogicalPlan::parse(
25716            r#"SELECT ?s WHERE {
25717              ?s <http://ex/p> ?o .
25718              ?s <http://ex/q> ?x .
25719            }"#,
25720        )
25721        .unwrap();
25722        assert_ne!(
25723            unlimited.join_ops().unwrap()[0].meta.strategy,
25724            JoinStrategy::Broadcast,
25725            "unbounded join should not force Broadcast without stats"
25726        );
25727
25728        let limited = LogicalPlan::parse(
25729            r#"SELECT ?s WHERE {
25730              ?s <http://ex/p> ?o .
25731              ?s <http://ex/q> ?x .
25732            } LIMIT 1"#,
25733        )
25734        .unwrap();
25735        assert_eq!(
25736            limited.join_ops().unwrap()[0].meta.strategy,
25737            JoinStrategy::Broadcast
25738        );
25739    }
25740
25741    #[test]
25742    fn ask_join_rewrites_scan_join_to_broadcast() {
25743        let query = SparqlParser::new()
25744            .parse_query(
25745                r#"ASK {
25746                  ?s <http://ex/p> ?o .
25747                  ?s <http://ex/q> ?x .
25748                }"#,
25749            )
25750            .unwrap();
25751        let Query::Ask { pattern, .. } = query else {
25752            panic!("expected ASK");
25753        };
25754        let plan = LogicalPlan::from_ask_algebra(pattern, None).unwrap();
25755        match &plan.root {
25756            PlanNode::Slice { start, length, .. } => {
25757                assert_eq!(*start, 0);
25758                assert_eq!(*length, Some(1));
25759            }
25760            other => panic!("expected Slice, got {other:?}"),
25761        }
25762        assert_eq!(
25763            plan.join_ops().unwrap()[0].meta.strategy,
25764            JoinStrategy::Broadcast
25765        );
25766    }
25767
25768    #[test]
25769    fn order_by_lowers_between_project_and_slice() {
25770        let plan =
25771            LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/p> ?o } ORDER BY ?s LIMIT 5")
25772                .expect("ORDER BY must plan");
25773        match &plan.root {
25774            PlanNode::Slice {
25775                start,
25776                length,
25777                inner,
25778            } => {
25779                assert_eq!(*start, 0);
25780                assert_eq!(*length, Some(5));
25781                match inner.as_ref() {
25782                    PlanNode::Sort { keys, inner } => {
25783                        assert_eq!(keys.len(), 1);
25784                        assert!(!keys[0].descending);
25785                        assert!(
25786                            matches!(inner.as_ref(), PlanNode::Scan(_)),
25787                            "expected Scan under Sort, got {inner:?}"
25788                        );
25789                    }
25790                    other => panic!("expected Sort under Slice, got {other:?}"),
25791                }
25792            }
25793            other => panic!("expected Slice, got {other:?}"),
25794        }
25795    }
25796
25797    #[test]
25798    fn distinct_lowers_onto_the_select_projection() {
25799        let plan = LogicalPlan::parse("SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o }").unwrap();
25800        match &plan.root {
25801            PlanNode::Distinct { columns, inner } => {
25802                assert_eq!(columns, &vec![var("s")]);
25803                assert!(
25804                    matches!(inner.as_ref(), PlanNode::Scan(_)),
25805                    "expected Scan under Distinct, got {inner:?}"
25806                );
25807            }
25808            other => panic!("expected Distinct, got {other:?}"),
25809        }
25810        assert_eq!(plan.projection, vec![var("s")]);
25811    }
25812
25813    #[test]
25814    fn distinct_then_limit_is_slice_over_distinct() {
25815        let plan =
25816            LogicalPlan::parse("SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 5").unwrap();
25817        match &plan.root {
25818            PlanNode::Slice {
25819                start,
25820                length,
25821                inner,
25822            } => {
25823                assert_eq!(*start, 0);
25824                assert_eq!(*length, Some(5));
25825                match inner.as_ref() {
25826                    PlanNode::Distinct { columns, .. } => {
25827                        assert_eq!(columns, &vec![var("s")]);
25828                    }
25829                    other => panic!("expected Distinct under Slice, got {other:?}"),
25830                }
25831            }
25832            other => panic!("expected Slice, got {other:?}"),
25833        }
25834    }
25835
25836    #[test]
25837    fn reduced_is_a_spec_legal_no_op() {
25838        // SPARQL 1.1 §18.2.4.1: REDUCED may but need not remove duplicates.
25839        // Waratah plans it as the un-deduped multiset.
25840        let reduced = LogicalPlan::parse("SELECT REDUCED ?s WHERE { ?s <http://ex/p> ?o }")
25841            .expect("REDUCED must plan");
25842        let plain = LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/p> ?o }")
25843            .expect("plain SELECT must plan");
25844        // Identical projection and plan tree: peel did not set Distinct, and
25845        // no Distinct node wraps the scans (would dedup — not required, but
25846        // also not what this plan lowers to).
25847        assert_eq!(reduced.projection, plain.projection);
25848        assert!(!plan_contains_distinct(&reduced.root));
25849        assert_eq!(format!("{:?}", reduced.root), format!("{:?}", plain.root));
25850    }
25851
25852    /// Whether any `PlanNode::Distinct` sits in the tree.
25853    fn plan_contains_distinct(node: &PlanNode) -> bool {
25854        match node {
25855            PlanNode::Distinct { .. } => true,
25856            PlanNode::Scan(_)
25857            | PlanNode::Path(_)
25858            | PlanNode::Values(_)
25859            | PlanNode::Unit
25860            | PlanNode::NamedGraphs { .. }
25861            | PlanNode::NamedGraphExists { .. }
25862            | PlanNode::DomainCounts { .. }
25863            | PlanNode::HeadCounts { .. }
25864            | PlanNode::PatternCount { .. } => false,
25865            PlanNode::Join { left, right, .. }
25866            | PlanNode::LeftJoin { left, right, .. }
25867            | PlanNode::Union { left, right } => {
25868                plan_contains_distinct(left) || plan_contains_distinct(right)
25869            }
25870            PlanNode::Filter { inner, .. }
25871            | PlanNode::Extend { inner, .. }
25872            | PlanNode::Slice { inner, .. }
25873            | PlanNode::Sort { inner, .. }
25874            | PlanNode::Group { inner, .. }
25875            | PlanNode::JoinGraphVar { inner, .. } => plan_contains_distinct(inner),
25876            PlanNode::SubSelect(sub) => plan_contains_distinct(&sub.inner),
25877            PlanNode::CustomNode(custom) => custom.children.iter().any(plan_contains_distinct),
25878        }
25879    }
25880
25881    fn find_group(node: &PlanNode) -> &PlanNode {
25882        match node {
25883            PlanNode::Group { .. } => node,
25884            PlanNode::Extend { inner, .. }
25885            | PlanNode::Filter { inner, .. }
25886            | PlanNode::Slice { inner, .. }
25887            | PlanNode::Distinct { inner, .. }
25888            | PlanNode::Sort { inner, .. } => find_group(inner),
25889            other => panic!("expected Group under unary wrappers, got {other:?}"),
25890        }
25891    }
25892
25893    /// Collect every ScanOp in the tree.
25894    /// Used by Tests only, for checking liveness and bag marks.
25895    fn collect_scans<'a>(node: &'a PlanNode, out: &mut Vec<&'a ScanOp>) {
25896        match node {
25897            PlanNode::Scan(scan) => out.push(scan),
25898            PlanNode::Path(_)
25899            | PlanNode::Values(_)
25900            | PlanNode::NamedGraphs { .. }
25901            | PlanNode::NamedGraphExists { .. }
25902            | PlanNode::DomainCounts { .. }
25903            | PlanNode::HeadCounts { .. }
25904            | PlanNode::PatternCount { .. }
25905            | PlanNode::Unit => {}
25906            PlanNode::Join { left, right, .. }
25907            | PlanNode::LeftJoin { left, right, .. }
25908            | PlanNode::Union { left, right } => {
25909                collect_scans(left, out);
25910                collect_scans(right, out);
25911            }
25912            PlanNode::Filter { inner, .. }
25913            | PlanNode::Extend { inner, .. }
25914            | PlanNode::Slice { inner, .. }
25915            | PlanNode::Distinct { inner, .. }
25916            | PlanNode::Sort { inner, .. }
25917            | PlanNode::Group { inner, .. }
25918            | PlanNode::JoinGraphVar { inner, .. } => collect_scans(inner, out),
25919            PlanNode::SubSelect(sub) => collect_scans(&sub.inner, out),
25920            PlanNode::CustomNode(custom) => {
25921                for child in &custom.children {
25922                    collect_scans(child, out);
25923                }
25924            }
25925        }
25926    }
25927
25928    #[test]
25929    fn count_distinct_star_keeps_all_inner_vars_uniformly_insensitive() {
25930        let plan = LogicalPlan::parse(
25931            "SELECT ?p (COUNT(DISTINCT *) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
25932        )
25933        .unwrap();
25934        let mut scans = Vec::new();
25935        collect_scans(&plan.root, &mut scans);
25936        assert!(!scans.is_empty());
25937        // Every slot variable is live (NOT dead) on every scan under the Group.
25938        for scan in &scans {
25939            for variable in scan.slot_variables() {
25940                let mark = scan.bag_mark(&variable);
25941                assert!(mark.is_some(), "{variable} must be live, scan {scan:?}");
25942                assert_eq!(
25943                    mark,
25944                    Some(BagMark::Insensitive),
25945                    "{variable} must be uniformly bag-insensitive (set-like), scan {scan:?}"
25946                );
25947            }
25948        }
25949    }
25950
25951    #[test]
25952    fn count_distinct_star_with_multiplicity_sibling_promotes_all_to_sensitive() {
25953        let plan = LogicalPlan::parse(
25954            "SELECT ?p (COUNT(DISTINCT *) AS ?c) (COUNT(?o) AS ?n) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
25955        )
25956        .unwrap();
25957        let mut scans = Vec::new();
25958        collect_scans(&plan.root, &mut scans);
25959        for scan in &scans {
25960            for variable in scan.slot_variables() {
25961                assert_eq!(
25962                    scan.bag_mark(&variable),
25963                    Some(BagMark::Sensitive),
25964                    "{variable} must be uniformly bag-sensitive (multiplicity wins), scan {scan:?}"
25965                );
25966            }
25967        }
25968    }
25969
25970    #[test]
25971    fn count_distinct_star_disarms_scan_domain_counts() {
25972        let plan = LogicalPlan::parse(
25973            "SELECT ?p (COUNT(DISTINCT *) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
25974        )
25975        .unwrap();
25976        let mut scans = Vec::new();
25977        collect_scans(&plan.root, &mut scans);
25978        assert!(!scans.is_empty());
25979        for scan in &scans {
25980            assert!(
25981                scan.domain_counts.is_none(),
25982                "COUNT(DISTINCT *) inner vars are live, not counted — scan must stay plain or domain_scan, got {:?}",
25983                scan.domain_counts
25984            );
25985        }
25986    }
25987
25988    #[test]
25989    fn count_distinct_star_with_sample_sibling_gets_uniform_marks() {
25990        // SAMPLE needs value-liveness but not multiplicity; the uniform-mark
25991        // rule still decides ONE mark for the whole group — never mixed.
25992        // Which mark it lands on is not pinned here: a GROUP BY ?p key that is
25993        // ground on a scan may be demoted to Insensitive by `is_grounded_kept`
25994        // (a constant slot cannot change full-row distinctness), and the
25995        // uniform promotion covers the rest. The correctness contract is:
25996        // every inner var is live, and all marks on one scan agree.
25997        let plan = LogicalPlan::parse(
25998            "SELECT ?p (COUNT(DISTINCT *) AS ?c) (SAMPLE(?o) AS ?v) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
25999        )
26000        .unwrap();
26001        let mut scans = Vec::new();
26002        collect_scans(&plan.root, &mut scans);
26003        for scan in &scans {
26004            let marks: Vec<_> = scan
26005                .slot_variables()
26006                .into_iter()
26007                .map(|v| (v.clone(), scan.bag_mark(&v)))
26008                .collect();
26009            assert!(!marks.is_empty(), "all vars must be live: {marks:?}");
26010            assert!(
26011                marks.iter().all(|(_, m)| *m == marks[0].1),
26012                "marks must be uniform (never mixed): {marks:?}"
26013            );
26014        }
26015    }
26016
26017    #[test]
26018    fn having_optional_group_scan_schemas_align() {
26019        let plan = LogicalPlan::parse(
26020            r#"SELECT ?w (COUNT(*) AS ?c) WHERE {
26021              ?p <http://ex/livesIn> ?city .
26022              OPTIONAL { ?city <http://ex/hasWeather> ?w }
26023            } GROUP BY ?w HAVING (?w = "Sunny")"#,
26024        )
26025        .unwrap();
26026        let mut scans = Vec::new();
26027        collect_scans(&plan.root, &mut scans);
26028        for scan in &scans {
26029            let mat = scan.materialized_variables();
26030            assert_eq!(
26031                mat.iter().map(|v| v.as_str()).collect::<Vec<_>>(),
26032                scan.slot_variables()
26033                    .iter()
26034                    .filter(|v| scan.is_live(v) || scan.is_counted(v))
26035                    .map(|v| v.as_str())
26036                    .collect::<Vec<_>>(),
26037                "materialized_variables must match live+counted slots: {scan:?}"
26038            );
26039        }
26040    }
26041
26042    #[test]
26043    fn plain_count_star_still_prunes_dead_columns() {
26044        // Plain COUNT(*) with GROUP BY: keys stay insensitive; non-key slots are
26045        // counted (Dead+Sensitive), not dropped — row multiplicity without
26046        // promoting keys.
26047        let plan = LogicalPlan::parse(
26048            "SELECT ?class (COUNT(*) AS ?n) WHERE { ?inst ?p ?class } GROUP BY ?class",
26049        )
26050        .unwrap();
26051        let group = find_group(&plan.root);
26052        let PlanNode::Group { inner, .. } = group else {
26053            panic!("expected Group, got {group:?}");
26054        };
26055        let PlanNode::Scan(scan) = inner.as_ref() else {
26056            panic!("expected Scan under Group");
26057        };
26058        assert_eq!(
26059            scan.bag_mark(scan.object.as_ref().unwrap()),
26060            Some(BagMark::Insensitive),
26061            "GROUP BY key stays bag-insensitive under COUNT(*)"
26062        );
26063        assert!(scan.is_live(scan.object.as_ref().unwrap()));
26064        assert!(scan.is_counted(scan.subject.as_ref().unwrap()));
26065        assert!(scan.is_counted(scan.predicate.as_ref().unwrap()));
26066        assert!(!scan.is_dropped(scan.subject.as_ref().unwrap()));
26067        assert!(!scan.is_dropped(scan.predicate.as_ref().unwrap()));
26068    }
26069
26070    #[test]
26071    fn plain_count_star_implicit_group_marks_non_keys_counted() {
26072        let plan = LogicalPlan::parse(
26073            "SELECT (COUNT(*) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p }",
26074        )
26075        .unwrap();
26076        let mut scans = Vec::new();
26077        collect_scans(&plan.root, &mut scans);
26078        for scan in &scans {
26079            assert!(
26080                !scan.marks.is_empty(),
26081                "liveness must annotate scans under COUNT(*): {scan:?}"
26082            );
26083            for variable in scan.slot_variables() {
26084                assert!(
26085                    scan.is_counted(&variable)
26086                        || scan.is_dropped(&variable)
26087                        || scan.is_live(&variable),
26088                    "implicit COUNT(*) marks slots counted, dropped, or live (join keys): {variable} {scan:?}"
26089                );
26090            }
26091        }
26092    }
26093
26094    #[test]
26095    fn count_without_group_by_lowers_to_pattern_count() {
26096        let plan =
26097            LogicalPlan::parse("SELECT (COUNT(*) AS ?c) WHERE { ?s <http://ex/p> ?o }").unwrap();
26098        assert_eq!(plan.projection, vec![var("c")]);
26099        // Ungrouped bag COUNT(*) over a single BGP lowers to the specialized
26100        // PatternCount leaf (eliminate_pattern_count_groups) — one
26101        // CountPattern RPC, no solution rows are returned — with the projection
26102        // variable rebound by an Extend. GROUP BY / COUNT(DISTINCT) /
26103        // multi-pattern inputs keep the DomainCounts / generic Group leaves.
26104        let PlanNode::Extend {
26105            inner,
26106            variable,
26107            expression,
26108            ..
26109        } = &plan.root
26110        else {
26111            panic!("expected Extend over PatternCount, got {:?}", plan.root);
26112        };
26113        assert_eq!(variable, &var("c"));
26114        let PlanNode::PatternCount {
26115            count,
26116            count_star,
26117            counted,
26118            ..
26119        } = &**inner
26120        else {
26121            panic!("expected PatternCount under Extend, got {inner:?}");
26122        };
26123        assert!(count_star, "COUNT(*) has no counted variable");
26124        assert!(counted.is_none());
26125        // The Extend rebinds PatternCount's internal count var to ?c.
26126        assert_eq!(
26127            expression,
26128            &spargebra::algebra::Expression::Variable(count.clone())
26129        );
26130        let out = plan.root.output_vars();
26131        assert!(
26132            out.always_bound.iter().any(|v| v.as_str() == "c"),
26133            "{out:?}"
26134        );
26135        assert_eq!(plan.root.produced_row_count_estimate(), 1);
26136    }
26137
26138    #[test]
26139    fn group_by_variable_drops_non_key_inner_vars() {
26140        let plan = LogicalPlan::parse(
26141            "SELECT ?p (COUNT(?o) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p",
26142        )
26143        .unwrap();
26144        let group = find_group(&plan.root);
26145        let PlanNode::Group {
26146            variables,
26147            aggregates,
26148            ..
26149        } = group
26150        else {
26151            unreachable!();
26152        };
26153        assert_eq!(variables, &vec![var("p")]);
26154        assert!(matches!(
26155            aggregates[0].1,
26156            spargebra::algebra::AggregateExpression::FunctionCall {
26157                name: spargebra::algebra::AggregateFunction::Count,
26158                ..
26159            }
26160        ));
26161        let names: Vec<_> = group
26162            .output_vars()
26163            .all()
26164            .into_iter()
26165            .map(|v| v.as_str().to_owned())
26166            .collect();
26167        assert!(names.iter().any(|n| n == "p"), "{names:?}");
26168        assert!(
26169            !names.iter().any(|n| n == "s"),
26170            "non-key ?s must not be projected: {names:?}"
26171        );
26172        assert!(
26173            !names.iter().any(|n| n == "o"),
26174            "non-key ?o must not be projected: {names:?}"
26175        );
26176        let projected: Vec<_> = plan
26177            .root
26178            .output_vars()
26179            .all()
26180            .into_iter()
26181            .map(|v| v.as_str().to_owned())
26182            .collect();
26183        assert!(projected.iter().any(|n| n == "c"), "{projected:?}");
26184    }
26185
26186    #[test]
26187    fn having_is_filter_over_group() {
26188        let plan = LogicalPlan::parse(
26189            "SELECT ?p (COUNT(*) AS ?c) WHERE { ?s <http://ex/p> ?o . ?s <http://ex/q> ?p } GROUP BY ?p HAVING (COUNT(*) > 1)",
26190        )
26191        .unwrap();
26192        let mut node = &plan.root;
26193        while let PlanNode::Extend { inner, .. } = node {
26194            node = inner;
26195        }
26196        let PlanNode::Filter { inner, early, .. } = node else {
26197            panic!("expected Filter (HAVING) over Group, got {:?}", plan.root);
26198        };
26199        assert!(
26200            early.is_some(),
26201            "HAVING comparison should be an early filter"
26202        );
26203        assert!(
26204            matches!(inner.as_ref(), PlanNode::Group { .. }),
26205            "HAVING Filter inner should be Group, got {inner:?}"
26206        );
26207    }
26208
26209    #[test]
26210    fn subselect_lowers_to_opaque_boundary_and_renames_inner_vars() {
26211        let plan = LogicalPlan::parse(
26212            r#"SELECT ?city WHERE {
26213                { SELECT ?city WHERE { ?cat <http://ex/type> <http://ex/Cat> . ?cat <http://ex/livesIn> ?city } }
26214                ?city <http://ex/hasWeather> ?w .
26215            }"#,
26216        )
26217        .unwrap();
26218        let mut subs = Vec::new();
26219        find_subqueries(&plan.root, &mut subs);
26220        assert_eq!(subs.len(), 1, "one subselect boundary: {:?}", plan.root);
26221        assert_eq!(
26222            subs[0].variables,
26223            vec![var("city")],
26224            "boundary schema is the SELECT list"
26225        );
26226        // ?cat is not projected: it must be renamed inside the boundary so it
26227        // can never collide with an outer ?cat. Projected names stay bare.
26228        let mut scans = Vec::new();
26229        collect_scans(&subs[0].inner, &mut scans);
26230        assert!(!scans.is_empty(), "subselect keeps its scans");
26231        let slot_names: Vec<String> = scans
26232            .iter()
26233            .flat_map(|scan| [&scan.subject, &scan.predicate, &scan.object])
26234            .flatten()
26235            .map(Variable::as_str)
26236            .map(str::to_owned)
26237            .collect();
26238        assert!(
26239            slot_names
26240                .iter()
26241                .any(|name| name.starts_with("sq_") && name.ends_with("_cat")),
26242            "non-projected ?cat should carry the random scope token: {slot_names:?}"
26243        );
26244        assert!(
26245            !slot_names.contains(&"cat".to_owned()),
26246            "non-projected ?cat must not keep its user-visible name: {slot_names:?}"
26247        );
26248        assert!(
26249            slot_names.contains(&"city".to_owned()),
26250            "projected ?city keeps its name: {slot_names:?}"
26251        );
26252        assert_eq!(plan.projection, vec![var("city")]);
26253    }
26254
26255    #[test]
26256    fn sibling_subqueries_get_distinct_random_scope_tokens() {
26257        // Counter prefixes were predictable (`sq1_`) and collided with legal
26258        // user variable names; each sub-SELECT now mints its own random token,
26259        // so two subqueries never share a prefix and none looks like `sq1_`.
26260        let plan = LogicalPlan::parse(
26261            r#"SELECT ?a ?b WHERE {
26262                { SELECT ?a WHERE { ?s <http://ex/p> ?a } }
26263                { SELECT ?b WHERE { ?s <http://ex/p> ?b } }
26264            }"#,
26265        )
26266        .unwrap();
26267        let mut subs = Vec::new();
26268        find_subqueries(&plan.root, &mut subs);
26269        assert_eq!(subs.len(), 2, "{:?}", plan.root);
26270        let mut prefixes = Vec::new();
26271        for sub in &subs {
26272            let mut scans = Vec::new();
26273            collect_scans(&sub.inner, &mut scans);
26274            let renamed: Vec<&str> = scans
26275                .iter()
26276                .flat_map(|scan| [&scan.subject, &scan.object])
26277                .flatten()
26278                .map(Variable::as_str)
26279                .filter(|name| name.starts_with("sq_"))
26280                .collect();
26281            assert_eq!(
26282                renamed.len(),
26283                1,
26284                "the non-projected ?s is renamed exactly once per subquery: {renamed:?}"
26285            );
26286            // `sq_` + 16 token chars + `_` + original name.
26287            let name = renamed[0];
26288            assert_eq!(name.len(), 3 + 16 + 1 + 1, "token is 16 chars: {name}");
26289            prefixes.push(name.trim_start_matches("sq_").split('_').next().unwrap());
26290        }
26291        assert_ne!(prefixes[0], prefixes[1], "tokens are per-subquery random");
26292    }
26293
26294    #[test]
26295    fn subselect_with_limit_keeps_boundary_schema() {
26296        let plan = LogicalPlan::parse(
26297            r#"SELECT ?x ?y WHERE {
26298                { SELECT ?x WHERE { ?s <http://ex/p> ?x } LIMIT 3 }
26299                ?x <http://ex/q> ?y .
26300            }"#,
26301        )
26302        .unwrap();
26303        let mut subs = Vec::new();
26304        find_subqueries(&plan.root, &mut subs);
26305        assert_eq!(subs.len(), 1, "{:?}", plan.root);
26306        assert_eq!(subs[0].variables, vec![var("x")]);
26307        // The subquery's own LIMIT is folded INSIDE the boundary, so nothing
26308        // wraps it from outside and the join arm is a bare SubQuery.
26309        assert!(
26310            matches!(
26311                subs[0].inner.as_ref(),
26312                PlanNode::Slice {
26313                    length: Some(3),
26314                    ..
26315                }
26316            ),
26317            "the boundary owns its LIMIT: {:?}",
26318            subs[0].inner
26319        );
26320        assert!(
26321            !matches!(plan.root, PlanNode::Slice { .. }),
26322            "no Slice may wrap the boundary from outside: {:?}",
26323            plan.root
26324        );
26325    }
26326
26327    #[test]
26328    fn subselect_modifier_spine_folds_inside_the_boundary() {
26329        // All four spargebra subselect spines — `Slice?(Distinct?(Project))`
26330        // — lower to ONE boundary that owns its modifiers, in SPARQL order
26331        // (`Slice?(Distinct?(body))`, Distinct below Slice). The executor
26332        // paths then bound the body evaluation by the subselect's own
26333        // OFFSET/LIMIT, and every join arm is a bare SubSelect node.
26334        let cases: &[(&str, bool, Option<u64>)] = &[
26335            ("SELECT ?x WHERE { ?s <http://ex/p> ?x }", false, None),
26336            (
26337                "SELECT DISTINCT ?x WHERE { ?s <http://ex/p> ?x }",
26338                true,
26339                None,
26340            ),
26341            (
26342                "SELECT ?x WHERE { ?s <http://ex/p> ?x } LIMIT 3",
26343                false,
26344                Some(3),
26345            ),
26346            (
26347                "SELECT DISTINCT ?x WHERE { ?s <http://ex/p> ?x } LIMIT 3",
26348                true,
26349                Some(3),
26350            ),
26351        ];
26352        for (select, distinct, limit) in cases {
26353            let query = format!("SELECT ?x WHERE {{ {{ {select} }} }}");
26354            let plan = LogicalPlan::parse(&query).unwrap();
26355            assert!(
26356                !matches!(
26357                    plan.root,
26358                    PlanNode::Slice { .. } | PlanNode::Distinct { .. }
26359                ),
26360                "{select}: no modifier may wrap the boundary: {:?}",
26361                plan.root
26362            );
26363            let mut subs = Vec::new();
26364            find_subqueries(&plan.root, &mut subs);
26365            assert_eq!(subs.len(), 1, "{select}: {:?}", plan.root);
26366            let sub = subs[0];
26367            assert_eq!(sub.variables, vec![var("x")], "{select}");
26368            // Peel the in-boundary spine, outermost first: Slice, then
26369            // Distinct, then the body.
26370            let mut inner: &PlanNode = &sub.inner;
26371            match limit {
26372                Some(n) => {
26373                    let PlanNode::Slice {
26374                        inner: wrapped,
26375                        length: Some(got),
26376                        ..
26377                    } = inner
26378                    else {
26379                        panic!("{select}: boundary must own its LIMIT: {:?}", sub.inner);
26380                    };
26381                    assert_eq!(*got, *n, "{select}");
26382                    inner = wrapped;
26383                }
26384                None => assert!(
26385                    !matches!(inner, PlanNode::Slice { .. }),
26386                    "{select}: no LIMIT, no Slice: {:?}",
26387                    sub.inner
26388                ),
26389            }
26390            if *distinct {
26391                let PlanNode::Distinct {
26392                    inner: wrapped,
26393                    columns,
26394                    ..
26395                } = inner
26396                else {
26397                    panic!("{select}: boundary must own its DISTINCT: {:?}", sub.inner);
26398                };
26399                assert_eq!(columns, &vec![var("x")], "{select}");
26400                inner = wrapped;
26401            } else {
26402                assert!(
26403                    !matches!(inner, PlanNode::Distinct { .. }),
26404                    "{select}: no DISTINCT, no Distinct: {:?}",
26405                    sub.inner
26406                );
26407            }
26408            assert!(
26409                matches!(inner, PlanNode::Scan(_)),
26410                "{select}: body directly under the spine: {inner:?}"
26411            );
26412        }
26413    }
26414
26415    #[test]
26416    fn values_is_pushed_into_both_sibling_subqueries() {
26417        let plan = LogicalPlan::parse(
26418            r#"SELECT ?animal ?colour WHERE {
26419                VALUES ?city { <http://ex/brisbane> }
26420                {
26421                    SELECT ?animal ?city WHERE {
26422                        ?cat a <http://ex/Cat> .
26423                        ?cat <http://ex/livesIn> ?city .
26424                        BIND(?cat AS ?animal) .
26425                    }
26426                }
26427                {
26428                    SELECT ?animal ?city WHERE {
26429                        ?dog a <http://ex/Dog> .
26430                        ?dog <http://ex/livesIn> ?city .
26431                        BIND(?dog AS ?animal) .
26432                    }
26433                }
26434                ?animal <http://ex/hasColour> ?colour .
26435            }"#,
26436        )
26437        .unwrap();
26438        let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap());
26439        let mut subs = Vec::new();
26440        find_subqueries(&plan.root, &mut subs);
26441        assert_eq!(subs.len(), 2, "{:?}", plan.root);
26442        for sub in &subs {
26443            assert!(
26444                values_has_term(&sub.inner, &brisbane),
26445                "VALUES clone should join below the sub-SELECT boundary: {:?}",
26446                sub.inner
26447            );
26448        }
26449        // Clone, never move: the outer table is still part of the plan.
26450        assert!(
26451            values_has_term(&plan.root, &brisbane),
26452            "outer VALUES stays: {:?}",
26453            plan.root
26454        );
26455    }
26456
26457    #[test]
26458    fn ground_bind_pushes_into_subselect() {
26459        // Note: `BIND` *after* a sub-SELECT group is rejected by spargebra's
26460        // parser (`expected [_]`), so the grounding BIND precedes it here.
26461        // The identity rewrite turns the ground BIND into a one-row VALUES
26462        // and the subquery pass pushes a clone below the boundary.
26463        let plan = LogicalPlan::parse(
26464            r#"SELECT ?cat ?colour WHERE {
26465                BIND(<http://ex/brisbane> AS ?city)
26466                {
26467                    SELECT ?cat ?city WHERE {
26468                        ?cat a <http://ex/Cat> .
26469                        ?cat <http://ex/livesIn> ?city .
26470                    }
26471                }
26472                ?cat <http://ex/hasColour> ?colour .
26473            }"#,
26474        )
26475        .unwrap();
26476        let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap());
26477        let mut subs = Vec::new();
26478        find_subqueries(&plan.root, &mut subs);
26479        assert_eq!(subs.len(), 1, "{:?}", plan.root);
26480        assert!(
26481            values_has_term(&subs[0].inner, &brisbane),
26482            "ground BIND should ground the subquery: {:?}",
26483            subs[0].inner
26484        );
26485    }
26486
26487    #[test]
26488    fn outer_sameterm_grounds_subselect_scan_and_dead_projection_is_pruned() {
26489        let plan = LogicalPlan::parse(
26490            r#"SELECT ?cat ?colour WHERE {
26491                {
26492                    SELECT ?cat ?city WHERE {
26493                        ?cat a <http://ex/Cat> .
26494                        ?cat <http://ex/livesIn> ?city .
26495                    }
26496                }
26497                ?cat <http://ex/hasColour> ?colour .
26498                FILTER (sameTerm(?city, <http://ex/brisbane>))
26499            }"#,
26500        )
26501        .unwrap();
26502        let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap());
26503        let mut subs = Vec::new();
26504        find_subqueries(&plan.root, &mut subs);
26505        assert_eq!(subs.len(), 1, "{:?}", plan.root);
26506        // sparopt pushes the outer conjunct into the subquery body and
26507        // fold_identity_filters grounds the inner livesIn scan on ?city.
26508        let mut inner_scans = Vec::new();
26509        collect_scans(&subs[0].inner, &mut inner_scans);
26510        assert!(
26511            inner_scans
26512                .iter()
26513                .any(|scan| scan.pattern.object.as_ref() == Some(&brisbane)),
26514            "inner scan slot should be grounded: {:?}",
26515            subs[0].inner
26516        );
26517        // With the filter inside the boundary, ?city is dead above and the
26518        // liveness walk prunes it from the boundary output.
26519        assert_eq!(
26520            subs[0].variables,
26521            vec![var("cat")],
26522            "dead ?city projection should be pruned: {:?}",
26523            subs[0].inner
26524        );
26525    }
26526
26527    #[test]
26528    fn dead_projected_vars_are_pruned_from_the_boundary() {
26529        let plan = LogicalPlan::parse(
26530            r#"SELECT ?animal ?city ?colour WHERE {
26531                {
26532                    SELECT ?animal ?city ?name1 WHERE {
26533                        ?cat a <http://ex/Cat> .
26534                        ?cat <http://ex/livesIn> ?city .
26535                        ?cat <http://ex/hasName> ?name1 .
26536                        BIND(?cat AS ?animal) .
26537                        FILTER(strstarts(?name1, "A"))
26538                    }
26539                }
26540                {
26541                    SELECT ?animal ?city ?name2 WHERE {
26542                        ?dog a <http://ex/Dog> .
26543                        ?dog <http://ex/livesIn> ?city .
26544                        ?dog <http://ex/hasName> ?name2 .
26545                        BIND(?dog AS ?animal) .
26546                        FILTER(strstarts(?name2, "A"))
26547                    }
26548                }
26549                ?animal <http://ex/hasColour> ?colour .
26550            }"#,
26551        )
26552        .unwrap();
26553        let mut subs = Vec::new();
26554        find_subqueries(&plan.root, &mut subs);
26555        assert_eq!(subs.len(), 2, "{:?}", plan.root);
26556        for sub in &subs {
26557            // ?name1 / ?name2 are projected but dead above: dropped from the
26558            // boundary output (multiset-preserving), while the inner FILTER
26559            // keeps them live inside.
26560            assert_eq!(
26561                sub.variables,
26562                vec![var("animal"), var("city")],
26563                "dead projections should be pruned: {:?}",
26564                sub.inner
26565            );
26566            let mut inner_scans = Vec::new();
26567            collect_scans(&sub.inner, &mut inner_scans);
26568            assert!(
26569                inner_scans.iter().any(|scan| scan
26570                    .object
26571                    .as_ref()
26572                    .is_some_and(|v| v.as_str().starts_with("name"))),
26573                "the name scan stays live for the inner FILTER: {:?}",
26574                sub.inner
26575            );
26576        }
26577    }
26578
26579    #[test]
26580    fn shared_projection_name_is_a_cross_boundary_join_key() {
26581        let plan = LogicalPlan::parse(
26582            r#"SELECT ?animal ?city ?colour WHERE {
26583                {
26584                    SELECT ?animal ?city ?name WHERE {
26585                        ?cat a <http://ex/Cat> .
26586                        ?cat <http://ex/livesIn> ?city .
26587                        ?cat <http://ex/hasName> ?name .
26588                        BIND(?cat AS ?animal) .
26589                    }
26590                }
26591                {
26592                    SELECT ?animal ?city ?name WHERE {
26593                        ?dog a <http://ex/Dog> .
26594                        ?dog <http://ex/livesIn> ?city .
26595                        ?dog <http://ex/hasName> ?name .
26596                        BIND(?dog AS ?animal) .
26597                    }
26598                }
26599                ?animal <http://ex/hasColour> ?colour .
26600            }"#,
26601        )
26602        .unwrap();
26603        // Both subqueries project ?name: it is in scope outside and MUST be
26604        // a join key even though the outer SELECT never mentions it.
26605        let mut found = false;
26606        for_each_join(&plan.root, &mut |hash_keys| {
26607            if hash_keys.iter().any(|v| v.as_str() == "name") {
26608                found = true;
26609            }
26610        });
26611        assert!(found, "?name should be a join key: {:?}", plan.root);
26612    }
26613
26614    #[test]
26615    fn distinct_subselect_blocks_values_pushdown_but_stays_correct() {
26616        let plan = LogicalPlan::parse(
26617            r#"SELECT ?cat ?city WHERE {
26618                VALUES ?city { <http://ex/brisbane> }
26619                {
26620                    SELECT DISTINCT ?cat ?city WHERE {
26621                        ?cat a <http://ex/Cat> .
26622                        ?cat <http://ex/livesIn> ?city .
26623                    }
26624                }
26625            }"#,
26626        )
26627        .unwrap();
26628        let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/brisbane").unwrap());
26629        let mut subs = Vec::new();
26630        find_subqueries(&plan.root, &mut subs);
26631        assert_eq!(subs.len(), 1, "{:?}", plan.root);
26632        assert!(
26633            !values_has_term(&subs[0].inner, &brisbane),
26634            "Distinct-spined subqueries are not pushed into in v1: {:?}",
26635            subs[0].inner
26636        );
26637        assert!(
26638            values_has_term(&plan.root, &brisbane),
26639            "outer VALUES still applies: {:?}",
26640            plan.root
26641        );
26642    }
26643
26644    #[test]
26645    fn order_by_in_subselect_lowers_inside_the_boundary() {
26646        let plan = LogicalPlan::parse(
26647            "SELECT ?x WHERE { { SELECT ?x WHERE { ?s <http://ex/p> ?x } ORDER BY ?x } }",
26648        )
26649        .expect("subselect ORDER BY must plan");
26650        let mut subs = Vec::new();
26651        find_subqueries(&plan.root, &mut subs);
26652        assert_eq!(subs.len(), 1, "{:?}", plan.root);
26653        assert!(
26654            matches!(subs[0].inner.as_ref(), PlanNode::Sort { .. }),
26655            "expected Sort inside SubSelect, got {:?}",
26656            subs[0].inner
26657        );
26658    }
26659
26660    #[test]
26661    fn exists_in_subselect_renames_inner_only_names() {
26662        let plan = LogicalPlan::parse(
26663            r#"SELECT ?x WHERE {
26664                { SELECT ?x WHERE { ?s <http://ex/p> ?x . FILTER(EXISTS { ?x <http://ex/q> ?z }) } }
26665            }"#,
26666        )
26667        .unwrap();
26668        let PlanNode::SubSelect(sub) = &plan.root else {
26669            panic!("expected SubSelect, got {:?}", plan.root);
26670        };
26671        let PlanNode::Filter { exists, .. } = sub.inner.as_ref() else {
26672            panic!("expected Filter inside subselect, got {:?}", sub.inner);
26673        };
26674        assert_eq!(exists.len(), 1);
26675        assert_eq!(exists[0].kind, ExistsKind::SemiJoin);
26676        assert_eq!(exists[0].correlation, vec![var("x")]);
26677        let PlanNode::Scan(scan) = exists[0].body.as_ref() else {
26678            panic!("expected Scan EXISTS body, got {:?}", exists[0].body);
26679        };
26680        assert_eq!(scan.subject, Some(var("x")));
26681        let object = scan.object.as_ref().expect("inner-only ?z");
26682        assert_ne!(object.as_str(), "z");
26683        assert!(
26684            object.as_str().starts_with("sq_"),
26685            "inner-only EXISTS var should be scope-renamed, got {object}"
26686        );
26687    }
26688
26689    #[test]
26690    fn nested_subselects_get_unique_scope_prefixes() {
26691        let plan = LogicalPlan::parse(
26692            r#"SELECT ?a WHERE {
26693                {
26694                    SELECT ?a ?b WHERE {
26695                        { SELECT ?b WHERE { ?s <http://ex/p> ?b } }
26696                        ?a <http://ex/q> ?b .
26697                    }
26698                }
26699            }"#,
26700        )
26701        .unwrap();
26702        let mut subs = Vec::new();
26703        find_subqueries(&plan.root, &mut subs);
26704        assert_eq!(subs.len(), 2, "{:?}", plan.root);
26705        // subs is post-order: [inner B2, outer B1]. B1 re-projects B2's ?b, so
26706        // nothing renames it — the nested boundary's list and its subtree both
26707        // keep the bare ?b, and only B2's own ?s carries a scope token. (The
26708        // outer query never uses B1's ?b, so liveness prunes it from B1's
26709        // boundary output; B2's ?b survives as a join key inside B1.)
26710        let [inner, outer] = subs.as_slice() else {
26711            unreachable!("two sub-SELECT boundaries");
26712        };
26713        assert_eq!(outer.variables, vec![var("a")]);
26714        assert_eq!(inner.variables, vec![var("b")]);
26715        let mut inner_scans = Vec::new();
26716        collect_scans(&inner.inner, &mut inner_scans);
26717        let slot_names: Vec<String> = inner_scans
26718            .iter()
26719            .flat_map(|scan| [&scan.subject, &scan.object])
26720            .flatten()
26721            .map(Variable::as_str)
26722            .map(str::to_owned)
26723            .collect();
26724        assert!(
26725            slot_names
26726                .iter()
26727                .any(|name| name.starts_with("sq_") && name.ends_with("_s")),
26728            "the nested scope's own token renames ?s: {slot_names:?}"
26729        );
26730        assert!(
26731            slot_names.contains(&"b".to_owned()),
26732            "?b stays consistent through the middle scope: {slot_names:?}"
26733        );
26734    }
26735
26736    #[test]
26737    fn middle_layer_rename_extends_into_nested_boundary_subtree() {
26738        // B1 does NOT re-project B2's ?b. Renaming B2's output list to the
26739        // B1-scope token must also relabel B2's subtree, or the boundary
26740        // declares a column nothing produces — project_to then substitutes an
26741        // all-unbound column and the join silently loses its values.
26742        let plan = LogicalPlan::parse(
26743            r#"SELECT ?x WHERE {
26744                { SELECT ?x WHERE {
26745                    { SELECT ?b WHERE { ?s <http://ex/p> ?b } }
26746                    ?t <http://ex/q> ?b .
26747                    BIND(?b AS ?x) .
26748                } }
26749            }"#,
26750        )
26751        .unwrap();
26752        let mut subs = Vec::new();
26753        find_subqueries(&plan.root, &mut subs);
26754        assert_eq!(subs.len(), 2, "{:?}", plan.root);
26755        let [inner, outer] = subs.as_slice() else {
26756            unreachable!("two sub-SELECT boundaries");
26757        };
26758        assert_eq!(
26759            outer.variables,
26760            vec![var("x")],
26761            "B1 schema: {:?}",
26762            plan.root
26763        );
26764        // B2's declared output is renamed to the B1-scope token (its ?b is not
26765        // in B1's SELECT list) ...
26766        assert_eq!(inner.variables.len(), 1, "{:?}", inner.inner);
26767        let renamed = &inner.variables[0];
26768        assert_ne!(
26769            renamed.as_str(),
26770            "b",
26771            "B2's ?b is renamed in B1's scope: {renamed}"
26772        );
26773        // ...and the identical name now reaches B2's own bindings.
26774        let mut inner_scans = Vec::new();
26775        collect_scans(&inner.inner, &mut inner_scans);
26776        assert_eq!(inner_scans.len(), 1, "{:?}", inner.inner);
26777        assert_eq!(
26778            inner_scans[0].object.as_ref(),
26779            Some(renamed),
26780            "B2's subtree must bind the boundary's declared output name"
26781        );
26782        // B1's body references the renamed name consistently: the q-scan slot,
26783        // the BIND expression target, and the inner join key.
26784        let mut outer_scans = Vec::new();
26785        collect_scans(&outer.inner, &mut outer_scans);
26786        assert!(
26787            outer_scans
26788                .iter()
26789                .any(|scan| scan.object.as_ref() == Some(renamed)),
26790            "B1's q-scan joins on the renamed name: {:?}",
26791            outer.inner
26792        );
26793        let mut inner_joins_named = false;
26794        for_each_join(&outer.inner, &mut |hash_keys| {
26795            if hash_keys.contains(renamed) {
26796                inner_joins_named = true;
26797            }
26798        });
26799        assert!(
26800            inner_joins_named,
26801            "the renamed name is a join key inside B1: {:?}",
26802            outer.inner
26803        );
26804    }
26805
26806    fn find_subqueries<'a>(node: &'a PlanNode, out: &mut Vec<&'a SubSelectOp>) {
26807        match node {
26808            PlanNode::SubSelect(sub) => {
26809                find_subqueries(&sub.inner, out);
26810                out.push(sub);
26811            }
26812            PlanNode::Join { left, right, .. }
26813            | PlanNode::LeftJoin { left, right, .. }
26814            | PlanNode::Union { left, right } => {
26815                find_subqueries(left, out);
26816                find_subqueries(right, out);
26817            }
26818            PlanNode::Filter { inner, .. }
26819            | PlanNode::Extend { inner, .. }
26820            | PlanNode::Slice { inner, .. }
26821            | PlanNode::Distinct { inner, .. }
26822            | PlanNode::Sort { inner, .. }
26823            | PlanNode::Group { inner, .. }
26824            | PlanNode::JoinGraphVar { inner, .. } => find_subqueries(inner, out),
26825            PlanNode::CustomNode(custom) => {
26826                for child in &custom.children {
26827                    find_subqueries(child, out);
26828                }
26829            }
26830            PlanNode::Scan(_)
26831            | PlanNode::Path(_)
26832            | PlanNode::Values(_)
26833            | PlanNode::NamedGraphs { .. }
26834            | PlanNode::NamedGraphExists { .. }
26835            | PlanNode::DomainCounts { .. }
26836            | PlanNode::HeadCounts { .. }
26837            | PlanNode::PatternCount { .. }
26838            | PlanNode::Unit => {}
26839        }
26840    }
26841
26842    fn for_each_join(node: &PlanNode, f: &mut impl FnMut(&[Variable])) {
26843        match node {
26844            PlanNode::Join {
26845                hash_keys,
26846                left,
26847                right,
26848                ..
26849            } => {
26850                f(hash_keys);
26851                for_each_join(left, f);
26852                for_each_join(right, f);
26853            }
26854            PlanNode::Union { left, right } | PlanNode::LeftJoin { left, right, .. } => {
26855                for_each_join(left, f);
26856                for_each_join(right, f);
26857            }
26858            PlanNode::Filter { inner, .. }
26859            | PlanNode::Extend { inner, .. }
26860            | PlanNode::Slice { inner, .. }
26861            | PlanNode::Distinct { inner, .. }
26862            | PlanNode::Sort { inner, .. }
26863            | PlanNode::Group { inner, .. }
26864            | PlanNode::JoinGraphVar { inner, .. } => for_each_join(inner, f),
26865            PlanNode::SubSelect(sub) => for_each_join(&sub.inner, f),
26866            PlanNode::CustomNode(custom) => {
26867                for child in &custom.children {
26868                    for_each_join(child, f);
26869                }
26870            }
26871            PlanNode::Scan(_)
26872            | PlanNode::Path(_)
26873            | PlanNode::Values(_)
26874            | PlanNode::NamedGraphs { .. }
26875            | PlanNode::NamedGraphExists { .. }
26876            | PlanNode::DomainCounts { .. }
26877            | PlanNode::HeadCounts { .. }
26878            | PlanNode::PatternCount { .. }
26879            | PlanNode::Unit => {}
26880        }
26881    }
26882
26883    #[test]
26884    fn ask_over_aggregate_subselect_is_slice_over_pattern_count() {
26885        let query = SparqlParser::new()
26886            .parse_query("ASK { SELECT (COUNT(*) AS ?c) WHERE { ?s <http://ex/p> ?o } }")
26887            .unwrap();
26888        let Query::Ask { pattern, .. } = query else {
26889            panic!("expected ASK");
26890        };
26891        let plan = LogicalPlan::from_ask_algebra(pattern, None).unwrap();
26892        match &plan.root {
26893            PlanNode::Slice {
26894                start,
26895                length,
26896                inner,
26897            } => {
26898                assert_eq!(*start, 0);
26899                assert_eq!(*length, Some(1));
26900                // The count lands in an Extend-bound PatternCount (the
26901                // projection variable rebound over the leaf's internal
26902                // count var).
26903                let count_node = match &**inner {
26904                    PlanNode::Extend { inner, .. } => &**inner,
26905                    other => other,
26906                };
26907                assert!(
26908                    matches!(
26909                        count_node,
26910                        PlanNode::PatternCount {
26911                            count_star: true,
26912                            ..
26913                        }
26914                    ),
26915                    "ASK SubSelect should lower to PatternCount: {inner:?}"
26916                );
26917            }
26918            other => panic!("expected Slice LIMIT 1 over PatternCount, got {other:?}"),
26919        }
26920    }
26921
26922    #[test]
26923    fn explain_sparql_keeps_limit() {
26924        let text =
26925            explain_optimised_sparql("SELECT ?s WHERE { ?s <http://ex/p> ?o } LIMIT 5 OFFSET 1");
26926        assert!(text.contains("LIMIT"), "{text}");
26927        assert!(text.contains("OFFSET"), "{text}");
26928    }
26929
26930    fn contains_filter(node: &PlanNode) -> bool {
26931        match node {
26932            PlanNode::Filter { .. } => true,
26933            PlanNode::Join { left, right, .. }
26934            | PlanNode::Union { left, right }
26935            | PlanNode::LeftJoin { left, right, .. } => {
26936                contains_filter(left) || contains_filter(right)
26937            }
26938            PlanNode::Extend { inner, .. }
26939            | PlanNode::Slice { inner, .. }
26940            | PlanNode::Distinct { inner, .. }
26941            | PlanNode::Sort { inner, .. }
26942            | PlanNode::Group { inner, .. } => contains_filter(inner),
26943            _ => false,
26944        }
26945    }
26946
26947    fn values_has_term(node: &PlanNode, term: &EncodedTerm) -> bool {
26948        match node {
26949            PlanNode::Values(values) => values
26950                .rows
26951                .iter()
26952                .any(|row| row.iter().any(|cell| cell.as_ref() == Some(term))),
26953            PlanNode::Join { left, right, .. }
26954            | PlanNode::Union { left, right }
26955            | PlanNode::LeftJoin { left, right, .. } => {
26956                values_has_term(left, term) || values_has_term(right, term)
26957            }
26958            PlanNode::Filter { inner, .. }
26959            | PlanNode::Extend { inner, .. }
26960            | PlanNode::Slice { inner, .. }
26961            | PlanNode::Distinct { inner, .. }
26962            | PlanNode::Sort { inner, .. }
26963            | PlanNode::Group { inner, .. } => values_has_term(inner, term),
26964            _ => false,
26965        }
26966    }
26967
26968    fn first_join_strategy(node: &PlanNode) -> Option<JoinStrategy> {
26969        match node {
26970            PlanNode::Join { meta, .. } => Some(meta.strategy),
26971            PlanNode::Slice { inner, .. }
26972            | PlanNode::Distinct { inner, .. }
26973            | PlanNode::Sort { inner, .. }
26974            | PlanNode::Filter { inner, .. }
26975            | PlanNode::Extend { inner, .. }
26976            | PlanNode::Group { inner, .. } => first_join_strategy(inner),
26977            PlanNode::LeftJoin { left, right, .. } | PlanNode::Union { left, right } => {
26978                first_join_strategy(left).or_else(|| first_join_strategy(right))
26979            }
26980            _ => None,
26981        }
26982    }
26983
26984    #[test]
26985    fn identity_equality_filter_grounds_scan_slot() {
26986        let sparql = r#"SELECT ?o WHERE { ?s <http://ex/hasWeather> ?o FILTER(?o = "Sunny") }"#;
26987        let plan = LogicalPlan::parse(sparql).unwrap();
26988        assert!(
26989            !contains_filter(&plan.root),
26990            "identity-safe = should fold into the scan, got {:?}",
26991            plan.root
26992        );
26993        let mut scans = Vec::new();
26994        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
26995        assert_eq!(scans.len(), 1);
26996        assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("o"));
26997        assert_eq!(
26998            scans[0].pattern.object,
26999            Some(EncodedTerm::from(&Literal::from("Sunny")))
27000        );
27001        assert_eq!(plan.projection, vec![var("o")]);
27002
27003        let text = explain_est(sparql, None);
27004        assert!(
27005            text.contains("\"Sunny\""),
27006            "EXPLAIN should show the bound term: {text}"
27007        );
27008        assert!(
27009            !text.contains("(filter"),
27010            "folded equality should not leave a Filter node: {text}"
27011        );
27012    }
27013
27014    #[test]
27015    fn identity_equality_filter_grounds_iri_slot() {
27016        let plan = LogicalPlan::parse(
27017            r#"SELECT ?c WHERE { ?p <http://ex/livesIn> ?c FILTER(?c = <http://ex/Brisbane>) }"#,
27018        )
27019        .unwrap();
27020        assert!(
27021            !contains_filter(&plan.root),
27022            "IRI = should fold into the scan, got {:?}",
27023            plan.root
27024        );
27025        let mut scans = Vec::new();
27026        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
27027        assert_eq!(scans.len(), 1);
27028        assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("c"));
27029        assert_eq!(
27030            scans[0].pattern.object,
27031            Some(EncodedTerm::from(
27032                &NamedNode::new("http://ex/Brisbane").unwrap()
27033            ))
27034        );
27035    }
27036
27037    #[test]
27038    fn identity_equality_and_grounds_both_scans() {
27039        let plan = LogicalPlan::parse(
27040            r#"SELECT ?s WHERE {
27041              ?s <http://ex/livesIn> ?c .
27042              ?c <http://ex/hasWeather> ?w
27043              FILTER(?c = <http://ex/Brisbane> && ?w = "Sunny")
27044            }"#,
27045        )
27046        .unwrap();
27047        assert!(
27048            !contains_filter(&plan.root),
27049            "&& of identity-safe equalities should fold, got {:?}",
27050            plan.root
27051        );
27052        let brisbane = EncodedTerm::from(&NamedNode::new("http://ex/Brisbane").unwrap());
27053        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
27054        let mut saw_brisbane = false;
27055        let mut saw_sunny = false;
27056        for_each_scan(&plan.root, &mut |scan| {
27057            if scan.pattern.object.as_ref() == Some(&brisbane) {
27058                saw_brisbane = true;
27059                assert_eq!(scan.subject.as_ref().map(Variable::as_str), Some("s"));
27060            }
27061            if scan.pattern.object.as_ref() == Some(&sunny) {
27062                saw_sunny = true;
27063                assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("w"));
27064            }
27065        });
27066        assert!(
27067            saw_brisbane && saw_sunny,
27068            "both slots should be ground, got {:?}",
27069            plan.root
27070        );
27071    }
27072
27073    #[test]
27074    fn numeric_equality_filter_is_not_folded() {
27075        let plan =
27076            LogicalPlan::parse(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v FILTER(?v = 1.0e0) }"#)
27077                .unwrap();
27078        assert!(
27079            !contains_filter(&plan.root),
27080            "the exact numeric = moves into the scan, got {:?}",
27081            plan.root
27082        );
27083        let PlanNode::Scan(scan) = &plan.root else {
27084            panic!("expected the scan root, got {:?}", plan.root);
27085        };
27086        assert!(
27087            scan.pattern.object.is_none(),
27088            "numeric = must not ground the scan: {scan:?}"
27089        );
27090        assert!(scan.eager.contains(&SlotComparison {
27091            slot: QuadSlot::Object,
27092            op: CompareOp::Eq,
27093            term: EncodedTerm::from(&Literal::from(1.0f64)),
27094        }));
27095    }
27096
27097    #[test]
27098    fn sameterm_filter_grounds_any_constant() {
27099        let plan = LogicalPlan::parse(
27100            r#"SELECT ?c WHERE { ?p <http://ex/livesIn> ?c FILTER(sameTerm(?c, <http://ex/Brisbane>)) }"#,
27101        )
27102        .unwrap();
27103        assert!(
27104            !contains_filter(&plan.root),
27105            "sameTerm should fold for any ground term, got {:?}",
27106            plan.root
27107        );
27108        let mut scans = Vec::new();
27109        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
27110        assert_eq!(
27111            scans[0].pattern.object,
27112            Some(EncodedTerm::from(
27113                &NamedNode::new("http://ex/Brisbane").unwrap()
27114            ))
27115        );
27116    }
27117
27118    #[test]
27119    fn bind_sameterm_grounds_scan_subject() {
27120        let iri = NamedNode::new("http://yago-knowledge.org/resource/Crow_Hill_Q20861371").unwrap();
27121        let plan = LogicalPlan::parse(
27122            r#"SELECT ?o ?b WHERE {
27123              ?b ?p ?o .
27124              BIND(<http://yago-knowledge.org/resource/Crow_Hill_Q20861371> AS ?c)
27125              FILTER(sameTerm(?b, ?c))
27126            }"#,
27127        )
27128        .unwrap();
27129        assert!(
27130            !contains_filter(&plan.root),
27131            "var-var sameTerm with grounded BIND should fold, got {:?}",
27132            plan.root
27133        );
27134        assert!(
27135            matches!(plan.root, PlanNode::Extend { .. }),
27136            "BIND column ?c should remain as Extend, got {:?}",
27137            plan.root
27138        );
27139        let mut scans = Vec::new();
27140        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
27141        assert_eq!(scans.len(), 1);
27142        assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
27143        assert_eq!(scans[0].pattern.subject, Some(EncodedTerm::from(&iri)));
27144    }
27145
27146    #[test]
27147    fn identity_filter_grounds_repeated_variable_slots() {
27148        let painting = NamedNode::new("http://schema.org/Painting").unwrap();
27149        let encoded = EncodedTerm::from(&painting);
27150        let sparql = r#"
27151            SELECT ?b WHERE {
27152              ?b a ?b .
27153              BIND(<http://schema.org/Painting> AS ?c)
27154              FILTER(sameTerm(?b, ?c))
27155            }
27156        "#;
27157        let plan = LogicalPlan::parse(sparql).unwrap();
27158        assert!(
27159            !contains_filter(&plan.root),
27160            "identity-safe sameTerm should fold, got {:?}",
27161            plan.root
27162        );
27163        let mut scans = Vec::new();
27164        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
27165        assert_eq!(scans.len(), 1);
27166        assert_eq!(scans[0].pattern.subject, Some(encoded.clone()));
27167        assert_eq!(scans[0].pattern.object, Some(encoded));
27168        assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
27169        assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("b"));
27170        assert!(
27171            scans[0].broadcasted.is_none(),
27172            "identity fold should not stamp broadcast, got {:?}",
27173            scans[0].broadcasted
27174        );
27175        assert_eq!(
27176            grounded_of(scans[0]),
27177            vec![("b", PatternSlot::Subject), ("b", PatternSlot::Object)],
27178            "both repeated ?b slots should be grounded, got {:?}",
27179            scans[0].grounded
27180        );
27181        assert_eq!(
27182            scans[0].produced_row_count_estimate, 1,
27183            "fully bound triple is a point lookup"
27184        );
27185        let text = explain_est(sparql, None);
27186        assert!(
27187            text.contains("(grounded ?b subject, ?b object)"),
27188            "EXPLAIN should list both grounded slots: {text}"
27189        );
27190    }
27191
27192    fn painting_identity_fold_sparql() -> &'static str {
27193        r#"
27194            SELECT ?s ?b WHERE {
27195              ?s a ?b .
27196              ?b a ?b .
27197              BIND(<http://ex/Painting> AS ?c)
27198              FILTER(sameTerm(?b, ?c))
27199            }
27200        "#
27201    }
27202
27203    fn painting_class_profile() -> (NamedNode, StatsProfile) {
27204        let painting = NamedNode::new("http://ex/Painting").unwrap();
27205        let mut profile = StatsProfile::default();
27206        profile.predicate_counts.insert(
27207            waratah_storage::StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
27208            50_000_000,
27209        );
27210        profile
27211            .class_counts
27212            .insert(waratah_storage::StrHash::new("http://ex/Painting"), 910_224);
27213        profile.total_puts = 50_000_000;
27214        (painting, profile)
27215    }
27216
27217    #[test]
27218    fn refinalize_swaps_selective_scan_left() {
27219        let (painting, profile) = painting_class_profile();
27220        let painting_term = EncodedTerm::from(&painting);
27221        let plan = LogicalPlan::parse_with_profile(painting_identity_fold_sparql(), Some(&profile))
27222            .unwrap();
27223        let PlanNode::Join {
27224            left, right, meta, ..
27225        } = find_inner_join(&plan.root)
27226        else {
27227            panic!("expected Join, got {:?}", plan.root);
27228        };
27229        let PlanNode::Scan(left_scan) = left.as_ref() else {
27230            panic!("expected left Scan after swap, got {left:?}");
27231        };
27232        let PlanNode::Scan(right_scan) = right.as_ref() else {
27233            panic!("expected right Scan after swap, got {right:?}");
27234        };
27235        assert_eq!(
27236            bound_slots(&left_scan.pattern),
27237            4,
27238            "point lookup should drive: {left_scan:?}"
27239        );
27240        assert_eq!(left_scan.produced_row_count_estimate, 1);
27241        assert_eq!(right_scan.pattern.object.as_ref(), Some(&painting_term));
27242        // The probe's ?b slot is identity-fold grounded, so grounding
27243        // supersedes claiming: no mark, and the catalog price is honest
27244        // (every row of `?s a Painting` carries ?b = Painting).
27245        assert_eq!(right_scan.produced_row_count_estimate, 910_224);
27246        // The settled plan must carry the promoted stamp: identity-fold
27247        // grounding makes `class_counts[Painting]` usable for the rdf:type
27248        // subject. The dedicated `bind_scan_equality` test isolates that
27249        // call; a later broadcast-grounding pass can refresh the same scan,
27250        // so this assertion covers the integrated result rather than the
27251        // single call.
27252        assert_eq!(
27253            right_scan.join_domains.get(JoinKeySlot::Subject),
27254            JoinDomainStamp::Known(910_224),
27255            "identity-fold grounding must promote the rdf:type subject stamp"
27256        );
27257        assert!(
27258            right_scan.broadcasted.is_none(),
27259            "grounded key slot must not be claimed, got {:?}",
27260            right_scan.broadcasted
27261        );
27262        assert_eq!(meta.produced_row_count_estimate, 910_224);
27263        assert!(
27264            left_scan.broadcasted.is_none(),
27265            "driver must not keep probe broadcast, got {:?}",
27266            left_scan.broadcasted
27267        );
27268    }
27269
27270    #[test]
27271    fn refinalize_promotes_broadcast_after_swap() {
27272        let (_, profile) = painting_class_profile();
27273        let plan = LogicalPlan::parse_with_profile(painting_identity_fold_sparql(), Some(&profile))
27274            .unwrap();
27275        let PlanNode::Join { right, meta, .. } = find_inner_join(&plan.root) else {
27276            panic!("expected Join, got {:?}", plan.root);
27277        };
27278        assert_eq!(
27279            meta.strategy,
27280            JoinStrategy::Broadcast,
27281            "1-row driver after swap should Broadcast, got {:?}",
27282            meta.strategy
27283        );
27284        let PlanNode::Scan(right_scan) = right.as_ref() else {
27285            panic!("expected class scan on the right, got {right:?}");
27286        };
27287        // Identity-fold grounded the probe's ?b slot — grounding supersedes
27288        // claiming, so the probe stays unmarked at its honest catalog price.
27289        assert_eq!(right_scan.produced_row_count_estimate, 910_224);
27290        assert!(
27291            right_scan.broadcasted.is_none(),
27292            "grounded key slot must not be claimed, got {:?}",
27293            right_scan.broadcasted
27294        );
27295        let text = explain_est(painting_identity_fold_sparql(), Some(&profile));
27296        assert!(
27297            text.contains("(domain ?b 1)"),
27298            "grounded join key domain is 1: {text}"
27299        );
27300    }
27301
27302    // ---- restamp_broadcast_marks -------------------------------------------
27303
27304    /// A scan `?<subject> <predicate> ?<object>` with both ends variable-bound.
27305    fn var_scan(subject: Option<&str>, predicate: &str, object: Option<&str>, rows: u64) -> ScanOp {
27306        ScanOp {
27307            ancestor_push_return_bound: None,
27308            fetch_once: None,
27309            pattern: EncodedTriplePattern {
27310                subject: None,
27311                predicate: Some(EncodedTerm::from(&NamedNode::new(predicate).unwrap())),
27312                object: None,
27313                graph_name: None,
27314            },
27315            subject: subject.map(|v| Variable::new(v).unwrap()),
27316            predicate: None,
27317            object: object.map(|v| Variable::new(v).unwrap()),
27318            graph: None,
27319            produced_row_count_estimate: rows,
27320            broadcasted: None,
27321            graph_filter: None,
27322            grounded: Vec::new(),
27323            merge_default_graph: false,
27324            marks: Vec::new(),
27325            domain_scan: None,
27326            head_scan: None,
27327            head_scan_counts: None,
27328            domain_counts: None,
27329            iri_only: Vec::new(),
27330            eager: Vec::new(),
27331            join_domains: crate::plan::JoinDomainStamps::default(),
27332        }
27333    }
27334
27335    fn values_node(var: &str, terms: &[&str]) -> PlanNode {
27336        PlanNode::Values(ValuesOp {
27337            variables: vec![Variable::new(var).unwrap()],
27338            rows: terms
27339                .iter()
27340                .map(|t| vec![Some(EncodedTerm::from(&NamedNode::new(*t).unwrap()))])
27341                .collect(),
27342            strings: Vec::new(),
27343            blobs: Vec::new(),
27344        })
27345    }
27346
27347    fn broadcast_join(left: PlanNode, right: PlanNode, keys: &[&str], rows: u64) -> PlanNode {
27348        PlanNode::Join {
27349            left: Box::new(left),
27350            right: Box::new(right),
27351            hash_keys: keys.iter().map(|k| Variable::new(*k).unwrap()).collect(),
27352            probe_key_domains: Vec::new(),
27353            probe_key_overlap_milli: Vec::new(),
27354            rhs_hostable_keys: Vec::new().into(),
27355            meta: JoinMeta {
27356                semi_gate: None,
27357                star_arms: None,
27358                strategy: JoinStrategy::Broadcast,
27359                produced_row_count_estimate: rows,
27360                own_push_removed_row_count_estimate: rows,
27361            },
27362        }
27363    }
27364
27365    fn left_join_node(left: PlanNode, right: PlanNode, keys: &[&str], rows: u64) -> PlanNode {
27366        PlanNode::LeftJoin {
27367            left: Box::new(left),
27368            right: Box::new(right),
27369            hash_keys: keys.iter().map(|k| Variable::new(*k).unwrap()).collect(),
27370            probe_key_domains: Vec::new(),
27371            probe_key_overlap_milli: Vec::new(),
27372            early_filter: None,
27373            residual_filter: None,
27374            meta: LeftJoinMeta {
27375                produced_row_count_estimate: rows,
27376                own_push_removed_row_count_estimate: rows,
27377            },
27378        }
27379    }
27380
27381    /// Pre-order makes "already marked" mean "an outer join claimed it": the
27382    /// same shared scan names the OUTER join's key when nested, and the inner
27383    /// join's key when it stands alone. This pins the walk order the
27384    /// claim-skip rule is load-bearing on.
27385    #[test]
27386    fn restamp_claims_outermost_join_first() {
27387        // Outer keys [?y], inner keys [?z]; the shared scan `?y :p ?z` hosts
27388        // both. Control tree: the inner join alone claims ?z.
27389        let inner_alone = broadcast_join(
27390            values_node("z", &["http://ex/z1", "http://ex/z2"]),
27391            PlanNode::Scan(var_scan(Some("y"), "http://ex/p", Some("z"), 1_000)),
27392            &["z"],
27393            100,
27394        );
27395        let mut control = inner_alone;
27396        restamp_broadcast_marks(&mut control, None);
27397        let PlanNode::Join { right, .. } = &control else {
27398            panic!("expected Join, got {control:?}")
27399        };
27400        let PlanNode::Scan(scan) = right.as_ref() else {
27401            panic!("expected Scan probe, got {right:?}")
27402        };
27403        assert_eq!(
27404            scan.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
27405            Some(("z", PatternSlot::Object)),
27406            "inner join alone claims its own key: {:?}",
27407            scan.broadcasted
27408        );
27409
27410        // Nested tree: the outer claim descends into the inner join and
27411        // claims the shared scan first; the inner claim then skips it.
27412        let inner = broadcast_join(
27413            values_node("z", &["http://ex/z1", "http://ex/z2"]),
27414            PlanNode::Scan(var_scan(Some("y"), "http://ex/p", Some("z"), 1_000)),
27415            &["z"],
27416            100,
27417        );
27418        let mut nested = broadcast_join(
27419            values_node("y", &["http://ex/y1", "http://ex/y2"]),
27420            inner,
27421            &["y"],
27422            10,
27423        );
27424        restamp_broadcast_marks(&mut nested, None);
27425        let mut shared: Option<&ScanOp> = None;
27426        for_each_scan(&nested, &mut |scan| {
27427            if scan.broadcasted.is_some() {
27428                assert!(shared.is_none(), "exactly one claimed scan: {nested:?}");
27429                shared = Some(scan);
27430            }
27431        });
27432        let shared = shared.expect("the shared scan is claimed exactly once");
27433        assert_eq!(
27434            shared.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
27435            Some(("y", PatternSlot::Subject)),
27436            "the OUTER join's key wins the claim: {:?}",
27437            shared.broadcasted
27438        );
27439        assert_eq!(
27440            shared.produced_row_count_estimate, 2,
27441            "claim-clamp prices the probe at the driver's key domain"
27442        );
27443    }
27444
27445    /// A claim may lower a probe's estimate, never raise it — the property
27446    /// that lets claims fire unconditionally in any pass state.
27447    #[test]
27448    fn claim_clamp_is_monotone_min() {
27449        // Driver pushes 3 distinct values: a 10-row probe lowers to 3, a
27450        // 2-row probe (already cheaper than the list) stays at 2.
27451        let mut big = broadcast_join(
27452            values_node("b", &["http://ex/k1", "http://ex/k2", "http://ex/k3"]),
27453            PlanNode::Scan(var_scan(Some("b"), "http://ex/p", Some("c"), 10)),
27454            &["b"],
27455            10,
27456        );
27457        restamp_broadcast_marks(&mut big, None);
27458        let PlanNode::Join { right, .. } = &big else {
27459            panic!("expected Join, got {big:?}")
27460        };
27461        let PlanNode::Scan(scan) = right.as_ref() else {
27462            panic!("expected Scan probe, got {right:?}")
27463        };
27464        assert_eq!(
27465            scan.produced_row_count_estimate, 3,
27466            "clamp lowers to the key domain"
27467        );
27468
27469        let mut small = broadcast_join(
27470            values_node("b", &["http://ex/k1", "http://ex/k2", "http://ex/k3"]),
27471            PlanNode::Scan(var_scan(Some("b"), "http://ex/p", Some("c"), 2)),
27472            &["b"],
27473            2,
27474        );
27475        restamp_broadcast_marks(&mut small, None);
27476        let PlanNode::Join { right, .. } = &small else {
27477            panic!("expected Join, got {small:?}")
27478        };
27479        let PlanNode::Scan(scan) = right.as_ref() else {
27480            panic!("expected Scan probe, got {right:?}")
27481        };
27482        assert_eq!(
27483            scan.produced_row_count_estimate, 2,
27484            "a clamp must never RAISE a cheaper exact estimate"
27485        );
27486        assert!(scan.broadcasted.is_some(), "still claimed");
27487    }
27488
27489    /// Fan-out-aware bound, pinned directly on the helper: pushed values ×
27490    /// the scan's own average rows per key value (price / key domain),
27491    /// capped by the price; unknown probe-side domain collapses to the
27492    /// values-broadcast bound.
27493    #[test]
27494    fn pushed_scan_return_bound_multiplies_fan_out() {
27495        let klass = EncodedTerm::from(&NamedNode::new("http://ex/Klass").unwrap());
27496        let klass_domain = |count: u64| {
27497            let mut profile = StatsProfile::default();
27498            profile
27499                .class_counts
27500                .insert(StrHash::new("http://ex/Klass"), count);
27501            profile
27502        };
27503        // `?class a <Klass>`: subject domain is the exact class count.
27504        let class_type_scan = |price: u64| ScanOp {
27505            ancestor_push_return_bound: None,
27506            fetch_once: None,
27507            pattern: EncodedTriplePattern {
27508                subject: None,
27509                predicate: Some(RDF_TYPE.clone()),
27510                object: Some(klass.clone()),
27511                graph_name: None,
27512            },
27513            subject: Some(var("class")),
27514            predicate: None,
27515            object: None,
27516            graph: None,
27517            produced_row_count_estimate: price,
27518            broadcasted: None,
27519            graph_filter: None,
27520            grounded: Vec::new(),
27521            merge_default_graph: false,
27522            marks: vec![(var("class"), Liveness::Live, BagMark::Sensitive)],
27523            domain_scan: None,
27524            head_scan: None,
27525            head_scan_counts: None,
27526            domain_counts: None,
27527            iri_only: Vec::new(),
27528            eager: Vec::new(),
27529            join_domains: crate::plan::JoinDomainStamps::default(),
27530        };
27531        let key = var("class");
27532        // 1,000 classes over 5,000 rows → 5 rows per key; 100 pushed values
27533        // → 500 rows back.
27534        assert_eq!(
27535            pushed_scan_return_bound(
27536                100,
27537                5_000,
27538                &class_type_scan(5_000),
27539                &key,
27540                Some(&klass_domain(1_000))
27541            ),
27542            500
27543        );
27544        // Containment cap: 500 pushed values × (1,000 / 2 per key) = 250k,
27545        // but the scan only HAS 1,000 rows.
27546        assert_eq!(
27547            pushed_scan_return_bound(
27548                500,
27549                1_000,
27550                &class_type_scan(1_000),
27551                &key,
27552                Some(&klass_domain(2))
27553            ),
27554            1_000
27555        );
27556        // Pushed beyond the price: 10k keys × 0.1 rows/key, still capped.
27557        assert_eq!(
27558            pushed_scan_return_bound(
27559                10_000,
27560                100,
27561                &class_type_scan(100),
27562                &key,
27563                Some(&klass_domain(1_000))
27564            ),
27565            100
27566        );
27567        // Unknown probe-side domain (unprofiled predicate, no HLL): the
27568        // values-broadcast bound stands.
27569        let unprofiled = var_scan(Some("class"), "http://ex/other", None, 100);
27570        assert_eq!(
27571            pushed_scan_return_bound(10, 100, &unprofiled, &key, None),
27572            10,
27573            "no probe domain → fan-out 1 → min(price, pushed values)"
27574        );
27575    }
27576
27577    /// The worked label example as a regression: a probe whose average
27578    /// rows per pushed key is huge (~34 labels per class) must price at
27579    /// ROWS — its price, under containment — not at pushed VALUES. The
27580    /// values-broadcast clamp answered 21,124 against a real ~376k return.
27581    /// The worked class-hierarchy shape: two independent optionals with
27582    /// wildly different fan-outs (~34 labels per class vs ~1.3 parents).
27583    /// The planner rotates the small-fan-out subClassOf optional into the
27584    /// inner slot — the engine-measured −11% ordering.
27585    #[test]
27586    fn independent_optionals_rotate_small_fanout_first() {
27587        let mut profile = StatsProfile::default();
27588        profile
27589            .class_counts
27590            .insert(StrHash::new("http://ex/Klass"), 21_124);
27591        profile
27592            .predicate_counts
27593            .insert(StrHash::new("http://ex/label"), 376_482);
27594        profile
27595            .subjects_per_predicate
27596            .insert(StrHash::new("http://ex/label"), hll_with_n(11_025));
27597        profile
27598            .predicate_counts
27599            .insert(StrHash::new("http://ex/sub"), 13_968);
27600        profile
27601            .subjects_per_predicate
27602            .insert(StrHash::new("http://ex/sub"), hll_with_n(10_718));
27603        profile.total_puts = 500_000;
27604        let sparql = r#"
27605            SELECT ?class ?label ?parent WHERE {
27606              ?class a <http://ex/Klass> .
27607              OPTIONAL { ?class <http://ex/label> ?label }
27608              OPTIONAL { ?class <http://ex/sub> ?parent }
27609            }
27610        "#;
27611        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
27612        // The outermost LeftJoin: its right arm must be the LABEL scan
27613        // (query order had it inner) and its inner left join's right arm
27614        // the subClassOf scan.
27615        let outer = outermost_left_join(&plan.root);
27616        let PlanNode::LeftJoin {
27617            left: inner_join,
27618            right: outer_right,
27619            ..
27620        } = outer
27621        else {
27622            panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
27623        };
27624        // Compare by row shape: the outer right must be the 376,482-row
27625        // label scan, the inner left join's right the 13,968-row subClassOf
27626        // scan.
27627        let outer_rows = outer_right.produced_row_count_estimate();
27628        assert!(
27629            outer_rows >= 300_000,
27630            "outer optional must be the label side (~376k), got {outer_rows}: {outer_right:#?}"
27631        );
27632        let PlanNode::LeftJoin {
27633            right: inner_right,
27634            meta: inner_meta,
27635            ..
27636        } = inner_join.as_ref()
27637        else {
27638            panic!("expected the rotated inner LeftJoin, got {inner_join:#?}")
27639        };
27640        let inner_rows = inner_right.produced_row_count_estimate();
27641        assert!(
27642            inner_rows <= 20_000,
27643            "inner optional must be the subClassOf side (~14k), got {inner_rows}"
27644        );
27645        // The rotated inner's estimate: (|L| − dom_sub) + |sub rows|, with
27646        // the live HLL cardinality for dom_sub.
27647        let card_sub = profile
27648            .subjects_per_predicate
27649            .get(&StrHash::new("http://ex/sub"))
27650            .map(|hll| hll.cardinality())
27651            .unwrap_or(10_718);
27652        let expected_inner = (21_124u64).saturating_sub(card_sub) + 13_968;
27653        assert_eq!(
27654            inner_meta.produced_row_count_estimate, expected_inner,
27655            "rotated inner prices at unmatched + subClassOf rows"
27656        );
27657    }
27658
27659    /// A required pattern written after an inflating OPTIONAL (3 emails
27660    /// per person): the required join currently runs against the
27661    /// OPTIONAL's ~3,000-row output; delaying re-unites the required
27662    /// side first (1,000-row join) and lets the OPTIONAL probe it.
27663    #[test]
27664    fn independent_optional_delays_past_later_required_pattern() {
27665        let mut profile = StatsProfile::default();
27666        profile
27667            .class_counts
27668            .insert(StrHash::new("http://ex/Person"), 1_000);
27669        profile
27670            .predicate_counts
27671            .insert(StrHash::new("http://ex/email"), 3_000);
27672        profile
27673            .subjects_per_predicate
27674            .insert(StrHash::new("http://ex/email"), hll_with_n(1_000));
27675        profile
27676            .predicate_counts
27677            .insert(StrHash::new("http://ex/worksIn"), 1_000);
27678        profile
27679            .subjects_per_predicate
27680            .insert(StrHash::new("http://ex/worksIn"), hll_with_n(1_000));
27681        profile.total_puts = 10_000;
27682        let sparql = r#"
27683            SELECT ?p ?email ?dept WHERE {
27684              ?p a <http://ex/Person> .
27685              OPTIONAL { ?p <http://ex/email> ?email }
27686              ?p <http://ex/worksIn> ?dept .
27687            }
27688        "#;
27689        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
27690        fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
27691            match node {
27692                PlanNode::Scan(scan) => {
27693                    scan.pattern.predicate.as_ref()
27694                        == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
27695                }
27696                PlanNode::Join { left, right, .. }
27697                | PlanNode::Union { left, right }
27698                | PlanNode::LeftJoin { left, right, .. } => {
27699                    scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
27700                }
27701                PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
27702                _ => false,
27703            }
27704        }
27705        let outer = outermost_left_join(&plan.root);
27706        let PlanNode::LeftJoin { left, right, .. } = outer else {
27707            panic!("expected the delayed LeftJoin, got {:#?}", plan.root)
27708        };
27709        assert!(
27710            scan_with_predicate(right, "http://ex/email"),
27711            "the OPTIONAL arm stays the outer right: {right:#?}"
27712        );
27713        assert!(
27714            scan_with_predicate(left, "http://ex/worksIn"),
27715            "the later required pattern moved under the required side: {left:#?}"
27716        );
27717        assert!(
27718            !scan_with_predicate(left, "http://ex/email"),
27719            "no email scan below the delay: {left:#?}"
27720        );
27721    }
27722
27723    /// The delay fires through the full refinalize round (either
27724    /// orientation — the arm swap may put the LeftJoin on the right)
27725    /// and the boundary schema is unchanged set-wise.
27726    #[test]
27727    fn independent_optional_delays_and_keeps_the_boundary_schema() {
27728        let mut profile = StatsProfile::default();
27729        profile
27730            .predicate_counts
27731            .insert(StrHash::new("http://ex/kind"), 100);
27732        profile
27733            .predicate_counts
27734            .insert(StrHash::new("http://ex/email"), 300);
27735        profile
27736            .predicate_counts
27737            .insert(StrHash::new("http://ex/worksIn"), 100);
27738        profile
27739            .subjects_per_predicate
27740            .insert(StrHash::new("http://ex/kind"), hll_with_n(100));
27741        profile
27742            .subjects_per_predicate
27743            .insert(StrHash::new("http://ex/email"), hll_with_n(100));
27744        profile
27745            .subjects_per_predicate
27746            .insert(StrHash::new("http://ex/worksIn"), hll_with_n(100));
27747        profile.total_puts = 1_000;
27748        let mut node = PlanNode::Join {
27749            left: Box::new(left_join_node(
27750                PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
27751                PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
27752                &["p"],
27753                300,
27754            )),
27755            right: Box::new(PlanNode::Scan(var_scan(
27756                Some("p"),
27757                "http://ex/worksIn",
27758                Some("d"),
27759                100,
27760            ))),
27761            hash_keys: vec![var("p")],
27762            probe_key_domains: Vec::new(),
27763            probe_key_overlap_milli: Vec::new(),
27764            rhs_hostable_keys: Vec::new().into(),
27765            meta: JoinMeta {
27766                semi_gate: None,
27767                star_arms: None,
27768                strategy: JoinStrategy::Hash,
27769                produced_row_count_estimate: 300,
27770                own_push_removed_row_count_estimate: 300,
27771            },
27772        };
27773        refinalize_joins_without_ctx(&mut node, Some(&profile));
27774        let PlanNode::LeftJoin { left, right, .. } = &node else {
27775            panic!("expected the delayed LeftJoin, got {node:#?}")
27776        };
27777        assert!(
27778            matches!(right.as_ref(), PlanNode::Scan(scan) if scan.pattern.predicate.as_ref()
27779                == Some(&EncodedTerm::from(&NamedNode::new("http://ex/email").unwrap()))),
27780            "the OPTIONAL arm stays the outer right: {right:#?}"
27781        );
27782        assert!(
27783            matches!(left.as_ref(), PlanNode::Join { .. }),
27784            "the required side re-united as a Join: {left:#?}"
27785        );
27786        let after = node.output_vars();
27787        // Hand-built pre-state: always {?p,?k,?d}, maybe {?e} — the delay
27788        // must return the same sets (order can differ with the swap).
27789        let mut always: Vec<&str> = after.always_bound.iter().map(Variable::as_str).collect();
27790        let mut maybe: Vec<&str> = after.maybe_unbound.iter().map(Variable::as_str).collect();
27791        always.sort_unstable();
27792        maybe.sort_unstable();
27793        assert_eq!(
27794            (always, maybe),
27795            (vec!["d", "k", "p"], vec!["e"]),
27796            "boundary schema unchanged by the delay"
27797        );
27798    }
27799
27800    /// R's subtree reads `?email` — a variable the OPTIONAL first-binds —
27801    /// so the pair is §2.11-dependent and the OPTIONAL must stay put: an
27802    /// R below O would execute before O binds what it reads.
27803    #[test]
27804    fn optional_delay_blocked_when_required_mentions_optional_var() {
27805        let mut profile = StatsProfile::default();
27806        profile
27807            .class_counts
27808            .insert(StrHash::new("http://ex/Person"), 1_000);
27809        profile
27810            .predicate_counts
27811            .insert(StrHash::new("http://ex/email"), 3_000);
27812        profile
27813            .subjects_per_predicate
27814            .insert(StrHash::new("http://ex/email"), hll_with_n(1_000));
27815        profile
27816            .predicate_counts
27817            .insert(StrHash::new("http://ex/worksIn"), 1_000);
27818        profile
27819            .subjects_per_predicate
27820            .insert(StrHash::new("http://ex/worksIn"), hll_with_n(1_000));
27821        profile
27822            .predicate_counts
27823            .insert(StrHash::new("http://ex/x"), 500);
27824        profile.total_puts = 10_000;
27825        let sparql = r#"
27826            SELECT ?p ?email ?y WHERE {
27827              ?p a <http://ex/Person> .
27828              OPTIONAL { ?p <http://ex/email> ?email }
27829              ?p <http://ex/worksIn> ?dept .
27830              ?email <http://ex/x> ?y .
27831            }
27832        "#;
27833        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
27834        fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
27835            match node {
27836                PlanNode::Scan(scan) => {
27837                    scan.pattern.predicate.as_ref()
27838                        == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
27839                }
27840                PlanNode::Join { left, right, .. }
27841                | PlanNode::Union { left, right }
27842                | PlanNode::LeftJoin { left, right, .. } => {
27843                    scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
27844                }
27845                PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
27846                _ => false,
27847            }
27848        }
27849        let outer = outermost_left_join(&plan.root);
27850        let PlanNode::LeftJoin { left, .. } = outer else {
27851            panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
27852        };
27853        assert!(
27854            !scan_with_predicate(left, "http://ex/worksIn"),
27855            "the required pattern reading ?email must stay ABOVE the optional: {left:#?}"
27856        );
27857    }
27858
27859    /// The OPTIONAL's keys must be bound by the required side alone — a
27860    /// hand-built key outside `always_bound(L)` refuses the rewrite.
27861    #[test]
27862    fn optional_delay_blocked_when_optional_key_not_bound_by_left() {
27863        let mut node = PlanNode::Join {
27864            left: Box::new(left_join_node(
27865                PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
27866                PlanNode::Scan(var_scan(Some("x"), "http://ex/email", Some("e"), 300)),
27867                &["x"],
27868                300,
27869            )),
27870            right: Box::new(PlanNode::Scan(var_scan(
27871                Some("p"),
27872                "http://ex/worksIn",
27873                Some("d"),
27874                100,
27875            ))),
27876            hash_keys: vec![var("p")],
27877            probe_key_domains: Vec::new(),
27878            probe_key_overlap_milli: Vec::new(),
27879            rhs_hostable_keys: Vec::new().into(),
27880            meta: JoinMeta {
27881                semi_gate: None,
27882                star_arms: None,
27883                strategy: JoinStrategy::Hash,
27884                produced_row_count_estimate: 300,
27885                own_push_removed_row_count_estimate: 300,
27886            },
27887        };
27888        assert!(
27889            !delay_optional_through_join(&mut node, None),
27890            "?x is not bound by the required side"
27891        );
27892        assert!(matches!(node, PlanNode::Join { .. }), "shape unchanged");
27893    }
27894
27895    /// A 1:1 OPTIONAL inflates nothing (both stage sums equal): the
27896    /// 15% strict-improvement margin declines the rewrite.
27897    #[test]
27898    fn optional_delay_blocked_within_margin() {
27899        let mut profile = StatsProfile::default();
27900        profile
27901            .predicate_counts
27902            .insert(StrHash::new("http://ex/kind"), 100);
27903        profile
27904            .predicate_counts
27905            .insert(StrHash::new("http://ex/email"), 100);
27906        profile
27907            .predicate_counts
27908            .insert(StrHash::new("http://ex/worksIn"), 100);
27909        profile
27910            .subjects_per_predicate
27911            .insert(StrHash::new("http://ex/kind"), hll_with_n(100));
27912        profile
27913            .subjects_per_predicate
27914            .insert(StrHash::new("http://ex/email"), hll_with_n(100));
27915        profile
27916            .subjects_per_predicate
27917            .insert(StrHash::new("http://ex/worksIn"), hll_with_n(100));
27918        profile.total_puts = 1_000;
27919        let mut node = PlanNode::Join {
27920            left: Box::new(left_join_node(
27921                PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
27922                PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 100)),
27923                &["p"],
27924                100,
27925            )),
27926            right: Box::new(PlanNode::Scan(var_scan(
27927                Some("p"),
27928                "http://ex/worksIn",
27929                Some("d"),
27930                100,
27931            ))),
27932            hash_keys: vec![var("p")],
27933            probe_key_domains: Vec::new(),
27934            probe_key_overlap_milli: Vec::new(),
27935            rhs_hostable_keys: Vec::new().into(),
27936            meta: JoinMeta {
27937                semi_gate: None,
27938                star_arms: None,
27939                strategy: JoinStrategy::Hash,
27940                produced_row_count_estimate: 100,
27941                own_push_removed_row_count_estimate: 100,
27942            },
27943        };
27944        refinalize_joins_without_ctx(&mut node, Some(&profile));
27945        assert!(
27946            matches!(node, PlanNode::Join { .. }),
27947            "equal stage sums: the margin must decline, got {node:#?}"
27948        );
27949    }
27950
27951    /// §2.11's vacuous share: R joins with nothing on L (the outer join
27952    /// has no hash keys). Delaying would seat that cartesian on the
27953    /// OPTIONAL's required side, where its rows also form the
27954    /// pass-through floor.
27955    #[test]
27956    fn optional_delay_blocked_when_required_shares_nothing() {
27957        let mut node = PlanNode::Join {
27958            left: Box::new(left_join_node(
27959                PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
27960                PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
27961                &["p"],
27962                300,
27963            )),
27964            right: Box::new(PlanNode::Scan(var_scan(
27965                Some("z"),
27966                "http://ex/q",
27967                Some("w"),
27968                50,
27969            ))),
27970            hash_keys: Vec::new(),
27971            probe_key_domains: Vec::new(),
27972            probe_key_overlap_milli: Vec::new(),
27973            rhs_hostable_keys: Vec::new().into(),
27974            meta: JoinMeta {
27975                semi_gate: None,
27976                star_arms: None,
27977                strategy: JoinStrategy::Hash,
27978                produced_row_count_estimate: 15_000,
27979                own_push_removed_row_count_estimate: 15_000,
27980            },
27981        };
27982        let _ = &mut node;
27983        assert!(
27984            !delay_optional_through_join(&mut node, None),
27985            "a cartesian R must not move under the OPTIONAL"
27986        );
27987        assert!(matches!(node, PlanNode::Join { .. }), "shape unchanged");
27988    }
27989
27990    /// The OPTIONAL's FILTER reads `?dept` — bound only by the later
27991    /// required pattern. In the current shape the filter evaluates with
27992    /// ?dept unbound (error → every row a miss); delayed it would see
27993    /// real values, a different multiset. The gate must keep the
27994    /// OPTIONAL put.
27995    #[test]
27996    fn optional_delay_blocked_when_filter_reads_required_side_var() {
27997        let mut profile = StatsProfile::default();
27998        profile
27999            .class_counts
28000            .insert(StrHash::new("http://ex/Person"), 1_000);
28001        profile
28002            .predicate_counts
28003            .insert(StrHash::new("http://ex/email"), 3_000);
28004        profile
28005            .subjects_per_predicate
28006            .insert(StrHash::new("http://ex/email"), hll_with_n(1_000));
28007        profile
28008            .predicate_counts
28009            .insert(StrHash::new("http://ex/worksIn"), 1_000);
28010        profile
28011            .subjects_per_predicate
28012            .insert(StrHash::new("http://ex/worksIn"), hll_with_n(1_000));
28013        profile.total_puts = 10_000;
28014        let sparql = r#"
28015            SELECT ?p ?email ?dept WHERE {
28016              ?p a <http://ex/Person> .
28017              OPTIONAL { ?p <http://ex/email> ?email . FILTER(?email = ?dept) }
28018              ?p <http://ex/worksIn> ?dept .
28019            }
28020        "#;
28021        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28022        fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
28023            match node {
28024                PlanNode::Scan(scan) => {
28025                    scan.pattern.predicate.as_ref()
28026                        == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
28027                }
28028                PlanNode::Join { left, right, .. }
28029                | PlanNode::Union { left, right }
28030                | PlanNode::LeftJoin { left, right, .. } => {
28031                    scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
28032                }
28033                PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
28034                _ => false,
28035            }
28036        }
28037        let outer = outermost_left_join(&plan.root);
28038        let PlanNode::LeftJoin { left, .. } = outer else {
28039            panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
28040        };
28041        assert!(
28042            !scan_with_predicate(left, "http://ex/worksIn"),
28043            "a filter reading ?dept pins the OPTIONAL in place: {left:#?}"
28044        );
28045    }
28046
28047    /// §2.11 on UNION arms: the required side is a Union whose second
28048    /// arm reads `?email` (the OPTIONAL's first-bound variable) — the
28049    /// subtree walk must see through the Union and refuse.
28050    #[test]
28051    fn optional_delay_blocked_when_union_arm_mentions_optional_var() {
28052        let mut node = PlanNode::Join {
28053            left: Box::new(left_join_node(
28054                PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
28055                PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
28056                &["p"],
28057                300,
28058            )),
28059            right: Box::new(PlanNode::Union {
28060                left: Box::new(PlanNode::Scan(var_scan(
28061                    Some("p"),
28062                    "http://ex/worksIn",
28063                    Some("d"),
28064                    100,
28065                ))),
28066                right: Box::new(PlanNode::Scan(var_scan(
28067                    Some("e"),
28068                    "http://ex/x",
28069                    Some("y"),
28070                    500,
28071                ))),
28072            }),
28073            hash_keys: vec![var("p")],
28074            probe_key_domains: Vec::new(),
28075            probe_key_overlap_milli: Vec::new(),
28076            rhs_hostable_keys: Vec::new().into(),
28077            meta: JoinMeta {
28078                semi_gate: None,
28079                star_arms: None,
28080                strategy: JoinStrategy::Hash,
28081                produced_row_count_estimate: 300,
28082                own_push_removed_row_count_estimate: 300,
28083            },
28084        };
28085        assert!(
28086            !delay_optional_through_join(&mut node, None),
28087            "the Union arm reading ?email blocks the delay"
28088        );
28089        assert!(matches!(node, PlanNode::Join { .. }), "shape unchanged");
28090    }
28091
28092    /// Two required patterns after the OPTIONAL: post-order refinalize
28093    /// delays the inner join first, then the outer — the OPTIONAL
28094    /// bubbles above both in a single round.
28095    #[test]
28096    fn optional_delay_bubbles_across_two_joins() {
28097        let mut profile = StatsProfile::default();
28098        profile
28099            .predicate_counts
28100            .insert(StrHash::new("http://ex/kind"), 100);
28101        profile
28102            .predicate_counts
28103            .insert(StrHash::new("http://ex/email"), 300);
28104        profile
28105            .predicate_counts
28106            .insert(StrHash::new("http://ex/worksIn"), 100);
28107        profile
28108            .predicate_counts
28109            .insert(StrHash::new("http://ex/office"), 100);
28110        for predicate in [
28111            "http://ex/kind",
28112            "http://ex/email",
28113            "http://ex/worksIn",
28114            "http://ex/office",
28115        ] {
28116            profile
28117                .subjects_per_predicate
28118                .insert(StrHash::new(predicate), hll_with_n(100));
28119        }
28120        profile.total_puts = 1_000;
28121        let mut node = PlanNode::Join {
28122            left: Box::new(PlanNode::Join {
28123                left: Box::new(left_join_node(
28124                    PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
28125                    PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
28126                    &["p"],
28127                    300,
28128                )),
28129                right: Box::new(PlanNode::Scan(var_scan(
28130                    Some("p"),
28131                    "http://ex/worksIn",
28132                    Some("d"),
28133                    100,
28134                ))),
28135                hash_keys: vec![var("p")],
28136                probe_key_domains: Vec::new(),
28137                probe_key_overlap_milli: Vec::new(),
28138                rhs_hostable_keys: Vec::new().into(),
28139                meta: JoinMeta {
28140                    semi_gate: None,
28141                    star_arms: None,
28142                    strategy: JoinStrategy::Hash,
28143                    produced_row_count_estimate: 300,
28144                    own_push_removed_row_count_estimate: 300,
28145                },
28146            }),
28147            right: Box::new(PlanNode::Scan(var_scan(
28148                Some("p"),
28149                "http://ex/office",
28150                Some("off"),
28151                100,
28152            ))),
28153            hash_keys: vec![var("p")],
28154            probe_key_domains: Vec::new(),
28155            probe_key_overlap_milli: Vec::new(),
28156            rhs_hostable_keys: Vec::new().into(),
28157            meta: JoinMeta {
28158                semi_gate: None,
28159                star_arms: None,
28160                strategy: JoinStrategy::Hash,
28161                produced_row_count_estimate: 300,
28162                own_push_removed_row_count_estimate: 300,
28163            },
28164        };
28165        refinalize_joins_without_ctx(&mut node, Some(&profile));
28166        fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
28167            match node {
28168                PlanNode::Scan(scan) => {
28169                    scan.pattern.predicate.as_ref()
28170                        == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
28171                }
28172                PlanNode::Join { left, right, .. }
28173                | PlanNode::Union { left, right }
28174                | PlanNode::LeftJoin { left, right, .. } => {
28175                    scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
28176                }
28177                PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
28178                _ => false,
28179            }
28180        }
28181        let PlanNode::LeftJoin { left, right, .. } = &node else {
28182            panic!("expected the bubbled LeftJoin, got {node:#?}")
28183        };
28184        assert!(
28185            scan_with_predicate(right, "http://ex/email"),
28186            "the OPTIONAL stays the outer right: {right:#?}"
28187        );
28188        assert!(
28189            scan_with_predicate(left, "http://ex/worksIn")
28190                && scan_with_predicate(left, "http://ex/office"),
28191            "both later required patterns joined under the required side: {left:#?}"
28192        );
28193    }
28194
28195    /// Marks regression: a Broadcast outer join with the LeftJoin side
28196    /// as its PROBE claims scans inside L (claim_broadcast_probe's
28197    /// LeftJoin descent). The delay dissolves that join, and since the
28198    /// boundary restamp is claim-skip — an existing mark blocks a new
28199    /// claim and is never replaced — only the rewrite's
28200    /// `clear_broadcast_marks` on L's clone can retire the stale mark.
28201    /// Plant one by hand (what the pre-round restamp would have left),
28202    /// fire the delay, restamp, and assert L's scan stays unclaimed:
28203    /// the new inner join drives from L (100 < 200 rows), so its claim
28204    /// lands on the R probe instead — nothing legitimately re-claims
28205    /// the kind scan.
28206    #[test]
28207    fn delay_clears_the_dissolved_join_claims_on_the_required_side() {
28208        let mut profile = StatsProfile::default();
28209        profile
28210            .predicate_counts
28211            .insert(StrHash::new("http://ex/kind"), 100);
28212        profile
28213            .predicate_counts
28214            .insert(StrHash::new("http://ex/email"), 300);
28215        profile
28216            .predicate_counts
28217            .insert(StrHash::new("http://ex/worksIn"), 200);
28218        profile
28219            .subjects_per_predicate
28220            .insert(StrHash::new("http://ex/kind"), hll_with_n(100));
28221        profile
28222            .subjects_per_predicate
28223            .insert(StrHash::new("http://ex/email"), hll_with_n(100));
28224        profile
28225            .subjects_per_predicate
28226            .insert(StrHash::new("http://ex/worksIn"), hll_with_n(200));
28227        profile.total_puts = 1_000;
28228        let mut node = PlanNode::Join {
28229            left: Box::new(left_join_node(
28230                PlanNode::Scan(var_scan(Some("p"), "http://ex/kind", Some("k"), 100)),
28231                PlanNode::Scan(var_scan(Some("p"), "http://ex/email", Some("e"), 300)),
28232                &["p"],
28233                300,
28234            )),
28235            right: Box::new(PlanNode::Scan(var_scan(
28236                Some("p"),
28237                "http://ex/worksIn",
28238                Some("d"),
28239                200,
28240            ))),
28241            hash_keys: vec![var("p")],
28242            probe_key_domains: Vec::new(),
28243            probe_key_overlap_milli: Vec::new(),
28244            rhs_hostable_keys: Vec::new().into(),
28245            meta: JoinMeta {
28246                semi_gate: None,
28247                star_arms: None,
28248                strategy: JoinStrategy::Hash,
28249                produced_row_count_estimate: 300,
28250                own_push_removed_row_count_estimate: 300,
28251            },
28252        };
28253        // Plant the dissolved outer join's claim on L's scan, as the
28254        // pre-round boundary restamp would have stamped it.
28255        if let PlanNode::Join { left, .. } = &mut node
28256            && let PlanNode::LeftJoin { left, .. } = left.as_mut()
28257            && let PlanNode::Scan(scan) = left.as_mut()
28258        {
28259            scan.broadcasted = Some((var("p"), PatternSlot::Subject));
28260        }
28261        refinalize_joins_without_ctx(&mut node, Some(&profile));
28262        restamp_broadcast_marks(&mut node, Some(&profile));
28263        let PlanNode::LeftJoin { left: inner, .. } = &node else {
28264            panic!("expected the delayed LeftJoin, got {node:#?}")
28265        };
28266        fn find_scan<'a>(node: &'a PlanNode, predicate: &str) -> Option<&'a ScanOp> {
28267            match node {
28268                PlanNode::Scan(scan)
28269                    if scan.pattern.predicate.as_ref()
28270                        == Some(&EncodedTerm::from(&NamedNode::new(predicate).unwrap())) =>
28271                {
28272                    Some(scan)
28273                }
28274                PlanNode::Join { left, right, .. }
28275                | PlanNode::Union { left, right }
28276                | PlanNode::LeftJoin { left, right, .. } => {
28277                    find_scan(left, predicate).or_else(|| find_scan(right, predicate))
28278                }
28279                PlanNode::Filter { inner, .. } => find_scan(inner, predicate),
28280                _ => None,
28281            }
28282        }
28283        let kind = find_scan(inner, "http://ex/kind")
28284            .expect("the kind scan moved under the required side");
28285        assert!(
28286            kind.broadcasted.is_none(),
28287            "the dissolved join's claim must be retired, not preserved by \
28288             claim-skip: {:?}",
28289            kind.broadcasted
28290        );
28291        let works_in = find_scan(inner, "http://ex/worksIn")
28292            .expect("the worksIn scan joined under the required side");
28293        assert_eq!(
28294            works_in.broadcasted.as_ref().map(|(v, _)| v.as_str()),
28295            Some("p"),
28296            "sanity: the new inner join claims its own probe, so the \
28297             unmarked kind scan is not just a silent restamp"
28298        );
28299    }
28300
28301    /// Three independent OPTIONALs in the worst query order (big-fan-out
28302    /// label first): the suffix-greedy rebuild puts the flattest arms
28303    /// first in one shot — sub (fan ~0.66) innermost, note (fan ~2)
28304    /// middle, label (fan ~34) outermost — where the old adjacent-pair
28305    /// bubble could not have reached this order in two rounds.
28306    #[test]
28307    fn suffix_greedy_orders_three_arms() {
28308        let mut profile = StatsProfile::default();
28309        profile
28310            .class_counts
28311            .insert(StrHash::new("http://ex/Klass"), 21_124);
28312        for (predicate, rows, subjects) in [
28313            ("http://ex/label", 376_482, 11_025),
28314            ("http://ex/sub", 13_968, 10_718),
28315            ("http://ex/note", 42_000, 21_000),
28316        ] {
28317            profile
28318                .predicate_counts
28319                .insert(StrHash::new(predicate), rows);
28320            profile
28321                .subjects_per_predicate
28322                .insert(StrHash::new(predicate), hll_with_n(subjects));
28323        }
28324        profile.total_puts = 500_000;
28325        let sparql = r#"
28326            SELECT ?class ?label ?parent ?note WHERE {
28327              ?class a <http://ex/Klass> .
28328              OPTIONAL { ?class <http://ex/label> ?label }
28329              OPTIONAL { ?class <http://ex/sub> ?parent }
28330              OPTIONAL { ?class <http://ex/note> ?note }
28331            }
28332        "#;
28333        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28334        let outer = outermost_left_join(&plan.root);
28335        // Outermost-first produced estimates of each arm down the spine.
28336        let mut whole_read_rows = Vec::new();
28337        let mut cursor = outer;
28338        while let PlanNode::LeftJoin { left, right, .. } = cursor {
28339            whole_read_rows.push(right.produced_row_count_estimate());
28340            cursor = left;
28341        }
28342        assert_eq!(
28343            whole_read_rows.len(),
28344            3,
28345            "all three arms on one spine: {outer:#?}"
28346        );
28347        assert!(
28348            whole_read_rows[0] >= 300_000,
28349            "outermost is the big-fan-out label side (~376k), got {:?}",
28350            whole_read_rows
28351        );
28352        assert!(
28353            (30_000..=100_000).contains(&whole_read_rows[1]),
28354            "middle is the note side (~42-48k), got {:?}",
28355            whole_read_rows
28356        );
28357        assert!(
28358            whole_read_rows[2] <= 25_000,
28359            "innermost is the sub side (~14k), got {:?}",
28360            whole_read_rows
28361        );
28362    }
28363
28364    /// The middle OPTIONAL's FILTER reads the FIRST optional's variable,
28365    /// so the first arm is frozen below the run: the top two reorder
28366    /// (tiny x before the fan-out multi), and the label arm stays
28367    /// innermost no matter what.
28368    #[test]
28369    fn suffix_reorder_stops_at_dependent_arm() {
28370        let mut profile = StatsProfile::default();
28371        profile
28372            .class_counts
28373            .insert(StrHash::new("http://ex/Klass"), 21_124);
28374        for (predicate, rows, subjects) in [
28375            ("http://ex/label", 376_482, 11_025),
28376            ("http://ex/multi", 200_000, 10_000),
28377            ("http://ex/x", 200, 100),
28378        ] {
28379            profile
28380                .predicate_counts
28381                .insert(StrHash::new(predicate), rows);
28382            profile
28383                .subjects_per_predicate
28384                .insert(StrHash::new(predicate), hll_with_n(subjects));
28385        }
28386        profile.total_puts = 500_000;
28387        let sparql = r#"
28388            SELECT ?class ?label ?m ?y WHERE {
28389              ?class a <http://ex/Klass> .
28390              OPTIONAL { ?class <http://ex/label> ?label }
28391              OPTIONAL { ?class <http://ex/multi> ?m }
28392              OPTIONAL { ?class <http://ex/x> ?y . FILTER(?y = ?label) }
28393            }
28394        "#;
28395        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28396        let outer = outermost_left_join(&plan.root);
28397        // Outermost-first: the arms' scan predicates down the spine.
28398        fn arm_predicate(node: &PlanNode) -> Option<String> {
28399            let PlanNode::Scan(scan) = node else {
28400                return None;
28401            };
28402            let predicate = scan.pattern.predicate.as_ref()?;
28403            Some(format!("{:?}", predicate))
28404        }
28405        let mut spine_predicates = Vec::new();
28406        let mut cursor = outer;
28407        while let PlanNode::LeftJoin { left, right, .. } = cursor {
28408            spine_predicates.push(arm_predicate(right));
28409            cursor = left;
28410        }
28411        // multi (outermost), x (middle), label (innermost — the run
28412        // stopped at the dependency, so label never moved above x).
28413        assert_eq!(spine_predicates.len(), 3, "{outer:#?}");
28414        assert!(
28415            spine_predicates[2].is_some(),
28416            "the depended-on label arm stays INNERMOST: {spine_predicates:?}"
28417        );
28418        assert!(
28419            spine_predicates[1].is_some() && spine_predicates[0].is_some(),
28420            "the run's two arms reordered above it: {spine_predicates:?}"
28421        );
28422        // The row-estimate fingerprint distinguishes them: outermost is
28423        // the fan-out multi (~200k), middle the tiny x (~200).
28424        let mut whole_read_rows = Vec::new();
28425        let mut cursor = outer;
28426        while let PlanNode::LeftJoin { left, right, .. } = cursor {
28427            whole_read_rows.push(right.produced_row_count_estimate());
28428            cursor = left;
28429        }
28430        assert!(
28431            whole_read_rows[0] >= 150_000 && whole_read_rows[1] <= 1_000,
28432            "greedy run order is x-then-multi: {whole_read_rows:?}"
28433        );
28434    }
28435
28436    /// Uniform fan-outs: every stage lands on the |L| floor, the stage
28437    /// sums tie, and the reorder declines — query order retained.
28438    #[test]
28439    fn suffix_reorder_keeps_order_within_margin() {
28440        let mut profile = StatsProfile::default();
28441        profile
28442            .class_counts
28443            .insert(StrHash::new("http://ex/Klass"), 21_124);
28444        for (predicate, rows, subjects) in [
28445            ("http://ex/p1", 21_000, 21_000),
28446            ("http://ex/p2", 20_000, 20_000),
28447            ("http://ex/p3", 19_000, 19_000),
28448        ] {
28449            profile
28450                .predicate_counts
28451                .insert(StrHash::new(predicate), rows);
28452            profile
28453                .subjects_per_predicate
28454                .insert(StrHash::new(predicate), hll_with_n(subjects));
28455        }
28456        profile.total_puts = 100_000;
28457        let sparql = r#"
28458            SELECT ?class ?a ?b ?c WHERE {
28459              ?class a <http://ex/Klass> .
28460              OPTIONAL { ?class <http://ex/p1> ?a }
28461              OPTIONAL { ?class <http://ex/p2> ?b }
28462              OPTIONAL { ?class <http://ex/p3> ?c }
28463            }
28464        "#;
28465        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28466        let outer = outermost_left_join(&plan.root);
28467        // Outermost-first produced estimates: query order kept means the
28468        // INNERMOST arm is p1 (first optional) and the outermost p3.
28469        let mut whole_read_rows = Vec::new();
28470        let mut cursor = outer;
28471        while let PlanNode::LeftJoin { left, right, .. } = cursor {
28472            whole_read_rows.push(right.produced_row_count_estimate());
28473            cursor = left;
28474        }
28475        assert_eq!(whole_read_rows.len(), 3, "{outer:#?}");
28476        assert!(
28477            whole_read_rows[0] <= whole_read_rows[2],
28478            "uniform fan-outs keep query order (p3 outermost, p1 \
28479             innermost): {whole_read_rows:?}"
28480        );
28481    }
28482
28483    /// Soundness: the later arm's FILTER reads `?y`, which the earlier
28484    /// arm produces only MAYBE-bound (a nested OPTIONAL inside it).
28485    /// Always-bound-only first-binding would call the pair independent
28486    /// and reorder B first — where the filter errors on every row and
28487    /// `?z` comes back unbound everywhere, a different multiset. The
28488    /// gate must count maybe-produced variables as dependencies and
28489    /// keep query order.
28490    #[test]
28491    fn maybe_bound_output_read_by_later_arm_blocks_reorder() {
28492        let mut profile = StatsProfile::default();
28493        profile
28494            .class_counts
28495            .insert(StrHash::new("http://ex/Klass"), 21_124);
28496        for (predicate, rows, subjects) in [
28497            ("http://ex/p", 200_000, 10_000),
28498            ("http://ex/q", 5_000, 5_000),
28499            ("http://ex/r", 200, 100),
28500        ] {
28501            profile
28502                .predicate_counts
28503                .insert(StrHash::new(predicate), rows);
28504            profile
28505                .subjects_per_predicate
28506                .insert(StrHash::new(predicate), hll_with_n(subjects));
28507        }
28508        profile.total_puts = 500_000;
28509        let sparql = r#"
28510            SELECT ?class ?x ?y ?z WHERE {
28511              ?class a <http://ex/Klass> .
28512              OPTIONAL { ?class <http://ex/p> ?x .
28513                         OPTIONAL { ?class <http://ex/q> ?y } }
28514              OPTIONAL { ?class <http://ex/r> ?z . FILTER(?z = ?y) }
28515            }
28516        "#;
28517        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28518        fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
28519            match node {
28520                PlanNode::Scan(scan) => {
28521                    scan.pattern.predicate.as_ref()
28522                        == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
28523                }
28524                PlanNode::Join { left, right, .. }
28525                | PlanNode::Union { left, right }
28526                | PlanNode::LeftJoin { left, right, .. } => {
28527                    scan_with_predicate(left, iri) || scan_with_predicate(right, iri)
28528                }
28529                PlanNode::Filter { inner, .. } => scan_with_predicate(inner, iri),
28530                _ => false,
28531            }
28532        }
28533        let outer = outermost_left_join(&plan.root);
28534        // Outermost-first right arms down the spine.
28535        let mut arms = Vec::new();
28536        let mut cursor = outer;
28537        while let PlanNode::LeftJoin { left, right, .. } = cursor {
28538            arms.push(right.as_ref());
28539            cursor = left;
28540        }
28541        assert_eq!(arms.len(), 2, "{outer:#?}");
28542        // Query order kept: the ?y-producing arm (with its nested q
28543        // optional) stays INNERMOST, the reading arm stays outermost —
28544        // the cheap-to-run-first temptation (r is 200 rows vs p's
28545        // 200,000) must not move the reader above the producer.
28546        assert!(
28547            scan_with_predicate(arms[0], "http://ex/r"),
28548            "outermost is the reading arm: {outer:#?}"
28549        );
28550        assert!(
28551            scan_with_predicate(arms[1], "http://ex/p")
28552                && scan_with_predicate(arms[1], "http://ex/q"),
28553            "innermost is the producing arm with its nested optional: {outer:#?}"
28554        );
28555    }
28556
28557    /// The second optional joins on `?label` — a variable the FIRST
28558    /// optional binds — so the pair is dependent and must keep query
28559    /// order.
28560    #[test]
28561    fn dependent_optional_key_blocks_rotation() {
28562        let mut profile = StatsProfile::default();
28563        profile
28564            .class_counts
28565            .insert(StrHash::new("http://ex/Klass"), 21_124);
28566        profile
28567            .predicate_counts
28568            .insert(StrHash::new("http://ex/label"), 376_482);
28569        profile
28570            .subjects_per_predicate
28571            .insert(StrHash::new("http://ex/label"), hll_with_n(11_025));
28572        profile
28573            .predicate_counts
28574            .insert(StrHash::new("http://ex/x"), 1_000);
28575        profile.total_puts = 500_000;
28576        let sparql = r#"
28577            SELECT ?class ?label ?y WHERE {
28578              ?class a <http://ex/Klass> .
28579              OPTIONAL { ?class <http://ex/label> ?label }
28580              OPTIONAL { ?label <http://ex/x> ?y }
28581            }
28582        "#;
28583        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28584        let outer = outermost_left_join(&plan.root);
28585        let PlanNode::LeftJoin {
28586            right: outer_right, ..
28587        } = outer
28588        else {
28589            panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
28590        };
28591        // Query order kept: the outer optional is the ?label-keyed scan
28592        // (small, 1,000 rows), NOT the big label side.
28593        assert!(
28594            outer_right.produced_row_count_estimate() <= 5_000,
28595            "dependent key (?label) must keep query order — outer stays the \
28596             small ?label-keyed arm, got {outer_right:#?}"
28597        );
28598    }
28599
28600    /// The second optional's FILTER references the first optional's
28601    /// variable — dependent even though the join key is independent.
28602    #[test]
28603    fn dependent_optional_filter_blocks_rotation() {
28604        let mut profile = StatsProfile::default();
28605        profile
28606            .class_counts
28607            .insert(StrHash::new("http://ex/Klass"), 21_124);
28608        profile
28609            .predicate_counts
28610            .insert(StrHash::new("http://ex/label"), 376_482);
28611        profile
28612            .subjects_per_predicate
28613            .insert(StrHash::new("http://ex/label"), hll_with_n(11_025));
28614        profile
28615            .predicate_counts
28616            .insert(StrHash::new("http://ex/sub"), 13_968);
28617        profile
28618            .subjects_per_predicate
28619            .insert(StrHash::new("http://ex/sub"), hll_with_n(10_718));
28620        profile.total_puts = 500_000;
28621        let sparql = r#"
28622            SELECT ?class ?label ?parent WHERE {
28623              ?class a <http://ex/Klass> .
28624              OPTIONAL { ?class <http://ex/label> ?label }
28625              OPTIONAL { ?class <http://ex/sub> ?parent . FILTER(?parent != ?label) }
28626            }
28627        "#;
28628        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28629        let outer = outermost_left_join(&plan.root);
28630        let PlanNode::LeftJoin {
28631            right: outer_right, ..
28632        } = outer
28633        else {
28634            panic!("expected the outermost LeftJoin, got {:#?}", plan.root)
28635        };
28636        // Query order kept: the label optional stays INNER, so the outer
28637        // right remains the ~14k subClassOf arm (a rotation would have put
28638        // the ~376k label arm here).
28639        assert!(
28640            outer_right.produced_row_count_estimate() <= 20_000,
28641            "FILTER referencing ?label makes the pair dependent — query order \
28642             keeps the subClassOf optional OUTER, got {outer_right:#?}"
28643        );
28644    }
28645
28646    #[test]
28647    fn high_fanout_probe_clamp_prices_rows_not_keys() {
28648        let mut profile = StatsProfile::default();
28649        profile
28650            .class_counts
28651            .insert(StrHash::new("http://ex/Klass"), 21_124);
28652        profile
28653            .predicate_counts
28654            .insert(StrHash::new("http://ex/label"), 376_482);
28655        profile
28656            .subjects_per_predicate
28657            .insert(StrHash::new("http://ex/label"), hll_with_n(11_025));
28658        profile.total_puts = 500_000;
28659        let sparql = r#"
28660            SELECT ?class ?label WHERE {
28661              ?class a <http://ex/Klass> .
28662              OPTIONAL { ?class <http://ex/label> ?label }
28663            }
28664        "#;
28665        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28666        let label = EncodedTerm::from(&NamedNode::new("http://ex/label").unwrap());
28667        let mut label_scan: Option<&ScanOp> = None;
28668        for_each_scan(&plan.root, &mut |scan| {
28669            if scan.pattern.predicate.as_ref() == Some(&label) {
28670                label_scan = Some(scan);
28671            }
28672        });
28673        let scan = label_scan.expect("label scan in plan");
28674        assert_eq!(
28675            scan.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
28676            Some(("class", PatternSlot::Subject)),
28677            "the LeftJoin claims the label probe on ?class"
28678        );
28679        assert_eq!(
28680            scan.produced_row_count_estimate, 376_482,
28681            "fan-out-aware clamp: 21,124 pushed values × ~34 rows/key (≈722k) capped at \\
28682             the price — NOT the values-broadcast 21,124"
28683        );
28684        // The LeftJoin estimate model on the same shape: produced =
28685        // unmatched + matched = (|L| − labeled classes) + all 376,482 label
28686        // rows (containment), with the live HLL for the labeled-class
28687        // domain. The push-aware restamp leaves it unchanged here — the
28688        // probe's settled count equals its price under containment.
28689        let card = profile
28690            .subjects_per_predicate
28691            .get(&StrHash::new("http://ex/label"))
28692            .map(|hll| hll.cardinality())
28693            .unwrap_or(11_025);
28694        let expected_leftjoin = (21_124u64).saturating_sub(card) + 376_482;
28695        let mut leftjoin_meta: Option<LeftJoinMeta> = None;
28696        walk_plan_node_meta(&plan.root, &mut leftjoin_meta);
28697        let meta = leftjoin_meta.expect("a LeftJoin in the plan");
28698        assert_eq!(
28699            meta.own_push_removed_row_count_estimate, expected_leftjoin,
28700            "own-push-removed: unmatched + |R| under containment"
28701        );
28702        assert_eq!(
28703            meta.produced_row_count_estimate, expected_leftjoin,
28704            "push-aware leaves it: probe settled count = price"
28705        );
28706    }
28707
28708    /// Meta collector for tests: the first [`LeftJoinMeta`] in the tree.
28709    fn walk_plan_node_meta(node: &PlanNode, out: &mut Option<LeftJoinMeta>) {
28710        if out.is_none()
28711            && let PlanNode::LeftJoin { meta, .. } = node
28712        {
28713            *out = Some(*meta);
28714        }
28715        match node {
28716            PlanNode::LeftJoin { left, right, .. }
28717            | PlanNode::Join { left, right, .. }
28718            | PlanNode::Union { left, right } => {
28719                walk_plan_node_meta(left, out);
28720                walk_plan_node_meta(right, out);
28721            }
28722            PlanNode::Filter { inner, .. }
28723            | PlanNode::Extend { inner, .. }
28724            | PlanNode::Slice { inner, .. }
28725            | PlanNode::Distinct { inner, .. }
28726            | PlanNode::Sort { inner, .. }
28727            | PlanNode::Group { inner, .. } => walk_plan_node_meta(inner, out),
28728            PlanNode::SubSelect(sub) => walk_plan_node_meta(&sub.inner, out),
28729            _ => {}
28730        }
28731    }
28732
28733    /// Test helper: the OUTERMOST LeftJoin — first one found top-down
28734    /// through unary wrappers, never descending into a LeftJoin's arms.
28735    fn outermost_left_join(node: &PlanNode) -> &PlanNode {
28736        match node {
28737            PlanNode::LeftJoin { .. } => node,
28738            PlanNode::Filter { inner, .. }
28739            | PlanNode::Extend { inner, .. }
28740            | PlanNode::Slice { inner, .. }
28741            | PlanNode::Distinct { inner, .. }
28742            | PlanNode::Sort { inner, .. }
28743            | PlanNode::Group { inner, .. }
28744            | PlanNode::JoinGraphVar { inner, .. } => outermost_left_join(inner),
28745            PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
28746                let found = outermost_left_join(left);
28747                if matches!(found, PlanNode::LeftJoin { .. }) {
28748                    found
28749                } else {
28750                    outermost_left_join(right)
28751                }
28752            }
28753            other => other,
28754        }
28755    }
28756
28757    /// Grounding supersedes claiming, and point lookups are exempt — both
28758    /// claim guards pinned directly.
28759    #[test]
28760    fn restamp_skips_grounded_and_point_lookup_probes() {
28761        let mut grounded = var_scan(Some("b"), "http://ex/p", Some("c"), 50);
28762        grounded
28763            .grounded
28764            .push((Variable::new("b").unwrap(), PatternSlot::Subject));
28765        let mut tree = broadcast_join(
28766            values_node("b", &["http://ex/k1"]),
28767            PlanNode::Scan(grounded),
28768            &["b"],
28769            1,
28770        );
28771        restamp_broadcast_marks(&mut tree, None);
28772        let PlanNode::Join { right, .. } = &tree else {
28773            panic!("expected Join, got {tree:?}")
28774        };
28775        let PlanNode::Scan(scan) = right.as_ref() else {
28776            panic!("expected Scan probe, got {right:?}")
28777        };
28778        assert!(
28779            scan.broadcasted.is_none(),
28780            "grounded key slot must not be claimed: {:?}",
28781            scan.broadcasted
28782        );
28783
28784        let mut point = var_scan(None, "http://ex/p", None, 1);
28785        point.pattern.subject = Some(EncodedTerm::from(&NamedNode::new("http://ex/s1").unwrap()));
28786        point.pattern.object = Some(EncodedTerm::from(&NamedNode::new("http://ex/o1").unwrap()));
28787        point.pattern.graph_name = Some(EncodedTerm::DefaultGraph);
28788        point.subject = None;
28789        point.object = None;
28790        let mut tree = broadcast_join(
28791            values_node("b", &["http://ex/k1"]),
28792            PlanNode::Scan(point),
28793            &["b"],
28794            1,
28795        );
28796        restamp_broadcast_marks(&mut tree, None);
28797        let PlanNode::Join { right, .. } = &tree else {
28798            panic!("expected Join, got {tree:?}")
28799        };
28800        let PlanNode::Scan(scan) = right.as_ref() else {
28801            panic!("expected Scan probe, got {right:?}")
28802        };
28803        assert!(
28804            scan.broadcasted.is_none(),
28805            "point lookups are exempt from claiming: {:?}",
28806            scan.broadcasted
28807        );
28808    }
28809
28810    /// The swap heals itself at the boundary: refinalize's swap clears the
28811    /// old probe's mark, and the restamp that follows claims the swapped-in
28812    /// probe — the original missing-restamp bug, as a unit.
28813    #[test]
28814    fn swap_clears_old_probe_and_restamp_reclaims_new_one() {
28815        // Construction order puts the big arm left; the right (old probe)
28816        // carries a stale mark from build time.
28817        let mut small = var_scan(Some("b"), "http://ex/q", Some("d"), 5);
28818        small.broadcasted = Some((Variable::new("b").unwrap(), PatternSlot::Subject));
28819        let mut tree = PlanNode::Join {
28820            left: Box::new(PlanNode::Scan(var_scan(
28821                Some("b"),
28822                "http://ex/p",
28823                Some("c"),
28824                500,
28825            ))),
28826            right: Box::new(PlanNode::Scan(small)),
28827            hash_keys: vec![Variable::new("b").unwrap()],
28828            probe_key_domains: Vec::new(),
28829            probe_key_overlap_milli: Vec::new(),
28830            rhs_hostable_keys: Vec::new().into(),
28831            meta: JoinMeta {
28832                semi_gate: None,
28833                star_arms: None,
28834                strategy: JoinStrategy::Hash,
28835                produced_row_count_estimate: 500,
28836                own_push_removed_row_count_estimate: 500,
28837            },
28838        };
28839        // No profile: driver_cost falls back to row counts, so the 5-row arm
28840        // wins the driver seat and the swap fires.
28841        refinalize_joins_without_ctx(&mut tree, None);
28842        let PlanNode::Join { left, meta, .. } = &tree else {
28843            panic!("expected Join, got {tree:?}")
28844        };
28845        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
28846        let PlanNode::Scan(driver) = left.as_ref() else {
28847            panic!("expected the small scan to drive, got {left:?}")
28848        };
28849        assert!(
28850            driver.broadcasted.is_none(),
28851            "swap-time clear_broadcast_marks removed the old probe's stale mark"
28852        );
28853        restamp_broadcast_marks(&mut tree, None);
28854        let PlanNode::Join { right, .. } = &tree else {
28855            panic!("expected Join, got {tree:?}")
28856        };
28857        let PlanNode::Scan(probe) = right.as_ref() else {
28858            panic!("expected the big scan as probe, got {right:?}")
28859        };
28860        assert_eq!(
28861            probe.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
28862            Some(("b", PatternSlot::Subject)),
28863            "the boundary restamp claims the swapped-in probe: {:?}",
28864            probe.broadcasted
28865        );
28866        assert_eq!(
28867            probe.produced_row_count_estimate, 5,
28868            "claim-clamp prices the probe at the driver's estimate (no HLL)"
28869        );
28870    }
28871
28872    /// The query that motivated the whole discussion, end to end, with the
28873    /// class-aware `estimate_join_key_domain` fix in place: the exact class
28874    /// counts (5 datasets / 100 submissions) cap the cartesian's driver cost
28875    /// at 5, it beats the isPartOf side's 121-domain, so NO swap fires — the
28876    /// cartesian keeps the driver seat and the isPartOf scan stays the probe,
28877    /// marked `(broadcast ?ds object)` from construction (surviving restamp
28878    /// via claim-skip). Exactly one coherent mark lands. (The wildly wrong
28879    /// 125,483 `rdf:type` subject HLL stays in the profile on purpose: exact
28880    /// counts must beat even a pathological HLL.)
28881    #[test]
28882    fn original_query_shape_keeps_cartesian_driving_and_marks_the_ispartof_probe() {
28883        let mut profile = StatsProfile::default();
28884        profile
28885            .class_counts
28886            .insert(StrHash::new("http://schema.org/Dataset"), 5);
28887        profile
28888            .class_counts
28889            .insert(StrHash::new("http://example.org/ontology/Submission"), 100);
28890        profile.predicate_counts.insert(
28891            StrHash::new("http://example.org/ontology/isPartOf"),
28892            237_016,
28893        );
28894        profile.objects_per_predicate.insert(
28895            StrHash::new("http://example.org/ontology/isPartOf"),
28896            hll_with_n(121),
28897        );
28898        profile.subjects_per_predicate.insert(
28899            StrHash::new("http://example.org/ontology/isPartOf"),
28900            hll_with_n(114_739),
28901        );
28902        profile.subjects_per_predicate.insert(
28903            StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
28904            hll_with_n(125_483),
28905        );
28906        profile.total_puts = 300_000;
28907
28908        let sparql = r#"
28909            PREFIX schema: <http://schema.org/>
28910            PREFIX myOnt: <http://example.org/ontology/>
28911            SELECT * WHERE {
28912              ?ds a schema:Dataset .
28913              ?sub a myOnt:Submission .
28914              ?sub myOnt:isPartOf ?ds .
28915            }
28916        "#;
28917        let plan = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
28918        // The outer join carries both keys [?ds, ?sub] (cartesian side first).
28919        let mut outer: Option<&PlanNode> = None;
28920        fn find_two_key_join<'a>(node: &'a PlanNode, out: &mut Option<&'a PlanNode>) {
28921            match node {
28922                PlanNode::Join {
28923                    left,
28924                    right,
28925                    hash_keys,
28926                    ..
28927                } => {
28928                    let names: Vec<&str> = hash_keys.iter().map(Variable::as_str).collect();
28929                    if names.contains(&"ds") && names.contains(&"sub") && out.is_none() {
28930                        *out = Some(node);
28931                    }
28932                    let _ = (left, right);
28933                    find_two_key_join(left, out);
28934                    find_two_key_join(right, out);
28935                }
28936                PlanNode::JoinGraphVar { inner, .. }
28937                | PlanNode::Extend { inner, .. }
28938                | PlanNode::Filter { inner, .. } => find_two_key_join(inner, out),
28939                _ => {}
28940            }
28941        }
28942        find_two_key_join(&plan.root, &mut outer);
28943        let Some(join) = outer else {
28944            panic!("expected the [?ds, ?sub] join, got {:?}", plan.root)
28945        };
28946        let PlanNode::Join {
28947            left,
28948            right,
28949            hash_keys,
28950            probe_key_domains: _,
28951            probe_key_overlap_milli: _,
28952            rhs_hostable_keys: _,
28953            meta,
28954        } = join
28955        else {
28956            unreachable!()
28957        };
28958        assert_eq!(
28959            meta.strategy,
28960            JoinStrategy::Broadcast,
28961            "the small cartesian driver keeps the join Broadcast"
28962        );
28963        assert!(
28964            matches!(left.as_ref(), PlanNode::Join { .. }),
28965            "the type-scan cartesian drives (no swap): {:?}",
28966            left
28967        );
28968        let key_order: Vec<&str> = hash_keys.iter().map(Variable::as_str).collect();
28969        assert_eq!(
28970            key_order,
28971            vec!["sub", "ds"],
28972            "keys ordered by expected probe return: ?sub (100 keys × ~2 rows) \\
28973             beats ?ds (5 keys × ~1,959 rows)"
28974        );
28975        let PlanNode::Scan(is_part_of) = right.as_ref() else {
28976            panic!("expected the isPartOf scan as probe, got {right:?}")
28977        };
28978        assert_eq!(
28979            is_part_of
28980                .broadcasted
28981                .as_ref()
28982                .map(|(v, s)| (v.as_str(), *s)),
28983            Some(("sub", PatternSlot::Subject)),
28984            "the claim names the cheapest key — the runtime broadcasts ~100 subject \\
28985             terms (~200 rows back), not 5 dataset terms (~113,688 rows back): {:?}",
28986            is_part_of.broadcasted
28987        );
28988        // Fan-out-aware claim-clamp: the pushed 100 ?sub keys each bring
28989        // the scan's average rows per subject (price 237,016 / subject
28990        // domain ~114,739 ≈ 2.07) → ~207 rows expected back, not one row
28991        // per key. Expected derived from the live HLL through the SHARED
28992        // core (`pushed_return_bound_core`) so sketch error cannot flake
28993        // the assertion and the pin cannot drift from the formula again —
28994        // the total rounds UP once (never understates), which is the +1
28995        // over the old total-floor this replaced.
28996        let expected_probe_rows = {
28997            let sub_domain = profile
28998                .subjects_per_predicate
28999                .get(&StrHash::new("http://example.org/ontology/isPartOf"))
29000                .map(|hll| hll.cardinality())
29001                .unwrap_or(114_739);
29002            pushed_return_bound_core(100, 237_016, Some(sub_domain)).unwrap_or(237_016)
29003        };
29004        assert_eq!(
29005            is_part_of.produced_row_count_estimate, expected_probe_rows,
29006            "claim-clamp prices the probe at pushed values × rows per key (~207)"
29007        );
29008        // Exactly one claimed scan in the whole tree: the isPartOf probe.
29009        // The type scans sit in the driver arm (never claimed), and neither
29010        // hosts another Broadcast join's first key.
29011        let mut claimed: Vec<(String, PatternSlot)> = Vec::new();
29012        for_each_scan(&plan.root, &mut |scan| {
29013            if let Some((v, s)) = &scan.broadcasted {
29014                claimed.push((v.as_str().to_string(), *s));
29015            }
29016        });
29017        assert_eq!(
29018            claimed,
29019            vec![("sub".to_string(), PatternSlot::Subject)],
29020            "one coherent mark: the isPartOf scan as the driven probe, on the \\
29021             cheapest key"
29022        );
29023        // End-of-pipeline push-aware restamp: the probe's mark is
29024        // (?sub, Subject), so ?sub divides by the driver-side domain alone
29025        // (100); ?ds keeps max(5, 121) — the fan-out-aware probe count
29026        // (~206) no longer caps its 121 domain below it. 500 × 206 /
29027        // (100 × 121) ≈ 8. (The true answer 100 needs conditional domains
29028        // the sketches do not carry — ?ds conditioned on ?sub being a
29029        // Submission is 5, not 121.)
29030        assert_eq!(
29031            meta.produced_row_count_estimate, 8,
29032            "push-aware product over [?sub, ?ds] with the fan-out-aware probe count"
29033        );
29034        // The recorded pre-push value finalize stamped: the plan-mode
29035        // arithmetic 500 × 237,016 / (max(5,121) × max(100,114_739)) = 8.
29036        // finalize re-derives the bare pattern price for a CLAIMED scan
29037        // probe (`path_arm_own_push_removed_price`) instead of reading its
29038        // push-clamped cell — the record never depends on clamp timing,
29039        // even though the ancestor bound persistence keeps the cell
29040        // clamped (~206) across rounds.
29041        assert_eq!(
29042            meta.own_push_removed_row_count_estimate, 8,
29043            "finalize's own-push-removed stamp survives the push-aware restamp"
29044        );
29045    }
29046
29047    /// Cartesian deferral: a disconnected mid-price leaf folds LAST, not in
29048    /// price-sort position. Query order p1 (10 rows) → p3 (1,000,
29049    /// disconnected) → p2 (100,000): the old fixed fold built
29050    /// Join(Join(p1, p3)[cartesian], p2); the greedy fold connects p2 to the
29051    /// accumulator first and defers the p3 cartesian to the root, where it
29052    /// multiplies the smallest possible intermediate.
29053    #[test]
29054    fn greedy_assoc_defers_cartesian() {
29055        let mut profile = StatsProfile::default();
29056        profile
29057            .predicate_counts
29058            .insert(StrHash::new("http://ex/p1"), 10);
29059        profile
29060            .predicate_counts
29061            .insert(StrHash::new("http://ex/p3"), 1_000);
29062        profile
29063            .predicate_counts
29064            .insert(StrHash::new("http://ex/p2"), 100_000);
29065        profile.total_puts = 200_000;
29066        let plan = LogicalPlan::parse_with_profile(
29067            r#"SELECT * WHERE {
29068              ?a <http://ex/p1> ?x .
29069              ?c <http://ex/p3> ?z .
29070              ?a <http://ex/p2> ?y .
29071            }"#,
29072            Some(&profile),
29073        )
29074        .unwrap();
29075        fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
29076            matches!(
29077                node,
29078                PlanNode::Scan(scan)
29079                    if scan.pattern.predicate.as_ref()
29080                        == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
29081            )
29082        }
29083        let PlanNode::Join {
29084            left,
29085            right,
29086            hash_keys,
29087            ..
29088        } = &plan.root
29089        else {
29090            panic!("expected a join root, got {:?}", plan.root)
29091        };
29092        assert!(
29093            hash_keys.is_empty(),
29094            "the deferred cartesian is the root, got keys {hash_keys:?}"
29095        );
29096        assert!(
29097            scan_with_predicate(right, "http://ex/p3"),
29098            "the disconnected p3 scan folds last, got {right:?}"
29099        );
29100        let PlanNode::Join {
29101            left: inner_left,
29102            right: inner_right,
29103            hash_keys: inner_keys,
29104            ..
29105        } = left.as_ref()
29106        else {
29107            panic!("expected the connected pair inside, got {left:?}")
29108        };
29109        assert_eq!(
29110            inner_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
29111            vec!["a"],
29112            "the connected pair joins on ?a"
29113        );
29114        assert!(scan_with_predicate(inner_left, "http://ex/p1"));
29115        assert!(scan_with_predicate(inner_right, "http://ex/p2"));
29116    }
29117
29118    /// The greedy picks by JOIN OUTPUT, not standalone leaf price: p2 is
29119    /// cheaper standalone (100,000 vs 500,000) but its tiny ?a domain makes
29120    /// joining it emit ~100,000 rows, while the pricier p3's huge ?a domain
29121    /// makes joining it emit ~5. The association pass must attach p3 first.
29122    #[test]
29123    fn greedy_assoc_picks_smallest_join_output_not_smallest_leaf() {
29124        let mut profile = StatsProfile::default();
29125        profile
29126            .predicate_counts
29127            .insert(StrHash::new("http://ex/p1"), 10);
29128        profile
29129            .predicate_counts
29130            .insert(StrHash::new("http://ex/p2"), 100_000);
29131        profile
29132            .predicate_counts
29133            .insert(StrHash::new("http://ex/p3"), 500_000);
29134        profile
29135            .subjects_per_predicate
29136            .insert(StrHash::new("http://ex/p1"), hll_with_n(10));
29137        profile
29138            .subjects_per_predicate
29139            .insert(StrHash::new("http://ex/p2"), hll_with_n(10));
29140        profile
29141            .subjects_per_predicate
29142            .insert(StrHash::new("http://ex/p3"), hll_with_n(1_000_000));
29143        profile.total_puts = 1_000_000;
29144        let plan = LogicalPlan::parse_with_profile(
29145            r#"SELECT * WHERE {
29146              ?a <http://ex/p1> ?x .
29147              ?a <http://ex/p2> ?y .
29148              ?a <http://ex/p3> ?z .
29149            }"#,
29150            Some(&profile),
29151        )
29152        .unwrap();
29153        fn scan_with_predicate(node: &PlanNode, iri: &str) -> bool {
29154            matches!(
29155                node,
29156                PlanNode::Scan(scan)
29157                    if scan.pattern.predicate.as_ref()
29158                        == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
29159            )
29160        }
29161        // Join(Join(p1, p3), p2): p3 joined first (output ~5), p2 last
29162        // (output ~100,000) — the reverse of the standalone-price order.
29163        let PlanNode::Join {
29164            left,
29165            right,
29166            hash_keys,
29167            ..
29168        } = &plan.root
29169        else {
29170            panic!("expected a join root, got {:?}", plan.root)
29171        };
29172        assert_eq!(
29173            hash_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
29174            vec!["a"],
29175            "all three leaves share ?a"
29176        );
29177        assert!(
29178            scan_with_predicate(right, "http://ex/p2"),
29179            "the small-?a-domain p2 scan (big join output) folds last, got {right:?}"
29180        );
29181        let PlanNode::Join {
29182            right: inner_right, ..
29183        } = left.as_ref()
29184        else {
29185            panic!("expected the inner join, got {left:?}")
29186        };
29187        assert!(
29188            scan_with_predicate(inner_right, "http://ex/p3"),
29189            "the huge-?a-domain p3 scan (tiny join output) folds second, got {inner_right:?}"
29190        );
29191    }
29192
29193    /// Without a profile every scan and every join is estimated at the same
29194    /// value: the association has no cost difference to rank on. It must
29195    /// still produce one deterministic plan, and that plan must not depend
29196    /// on the order the triples were written in.
29197    #[test]
29198    fn no_statistic_assoc_ties_ignore_input_order() {
29199        let plan = |sparql: &str| LogicalPlan::parse(sparql).unwrap();
29200        let first = plan(
29201            r#"SELECT * WHERE {
29202              ?x <http://ex/p1> ?a .
29203              ?x <http://ex/p2> ?b .
29204              ?x <http://ex/p3> ?c .
29205            }"#,
29206        );
29207        let second = plan(
29208            r#"SELECT * WHERE {
29209              ?x <http://ex/p3> ?c .
29210              ?x <http://ex/p1> ?a .
29211              ?x <http://ex/p2> ?b .
29212            }"#,
29213        );
29214
29215        // The tie premise: with no statistics every leaf and every join
29216        // carries the same estimate, so no ordering is cheaper.
29217        fn assert_all_estimates_equal(node: &PlanNode, expected: u64) {
29218            assert_eq!(
29219                node.produced_row_count_estimate(),
29220                expected,
29221                "no-statistics estimate must tie with the root, got {node:?}"
29222            );
29223            if let PlanNode::Join { left, right, .. } = node {
29224                assert_all_estimates_equal(left, expected);
29225                assert_all_estimates_equal(right, expected);
29226            }
29227        }
29228        let expected = first.root.produced_row_count_estimate();
29229        assert_all_estimates_equal(&first.root, expected);
29230        assert_all_estimates_equal(&second.root, expected);
29231
29232        // The property: the association is decided from the operands, not
29233        // from the order the query text arrived in.
29234        assert_eq!(first.root, second.root);
29235    }
29236
29237    /// The reorder degenerates safely: with no profile there is no cost
29238    /// information for any key, so the structural order must survive
29239    /// byte-for-byte (stable sort, unknowns last and uniform).
29240    #[test]
29241    fn hash_key_reorder_without_profile_keeps_structural_order() {
29242        let mut keys: Vec<Variable> = ["b", "a"]
29243            .iter()
29244            .map(|k| Variable::new(*k).unwrap())
29245            .collect();
29246        let left = PlanNode::Unit;
29247        let right = PlanNode::Scan(var_scan(Some("b"), "http://ex/p", Some("a"), 10));
29248        reorder_hash_keys_by_probe_return(
29249            &mut keys,
29250            &mut Vec::new(),
29251            &mut Vec::new(),
29252            &left,
29253            &right,
29254            None,
29255        );
29256        assert_eq!(
29257            keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
29258            vec!["b", "a"],
29259            "no profile ⇒ no information ⇒ original order"
29260        );
29261    }
29262
29263    /// A key the probe does NOT host has an unsizable cost and must sort
29264    /// LAST, not first: `hash_keys.first()` is the key the restamp claim
29265    /// names and the first allow-list the runtime broadcasts — an unhosted key
29266    /// in front would make the claim miss the scan entirely. The probe here
29267    /// hosts `?b` (object slot) but never `?a`.
29268    #[test]
29269    fn hash_key_reorder_sorts_unknown_cost_last() {
29270        let x = EncodedTerm::from(&NamedNode::new("http://ex/X").unwrap());
29271        let y = EncodedTerm::from(&NamedNode::new("http://ex/Y").unwrap());
29272        let driver = PlanNode::Values(ValuesOp {
29273            variables: vec![var("a"), var("b")],
29274            rows: vec![vec![Some(x), Some(y)]],
29275            strings: Vec::new(),
29276            blobs: Vec::new(),
29277        });
29278        let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/p", Some("b"), 10));
29279        let mut keys = vec![var("a"), var("b")];
29280        reorder_hash_keys_by_probe_return(
29281            &mut keys,
29282            &mut Vec::new(),
29283            &mut Vec::new(),
29284            &driver,
29285            &probe,
29286            None,
29287        );
29288        assert_eq!(
29289            keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
29290            vec!["b", "a"],
29291            "unknown-cost ?a must sort behind the hosted, shippable ?b"
29292        );
29293    }
29294
29295    /// Grounding is decoupled from key order: the reorder sorts [?s, ?x]
29296    /// (?x's push prices dear — its tiny object domain on the probe means a
29297    /// huge uniform fan-out), yet ?x is ground-unique on the driver (the
29298    /// singleton VALUES), so the grounding pass still bakes its term into
29299    /// the probe's object slot. The claim, run afterwards, names the FIRST
29300    /// key ?s — delivery and grounding are separate decisions.
29301    #[test]
29302    fn grounding_uses_any_ground_unique_key_not_just_first() {
29303        let mut profile = StatsProfile::default();
29304        let p = StrHash::new("http://ex/p");
29305        let q = StrHash::new("http://ex/q");
29306        profile.predicate_counts.insert(p, 5_000);
29307        profile.predicate_counts.insert(q, 500_000);
29308        profile.subjects_per_predicate.insert(p, hll_with_n(100));
29309        profile
29310            .subjects_per_predicate
29311            .insert(q, hll_with_n(100_000));
29312        profile.objects_per_predicate.insert(p, hll_with_n(50));
29313        profile.objects_per_predicate.insert(q, hll_with_n(10));
29314        profile.total_puts = 600_000;
29315
29316        let x = EncodedTerm::from(&NamedNode::new("http://ex/X").unwrap());
29317        // Driver: singleton VALUES(?x) ⋈ (?s :p ?x) — binds both keys, with
29318        // ?x ground-unique from the VALUES row.
29319        let driver = PlanNode::Join {
29320            left: Box::new(PlanNode::Values(ValuesOp {
29321                variables: vec![var("x")],
29322                rows: vec![vec![Some(x.clone())]],
29323                strings: Vec::new(),
29324                blobs: Vec::new(),
29325            })),
29326            right: Box::new(PlanNode::Scan(var_scan(
29327                Some("s"),
29328                "http://ex/p",
29329                Some("x"),
29330                5_000,
29331            ))),
29332            hash_keys: vec![var("x")],
29333            probe_key_domains: Vec::new(),
29334            probe_key_overlap_milli: Vec::new(),
29335            rhs_hostable_keys: Vec::new().into(),
29336            meta: JoinMeta {
29337                semi_gate: None,
29338                star_arms: None,
29339                strategy: JoinStrategy::Hash,
29340                produced_row_count_estimate: 100,
29341                own_push_removed_row_count_estimate: 100,
29342            },
29343        };
29344        let mut tree = PlanNode::Join {
29345            left: Box::new(driver),
29346            right: Box::new(PlanNode::Scan(var_scan(
29347                Some("s"),
29348                "http://ex/q",
29349                Some("x"),
29350                500_000,
29351            ))),
29352            hash_keys: vec![var("s"), var("x")],
29353            probe_key_domains: Vec::new(),
29354            probe_key_overlap_milli: Vec::new(),
29355            rhs_hostable_keys: Vec::new().into(),
29356            meta: JoinMeta {
29357                semi_gate: None,
29358                star_arms: None,
29359                strategy: JoinStrategy::Hash,
29360                produced_row_count_estimate: 1,
29361                own_push_removed_row_count_estimate: 1,
29362            },
29363        };
29364        refinalize_joins_without_ctx(&mut tree, Some(&profile));
29365        restamp_broadcast_marks(&mut tree, Some(&profile));
29366        let PlanNode::Join {
29367            left: _,
29368            right,
29369            hash_keys,
29370            probe_key_domains: _,
29371            probe_key_overlap_milli: _,
29372            rhs_hostable_keys: _,
29373            meta,
29374        } = &tree
29375        else {
29376            panic!("expected Join, got {tree:?}")
29377        };
29378        let key_order: Vec<&str> = hash_keys.iter().map(Variable::as_str).collect();
29379        assert_eq!(
29380            key_order,
29381            vec!["s", "x"],
29382            "?s's push is cheaper (?x's tiny object domain gives it a huge \\
29383             uniform fan-out): {key_order:?}"
29384        );
29385        let PlanNode::Scan(probe) = right.as_ref() else {
29386            panic!("expected the :q scan as probe, got {right:?}")
29387        };
29388        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
29389        assert_eq!(
29390            probe
29391                .grounded
29392                .iter()
29393                .map(|(v, s)| (v.as_str(), *s))
29394                .collect::<Vec<_>>(),
29395            vec![("x", PatternSlot::Object)],
29396            "the SECOND key grounds — ground-uniqueness, not sort position, \\
29397             decides: {:?}",
29398            probe.grounded
29399        );
29400        assert_eq!(probe.pattern.object, Some(x));
29401        assert_eq!(
29402            probe.broadcasted.as_ref().map(|(v, s)| (v.as_str(), *s)),
29403            Some(("s", PatternSlot::Subject)),
29404            "the claim names the first key (delivery), grounding took ?x: {:?}",
29405            probe.broadcasted
29406        );
29407        assert!(
29408            probe.produced_row_count_estimate < 500_000,
29409            "grounded probe re-priced below its catalog estimate: {}",
29410            probe.produced_row_count_estimate
29411        );
29412    }
29413
29414    #[test]
29415    fn bind_iri_equality_grounds_scan_subject() {
29416        let iri = NamedNode::new("http://yago-knowledge.org/resource/Crow_Hill_Q20861371").unwrap();
29417        let plan = LogicalPlan::parse(
29418            r#"SELECT ?o ?b WHERE {
29419              ?b ?p ?o .
29420              BIND(<http://yago-knowledge.org/resource/Crow_Hill_Q20861371> AS ?c)
29421              FILTER(?b = ?c)
29422            }"#,
29423        )
29424        .unwrap();
29425        assert!(
29426            !contains_filter(&plan.root),
29427            "IRI = with grounded BIND should fold, got {:?}",
29428            plan.root
29429        );
29430        let mut scans = Vec::new();
29431        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29432        assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
29433        assert_eq!(scans[0].pattern.subject, Some(EncodedTerm::from(&iri)));
29434    }
29435
29436    #[test]
29437    fn values_singleton_sameterm_grounds_scan_subject() {
29438        let iri = NamedNode::new("http://ex/CrowHill").unwrap();
29439        let plan = LogicalPlan::parse(
29440            r#"SELECT ?o ?b WHERE {
29441              VALUES ?c { <http://ex/CrowHill> }
29442              ?b ?p ?o .
29443              FILTER(sameTerm(?b, ?c))
29444            }"#,
29445        )
29446        .unwrap();
29447        assert!(
29448            !contains_filter(&plan.root),
29449            "singleton VALUES sameTerm should fold, got {:?}",
29450            plan.root
29451        );
29452        let mut scans = Vec::new();
29453        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29454        assert_eq!(scans.len(), 1);
29455        assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
29456        assert_eq!(scans[0].pattern.subject, Some(EncodedTerm::from(&iri)));
29457    }
29458
29459    #[test]
29460    fn values_two_column_row_grounds_both_scan_slots() {
29461        let a = EncodedTerm::from(&NamedNode::new("http://ex/a").unwrap());
29462        let b = EncodedTerm::from(&NamedNode::new("http://ex/b").unwrap());
29463        let plan = LogicalPlan::parse(
29464            r#"SELECT ?s ?p ?o WHERE {
29465              VALUES (?a ?b) { (<http://ex/a> <http://ex/b>) }
29466              ?s ?p ?o .
29467              FILTER(sameTerm(?s, ?a) && sameTerm(?o, ?b))
29468            }"#,
29469        )
29470        .unwrap();
29471        assert!(
29472            !contains_filter(&plan.root),
29473            "one-row two-column VALUES should fold both conjuncts, got {:?}",
29474            plan.root
29475        );
29476        let mut scans = Vec::new();
29477        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29478        assert_eq!(scans.len(), 1);
29479        assert_eq!(scans[0].pattern.subject, Some(a));
29480        assert_eq!(scans[0].pattern.object, Some(b));
29481        assert!(
29482            scans[0].pattern.predicate.is_none(),
29483            "predicate should stay unbound, got {:?}",
29484            scans[0]
29485        );
29486    }
29487
29488    #[test]
29489    fn str_filter_grounds_object_and_drops_filter() {
29490        let green_str = EncodedTerm::from(&Literal::new_simple_literal(
29491            "https://example.org/colour/green",
29492        ));
29493        let plan = LogicalPlan::parse(
29494            r#"SELECT ?s WHERE {
29495              ?s <http://ex/p> ?colour .
29496              FILTER(?colour = STR(<https://example.org/colour/green>))
29497            }"#,
29498        )
29499        .unwrap();
29500        assert!(
29501            !contains_filter(&plan.root),
29502            "STR equality should fold like a plain string: {:?}",
29503            plan.root
29504        );
29505        let mut scans = Vec::new();
29506        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29507        assert_eq!(scans.len(), 1);
29508        assert_eq!(scans[0].pattern.object, Some(green_str));
29509        assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("s"));
29510    }
29511
29512    #[test]
29513    fn bind_str_sameterm_grounds_scan_subject() {
29514        let lexical = "http://ex/Resource";
29515        let ground_str = EncodedTerm::from(&Literal::new_simple_literal(lexical));
29516        let plan = LogicalPlan::parse(
29517            r#"SELECT ?o ?s WHERE {
29518              ?s ?p ?o .
29519              BIND(STR(<http://ex/Resource>) AS ?c)
29520              FILTER(sameTerm(?s, ?c))
29521            }"#,
29522        )
29523        .unwrap();
29524        assert!(
29525            !contains_filter(&plan.root),
29526            "BIND(STR(iri)) + sameTerm should ground ?s: {:?}",
29527            plan.root
29528        );
29529        let mut scans = Vec::new();
29530        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29531        assert_eq!(scans.len(), 1);
29532        assert_eq!(scans[0].pattern.subject, Some(ground_str));
29533    }
29534
29535    #[test]
29536    fn constant_arithmetic_equalities_drop_filter() {
29537        for sparql in [
29538            r#"SELECT ?s WHERE { ?s <http://ex/p> ?o . FILTER(4.1 - 3.2 = 0.9) }"#,
29539            r#"SELECT ?s WHERE { ?s <http://ex/p> ?o . FILTER(ABS(-1) = 1) }"#,
29540        ] {
29541            let plan = LogicalPlan::parse(sparql).unwrap();
29542            assert!(
29543                !contains_filter(&plan.root),
29544                "constant numeric equality should fold away: {:?}",
29545                plan.root
29546            );
29547        }
29548    }
29549
29550    #[test]
29551    fn variable_equals_folded_arithmetic_keeps_filter() {
29552        let plan = LogicalPlan::parse(
29553            r#"SELECT ?s ?n WHERE {
29554              ?s <http://ex/p> ?n .
29555              FILTER(?n = 4.1 - 3.2)
29556            }"#,
29557        )
29558        .unwrap();
29559        assert!(
29560            !contains_filter(&plan.root),
29561            "the exact folded comparison moves into the scan: {:?}",
29562            plan.root
29563        );
29564        let mut scans = Vec::new();
29565        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29566        assert!(
29567            scans[0].pattern.object.is_none(),
29568            "numeric literal must not identity-fold the object slot: {:?}",
29569            scans[0]
29570        );
29571        assert!(
29572            scans[0]
29573                .eager
29574                .iter()
29575                .any(|comparison| comparison.op == CompareOp::Eq
29576                    && matches!(comparison.term, EncodedTerm::DecimalLiteral(_))),
29577            "the scan must carry the exact decimal equality: {:?}",
29578            scans[0].eager
29579        );
29580    }
29581
29582    #[test]
29583    fn sha1_on_boolean_is_not_constant_folded() {
29584        let plan =
29585            LogicalPlan::parse(r#"SELECT ?s WHERE { ?s <http://ex/p> ?o . FILTER(SHA1(true)) }"#)
29586                .unwrap();
29587        assert!(
29588            contains_filter(&plan.root),
29589            "SHA1 must stay a residual filter, not fold away: {:?}",
29590            plan.root
29591        );
29592        let PlanNode::Filter { residual, .. } = &plan.root else {
29593            panic!("expected Filter root");
29594        };
29595        assert!(
29596            matches!(
29597                residual.as_ref(),
29598                Some(Expression::FunctionCall(
29599                    spargebra::algebra::Function::Sha1,
29600                    _
29601                ))
29602            ),
29603            "expected SHA1 residual, got {residual:?}"
29604        );
29605    }
29606
29607    #[test]
29608    fn bind_numeric_equality_is_not_folded() {
29609        let plan = LogicalPlan::parse(
29610            r#"SELECT ?x WHERE {
29611              ?x <http://ex/p> ?v .
29612              BIND(1.0e0 AS ?c)
29613              FILTER(?v = ?c)
29614            }"#,
29615        )
29616        .unwrap();
29617        assert!(
29618            !contains_filter(&plan.root),
29619            "the exact numeric = moves into the scan, got {:?}",
29620            plan.root
29621        );
29622        let mut scans = Vec::new();
29623        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29624        assert_eq!(scans.len(), 1);
29625        assert!(
29626            scans[0].pattern.object.is_none(),
29627            "numeric = must not ground the scan: {:?}",
29628            scans[0]
29629        );
29630        assert!(
29631            scans[0].eager.contains(&SlotComparison {
29632                slot: QuadSlot::Object,
29633                op: CompareOp::Eq,
29634                term: EncodedTerm::from(&Literal::from(1.0f64)),
29635            }),
29636            "the scan must carry the eager numeric =: {:?}",
29637            scans[0].eager
29638        );
29639    }
29640
29641    #[test]
29642    fn values_multi_row_sameterm_is_not_folded() {
29643        let plan = LogicalPlan::parse(
29644            r#"SELECT ?o ?b WHERE {
29645              VALUES ?c { <http://ex/a> <http://ex/b> }
29646              ?b ?p ?o .
29647              FILTER(sameTerm(?b, ?c))
29648            }"#,
29649        )
29650        .unwrap();
29651        assert!(
29652            contains_filter(&plan.root),
29653            "multi-row VALUES sameTerm must stay a Filter, got {:?}",
29654            plan.root
29655        );
29656        let mut scans = Vec::new();
29657        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29658        assert_eq!(scans.len(), 1);
29659        assert!(
29660            scans[0].pattern.subject.is_none()
29661                && scans[0].pattern.predicate.is_none()
29662                && scans[0].pattern.object.is_none(),
29663            "multi-row VALUES must not ground the scan: {:?}",
29664            scans[0]
29665        );
29666    }
29667
29668    #[test]
29669    fn union_scan_and_conflicting_values_grounds_scan_but_keeps_filter() {
29670        let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29671        let other = EncodedTerm::from(&NamedNode::new("http://ex/other").unwrap());
29672        let plan = LogicalPlan::parse(
29673            r#"SELECT ?b WHERE {
29674              { ?b ?p ?o } UNION { VALUES ?b { <http://ex/other> } }
29675              FILTER(sameTerm(?b, <http://ex/crow>))
29676            }"#,
29677        )
29678        .unwrap();
29679        assert!(
29680            contains_filter(&plan.root),
29681            "conflicting VALUES arm must keep FILTER so <other> cannot leak, got {:?}",
29682            plan.root
29683        );
29684        assert!(
29685            values_has_term(&plan.root, &other),
29686            "VALUES <other> must stay a producer, got {:?}",
29687            plan.root
29688        );
29689        let mut scans = Vec::new();
29690        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29691        assert_eq!(
29692            scans.len(),
29693            1,
29694            "expected the BGP arm's scan, got {:?}",
29695            plan.root
29696        );
29697        assert_eq!(
29698            scans[0].pattern.subject,
29699            Some(crow),
29700            "scan arm should still be prefixed, got {:?}",
29701            scans[0]
29702        );
29703    }
29704
29705    #[test]
29706    fn bind_around_union_grounds_scan_but_keeps_filter() {
29707        let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29708        let other = EncodedTerm::from(&NamedNode::new("http://ex/other").unwrap());
29709        let plan = LogicalPlan::parse(
29710            r#"SELECT ?b ?c WHERE {
29711              { ?b ?p ?o } UNION { VALUES ?b { <http://ex/other> } }
29712              BIND(<http://ex/crow> AS ?c)
29713              FILTER(sameTerm(?b, ?c))
29714            }"#,
29715        )
29716        .unwrap();
29717        assert!(
29718            contains_filter(&plan.root),
29719            "BIND outside UNION must not drop FILTER when a VALUES arm disagrees, got {:?}",
29720            plan.root
29721        );
29722        assert!(
29723            values_has_term(&plan.root, &other),
29724            "VALUES <other> must stay, got {:?}",
29725            plan.root
29726        );
29727        let mut scans = Vec::new();
29728        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29729        assert_eq!(scans.len(), 1);
29730        assert_eq!(
29731            scans[0].pattern.subject,
29732            Some(crow),
29733            "scan arm should still be prefixed, got {:?}",
29734            scans[0]
29735        );
29736    }
29737
29738    #[test]
29739    fn union_join_arms_with_disagreeing_values_keep_filter() {
29740        let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29741        let other = EncodedTerm::from(&NamedNode::new("http://ex/other").unwrap());
29742        let plan = LogicalPlan::parse(
29743            r#"SELECT ?s ?b WHERE {
29744              {
29745                VALUES ?b { <http://ex/crow> }
29746                ?s <http://ex/p> ?b
29747              } UNION {
29748                VALUES ?b { <http://ex/other> }
29749                ?s <http://ex/q> ?b
29750              }
29751              FILTER(sameTerm(?b, <http://ex/crow>))
29752            }"#,
29753        )
29754        .unwrap();
29755        assert!(
29756            contains_filter(&plan.root),
29757            "VALUES <other> inside a UNION join arm must keep FILTER, got {:?}",
29758            plan.root
29759        );
29760        assert!(
29761            values_has_term(&plan.root, &other),
29762            "disagreeing VALUES must not be rewritten away, got {:?}",
29763            plan.root
29764        );
29765        let mut scans = Vec::new();
29766        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29767        assert_eq!(
29768            scans.len(),
29769            2,
29770            "expected a scan per UNION arm, got {:?}",
29771            plan.root
29772        );
29773        assert!(
29774            scans
29775                .iter()
29776                .any(|scan| scan.pattern.object.as_ref() == Some(&crow))
29777                && scans
29778                    .iter()
29779                    .any(|scan| scan.pattern.object.as_ref() == Some(&other)),
29780            "each VALUES join prefixes its own scan; a later sameTerm does not overwrite the disagreeing arm, got {:?}",
29781            plan.root
29782        );
29783    }
29784
29785    #[test]
29786    fn union_both_arms_agreeing_values_drops_filter() {
29787        let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29788        let plan = LogicalPlan::parse(
29789            r#"SELECT ?s ?b WHERE {
29790              {
29791                VALUES ?b { <http://ex/crow> }
29792                ?s <http://ex/p> ?b
29793              } UNION {
29794                VALUES ?b { <http://ex/crow> }
29795                ?s <http://ex/q> ?b
29796              }
29797              FILTER(sameTerm(?b, <http://ex/crow>))
29798            }"#,
29799        )
29800        .unwrap();
29801        assert!(
29802            !contains_filter(&plan.root),
29803            "agreeing VALUES in both UNION arms should drop FILTER, got {:?}",
29804            plan.root
29805        );
29806        let mut scans = Vec::new();
29807        for_each_scan(&plan.root, &mut |scan| scans.push(scan));
29808        assert_eq!(scans.len(), 2);
29809        assert!(
29810            scans
29811                .iter()
29812                .all(|scan| scan.pattern.object.as_ref() == Some(&crow)),
29813            "both scans should be prefixed, got {:?}",
29814            plan.root
29815        );
29816    }
29817
29818    #[test]
29819    fn optional_union_conflicting_values_grounds_scan_but_keeps_filter() {
29820        let crow = EncodedTerm::from(&NamedNode::new("http://ex/crow").unwrap());
29821        let other = EncodedTerm::from(&NamedNode::new("http://ex/other").unwrap());
29822        let plan = LogicalPlan::parse(
29823            r#"SELECT * WHERE {
29824              ?person <http://ex/livesIn> ?city .
29825              OPTIONAL {
29826                { ?b ?p ?o } UNION { VALUES ?b { <http://ex/other> } }
29827                FILTER(sameTerm(?b, <http://ex/crow>))
29828              }
29829            }"#,
29830        )
29831        .unwrap();
29832        let PlanNode::LeftJoin {
29833            right,
29834            early_filter,
29835            ..
29836        } = &plan.root
29837        else {
29838            panic!("expected LeftJoin, got {:?}", plan.root);
29839        };
29840        assert!(
29841            early_filter.is_some() || contains_filter(right),
29842            "OPTIONAL early filter must stay when a VALUES arm disagrees, early={early_filter:?} right={right:?}"
29843        );
29844        assert!(
29845            values_has_term(right, &other),
29846            "VALUES <other> must stay on the optional side, got {right:?}"
29847        );
29848        let mut scans = Vec::new();
29849        for_each_scan(right, &mut |scan| scans.push(scan));
29850        assert_eq!(
29851            scans.len(),
29852            1,
29853            "expected the optional BGP scan, got {right:?}"
29854        );
29855        assert_eq!(
29856            scans[0].pattern.subject,
29857            Some(crow),
29858            "optional scan arm should still be prefixed, got {:?}",
29859            scans[0]
29860        );
29861    }
29862
29863    #[test]
29864    fn optional_inner_equality_filter_grounds_right_scan() {
29865        let plan = LogicalPlan::parse(
29866            r#"SELECT * WHERE {
29867              ?person <http://ex/livesIn> ?city .
29868              OPTIONAL { ?city <http://ex/hasWeather> ?w FILTER(?w = "Sunny") }
29869            }"#,
29870        )
29871        .unwrap();
29872        let PlanNode::LeftJoin {
29873            right,
29874            early_filter,
29875            ..
29876        } = &plan.root
29877        else {
29878            panic!("expected LeftJoin, got {:?}", plan.root);
29879        };
29880        assert!(
29881            early_filter.is_none(),
29882            "identity-safe OPTIONAL FILTER should fold, early={early_filter:?}"
29883        );
29884        assert!(
29885            !contains_filter(right),
29886            "folded OPTIONAL FILTER should not leave a Filter, got {right:?}"
29887        );
29888        let PlanNode::Scan(scan) = right.as_ref() else {
29889            panic!("expected Scan, got {right:?}");
29890        };
29891        assert_eq!(
29892            scan.pattern.object,
29893            Some(EncodedTerm::from(&Literal::from("Sunny")))
29894        );
29895        assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("w"));
29896    }
29897
29898    #[test]
29899    fn optional_inner_bind_sameterm_grounds_right_scan() {
29900        let iri = NamedNode::new("http://ex/CrowHill").unwrap();
29901        let plan = LogicalPlan::parse(
29902            r#"SELECT * WHERE {
29903              ?person <http://ex/livesIn> ?city .
29904              OPTIONAL {
29905                ?b ?p ?o .
29906                BIND(<http://ex/CrowHill> AS ?c)
29907                FILTER(sameTerm(?b, ?c))
29908              }
29909            }"#,
29910        )
29911        .unwrap();
29912        let PlanNode::LeftJoin {
29913            right,
29914            early_filter,
29915            ..
29916        } = &plan.root
29917        else {
29918            panic!("expected LeftJoin, got {:?}", plan.root);
29919        };
29920        assert!(
29921            early_filter.is_none(),
29922            "OPTIONAL var-var sameTerm should fold, early={early_filter:?}"
29923        );
29924        assert!(
29925            !contains_filter(right),
29926            "folded OPTIONAL BIND sameTerm should not leave a Filter, got {right:?}"
29927        );
29928        let mut scans = Vec::new();
29929        for_each_scan(right, &mut |scan| scans.push(scan));
29930        assert_eq!(scans.len(), 1, "expected one optional scan, got {right:?}");
29931        assert_eq!(scans[0].subject.as_ref().map(Variable::as_str), Some("b"));
29932        assert_eq!(
29933            scans[0].pattern.subject,
29934            Some(EncodedTerm::from(&iri)),
29935            "optional scan subject should be grounded"
29936        );
29937    }
29938
29939    #[test]
29940    fn outer_filter_on_optional_var_grounds_but_keeps_filter() {
29941        let plan = LogicalPlan::parse(
29942            r#"SELECT * WHERE {
29943              ?person <http://ex/livesIn> ?city .
29944              OPTIONAL { ?city <http://ex/hasWeather> ?w }
29945              FILTER(?w = "Sunny")
29946            }"#,
29947        )
29948        .unwrap();
29949        let PlanNode::Filter { inner, early, .. } = &plan.root else {
29950            panic!(
29951                "outer FILTER on maybe-unbound ?w must stay Filter(LeftJoin), got {:?}",
29952                plan.root
29953            );
29954        };
29955        assert!(
29956            early.is_some(),
29957            "maybe-unbound identity FILTER must be kept, early={early:?}"
29958        );
29959        let PlanNode::LeftJoin { right, .. } = inner.as_ref() else {
29960            panic!("expected LeftJoin under Filter, got {inner:?}");
29961        };
29962        let PlanNode::Scan(scan) = right.as_ref() else {
29963            panic!("expected optional Scan, got {right:?}");
29964        };
29965        assert_eq!(
29966            scan.pattern.object,
29967            Some(EncodedTerm::from(&Literal::from("Sunny"))),
29968            "optional scan should still be grounded"
29969        );
29970    }
29971
29972    #[test]
29973    fn having_identity_on_optional_group_key_grounds_but_keeps_filter() {
29974        let plan = LogicalPlan::parse(
29975            r#"SELECT ?w (COUNT(*) AS ?c) WHERE {
29976              ?person <http://ex/livesIn> ?city .
29977              OPTIONAL { ?city <http://ex/hasWeather> ?w }
29978            } GROUP BY ?w HAVING (?w = "Sunny")"#,
29979        )
29980        .unwrap();
29981        let mut node = &plan.root;
29982        while let PlanNode::Extend { inner, .. } = node {
29983            node = inner;
29984        }
29985        let PlanNode::Filter { inner, early, .. } = node else {
29986            panic!(
29987                "HAVING on maybe-unbound group key must stay Filter(Group), got {:?}",
29988                plan.root
29989            );
29990        };
29991        assert!(
29992            early.is_some(),
29993            "maybe-unbound identity HAVING must be kept, early={early:?}"
29994        );
29995        assert!(
29996            matches!(inner.as_ref(), PlanNode::Group { .. }),
29997            "HAVING Filter inner should be Group, got {inner:?}"
29998        );
29999        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
30000        let mut grounded = false;
30001        for_each_scan(inner, &mut |scan| {
30002            if scan.object.as_ref().map(Variable::as_str) == Some("w") {
30003                grounded = scan.pattern.object.as_ref() == Some(&sunny);
30004            }
30005        });
30006        assert!(
30007            grounded,
30008            "optional ?w scan should still be grounded, got {inner:?}"
30009        );
30010    }
30011
30012    #[test]
30013    fn ask_inequality_filter_moves_to_the_scan_and_broadcasts() {
30014        let query = SparqlParser::new()
30015            .parse_query(
30016                r#"ASK {
30017                  ?p <http://ex/livesIn> ?c .
30018                  ?c <http://ex/hasWeather> ?w FILTER(?w != "Sunny")
30019                }"#,
30020            )
30021            .unwrap();
30022        let Query::Ask { pattern, .. } = query else {
30023            panic!("expected ASK");
30024        };
30025        let plan = LogicalPlan::from_ask_algebra(pattern, None).unwrap();
30026        assert_eq!(
30027            first_join_strategy(&plan.root),
30028            Some(JoinStrategy::Broadcast)
30029        );
30030        // `!=` is not identity-safe, so the object slot stays a variable; the
30031        // exact comparison moves into the scan's eager authority instead of a
30032        // Filter node.
30033        assert!(
30034            !contains_filter(&plan.root),
30035            "the exact != must move into the scan: {:?}",
30036            plan.root
30037        );
30038        let mut moved = 0;
30039        let mut seen = Vec::new();
30040        for_each_scan(&plan.root, &mut |scan| {
30041            seen.extend(scan.eager.clone());
30042            if scan.eager.contains(&SlotComparison {
30043                slot: QuadSlot::Object,
30044                op: CompareOp::Ne,
30045                term: EncodedTerm::from(&Literal::from("Sunny")),
30046            }) {
30047                moved += 1;
30048                assert!(
30049                    scan.pattern.object.is_none(),
30050                    "!= must not identity-ground the object: {scan:?}"
30051                );
30052            }
30053        });
30054        assert_eq!(
30055            moved, 1,
30056            "one weather scan carries the eager !=; saw {seen:?}"
30057        );
30058        let text = explain_est(
30059            r#"ASK {
30060              ?p <http://ex/livesIn> ?c .
30061              ?c <http://ex/hasWeather> ?w FILTER(?w != "Sunny")
30062            }"#,
30063            None,
30064        );
30065        assert!(!text.contains("(filter"), "{text}");
30066        assert!(text.contains("broadcast"), "{text}");
30067    }
30068
30069    #[test]
30070    fn ask_equality_filter_folds_then_broadcasts_bare_scan() {
30071        let query = SparqlParser::new()
30072            .parse_query(
30073                r#"ASK {
30074                  ?p <http://ex/livesIn> ?c .
30075                  ?c <http://ex/hasWeather> ?w FILTER(?w = "Sunny")
30076                }"#,
30077            )
30078            .unwrap();
30079        let Query::Ask { pattern, .. } = query else {
30080            panic!("expected ASK");
30081        };
30082        let plan = LogicalPlan::from_ask_algebra(pattern, None).unwrap();
30083        assert_eq!(
30084            first_join_strategy(&plan.root),
30085            Some(JoinStrategy::Broadcast)
30086        );
30087        assert!(
30088            !contains_filter(&plan.root),
30089            "folded = should leave a bare Scan, got {:?}",
30090            plan.root
30091        );
30092        let sunny = EncodedTerm::from(&Literal::from("Sunny"));
30093        let mut saw_sunny = false;
30094        for_each_scan(&plan.root, &mut |scan| {
30095            if scan.pattern.object.as_ref() == Some(&sunny) {
30096                saw_sunny = true;
30097                assert_eq!(scan.object.as_ref().map(Variable::as_str), Some("w"));
30098            }
30099        });
30100        assert!(
30101            saw_sunny,
30102            "Sunny should be a bound scan slot: {:?}",
30103            plan.root
30104        );
30105        let text = explain_est(
30106            r#"ASK {
30107              ?p <http://ex/livesIn> ?c .
30108              ?c <http://ex/hasWeather> ?w FILTER(?w = "Sunny")
30109            }"#,
30110            None,
30111        );
30112        assert!(!text.contains("(filter"), "{text}");
30113        assert!(text.contains("\"Sunny\""), "{text}");
30114        assert!(text.contains("broadcast"), "{text}");
30115    }
30116
30117    #[test]
30118    fn sequence_path_stays_bgp_scans() {
30119        let plan =
30120            LogicalPlan::parse(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>/<http://ex/q> ?o }"#)
30121                .unwrap();
30122        assert!(
30123            plan.root.as_path().is_none(),
30124            "simple / must not lower to Path: {:?}",
30125            plan.root
30126        );
30127        let scans = plan.scans().unwrap();
30128        assert_eq!(scans.len(), 2, "expected two BGP scans, got {scans:?}");
30129        assert_eq!(plan.join_ops().unwrap().len(), 1);
30130    }
30131
30132    #[test]
30133    fn inverse_path_stays_swapped_bgp() {
30134        let plan =
30135            LogicalPlan::parse(r#"SELECT ?s WHERE { ?s ^<http://ex/p> <http://ex/b> }"#).unwrap();
30136        assert!(plan.root.as_path().is_none(), "got {:?}", plan.root);
30137        let scans = plan.scans().unwrap();
30138        assert_eq!(scans.len(), 1);
30139        assert_eq!(
30140            scans[0].pattern.subject,
30141            Some(EncodedTerm::from(&NamedNode::new("http://ex/b").unwrap()))
30142        );
30143        assert_eq!(scans[0].object.as_ref().map(Variable::as_str), Some("s"));
30144    }
30145
30146    #[test]
30147    fn star_path_lowers_to_path_node() {
30148        let plan =
30149            LogicalPlan::parse(r#"SELECT ?o WHERE { <http://ex/a> <http://ex/p>* ?o }"#).unwrap();
30150        let path = plan.root.as_path().expect("expected Path");
30151        assert!(matches!(path.path, PropertyPath::ZeroOrMore(_)));
30152        assert!(path.subject_term.is_some());
30153        assert_eq!(path.object.as_ref().map(Variable::as_str), Some("o"));
30154        assert_eq!(plan.projection, vec![var("o")]);
30155    }
30156
30157    #[test]
30158    fn blank_node_path_start_is_unprojected_var() {
30159        let plan = LogicalPlan::parse(r#"SELECT ?o WHERE { _:s <http://ex/p>* ?o }"#).unwrap();
30160        assert_eq!(plan.projection, vec![var("o")]);
30161        let path = plan.root.as_path().expect("expected Path");
30162        let start = path
30163            .subject
30164            .as_ref()
30165            .expect("blank node becomes a variable");
30166        assert_ne!(start, &var("o"));
30167        assert!(!plan.projection.contains(start));
30168        assert!(path.subject_term.is_none());
30169    }
30170
30171    #[test]
30172    fn unbound_star_sorts_after_selective_scan() {
30173        let plan = LogicalPlan::parse(
30174            r#"SELECT ?s ?y WHERE {
30175              ?s <http://ex/p> ?x .
30176              ?x <http://ex/knows>* ?y .
30177            }"#,
30178        )
30179        .unwrap();
30180        let PlanNode::Join {
30181            left, right, meta, ..
30182        } = &plan.root
30183        else {
30184            panic!("expected Join, got {:?}", plan.root);
30185        };
30186        assert!(
30187            left.as_scan().is_some(),
30188            "selective scan should be left of unbound *: {left:?}"
30189        );
30190        let path = right.as_path().expect("Path on the right");
30191        assert!(matches!(path.path, PropertyPath::ZeroOrMore(_)));
30192        assert!(path.subject_term.is_none());
30193        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
30194    }
30195
30196    #[test]
30197    fn open_star_and_plus_cost_as_all_pairs() {
30198        let open_star =
30199            LogicalPlan::parse(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o }"#).unwrap();
30200        let open_plus =
30201            LogicalPlan::parse(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>+ ?o }"#).unwrap();
30202        let bound =
30203            LogicalPlan::parse(r#"SELECT ?o WHERE { <http://ex/a> <http://ex/p>* ?o }"#).unwrap();
30204        let open_star_rows = open_star
30205            .root
30206            .as_path()
30207            .unwrap()
30208            .produced_row_count_estimate;
30209        let open_plus_rows = open_plus
30210            .root
30211            .as_path()
30212            .unwrap()
30213            .produced_row_count_estimate;
30214        let bound_rows = bound.root.as_path().unwrap().produced_row_count_estimate;
30215        assert_eq!(open_star_rows, u64::MAX / 4);
30216        assert_eq!(open_plus_rows, u64::MAX / 4);
30217        assert!(
30218            bound_rows < open_star_rows,
30219            "one-end * must cost below open *: {bound_rows} vs {open_star_rows}"
30220        );
30221    }
30222
30223    #[test]
30224    fn identity_filter_grounds_path_end() {
30225        let sparql = r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o FILTER(?o = <http://ex/t>) }"#;
30226        let plan = LogicalPlan::parse(sparql).unwrap();
30227        assert!(
30228            !contains_filter(&plan.root),
30229            "identity-safe = should fold into the Path, got {:?}",
30230            plan.root
30231        );
30232        let path = plan.root.as_path().expect("expected Path");
30233        assert_eq!(path.object.as_ref().map(Variable::as_str), Some("o"));
30234        assert_eq!(
30235            path.object_term,
30236            Some(EncodedTerm::from(&NamedNode::new("http://ex/t").unwrap()))
30237        );
30238        assert!(
30239            path.produced_row_count_estimate < 1_000_000_000,
30240            "bound end must recost below unbound *: {}",
30241            path.produced_row_count_estimate
30242        );
30243        let text = explain_est(sparql, None);
30244        assert!(!text.contains("(filter"), "{text}");
30245    }
30246
30247    #[test]
30248    fn sameterm_grounds_path_end() {
30249        let plan = LogicalPlan::parse(
30250            r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o FILTER(sameTerm(?o, <http://ex/t>)) }"#,
30251        )
30252        .unwrap();
30253        assert!(
30254            !contains_filter(&plan.root),
30255            "sameTerm should fold into the Path, got {:?}",
30256            plan.root
30257        );
30258        let mut paths = Vec::new();
30259        for_each_path(&plan.root, &mut |path| paths.push(path));
30260        assert_eq!(paths.len(), 1);
30261        assert_eq!(
30262            paths[0].object_term,
30263            Some(EncodedTerm::from(&NamedNode::new("http://ex/t").unwrap()))
30264        );
30265    }
30266
30267    #[test]
30268    fn bind_sameterm_grounds_path_end_and_strings() {
30269        let iri = NamedNode::new("http://yago-knowledge.org/resource/Crow_Hill_Q20861371").unwrap();
30270        let encoded = EncodedTerm::from(&iri);
30271        let expected_strings =
30272            waratah_storage::strings_entries_for_term(&Term::NamedNode(iri.clone()), &encoded);
30273        let plan = LogicalPlan::parse(
30274            r#"SELECT ?s ?o WHERE {
30275              ?s <http://ex/p>* ?o .
30276              BIND(<http://yago-knowledge.org/resource/Crow_Hill_Q20861371> AS ?c)
30277              FILTER(sameTerm(?o, ?c))
30278            }"#,
30279        )
30280        .unwrap();
30281        assert!(
30282            !contains_filter(&plan.root),
30283            "BIND sameTerm should fold into the Path, got {:?}",
30284            plan.root
30285        );
30286        let mut paths = Vec::new();
30287        for_each_path(&plan.root, &mut |path| paths.push(path));
30288        assert_eq!(paths.len(), 1);
30289        assert_eq!(paths[0].object.as_ref().map(Variable::as_str), Some("o"));
30290        assert_eq!(paths[0].object_term, Some(encoded));
30291        for (hash, raw) in &expected_strings {
30292            assert!(
30293                paths[0].strings.iter().any(|(h, s)| h == hash && s == raw),
30294                "path.strings should include {raw}, got {:?}",
30295                paths[0].strings
30296            );
30297        }
30298    }
30299
30300    #[test]
30301    fn numeric_equality_does_not_ground_path() {
30302        let plan =
30303            LogicalPlan::parse(r#"SELECT ?s ?o WHERE { ?s <http://ex/p>* ?o FILTER(?o = 1) }"#)
30304                .unwrap();
30305        assert!(
30306            contains_filter(&plan.root),
30307            "numeric = must stay a Filter, got {:?}",
30308            plan.root
30309        );
30310        let mut paths = Vec::new();
30311        for_each_path(&plan.root, &mut |path| paths.push(path));
30312        assert_eq!(paths.len(), 1);
30313        assert!(
30314            paths[0].object_term.is_none() && paths[0].subject_term.is_none(),
30315            "numeric = must not ground Path ends: {:?}",
30316            paths[0]
30317        );
30318    }
30319
30320    #[test]
30321    fn outer_filter_after_optional_path_keeps_filter() {
30322        let plan = LogicalPlan::parse(
30323            r#"SELECT * WHERE {
30324              ?s <http://ex/p> ?x
30325              OPTIONAL { ?x <http://ex/knows>* ?o }
30326              FILTER(?o = <http://ex/t>)
30327            }"#,
30328        )
30329        .unwrap();
30330        assert!(
30331            contains_filter(&plan.root),
30332            "outer FILTER on maybe-unbound Path var must stay, got {:?}",
30333            plan.root
30334        );
30335        let PlanNode::Filter { inner, early, .. } = &plan.root else {
30336            panic!("expected Filter(LeftJoin), got {:?}", plan.root);
30337        };
30338        assert!(
30339            early.is_some(),
30340            "maybe-unbound identity FILTER must be kept, early={early:?}"
30341        );
30342        let PlanNode::LeftJoin { right, .. } = inner.as_ref() else {
30343            panic!("expected LeftJoin under Filter, got {inner:?}");
30344        };
30345        let mut paths = Vec::new();
30346        for_each_path(right, &mut |path| paths.push(path));
30347        assert_eq!(paths.len(), 1);
30348        assert_eq!(
30349            paths[0].object_term,
30350            Some(EncodedTerm::from(&NamedNode::new("http://ex/t").unwrap())),
30351            "optional Path should still be grounded"
30352        );
30353    }
30354
30355    #[test]
30356    fn graph_var_is_supported_and_blocks_default() {
30357        let plan = LogicalPlan::parse(r#"SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#)
30358            .unwrap();
30359        let scans = plan.scans().unwrap();
30360        assert_eq!(scans.len(), 1);
30361        assert_eq!(scans[0].graph.as_ref().map(Variable::as_str), Some("g"));
30362        assert!(scans[0].pattern.graph_name.is_none());
30363        let filter = scans[0]
30364            .graph_filter
30365            .as_ref()
30366            .expect("unbound GRAPH ?g must send a block-list");
30367        assert!(filter.is_exclude());
30368        assert_eq!(filter.terms(), &[EncodedTerm::DefaultGraph]);
30369        let sse = explain_est(
30370            r#"SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#,
30371            None,
30372        );
30373        assert!(
30374            sse.contains("graph_filter block(1)"),
30375            "EXPLAIN should show the DefaultGraph block-list: {sse}"
30376        );
30377    }
30378
30379    #[test]
30380    fn graph_same_term_grounds_g() {
30381        let plan = LogicalPlan::parse(
30382            r#"SELECT ?s ?g WHERE {
30383              GRAPH ?g { ?s <http://ex/p> ?o }
30384              FILTER(sameTerm(?g, <http://ex/A>))
30385            }"#,
30386        )
30387        .unwrap();
30388        let scans = plan.scans().unwrap();
30389        assert_eq!(scans.len(), 1);
30390        assert_eq!(
30391            scans[0].pattern.graph_name,
30392            Some(EncodedTerm::from(&NamedNode::new("http://ex/A").unwrap()))
30393        );
30394        assert!(
30395            scans[0].graph_filter.is_none(),
30396            "grounded G must not keep a graph_filter: {:?}",
30397            scans[0].graph_filter
30398        );
30399        let sse = explain_est(
30400            r#"SELECT ?s ?g WHERE {
30401              GRAPH ?g { ?s <http://ex/p> ?o }
30402              FILTER(sameTerm(?g, <http://ex/A>))
30403            }"#,
30404            None,
30405        );
30406        assert!(
30407            !sse.contains("graph_filter"),
30408            "grounded G should not show graph_filter: {sse}"
30409        );
30410    }
30411
30412    #[test]
30413    fn graph_not_same_term_folds_into_block_list() {
30414        let plan = LogicalPlan::parse(
30415            r#"SELECT ?s ?g WHERE {
30416              GRAPH ?g { ?s <http://ex/p> ?o }
30417              FILTER(!sameTerm(?g, <http://ex/A>) && !sameTerm(?g, <http://ex/B>))
30418            }"#,
30419        )
30420        .unwrap();
30421        let scans = plan.scans().unwrap();
30422        assert_eq!(scans.len(), 1);
30423        let filter = scans[0]
30424            .graph_filter
30425            .as_ref()
30426            .expect("!sameTerm should fold into the GRAPH block-list");
30427        assert!(filter.is_exclude());
30428        let a = EncodedTerm::from(&NamedNode::new("http://ex/A").unwrap());
30429        let b = EncodedTerm::from(&NamedNode::new("http://ex/B").unwrap());
30430        assert!(filter.contains_member(&EncodedTerm::DefaultGraph));
30431        assert!(filter.contains_member(&a));
30432        assert!(filter.contains_member(&b));
30433        assert_eq!(filter.len(), 3);
30434        assert!(
30435            !contains_filter(&plan.root),
30436            "folded !sameTerm conjuncts should drop the Filter, got {:?}",
30437            plan.root
30438        );
30439    }
30440
30441    #[test]
30442    fn graph_not_same_term_on_optional_pushes_block_list_but_keeps_filter() {
30443        let plan = LogicalPlan::parse(
30444            r#"SELECT ?s ?g WHERE {
30445              ?s <http://ex/p> ?o
30446              OPTIONAL { GRAPH ?g { ?s <http://ex/q> ?x } }
30447              FILTER(!sameTerm(?g, <http://ex/g1>))
30448            }"#,
30449        )
30450        .unwrap();
30451        let PlanNode::Filter { inner, early, .. } = &plan.root else {
30452            panic!(
30453                "maybe-unbound !sameTerm(?g) must stay Filter, got {:?}",
30454                plan.root
30455            );
30456        };
30457        assert!(
30458            early.is_some(),
30459            "OPTIONAL-miss rows need the residual !sameTerm, early={early:?}"
30460        );
30461        let g1 = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
30462        let mut graph_scan_blocked = false;
30463        for_each_scan(inner, &mut |scan| {
30464            if scan.graph.as_ref().map(Variable::as_str) == Some("g") {
30465                graph_scan_blocked = scan
30466                    .graph_filter
30467                    .as_ref()
30468                    .is_some_and(|f| f.is_exclude() && f.contains_member(&g1));
30469            }
30470        });
30471        assert!(
30472            graph_scan_blocked,
30473            "GRAPH scan should still get the g1 block-list, got {inner:?}"
30474        );
30475    }
30476
30477    #[test]
30478    fn graph_not_same_term_on_union_keeps_filter() {
30479        let plan = LogicalPlan::parse(
30480            r#"SELECT ?s ?g WHERE {
30481              { ?s <http://ex/p> ?o }
30482              UNION
30483              { GRAPH ?g { ?s <http://ex/q> ?x } }
30484              FILTER(!sameTerm(?g, <http://ex/g1>))
30485            }"#,
30486        )
30487        .unwrap();
30488        let PlanNode::Filter { inner, early, .. } = &plan.root else {
30489            panic!(
30490                "UNION omit of ?g must keep !sameTerm Filter, got {:?}",
30491                plan.root
30492            );
30493        };
30494        assert!(
30495            early.is_some(),
30496            "UNION arm without ?g needs the residual !sameTerm, early={early:?}"
30497        );
30498        let g1 = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
30499        let mut graph_scan_blocked = false;
30500        for_each_scan(inner, &mut |scan| {
30501            if scan.graph.as_ref().map(Variable::as_str) == Some("g") {
30502                graph_scan_blocked = scan
30503                    .graph_filter
30504                    .as_ref()
30505                    .is_some_and(|f| f.is_exclude() && f.contains_member(&g1));
30506            }
30507        });
30508        assert!(
30509            graph_scan_blocked,
30510            "GRAPH UNION arm should still get the g1 block-list, got {inner:?}"
30511        );
30512    }
30513
30514    #[test]
30515    fn two_triple_graph_join_keys_include_g() {
30516        let plan = LogicalPlan::parse(
30517            r#"SELECT ?s ?x WHERE {
30518              GRAPH ?g { ?s <http://ex/p> ?o . ?o <http://ex/q> ?x }
30519            }"#,
30520        )
30521        .unwrap();
30522        let joins = plan.join_ops().unwrap();
30523        assert_eq!(joins.len(), 1);
30524        assert!(
30525            joins[0].hash_keys.iter().any(|v| v.as_str() == "g"),
30526            "same-graph BGP must join on ?g: {:?}",
30527            joins[0].hash_keys
30528        );
30529        assert!(
30530            joins[0].hash_keys.iter().any(|v| v.as_str() == "o"),
30531            "inner object join key should remain: {:?}",
30532            joins[0].hash_keys
30533        );
30534    }
30535
30536    #[test]
30537    fn from_named_without_from_empties_bare_bgp() {
30538        let plan = LogicalPlan::parse(
30539            r#"SELECT ?s FROM NAMED <http://ex/g> WHERE { ?s <http://ex/p> ?o }"#,
30540        )
30541        .unwrap();
30542        assert!(
30543            matches!(&plan.root, PlanNode::Values(v) if v.rows.is_empty()),
30544            "FROM NAMED without FROM must not scan the SPARQL default graph: {:?}",
30545            plan.root
30546        );
30547    }
30548
30549    #[test]
30550    fn from_named_without_from_empties_bare_path() {
30551        let plan = LogicalPlan::parse(
30552            r#"SELECT ?s FROM NAMED <http://ex/g> WHERE { ?s <http://ex/p>+ ?o }"#,
30553        )
30554        .unwrap();
30555        assert!(
30556            matches!(&plan.root, PlanNode::Values(v) if v.rows.is_empty()),
30557            "empty SPARQL default must empty a default-graph path: {:?}",
30558            plan.root
30559        );
30560    }
30561
30562    #[test]
30563    fn from_named_without_from_keeps_values() {
30564        let plan =
30565            LogicalPlan::parse(r#"SELECT ?x FROM NAMED <http://ex/g> WHERE { VALUES ?x { 1 } }"#)
30566                .unwrap();
30567        match &plan.root {
30568            PlanNode::Values(values) => {
30569                assert_eq!(values.variables, vec![var("x")]);
30570                assert_eq!(values.rows.len(), 1);
30571            }
30572            other => panic!("VALUES is not a default-graph scan: {other:?}"),
30573        }
30574    }
30575
30576    #[test]
30577    fn from_named_without_from_keeps_bind() {
30578        let plan =
30579            LogicalPlan::parse(r#"SELECT ?x FROM NAMED <http://ex/g> WHERE { BIND(1 AS ?x) }"#)
30580                .unwrap();
30581        match &plan.root {
30582            PlanNode::Values(values) => {
30583                assert_eq!(values.variables, vec![var("x")]);
30584                assert_eq!(values.rows.len(), 1);
30585            }
30586            PlanNode::Extend {
30587                inner, variable, ..
30588            } => {
30589                assert_eq!(variable.as_str(), "x");
30590                assert!(
30591                    matches!(inner.as_ref(), PlanNode::Unit),
30592                    "BIND over empty group must keep Unit, got {inner:?}"
30593                );
30594            }
30595            other => panic!("BIND is not a default-graph scan: {other:?}"),
30596        }
30597    }
30598
30599    #[test]
30600    fn from_named_without_from_empty_group_is_unit() {
30601        let plan = LogicalPlan::parse(r#"SELECT * FROM NAMED <http://ex/g> WHERE { }"#).unwrap();
30602        assert!(
30603            matches!(plan.root, PlanNode::Unit),
30604            "empty group is join identity, not 0-row VALUES: {:?}",
30605            plan.root
30606        );
30607    }
30608
30609    #[test]
30610    fn from_named_union_values_with_default_bgp_keeps_values_arm() {
30611        let plan = LogicalPlan::parse(
30612            r#"SELECT ?x FROM NAMED <http://ex/g> WHERE {
30613              { VALUES ?x { 1 } } UNION { ?s <http://ex/p> ?o }
30614            }"#,
30615        )
30616        .unwrap();
30617        fn values_rows(node: &PlanNode) -> Option<usize> {
30618            match node {
30619                PlanNode::Values(values) => Some(values.rows.len()),
30620                PlanNode::Union { left, right } => values_rows(left).or_else(|| values_rows(right)),
30621                PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
30622                    values_rows(left).or_else(|| values_rows(right))
30623                }
30624                PlanNode::Filter { inner, .. }
30625                | PlanNode::Extend { inner, .. }
30626                | PlanNode::Slice { inner, .. }
30627                | PlanNode::Distinct { inner, .. }
30628                | PlanNode::Sort { inner, .. } => values_rows(inner),
30629                _ => None,
30630            }
30631        }
30632        assert!(
30633            values_rows(&plan.root).is_some_and(|n| n == 1),
30634            "UNION VALUES arm must survive empty SPARQL default: {:?}",
30635            plan.root
30636        );
30637    }
30638
30639    #[test]
30640    fn from_named_union_values_join_graph_keeps_tables() {
30641        let plan = LogicalPlan::parse(
30642            r#"SELECT ?s ?g FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2> WHERE {
30643              { VALUES ?g { <http://ex/g1> } } UNION { VALUES ?g { <http://ex/g2> } }
30644              GRAPH ?g { ?s <http://ex/p> ?o }
30645            }"#,
30646        )
30647        .unwrap();
30648        fn nonempty_values(node: &PlanNode) -> bool {
30649            match node {
30650                PlanNode::Values(values) => !values.rows.is_empty(),
30651                PlanNode::Union { left, right }
30652                | PlanNode::Join { left, right, .. }
30653                | PlanNode::LeftJoin { left, right, .. } => {
30654                    nonempty_values(left) || nonempty_values(right)
30655                }
30656                PlanNode::Filter { inner, .. }
30657                | PlanNode::Extend { inner, .. }
30658                | PlanNode::Slice { inner, .. }
30659                | PlanNode::Distinct { inner, .. }
30660                | PlanNode::Sort { inner, .. } => nonempty_values(inner),
30661                _ => false,
30662            }
30663        }
30664        fn has_scan(node: &PlanNode) -> bool {
30665            match node {
30666                PlanNode::Scan(_) => true,
30667                PlanNode::Union { left, right }
30668                | PlanNode::Join { left, right, .. }
30669                | PlanNode::LeftJoin { left, right, .. } => has_scan(left) || has_scan(right),
30670                PlanNode::Filter { inner, .. }
30671                | PlanNode::Extend { inner, .. }
30672                | PlanNode::Slice { inner, .. }
30673                | PlanNode::Distinct { inner, .. }
30674                | PlanNode::Sort { inner, .. } => has_scan(inner),
30675                _ => false,
30676            }
30677        }
30678        assert!(
30679            nonempty_values(&plan.root),
30680            "UNION VALUES ⋈ GRAPH must not wipe VALUES: {:?}",
30681            plan.root
30682        );
30683        assert!(
30684            has_scan(&plan.root),
30685            "GRAPH scan must remain: {:?}",
30686            plan.root
30687        );
30688    }
30689
30690    #[test]
30691    fn from_without_from_named_empties_graph() {
30692        let plan = LogicalPlan::parse(
30693            r#"SELECT ?s ?g FROM <http://ex/g> WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#,
30694        )
30695        .unwrap();
30696        assert!(
30697            matches!(&plan.root, PlanNode::Values(v) if v.rows.is_empty()),
30698            "FROM without FROM NAMED must empty GRAPH: {:?}",
30699            plan.root
30700        );
30701    }
30702
30703    #[test]
30704    fn from_named_graph_var_uses_allow_list() {
30705        let plan = LogicalPlan::parse(
30706            r#"SELECT ?s ?g FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30707               WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#,
30708        )
30709        .unwrap();
30710        let scans = plan.scans().unwrap();
30711        assert_eq!(scans.len(), 1);
30712        let filter = scans[0]
30713            .graph_filter
30714            .as_ref()
30715            .expect("enumerated FROM NAMED must be an allow-list");
30716        assert!(!filter.is_exclude());
30717        assert_eq!(filter.len(), 2);
30718        let sse = explain_est(
30719            r#"SELECT ?s ?g FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30720               WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#,
30721            None,
30722        );
30723        assert!(
30724            sse.contains("graph_filter allow(2)"),
30725            "EXPLAIN should show the FROM NAMED allow-list: {sse}"
30726        );
30727    }
30728
30729    fn tree_has_named_graphs(node: &PlanNode) -> bool {
30730        match node {
30731            PlanNode::NamedGraphs { .. } => true,
30732            PlanNode::Join { left, right, .. }
30733            | PlanNode::Union { left, right }
30734            | PlanNode::LeftJoin { left, right, .. } => {
30735                tree_has_named_graphs(left) || tree_has_named_graphs(right)
30736            }
30737            PlanNode::Filter { inner, .. }
30738            | PlanNode::Extend { inner, .. }
30739            | PlanNode::Slice { inner, .. }
30740            | PlanNode::Distinct { inner, .. }
30741            | PlanNode::Sort { inner, .. }
30742            | PlanNode::Group { inner, .. }
30743            | PlanNode::JoinGraphVar { inner, .. } => tree_has_named_graphs(inner),
30744            _ => false,
30745        }
30746    }
30747
30748    fn tree_has_named_graph_exists(node: &PlanNode) -> bool {
30749        match node {
30750            PlanNode::NamedGraphExists { .. } => true,
30751            PlanNode::Join { left, right, .. }
30752            | PlanNode::Union { left, right }
30753            | PlanNode::LeftJoin { left, right, .. } => {
30754                tree_has_named_graph_exists(left) || tree_has_named_graph_exists(right)
30755            }
30756            PlanNode::Filter { inner, .. }
30757            | PlanNode::Extend { inner, .. }
30758            | PlanNode::Slice { inner, .. }
30759            | PlanNode::Distinct { inner, .. }
30760            | PlanNode::Sort { inner, .. }
30761            | PlanNode::Group { inner, .. }
30762            | PlanNode::JoinGraphVar { inner, .. } => tree_has_named_graph_exists(inner),
30763            _ => false,
30764        }
30765    }
30766
30767    fn tree_has_join_graph_var(node: &PlanNode) -> bool {
30768        match node {
30769            PlanNode::JoinGraphVar { .. } => true,
30770            PlanNode::Join { left, right, .. }
30771            | PlanNode::Union { left, right }
30772            | PlanNode::LeftJoin { left, right, .. } => {
30773                tree_has_join_graph_var(left) || tree_has_join_graph_var(right)
30774            }
30775            PlanNode::Filter { inner, .. }
30776            | PlanNode::Extend { inner, .. }
30777            | PlanNode::Slice { inner, .. }
30778            | PlanNode::Distinct { inner, .. }
30779            | PlanNode::Sort { inner, .. }
30780            | PlanNode::Group { inner, .. } => tree_has_join_graph_var(inner),
30781            _ => false,
30782        }
30783    }
30784
30785    #[test]
30786    fn from_named_scan_free_graph_joins_values_domain() {
30787        let plan = LogicalPlan::parse(
30788            r#"SELECT ?g ?x FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30789               WHERE { GRAPH ?g { VALUES ?x { 1 } } }"#,
30790        )
30791        .unwrap();
30792        assert!(
30793            !tree_has_named_graphs(&plan.root),
30794            "FROM NAMED must not use the catalog leaf: {:?}",
30795            plan.root
30796        );
30797        let PlanNode::Join { hash_keys, .. } = &plan.root else {
30798            panic!(
30799                "expected cartesian Join(domain VALUES, inner VALUES), got {:?}",
30800                plan.root
30801            );
30802        };
30803        assert!(
30804            hash_keys.is_empty(),
30805            "scan-free GRAPH domain join is cartesian, got {hash_keys:?}"
30806        );
30807        let g1 = EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap());
30808        let g2 = EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap());
30809        assert!(
30810            values_has_term(&plan.root, &g1) && values_has_term(&plan.root, &g2),
30811            "domain VALUES must list FROM NAMED IRIs: {:?}",
30812            plan.root
30813        );
30814    }
30815
30816    #[test]
30817    fn engine_empty_graph_iri_is_named_graph_exists() {
30818        let plan = LogicalPlan::parse(r#"SELECT * WHERE { GRAPH <http://ex/g1> { } }"#).unwrap();
30819        match &plan.root {
30820            PlanNode::NamedGraphExists { graph } => {
30821                assert_eq!(
30822                    graph,
30823                    &EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap())
30824                );
30825            }
30826            other => panic!("engine GRAPH <iri> {{ }} must be NamedGraphExists, got {other:?}"),
30827        }
30828    }
30829
30830    #[test]
30831    fn from_named_empty_graph_iri_stays_unit() {
30832        let plan = LogicalPlan::parse(
30833            r#"SELECT * FROM NAMED <http://ex/g1> WHERE { GRAPH <http://ex/g1> { } }"#,
30834        )
30835        .unwrap();
30836        assert!(
30837            matches!(plan.root, PlanNode::Unit),
30838            "FROM NAMED GRAPH <g> {{ }} is dataset membership, not catalog: {:?}",
30839            plan.root
30840        );
30841    }
30842
30843    #[test]
30844    fn values_empty_graph_var_rewrites_named_graphs_to_exists() {
30845        let plan =
30846            LogicalPlan::parse(r#"SELECT ?g WHERE { VALUES ?g { <http://ex/g1> } GRAPH ?g { } }"#)
30847                .unwrap();
30848        assert!(
30849            !tree_has_named_graphs(&plan.root),
30850            "unique VALUES IRI must not list the catalog: {:?}",
30851            plan.root
30852        );
30853        assert!(
30854            tree_has_named_graph_exists(&plan.root),
30855            "expected NamedGraphExists, got {:?}",
30856            plan.root
30857        );
30858    }
30859
30860    #[test]
30861    fn graph_var_optional_uses_join_graph_var() {
30862        let plan = LogicalPlan::parse(
30863            r#"SELECT ?g ?s WHERE { GRAPH ?g { ?s ?p ?o OPTIONAL { ?s ?p ?g } } }"#,
30864        )
30865        .unwrap();
30866        let PlanNode::JoinGraphVar {
30867            inner,
30868            graph_var,
30869            active_var,
30870        } = &plan.root
30871        else {
30872            panic!("expected JoinGraphVar wrap, got {:?}", plan.root);
30873        };
30874        assert_eq!(graph_var.as_str(), "g");
30875        assert!(
30876            active_var.as_str().starts_with("gact_"),
30877            "active G slot must be minted, got {active_var}"
30878        );
30879        let PlanNode::LeftJoin { hash_keys, .. } = inner.as_ref() else {
30880            panic!("expected LeftJoin under JoinGraphVar, got {inner:?}");
30881        };
30882        assert!(
30883            !hash_keys.iter().any(|k| k.as_str() == "g"),
30884            "OPTIONAL must not join on SPARQL ?g: {hash_keys:?}"
30885        );
30886        assert!(
30887            hash_keys.iter().any(|k| k == active_var),
30888            "OPTIONAL should join on the active-graph var: {hash_keys:?}"
30889        );
30890    }
30891
30892    #[test]
30893    fn graph_var_bgp_without_inner_g_keeps_graph_slot() {
30894        let plan = LogicalPlan::parse(r#"SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#)
30895            .unwrap();
30896        let PlanNode::Scan(scan) = &plan.root else {
30897            panic!("expected Scan, got {:?}", plan.root);
30898        };
30899        assert_eq!(scan.graph.as_ref().map(Variable::as_str), Some("g"));
30900        assert!(
30901            !tree_has_join_graph_var(&plan.root),
30902            "P does not mention ?g, so no JoinGraphVar: {:?}",
30903            plan.root
30904        );
30905    }
30906
30907    #[test]
30908    fn engine_empty_graph_var_is_named_graphs_leaf() {
30909        let plan = LogicalPlan::parse(r#"SELECT ?g WHERE { GRAPH ?g { } }"#).unwrap();
30910        match &plan.root {
30911            PlanNode::NamedGraphs {
30912                variable,
30913                produced_row_count_estimate,
30914            } => {
30915                assert_eq!(variable.as_str(), "g");
30916                assert_eq!(*produced_row_count_estimate, NAMED_GRAPHS_ESTIMATED_ROWS);
30917            }
30918            other => panic!("engine GRAPH ?g {{ }} must be NamedGraphs, got {other:?}"),
30919        }
30920    }
30921
30922    #[test]
30923    fn named_graphs_leaf_uses_profile_count() {
30924        let profile = StatsProfile {
30925            named_graph_count: 7,
30926            total_puts: 1,
30927            ..StatsProfile::default()
30928        };
30929        let plan =
30930            LogicalPlan::parse_with_profile(r#"SELECT ?g WHERE { GRAPH ?g { } }"#, Some(&profile))
30931                .unwrap();
30932        assert_eq!(plan.root.produced_row_count_estimate(), 7);
30933    }
30934
30935    #[test]
30936    fn graph_bgp_does_not_cartesian_domain() {
30937        let plan = LogicalPlan::parse(r#"SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://ex/p> ?o } }"#)
30938            .unwrap();
30939        assert!(
30940            matches!(&plan.root, PlanNode::Scan(_)),
30941            "BGP that always binds ?g must stay a Scan, got {:?}",
30942            plan.root
30943        );
30944    }
30945
30946    #[test]
30947    fn nested_graph_var_joins_outer_from_named_domain() {
30948        let plan = LogicalPlan::parse(
30949            r#"SELECT ?g ?h ?s FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30950               WHERE { GRAPH ?g { GRAPH ?h { ?s <http://ex/p> ?o } } }"#,
30951        )
30952        .unwrap();
30953        assert!(
30954            !tree_has_named_graphs(&plan.root),
30955            "FROM NAMED nested GRAPH must not call the catalog: {:?}",
30956            plan.root
30957        );
30958        let mut inner_graphs = Vec::new();
30959        for_each_scan(&plan.root, &mut |scan| {
30960            inner_graphs.push(scan.graph.as_ref().map(Variable::as_str).map(str::to_owned));
30961        });
30962        assert_eq!(
30963            inner_graphs,
30964            vec![Some("h".into())],
30965            "inner scan must stay scoped to ?h: {:?}",
30966            plan.root
30967        );
30968        let PlanNode::Join { hash_keys, .. } = &plan.root else {
30969            panic!(
30970                "expected Join(outer domain, inner GRAPH), got {:?}",
30971                plan.root
30972            );
30973        };
30974        assert!(
30975            hash_keys.is_empty(),
30976            "outer ?g is not on the inner scan, so the domain join is cartesian: {hash_keys:?}"
30977        );
30978    }
30979
30980    #[test]
30981    fn graph_optional_leftjoins_from_named_domain() {
30982        let plan = LogicalPlan::parse(
30983            r#"SELECT ?g ?o FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2>
30984               WHERE { GRAPH ?g { OPTIONAL { <http://ex/s> <http://ex/p> ?o } } }"#,
30985        )
30986        .unwrap();
30987        match &plan.root {
30988            PlanNode::LeftJoin {
30989                left, hash_keys, ..
30990            } => {
30991                assert_eq!(
30992                    hash_keys.iter().map(Variable::as_str).collect::<Vec<_>>(),
30993                    ["g"]
30994                );
30995                assert!(
30996                    matches!(left.as_ref(), PlanNode::Values(_)),
30997                    "required side must be the FROM NAMED domain, got {left:?}"
30998                );
30999            }
31000            other => panic!("expected LeftJoin(domain, scan) on ?g, got {other:?}"),
31001        }
31002    }
31003
31004    #[test]
31005    fn graph_iri_grounds_inner_scan() {
31006        let plan = LogicalPlan::parse(
31007            r#"SELECT ?s WHERE { GRAPH <http://ex/g1> { ?s <http://ex/p> ?o } }"#,
31008        )
31009        .unwrap();
31010        let scans = plan.scans().unwrap();
31011        assert_eq!(scans.len(), 1);
31012        assert_eq!(
31013            scans[0].pattern.graph_name,
31014            Some(EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap()))
31015        );
31016        assert!(scans[0].graph.is_none());
31017        assert!(scans[0].graph_filter.is_none());
31018    }
31019
31020    #[test]
31021    fn from_named_plus_disjoint_values_is_empty_allow() {
31022        let plan = LogicalPlan::parse(
31023            r#"SELECT ?s FROM NAMED <http://ex/g1> WHERE {
31024              VALUES ?g { <http://ex/g2> }
31025              GRAPH ?g { ?s <http://ex/p> ?o }
31026            }"#,
31027        )
31028        .unwrap();
31029        let scans = plan.scans().unwrap();
31030        assert_eq!(scans.len(), 1);
31031        let filter = scans[0]
31032            .graph_filter
31033            .as_ref()
31034            .expect("disjoint G push must keep an empty allow-list, not clear the filter");
31035        assert!(
31036            filter.is_empty_allow(),
31037            "expected empty allow-list, got {filter:?}"
31038        );
31039        assert!(
31040            scans[0].pattern.graph_name.is_none(),
31041            "must not ground G to a graph outside FROM NAMED: {:?}",
31042            scans[0].pattern.graph_name
31043        );
31044    }
31045
31046    #[test]
31047    fn from_named_plus_legal_values_grounds_g() {
31048        let plan = LogicalPlan::parse(
31049            r#"SELECT ?s FROM NAMED <http://ex/g1> FROM NAMED <http://ex/g2> WHERE {
31050              VALUES ?g { <http://ex/g2> }
31051              GRAPH ?g { ?s <http://ex/p> ?o }
31052            }"#,
31053        )
31054        .unwrap();
31055        let scans = plan.scans().unwrap();
31056        assert_eq!(scans.len(), 1);
31057        assert_eq!(
31058            scans[0].pattern.graph_name,
31059            Some(EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap()))
31060        );
31061        assert!(
31062            scans[0].graph_filter.is_none(),
31063            "legal singleton may drop the residual: {:?}",
31064            scans[0].graph_filter
31065        );
31066    }
31067
31068    #[test]
31069    fn from_named_plus_disjoint_same_term_is_empty_allow() {
31070        let plan = LogicalPlan::parse(
31071            r#"SELECT ?s FROM NAMED <http://ex/g1> WHERE {
31072              GRAPH ?g { ?s <http://ex/p> ?o }
31073              FILTER(sameTerm(?g, <http://ex/g2>))
31074            }"#,
31075        )
31076        .unwrap();
31077        let scans = plan.scans().unwrap();
31078        assert_eq!(scans.len(), 1);
31079        let filter = scans[0]
31080            .graph_filter
31081            .as_ref()
31082            .expect("sameTerm outside FROM NAMED must not clear the filter");
31083        assert!(
31084            filter.is_empty_allow(),
31085            "expected empty allow-list, got {filter:?}"
31086        );
31087        assert!(scans[0].pattern.graph_name.is_none());
31088    }
31089
31090    // ---- DomainCounts (Group elimination) rewrite --------------------------
31091
31092    /// Aggregate aliases lower as `Extend { alias <- internal agg var }` over
31093    /// the Group; unwrap it to the node the Group lowered to.
31094    fn domain_counts_root(plan: &LogicalPlan) -> Option<(&DomainScanKind, &Variable, &Variable)> {
31095        let PlanNode::Extend {
31096            inner,
31097            variable: alias,
31098            expression: Expression::Variable(copy),
31099            ..
31100        } = &plan.root
31101        else {
31102            return None;
31103        };
31104        let PlanNode::DomainCounts {
31105            kind, head, count, ..
31106        } = inner.as_ref()
31107        else {
31108            return None;
31109        };
31110        (copy == count).then_some((kind, head, alias))
31111    }
31112
31113    #[test]
31114    fn group_count_var_lowers_to_domain_counts() {
31115        let plan = LogicalPlan::parse(
31116            "SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31117        )
31118        .unwrap();
31119        let Some((_, head, alias)) = domain_counts_root(&plan) else {
31120            panic!(
31121                "expected DomainCounts under the alias Extend, got {:?}",
31122                plan.root
31123            );
31124        };
31125        assert_eq!(head.as_str(), "o");
31126        assert_eq!(alias.as_str(), "n");
31127        // Output schema matches the replaced Group: the head key plus the
31128        // internal count variable, with the alias mapping applied above.
31129        let vars = plan.root.variables();
31130        assert!(vars.contains(&var("o")) && vars.contains(&var("n")));
31131    }
31132
31133    #[test]
31134    fn group_count_star_lowers_to_domain_counts() {
31135        let plan = LogicalPlan::parse(
31136            "SELECT ?o (COUNT(*) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31137        )
31138        .unwrap();
31139        assert!(domain_counts_root(&plan).is_some());
31140    }
31141
31142    #[test]
31143    fn group_count_on_object_head_lowers_to_domain_counts() {
31144        // Predicates constrained (const), objects grouped, subjects counted:
31145        // the `PredicateDomain` kind (constraint P -> distinct O on POSG).
31146        let plan = LogicalPlan::parse(
31147            "SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31148        )
31149        .unwrap();
31150        assert!(domain_counts_root(&plan).is_some());
31151    }
31152
31153    #[test]
31154    fn group_count_on_predicate_head_lowers_to_domain_counts() {
31155        // Objects constrained (const), predicates grouped, subjects counted:
31156        // the `ObjectPreds` kind (constraint O -> distinct P on OPSG).
31157        let plan = LogicalPlan::parse(
31158            "SELECT ?p (COUNT(?s) AS ?n) WHERE { ?s ?p <http://ex/o> } GROUP BY ?p",
31159        )
31160        .unwrap();
31161        assert!(
31162            domain_counts_root(&plan).is_some(),
31163            "root = {:?}",
31164            plan.root
31165        );
31166    }
31167
31168    #[test]
31169    fn domain_counts_explain_renders_kind_and_estimate() {
31170        let text = explain_est(
31171            "SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31172            None,
31173        );
31174        assert!(
31175            text.contains("domain_counts") && text.contains("predicate_domain@posg"),
31176            "unexpected explain: {text}"
31177        );
31178    }
31179
31180    /// Zero-row edge: the two count relations share no region, so the
31181    /// key join is empty and the single-group SUM must still return one
31182    /// row holding zero — the plain join's COUNT(*) answer.
31183    #[tokio::test]
31184    async fn count_split_empty_relation_join_yields_zero() {
31185        use crate::error::RetryPolicy;
31186        use crate::query::caches::QueryCaches;
31187        use crate::query::fixtures::{CountingStore, NullResolve, count_split_quads_disjoint};
31188        use oxsdatatypes::Integer;
31189        use waratah_router::ClusterConfig;
31190        use waratah_storage::SnapshotId;
31191
31192        let store = CountingStore::new(count_split_quads_disjoint());
31193        let engine = crate::query::QueryEngine::new(
31194            store,
31195            NullResolve,
31196            ClusterConfig::local_dev().router(16).unwrap(),
31197            RetryPolicy::none(),
31198        );
31199        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
31200        let mut cache = QueryCaches::new();
31201        let solutions = engine
31202            .execute_node(&count_split_probe::root(), &ctx, &mut cache, None)
31203            .await
31204            .unwrap();
31205        assert_eq!(solutions.len(), 1, "the implicit group still has one row");
31206        let rows = solutions.optional_rows().unwrap();
31207        assert_eq!(
31208            rows[0][0],
31209            Some(EncodedTerm::IntegerLiteral(Integer::from(0)))
31210        );
31211    }
31212
31213    /// Count-split probe, eager path: the emitted shape must execute
31214    /// exactly as a NON-ROOT plan — the `DomainCounts` op is re-entrant
31215    /// as a plain row source, its count terms flow through the join as
31216    /// numerics, and the `Multiply`/`SUM` combine folds them to the
31217    /// hand-computed 23 (the shape and fixture are documented on
31218    /// [`count_split_probe`]).
31219    #[tokio::test]
31220    async fn count_split_emitted_shape_executes_and_sums_exactly() {
31221        use crate::error::RetryPolicy;
31222        use crate::query::caches::QueryCaches;
31223        use crate::query::fixtures::{CountingStore, NullResolve, count_split_quads};
31224        use oxsdatatypes::Integer;
31225        use waratah_router::ClusterConfig;
31226        use waratah_storage::SnapshotId;
31227
31228        let store = CountingStore::new(count_split_quads());
31229        let engine = crate::query::QueryEngine::new(
31230            store,
31231            NullResolve,
31232            ClusterConfig::local_dev().router(16).unwrap(),
31233            RetryPolicy::none(),
31234        );
31235        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
31236        let mut cache = QueryCaches::new();
31237        let solutions = engine
31238            .execute_node(&count_split_probe::root(), &ctx, &mut cache, None)
31239            .await
31240            .unwrap();
31241        assert_eq!(solutions.len(), 1, "a bare count folds to exactly one row");
31242        let rows = solutions.optional_rows().unwrap();
31243        assert_eq!(
31244            rows[0][0],
31245            Some(EncodedTerm::IntegerLiteral(Integer::from(23))),
31246            "the sum-of-products combine must reproduce the join's count exactly"
31247        );
31248    }
31249
31250    // ---- Count-split rewrite ----------------------------------------------
31251
31252    /// The two join arms of a fired count-split, if the plan has the shape:
31253    /// alias `Extend` over the sum `Group` over the product `Extend` over
31254    /// the key join.
31255    fn count_split_arms(plan: &LogicalPlan) -> Option<(&PlanNode, &PlanNode)> {
31256        let PlanNode::Extend { inner, .. } = &plan.root else {
31257            return None;
31258        };
31259        let PlanNode::Group {
31260            inner,
31261            variables,
31262            aggregates,
31263            ..
31264        } = inner.as_ref()
31265        else {
31266            return None;
31267        };
31268        if !variables.is_empty()
31269            || !matches!(
31270                &aggregates[0].1,
31271                AggregateExpression::FunctionCall {
31272                    name: AggregateFunction::Sum,
31273                    ..
31274                }
31275            )
31276        {
31277            return None;
31278        }
31279        let PlanNode::Extend {
31280            inner,
31281            expression: Expression::Multiply(..),
31282            ..
31283        } = inner.as_ref()
31284        else {
31285            return None;
31286        };
31287        let PlanNode::Join { left, right, .. } = inner.as_ref() else {
31288            return None;
31289        };
31290        Some((left, right))
31291    }
31292
31293    /// Live profile seeded with the coverage-sites shape: occurrence rows
31294    /// spanning `regions` objects, typed sites, and withinIBRA pairs — the
31295    /// priced product sits far above the head-domain threshold.
31296    fn count_split_profile(rows: u32, sites: u32, within: u32, regions: u32) -> StatsProfile {
31297        let mut live = LiveQuadsProfile::default();
31298        let ibra = NamedNode::new("http://ex/ibraRegion").unwrap();
31299        let ty = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
31300        let site_class = NamedNode::new("https://w3id.org/tern/Site").unwrap();
31301        let pwithin = NamedNode::new("http://ex/withinIBRA").unwrap();
31302        let mut observe = |s: NamedNode, p: &NamedNode, o: NamedNode| {
31303            let quad = waratah_storage::Quad::new(
31304                s,
31305                p.clone(),
31306                o,
31307                waratah_storage::GraphName::DefaultGraph,
31308            );
31309            observe_quad(&mut live, &encode_quad(&quad).unwrap(), StorageOp::Put);
31310        };
31311        for i in 0..rows {
31312            observe(
31313                NamedNode::new(format!("http://ex/occ{i}")).unwrap(),
31314                &ibra,
31315                NamedNode::new(format!("http://ex/r{}", i % regions)).unwrap(),
31316            );
31317        }
31318        for i in 0..sites {
31319            observe(
31320                NamedNode::new(format!("http://ex/site{i}")).unwrap(),
31321                &ty,
31322                site_class.clone(),
31323            );
31324        }
31325        for i in 0..within {
31326            observe(
31327                NamedNode::new(format!("http://ex/site{}", i % sites.max(1))).unwrap(),
31328                &pwithin,
31329                NamedNode::new(format!("http://ex/r{}", i % regions)).unwrap(),
31330            );
31331        }
31332        StatsProfile::from(live)
31333    }
31334
31335    const COVERAGE_SITES: &str = r#"
31336        SELECT (COUNT(*) AS ?n) WHERE {
31337          ?occ <http://ex/ibraRegion> ?r .
31338          ?site a <https://w3id.org/tern/Site> ;
31339                <http://ex/withinIBRA> ?r .
31340        }
31341    "#;
31342
31343    fn is_predicate_domain_relation(arm: &PlanNode, predicate: &str, key: &str) -> bool {
31344        let predicate = EncodedTerm::from(&NamedNode::new(predicate).unwrap());
31345        matches!(
31346            arm,
31347            PlanNode::DomainCounts {
31348                kind: DomainScanKind::PredicateDomain,
31349                constraints,
31350                head,
31351                ..
31352            } if head == &var(key) && constraints.as_slice() == [predicate]
31353        )
31354    }
31355
31356    fn is_key_count_collapse(arm: &PlanNode, key: &str) -> bool {
31357        let PlanNode::Group {
31358            variables,
31359            aggregates,
31360            ..
31361        } = arm
31362        else {
31363            return false;
31364        };
31365        variables.as_slice() == [var(key)]
31366            && matches!(
31367                &aggregates[0].1,
31368                AggregateExpression::CountSolutions { distinct: false }
31369            )
31370    }
31371
31372    #[test]
31373    fn count_split_fires_on_bare_join_count() {
31374        let profile = count_split_profile(40_000, 600, 700, 37);
31375        let plan = LogicalPlan::parse_with_profile(COVERAGE_SITES, Some(&profile)).unwrap();
31376        let Some((left, right)) = count_split_arms(&plan) else {
31377            panic!("expected a count-split plan, got {:?}", plan.root);
31378        };
31379        assert!(
31380            is_predicate_domain_relation(left, "http://ex/ibraRegion", "r")
31381                && is_key_count_collapse(right, "r")
31382                || is_predicate_domain_relation(right, "http://ex/ibraRegion", "r")
31383                    && is_key_count_collapse(left, "r"),
31384            "expected the occurrence DomainCounts relation plus the site collapse, \
31385             got {left:?} and {right:?}"
31386        );
31387    }
31388
31389    #[test]
31390    fn count_split_binds_a_counted_variable_to_the_dead_slot() {
31391        let profile = count_split_profile(40_000, 600, 700, 37);
31392        let plan = LogicalPlan::parse_with_profile(
31393            r#"
31394            SELECT (COUNT(?occ) AS ?n) WHERE {
31395              ?occ <http://ex/ibraRegion> ?r .
31396              ?site a <https://w3id.org/tern/Site> ;
31397                    <http://ex/withinIBRA> ?r .
31398            }
31399            "#,
31400            Some(&profile),
31401        )
31402        .unwrap();
31403        let Some((left, right)) = count_split_arms(&plan) else {
31404            panic!("expected a count-split plan, got {:?}", plan.root);
31405        };
31406        let relation = if is_predicate_domain_relation(left, "http://ex/ibraRegion", "r") {
31407            left
31408        } else {
31409            assert!(
31410                is_predicate_domain_relation(right, "http://ex/ibraRegion", "r"),
31411                "expected the occurrence DomainCounts relation, got {right:?}"
31412            );
31413            right
31414        };
31415        let PlanNode::DomainCounts {
31416            dead, count_star, ..
31417        } = relation
31418        else {
31419            unreachable!("relation matched as DomainCounts");
31420        };
31421        assert_eq!(dead.as_ref(), Some(&var("occ")));
31422        assert!(!count_star, "COUNT(?occ) keeps the counted spelling");
31423    }
31424
31425    #[test]
31426    fn count_split_serves_two_storage_arms() {
31427        let mut live = LiveQuadsProfile::default();
31428        let p1 = NamedNode::new("http://ex/p1").unwrap();
31429        let p2 = NamedNode::new("http://ex/p2").unwrap();
31430        for i in 0..2_000 {
31431            let key = NamedNode::new(format!("http://ex/k{}", i % 40)).unwrap();
31432            for predicate in [&p1, &p2] {
31433                let quad = waratah_storage::Quad::new(
31434                    NamedNode::new(format!("http://ex/a{i}")).unwrap(),
31435                    predicate.clone(),
31436                    key.clone(),
31437                    waratah_storage::GraphName::DefaultGraph,
31438                );
31439                observe_quad(&mut live, &encode_quad(&quad).unwrap(), StorageOp::Put);
31440            }
31441        }
31442        let profile = StatsProfile::from(live);
31443        let plan = LogicalPlan::parse_with_profile(
31444            r#"SELECT (COUNT(*) AS ?n) WHERE {
31445                 ?a <http://ex/p1> ?k . ?b <http://ex/p2> ?k
31446               }"#,
31447            Some(&profile),
31448        )
31449        .unwrap();
31450        let Some((left, right)) = count_split_arms(&plan) else {
31451            panic!("expected a count-split plan, got {:?}", plan.root);
31452        };
31453        assert!(
31454            matches!(left, PlanNode::DomainCounts { .. })
31455                && matches!(right, PlanNode::DomainCounts { .. }),
31456            "both arms should be stored relations, got {left:?} and {right:?}"
31457        );
31458    }
31459
31460    #[test]
31461    fn count_split_refuses_distinct_count() {
31462        let profile = count_split_profile(40_000, 600, 700, 37);
31463        let plan = LogicalPlan::parse_with_profile(
31464            r#"
31465            SELECT (COUNT(DISTINCT ?occ) AS ?n) WHERE {
31466              ?occ <http://ex/ibraRegion> ?r .
31467              ?site a <https://w3id.org/tern/Site> ;
31468                    <http://ex/withinIBRA> ?r .
31469            }
31470            "#,
31471            Some(&profile),
31472        )
31473        .unwrap();
31474        assert!(count_split_arms(&plan).is_none());
31475    }
31476
31477    #[test]
31478    fn count_split_refuses_group_by() {
31479        let profile = count_split_profile(40_000, 600, 700, 37);
31480        let plan = LogicalPlan::parse_with_profile(
31481            r#"
31482            SELECT ?r (COUNT(*) AS ?n) WHERE {
31483              ?occ <http://ex/ibraRegion> ?r .
31484              ?site a <https://w3id.org/tern/Site> ;
31485                    <http://ex/withinIBRA> ?r .
31486            }
31487            GROUP BY ?r
31488            "#,
31489            Some(&profile),
31490        )
31491        .unwrap();
31492        assert!(count_split_arms(&plan).is_none());
31493    }
31494
31495    #[test]
31496    fn count_split_refuses_without_profile() {
31497        // No stats means no honest product-versus-read comparison: the
31498        // row-shipping plan stays.
31499        let plan = LogicalPlan::parse(COVERAGE_SITES).unwrap();
31500        assert!(count_split_arms(&plan).is_none());
31501    }
31502
31503    #[test]
31504    fn count_split_refuses_without_a_storage_countable_arm() {
31505        // Unbound predicates: no slot family has the join key on its head
31506        // with the constraint slot anchored.
31507        let profile = count_split_profile(40_000, 600, 700, 37);
31508        let plan = LogicalPlan::parse_with_profile(
31509            r#"SELECT (COUNT(*) AS ?n) WHERE { ?a ?p1 ?k . ?b ?p2 ?k }"#,
31510            Some(&profile),
31511        )
31512        .unwrap();
31513        assert!(count_split_arms(&plan).is_none());
31514    }
31515
31516    /// End to end: the fired rewrite must produce the same answer as the
31517    /// plain join plan on the same data — structural equivalence is not
31518    /// enough, the emitted relations and combine must sum to the join's
31519    /// count exactly.
31520    #[tokio::test]
31521    async fn count_split_rewrite_matches_the_plain_plan_exactly() {
31522        use crate::error::RetryPolicy;
31523        use crate::query::caches::QueryCaches;
31524        use crate::query::fixtures::{CountingStore, NullResolve, count_split_quads};
31525        use oxsdatatypes::Integer;
31526        use waratah_router::ClusterConfig;
31527        use waratah_storage::SnapshotId;
31528
31529        let run = |plan: &LogicalPlan| {
31530            let engine = crate::query::QueryEngine::new(
31531                CountingStore::new(count_split_quads()),
31532                NullResolve,
31533                ClusterConfig::local_dev().router(16).unwrap(),
31534                RetryPolicy::none(),
31535            );
31536            let ctx = QueryContext::from_snapshot(SnapshotId::latest());
31537            let mut cache = QueryCaches::new();
31538            let root = plan.root.clone();
31539            async move {
31540                engine
31541                    .execute_node(&root, &ctx, &mut cache, None)
31542                    .await
31543                    .unwrap()
31544            }
31545        };
31546
31547        let split = LogicalPlan::parse_with_profile(
31548            COVERAGE_SITES,
31549            Some(&count_split_profile(40_000, 600, 700, 37)),
31550        )
31551        .unwrap();
31552        assert!(
31553            count_split_arms(&split).is_some(),
31554            "the firing profile must actually fire, got {:?}",
31555            split.root
31556        );
31557        let plain = LogicalPlan::parse(COVERAGE_SITES).unwrap();
31558        assert!(count_split_arms(&plain).is_none(), "no profile, no split");
31559
31560        let split_rows = run(&split).await.optional_rows().unwrap();
31561        let plain_rows = run(&plain).await.optional_rows().unwrap();
31562        assert_eq!(split_rows.len(), 1);
31563        assert_eq!(
31564            split_rows, plain_rows,
31565            "the count-split answer must equal the plain join's answer"
31566        );
31567        assert_eq!(
31568            split_rows[0][0],
31569            Some(EncodedTerm::IntegerLiteral(Integer::from(23)))
31570        );
31571    }
31572
31573    // ---- PredicateSubjects (PSOG) domain scans ----------------------------
31574
31575    /// PSOG is the only remaining domain-scan family: the O partition owns
31576    /// OPSG and TSG, there is no OSPG. A P-constrained pattern with a live
31577    /// subject head and a dead object is exactly the missing permutation.
31578    #[test]
31579    fn group_count_on_subject_head_lowers_to_predicate_subjects() {
31580        const QUERY: &str = "SELECT ?s (COUNT(*) AS ?n) WHERE { ?s <http://ex/p> ?o } GROUP BY ?s";
31581        let plan = LogicalPlan::parse(QUERY).unwrap();
31582        let Some((kind, head, alias)) = domain_counts_root(&plan) else {
31583            panic!("expected DomainCounts under alias, got {:?}", plan.root);
31584        };
31585        assert_eq!(*kind, DomainScanKind::PredicateSubjects);
31586        assert_eq!(head.as_str(), "s");
31587        assert_eq!(alias.as_str(), "n");
31588        assert!(
31589            explain_est(QUERY, None).contains("predicate_subjects@psog"),
31590            "EXPLAIN must name the new kind and its axis"
31591        );
31592    }
31593
31594    #[test]
31595    fn distinct_subject_head_lowers_to_predicate_subjects_stamp() {
31596        let text = explain_est("SELECT DISTINCT ?s WHERE { ?s <http://ex/p> ?o }", None);
31597        assert!(
31598            text.contains("domain_scan predicate_subjects@psog"),
31599            "unexpected explain: {text}"
31600        );
31601    }
31602
31603    /// Fixture-level PSOG run-length read: the dead O slot's multiplicity is
31604    /// the count, and the live S slot is returned as the group key. The real
31605    /// partition path is covered by the gRPC integration test in
31606    /// `select_query.rs`.
31607    #[tokio::test]
31608    async fn predicate_subjects_counts_execute_on_psog_walk() {
31609        use crate::error::RetryPolicy;
31610        use crate::query::caches::QueryCaches;
31611        use crate::query::fixtures::{CountingStore, NullResolve};
31612        use oxsdatatypes::Integer;
31613        use waratah_router::ClusterConfig;
31614        use waratah_storage::{GraphName, Quad, SnapshotId};
31615
31616        let p = NamedNode::new("http://ex/p").unwrap();
31617        let quad = |s: &str, o: &str| {
31618            Quad::new(
31619                NamedNode::new(s).unwrap(),
31620                p.clone(),
31621                NamedNode::new(o).unwrap(),
31622                GraphName::DefaultGraph,
31623            )
31624        };
31625        let store = CountingStore::new(vec![
31626            quad("http://ex/a1", "http://ex/x1"),
31627            quad("http://ex/a1", "http://ex/x2"),
31628            quad("http://ex/a2", "http://ex/x1"),
31629        ]);
31630        let engine = crate::query::QueryEngine::new(
31631            store,
31632            NullResolve,
31633            ClusterConfig::local_dev().router(16).unwrap(),
31634            RetryPolicy::none(),
31635        );
31636        let plan = LogicalPlan::parse(
31637            "SELECT ?s (COUNT(*) AS ?n) WHERE { ?s <http://ex/p> ?o } GROUP BY ?s",
31638        )
31639        .unwrap();
31640        let root = plan.root.clone();
31641        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
31642        let mut cache = QueryCaches::new();
31643        let solutions = engine
31644            .execute_node(&root, &ctx, &mut cache, None)
31645            .await
31646            .unwrap();
31647        let rows = solutions.optional_rows().unwrap();
31648        assert_eq!(rows.len(), 2, "one row per distinct subject head");
31649        let a1 = EncodedTerm::from(&NamedNode::new("http://ex/a1").unwrap());
31650        let a2 = EncodedTerm::from(&NamedNode::new("http://ex/a2").unwrap());
31651        let mut got: Vec<_> = rows
31652            .iter()
31653            .map(|row| (row[0].clone().unwrap(), row[1].clone().unwrap()))
31654            .collect();
31655        got.sort_by_key(|(subject, _)| if *subject == a1 { 0 } else { 1 });
31656        assert_eq!(
31657            got,
31658            [
31659                (a1, EncodedTerm::IntegerLiteral(Integer::from(2))),
31660                (a2, EncodedTerm::IntegerLiteral(Integer::from(1))),
31661            ]
31662        );
31663    }
31664
31665    /// The count-split's kind-generic classifier must pick up PSOG: a
31666    /// chain whose single-scan arm has its join key on the S slot is now
31667    /// storage-countable, with the other arm collapsed in compute.
31668    #[test]
31669    fn count_split_uses_predicate_subjects_for_s_head_arms() {
31670        let mut live = LiveQuadsProfile::default();
31671        let mut observe = |s: &str, p: &NamedNode, o: &str| {
31672            let quad = waratah_storage::Quad::new(
31673                NamedNode::new(s).unwrap(),
31674                p.clone(),
31675                NamedNode::new(o).unwrap(),
31676                waratah_storage::GraphName::DefaultGraph,
31677            );
31678            observe_quad(&mut live, &encode_quad(&quad).unwrap(), StorageOp::Put);
31679        };
31680        let p1 = NamedNode::new("http://ex/p1").unwrap();
31681        let p2 = NamedNode::new("http://ex/p2").unwrap();
31682        let p3 = NamedNode::new("http://ex/p3").unwrap();
31683        for i in 0..20_000 {
31684            observe(
31685                &format!("http://ex/s{}", i % 40),
31686                &p1,
31687                &format!("http://ex/o{i}"),
31688            );
31689        }
31690        for i in 0..2_000 {
31691            observe(
31692                &format!("http://ex/s{}", i % 40),
31693                &p2,
31694                &format!("http://ex/v{i}"),
31695            );
31696            observe(&format!("http://ex/v{i}"), &p3, &format!("http://ex/w{i}"));
31697        }
31698        let profile = StatsProfile::from(live);
31699        let plan = LogicalPlan::parse_with_profile(
31700            r#"SELECT (COUNT(*) AS ?n) WHERE {
31701                 ?s <http://ex/p1> ?o . ?s <http://ex/p2> ?v . ?v <http://ex/p3> ?w
31702               }"#,
31703            Some(&profile),
31704        )
31705        .unwrap();
31706        let Some((left, right)) = count_split_arms(&plan) else {
31707            panic!("expected a count-split plan, got {:?}", plan.root);
31708        };
31709        let stored = [left, right].into_iter().find(|arm| {
31710            matches!(
31711                arm,
31712                PlanNode::DomainCounts {
31713                    kind: DomainScanKind::PredicateSubjects,
31714                    ..
31715                }
31716            )
31717        });
31718        assert!(
31719            stored.is_some(),
31720            "expected a PSOG DomainCounts relation, got {left:?} and {right:?}"
31721        );
31722    }
31723
31724    /// The head-count rewrite root, if the plan replaced the Group with a
31725    /// [`PlanNode::HeadCounts`] leaf.
31726    fn head_counts_root(plan: &LogicalPlan) -> Option<(&HeadScanKind, bool, &Variable, &Variable)> {
31727        let PlanNode::Extend {
31728            inner,
31729            variable: _alias,
31730            expression: Expression::Variable(copy),
31731            ..
31732        } = &plan.root
31733        else {
31734            return None;
31735        };
31736        let PlanNode::HeadCounts {
31737            kind,
31738            total,
31739            counted,
31740            count,
31741            ..
31742        } = inner.as_ref()
31743        else {
31744            return None;
31745        };
31746        // The Extend copies the node's count column onto the SELECT alias.
31747        debug_assert_eq!(copy, count);
31748        Some((kind, *total, counted, count))
31749    }
31750
31751    /// Flagship: `?f a ?cls GROUP BY ?cls COUNT(DISTINCT ?f)` matches BOTH
31752    /// count rewrites; the head pass runs first and TSG — the smaller,
31753    /// type-dense CF — wins.
31754    #[test]
31755    fn flagship_type_distinct_count_rewrites_to_tsg_head_counts() {
31756        let plan = LogicalPlan::parse(
31757            "SELECT ?cls (COUNT(DISTINCT ?f) AS ?n) WHERE { ?f a ?cls } GROUP BY ?cls",
31758        )
31759        .unwrap();
31760        let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31761            panic!("expected a HeadCounts root: {:?}", plan.root);
31762        };
31763        assert_eq!(*kind, HeadScanKind::Classes);
31764        assert!(!total, "grouped shape is PER_HEAD");
31765        assert_eq!(counted.as_str(), "f");
31766        assert!(domain_counts_root(&plan).is_none(), "head pass wins");
31767    }
31768
31769    /// Ungrouped distinct class count: the TOTAL shape, one RPC row.
31770    #[test]
31771    fn ungrouped_class_distinct_count_rewrites_to_tsg_total() {
31772        let plan =
31773            LogicalPlan::parse("SELECT (COUNT(DISTINCT ?cls) AS ?c) WHERE { ?f a ?cls }").unwrap();
31774        let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31775            panic!("expected a HeadCounts root: {:?}", plan.root);
31776        };
31777        assert_eq!(*kind, HeadScanKind::Classes);
31778        assert!(total);
31779        assert_eq!(counted.as_str(), "cls");
31780    }
31781
31782    /// Bare patterns map each slot-0 variable to its own axis family.
31783    #[test]
31784    fn bare_patterns_rewrite_per_head_counts_by_axis() {
31785        // Subjects (SPOG), PER_HEAD.
31786        let plan = LogicalPlan::parse(
31787            "SELECT ?s (COUNT(DISTINCT ?p) AS ?n) WHERE { ?s ?p ?o } GROUP BY ?s",
31788        )
31789        .unwrap();
31790        let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31791            panic!("expected a HeadCounts root: {:?}", plan.root);
31792        };
31793        assert_eq!(*kind, HeadScanKind::Subjects);
31794        assert!(!total);
31795        assert_eq!(counted.as_str(), "p");
31796
31797        // Objects (OPSG), TOTAL.
31798        let plan =
31799            LogicalPlan::parse("SELECT (COUNT(DISTINCT ?o) AS ?c) WHERE { ?s ?p ?o }").unwrap();
31800        let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31801            panic!("expected a HeadCounts root: {:?}", plan.root);
31802        };
31803        assert_eq!(*kind, HeadScanKind::Objects);
31804        assert!(total);
31805        assert_eq!(counted.as_str(), "o");
31806
31807        // Predicates (PSOG), PER_HEAD.
31808        let plan = LogicalPlan::parse(
31809            "SELECT ?p (COUNT(DISTINCT ?s) AS ?n) WHERE { ?s ?p ?o } GROUP BY ?p",
31810        )
31811        .unwrap();
31812        let Some((kind, total, counted, _)) = head_counts_root(&plan) else {
31813            panic!("expected a HeadCounts root: {:?}", plan.root);
31814        };
31815        assert_eq!(*kind, HeadScanKind::Predicates);
31816        assert!(!total);
31817        assert_eq!(counted.as_str(), "s");
31818    }
31819
31820    /// Trap 2: an ungrouped `COUNT(DISTINCT ?f)` over the type pattern counts
31821    /// distinct SUBJECTS — which no CF head can serve as one number (subjects
31822    /// are not TSG's head, and per-class counts would overcount subjects in
31823    /// several classes). Must stay on the generic group path.
31824    #[test]
31825    fn ungrouped_subject_distinct_count_over_types_stays_generic() {
31826        let plan =
31827            LogicalPlan::parse("SELECT (COUNT(DISTINCT ?f) AS ?c) WHERE { ?f a ?cls }").unwrap();
31828        assert!(head_counts_root(&plan).is_none());
31829        assert!(domain_counts_root(&plan).is_none());
31830        assert!(matches!(find_group(&plan.root), PlanNode::Group { .. }));
31831    }
31832
31833    /// Refusals: the rewrite needs one distinct-count aggregate over a bare,
31834    /// anchor-free scan.
31835    #[test]
31836    fn head_counts_rewrite_refusals() {
31837        // Plain count: bag demand.
31838        let plan =
31839            LogicalPlan::parse("SELECT ?cls (COUNT(?f) AS ?n) WHERE { ?f a ?cls } GROUP BY ?cls")
31840                .unwrap();
31841        assert!(head_counts_root(&plan).is_none());
31842        // COUNT(*): bag demand.
31843        let plan =
31844            LogicalPlan::parse("SELECT ?cls (COUNT(*) AS ?n) WHERE { ?f a ?cls } GROUP BY ?cls")
31845                .unwrap();
31846        assert!(head_counts_root(&plan).is_none());
31847        // COUNT(DISTINCT *): whole-mapping rule.
31848        let plan = LogicalPlan::parse(
31849            "SELECT ?cls (COUNT(DISTINCT *) AS ?n) WHERE { ?f a ?cls } GROUP BY ?cls",
31850        )
31851        .unwrap();
31852        assert!(head_counts_root(&plan).is_none());
31853        // Two aggregates: beyond the narrow shortcut (the ScanOp-residual
31854        // path or the generic group serves these).
31855        let plan = LogicalPlan::parse(
31856            "SELECT ?cls (COUNT(DISTINCT ?f) AS ?n) (COUNT(DISTINCT ?f) AS ?m) WHERE { ?f a ?cls } GROUP BY ?cls",
31857        )
31858        .unwrap();
31859        assert!(head_counts_root(&plan).is_none());
31860        // Anchored scan (bound object): not a head-count shape.
31861        let plan =
31862            LogicalPlan::parse("SELECT (COUNT(DISTINCT ?f) AS ?c) WHERE { ?f a <http://ex/C> }")
31863                .unwrap();
31864        assert!(head_counts_root(&plan).is_none());
31865    }
31866
31867    #[test]
31868    fn count_distinct_dead_slot_elimminates_to_domain_counts() {
31869        // `COUNT(DISTINCT ?s)` over the dead slot is served by the count RPC
31870        // in distinct mode: each hit's count IS the per-head distinct
31871        // cardinality, so the Group still eliminates.
31872        let plan = LogicalPlan::parse(
31873            "SELECT ?o (COUNT(DISTINCT ?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31874        )
31875        .unwrap();
31876        match domain_counts_root(&plan) {
31877            Some((_, _, _)) => {}
31878            other => panic!("expected a DomainCounts root, got {other:?}"),
31879        }
31880        let PlanNode::Extend { inner, .. } = &plan.root else {
31881            unreachable!()
31882        };
31883        let PlanNode::DomainCounts { count_distinct, .. } = inner.as_ref() else {
31884            unreachable!()
31885        };
31886        assert!(count_distinct, "the rewrite must carry the distinct mode");
31887    }
31888
31889    /// The ScanOp-residual path: multi-aggregate distinct-count groups are
31890    /// beyond the head-count shortcut, but liveness arms the TSG head-count
31891    /// annotation and the (loosened) fold gate accepts SAMPLE/MIN over the
31892    /// head — the TSG head-count fold serves the whole group in one RPC.
31893    #[test]
31894    fn multi_agg_distinct_count_arms_tsg_head_counts_fold() {
31895        let plan = LogicalPlan::parse(
31896            "SELECT ?cls (COUNT(DISTINCT ?f) AS ?n) (SAMPLE(?cls) AS ?s) WHERE { ?f a ?cls } GROUP BY ?cls",
31897        )
31898        .unwrap();
31899        assert!(
31900            head_counts_root(&plan).is_none(),
31901            "shortcut refuses 2 aggregates"
31902        );
31903        let mut scans = Vec::new();
31904        collect_scans(&plan.root, &mut scans);
31905        assert_eq!(scans.len(), 1);
31906        let scan = scans[0];
31907        assert_eq!(
31908            scan.head_scan_counts,
31909            Some(HeadScanKind::Classes),
31910            "TSG head-count annotation arms the PER_HEAD fold"
31911        );
31912        assert!(
31913            scan.domain_counts.is_none(),
31914            "head-count annotation precedes domain counts"
31915        );
31916        assert!(scan.is_counted_distinct(scan.subject.as_ref().unwrap()));
31917        // The group key stays bag-insensitive (SAMPLE needs no multiplicity).
31918        assert_eq!(
31919            scan.bag_mark(scan.object.as_ref().unwrap()),
31920            Some(BagMark::Insensitive)
31921        );
31922        // MIN behaves identically to SAMPLE here: it is
31923        // multiplicity-insensitive, so the keys are NOT promoted to
31924        // Sensitive by `aggregate_triggers_sensitive_group_keys` and the TSG
31925        // annotation arms for the MIN-composed group too.
31926        let plan = LogicalPlan::parse(
31927            "SELECT ?cls (COUNT(DISTINCT ?f) AS ?n) (MIN(?cls) AS ?m) WHERE { ?f a ?cls } GROUP BY ?cls",
31928        )
31929        .unwrap();
31930        let mut min_scans = Vec::new();
31931        collect_scans(&plan.root, &mut min_scans);
31932        assert_eq!(min_scans.len(), 1);
31933        assert_eq!(
31934            min_scans[0].head_scan_counts,
31935            Some(HeadScanKind::Classes),
31936            "MIN over the head folds from the same TSG hits"
31937        );
31938    }
31939
31940    /// A bag-count sibling (plain `COUNT`) blocks the counted-distinct mark:
31941    /// one scan serves one count mode, so the dual-agg bag shape keeps its
31942    /// POSG domain-counts annotation and never arms head counts.
31943    #[test]
31944    fn dual_agg_bag_shape_never_arms_head_counts() {
31945        let plan = LogicalPlan::parse(
31946            "SELECT ?class (COUNT(?s) AS ?n) (COUNT(*) AS ?all) WHERE { ?s a ?class } GROUP BY ?class",
31947        )
31948        .unwrap();
31949        let mut scans = Vec::new();
31950        collect_scans(&plan.root, &mut scans);
31951        assert_eq!(scans.len(), 1);
31952        let scan = scans[0];
31953        assert!(scan.head_scan_counts.is_none());
31954        assert!(scan.head_scan.is_none());
31955        assert_eq!(
31956            scan.domain_counts,
31957            Some(DomainScanKind::PredicateDomain),
31958            "POSG domain counts supply the bag"
31959        );
31960    }
31961
31962    #[test]
31963    fn count_distinct_star_stays_on_the_group_path() {
31964        // `COUNT(DISTINCT *)` needs the whole mapping; a counted slot has no
31965        // values, so neither the shortcut nor the distinct count RPC serves
31966        // it and the Group survives on a plain scan.
31967        let plan = LogicalPlan::parse(
31968            "SELECT ?o (COUNT(DISTINCT *) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31969        )
31970        .unwrap();
31971        assert!(domain_counts_root(&plan).is_none());
31972        assert!(
31973            matches!(find_group(&plan.root), PlanNode::Group { .. }),
31974            "Group must survive"
31975        );
31976    }
31977
31978    #[test]
31979    fn group_count_of_the_key_does_not_distinct_scan() {
31980        // COUNT(?o) grouped by ?o needs the input bag; elimination already
31981        // refuses counted == key, and liveness must not domain-scan either.
31982        let plan = LogicalPlan::parse(
31983            "SELECT ?o (COUNT(?o) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
31984        )
31985        .unwrap();
31986        assert!(domain_counts_root(&plan).is_none());
31987        let mut scans = Vec::new();
31988        collect_scans(&plan.root, &mut scans);
31989        assert_eq!(scans.len(), 1);
31990        let scan = scans[0];
31991        assert_eq!(
31992            scan.bag_mark(scan.object.as_ref().unwrap()),
31993            Some(BagMark::Sensitive)
31994        );
31995        assert!(scan.domain_scan.is_none() && scan.head_scan.is_none());
31996    }
31997
31998    #[test]
31999    fn sum_aggregate_stays_on_the_group_path() {
32000        let plan = LogicalPlan::parse(
32001            "SELECT ?o (SUM(?s) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
32002        )
32003        .unwrap();
32004        assert!(domain_counts_root(&plan).is_none());
32005    }
32006
32007    #[test]
32008    fn count_expression_argument_stays_on_the_group_path() {
32009        let plan = LogicalPlan::parse(
32010            "SELECT ?o (COUNT(?s + 1) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?o",
32011        )
32012        .unwrap();
32013        assert!(domain_counts_root(&plan).is_none());
32014    }
32015
32016    #[test]
32017    fn repeated_count_variable_stays_on_the_group_path() {
32018        // `?x ?p ?x`: the counted slot carries an equality a run count
32019        // cannot respect.
32020        let plan = LogicalPlan::parse(
32021            "SELECT ?p (COUNT(?x) AS ?n) WHERE { ?x <http://ex/p> ?x } GROUP BY ?p",
32022        )
32023        .unwrap();
32024        assert!(domain_counts_root(&plan).is_none());
32025    }
32026
32027    #[test]
32028    fn count_star_repeated_slot_stays_on_the_group_path() {
32029        // `COUNT(*)` names no variable, but `{ ?o :p ?o }` is still an
32030        // equality the run count never sees. The rewrite must refuse.
32031        let plan = LogicalPlan::parse(
32032            "SELECT ?o (COUNT(*) AS ?n) WHERE { ?o <http://ex/p> ?o } GROUP BY ?o",
32033        )
32034        .unwrap();
32035        assert!(domain_counts_root(&plan).is_none());
32036    }
32037
32038    #[test]
32039    fn unbound_constraint_slot_stays_on_the_group_path() {
32040        // No pattern constant: the constraint term list would be empty.
32041        let plan = LogicalPlan::parse("SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s ?p ?o } GROUP BY ?o")
32042            .unwrap();
32043        assert!(domain_counts_root(&plan).is_none());
32044    }
32045
32046    #[test]
32047    fn group_key_on_subject_slot_rewrites_via_predicate_subjects() {
32048        // A subject group key under a bound predicate was unreachable with
32049        // the original four kinds. PSOG makes it the PredicateSubjects
32050        // family: constraint P, head S (the group key), dead O (counted).
32051        let plan = LogicalPlan::parse(
32052            "SELECT ?s (COUNT(?o) AS ?n) WHERE { ?s <http://ex/hasColour> ?o } GROUP BY ?s",
32053        )
32054        .unwrap();
32055        let Some((kind, head, _)) = domain_counts_root(&plan) else {
32056            panic!("expected DomainCounts under alias, got {:?}", plan.root);
32057        };
32058        assert_eq!(*kind, DomainScanKind::PredicateSubjects);
32059        assert_eq!(head.as_str(), "s");
32060    }
32061
32062    fn find_domain_counts_node(node: &PlanNode) -> Option<&PlanNode> {
32063        match node {
32064            PlanNode::DomainCounts { .. } => Some(node),
32065            PlanNode::Extend { inner, .. }
32066            | PlanNode::Filter { inner, .. }
32067            | PlanNode::Distinct { inner, .. }
32068            | PlanNode::Sort { inner, .. }
32069            | PlanNode::Slice { inner, .. }
32070            | PlanNode::Group { inner, .. } => find_domain_counts_node(inner),
32071            PlanNode::Join { left, right, .. } => {
32072                find_domain_counts_node(left).or_else(|| find_domain_counts_node(right))
32073            }
32074            _ => None,
32075        }
32076    }
32077
32078    #[test]
32079    fn values_two_key_group_lowers_to_domain_counts() {
32080        let plan = LogicalPlan::parse(
32081            "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32082              VALUES ?p { <http://ex/colour> <http://ex/height> <http://ex/condition> <http://ex/width> }
32083              ?s ?p ?o
32084            } GROUP BY ?p ?o",
32085        )
32086        .unwrap();
32087        let node = find_domain_counts_node(&plan.root).expect("DomainCounts shortcut");
32088        let PlanNode::DomainCounts {
32089            constraints,
32090            constraint_var,
32091            ..
32092        } = node
32093        else {
32094            unreachable!();
32095        };
32096        assert_eq!(constraints.len(), 4);
32097        assert_eq!(constraint_var.as_ref().map(|v| v.as_str()), Some("p"));
32098        let PlanNode::DomainCounts {
32099            constraint_multiplicity,
32100            ..
32101        } = node
32102        else {
32103            unreachable!();
32104        };
32105        assert_eq!(constraint_multiplicity.as_slice(), &[1, 1, 1, 1]);
32106    }
32107
32108    #[test]
32109    fn values_duplicate_constraint_keeps_row_multiplicity() {
32110        let plan = LogicalPlan::parse(
32111            "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32112              VALUES ?p { <http://ex/colour> <http://ex/colour> <http://ex/height> }
32113              ?s ?p ?o
32114            } GROUP BY ?p ?o",
32115        )
32116        .unwrap();
32117        let node = find_domain_counts_node(&plan.root).expect("DomainCounts shortcut");
32118        let PlanNode::DomainCounts {
32119            constraints,
32120            constraint_multiplicity,
32121            ..
32122        } = node
32123        else {
32124            unreachable!();
32125        };
32126        assert_eq!(constraints.len(), 2);
32127        // The list is key-sorted with the VALUES row factors permuted in
32128        // lockstep, so the pairing holds under either hash layout.
32129        let colour =
32130            waratah_storage::EncodedTerm::from(&NamedNode::new("http://ex/colour").unwrap());
32131        let height =
32132            waratah_storage::EncodedTerm::from(&NamedNode::new("http://ex/height").unwrap());
32133        let want: Vec<(waratah_storage::EncodedTerm, u64)> =
32134            if waratah_storage::encode_term_bytes(&colour)
32135                < waratah_storage::encode_term_bytes(&height)
32136            {
32137                vec![(colour, 2), (height, 1)]
32138            } else {
32139                vec![(height, 1), (colour, 2)]
32140            };
32141        let want_terms: Vec<_> = want.iter().map(|(term, _)| term.clone()).collect();
32142        let want_mults: Vec<_> = want.iter().map(|(_, mult)| *mult).collect();
32143        assert_eq!(constraints.as_slice(), want_terms.as_slice());
32144        assert_eq!(constraint_multiplicity.as_slice(), want_mults.as_slice());
32145    }
32146
32147    #[test]
32148    fn values_extra_non_join_column_counts_as_row_multiplicity() {
32149        let plan = LogicalPlan::parse(
32150            "SELECT ?p ?o (COUNT(*) AS ?c) WHERE {
32151              VALUES (?p ?tag) { (<http://ex/colour> 1) (<http://ex/colour> 2) }
32152              ?s ?p ?o
32153            } GROUP BY ?p ?o",
32154        )
32155        .unwrap();
32156        let node = find_domain_counts_node(&plan.root).expect("DomainCounts shortcut");
32157        let PlanNode::DomainCounts {
32158            constraints,
32159            constraint_multiplicity,
32160            ..
32161        } = node
32162        else {
32163            unreachable!();
32164        };
32165        assert_eq!(constraints.len(), 1);
32166        assert_eq!(constraint_multiplicity.as_slice(), &[2]);
32167    }
32168
32169    #[test]
32170    fn values_undef_constraint_does_not_eliminate_group() {
32171        let plan = LogicalPlan::parse(
32172            "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32173              VALUES ?p { UNDEF <http://ex/colour> }
32174              ?s ?p ?o
32175            } GROUP BY ?p ?o",
32176        )
32177        .unwrap();
32178        assert!(
32179            find_domain_counts_node(&plan.root).is_none(),
32180            "UNDEF on the constraint column must stay on the Group path"
32181        );
32182    }
32183
32184    #[test]
32185    fn values_binding_the_head_does_not_eliminate_group() {
32186        let plan = LogicalPlan::parse(
32187            "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32188              VALUES (?p ?o) { (<http://ex/colour> \"red\") (<http://ex/colour> \"red\") }
32189              ?s ?p ?o
32190            } GROUP BY ?p ?o",
32191        )
32192        .unwrap();
32193        assert!(
32194            find_domain_counts_node(&plan.root).is_none(),
32195            "a VALUES column that is also the head is a join key, not a scalar multiplier"
32196        );
32197    }
32198
32199    #[test]
32200    fn group_with_extra_triple_keeps_group_and_annotates_domain_counts() {
32201        let plan = LogicalPlan::parse(
32202            "SELECT ?p ?o (COUNT(?s) AS ?c) WHERE {
32203              VALUES ?p { <http://ex/colour> <http://ex/height> }
32204              ?s ?p ?o .
32205              ?s <http://ex/tag> ?t
32206            } GROUP BY ?p ?o",
32207        )
32208        .unwrap();
32209        assert!(
32210            matches!(find_group(&plan.root), PlanNode::Group { .. }),
32211            "extra triple must block the DomainCounts shortcut"
32212        );
32213    }
32214
32215    #[test]
32216    fn type_count_dual_agg_refuses_classes_head_scan() {
32217        // Dual aggregates keep Group (elimination requires a single COUNT).
32218        // Counted `?s` must not lose to the TSG distinct-classes skip-scan.
32219        let plan = LogicalPlan::parse(
32220            "SELECT ?class (COUNT(?s) AS ?n) (COUNT(*) AS ?all) WHERE { ?s a ?class } GROUP BY ?class",
32221        )
32222        .unwrap();
32223        assert!(
32224            matches!(find_group(&plan.root), PlanNode::Group { .. }),
32225            "a second aggregate must keep Group"
32226        );
32227        let mut scans = Vec::new();
32228        collect_scans(&plan.root, &mut scans);
32229        assert_eq!(scans.len(), 1);
32230        let scan = scans[0];
32231        let s = scan.subject.as_ref().unwrap();
32232        assert!(
32233            scan.is_counted(s),
32234            "COUNT(?s) / COUNT(*) must count the subject"
32235        );
32236        assert!(
32237            scan.head_scan.is_none(),
32238            "Classes skip-scan has no multiplicity: {scan:?}"
32239        );
32240        assert_eq!(
32241            scan.domain_counts,
32242            Some(DomainScanKind::PredicateDomain),
32243            "type COUNT must fall through to POSG domain counts: {scan:?}"
32244        );
32245    }
32246
32247    #[test]
32248    fn count_group_by_counted_var_is_live_not_counted() {
32249        let plan = LogicalPlan::parse(
32250            "SELECT ?s (COUNT(?s) AS ?n) WHERE { ?s <http://ex/p> ?o } GROUP BY ?s",
32251        )
32252        .unwrap();
32253        let PlanNode::Extend { inner, .. } = &plan.root else {
32254            panic!("expected Extend over Group");
32255        };
32256        let PlanNode::Group { inner, .. } = inner.as_ref() else {
32257            panic!("expected Group");
32258        };
32259        let PlanNode::Scan(scan) = inner.as_ref() else {
32260            panic!("expected Scan");
32261        };
32262        let s = scan.subject.as_ref().unwrap();
32263        assert!(scan.is_live(s));
32264        assert!(!scan.is_counted(s));
32265        assert!(domain_counts_root(&plan).is_none());
32266    }
32267
32268    /// Exact predicate count `triples` against an HLL of `distinct_heads`
32269    /// objects of `predicate`. The bag-counts gate fires when
32270    /// `triples >= 2 *` that HLL's cardinality.
32271    fn bag_counts_profile(predicate: &str, triples: u64, distinct_heads: u128) -> StatsProfile {
32272        let mut profile = StatsProfile::default();
32273        let hash = waratah_storage::StrHash::new(predicate);
32274        profile.total_puts = triples;
32275        profile.predicate_counts.insert(hash, triples);
32276        profile
32277            .objects_per_predicate
32278            .insert(hash, hll_with_n(distinct_heads));
32279        profile
32280    }
32281
32282    #[test]
32283    fn bag_sensitive_head_annotates_domain_counts() {
32284        let profile = bag_counts_profile("http://ex/p", 100, 10);
32285        let plan = LogicalPlan::parse_with_profile(
32286            "SELECT ?o WHERE { ?s <http://ex/p> ?o }",
32287            Some(&profile),
32288        )
32289        .unwrap();
32290        let scans = plan.scans().unwrap();
32291        assert_eq!(scans.len(), 1);
32292        assert!(
32293            scans[0].domain_counts.is_some(),
32294            "bag head over a constrained scan should annotate the counts walk"
32295        );
32296        assert!(scans[0].domain_scan.is_none() && scans[0].head_scan.is_none());
32297    }
32298
32299    #[test]
32300    fn bag_counts_annotation_needs_a_loaded_profile() {
32301        let plan = LogicalPlan::parse("SELECT ?o WHERE { ?s <http://ex/p> ?o }").unwrap();
32302        let scans = plan.scans().unwrap();
32303        assert_eq!(scans.len(), 1);
32304        assert!(
32305            scans[0].domain_counts.is_none(),
32306            "no profile must keep the plain scan"
32307        );
32308    }
32309
32310    #[test]
32311    fn bag_counts_annotation_skips_short_runs() {
32312        // 10 triples, ~10 distinct objects: average run length < 2.
32313        let profile = bag_counts_profile("http://ex/p", 10, 10);
32314        let plan = LogicalPlan::parse_with_profile(
32315            "SELECT ?o WHERE { ?s <http://ex/p> ?o }",
32316            Some(&profile),
32317        )
32318        .unwrap();
32319        let scans = plan.scans().unwrap();
32320        assert!(scans[0].domain_counts.is_none());
32321    }
32322
32323    #[test]
32324    fn distinct_head_beats_the_bag_counts_annotation() {
32325        let plan = LogicalPlan::parse("SELECT DISTINCT ?o WHERE { ?s <http://ex/p> ?o }").unwrap();
32326        let scans = plan.scans().unwrap();
32327        assert_eq!(scans.len(), 1);
32328        assert!(scans[0].domain_scan.is_some() || scans[0].head_scan.is_some());
32329        assert!(scans[0].domain_counts.is_none());
32330    }
32331
32332    /// First scan anywhere in the plan, descending every wrapper including
32333    /// subqueries (`scans()`/`collect_bgp_scans` refuses shapes with count
32334    /// nodes or `SubSelect` wrappers, which these tests deliberately use).
32335    fn find_first_scan(node: &PlanNode) -> Option<&ScanOp> {
32336        match node {
32337            PlanNode::Scan(scan) => Some(scan),
32338            PlanNode::Join { left, right, .. }
32339            | PlanNode::LeftJoin { left, right, .. }
32340            | PlanNode::Union { left, right } => {
32341                find_first_scan(left).or_else(|| find_first_scan(right))
32342            }
32343            PlanNode::Filter { inner, .. }
32344            | PlanNode::Extend { inner, .. }
32345            | PlanNode::Slice { inner, .. }
32346            | PlanNode::Distinct { inner, .. }
32347            | PlanNode::Sort { inner, .. }
32348            | PlanNode::Group { inner, .. }
32349            | PlanNode::JoinGraphVar { inner, .. } => find_first_scan(inner),
32350            PlanNode::SubSelect(sub) => find_first_scan(&sub.inner),
32351            PlanNode::CustomNode(op) => op.children.iter().find_map(find_first_scan),
32352            _ => None,
32353        }
32354    }
32355
32356    /// Both VALUES predicates expensive and a store-sized `total_puts`, so
32357    /// the unbound probe scan prices large: the comparator seats the VALUES
32358    /// table on the join's left (the broadcast driver arm) and the scan on
32359    /// the right, where `claim_broadcast_probe` stamps it. Without
32360    /// `total_puts` the scan prices ~1, lands on the left arm, and no stamp
32361    /// exists for the rewrite gates to read.
32362    fn two_predicate_profile() -> StatsProfile {
32363        let mut profile = StatsProfile {
32364            total_puts: 2_000_000,
32365            ..StatsProfile::default()
32366        };
32367        for predicate in ["http://ex/p1", "http://ex/p2"] {
32368            let hash = waratah_storage::StrHash::new(predicate);
32369            profile.predicate_counts.insert(hash, 1_000_000);
32370            profile.objects_per_predicate.insert(hash, hll_with_n(50));
32371        }
32372        profile
32373    }
32374
32375    /// A broadcast VALUES list on the constraint slot reaches the domain
32376    /// rewrite even though the constraint name is unprojected: the head's
32377    /// live-insensitive mark (a distinct context, via the `!allow_collapse`
32378    /// demotion) already proves the constraint's multiplicity cannot matter,
32379    /// and the join re-multiplies duplicate VALUES rows against the RPC's
32380    /// (constraint, head) pairs.
32381    #[test]
32382    fn values_constrained_distinct_head_takes_domain_scan() {
32383        let profile = two_predicate_profile();
32384        let plan = LogicalPlan::parse_with_profile(
32385            "SELECT DISTINCT ?o WHERE { VALUES ?p { <http://ex/p1> <http://ex/p2> <http://ex/p2> } ?s ?p ?o }",
32386            Some(&profile),
32387        )
32388        .unwrap();
32389        let scan = find_first_scan(&plan.root).expect("scan must survive planning");
32390        assert!(
32391            scan.domain_scan.is_some(),
32392            "VALUES-constrained DISTINCT head must take the domain scan"
32393        );
32394        assert!(scan.broadcasted.is_some());
32395    }
32396
32397    /// The same VALUES list under a bag-sensitive projection must not take
32398    /// the domain rewrite: the head is Sensitive and rows carry
32399    /// multiplicity.
32400    #[test]
32401    fn values_constrained_plain_select_keeps_bag_rows() {
32402        let profile = two_predicate_profile();
32403        let plan = LogicalPlan::parse_with_profile(
32404            "SELECT ?o WHERE { VALUES ?p { <http://ex/p1> <http://ex/p2> } ?s ?p ?o }",
32405            Some(&profile),
32406        )
32407        .unwrap();
32408        let scan = find_first_scan(&plan.root).expect("scan must survive planning");
32409        assert!(
32410            scan.broadcasted.is_some(),
32411            "the stamp must land for this pin"
32412        );
32413        assert!(scan.domain_scan.is_none());
32414        assert!(scan.domain_counts.is_none());
32415    }
32416
32417    /// COUNT reads row multiplicity, so the domain gate refuses (counted or
32418    /// sensitive head); the count rewrites own that shape.
32419    #[test]
32420    fn values_constrained_count_keeps_row_multiplicity() {
32421        let profile = two_predicate_profile();
32422        let plan = LogicalPlan::parse_with_profile(
32423            "SELECT (COUNT(*) AS ?n) WHERE { VALUES ?p { <http://ex/p1> <http://ex/p2> <http://ex/p2> } ?s ?p ?o }",
32424            Some(&profile),
32425        )
32426        .unwrap();
32427        // A count rewrite may consume the whole shape (no scan survives);
32428        // if a scan survives it must not carry the distinct-head rewrite.
32429        assert!(find_first_scan(&plan.root).is_none_or(|scan| scan.domain_scan.is_none()));
32430    }
32431
32432    /// A bare LIMIT between the projection and the scan keeps the head
32433    /// bag-sensitive (the `!allow_collapse` demotion): deduping under the
32434    /// slice would change which rows survive, so no domain rewrite inside.
32435    #[test]
32436    fn values_constrained_slice_head_stays_sensitive() {
32437        let profile = two_predicate_profile();
32438        let plan = LogicalPlan::parse_with_profile(
32439            "SELECT DISTINCT ?o WHERE { { SELECT ?o WHERE { VALUES ?p { <http://ex/p1> } ?s ?p ?o } LIMIT 3 } }",
32440            Some(&profile),
32441        )
32442        .unwrap();
32443        let scan = find_first_scan(&plan.root).expect("scan must survive planning");
32444        assert!(scan.domain_scan.is_none());
32445    }
32446
32447    #[test]
32448    fn bag_counts_annotation_survives_a_bare_limit() {
32449        // The annotation stays on the plan. Estimate EXPLAIN names the count
32450        // RPC on the Group that folds it, so a bag SELECT scan does not print
32451        // `domain_counts_bag`.
32452        let profile = bag_counts_profile("http://ex/p", 100, 10);
32453        let plan = LogicalPlan::parse_with_profile(
32454            "SELECT ?o WHERE { ?s <http://ex/p> ?o } LIMIT 10",
32455            Some(&profile),
32456        )
32457        .unwrap();
32458        let scans = plan.scans().unwrap();
32459        assert_eq!(scans.len(), 1);
32460        assert!(scans[0].domain_counts.is_some());
32461        for sparql in [
32462            "SELECT ?o WHERE { ?s <http://ex/p> ?o } LIMIT 10",
32463            "SELECT ?o WHERE { ?s <http://ex/p> ?o } ORDER BY ?o LIMIT 10",
32464            "SELECT ?o WHERE { ?s <http://ex/p> ?o }",
32465        ] {
32466            let text = explain_est(sparql, Some(&profile));
32467            assert!(
32468                !text.contains("domain_counts_bag"),
32469                "the scan leaf does not print the count RPC: {text}"
32470            );
32471        }
32472    }
32473
32474    #[test]
32475    fn bag_counts_under_default_union_stays_on_the_scan() {
32476        let profile = bag_counts_profile("http://ex/p", 1_000, 1);
32477        let query =
32478            crate::rephrase_error::parse_query("SELECT ?o WHERE { ?s <http://ex/p> ?o }").unwrap();
32479        let Query::Select {
32480            pattern, dataset, ..
32481        } = query
32482        else {
32483            panic!("select");
32484        };
32485        let dataset = QueryDataset::resolve(&[], &[], dataset.as_ref(), true).unwrap();
32486        let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_dataset(dataset);
32487        let plan = LogicalPlan::from_algebra_with_ctx(pattern, Some(&profile), &ctx).unwrap();
32488        let scans = plan.scans().unwrap();
32489        assert!(scans[0].domain_counts.is_some());
32490        assert!(scans[0].merge_default_graph);
32491    }
32492
32493    #[test]
32494    fn grouped_estimate_names_domain_counts_on_the_group() {
32495        let text = explain_est(
32496            "SELECT ?o (COUNT(?s) AS ?n) (COUNT(*) AS ?all) WHERE { ?s <http://ex/p> ?o } GROUP BY ?o",
32497            None,
32498        );
32499        assert!(
32500            text.contains("(weighted_counts domain_counts_bag "),
32501            "{text}"
32502        );
32503        assert_eq!(
32504            text.matches("domain_counts_bag").count(),
32505            1,
32506            "the scan leaf must not repeat the count RPC: {text}"
32507        );
32508    }
32509
32510    #[test]
32511    fn having_is_iri_stamps_domain_counts() {
32512        let plan = LogicalPlan::parse(
32513            "SELECT ?o (COUNT(?s) AS ?n) WHERE { ?s <http://ex/p> ?o } GROUP BY ?o HAVING (isIRI(?o))",
32514        )
32515        .unwrap();
32516        let PlanNode::DomainCounts { iri_only, .. } =
32517            find_domain_counts(&plan.root).expect("DomainCounts under HAVING")
32518        else {
32519            unreachable!()
32520        };
32521        assert!(
32522            *iri_only,
32523            "isIRI(?o) on the group key must stamp the count node"
32524        );
32525    }
32526
32527    fn find_domain_counts(node: &PlanNode) -> Option<&PlanNode> {
32528        match node {
32529            PlanNode::DomainCounts { .. } => Some(node),
32530            PlanNode::Extend { inner, .. }
32531            | PlanNode::Filter { inner, .. }
32532            | PlanNode::Slice { inner, .. }
32533            | PlanNode::Group { inner, .. }
32534            | PlanNode::Distinct { inner, .. }
32535            | PlanNode::Sort { inner, .. } => find_domain_counts(inner),
32536            _ => None,
32537        }
32538    }
32539
32540    /// The coverage stamp must come from the PROBE arm. A driver-side stamp
32541    /// measures page saturation instead of probe selectivity and would make
32542    /// the runtime drop kill a selective push: a 400-subject niche driver
32543    /// joined into a wide probe must keep its allow-list, so the stamped
32544    /// domain has to be the probe's (~1M), not the driver's (~400).
32545    #[test]
32546    fn probe_key_domains_stamp_from_the_probe_arm_not_the_driver() {
32547        let mut profile = StatsProfile::default();
32548        let niche = StrHash::new("http://ex/niche");
32549        let wide = StrHash::new("http://ex/wide");
32550        profile.predicate_counts.insert(niche, 400);
32551        profile.predicate_counts.insert(wide, 5_000_000);
32552        profile
32553            .subjects_per_predicate
32554            .insert(niche, hll_with_n(400));
32555        profile
32556            .subjects_per_predicate
32557            .insert(wide, hll_with_n(1_000_000));
32558        profile.total_puts = 5_000_400;
32559
32560        // Driver: ?s :niche ?flag (400 subjects). Probe: ?s :wide ?o
32561        // (1M distinct subjects). Seating stays scan-left (no scan↔union).
32562        let left = PlanNode::Scan(var_scan(Some("s"), "http://ex/niche", Some("flag"), 400));
32563        let right = PlanNode::Scan(var_scan(Some("s"), "http://ex/wide", Some("o"), 5_000_000));
32564        let join = join_nodes(left, right, Some(&profile));
32565        let PlanNode::Join {
32566            hash_keys,
32567            probe_key_domains,
32568            probe_key_overlap_milli: _,
32569            ..
32570        } = join
32571        else {
32572            panic!("expected Join, got {join:?}");
32573        };
32574        assert_eq!(hash_keys, vec![var("s")]);
32575        assert_eq!(probe_key_domains.len(), 1);
32576        // HLL tolerance ±10%: near 1M (probe side), decisively not ~400
32577        // (the driver side the pre-fix code stamped).
32578        let stamped = probe_key_domains[0];
32579        assert!(
32580            (900_000..=1_100_000).contains(&stamped),
32581            "stamp must be the probe arm's domain (~1M), got {stamped}"
32582        );
32583    }
32584
32585    /// `--seat-by-total-cost` must actually move the seating where the two
32586    /// comparators disagree. The fixture is the q02 geometry flattened onto
32587    /// one key pair: `memberOf` (1.05M rows over a 1,500 subject domain)
32588    /// joined to `degreeFrom` (652k rows over a 3,000 subject domain),
32589    /// sharing both variables.
32590    ///
32591    /// - The legacy `driver_cost` pair credits the big arm by its small
32592    ///   domain (`min(rows, domain)` — the phantom department credit) and
32593    ///   keeps `memberOf` driving (1,500 < 3,000).
32594    /// - The totals price whole seatings with the per-page lists the
32595    ///   executor really builds: memberOf's pages hold ~28 subjects and
32596    ///   ~6,228 objects — neither covers, so all 53 pages pay filtered
32597    ///   fetches (~1.37M row work); reversed, the ~91-subject and
32598    ///   ~306-object lists also broadcast, but the narrowest filter matches
32599    ///   only ~982 rows on each of 33 pages (~0.68M) — `degreeFrom`
32600    ///   driving clears the swap margin on rows alone.
32601    ///
32602    /// The gate rides the [`QueryContext`], not a process global: the two
32603    /// runs below cannot leak into each other or into parallel tests.
32604    #[test]
32605    fn seat_by_total_cost_flips_the_legacy_swap() {
32606        let member_of = StrHash::new("http://ex/memberOf");
32607        let degree_from = StrHash::new("http://ex/degreeFrom");
32608        let mut profile = StatsProfile::default();
32609        profile.predicate_counts.insert(member_of, 1_048_532);
32610        profile.predicate_counts.insert(degree_from, 652_374);
32611        profile
32612            .subjects_per_predicate
32613            .insert(member_of, hll_with_n(1_500));
32614        profile
32615            .subjects_per_predicate
32616            .insert(degree_from, hll_with_n(3_000));
32617        profile
32618            .objects_per_predicate
32619            .insert(member_of, hll_with_n(326_526));
32620        profile
32621            .objects_per_predicate
32622            .insert(degree_from, hll_with_n(10_000));
32623        profile.total_puts = 1_048_532 + 652_374;
32624        let member_of_term = Some(EncodedTerm::from(
32625            &NamedNode::new("http://ex/memberOf").unwrap(),
32626        ));
32627        let degree_from_term = Some(EncodedTerm::from(
32628            &NamedNode::new("http://ex/degreeFrom").unwrap(),
32629        ));
32630        let join_of = || {
32631            join_nodes(
32632                PlanNode::Scan(var_scan(
32633                    Some("x"),
32634                    "http://ex/memberOf",
32635                    Some("y"),
32636                    1_048_532,
32637                )),
32638                PlanNode::Scan(var_scan(
32639                    Some("x"),
32640                    "http://ex/degreeFrom",
32641                    Some("y"),
32642                    652_374,
32643                )),
32644                Some(&profile),
32645            )
32646        };
32647        let driving_predicate = |node: &PlanNode| {
32648            let PlanNode::Join { left, .. } = node else {
32649                panic!("expected Join, got {node:?}");
32650            };
32651            let PlanNode::Scan(scan) = left.as_ref() else {
32652                panic!("driver arm should stay a scan, got {left:?}");
32653            };
32654            scan.pattern.predicate.clone()
32655        };
32656
32657        // Default: the legacy comparator decides. `memberOf` keeps driving.
32658        let mut legacy = join_of();
32659        refinalize_joins(&mut legacy, Some(&profile), None);
32660        assert_eq!(
32661            driving_predicate(&legacy),
32662            member_of_term,
32663            "the legacy comparator must keep the small-domain big arm driving"
32664        );
32665
32666        // `--seat-by-total-cost` on: the totals decide — `degreeFrom` drives,
32667        // and the divergent seat logs `join-seat-totals` with a context.
32668        let seat_ctx =
32669            QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
32670        let mut promoted = join_of();
32671        refinalize_joins(&mut promoted, Some(&profile), Some(&seat_ctx));
32672        assert_eq!(
32673            driving_predicate(&promoted),
32674            degree_from_term,
32675            "the seat-by-total-cost comparator must invert the seating here"
32676        );
32677    }
32678
32679    /// E2/H2 shape pin: the s32 `t1-facets` plan under the benchmark's
32680    /// `--seat-by-total-cost` is
32681    /// `Group(Join{left: Union, right: Scan(record), strategy: Semi})`.
32682    /// The default driver-cost rule seats the record scan on the left, where
32683    /// a semi join cannot form (it keeps the left schema); the benchmark flag
32684    /// lets the larger union drive and leaves the key-unique, whole-read
32685    /// record scan as the probe. This is the shape E2's fused group sink folds
32686    /// arm by arm.
32687    #[test]
32688    fn t1_facet_shape_seats_union_left_and_promotes_semi() {
32689        use spargebra::Query;
32690        use waratah_stats::term_key;
32691
32692        let sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32693          ?r <http://ex/isRecord> <http://ex/record> .
32694          { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32695          UNION
32696          { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32697          UNION
32698          { ?r <http://ex/kindC> ?v . BIND(<http://ex/dimC> AS ?dim) }
32699        } GROUP BY ?dim ?v"#;
32700
32701        let mut profile = StatsProfile::default();
32702        for (predicate, rows, subjects, objects) in [
32703            ("http://ex/isRecord", 500_000u64, 500_000u128, 1u128),
32704            ("http://ex/kindA", 1_000_000, 500_000, 4),
32705            ("http://ex/kindB", 1_000_000, 500_000, 4),
32706            ("http://ex/kindC", 1_000_000, 500_000, 4),
32707        ] {
32708            profile
32709                .predicate_counts
32710                .insert(StrHash::new(predicate), rows);
32711            profile
32712                .subjects_per_predicate
32713                .insert(StrHash::new(predicate), hll_with_n(subjects));
32714            profile
32715                .objects_per_predicate
32716                .insert(StrHash::new(predicate), hll_with_n(objects));
32717        }
32718        profile.total_puts = 3_500_000;
32719        let record = EncodedTerm::from(&NamedNode::new("http://ex/record").unwrap());
32720        profile.object_cms.add(term_key(&record), 500_000);
32721
32722        let Query::Select { pattern, .. } = crate::rephrase_error::parse_query(sparql).unwrap()
32723        else {
32724            panic!("expected SELECT");
32725        };
32726        let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
32727        let plan = LogicalPlan::from_algebra_with_ctx(pattern, Some(&profile), &ctx).unwrap();
32728
32729        let group = match &plan.root {
32730            PlanNode::Group { .. } => &plan.root,
32731            PlanNode::Extend { inner, .. } => inner.as_ref(),
32732            other => panic!("expected the alias Extend over the Group, got {other:?}"),
32733        };
32734        let PlanNode::Group {
32735            inner,
32736            variables,
32737            aggregates,
32738            ..
32739        } = group
32740        else {
32741            panic!("expected Group, got {group:?}");
32742        };
32743        let PlanNode::Join {
32744            left, right, meta, ..
32745        } = inner.as_ref()
32746        else {
32747            panic!("expected the Join under the Group, got {inner:?}");
32748        };
32749        assert!(
32750            matches!(left.as_ref(), PlanNode::Union { .. }),
32751            "the union must be the driver, got {left:?}"
32752        );
32753        let PlanNode::Scan(scan) = right.as_ref() else {
32754            panic!("expected the record scan as the probe, got {right:?}");
32755        };
32756        assert_eq!(
32757            scan.pattern.object,
32758            Some(record),
32759            "the probe must be ?r isRecord <record>"
32760        );
32761        assert!(
32762            scan.fetch_once.is_some(),
32763            "the benchmark shape needs the whole-read verdict, got {scan:?}"
32764        );
32765        assert_eq!(
32766            meta.strategy,
32767            JoinStrategy::SemiScan,
32768            "the key-unique whole-read record scan must be a semi probe"
32769        );
32770        // The three arms are single patterns with a row-invariant `?dim`
32771        // constant, so the count-mode map must mark all three groups for the
32772        // row-count mode instead of the DISTINCT seen-set.
32773        let modes = count_mode_plan(inner, variables, aggregates)
32774            .expect("the three single-pattern arms must qualify");
32775        assert_eq!(modes.dim.as_str(), "dim");
32776        assert_eq!(modes.by_dim.len(), 3);
32777        assert!(
32778            modes
32779                .by_dim
32780                .values()
32781                .all(|mode| *mode == CountMode::CountRows),
32782            "all three single-pattern arms must count rows: {modes:?}"
32783        );
32784
32785        // A fourth arm that is a join: `?_h`-style arms cannot prove the
32786        // counted variable unique per group, so only that dim keeps DISTINCT.
32787        // This runs the same S2 shape with the extra arm and a matching
32788        // profile, so the mixed map is exercised on the real planner output.
32789        let mixed_sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32790          ?r <http://ex/isRecord> <http://ex/record> .
32791          { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32792          UNION
32793          { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32794          UNION
32795          { ?r <http://ex/kindC> ?v . BIND(<http://ex/dimC> AS ?dim) }
32796          UNION
32797          { ?r <http://ex/kindD> ?v . ?r <http://ex/other> ?w . BIND(<http://ex/dimD> AS ?dim) }
32798        } GROUP BY ?dim ?v"#;
32799        let Query::Select { pattern, .. } =
32800            crate::rephrase_error::parse_query(mixed_sparql).unwrap()
32801        else {
32802            panic!("expected SELECT");
32803        };
32804        let mut mixed_profile = profile.clone();
32805        for (predicate, rows, subjects, objects) in [
32806            ("http://ex/kindD", 1_000_000u64, 500_000u128, 4u128),
32807            ("http://ex/other", 1_000_000, 500_000, 500_000),
32808        ] {
32809            mixed_profile
32810                .predicate_counts
32811                .insert(StrHash::new(predicate), rows);
32812            mixed_profile
32813                .subjects_per_predicate
32814                .insert(StrHash::new(predicate), hll_with_n(subjects));
32815            mixed_profile
32816                .objects_per_predicate
32817                .insert(StrHash::new(predicate), hll_with_n(objects));
32818        }
32819        mixed_profile.total_puts += 2_000_000;
32820        let mixed_plan =
32821            LogicalPlan::from_algebra_with_ctx(pattern, Some(&mixed_profile), &ctx).unwrap();
32822        let mixed_group = match &mixed_plan.root {
32823            PlanNode::Group { .. } => &mixed_plan.root,
32824            PlanNode::Extend { inner, .. } => inner.as_ref(),
32825            other => panic!("expected the alias Extend over the Group, got {other:?}"),
32826        };
32827        let PlanNode::Group {
32828            inner,
32829            variables,
32830            aggregates,
32831            ..
32832        } = mixed_group
32833        else {
32834            panic!("expected Group, got {mixed_group:?}");
32835        };
32836        let PlanNode::Join { left, meta, .. } = inner.as_ref() else {
32837            panic!("expected the semi Join under the mixed Group, got {inner:?}");
32838        };
32839        assert!(
32840            matches!(left.as_ref(), PlanNode::Union { .. }),
32841            "the mixed union must stay on the driver side, got {left:?}"
32842        );
32843        assert_eq!(
32844            meta.strategy,
32845            JoinStrategy::SemiScan,
32846            "the mixed shape must keep the key-unique semi probe"
32847        );
32848        let mixed_modes = count_mode_plan(inner, variables, aggregates)
32849            .expect("the three single-pattern arms still qualify");
32850        assert_eq!(
32851            mixed_modes.summary(),
32852            "dim=?dim arms_count_rows=3 arms_distinct=1"
32853        );
32854
32855        // Two arms sharing the same discriminator can put the same counted
32856        // value in one group from both arms. Even when each arm alone is
32857        // unique, the shared constant must keep the seen-set.
32858        let duplicate_sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32859          ?r <http://ex/isRecord> <http://ex/record> .
32860          { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32861          UNION
32862          { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32863          UNION
32864          { ?r <http://ex/kindC> ?v . BIND(<http://ex/dimC> AS ?dim) }
32865          UNION
32866          { ?r <http://ex/kindD> ?v . BIND(<http://ex/dimA> AS ?dim) }
32867        } GROUP BY ?dim ?v"#;
32868        let Query::Select { pattern, .. } =
32869            crate::rephrase_error::parse_query(duplicate_sparql).unwrap()
32870        else {
32871            panic!("expected SELECT");
32872        };
32873        let duplicate_plan =
32874            LogicalPlan::from_algebra_with_ctx(pattern, Some(&mixed_profile), &ctx).unwrap();
32875        let duplicate_group = match &duplicate_plan.root {
32876            PlanNode::Group { .. } => &duplicate_plan.root,
32877            PlanNode::Extend { inner, .. } => inner.as_ref(),
32878            other => panic!("expected the alias Extend over the Group, got {other:?}"),
32879        };
32880        let PlanNode::Group {
32881            inner,
32882            variables,
32883            aggregates,
32884            ..
32885        } = duplicate_group
32886        else {
32887            panic!("expected Group, got {duplicate_group:?}");
32888        };
32889        let duplicate_modes = count_mode_plan(inner, variables, aggregates)
32890            .expect("the single-pattern arms still build the map");
32891        assert_eq!(
32892            duplicate_modes.summary(),
32893            "dim=?dim arms_count_rows=2 arms_distinct=1",
32894            "a shared discriminator must keep the seen-set"
32895        );
32896
32897        // A slot variable that liveness dropped is still part of the
32898        // pattern. `variables()` omits it, so the proof must use
32899        // `slot_variables()`; otherwise two triples that differ only in the
32900        // dropped slot collapse to duplicate rows and `COUNT(?r)` overcounts.
32901        let dead_slot_sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32902          ?r <http://ex/isRecord> <http://ex/record> .
32903          { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32904          UNION
32905          { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32906          UNION
32907          { ?r ?pc ?v . BIND(<http://ex/dimC> AS ?dim) }
32908        } GROUP BY ?dim ?v"#;
32909        let Query::Select { pattern, .. } =
32910            crate::rephrase_error::parse_query(dead_slot_sparql).unwrap()
32911        else {
32912            panic!("expected SELECT");
32913        };
32914        let dead_slot_plan =
32915            LogicalPlan::from_algebra_with_ctx(pattern, Some(&profile), &ctx).unwrap();
32916        let dead_slot_group = match &dead_slot_plan.root {
32917            PlanNode::Group { .. } => &dead_slot_plan.root,
32918            PlanNode::Extend { inner, .. } => inner.as_ref(),
32919            other => panic!("expected the alias Extend over the Group, got {other:?}"),
32920        };
32921        let PlanNode::Group {
32922            inner,
32923            variables,
32924            aggregates,
32925            ..
32926        } = dead_slot_group
32927        else {
32928            panic!("expected Group, got {dead_slot_group:?}");
32929        };
32930        let dead_slot_modes = count_mode_plan(inner, variables, aggregates)
32931            .expect("the two constant-predicate arms still qualify");
32932        assert_eq!(
32933            dead_slot_modes.summary(),
32934            "dim=?dim arms_count_rows=2 arms_distinct=1",
32935            "the arm with a dropped slot variable must keep the seen-set"
32936        );
32937    }
32938
32939    /// The count-mode map refuses an arm whose final scan is a specialized
32940    /// domain-count RPC. With no profile the liveness pass rewrites all
32941    /// three single-pattern arms to `domain_counts`, so the map must leave
32942    /// every group on `DISTINCT` rather than treat the run-count output as
32943    /// pattern rows.
32944    #[test]
32945    fn count_mode_plan_refuses_specialized_domain_counts_arms() {
32946        use spargebra::Query;
32947
32948        let sparql = r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
32949          { ?r <http://ex/kindA> ?v . BIND(<http://ex/dimA> AS ?dim) }
32950          UNION
32951          { ?r <http://ex/kindB> ?v . BIND(<http://ex/dimB> AS ?dim) }
32952          UNION
32953          { ?r <http://ex/kindD> ?v . ?r <http://ex/other> ?w . BIND(<http://ex/dimD> AS ?dim) }
32954        } GROUP BY ?dim ?v"#;
32955        let Query::Select { pattern, .. } = crate::rephrase_error::parse_query(sparql).unwrap()
32956        else {
32957            panic!("expected SELECT");
32958        };
32959        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
32960        let plan = LogicalPlan::from_algebra_with_ctx(pattern, None, &ctx).unwrap();
32961        let group = match &plan.root {
32962            PlanNode::Group { .. } => &plan.root,
32963            PlanNode::Extend { inner, .. } => inner.as_ref(),
32964            other => panic!("expected the alias Extend over the Group, got {other:?}"),
32965        };
32966        let PlanNode::Group {
32967            inner,
32968            variables,
32969            aggregates,
32970            ..
32971        } = group
32972        else {
32973            panic!("expected Group, got {group:?}");
32974        };
32975        assert!(
32976            matches!(inner.as_ref(), PlanNode::Union { .. }),
32977            "expected the union under the Group, got {inner:?}"
32978        );
32979        let modes = count_mode_plan(inner, variables, aggregates)
32980            .expect("the dim map is still built; the specialized arms just refuse CountRows");
32981        assert_eq!(
32982            modes.summary(),
32983            "dim=?dim arms_count_rows=0 arms_distinct=3"
32984        );
32985    }
32986
32987    /// The remaining plan-time refusals. Each case differs from the positive
32988    /// fixture by one fact; the map must leave that arm on `Distinct` (or
32989    /// refuse the shape entirely when the discriminator is ambiguous).
32990    #[test]
32991    fn count_mode_plan_refuses_the_negative_gates() {
32992        let var = |name: &str| Variable::new(name).unwrap();
32993        let count_distinct = |name: &str| AggregateExpression::FunctionCall {
32994            name: AggregateFunction::Count,
32995            expr: Expression::Variable(var(name)),
32996            distinct: true,
32997        };
32998        let keys = vec![var("dim"), var("v")];
32999        let aggregates = vec![(var("n"), count_distinct("r"))];
33000        let arm = |scan: ScanOp, dim_iri: &str| PlanNode::Extend {
33001            inner: Box::new(PlanNode::Scan(scan)),
33002            variable: var("dim"),
33003            expression: Expression::NamedNode(NamedNode::new(dim_iri).unwrap()),
33004            const_strings: Vec::new(),
33005            const_blobs: Vec::new(),
33006        };
33007        let union = |left: PlanNode, right: PlanNode| PlanNode::Union {
33008            left: Box::new(left),
33009            right: Box::new(right),
33010        };
33011        let scan =
33012            |predicate: &str| var_scan(Some("r"), &format!("http://ex/{predicate}"), Some("v"), 10);
33013        let summary = |inner: &PlanNode| {
33014            count_mode_plan(inner, &keys, &aggregates)
33015                .expect("the dim map is built")
33016                .summary()
33017        };
33018
33019        let baseline = union(
33020            arm(scan("kindA"), "http://ex/dimA"),
33021            arm(scan("kindB"), "http://ex/dimB"),
33022        );
33023        assert_eq!(
33024            summary(&baseline),
33025            "dim=?dim arms_count_rows=2 arms_distinct=0"
33026        );
33027
33028        let one_arm_refused = |scan_b: ScanOp| {
33029            union(
33030                arm(scan("kindA"), "http://ex/dimA"),
33031                arm(scan_b, "http://ex/dimB"),
33032            )
33033        };
33034        for (label, scan_b) in [
33035            ("merge_default_graph", {
33036                let mut scan = scan("kindB");
33037                scan.merge_default_graph = true;
33038                scan
33039            }),
33040            ("graph variable", {
33041                let mut scan = scan("kindB");
33042                scan.graph = Some(var("g"));
33043                scan
33044            }),
33045            ("graph filter", {
33046                let mut scan = scan("kindB");
33047                scan.graph_filter = Some(GraphFilter::exclude_default());
33048                scan
33049            }),
33050            ("grounded counted", {
33051                let mut scan = scan("kindB");
33052                scan.grounded.push((var("r"), PatternSlot::Subject));
33053                scan
33054            }),
33055            ("second ungrouped variable", {
33056                let mut scan = scan("kindB");
33057                scan.predicate = Some(var("pc"));
33058                scan.pattern.predicate = None;
33059                scan
33060            }),
33061        ] {
33062            let plan = one_arm_refused(scan_b);
33063            assert_eq!(
33064                summary(&plan),
33065                "dim=?dim arms_count_rows=1 arms_distinct=1",
33066                "{label} must keep the seen-set"
33067            );
33068        }
33069
33070        let star = vec![(
33071            var("n"),
33072            AggregateExpression::CountSolutions { distinct: true },
33073        )];
33074        assert!(
33075            count_mode_plan(&baseline, &keys, &star).is_none(),
33076            "COUNT(DISTINCT *) is not a bare-variable count"
33077        );
33078
33079        let expression = vec![(
33080            var("n"),
33081            AggregateExpression::FunctionCall {
33082                name: AggregateFunction::Count,
33083                expr: Expression::Bound(var("r")),
33084                distinct: true,
33085            },
33086        )];
33087        assert!(
33088            count_mode_plan(&baseline, &keys, &expression).is_none(),
33089            "an expression argument keeps the Encoded seen-set"
33090        );
33091
33092        let two_extend = |dim_iri: &str, dim2_iri: &str| PlanNode::Extend {
33093            inner: Box::new(PlanNode::Extend {
33094                inner: Box::new(PlanNode::Scan(scan("kindA"))),
33095                variable: var("dim2"),
33096                expression: Expression::NamedNode(NamedNode::new(dim2_iri).unwrap()),
33097                const_strings: Vec::new(),
33098                const_blobs: Vec::new(),
33099            }),
33100            variable: var("dim"),
33101            expression: Expression::NamedNode(NamedNode::new(dim_iri).unwrap()),
33102            const_strings: Vec::new(),
33103            const_blobs: Vec::new(),
33104        };
33105        let multi = union(
33106            two_extend("http://ex/dimA", "http://ex/dimA2"),
33107            two_extend("http://ex/dimB", "http://ex/dimB2"),
33108        );
33109        let multi_keys = vec![var("dim"), var("dim2"), var("v")];
33110        assert!(
33111            count_mode_plan(&multi, &multi_keys, &aggregates).is_none(),
33112            "a second arm-discriminating key must refuse the map"
33113        );
33114
33115        let non_key_unique_right = PlanNode::Join {
33116            left: Box::new(baseline),
33117            right: Box::new(PlanNode::Scan(var_scan(
33118                Some("r"),
33119                "http://ex/isRecord",
33120                Some("o"),
33121                10,
33122            ))),
33123            hash_keys: vec![var("r")],
33124            probe_key_domains: vec![0],
33125            probe_key_overlap_milli: vec![1000],
33126            rhs_hostable_keys: Arc::from(vec![var("r")]),
33127            meta: JoinMeta {
33128                semi_gate: None,
33129                strategy: JoinStrategy::SemiScan,
33130                produced_row_count_estimate: 10,
33131                own_push_removed_row_count_estimate: 10,
33132                star_arms: None,
33133            },
33134        };
33135        assert!(
33136            count_mode_plan(&non_key_unique_right, &keys, &aggregates).is_none(),
33137            "a non-key-unique right must refuse the semi count mode"
33138        );
33139    }
33140
33141    /// The t4 selector `VALUES` table must move to the facet UNION and ground
33142    /// the selector scans. The table is one row, so its columns are
33143    /// independent; `?word` has no consumer and is dropped. Without the LCA
33144    /// pass the table rides the dataset-kind cartesian and the arm scans keep
33145    /// their full document-type/commodity domains.
33146    #[test]
33147    fn t4_values_move_to_the_union_and_ground_the_selector_scans() {
33148        use spargebra::Query;
33149
33150        let sparql = r#"PREFIX sdo: <https://schema.org/>
33151PREFIX scr: <https://koenigsnet/scraper-vocab/>
33152PREFIX kn: <https://koenigsnet/ont/>
33153SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
33154  VALUES ?selCommodity { <https://koenigsnet/scraper-vocab/concept/commodity/gold> }
33155  VALUES ?selDocType { <https://koenigsnet/scraper-vocab/concept/record-type/report> }
33156  VALUES ?word { "report" }
33157  ?r scr:datasetKind <https://koenigsnet/scraper-vocab/concept/dataset-kind/record> .
33158  ?r sdo:name|sdo:abstract|scr:searchKeyword ?_lit .
33159  FILTER(CONTAINS(LCASE(STR(?_lit)), LCASE("report")))
33160  { ?r scr:documentType ?selDocType . { ?r scr:commodity ?v . BIND(scr:commodity AS ?dim) } }
33161  UNION
33162  { ?r scr:commodity ?selCommodity . { ?r scr:documentType ?v . BIND(scr:documentType AS ?dim) } }
33163  UNION
33164  { ?r scr:commodity ?selCommodity ; scr:documentType ?selDocType .
33165    { ?r sdo:isPartOf ?v . ?v a sdo:DataCatalog . BIND(kn:catalog AS ?dim) }
33166    UNION
33167    { ?r scr:documentType ?v . BIND(scr:documentType AS ?dim) }
33168    UNION
33169    { ?r scr:commodity ?v . BIND(scr:commodity AS ?dim) }
33170    UNION
33171    { ?r scr:subject ?v . BIND(scr:subject AS ?dim) }
33172    UNION
33173    { ?r scr:workCategory ?v . BIND(scr:workCategory AS ?dim) }
33174    UNION
33175    { ?r scr:geologicAge ?v . BIND(scr:geologicAge AS ?dim) }
33176    UNION
33177    { ?r scr:tenement|scr:mineralClaim|scr:mineralOccurrence ?_h . ?_h scr:jurisdiction ?v . ?v a scr:AdministrativeArea . BIND(scr:jurisdiction AS ?dim) }
33178  }
33179} GROUP BY ?dim ?v"#;
33180        let Query::Select { pattern, .. } = crate::rephrase_error::parse_query(sparql).unwrap()
33181        else {
33182            panic!("expected SELECT");
33183        };
33184        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
33185        let plan = LogicalPlan::from_algebra_with_ctx(pattern, None, &ctx).unwrap();
33186
33187        let mut scans = Vec::new();
33188        collect_scans(&plan.root, &mut scans);
33189        let doc = var("selDocType");
33190        let commodity = var("selCommodity");
33191        let doc_term = EncodedTerm::from(
33192            &NamedNode::new("https://koenigsnet/scraper-vocab/concept/record-type/report").unwrap(),
33193        );
33194        let commodity_term = EncodedTerm::from(
33195            &NamedNode::new("https://koenigsnet/scraper-vocab/concept/commodity/gold").unwrap(),
33196        );
33197        let doc_scans: Vec<&ScanOp> = scans
33198            .iter()
33199            .copied()
33200            .filter(|scan| !scan.slot_of(&doc).is_empty())
33201            .collect();
33202        let commodity_scans: Vec<&ScanOp> = scans
33203            .iter()
33204            .copied()
33205            .filter(|scan| !scan.slot_of(&commodity).is_empty())
33206            .collect();
33207        assert!(
33208            !doc_scans.is_empty(),
33209            "the document-type selector scans must survive lowering"
33210        );
33211        assert!(
33212            doc_scans
33213                .iter()
33214                .all(|scan| scan.pattern.object.as_ref() == Some(&doc_term)),
33215            "every document-type selector scan must be grounded to the report term: {doc_scans:?}"
33216        );
33217        assert!(
33218            !commodity_scans.is_empty(),
33219            "the commodity selector scans must survive lowering"
33220        );
33221        assert!(
33222            commodity_scans
33223                .iter()
33224                .all(|scan| scan.pattern.object.as_ref() == Some(&commodity_term)),
33225            "every commodity selector scan must be grounded to the gold term: {commodity_scans:?}"
33226        );
33227
33228        let values = values_in_plan(&plan.root);
33229        assert!(
33230            values
33231                .iter()
33232                .all(|values| !values.variables.contains(&var("word"))),
33233            "the unused ?word column must be dropped: {values:?}"
33234        );
33235    }
33236
33237    /// Peel the SELECT/aggregate wrappers down to the WHERE algebra, where the
33238    /// VALUES placement pass operates. A FILTER boundary is peeled too: the
33239    /// pass seats tables inside the filter body, not above it.
33240    fn select_region(pattern: &GraphPattern) -> &GraphPattern {
33241        match pattern {
33242            GraphPattern::Project { inner, .. }
33243            | GraphPattern::Extend { inner, .. }
33244            | GraphPattern::Group { inner, .. }
33245            | GraphPattern::Filter { inner, .. } => select_region(inner),
33246            other => other,
33247        }
33248    }
33249
33250    /// A path, column list and row set for one algebra `VALUES`.
33251    type AlgebraValues<'a> = (Vec<usize>, &'a [Variable], &'a [Vec<Option<GroundTerm>>]);
33252
33253    /// Collect every algebra `VALUES` with its child-index path, using the
33254    /// same child order as [`algebra_child`].
33255    fn collect_algebra_values<'a>(
33256        pattern: &'a GraphPattern,
33257        path: &mut Vec<usize>,
33258        out: &mut Vec<AlgebraValues<'a>>,
33259    ) {
33260        match pattern {
33261            GraphPattern::Values {
33262                variables,
33263                bindings,
33264            } => out.push((path.clone(), variables, bindings)),
33265            GraphPattern::Join { left, right }
33266            | GraphPattern::Union { left, right }
33267            | GraphPattern::Minus { left, right } => {
33268                path.push(0);
33269                collect_algebra_values(left, path, out);
33270                path.pop();
33271                path.push(1);
33272                collect_algebra_values(right, path, out);
33273                path.pop();
33274            }
33275            GraphPattern::LeftJoin { left, right, .. } => {
33276                path.push(0);
33277                collect_algebra_values(left, path, out);
33278                path.pop();
33279                path.push(1);
33280                collect_algebra_values(right, path, out);
33281                path.pop();
33282            }
33283            GraphPattern::Filter { inner, .. }
33284            | GraphPattern::Extend { inner, .. }
33285            | GraphPattern::Group { inner, .. }
33286            | GraphPattern::Project { inner, .. }
33287            | GraphPattern::OrderBy { inner, .. }
33288            | GraphPattern::Distinct { inner }
33289            | GraphPattern::Reduced { inner }
33290            | GraphPattern::Slice { inner, .. }
33291            | GraphPattern::Graph { inner, .. }
33292            | GraphPattern::Service { inner, .. } => {
33293                path.push(0);
33294                collect_algebra_values(inner, path, out);
33295                path.pop();
33296            }
33297            GraphPattern::Bgp { .. } | GraphPattern::Path { .. } => {}
33298        }
33299    }
33300
33301    fn parse_select_pattern(sparql: &str) -> GraphPattern {
33302        let Query::Select { pattern, .. } = crate::rephrase_error::parse_query(sparql).unwrap()
33303        else {
33304            panic!("expected SELECT");
33305        };
33306        pattern
33307    }
33308
33309    fn placed_values(sparql: &str) -> GraphPattern {
33310        place_values_at_lca_with_live(parse_select_pattern(sparql), &[])
33311    }
33312
33313    fn report_term() -> GroundTerm {
33314        GroundTerm::NamedNode(NamedNode::new("http://ex/report").unwrap())
33315    }
33316
33317    fn datasheet_term() -> GroundTerm {
33318        GroundTerm::NamedNode(NamedNode::new("http://ex/datasheet").unwrap())
33319    }
33320
33321    /// A multi-row table is correlated: it must move as one unit, keep every
33322    /// bound column, preserve its rows, and drop an always-unbound column that
33323    /// nothing reads. Splitting it by column would cross-product the rows.
33324    #[test]
33325    fn multi_row_values_move_whole_and_drop_a_dead_unbound_column() {
33326        let placed = placed_values(
33327            r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
33328              VALUES (?selDocType ?word ?extra) {
33329                (<http://ex/report> "report" UNDEF)
33330                (<http://ex/datasheet> "data" UNDEF)
33331              }
33332              ?r <http://ex/datasetKind> <http://ex/record> .
33333              ?r <http://ex/documentType> ?selDocType .
33334              ?r <http://ex/searchKeyword> ?word .
33335              { ?r <http://ex/commodity> ?v . BIND(<http://ex/commodity> AS ?dim) }
33336              UNION
33337              { ?r <http://ex/subject> ?v . BIND(<http://ex/subject> AS ?dim) }
33338            } GROUP BY ?dim ?v"#,
33339        );
33340        let region = select_region(&placed);
33341        let mut values = Vec::new();
33342        collect_algebra_values(region, &mut Vec::new(), &mut values);
33343        assert_eq!(
33344            values.len(),
33345            1,
33346            "the multi-row table must stay one unit, got {values:?}"
33347        );
33348        let (path, variables, rows) = &values[0];
33349        assert_eq!(
33350            variables,
33351            &[var("selDocType"), var("word")],
33352            "the always-unbound unused ?extra column must be dropped, and the bound columns kept"
33353        );
33354        let report_row = vec![
33355            Some(report_term()),
33356            Some(GroundTerm::Literal(Literal::new_simple_literal("report"))),
33357        ];
33358        let datasheet_row = vec![
33359            Some(datasheet_term()),
33360            Some(GroundTerm::Literal(Literal::new_simple_literal("data"))),
33361        ];
33362        assert_eq!(rows, &[report_row, datasheet_row], "row multiplicity lost");
33363        assert!(
33364            path.len() > 1,
33365            "the table must move below the region root, got {path:?}"
33366        );
33367    }
33368
33369    /// An expression-only column has no binding site, so the table must stay
33370    /// at the seating it had, where the expression can read it. The always-unbound
33371    /// unused column is still dropped before that decision.
33372    #[test]
33373    fn multi_row_values_with_an_expression_only_column_keep_their_original_seat() {
33374        let parsed = parse_select_pattern(
33375            r#"SELECT ?dim ?v (COUNT(DISTINCT ?r) AS ?n) WHERE {
33376              VALUES (?selDocType ?word ?extra) {
33377                (<http://ex/report> "report" UNDEF)
33378                (<http://ex/datasheet> "data" UNDEF)
33379              }
33380              ?r <http://ex/documentType> ?selDocType .
33381              FILTER(CONTAINS(?word, "rep"))
33382              { ?r <http://ex/commodity> ?v . BIND(<http://ex/commodity> AS ?dim) }
33383              UNION
33384              { ?r <http://ex/subject> ?v . BIND(<http://ex/subject> AS ?dim) }
33385            } GROUP BY ?dim ?v"#,
33386        );
33387        let mut before = Vec::new();
33388        collect_algebra_values(select_region(&parsed), &mut Vec::new(), &mut before);
33389        let origin = before
33390            .iter()
33391            .find(|(_, variables, _)| variables.contains(&var("word")))
33392            .map(|(path, _, _)| path.clone())
33393            .expect("the original table must contain ?word");
33394        let placed = place_values_at_lca_with_live(parsed, &[]);
33395        let region = select_region(&placed);
33396        let mut values = Vec::new();
33397        collect_algebra_values(region, &mut Vec::new(), &mut values);
33398        assert_eq!(values.len(), 1, "got {values:?}");
33399        let (path, variables, rows) = &values[0];
33400        // Insertion wraps the empty BGP that replaced the original table, so
33401        // the binding sits at the origin plus one left-child step.
33402        let expected: Vec<usize> = origin.iter().copied().chain([0]).collect();
33403        assert_eq!(
33404            path, &expected,
33405            "the table must keep its original seat so the FILTER can read ?word"
33406        );
33407        assert_eq!(
33408            variables,
33409            &[var("selDocType"), var("word")],
33410            "?extra is dropped, ?word stays for the FILTER expression"
33411        );
33412        assert_eq!(rows.len(), 2);
33413    }
33414
33415    /// A table inside one UNION arm belongs to that arm. Hoisting it to the
33416    /// UNION would multiply the other arms' rows by the table's row count.
33417    #[test]
33418    fn multi_row_values_inside_a_union_arm_stay_in_that_arm() {
33419        let placed = placed_values(
33420            r#"SELECT * WHERE {
33421              { VALUES ?x { <http://ex/a> <http://ex/b> } . ?s <http://ex/p> ?x }
33422              UNION
33423              { ?s <http://ex/q> ?y }
33424            }"#,
33425        );
33426        let region = select_region(&placed);
33427        let mut values = Vec::new();
33428        collect_algebra_values(region, &mut Vec::new(), &mut values);
33429        assert_eq!(values.len(), 1, "got {values:?}");
33430        let (path, variables, rows) = &values[0];
33431        assert_eq!(variables, &[var("x")]);
33432        assert_eq!(rows.len(), 2);
33433        assert_eq!(
33434            path.first(),
33435            Some(&0),
33436            "the table must stay in the left UNION arm, got {path:?}"
33437        );
33438    }
33439
33440    /// A top-level ORDER BY is peeled above the SELECT list, so its variables
33441    /// are not projected. A multi-row table column read only by the sort key
33442    /// must still move with the table.
33443    #[test]
33444    fn values_column_read_only_by_order_by_survives_placement() {
33445        let plan = LogicalPlan::parse(
33446            r#"SELECT ?s ?y WHERE {
33447              VALUES (?x ?y) { (2 "a") (1 "b") }
33448              ?s <http://ex/p> ?o .
33449            } ORDER BY ?x"#,
33450        )
33451        .unwrap();
33452        let values = values_in_plan(&plan.root);
33453        assert_eq!(values.len(), 1, "{:?}", plan.root);
33454        assert!(
33455            values[0].variables.contains(&var("x")),
33456            "the ORDER BY key column must survive placement: {:?}",
33457            values[0]
33458        );
33459        assert_eq!(values[0].rows.len(), 2);
33460    }
33461
33462    /// A column whose only reader is inside a FILTER EXISTS body must survive
33463    /// placement: the body is correlated against the outer bindings, so
33464    /// dropping the column turns the body's comparison into an unbound-variable
33465    /// error and silently changes the boolean.
33466    #[test]
33467    fn values_column_read_only_by_an_exists_body_survives_placement() {
33468        let plan = LogicalPlan::parse(
33469            r#"SELECT ?s WHERE {
33470              VALUES ?s { <http://ex/s1> }
33471              VALUES ?x { <http://ex/a> }
33472              FILTER EXISTS { VALUES ?q { 1 } FILTER(?x = <http://ex/a>) }
33473            }"#,
33474        )
33475        .unwrap();
33476        let values = values_in_plan(&plan.root);
33477        assert!(
33478            values.iter().any(|v| v.variables.contains(&var("x"))),
33479            "the VALUES column read only inside EXISTS must survive: {:?}",
33480            plan.root
33481        );
33482    }
33483
33484    /// A one-row table splits by column: each column's site is in a different
33485    /// join branch, so the table must become one `Values` node per branch.
33486    #[test]
33487    fn one_row_values_split_seats_each_column_at_its_branch() {
33488        let plan = LogicalPlan::parse(
33489            r#"SELECT ?s ?t WHERE {
33490              VALUES (?x ?y) { ( <http://ex/a> 7 ) }
33491              { ?s <http://ex/p> ?x }
33492              { ?t <http://ex/q> ?y }
33493            }"#,
33494        )
33495        .unwrap();
33496        let values = values_in_plan(&plan.root);
33497        let x: Vec<_> = values
33498            .iter()
33499            .filter(|values| values.variables == vec![var("x")])
33500            .collect();
33501        let y: Vec<_> = values
33502            .iter()
33503            .filter(|values| values.variables == vec![var("y")])
33504            .collect();
33505        assert_eq!(x.len(), 1, "one Values node for ?x: {values:?}");
33506        assert_eq!(y.len(), 1, "one Values node for ?y: {values:?}");
33507        assert_eq!(x[0].rows.len(), 1);
33508        assert_eq!(y[0].rows.len(), 1);
33509    }
33510
33511    /// A multi-row table must not enter the right side of an OPTIONAL: the
33512    /// seat is the LeftJoin (or above it), so missing optional rows keep the
33513    /// table's binding.
33514    #[test]
33515    fn multi_row_values_never_enter_an_optional_right() {
33516        let plan = LogicalPlan::parse(
33517            r#"SELECT ?s ?x WHERE {
33518              VALUES ?s { <http://ex/s1> }
33519              VALUES ?x { <http://ex/a> <http://ex/b> }
33520              OPTIONAL { ?s <http://ex/p> ?x }
33521            }"#,
33522        )
33523        .unwrap();
33524        let mut saw_left_join = false;
33525        walk_plan(&plan.root, &mut |node| {
33526            if let PlanNode::LeftJoin { right, .. } = node {
33527                saw_left_join = true;
33528                assert!(
33529                    !values_in_plan(right)
33530                        .iter()
33531                        .any(|values| values.variables.contains(&var("x"))),
33532                    "the multi-row ?x table must stay out of the OPTIONAL right: {right:?}"
33533                );
33534            }
33535        });
33536        assert!(saw_left_join, "expected a LeftJoin: {:?}", plan.root);
33537    }
33538
33539    /// The mention walk is the drop rule's only reader list; `BOUND`, `GRAPH`
33540    /// names, and `SERVICE` names are readers that must count.
33541    #[test]
33542    fn mention_walk_counts_bound_and_graph_and_service_names() {
33543        let empty = || GraphPattern::Bgp {
33544            patterns: Vec::new(),
33545        };
33546
33547        let mut bound = Vec::new();
33548        collect_mentions(
33549            &GraphPattern::Filter {
33550                expr: Expression::Bound(var("bound")),
33551                inner: Box::new(empty()),
33552            },
33553            &mut bound,
33554        );
33555        assert_eq!(mention_count(&bound, &var("bound")), 1);
33556
33557        let mut graph = Vec::new();
33558        collect_mentions(
33559            &GraphPattern::Graph {
33560                name: NamedNodePattern::Variable(var("g")),
33561                inner: Box::new(empty()),
33562            },
33563            &mut graph,
33564        );
33565        assert_eq!(mention_count(&graph, &var("g")), 1);
33566
33567        let mut service = Vec::new();
33568        collect_mentions(
33569            &GraphPattern::Service {
33570                name: NamedNodePattern::Variable(var("svc")),
33571                inner: Box::new(empty()),
33572                silent: false,
33573            },
33574            &mut service,
33575        );
33576        assert_eq!(mention_count(&service, &var("svc")), 1);
33577    }
33578
33579    #[test]
33580    fn exists_bearing_expressions_are_detected_for_the_pin_guard() {
33581        let body = GraphPattern::Bgp {
33582            patterns: Vec::new(),
33583        };
33584        let nested = Expression::If(
33585            Box::new(Expression::Exists(Box::new(body))),
33586            Box::new(Expression::Variable(var("x"))),
33587            Box::new(Expression::Literal(Literal::new_simple_literal("fallback"))),
33588        );
33589        assert!(expression_contains_exists(&nested));
33590        assert!(!expression_contains_exists(&Expression::Variable(var("x"))));
33591        assert!(!expression_contains_exists(&Expression::Literal(
33592            Literal::new_simple_literal("fallback")
33593        )));
33594    }
33595
33596    /// With `--seat-by-total-cost`, the association ranks candidates by the
33597    /// seating the later arm-swap
33598    /// pass will keep — both orientations priced, `seat_beats` survivor
33599    /// ranks — not by the as-built (seed-driving) orientation. This
33600    /// fixture is the shape where the two disagree about the ASSOCIATION:
33601    ///
33602    /// Seed `?x pS ?z`: 100k rows, 100k distinct subjects (one row per
33603    /// subject). Two candidates keyed on `?x`:
33604    /// - B `?x pB ?w`: 50k rows, 100 distinct subjects.
33605    /// - C `?x pC ?v`: 40k rows, 80k distinct subjects.
33606    ///
33607    /// Seed-driving prices (what an as-built-only ranking would compare):
33608    /// with the fetch-once road both seats collapse to builds (a seed page
33609    /// broadcasts ~24,576 keys, matching B's whole 100-key domain and a quarter
33610    /// of C's 80k) — B = 150,000 rows / 0 seeks, C = 140,000 / 0 → C
33611    /// attaches. But the swap pass then re-seats every edge, and the
33612    /// survivor prices invert the comparison: B driving stays a cheap
33613    /// ~49-key-list probe ≈ 50,150 rows / ~150 seeks, C driving fires the
33614    /// trigger ≈ 179,620 rows (C + the seed's unclamped price) → the B tree
33615    /// is the cheaper association, and the swap can never go back and
33616    /// re-attach B once C is folded in. Ranking on the survivor picks B
33617    /// outright. Both outputs (50k, 40k) clear the 4× guard, so
33618    /// eligibility is not the discriminator here — the ranking currency
33619    /// is.
33620    #[test]
33621    fn stamped_custom_driver_and_probe_price_regime_work() {
33622        // The item-5 comparator wiring: a stamped custom arm's seating cost
33623        // is its regime work, not its output cardinality. keys-empty
33624        // joins pin each basis exactly (no page arithmetic): the driver
33625        // term is the keyless sweep (drain 90 + 1_000 × 8 relate units =
33626        // 8_090), the unkeyed probe work is the same sweep, and the scan
33627        // arm keeps its produced read.
33628        let stamped = |rows: u64| {
33629            PlanNode::CustomNode(cost_test_op(
33630                rows,
33631                Some(CustomOpCost {
33632                    drain_rows: 90,
33633                    per_key_unit: 8,
33634                    inline_point_unit: 1,
33635                    direct_probe: true,
33636                    probe_keyed_columns: 0b1,
33637                    probe_filter_unit: 8,
33638                    probe_memo_entry_rows: 0,
33639                }),
33640            ))
33641        };
33642        let scan = || PlanNode::Scan(var_scan(Some("s"), "http://ex/p", Some("o"), 7_000));
33643
33644        let op_drives = seat_cost_total(None, &stamped(1_000), &scan(), &[], None, None);
33645        assert_eq!(op_drives.rows, 8_090 + 7_000);
33646        assert_eq!(op_drives.seeks, 0);
33647
33648        let op_probes = seat_cost_total(None, &scan(), &stamped(1_000), &[], None, None);
33649        assert_eq!(op_probes.rows, 7_000 + 8_090);
33650        assert_eq!(op_probes.seeks, 0);
33651    }
33652
33653    #[test]
33654    fn unstamped_custom_arms_still_price_at_the_row_estimate() {
33655        // `cost: None` is the legacy shape: both bases fall back to the
33656        // produced estimate — the pre-cost-model behavior, unchanged.
33657        let op = PlanNode::CustomNode(cost_test_op(1_000, None));
33658        let scan = PlanNode::Scan(var_scan(Some("s"), "http://ex/p", Some("o"), 7_000));
33659        let seat = seat_cost_total(None, &op, &scan, &[], None, None);
33660        assert_eq!(seat.rows, 1_000 + 7_000);
33661    }
33662
33663    #[test]
33664    fn stamped_custom_probe_keyed_road_is_regime_work_per_page() {
33665        // The keyed road: the driver streams 100k rows in threshold
33666        // pages, each page pushing its distinct ?g list into the op; the
33667        // op's answer prices at `keyed_cost(list)` per page with ZERO
33668        // seeks (an op's work is CPU + partition-side walks, not index
33669        // seeks). The probe's 500k domain never covers (a page list is
33670        // ~24k keys, far under 90% of it), so the coverage road cannot
33671        // fire and the keyed road is the price.
33672        let mut profile = StatsProfile::default();
33673        profile
33674            .predicate_counts
33675            .insert(StrHash::new("http://ex/p"), 100_000);
33676        profile
33677            .subjects_per_predicate
33678            .insert(StrHash::new("http://ex/p"), hll_with_n(100_000));
33679        profile
33680            .objects_per_predicate
33681            .insert(StrHash::new("http://ex/p"), hll_with_n(50_000));
33682        profile.total_puts = 100_000;
33683        let driver = PlanNode::Scan(var_scan(None, "http://ex/p", Some("g"), 100_000));
33684        let op = cost_test_op(
33685            500_000,
33686            Some(CustomOpCost {
33687                drain_rows: 90,
33688                per_key_unit: 8,
33689                inline_point_unit: 1,
33690                direct_probe: true,
33691                probe_keyed_columns: 0b1,
33692                probe_filter_unit: 8,
33693                probe_memo_entry_rows: 0,
33694            }),
33695        );
33696        let probe = PlanNode::CustomNode(op.clone());
33697        let keys = hash_keys_for(&driver.output_vars(), &probe.output_vars());
33698        let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
33699        // Derive the same page/list numbers the gather produces (the
33700        // fixture numbers self-normalize against whatever the sketches
33701        // actually read, the same approach as the association test below).
33702        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
33703        let dom = profile
33704            .objects_per_predicate
33705            .get(&StrHash::new("http://ex/p"))
33706            .expect("object HLL")
33707            .cardinality();
33708        let list = clustered_page_distinct(100_000, dom, page);
33709        let pages = 100_000u64.div_ceil(page);
33710        let keyed = op
33711            .keyed_cost(list, Some(0))
33712            .expect("stamped op prices keyed_cost");
33713        assert_eq!(seat.rows, 100_000 + pages * keyed);
33714        assert_eq!(seat.seeks, 0);
33715    }
33716
33717    #[test]
33718    fn stamped_custom_probe_coverage_road_prices_one_sweep() {
33719        // The coverage road: every key a covered, droppable push — the
33720        // op executes once unfiltered, its keyless sweep, the same
33721        // one-read shape as a dropped subtree arm. A ~24k-key page list
33722        // covers 90% of a 300-key domain trivially, and non-scan arms
33723        // always get the drop.
33724        let mut profile = StatsProfile::default();
33725        profile
33726            .predicate_counts
33727            .insert(StrHash::new("http://ex/p"), 100_000);
33728        profile
33729            .subjects_per_predicate
33730            .insert(StrHash::new("http://ex/p"), hll_with_n(100_000));
33731        profile
33732            .objects_per_predicate
33733            .insert(StrHash::new("http://ex/p"), hll_with_n(50_000));
33734        profile.total_puts = 100_000;
33735        let driver = PlanNode::Scan(var_scan(None, "http://ex/p", Some("g"), 100_000));
33736        let probe = PlanNode::CustomNode(cost_test_op(
33737            300,
33738            Some(CustomOpCost {
33739                drain_rows: 90,
33740                per_key_unit: 8,
33741                inline_point_unit: 1,
33742                direct_probe: true,
33743                probe_keyed_columns: 0b1,
33744                probe_filter_unit: 8,
33745                probe_memo_entry_rows: 0,
33746            }),
33747        ));
33748        let keys = hash_keys_for(&driver.output_vars(), &probe.output_vars());
33749        let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
33750        // Sweep once: drain 90 + 300 × 8 relate units = 2_490.
33751        assert_eq!(seat.rows, 100_000 + 90 + 300 * 8);
33752        assert_eq!(seat.seeks, 0);
33753    }
33754
33755    /// Facts about the custom cluster in a tree: `(depth, key-arm rows,
33756    /// stamped)` for the `Join` with one direct `CustomNode` arm. In the
33757    /// as-built shape the cluster join has exactly the spine's TOP join
33758    /// above it (depth 1); pooled, the scan joins attach around it and the
33759    /// depth grows (the sydney shape pools to depth 3 — union, aFeature,
33760    /// aCls all above the cluster).
33761    fn custom_cluster_facts(node: &PlanNode) -> Option<(usize, u64, bool)> {
33762        fn walk(node: &PlanNode, joins_above: usize) -> Option<(usize, u64, bool)> {
33763            match node {
33764                PlanNode::Join { left, right, .. } => match (&**left, &**right) {
33765                    (PlanNode::CustomNode(op), other) | (other, PlanNode::CustomNode(op)) => {
33766                        Some((
33767                            joins_above,
33768                            other.produced_row_count_estimate(),
33769                            op.cost.is_some(),
33770                        ))
33771                    }
33772                    _ => walk(left, joins_above + 1).or_else(|| walk(right, joins_above + 1)),
33773                },
33774                _ => None,
33775            }
33776        }
33777        walk(node, 0)
33778    }
33779
33780    /// Minimal inner-join scaffolding for the reassociation tests: hash
33781    /// keys derived from the arms' shared variables, meta from the real
33782    /// `finalize_inner_join_meta` (the association pass re-derives all meta itself,
33783    /// but hand-built joins must carry sane prices for the seating-cost tests).
33784    fn test_join(left: PlanNode, right: PlanNode) -> PlanNode {
33785        let keys = hash_keys_for(&left.output_vars(), &right.output_vars());
33786        let (strategy, produced, own_push_removed) =
33787            finalize_inner_join_meta(&left, &right, &keys, None);
33788        PlanNode::Join {
33789            left: Box::new(left),
33790            right: Box::new(right),
33791            hash_keys: keys,
33792            probe_key_domains: Vec::new(),
33793            probe_key_overlap_milli: Vec::new(),
33794            rhs_hostable_keys: Vec::new().into(),
33795            meta: JoinMeta {
33796                semi_gate: None,
33797                star_arms: None,
33798                strategy,
33799                produced_row_count_estimate: produced,
33800                own_push_removed_row_count_estimate: own_push_removed,
33801            },
33802        }
33803    }
33804
33805    fn sydney_shaped_tree(cluster: PlanNode) -> PlanNode {
33806        // The as-built frozen shape: the geo cluster joined ON TOP of a
33807        // triple spine — union(hasGeometry|hasDefault) ⋈ aFeature) ⋈ aCls.
33808        let union = PlanNode::Union {
33809            left: Box::new(PlanNode::Scan(var_scan(
33810                Some("f"),
33811                "http://ex/hasGeom",
33812                Some("g"),
33813                8_000_000,
33814            ))),
33815            right: Box::new(PlanNode::Scan(var_scan(
33816                Some("f"),
33817                "http://ex/hasDefault",
33818                Some("g"),
33819                1,
33820            ))),
33821        };
33822        let feature = PlanNode::Scan(var_scan(
33823            Some("f"),
33824            "http://ex/aFeature",
33825            Some("ft"),
33826            7_900_000,
33827        ));
33828        let cls = PlanNode::Scan(var_scan(Some("f"), "http://ex/aCls", Some("c"), 39_000_000));
33829        test_join(test_join(test_join(union, feature), cls), cluster)
33830    }
33831
33832    fn geo_cluster_profile() -> StatsProfile {
33833        let mut profile = StatsProfile::default();
33834        for (p, rows) in [
33835            ("http://ex/hasGeom", 8_000_000u64),
33836            ("http://ex/hasDefault", 1),
33837            ("http://ex/aFeature", 7_900_000),
33838            ("http://ex/aCls", 39_000_000),
33839            ("http://ex/asWKT", 5_000_000),
33840        ] {
33841            profile.predicate_counts.insert(StrHash::new(p), rows);
33842        }
33843        // hasDefault stays deliberately SKETCHLESS — the sydney poisoning
33844        // shape: a never-observed predicate (rows priced at 1) whose
33845        // missing HLL must not discard hasGeom's sketch from the union's
33846        // key domain. Every other predicate carries full HLLs.
33847        for (p, rows) in [
33848            ("http://ex/hasGeom", 8_000_000u64),
33849            ("http://ex/aFeature", 7_900_000),
33850            ("http://ex/aCls", 39_000_000),
33851            ("http://ex/asWKT", 5_000_000),
33852        ] {
33853            profile
33854                .subjects_per_predicate
33855                .insert(StrHash::new(p), hll_with_n(rows as u128));
33856            profile
33857                .objects_per_predicate
33858                .insert(StrHash::new(p), hll_with_n(rows as u128));
33859        }
33860        profile.total_puts = 59_900_001;
33861        profile
33862    }
33863
33864    #[test]
33865    fn stamped_custom_cluster_pools_and_seats_first() {
33866        // The reassociation lift: with the cost stamp, the spine pools and
33867        // the cluster — the smallest operand by far — attaches in round 1,
33868        // so its selectivity ranks against every arm and the scans above
33869        // become key-pushed joins instead of a full-width spine the top
33870        // join discards 97.9% of.
33871        let cluster = test_join(
33872            PlanNode::CustomNode(cost_test_op(
33873                500,
33874                Some(CustomOpCost {
33875                    drain_rows: 90,
33876                    per_key_unit: 8,
33877                    inline_point_unit: 1,
33878                    direct_probe: true,
33879                    probe_keyed_columns: 0b1,
33880                    probe_filter_unit: 8,
33881                    probe_memo_entry_rows: 0,
33882                }),
33883            )),
33884            PlanNode::Scan(var_scan(
33885                Some("gm"),
33886                "http://ex/asWKT",
33887                Some("g"),
33888                5_000_000,
33889            )),
33890        );
33891        let mut tree = sydney_shaped_tree(cluster);
33892        let profile = geo_cluster_profile();
33893        // Sanity: as built, only the spine's top join sits above the
33894        // cluster.
33895        assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, true)));
33896        reassociate_inner_joins(&mut tree, Some(&profile), None);
33897        // Pooled and seated in round 1: all three scan joins (union,
33898        // aFeature, aCls) sit above the cluster, the key arm stayed INSIDE
33899        // the cluster, and the stamp survived the pool (the association pass's pricing
33900        // reads it).
33901        assert_eq!(custom_cluster_facts(&tree), Some((3, 5_000_000, true)));
33902        // Idempotent: re-flattening the rebuilt tree yields the same pool
33903        // and the same fold.
33904        let once = tree.clone();
33905        reassociate_inner_joins(&mut tree, Some(&profile), None);
33906        assert_eq!(tree, once);
33907    }
33908
33909    #[test]
33910    fn unpriced_custom_cluster_keeps_the_spine_frozen() {
33911        // `cost: None` = no honest pool price (the temporal plugins today):
33912        // the spine containing the cluster never pools — the cluster join
33913        // stays the top of THAT spine, the pre-pooling behavior — even
33914        // though cluster-free sub-spines still reassociate on their own.
33915        let cluster = test_join(
33916            PlanNode::CustomNode(cost_test_op(500, None)),
33917            PlanNode::Scan(var_scan(
33918                Some("gm"),
33919                "http://ex/asWKT",
33920                Some("g"),
33921                5_000_000,
33922            )),
33923        );
33924        let mut tree = sydney_shaped_tree(cluster);
33925        assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, false)));
33926        reassociate_inner_joins(&mut tree, Some(&geo_cluster_profile()), None);
33927        assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, false)));
33928    }
33929
33930    #[test]
33931    fn pinned_custom_cluster_keeps_the_spine_frozen() {
33932        // A pinned op's executor contract is one ground-unique probe term;
33933        // the pass must not reorder the spine around it. Defensive today
33934        // (pins are stamped after reassociation) — this pins the rule
33935        // against a future pipeline point stamping them earlier.
33936        let mut op = cost_test_op(
33937            500,
33938            Some(CustomOpCost {
33939                drain_rows: 90,
33940                per_key_unit: 8,
33941                inline_point_unit: 1,
33942                direct_probe: true,
33943                probe_keyed_columns: 0b1,
33944                probe_filter_unit: 8,
33945                probe_memo_entry_rows: 0,
33946            }),
33947        );
33948        op.pinned
33949            .push((var("g"), EncodedTerm::from(&Literal::from(1))));
33950        let cluster = test_join(
33951            PlanNode::CustomNode(op),
33952            PlanNode::Scan(var_scan(
33953                Some("gm"),
33954                "http://ex/asWKT",
33955                Some("g"),
33956                5_000_000,
33957            )),
33958        );
33959        let mut tree = sydney_shaped_tree(cluster);
33960        assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, true)));
33961        reassociate_inner_joins(&mut tree, Some(&geo_cluster_profile()), None);
33962        assert_eq!(custom_cluster_facts(&tree), Some((1, 5_000_000, true)));
33963    }
33964
33965    /// Left-deep order of the Scan leaves' row estimates — the observable
33966    /// for "which association order did the association pass pick" in the operand-
33967    /// descent tests (row counts are unique per fixture).
33968    fn scan_row_order(node: &PlanNode, out: &mut Vec<u64>) {
33969        match node {
33970            PlanNode::Join { left, right, .. } | PlanNode::Union { left, right } => {
33971                scan_row_order(left, out);
33972                scan_row_order(right, out);
33973            }
33974            PlanNode::Scan(scan) => out.push(scan.produced_row_count_estimate),
33975            _ => {}
33976        }
33977    }
33978
33979    /// Sketches for the operand-descent fixtures: every predicate priced
33980    /// AND sketched, so the association pass's produced estimates track the row counts
33981    /// the tests assert on.
33982    fn chained_union_profile() -> StatsProfile {
33983        let mut profile = StatsProfile::default();
33984        for (p, rows) in [
33985            ("http://ex/hasOwner", 5_000_000u64),
33986            ("http://ex/inAgency", 4_000_000),
33987            ("http://ex/flagged", 2_000),
33988            ("http://ex/underReview", 500),
33989            ("http://ex/asWKT", 5_000_000),
33990            ("http://ex/tagOne", 2_000),
33991            ("http://ex/tagTwo", 3_000),
33992            ("http://ex/agencyName", 1_000),
33993        ] {
33994            profile.predicate_counts.insert(StrHash::new(p), rows);
33995            profile
33996                .subjects_per_predicate
33997                .insert(StrHash::new(p), hll_with_n(rows as u128));
33998            profile
33999                .objects_per_predicate
34000                .insert(StrHash::new(p), hll_with_n(rows as u128));
34001        }
34002        profile
34003    }
34004
34005    /// Shape 1: arm 1 pooled a
34006    /// Union operand WHOLE and returned, so a multi-triple chain inside a
34007    /// union arm kept parse order — unbounded-bad, the same driver-choice
34008    /// cost class sydney cured, one level down. The operand descent must
34009    /// reach it: the chain folds cost-based (the 2K `flagged` scan
34010    /// attaches before the 4M `inAgency` pair) instead of staying
34011    /// parse-order.
34012    #[test]
34013    fn pooled_union_operand_interior_associates_cost_based() {
34014        let profile = chained_union_profile();
34015        // The reviewer's chain, parse order: hasOwner -> inAgency ->
34016        // flagged (flagged last).
34017        let has_owner = PlanNode::Scan(var_scan(
34018            Some("parcel"),
34019            "http://ex/hasOwner",
34020            Some("owner"),
34021            5_000_000,
34022        ));
34023        let in_agency = PlanNode::Scan(var_scan(
34024            Some("owner"),
34025            "http://ex/inAgency",
34026            Some("agency"),
34027            4_000_000,
34028        ));
34029        let flagged = PlanNode::Scan(var_scan(
34030            Some("parcel"),
34031            "http://ex/flagged",
34032            Some("v"),
34033            2_000,
34034        ));
34035        let chain = test_join(test_join(has_owner, in_agency), flagged);
34036        let union = PlanNode::Union {
34037            left: Box::new(chain),
34038            right: Box::new(PlanNode::Scan(var_scan(
34039                Some("parcel"),
34040                "http://ex/underReview",
34041                Some("r"),
34042                500,
34043            ))),
34044        };
34045        let cluster = test_join(
34046            PlanNode::CustomNode(cost_test_op(
34047                500,
34048                Some(CustomOpCost {
34049                    drain_rows: 90,
34050                    per_key_unit: 8,
34051                    inline_point_unit: 1,
34052                    direct_probe: true,
34053                    probe_keyed_columns: 0b1,
34054                    probe_filter_unit: 8,
34055                    probe_memo_entry_rows: 0,
34056                }),
34057            )),
34058            PlanNode::Scan(var_scan(
34059                Some("gm"),
34060                "http://ex/asWKT",
34061                Some("g"),
34062                5_000_000,
34063            )),
34064        );
34065        let mut tree = test_join(union, cluster);
34066        reassociate_inner_joins(&mut tree, Some(&profile), None);
34067        // The pool seats the union and the cluster as its two operands;
34068        // which side each occupies is a seating decision. The claim is that
34069        // the pass descends into the union's arms and rebuilds the chain.
34070        let PlanNode::Join { left, right, .. } = &tree else {
34071            panic!("expected the spine root Join, got {tree:?}")
34072        };
34073        let (union, other) = match (left.as_ref(), right.as_ref()) {
34074            (union @ PlanNode::Union { .. }, other) => (union, other),
34075            (other, union @ PlanNode::Union { .. }) => (union, other),
34076            _ => panic!("expected the Union as a root operand, got {tree:?}"),
34077        };
34078        assert!(
34079            custom_cluster_facts(other).is_some(),
34080            "the cluster must remain the pool's other operand: {other:?}"
34081        );
34082        let PlanNode::Union { left: chain, .. } = union else {
34083            unreachable!("matched a Union above")
34084        };
34085
34086        // The chain was written hasOwner -> inAgency -> flagged. The rebuild
34087        // must not keep that order: the 2K flagged scan must be joined before
34088        // the 4M inAgency scan. Where the 5M hasOwner scan lands (the starting
34089        // point or the last attachment) is the starting point's choice and is
34090        // not the claim.
34091        let mut order = Vec::new();
34092        scan_row_order(chain, &mut order);
34093        let position = |rows: u64| {
34094            order
34095                .iter()
34096                .position(|&row| row == rows)
34097                .unwrap_or_else(|| panic!("scan {rows} missing from the rebuilt chain: {order:?}"))
34098        };
34099        assert!(
34100            position(2_000) < position(4_000_000),
34101            "flagged (2K) must be joined before inAgency (4M), \
34102             inverting the written order: {order:?}"
34103        );
34104
34105        // Idempotent: the descent must not destabilize the association pass.
34106        let once = tree.clone();
34107        reassociate_inner_joins(&mut tree, Some(&profile), None);
34108        assert_eq!(tree, once);
34109    }
34110
34111    /// Shape 2: the spine whose pool is ONLY the cluster
34112    /// (`operands.len() == 1` — the association pass never runs; the two-variable
34113    /// filter shape where the plugin's cluster IS the spine). Arm 1
34114    /// pre-fix returned the cluster unchanged, key arm in parse order.
34115    /// The operand descent reaches the key arm: it folds cost-based
34116    /// (tagOne, 2K, attaches before tagTwo, 3K) while the cluster itself
34117    /// stays atomic.
34118    #[test]
34119    fn pooled_cluster_operand_descends_into_the_key_arm() {
34120        let profile = chained_union_profile();
34121        let wkt = PlanNode::Scan(var_scan(Some("g"), "http://ex/asWKT", Some("w"), 5_000_000));
34122        let tag_two = PlanNode::Scan(var_scan(Some("g"), "http://ex/tagTwo", Some("t2"), 3_000));
34123        let tag_one = PlanNode::Scan(var_scan(Some("g"), "http://ex/tagOne", Some("t1"), 2_000));
34124        // Parse order: tagTwo before tagOne — the association pass must invert it.
34125        let key_arm = test_join(test_join(wkt, tag_two), tag_one);
34126        let mut tree = test_join(
34127            PlanNode::CustomNode(cost_test_op(
34128                500,
34129                Some(CustomOpCost {
34130                    drain_rows: 90,
34131                    per_key_unit: 8,
34132                    inline_point_unit: 1,
34133                    direct_probe: true,
34134                    probe_keyed_columns: 0b1,
34135                    probe_filter_unit: 8,
34136                    probe_memo_entry_rows: 0,
34137                }),
34138            )),
34139            key_arm,
34140        );
34141        assert_eq!(
34142            custom_cluster_facts(&tree).map(|(joins_above, _, stamped)| (joins_above, stamped)),
34143            Some((0, true)),
34144            "as built: the cluster is the whole spine, key arm in parse order"
34145        );
34146        reassociate_inner_joins(&mut tree, Some(&profile), None);
34147        // The cluster stayed atomic (the CustomNode still sits one join
34148        // above its key arm) and the key arm is rebuilt by cost.
34149        assert_eq!(
34150            custom_cluster_facts(&tree).map(|(joins_above, _, stamped)| (joins_above, stamped)),
34151            Some((0, true)),
34152            "the descent must not dissolve the cluster from its key arm"
34153        );
34154        let PlanNode::Join { right: key_arm, .. } = &tree else {
34155            panic!("expected the cluster Join, got {tree:?}")
34156        };
34157
34158        // The key arm was written wkt -> tagTwo -> tagOne. The rebuild must
34159        // not keep that order: the 2K tagOne scan must be joined before the
34160        // 3K tagTwo scan. Where the 5M wkt scan lands (the starting point or
34161        // the last attachment) is the starting point's choice and is not the
34162        // claim.
34163        let mut order = Vec::new();
34164        scan_row_order(key_arm, &mut order);
34165        let position = |rows: u64| {
34166            order
34167                .iter()
34168                .position(|&row| row == rows)
34169                .unwrap_or_else(|| {
34170                    panic!("scan {rows} missing from the rebuilt key arm: {order:?}")
34171                })
34172        };
34173        assert!(
34174            position(2_000) < position(3_000),
34175            "tagOne (2K) must be joined before tagTwo (3K), \
34176             inverting the written order: {order:?}"
34177        );
34178
34179        let once = tree.clone();
34180        reassociate_inner_joins(&mut tree, Some(&profile), None);
34181        assert_eq!(tree, once);
34182    }
34183
34184    /// The widening beyond the Lot A regression: a spine with NO custom
34185    /// node also pools (arm 1 predates Lot A) and also skipped operand
34186    /// interiors. The descent reaches those too — with no cluster
34187    /// anywhere in the query, the union arm's chain still folds
34188    /// cost-based.
34189    #[test]
34190    fn cluster_free_pooled_spine_visits_union_interiors() {
34191        let profile = chained_union_profile();
34192        let has_owner = PlanNode::Scan(var_scan(
34193            Some("parcel"),
34194            "http://ex/hasOwner",
34195            Some("owner"),
34196            5_000_000,
34197        ));
34198        let in_agency = PlanNode::Scan(var_scan(
34199            Some("owner"),
34200            "http://ex/inAgency",
34201            Some("agency"),
34202            4_000_000,
34203        ));
34204        let flagged = PlanNode::Scan(var_scan(
34205            Some("parcel"),
34206            "http://ex/flagged",
34207            Some("v"),
34208            2_000,
34209        ));
34210        let chain = test_join(test_join(has_owner, in_agency), flagged);
34211        let union = PlanNode::Union {
34212            left: Box::new(chain),
34213            right: Box::new(PlanNode::Scan(var_scan(
34214                Some("parcel"),
34215                "http://ex/underReview",
34216                Some("r"),
34217                500,
34218            ))),
34219        };
34220        let mut tree = test_join(
34221            union,
34222            PlanNode::Scan(var_scan(
34223                Some("agency"),
34224                "http://ex/agencyName",
34225                Some("name"),
34226                1_000,
34227            )),
34228        );
34229        reassociate_inner_joins(&mut tree, Some(&profile), None);
34230
34231        // The union is one operand of the root spine; which side it occupies
34232        // is a seating decision. The claim is that the pass descends into its
34233        // arms and rebuilds the chain there.
34234        let PlanNode::Join { left, right, .. } = &tree else {
34235            panic!("expected the spine root Join, got {tree:?}")
34236        };
34237        let union = if matches!(**left, PlanNode::Union { .. }) {
34238            left
34239        } else if matches!(**right, PlanNode::Union { .. }) {
34240            right
34241        } else {
34242            panic!("expected the Union as a root operand, got {tree:?}");
34243        };
34244        let PlanNode::Union { left: chain, .. } = &**union else {
34245            unreachable!("matched a Union above")
34246        };
34247
34248        fn one_scan_rows(node: &PlanNode) -> u64 {
34249            let mut rows = Vec::new();
34250            scan_row_order(node, &mut rows);
34251            assert_eq!(rows.len(), 1, "expected a single scan, got {node:?}");
34252            rows[0]
34253        }
34254
34255        // The chain was written hasOwner -> inAgency -> flagged. The rebuild
34256        // must not keep that order: the two small scans form the inner pair
34257        // and the 4M inAgency scan is attached last. Which side of the pair
34258        // each scan occupies is the starting point's choice and is not the
34259        // claim.
34260        let PlanNode::Join {
34261            left: inner,
34262            right: outer_probe,
34263            ..
34264        } = chain.as_ref()
34265        else {
34266            panic!("expected the rebuilt chain, got {chain:?}");
34267        };
34268        assert_eq!(
34269            one_scan_rows(outer_probe),
34270            4_000_000,
34271            "inAgency must be attached last, not left in written order"
34272        );
34273        let PlanNode::Join {
34274            left: pair_a,
34275            right: pair_b,
34276            ..
34277        } = inner.as_ref()
34278        else {
34279            panic!("expected the inner pair, got {inner:?}");
34280        };
34281        let mut pair = [one_scan_rows(pair_a), one_scan_rows(pair_b)];
34282        pair.sort_unstable();
34283        assert_eq!(
34284            pair,
34285            [2_000, 5_000_000],
34286            "the inner pair must be flagged + hasOwner"
34287        );
34288    }
34289
34290    #[test]
34291    fn union_domain_binds_an_unknown_hosting_arm_by_its_rows() {
34292        // The sydney poisoning shape: one sketched arm (hasGeometry, 8M
34293        // rows, objects HLL) beside one sketchless arm hosting the same
34294        // key (hasDefault — never-observed, rows priced at 1). The union's
34295        // key domain must be `sketch + unknown rows` — a sound upper
34296        // bound — instead of the old both-or-nothing `None` that made the
34297        // seating-cost model price every pushed page as a full-arm match.
34298        let profile = geo_cluster_profile();
34299        let sketched = PlanNode::Scan(var_scan(
34300            Some("f"),
34301            "http://ex/hasGeom",
34302            Some("g"),
34303            8_000_000,
34304        ));
34305        let sketchless = PlanNode::Scan(var_scan(Some("f"), "http://ex/hasDefault", Some("g"), 1));
34306        let union = PlanNode::Union {
34307            left: Box::new(sketched.clone()),
34308            right: Box::new(sketchless),
34309        };
34310        let dom = |node: &PlanNode| join_key_domain_for_node(Some(&profile), node, &var("g"));
34311        let sketched_dom = dom(&sketched).expect("hasGeom objects HLL");
34312        let got = dom(&union).expect("union domain is bound by the rows");
34313        // The sketchless arm contributes its row estimate (1), not None.
34314        assert_eq!(got, sketched_dom.saturating_add(1));
34315        // An arm that does not host the key keeps the old None: the
34316        // union's domain must not inherit a foreign arm's rows, and the
34317        // hosting probe cannot see every shape (a Path binds its slots).
34318        let foreign = PlanNode::Scan(var_scan(Some("x"), "http://ex/aCls", Some("c"), 39_000_000));
34319        let foreign_union = PlanNode::Union {
34320            left: Box::new(sketched),
34321            right: Box::new(foreign),
34322        };
34323        assert_eq!(dom(&foreign_union), None);
34324        // Both arms sketchless: None, the bare-scan contract.
34325        let both = PlanNode::Union {
34326            left: Box::new(PlanNode::Scan(var_scan(
34327                Some("f"),
34328                "http://ex/none1",
34329                Some("g"),
34330                10,
34331            ))),
34332            right: Box::new(PlanNode::Scan(var_scan(
34333                Some("f"),
34334                "http://ex/none2",
34335                Some("g"),
34336                20,
34337            ))),
34338        };
34339        assert_eq!(dom(&both), None);
34340    }
34341
34342    #[test]
34343    fn union_domain_merges_arm_sketches_instead_of_summing() {
34344        // Two facet arms over the same subject population: the union's
34345        // distinct-subject count is the merged sketch, not the sum of the arm
34346        // counts (which would count every shared subject once per arm).
34347        let mut profile = StatsProfile::default();
34348        let mut first = waratah_stats::HyperLogLog::default_params();
34349        for i in 0..1_000u128 {
34350            first.add(i);
34351        }
34352        let mut second = waratah_stats::HyperLogLog::default_params();
34353        for i in 500..1_500u128 {
34354            second.add(i);
34355        }
34356        profile.total_puts = 2_000;
34357        profile
34358            .subjects_per_predicate
34359            .insert(StrHash::new("http://ex/p1"), first);
34360        profile
34361            .subjects_per_predicate
34362            .insert(StrHash::new("http://ex/p2"), second);
34363        let union = PlanNode::Union {
34364            left: Box::new(PlanNode::Scan(var_scan(
34365                Some("s"),
34366                "http://ex/p1",
34367                Some("o1"),
34368                1_000,
34369            ))),
34370            right: Box::new(PlanNode::Scan(var_scan(
34371                Some("s"),
34372                "http://ex/p2",
34373                Some("o2"),
34374                1_000,
34375            ))),
34376        };
34377        let domain = join_key_domain_for_node(Some(&profile), &union, &var("s"))
34378            .expect("the merged sketch supplies the domain");
34379        assert!(
34380            (1_300..=1_700).contains(&domain),
34381            "merged union domain, got {domain}"
34382        );
34383        assert!(
34384            domain < 1_900,
34385            "the two-arm sum (2,000) must not be the domain: {domain}"
34386        );
34387    }
34388
34389    #[test]
34390    fn union_domain_adds_the_exact_class_count() {
34391        // A ground-class `rdf:type` arm has an exact count but no sketch; it
34392        // is added to the merged sketched arms.
34393        let mut profile = StatsProfile::default();
34394        let mut subjects = waratah_stats::HyperLogLog::default_params();
34395        for i in 0..1_000u128 {
34396            subjects.add(i);
34397        }
34398        profile
34399            .subjects_per_predicate
34400            .insert(StrHash::new("http://ex/p1"), subjects);
34401        profile
34402            .class_counts
34403            .insert(StrHash::new("http://ex/Cls"), 250);
34404        let plain = PlanNode::Scan(var_scan(Some("s"), "http://ex/p1", Some("o"), 1_000));
34405        let mut typed = var_scan(None, "http://ex/placeholder", None, 250);
34406        typed.pattern.predicate = Some(RDF_TYPE.clone());
34407        typed.pattern.object = Some(EncodedTerm::from(&NamedNode::new("http://ex/Cls").unwrap()));
34408        typed.subject = Some(var("s"));
34409        typed.object = None;
34410        let union = PlanNode::Union {
34411            left: Box::new(plain),
34412            right: Box::new(PlanNode::Scan(typed)),
34413        };
34414        let domain = join_key_domain_for_node(Some(&profile), &union, &var("s"))
34415            .expect("merged sketch plus the exact class count");
34416        assert!(
34417            (1_150..=1_350).contains(&domain),
34418            "merged sketch plus the exact class count, got {domain}"
34419        );
34420    }
34421
34422    #[test]
34423    fn union_domain_counts_the_class_universe_once() {
34424        // Every `rdf:type` arm with a class variable describes the same class
34425        // universe: two arms must not double the domain.
34426        let mut profile = StatsProfile::default();
34427        for class in ["http://ex/C1", "http://ex/C2", "http://ex/C3"] {
34428            profile.class_counts.insert(StrHash::new(class), 100);
34429        }
34430        let type_object = |subject: &str| {
34431            let mut scan = var_scan(Some(subject), "http://ex/placeholder", None, 300);
34432            scan.pattern.predicate = Some(RDF_TYPE.clone());
34433            scan.object = Some(var("c"));
34434            PlanNode::Scan(scan)
34435        };
34436        let union = PlanNode::Union {
34437            left: Box::new(type_object("s1")),
34438            right: Box::new(type_object("s2")),
34439        };
34440        let domain = join_key_domain_for_node(Some(&profile), &union, &var("c"))
34441            .expect("the class universe is exact");
34442        assert_eq!(domain, 3, "the class universe is one set, not one per arm");
34443    }
34444
34445    #[test]
34446    fn facet_union_join_estimates_the_containment_output() {
34447        // Two facet arms over the same record population, joined to the
34448        // key-unique record scan on the subject. Every facet subject is a
34449        // record, so the output is |L| = 4,000; the summed arm domains would
34450        // divide by 2,000 and price 2,000.
34451        let mut profile = StatsProfile::default();
34452        let mut subjects = waratah_stats::HyperLogLog::default_params();
34453        for i in 0..1_000u128 {
34454            subjects.add(i);
34455        }
34456        profile.total_puts = 4_000;
34457        profile
34458            .subjects_per_predicate
34459            .insert(StrHash::new("http://ex/facetA"), subjects.clone());
34460        profile
34461            .subjects_per_predicate
34462            .insert(StrHash::new("http://ex/facetB"), subjects.clone());
34463        profile
34464            .subjects_per_predicate
34465            .insert(StrHash::new("http://ex/datasetKind"), subjects);
34466        let union = PlanNode::Union {
34467            left: Box::new(PlanNode::Scan(var_scan(
34468                Some("r"),
34469                "http://ex/facetA",
34470                Some("v1"),
34471                2_000,
34472            ))),
34473            right: Box::new(PlanNode::Scan(var_scan(
34474                Some("r"),
34475                "http://ex/facetB",
34476                Some("v2"),
34477                2_000,
34478            ))),
34479        };
34480        let mut record_scan = var_scan(Some("r"), "http://ex/datasetKind", None, 1_000);
34481        record_scan.pattern.object = Some(EncodedTerm::from(
34482            &NamedNode::new("http://ex/record").unwrap(),
34483        ));
34484        let record = PlanNode::Scan(record_scan);
34485        let keys = hash_keys_for(&union.output_vars(), &record.output_vars());
34486        let (_, produced, _) = finalize_inner_join_meta(&union, &record, &keys, Some(&profile));
34487        assert!(
34488            produced >= 3_500,
34489            "containment-aware union join output, got {produced}"
34490        );
34491    }
34492
34493    #[test]
34494    fn union_domain_bound_lets_the_cluster_drive() {
34495        // The sydney seating, end to end at the comparator: the geo
34496        // cluster joined against a union-carrying subtree whose ?geom
34497        // domain only exists once the sketchless union arm contributes
34498        // its row estimate. Pre-fix, the unknown domain priced the
34499        // cluster-driving orientation as a full-arm match per page and
34500        // the 8M side drove (the 355s shape); post-fix the sweep-priced
34501        // cluster drives and the subtree answers per-page key pushes.
34502        let profile = geo_cluster_profile();
34503        let union = PlanNode::Union {
34504            left: Box::new(PlanNode::Scan(var_scan(
34505                Some("f"),
34506                "http://ex/hasGeom",
34507                Some("g"),
34508                8_000_000,
34509            ))),
34510            right: Box::new(PlanNode::Scan(var_scan(
34511                Some("f"),
34512                "http://ex/hasDefault",
34513                Some("g"),
34514                1,
34515            ))),
34516        };
34517        let feature = PlanNode::Scan(var_scan(
34518            Some("f"),
34519            "http://ex/aFeature",
34520            Some("ft"),
34521            7_900_000,
34522        ));
34523        let subtree = test_join(union, feature);
34524        let cluster = test_join(
34525            PlanNode::CustomNode(cost_test_op(
34526                500,
34527                Some(CustomOpCost {
34528                    drain_rows: 90,
34529                    per_key_unit: 8,
34530                    inline_point_unit: 1,
34531                    direct_probe: true,
34532                    probe_keyed_columns: 0b1,
34533                    probe_filter_unit: 8,
34534                    probe_memo_entry_rows: 0,
34535                }),
34536            )),
34537            PlanNode::Scan(var_scan(
34538                Some("gm"),
34539                "http://ex/asWKT",
34540                Some("g"),
34541                5_000_000,
34542            )),
34543        );
34544        // As built: the fat subtree drives, the cluster probes.
34545        let mut join = test_join(subtree, cluster);
34546        refinalize_joins_without_ctx(&mut join, Some(&profile));
34547        let PlanNode::Join { left, .. } = &join else {
34548            panic!("still a join")
34549        };
34550        // The swap puts the DRIVER on the left: the cluster join drives,
34551        // and inside it the custom op still leads its key arm.
34552        let PlanNode::Join {
34553            left: cluster_lead, ..
34554        } = &**left
34555        else {
34556            panic!("the driver side is the cluster join")
34557        };
34558        assert!(
34559            matches!(&**cluster_lead, PlanNode::CustomNode(_)),
34560            "the geo cluster drives"
34561        );
34562    }
34563
34564    #[test]
34565    fn assoc_ranks_by_the_seating_the_arm_swap_keeps() {
34566        let mut profile = StatsProfile::default();
34567        profile
34568            .predicate_counts
34569            .insert(StrHash::new("http://ex/pS"), 100_000);
34570        profile
34571            .predicate_counts
34572            .insert(StrHash::new("http://ex/pB"), 50_000);
34573        profile
34574            .predicate_counts
34575            .insert(StrHash::new("http://ex/pC"), 40_000);
34576        profile
34577            .subjects_per_predicate
34578            .insert(StrHash::new("http://ex/pS"), hll_with_n(100_000));
34579        profile
34580            .subjects_per_predicate
34581            .insert(StrHash::new("http://ex/pB"), hll_with_n(100));
34582        profile
34583            .subjects_per_predicate
34584            .insert(StrHash::new("http://ex/pC"), hll_with_n(80_000));
34585        profile
34586            .objects_per_predicate
34587            .insert(StrHash::new("http://ex/pS"), hll_with_n(10_000));
34588        profile
34589            .objects_per_predicate
34590            .insert(StrHash::new("http://ex/pB"), hll_with_n(2_000));
34591        profile
34592            .objects_per_predicate
34593            .insert(StrHash::new("http://ex/pC"), hll_with_n(1_000));
34594        profile.total_puts = 190_000;
34595        let seed = PlanNode::Scan(var_scan(Some("x"), "http://ex/pS", Some("z"), 100_000));
34596        let cand_b = PlanNode::Scan(var_scan(Some("x"), "http://ex/pB", Some("w"), 50_000));
34597        let cand_c = PlanNode::Scan(var_scan(Some("x"), "http://ex/pC", Some("v"), 40_000));
34598
34599        // Pin all four orientation prices first — the as-built pair and
34600        // the survivor pair — so the assertion below is checkable by hand
34601        // against the fixture numbers.
34602        let price = |driver: &PlanNode, probe: &PlanNode| {
34603            let keys = hash_keys_for(&driver.output_vars(), &probe.output_vars());
34604            seat_cost_total(Some(&profile), driver, probe, &keys, None, None)
34605        };
34606        let b_seed_drives = price(&seed, &cand_b);
34607        let seed_b = price(&cand_b, &seed);
34608        let c_seed_drives = price(&seed, &cand_c);
34609        let seed_c = price(&cand_c, &seed);
34610        // HLL cardinalities land within ~0.5% of the inserted counts, so
34611        // the seek/list pins derive from the profile's own cardinality
34612        // (clustered_page_distinct on the real domain) instead of the
34613        // nominal numbers — the pins stay exact against whatever the
34614        // sketches actually read. The B rows cells are self-normalizing
34615        // (the matched fraction divides the probe's own domain out).
34616        let dom = |p: &str| {
34617            profile
34618                .subjects_per_predicate
34619                .get(&StrHash::new(p))
34620                .expect("subject HLL")
34621                .cardinality()
34622        };
34623        let (seed_dom, b_dom) = (dom("http://ex/pS"), dom("http://ex/pB"));
34624        // One seed page's key list: one production page (`seat_page_rows`
34625        // for a scan driver — the PUSHDOWN_TERMS_LIMIT terms limit through the
34626        // coalescer's clamp) of the seed's ~100k-key domain.
34627        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
34628        // Seed-driving B and C both fire the priced fetch-once trigger:
34629        // every seed page broadcasts a ~24,576-key list, and B's whole 100-key
34630        // domain sits inside it (matched = the whole arm per page), while
34631        // C matches a quarter of its 80k domain per page — five pages of
34632        // seeks + matches dwarfs 1.5 × either arm. Both seats price the
34633        // BUILD the runtime stamps: seed + one probe read, zero seeks.
34634        assert_eq!(b_seed_drives.rows, 150_000);
34635        assert_eq!(b_seed_drives.seeks, 0);
34636        // B-driving: the per-page list is B's own domain squeezed into a
34637        // page (b_dom times the page fraction of B's rows), and the
34638        // matched rows follow that list against the seed's domain. The
34639        // trigger does NOT fire (three pages of ~49-key lists ≈ 0.7M
34640        // row-equiv ≪ 1.5 × 100k) — per-page mode survives, pins unchanged.
34641        let b_list = clustered_page_distinct(50_000, b_dom, page);
34642        assert_eq!(
34643            seed_b.rows,
34644            50_000 + 3 * (100_000 * b_list.min(seed_dom) / seed_dom)
34645        );
34646        assert_eq!(seed_b.seeks, 3 * b_list);
34647        assert_eq!(c_seed_drives.seeks, b_seed_drives.seeks);
34648        // C's seating is also a build: the seed's pages saturate c_dom, and
34649        // the build price carries C's UNCLAMPED pattern price (~79.6k —
34650        // the profile invariant floors it at C's ~80k subject HLL), not
34651        // the 40k produced count.
34652        assert_eq!(c_seed_drives.rows, 179_620);
34653        // C drives at its own page count (2 pages over C's 40k rows); the
34654        // C-page key list is the page saturated against c_dom. Those two
34655        // pages of ~24,576-key lists match a quarter of the seed each —
34656        // 2 × (24,576 × 3.6 + 24,576) ≈ 226k row-equivalents ≥ 1.5 ×
34657        // 100k — the trigger fires and the cost model prices the build (the
34658        // seed's unclamped arm estimate is its own 100k count).
34659        assert_eq!(seed_c.seeks, 0);
34660        assert_eq!(seed_c.rows, 140_000);
34661
34662        let seat_ctx =
34663            QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
34664        // `associate_from_seed` establishes this order once before the loop;
34665        // a produced tie keeps the earliest entry, so the order is an input.
34666        let canonical = |mut candidates: Vec<JoinableSpineNode>| {
34667            candidates.sort_by(|a, b| {
34668                crate::explain::plan_node_tag(a.as_plan())
34669                    .cmp(&crate::explain::plan_node_tag(b.as_plan()))
34670            });
34671            candidates
34672        };
34673        let candidates = canonical(vec![
34674            JoinableSpineNode::Bare(cand_b.clone()),
34675            JoinableSpineNode::Bare(cand_c.clone()),
34676        ]);
34677        let picked = |idx: usize| crate::explain::plan_node_tag(candidates[idx].as_plan());
34678        let b_tag = crate::explain::plan_node_tag(&cand_b);
34679        let c_tag = crate::explain::plan_node_tag(&cand_c);
34680
34681        // Non-seat-by-total-cost mode: output rows decide. C (40,000) beats
34682        // B (50,000).
34683        let (idx, produced_c, _) = pick_attachment(&seed, &candidates, Some(&profile), None, false);
34684        assert_eq!(picked(idx), c_tag);
34685        let keys_b = hash_keys_for(&seed.output_vars(), &cand_b.output_vars());
34686        let produced_b = finalize_inner_join_meta(&seed, &cand_b, &keys_b, Some(&profile)).1;
34687        assert!(
34688            produced_c < produced_b,
34689            "C's join output ({produced_c}) must be below B's ({produced_b})"
34690        );
34691
34692        // Seat-by-total-cost mode: the cheaper of the two seatings decides.
34693        // B's survivor (~50,147) is below C's (140,000), so B is chosen. The
34694        // price that ranked B must be that survivor, not B's as-built
34695        // seating (150,000): ranking on the as-built price would return the
34696        // 150,000 figure and fail here.
34697        let (idx, _, cost) =
34698            pick_attachment(&seed, &candidates, Some(&profile), Some(&seat_ctx), true);
34699        assert_eq!(picked(idx), b_tag);
34700        assert_eq!((cost.rows, cost.seeks), (seed_b.rows, seed_b.seeks));
34701        assert_ne!(
34702            (cost.rows, cost.seeks),
34703            (b_seed_drives.rows, b_seed_drives.seeks)
34704        );
34705    }
34706
34707    /// End-to-end seat-mode coverage for the two starts. The seed is the
34708    /// 10-row disconnected A scan; the cheapest eligible pair is the keyed
34709    /// B-C pair (the cartesian pairs involving A exceed the 4x output
34710    /// guard). Start a therefore builds `A x C` first, while start b builds
34711    /// `B join C` first.
34712    ///
34713    /// This fixture's two accumulated totals land inside `seat_beats`' noise
34714    /// band, so the band-tie rule is what keeps the pair start; the strict
34715    /// "start b reads less" branch is not exercised here. Returning the seed
34716    /// start, or skipping the pair run, puts A back in the inner pair and
34717    /// fails the assertion.
34718    #[test]
34719    fn seat_mode_two_start_picks_the_pair_start_when_it_differs_from_the_seed_start() {
34720        fn one_scan_rows(node: &PlanNode) -> u64 {
34721            let mut rows = Vec::new();
34722            scan_row_order(node, &mut rows);
34723            assert_eq!(rows.len(), 1, "expected a single scan, got {node:?}");
34724            rows[0]
34725        }
34726        let mut profile = StatsProfile::default();
34727        for (predicate, rows) in [
34728            ("http://ex/pA", 10u64),
34729            ("http://ex/pB", 10_000),
34730            ("http://ex/pC", 5_000),
34731        ] {
34732            profile
34733                .predicate_counts
34734                .insert(StrHash::new(predicate), rows);
34735            profile
34736                .subjects_per_predicate
34737                .insert(StrHash::new(predicate), hll_with_n(rows as u128));
34738            profile
34739                .objects_per_predicate
34740                .insert(StrHash::new(predicate), hll_with_n(rows as u128));
34741        }
34742        // A shares no variable with B or C, so every pair involving A is a
34743        // cartesian; B and C share ?x.
34744        let a = PlanNode::Scan(var_scan(Some("a"), "http://ex/pA", Some("va"), 10));
34745        let b = PlanNode::Scan(var_scan(Some("x"), "http://ex/pB", Some("vb"), 10_000));
34746        let c = PlanNode::Scan(var_scan(Some("x"), "http://ex/pC", Some("vc"), 5_000));
34747        let mut tree = test_join(test_join(a, b), c);
34748        let seat_ctx =
34749            QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
34750        reassociate_inner_joins(&mut tree, Some(&profile), Some(&seat_ctx));
34751
34752        // The pair start attaches A last; the seed start would have A in the
34753        // inner pair (A x C first). Assert the pair start's association.
34754        let PlanNode::Join { left, right, .. } = &tree else {
34755            panic!("expected the spine root Join, got {tree:?}");
34756        };
34757        assert_eq!(
34758            one_scan_rows(right),
34759            10,
34760            "the 10-row A scan must be attached last, not first: {tree:?}"
34761        );
34762        let PlanNode::Join {
34763            left: pair_a,
34764            right: pair_b,
34765            ..
34766        } = left.as_ref()
34767        else {
34768            panic!("expected the pair start's inner join, got {left:?}");
34769        };
34770        let mut pair = [one_scan_rows(pair_a), one_scan_rows(pair_b)];
34771        pair.sort_unstable();
34772        assert_eq!(
34773            pair,
34774            [5_000, 10_000],
34775            "the inner pair must be B and C: {tree:?}"
34776        );
34777    }
34778
34779    /// Planner-work ceiling for the seat-mode association. The other
34780    /// `SEAT_CALLS` tests pin the cost of ONE seat price (linear in the
34781    /// subtree's joins); this one pins how many seat prices the association
34782    /// buys. Four operands, one disconnected 10-row seed whose cartesian
34783    /// pairs the explosion guard excludes, and three eligible keyed pairs:
34784    ///
34785    /// - pair pre-pass: 3 pairs x 2 orientations = 6;
34786    /// - seed run: 3 x 2 + 2 x 4 + 1 x 6 = 20;
34787    /// - pair run: (2 + 1) + (2 + 2) + (3 + 1) = 11.
34788    ///
34789    /// The runs exceed the flat two-per-candidate count because a join
34790    /// accumulator prices its own interior at every later attachment — once
34791    /// as the driver's once-cost and once through the probe walk — and a
34792    /// keys-empty candidate skips the probe walk. 37 in total. Skipping the
34793    /// pre-pass or the pair run lands at 26 or 31, and re-pricing a candidate
34794    /// or repeating the pre-pass exceeds 37, so any growth in that
34795    /// multiplier must be a deliberate, reviewed change rather than a silent
34796    /// planner-time regression.
34797    #[test]
34798    fn seat_mode_association_work_is_bounded_by_pairs_and_attachments() {
34799        let a = PlanNode::Scan(var_scan(Some("a"), "http://ex/pA", Some("va"), 10));
34800        let b = PlanNode::Scan(var_scan(Some("x"), "http://ex/pB", Some("vb"), 10_000));
34801        let c = PlanNode::Scan(var_scan(Some("x"), "http://ex/pC", Some("vc"), 5_000));
34802        let d = PlanNode::Scan(var_scan(Some("x"), "http://ex/pD", Some("vd"), 2_000));
34803        let mut tree = test_join(test_join(test_join(a, b), c), d);
34804        let seat_ctx =
34805            QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
34806        super::SEAT_CALLS.with(|counter| counter.set(0));
34807        reassociate_inner_joins(&mut tree, None, Some(&seat_ctx));
34808        let seat_calls = super::SEAT_CALLS.with(|counter| counter.get());
34809        assert_eq!(
34810            seat_calls, 37,
34811            "the pair pre-pass and both association runs must price 37 seats, got {seat_calls}"
34812        );
34813    }
34814
34815    /// The start-b dedup follows the pair's BUILT orientation, not tag order:
34816    /// a pair built with the seed on the right is a different seating of the
34817    /// same association and must be compared.
34818    #[test]
34819    fn pair_start_dedup_follows_the_built_orientation() {
34820        let other = "scan(?u <#1> ?t *)";
34821        let seed = "scan(?s <#2> ?t *)";
34822        assert!(
34823            pair_start_matches_seed_start(0, 0, Some(other), other),
34824            "the seed is the pair's left arm and start a attaches the pair's other arm"
34825        );
34826        assert!(
34827            !pair_start_matches_seed_start(1, 0, Some(other), other),
34828            "a pair built with the other arm on the left is a different seating"
34829        );
34830        assert!(
34831            !pair_start_matches_seed_start(0, 0, Some(seed), other),
34832            "start a's first attachment is not the pair's other arm"
34833        );
34834    }
34835
34836    /// Seat mode runs two starts. When the cheapest pair is the seed start's
34837    /// first pair but was BUILT in the other orientation, the second start is
34838    /// a different seating and must not be deduped away. The committed tree's
34839    /// pair carries pB on the left only when start b ran; a dedup that falls
34840    /// back to tag order leaves start a's pS on the left.
34841    #[test]
34842    fn seat_mode_pair_start_is_not_deduped_when_its_orientation_differs() {
34843        let mut profile = StatsProfile::default();
34844        profile
34845            .predicate_counts
34846            .insert(StrHash::new("http://ex/pS"), 10_000);
34847        profile
34848            .predicate_counts
34849            .insert(StrHash::new("http://ex/pB"), 20_000);
34850        profile
34851            .predicate_counts
34852            .insert(StrHash::new("http://ex/pC"), 200_000);
34853        profile
34854            .subjects_per_predicate
34855            .insert(StrHash::new("http://ex/pS"), hll_with_n(10_000));
34856        profile
34857            .subjects_per_predicate
34858            .insert(StrHash::new("http://ex/pB"), hll_with_n(20_000));
34859        // pC's `?t` domain matches pS's, so the second join stays keyed on
34860        // `?t`. With a tiny pC domain the second join degenerates towards a
34861        // cartesian, and start a's near-cartesian price can beat start b's
34862        // keyed price for reasons that have nothing to do with the dedup.
34863        profile
34864            .subjects_per_predicate
34865            .insert(StrHash::new("http://ex/pC"), hll_with_n(10_000));
34866        profile
34867            .objects_per_predicate
34868            .insert(StrHash::new("http://ex/pS"), hll_with_n(10_000));
34869        profile
34870            .objects_per_predicate
34871            .insert(StrHash::new("http://ex/pB"), hll_with_n(100));
34872        profile.total_puts = 230_000;
34873
34874        // Seed: smallest output and tag-first (`?s` < `?u`).
34875        let seed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pS", Some("t"), 10_000));
34876        // The seed start's first attachment. It is the cheaper pair driver
34877        // because its `?t` domain is tiny (100), despite having more rows.
34878        let other = PlanNode::Scan(var_scan(Some("u"), "http://ex/pB", Some("t"), 20_000));
34879        // Large and over the produced guard, so it cannot be the first
34880        // attachment or the pair. Its `?t` domain is pS-sized, so the second
34881        // join is keyed and start b's row total (the small pair plus one
34882        // keyed probe) beats start a's.
34883        let third = PlanNode::Scan(var_scan(Some("t"), "http://ex/pC", Some("v"), 200_000));
34884
34885        let mut tree = test_join(test_join(seed, other.clone()), third.clone());
34886        let seat_ctx =
34887            QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
34888        reassociate_inner_joins(&mut tree, Some(&profile), Some(&seat_ctx));
34889
34890        fn scan_with(node: &PlanNode, iri: &str) -> bool {
34891            matches!(
34892                node,
34893                PlanNode::Scan(scan)
34894                    if scan.pattern.predicate.as_ref()
34895                        == Some(&EncodedTerm::from(&NamedNode::new(iri).unwrap()))
34896            )
34897        }
34898        let PlanNode::Join { left, right, .. } = &tree else {
34899            panic!("expected the spine root, got {tree:?}");
34900        };
34901        let PlanNode::Join {
34902            left: inner_left,
34903            right: inner_right,
34904            ..
34905        } = left.as_ref()
34906        else {
34907            panic!("expected the pair join, got {left:?}");
34908        };
34909        assert!(
34910            scan_with(inner_left, "http://ex/pB"),
34911            "the pair must be built with its cheaper driver (pB) on the left, got {tree:?}"
34912        );
34913        assert!(scan_with(inner_right, "http://ex/pS"));
34914        assert!(scan_with(right, "http://ex/pC"));
34915    }
34916
34917    /// The gather's page count prices the driver's ownership-aware whole
34918    /// read (`driver_whole_read_rows`), never the raw cell: a driver scan
34919    /// clamped by its OWN claim carries the probe road's return in its
34920    /// cell (~80 on a 50k-catalog arm here), and pages priced off that
34921    /// count ONE page where the driving read streams three — the
34922    /// phantom-page defect (the tenant-union flip's class), under-pricing
34923    /// every per-page list/seek/matched term built on the count. Both
34924    /// gather consumers — the comparator's seats and the fetch-once
34925    /// stamp's priced verdict — take the same fixed count.
34926    #[test]
34927    fn seat_pages_price_the_ownership_aware_driver_read() {
34928        let mut profile = StatsProfile::default();
34929        profile
34930            .predicate_counts
34931            .insert(StrHash::new("http://ex/drv"), 50_000);
34932        profile
34933            .subjects_per_predicate
34934            .insert(StrHash::new("http://ex/drv"), hll_with_n(50_000));
34935        profile
34936            .objects_per_predicate
34937            .insert(StrHash::new("http://ex/drv"), hll_with_n(40_000));
34938        profile
34939            .predicate_counts
34940            .insert(StrHash::new("http://ex/prb"), 40_000);
34941        profile
34942            .subjects_per_predicate
34943            .insert(StrHash::new("http://ex/prb"), hll_with_n(40_000));
34944        profile.total_puts = 90_000;
34945        let key = var("k");
34946        let keys = [key.clone()];
34947        let probe = PlanNode::Scan(var_scan(Some("k"), "http://ex/prb", Some("o"), 40_000));
34948        // Three drivers over the same 50k-intrinsic pattern, differing
34949        // only in claim state and cell: an OWN claim (mark variable ∈ the
34950        // join's hash keys) whose cell carries the probe road's ~80-row
34951        // return; an unmarked scan at the intrinsic 50k; a FOREIGN claim
34952        // (mark variable outside the hash keys) whose cell carries the
34953        // ancestor push's 1,500-row bounded read.
34954        let intrinsic = estimate_unclamped_scan_rows(
34955            Some(&profile),
34956            &var_scan(Some("k"), "http://ex/drv", Some("o"), 1),
34957        );
34958        // Three drivers over the same intrinsic pattern, differing only
34959        // in claim state and cell: an OWN claim (mark variable ∈ the
34960        // join's hash keys) whose cell carries the probe road's ~80-row
34961        // return; an unmarked scan at the intrinsic (the same number the
34962        // own-claim branch recomputes — HLL estimation noise included, or
34963        // the equality below would pin that noise instead of the basis);
34964        // a FOREIGN claim (mark variable outside the hash keys) whose
34965        // cell carries the ancestor push's 1,500-row bounded read.
34966        let mut own_claimed = var_scan(Some("k"), "http://ex/drv", Some("o"), 80);
34967        own_claimed.broadcasted = Some((key.clone(), PatternSlot::Subject));
34968        let unmarked = var_scan(Some("k"), "http://ex/drv", Some("o"), intrinsic);
34969        let mut foreign_claimed = var_scan(Some("k"), "http://ex/drv", Some("o"), 1_500);
34970        foreign_claimed.broadcasted = Some((var("zzz"), PatternSlot::Subject));
34971        let own_driver = PlanNode::Scan(own_claimed);
34972        let plain_driver = PlanNode::Scan(unmarked);
34973        let foreign_driver = PlanNode::Scan(foreign_claimed);
34974
34975        // Page counts: the own-claim clamp conditioned the PROBE road, not
34976        // a driving read, so the own-claimed and unmarked drivers price the
34977        // SAME whole read and the same page count; the foreign claim's
34978        // cell IS the ancestor-bounded whole read (it holds in every
34979        // seating), so it keeps its own smaller count.
34980        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
34981        let own = seat_probe_shape(Some(&profile), &own_driver, &probe, &keys, None, None);
34982        assert_eq!(
34983            own.pages,
34984            intrinsic.div_ceil(page),
34985            "own claim: the page count prices the intrinsic whole read"
34986        );
34987        let plain = seat_probe_shape(Some(&profile), &plain_driver, &probe, &keys, None, None);
34988        assert_eq!(
34989            plain.pages, own.pages,
34990            "an own-claim clamp on the driver must not change the page count"
34991        );
34992        let foreign = seat_probe_shape(Some(&profile), &foreign_driver, &probe, &keys, None, None);
34993        assert_eq!(
34994            foreign.pages,
34995            1_500u64.div_ceil(page),
34996            "foreign claim: the ancestor-bounded cell is the whole read"
34997        );
34998
34999        // The cost estimate follows the gather: an own-claim clamp on the driver
35000        // cannot change the seating price — a phantom-cheap claimed driver
35001        // flipping a seat is exactly the tenant-union defect. (The drop
35002        // guard still reads the driver's cell — grant vs deny differs
35003        // between these variants — but a non-covered key prices
35004        // identically either way, so only the basis can move the cost estimate.)
35005        let seat_claimed = seat_cost_total(Some(&profile), &own_driver, &probe, &keys, None, None);
35006        let seat_plain = seat_cost_total(Some(&profile), &plain_driver, &probe, &keys, None, None);
35007        assert_eq!(
35008            seat_claimed, seat_plain,
35009            "an own-claim clamp on the driver must not change the cost estimate"
35010        );
35011    }
35012
35013    /// A driver key with NO domain sketch must price expensive, never
35014    /// free. This is a real planning-time state, not a synthetic one:
35015    /// `capped_for_wire` trims HLL map entries while `predicate_counts`
35016    /// survives, so a big enough predicate inventory produces arms whose
35017    /// domain lookups return `None`. The branch pins both halves of the
35018    /// conservative answer: the cover list is pinned to 1 —
35019    /// `push_list_covers_domain` requires length ≥ 2, so a missing
35020    /// sketch can never claim the push covers the probe domain — while
35021    /// the price stays the worst case, a full page of seeks per page with
35022    /// matched rows at that long list's fraction.
35023    #[test]
35024    fn missing_driver_domain_never_covers_and_prices_a_full_page() {
35025        let mut profile = StatsProfile::default();
35026        profile
35027            .predicate_counts
35028            .insert(StrHash::new("http://ex/pA"), 100_000);
35029        profile
35030            .predicate_counts
35031            .insert(StrHash::new("http://ex/pB"), 60_000);
35032        // pA deliberately has NO subjects_per_predicate entry — the shape
35033        // the wire cap leaves behind.
35034        profile
35035            .subjects_per_predicate
35036            .insert(StrHash::new("http://ex/pB"), hll_with_n(6_000));
35037        profile.total_puts = 160_000;
35038        let driver = PlanNode::Scan(var_scan(Some("x"), "http://ex/pA", Some("z"), 100_000));
35039        let probe = PlanNode::Scan(var_scan(Some("x"), "http://ex/pB", Some("w"), 60_000));
35040        let keys = hash_keys_for(&driver.output_vars(), &probe.output_vars());
35041        let seat = seat_cost_total(Some(&profile), &driver, &probe, &keys, None, None);
35042        // 5 pages (ceil(100k / page)); every key kept (the len-1 list
35043        // never covers); a full page of seeks per page; the matched
35044        // fraction self-normalizes against the probe's own domain, so the
35045        // whole arm is matched per page. 100k driver rows + 5 × 60k
35046        // matched; seeks 5 × page (the partial last page still prices a
35047        // full page of seeks). The fetch-once predicate does NOT fire
35048        // here — the driver sketch is missing, and a worst-case price is
35049        // not evidence (the same rule that keeps the coverage gate shut
35050        // on missing sketches).
35051        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
35052        assert_eq!((seat.rows, seat.seeks), (400_000, 5 * page));
35053    }
35054
35055    /// The explosion guard: a keyless (cartesian) candidate whose FETCH
35056    /// cost is tiny (read both sides once: 700k rows) but whose PRODUCT
35057    /// is enormous (200k × 500k = 1e11 output rows) must NOT win the
35058    /// flag-on pick — the seating-cost model cannot see intermediate size, so
35059    /// eligibility disqualifies it before the ranking. The keyed rival
35060    /// reads 2.42M rows, so without the guard the cost ranking would
35061    /// attach the cartesian.
35062    #[test]
35063    fn assoc_explosion_guard_blocks_read_cheap_product_huge_cartesian() {
35064        let mut profile = StatsProfile::default();
35065        profile
35066            .predicate_counts
35067            .insert(StrHash::new("http://ex/pS"), 200_000);
35068        profile
35069            .predicate_counts
35070            .insert(StrHash::new("http://ex/pK"), 1_000_000);
35071        profile
35072            .predicate_counts
35073            .insert(StrHash::new("http://ex/pQ"), 500_000);
35074        profile
35075            .subjects_per_predicate
35076            .insert(StrHash::new("http://ex/pS"), hll_with_n(200_000));
35077        profile
35078            .subjects_per_predicate
35079            .insert(StrHash::new("http://ex/pK"), hll_with_n(100_000));
35080        profile
35081            .subjects_per_predicate
35082            .insert(StrHash::new("http://ex/pQ"), hll_with_n(400_000));
35083        profile.total_puts = 1_700_000;
35084        let seed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pS", Some("t"), 200_000));
35085        let keyed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pK", Some("u"), 1_000_000));
35086        let cart = PlanNode::Scan(var_scan(Some("q"), "http://ex/pQ", Some("r"), 500_000));
35087
35088        let price = |cand: &PlanNode| {
35089            let keys = hash_keys_for(&seed.output_vars(), &cand.output_vars());
35090            (
35091                finalize_inner_join_meta(&seed, cand, &keys, Some(&profile)).1,
35092                seat_cost_total(Some(&profile), &seed, cand, &keys, None, None),
35093            )
35094        };
35095        let (produced_k, seat_k) = price(&keyed);
35096        let (produced_cart, seat_cart) = price(&cart);
35097        // Fetch work alone prefers the cartesian — the trap the guard
35098        // exists for.
35099        assert_eq!((seat_cart.rows, seat_cart.seeks), (700_000, 0));
35100        // Keyed seat: the priced fetch-once trigger fires (nine pages ×
35101        // (24,576 seeks × 3.6 + 245,760 matched rows) ≈ 3.0B row-equiv ≥
35102        // 1.5 × the 1M probe), so the cost model prices the BUILD the runtime
35103        // stamps — the 1M probe read once, past the line (no risk extra).
35104        // The cartesian is still row-cheaper; only the eligibility guard
35105        // keeps it out.
35106        assert_eq!((seat_k.rows, seat_k.seeks), (1_200_000, 0));
35107        assert!(seat_cart.rows < seat_k.rows);
35108        // The product is what eligibility sees: 1e11 > 4 × 1M.
35109        assert_eq!(produced_k, 1_000_000);
35110        assert_eq!(produced_cart, 100_000_000_000);
35111
35112        let p_k = Some(EncodedTerm::from(&NamedNode::new("http://ex/pK").unwrap()));
35113        let first_attached = |tree: &PlanNode| -> Option<EncodedTerm> {
35114            let mut node = tree;
35115            while let PlanNode::Join { left, right, .. } = node {
35116                if !matches!(**left, PlanNode::Join { .. }) {
35117                    let PlanNode::Scan(scan) = right.as_ref() else {
35118                        panic!("expected a scan probe, got {right:?}")
35119                    };
35120                    return scan.pattern.predicate.clone();
35121                }
35122                node = left;
35123            }
35124            panic!("expected a join spine, got {tree:?}");
35125        };
35126        let associate = |seat_ctx: Option<QueryContext>| {
35127            let mut tree = join_nodes(
35128                join_nodes(seed.clone(), keyed.clone(), Some(&profile)),
35129                cart.clone(),
35130                Some(&profile),
35131            );
35132            reassociate_inner_joins(&mut tree, Some(&profile), seat_ctx.as_ref());
35133            tree
35134        };
35135
35136        // With the flag on and off, the keyed candidate attaches: the guard held
35137        // the cartesian out of the ranking while the output scale keeps
35138        // agreeing — the direct price assertions above are what prove the
35139        // guard (not the output scale) made the cost-ranked decision.
35140        assert_eq!(
35141            first_attached(&associate(Some(
35142                QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true)
35143            ))),
35144            p_k
35145        );
35146        assert_eq!(first_attached(&associate(None)), p_k);
35147    }
35148
35149    /// The guard does not ban cartesians — only explosions. A keyless
35150    /// candidate whose product clears the bar (200k × 5 = 1M, tying the
35151    /// keyed rival's 1M) is eligible and wins the flag-on ranking on its
35152    /// honest fetch price (read both sides: 200,005 rows vs the keyed
35153    /// rival's 2.42M). With the flag off, the earliest tag-sorted candidate
35154    /// on the produced tie (the keyed arm), so this is also an
35155    /// association flip.
35156    #[test]
35157    fn assoc_guard_admits_small_product_cartesian() {
35158        let mut profile = StatsProfile::default();
35159        profile
35160            .predicate_counts
35161            .insert(StrHash::new("http://ex/pS"), 200_000);
35162        profile
35163            .predicate_counts
35164            .insert(StrHash::new("http://ex/pK"), 1_000_000);
35165        profile
35166            .predicate_counts
35167            .insert(StrHash::new("http://ex/pQ2"), 5);
35168        profile
35169            .predicate_counts
35170            .insert(StrHash::new("http://ex/pQ2b"), 100);
35171        profile
35172            .subjects_per_predicate
35173            .insert(StrHash::new("http://ex/pS"), hll_with_n(200_000));
35174        profile
35175            .subjects_per_predicate
35176            .insert(StrHash::new("http://ex/pK"), hll_with_n(100_000));
35177        profile
35178            .subjects_per_predicate
35179            .insert(StrHash::new("http://ex/pQ2"), hll_with_n(5));
35180        profile
35181            .subjects_per_predicate
35182            .insert(StrHash::new("http://ex/pQ2b"), hll_with_n(100));
35183        profile.total_puts = 1_200_105;
35184        let seed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pS", Some("t"), 200_000));
35185        let keyed = PlanNode::Scan(var_scan(Some("s"), "http://ex/pK", Some("u"), 1_000_000));
35186        let cart_small = PlanNode::Scan(var_scan(Some("q2"), "http://ex/pQ2", Some("r2"), 5));
35187        let cart_huge = PlanNode::Scan(var_scan(Some("q3"), "http://ex/pQ2b", Some("r3"), 100));
35188
35189        // The prices the ranking sees from the seed accumulator.
35190        let price = |cand: &PlanNode| {
35191            let keys = hash_keys_for(&seed.output_vars(), &cand.output_vars());
35192            (
35193                finalize_inner_join_meta(&seed, cand, &keys, Some(&profile)).1,
35194                seat_cost_total(Some(&profile), &seed, cand, &keys, None, None),
35195            )
35196        };
35197        let (produced_k, seat_k) = price(&keyed);
35198        let (produced_cart, seat_cart) = price(&cart_small);
35199        let (produced_huge, seat_huge) = price(&cart_huge);
35200        assert_eq!(produced_k, 1_000_000);
35201        assert_eq!(produced_cart, 1_000_000);
35202        assert_eq!((seat_cart.rows, seat_cart.seeks), (200_005, 0));
35203        assert_eq!((seat_k.rows, seat_k.seeks), (1_200_000, 0));
35204        // The blocked fixture's cartesian is the cheaper read but produces four
35205        // times what the gap admits (4 × the keyed candidate's 1M).
35206        assert_eq!(produced_huge, 20_000_000);
35207        assert_eq!((seat_huge.rows, seat_huge.seeks), (200_100, 0));
35208
35209        let seat_ctx =
35210            QueryContext::from_snapshot(SnapshotId::latest()).with_seat_by_total_cost(true);
35211        // `associate_from_seed` establishes this order once before the loop; a
35212        // produced tie keeps the earliest entry, so the order is an input.
35213        let canonical = |mut candidates: Vec<JoinableSpineNode>| {
35214            candidates.sort_by(|a, b| {
35215                crate::explain::plan_node_tag(a.as_plan())
35216                    .cmp(&crate::explain::plan_node_tag(b.as_plan()))
35217            });
35218            candidates
35219        };
35220        let candidates = |a: &PlanNode, b: &PlanNode| {
35221            canonical(vec![
35222                JoinableSpineNode::Bare(a.clone()),
35223                JoinableSpineNode::Bare(b.clone()),
35224            ])
35225        };
35226        let picked = |candidates: &[JoinableSpineNode], idx: usize| {
35227            crate::explain::plan_node_tag(candidates[idx].as_plan())
35228        };
35229        let cart_tag = crate::explain::plan_node_tag(&cart_small);
35230        let keyed_tag = crate::explain::plan_node_tag(&keyed);
35231
35232        // Admission, total-cost mode: both candidates produce 1M, so the 4× guard
35233        // admits the cartesian, and the cost model picks its cheaper read.
35234        let admitted = candidates(&keyed, &cart_small);
35235        let (idx, _, _) = pick_attachment(&seed, &admitted, Some(&profile), Some(&seat_ctx), true);
35236        assert_eq!(picked(&admitted, idx), cart_tag);
35237
35238        // Admission, non-total-cost mode: the guard never participates; the pick is the
35239        // smallest produced, and the produced tie keeps the canonical first.
35240        let (idx, _, _) = pick_attachment(&seed, &admitted, Some(&profile), None, false);
35241        assert_eq!(picked(&admitted, idx), cart_tag);
35242
35243        // Blocked, total-cost mode only: the huge cartesian reads less (200,100) but
35244        // produces 20M, above the 4M guard, so it is skipped and the keyed
35245        // candidate is picked. Without the guard the cost model would take the
35246        // cartesian.
35247        let blocked = candidates(&keyed, &cart_huge);
35248        let (idx, produced, _) =
35249            pick_attachment(&seed, &blocked, Some(&profile), Some(&seat_ctx), true);
35250        assert_eq!(picked(&blocked, idx), keyed_tag);
35251        assert_eq!(produced, produced_k);
35252    }
35253
35254    /// The scan memo key must carry the pattern's graph slot: a
35255    /// default-graph scan and a `GRAPH <g>` scan of the same S/P/O must
35256    /// never collide (the graph arm would hit the default arm's cached
35257    /// quads), and neither must two different named graphs. `None`
35258    /// (unconstrained G) is a third, distinct identity.
35259    #[test]
35260    fn scan_memo_key_distinguishes_graph_identity() {
35261        use crate::query::caches::ScanMemoKey;
35262        let default_scan = var_scan(Some("s"), "http://ex/p", Some("o"), 100);
35263        let named = |iri: &str| {
35264            let mut scan = var_scan(Some("s"), "http://ex/p", Some("o"), 100);
35265            scan.pattern.graph_name = Some(EncodedTerm::from(&NamedNode::new(iri).unwrap()));
35266            scan
35267        };
35268        let g1 = named("http://ex/g1");
35269        let g2 = named("http://ex/g2");
35270        assert_ne!(
35271            ScanMemoKey::of(&default_scan, 7),
35272            ScanMemoKey::of(&g1, 7),
35273            "default-graph and GRAPH <g1> scans must not share a memo entry"
35274        );
35275        assert_ne!(
35276            ScanMemoKey::of(&g1, 7),
35277            ScanMemoKey::of(&g2, 7),
35278            "two named graphs must not share a memo entry"
35279        );
35280        assert_ne!(
35281            ScanMemoKey::of(&default_scan, 7),
35282            ScanMemoKey::of(&default_scan, 8),
35283            "snapshot is part of the identity"
35284        );
35285        assert_eq!(
35286            ScanMemoKey::of(&g1, 7),
35287            ScanMemoKey::of(&g1, 7),
35288            "same identity (graph included) is stable"
35289        );
35290    }
35291
35292    /// The key must also separate scans by REPEAT STRUCTURE and live
35293    /// schema: `?a :p ?a` (repeated-variable row filter in `from_scan`)
35294    /// and `?a :p ?dead` (dead second slot, no filter) share pattern
35295    /// shape and live list, but a solutions entry bakes the publisher's
35296    /// row filter in — they must never share an entry (round-3 B1).
35297    #[test]
35298    fn scan_memo_key_distinguishes_repeat_structure() {
35299        use crate::query::caches::ScanMemoKey;
35300        let repeat = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35301        let mut dead = var_scan(Some("a"), "http://ex/p", Some("dead"), 100);
35302        // Mark the dead slot dead the way materialization planning does.
35303        dead.marks.push((
35304            Variable::new("dead").unwrap(),
35305            Liveness::Dead,
35306            BagMark::Sensitive,
35307        ));
35308
35309        // Same live list (materialized_variables dedups by name and drops
35310        // the dead slot), different repeat structure:
35311        assert_eq!(
35312            repeat.materialized_variables(),
35313            dead.materialized_variables()
35314        );
35315        assert_eq!(repeat.repeat_slot_pairs(), vec![(0, 2)]);
35316        assert!(dead.repeat_slot_pairs().is_empty());
35317        assert_ne!(
35318            ScanMemoKey::of(&repeat, 7),
35319            ScanMemoKey::of(&dead, 7),
35320            "a repeat-filtered scan and a same-shaped unfiltered scan must not share a memo entry"
35321        );
35322    }
35323
35324    /// The single output-slot derivation (`ScanOp::output_slots`) must agree
35325    /// across all of its consumers: `materialized_variables` (page schema,
35326    /// memo-key live list), `repeat_slot_pairs` (memo-key repeat identity),
35327    /// and `EncodedSolutions::from_scan` (schema, column mapping,
35328    /// repeated-variable row filter). The four shapes below each pin a
35329    /// different edge of that agreement: a subject/object repeat through a
35330    /// bound predicate, a repeat through a variable predicate (the
35331    /// predicate column must still materialize), a graph repeat (G joins
35332    /// the same-name walk as slot 3), and a repeat whose name is dropped
35333    /// (the filter survives; the column does not).
35334    #[test]
35335    fn scan_output_slots_single_derivation_agreement() {
35336        // ?a :p ?a — subject/object repeat, predicate a bound constant.
35337        let so = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35338        assert_eq!(so.repeat_slot_pairs(), vec![(0, 2)]);
35339        assert_eq!(
35340            so.materialized_variables(),
35341            vec![Variable::new("a").unwrap()]
35342        );
35343
35344        // ?a ?p ?a — repeat through a variable predicate: both the repeat
35345        // pair and the predicate column must materialize, and the views
35346        // must equal the derivation they are built on.
35347        let mut sp_o = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35348        sp_o.predicate = Some(Variable::new("p").unwrap());
35349        let out = sp_o.output_slots();
35350        assert_eq!(
35351            out.slots,
35352            [
35353                Some(Variable::new("a").unwrap()),
35354                Some(Variable::new("p").unwrap()),
35355                Some(Variable::new("a").unwrap()),
35356                None
35357            ]
35358        );
35359        assert_eq!(out.repeats, vec![(0, 2)]);
35360        assert_eq!(
35361            out.materialized,
35362            vec![
35363                (0, Variable::new("a").unwrap()),
35364                (1, Variable::new("p").unwrap())
35365            ]
35366        );
35367        assert_eq!(
35368            sp_o.materialized_variables(),
35369            out.materialized
35370                .iter()
35371                .map(|(_, v)| v.clone())
35372                .collect::<Vec<_>>()
35373        );
35374        assert_eq!(sp_o.repeat_slot_pairs(), out.repeats);
35375
35376        // Graph repeat: ?a :p ?x with GRAPH ?a — G is slot 3 in the same
35377        // walk, so the pair is (0, 3) and only the first occurrence
35378        // materializes.
35379        let mut graph_repeat = var_scan(Some("a"), "http://ex/p", None, 100);
35380        graph_repeat.graph = Some(Variable::new("a").unwrap());
35381        let out = graph_repeat.output_slots();
35382        assert_eq!(out.repeats, vec![(0, 3)]);
35383        assert_eq!(out.materialized, vec![(0, Variable::new("a").unwrap())]);
35384
35385        // Dropped repeat: the name is Dead, so no column materializes, but
35386        // the repeat pair survives — the row filter still compares the two
35387        // slots, and the memo key bakes that filter into cached entries.
35388        let mut dead_repeat = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35389        dead_repeat.marks.push((
35390            Variable::new("a").unwrap(),
35391            Liveness::Dead,
35392            BagMark::Sensitive,
35393        ));
35394        let out = dead_repeat.output_slots();
35395        assert_eq!(out.repeats, vec![(0, 2)]);
35396        assert!(out.materialized.is_empty());
35397        assert!(dead_repeat.materialized_variables().is_empty());
35398
35399        // from_scan agreement: schema equals materialized_variables, and the
35400        // repeated-variable row filter is the one the derivation reports —
35401        // the disagreeing row is dropped, the agreeing row carries each
35402        // column from its derived slot.
35403        let dict = waratah_exec::TermDict::new_shared();
35404        let term =
35405            |local: &str| EncodedTerm::from(&NamedNode::new(format!("http://ex/{local}")).unwrap());
35406        let quad = |object: EncodedTerm| {
35407            waratah_storage::EncodedQuad::new(
35408                term("a"),
35409                term("p"),
35410                object,
35411                EncodedTerm::DefaultGraph,
35412            )
35413        };
35414        let solutions = crate::solutions::EncodedSolutions::from_scan(
35415            Arc::clone(&dict),
35416            &sp_o,
35417            vec![quad(term("a")), quad(term("b"))],
35418        )
35419        .unwrap();
35420        assert_eq!(solutions.variables(), sp_o.materialized_variables());
35421        assert_eq!(solutions.len(), 1);
35422        assert_eq!(
35423            solutions.get(0, &Variable::new("a").unwrap()).unwrap(),
35424            Some(term("a"))
35425        );
35426        assert_eq!(
35427            solutions.get(0, &Variable::new("p").unwrap()).unwrap(),
35428            Some(term("p"))
35429        );
35430
35431        // The dropped repeat keeps only the rows whose slots agree, with a
35432        // zero-width schema (no columns materialize).
35433        let dead_solutions = crate::solutions::EncodedSolutions::from_scan(
35434            dict,
35435            &dead_repeat,
35436            vec![quad(term("a")), quad(term("b"))],
35437        )
35438        .unwrap();
35439        assert!(dead_solutions.variables().is_empty());
35440        assert_eq!(dead_solutions.len(), 1);
35441    }
35442
35443    /// `ScanOp::omitted_slots` is the *producer* of the wire mask — the one
35444    /// load-bearing scan decision nothing else pins (the partition tests
35445    /// exercise the decoder side with hand-built masks, so a regression
35446    /// here would surface only as a silently wrong cursor key). Table over
35447    /// the full rule set: a bound slot omits at either `allow_dead`; a dead
35448    /// slot omits only under `allow_dead`; a repeated name never omits even
35449    /// when dead (the row filter still compares both slots); a slot with no
35450    /// variable and no bound term is dead by definition. The unnamed-graph
35451    /// slot therefore omits under `allow_dead` in every case where the scan
35452    /// does not bind it.
35453    #[test]
35454    fn scan_omitted_slots_producer_table() {
35455        let bound_p = || Some(EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()));
35456        let eff = |subject: Option<EncodedTerm>,
35457                   predicate: Option<EncodedTerm>,
35458                   object: Option<EncodedTerm>,
35459                   graph_name: Option<EncodedTerm>| EncodedTriplePattern {
35460            subject,
35461            predicate,
35462            object,
35463            graph_name,
35464        };
35465        let live = var_scan(Some("a"), "http://ex/p", Some("b"), 100);
35466        let mut dead = var_scan(Some("a"), "http://ex/p", Some("b"), 100);
35467        dead.marks.push((
35468            Variable::new("b").unwrap(),
35469            Liveness::Dead,
35470            BagMark::Sensitive,
35471        ));
35472        let mut dead_repeat = var_scan(Some("a"), "http://ex/p", Some("a"), 100);
35473        dead_repeat.marks.push((
35474            Variable::new("a").unwrap(),
35475            Liveness::Dead,
35476            BagMark::Sensitive,
35477        ));
35478        // Broadcast pin: the plan still names the slot, the request carries
35479        // the pinned term.
35480        let mut pinned = live.clone();
35481        pinned.pattern.subject = Some(EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()));
35482        let free_scan = var_scan(None, "http://ex/p", None, 100);
35483
35484        let cases: &[(&str, &ScanOp, EncodedTriplePattern, u8, u8)] = &[
35485            // (label, scan, effective pattern, mask @ allow_dead=false, mask @ true)
35486            (
35487                "bound predicate only",
35488                &live,
35489                eff(None, bound_p(), None, None),
35490                OMIT_PREDICATE,
35491                OMIT_PREDICATE | OMIT_GRAPH,
35492            ),
35493            (
35494                "broadcast-pinned subject omits like any bound slot",
35495                &pinned,
35496                eff(pinned.pattern.subject.clone(), bound_p(), None, None),
35497                OMIT_SUBJECT | OMIT_PREDICATE,
35498                OMIT_SUBJECT | OMIT_PREDICATE | OMIT_GRAPH,
35499            ),
35500            (
35501                "dead object omits only under allow_dead",
35502                &dead,
35503                eff(None, bound_p(), None, None),
35504                OMIT_PREDICATE,
35505                OMIT_PREDICATE | OMIT_OBJECT | OMIT_GRAPH,
35506            ),
35507            (
35508                "dead repeated name never omits (row filter compares both)",
35509                &dead_repeat,
35510                eff(None, bound_p(), None, None),
35511                OMIT_PREDICATE,
35512                OMIT_PREDICATE | OMIT_GRAPH,
35513            ),
35514            (
35515                "bound graph omits at either flag",
35516                &live,
35517                eff(None, bound_p(), None, Some(EncodedTerm::DefaultGraph)),
35518                OMIT_PREDICATE | OMIT_GRAPH,
35519                OMIT_PREDICATE | OMIT_GRAPH,
35520            ),
35521            (
35522                "free pattern on named live slots: only nameless slots omit",
35523                &live,
35524                eff(None, None, None, None),
35525                0,
35526                OMIT_PREDICATE | OMIT_GRAPH,
35527            ),
35528            (
35529                "fully free scan: every slot is dead by definition",
35530                &free_scan,
35531                eff(None, None, None, None),
35532                0,
35533                OMIT_SUBJECT | OMIT_PREDICATE | OMIT_OBJECT | OMIT_GRAPH,
35534            ),
35535        ];
35536        for (label, scan, effective, expect_strict, expect_allow) in cases {
35537            assert_eq!(
35538                scan.omitted_slots(effective, false),
35539                *expect_strict,
35540                "{label}: allow_dead=false"
35541            );
35542            assert_eq!(
35543                scan.omitted_slots(effective, true),
35544                *expect_allow,
35545                "{label}: allow_dead=true"
35546            );
35547        }
35548    }
35549
35550    // ------------------------------------------------------------------
35551    // Item 7 leaf-walk: the kept-key subtree-probe price, plus the
35552    // planner-time regression gate (Layers 1–2 here in the battery;
35553    // Layer 3 is the `#[ignore]`d release harness at the end).
35554    // ------------------------------------------------------------------
35555
35556    /// The MAJOR-2 counterexample as a PRICE: the subtree's output
35557    /// collapses (24k produced) while its driver's keyed return stays
35558    /// page-wide (8M rows / 8M domain = one row per key). The leaf-walk
35559    /// must price the subtree's per-page execution with the driver
35560    /// re-geometried to the keyed answer (~pushed_val_count, not 8M), and the
35561    /// recursion's result must replace the broadcast matched-scaling at
35562    /// the parent (no double-counting).
35563    #[test]
35564    fn leaf_walk_prices_kept_key_subtree_per_page() {
35565        let mut profile = StatsProfile::default();
35566        // A1 joins D1 on ?g (NOT ?s): its tiny ?g domain keeps the inner
35567        // join's road unambiguous, while its missing ?s lets the subtree's
35568        // probe-side ?s domain stay at D1's 8M — J0's page list cannot
35569        // cover that, so the kept-key road is unambiguous too. A1's whole
35570        // read comes from the profile's HLLs (the estimator's basis), not
35571        // the row argument.
35572        for (pred, rows, subjects) in [
35573            ("http://ex/p0", 100_000_u64, 100_000_u128),
35574            ("http://ex/p1", 8_000_000, 8_000_000),
35575            ("http://ex/p2", 300, 1_000),
35576        ] {
35577            profile.predicate_counts.insert(StrHash::new(pred), rows);
35578            profile
35579                .subjects_per_predicate
35580                .insert(StrHash::new(pred), hll_with_n(subjects));
35581            profile
35582                .objects_per_predicate
35583                .insert(StrHash::new(pred), hll_with_n(subjects));
35584        }
35585        profile.total_puts = 8_100_300;
35586        // The subtree: D1 (?s p1 ?g, 8M rows) drives a keyed join on ?g
35587        // whose probe A1 (?g p2 ?z) collapses the output to 24k. D1 hosts
35588        // the pushed key ?s — the MAJOR-2 gate.
35589        let subtree = PlanNode::Join {
35590            left: Box::new(PlanNode::Scan(var_scan(
35591                Some("s"),
35592                "http://ex/p1",
35593                None,
35594                8_000_000,
35595            ))),
35596            right: Box::new(PlanNode::Scan(var_scan(
35597                Some("g"),
35598                "http://ex/p2",
35599                Some("z"),
35600                300,
35601            ))),
35602            hash_keys: vec![var("g")],
35603            probe_key_domains: Vec::new(),
35604            probe_key_overlap_milli: Vec::new(),
35605            rhs_hostable_keys: Vec::new().into(),
35606            meta: JoinMeta {
35607                semi_gate: None,
35608                star_arms: None,
35609                strategy: JoinStrategy::Broadcast,
35610                produced_row_count_estimate: 24_000,
35611                own_push_removed_row_count_estimate: 24_000,
35612            },
35613        };
35614        let a1 = PlanNode::Scan(var_scan(Some("g"), "http://ex/p2", Some("z"), 300));
35615        let d1 = PlanNode::Scan(var_scan(Some("s"), "http://ex/p1", None, 8_000_000));
35616        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p0", Some("o"), 100_000));
35617        let keys = hash_keys_for(&driver.output_vars(), &subtree.output_vars());
35618
35619        super::SEAT_CALLS.with(|c| c.set(0));
35620        super::WALK_VISITS.with(|c| c.set(0));
35621        let seat = seat_cost_total(Some(&profile), &driver, &subtree, &keys, None, None);
35622        let seat_calls = super::SEAT_CALLS.with(|c| c.get());
35623        let walk_visits = super::WALK_VISITS.with(|c| c.get());
35624
35625        // Derive the same numbers the walk produces (the fixture
35626        // self-normalizes against the HLL cardinalities, the established
35627        // pattern): the establishing push is ?s at pushed_val_count =
35628        // min(driver domain, page rows); the contained driver prices
35629        // pushed_val_count × (8M / its ?g domain) instead of 8M — the MAJOR-2
35630        // bound; A1 answers from the coverage road (a page list covers its
35631        // tiny ?g domain) at driver + whole-read + the memo-refusal extra.
35632        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
35633        let dom_s0 = profile
35634            .subjects_per_predicate
35635            .get(&StrHash::new("http://ex/p0"))
35636            .expect("p0 subjects HLL")
35637            .cardinality();
35638        // The establishing list size and the contained driver's bound both
35639        // come from the SHARED derivations (`pushed_val_count`,
35640        // `containing_push_driver_bound`) — the fixture composes them; it
35641        // does not re-implement the arithmetic (the per-key-ceil this used
35642        // to mimic was replaced by the core's single total-ceil).
35643        let pushed_val_count = pushed_val_count(Some(&profile), &driver, &var("s")).min(page);
35644        assert_eq!(pushed_val_count, dom_s0.min(page));
35645        let inner_driver =
35646            containing_push_driver_bound(Some(&profile), &d1, &var("s"), pushed_val_count)
35647                .expect("D1's ?s domain is known");
35648        let a1_whole = estimate_unclamped_scan_rows(
35649            Some(&profile),
35650            match &a1 {
35651                PlanNode::Scan(scan) => scan,
35652                _ => unreachable!("a1 is a scan"),
35653            },
35654        );
35655        let a1_domain = profile
35656            .subjects_per_predicate
35657            .get(&StrHash::new("http://ex/p2"))
35658            .expect("p2 subjects HLL")
35659            .cardinality();
35660        let a1_scan = match &a1 {
35661            PlanNode::Scan(scan) => scan,
35662            _ => unreachable!("a1 is a scan"),
35663        };
35664        // The gather's own epistemics, mirrored through the SAME helpers
35665        // the shape calls: the driver key domain comes from
35666        // `join_key_domain_for_node` (an object-slot key has no domain
35667        // sketch here), an unknown domain never covers, and the build
35668        // verdict refuses on it — a missing sketch is not evidence.
35669        let inner_driver_domain = join_key_domain_for_node(Some(&profile), &d1, &var("g"));
35670        let (cover_len, inner_list, domains_known) = match inner_driver_domain {
35671            Some(d) => {
35672                let clustered = clustered_page_distinct(inner_driver, d, page);
35673                (clustered, clustered, true)
35674            }
35675            None => (1, page.min(inner_driver.max(1)), false),
35676        };
35677        let covered = crate::query::pushdown::push_list_covers_domain(
35678            usize::try_from(cover_len).unwrap_or(usize::MAX),
35679            a1_domain,
35680            1_000,
35681        );
35682        let drop = crate::query::pushdown::source_coverage_drop(&d1, &a1, page);
35683        // The inner seat, priced by the SAME arithmetic the walk calls —
35684        // deriving only the gather inputs. Re-deriving the road logic by
35685        // hand would just duplicate the code under test.
35686        let inner = seat_cost_arithmetic(
35687            inner_driver,
35688            a1_whole,
35689            crate::query::scan_memo_eligible(a1_scan)
35690                && a1_whole <= crate::query::caches::SCAN_MEMO_MAX_ENTRY_ROWS as u64,
35691            inner_driver.div_ceil(page),
35692            &[(covered, inner_list, a1_domain, 1_000)],
35693            drop,
35694            fetch_once_stampable(a1_scan),
35695            whole_read_rows_known(Some(&profile), a1_scan),
35696            domains_known,
35697            false,
35698            None,
35699        );
35700        let inner_rows = inner.rows;
35701        let inner_seeks = inner.seeks;
35702        let j0_pages = 100_000u64.div_ceil(page);
35703        assert_eq!(
35704            seat,
35705            SeatCost {
35706                rows: 100_000 + j0_pages * inner_rows,
35707                seeks: j0_pages * inner_seeks,
35708            },
35709            "the subtree must price per-page with the driver keyed to ~{pushed_val_count}, not 8M"
35710        );
35711        // The gate's teeth: exactly the top seat + the subtree's one join
35712        // priced; the walk entered exactly once (S1's Join arm).
35713        assert_eq!(seat_calls, 2, "top seat + one inner seat");
35714        assert_eq!(walk_visits, 1, "one Join arm walked");
35715    }
35716
35717    /// Layer 1: the leaf-walk's comparator work is LINEAR in the subtree's
35718    /// join count — one seat per join, one walk visit per Join arm — never
35719    /// per-candidate-per-level (O(k²)). A bare-scan probe prices with
35720    /// exactly one seat call and zero walk visits (no recursion). The
35721    /// absolute bounds here are the planner-time gate: a change that
35722    /// exceeds them must be a deliberate, reviewed trade.
35723    #[test]
35724    fn leaf_walk_recursion_is_linear_in_subtree_joins() {
35725        let mut profile = StatsProfile::default();
35726        profile
35727            .predicate_counts
35728            .insert(StrHash::new("http://ex/chain"), 50_000);
35729        profile
35730            .subjects_per_predicate
35731            .insert(StrHash::new("http://ex/chain"), hll_with_n(50_000));
35732        profile
35733            .objects_per_predicate
35734            .insert(StrHash::new("http://ex/chain"), hll_with_n(50_000));
35735        profile.total_puts = 50_000;
35736        const SEGMENTS: usize = 24;
35737        // Right-spine keyed chain: scan_i(?s{i-1} chain ?s{i}) joins the
35738        // rest on ?s{i}. Every key's domain (50k) exceeds a page list
35739        // (~24k), so no coverage road fires and the walk engages at every
35740        // level.
35741        let mut node = PlanNode::Scan(var_scan(
35742            Some(&format!("s{}", SEGMENTS - 1)),
35743            "http://ex/chain",
35744            Some(&format!("s{SEGMENTS}")),
35745            50_000,
35746        ));
35747        for i in (1..SEGMENTS).rev() {
35748            node = PlanNode::Join {
35749                left: Box::new(PlanNode::Scan(var_scan(
35750                    Some(&format!("s{}", i - 1)),
35751                    "http://ex/chain",
35752                    Some(&format!("s{i}")),
35753                    50_000,
35754                ))),
35755                right: Box::new(node),
35756                hash_keys: vec![var(&format!("s{i}"))],
35757                probe_key_domains: Vec::new(),
35758                probe_key_overlap_milli: Vec::new(),
35759                rhs_hostable_keys: Vec::new().into(),
35760                meta: JoinMeta {
35761                    semi_gate: None,
35762                    star_arms: None,
35763                    strategy: JoinStrategy::Broadcast,
35764                    produced_row_count_estimate: 50_000,
35765                    own_push_removed_row_count_estimate: 50_000,
35766                },
35767            };
35768        }
35769        let driver = PlanNode::Scan(var_scan(
35770            Some("s0"),
35771            "http://ex/chain",
35772            Some("head"),
35773            50_000,
35774        ));
35775        let keys = hash_keys_for(&driver.output_vars(), &node.output_vars());
35776        super::SEAT_CALLS.with(|c| c.set(0));
35777        super::WALK_VISITS.with(|c| c.set(0));
35778        let seat = seat_cost_total(Some(&profile), &driver, &node, &keys, None, None);
35779        let seat_calls = super::SEAT_CALLS.with(|c| c.get());
35780        let walk_visits = super::WALK_VISITS.with(|c| c.get());
35781        assert!(seat.rows > 0);
35782        assert!(
35783            (SEGMENTS as u64..=2 * SEGMENTS as u64).contains(&seat_calls),
35784            "one seat per join ({SEGMENTS}), ±headroom — got {seat_calls}"
35785        );
35786        assert!(
35787            ((SEGMENTS - 1) as u64..=2 * SEGMENTS as u64).contains(&walk_visits),
35788            "one walk visit per Join arm, ±headroom — got {walk_visits}"
35789        );
35790
35791        // Control: a bare-scan probe never enters the walk.
35792        let plain = PlanNode::Scan(var_scan(Some("s0"), "http://ex/chain", Some("x"), 50_000));
35793        let plain_keys = hash_keys_for(&driver.output_vars(), &plain.output_vars());
35794        super::SEAT_CALLS.with(|c| c.set(0));
35795        super::WALK_VISITS.with(|c| c.set(0));
35796        let _ = seat_cost_total(Some(&profile), &driver, &plain, &plain_keys, None, None);
35797        assert_eq!(super::SEAT_CALLS.with(|c| c.get()), 1, "no recursion");
35798        assert_eq!(super::WALK_VISITS.with(|c| c.get()), 0, "no walk");
35799    }
35800
35801    /// Layer 2: the walk's per-entry node budget degrades a WIDE subtree
35802    /// to the coarse produced-estimate price after
35803    /// `SUBTREE_WALK_NODE_BUDGET` visits — bounded work, never a planning
35804    /// stall, and a degraded walk still prices the arm (never zero).
35805    #[test]
35806    fn leaf_walk_budget_degrades_wide_subtrees_to_the_coarse_price() {
35807        let mut profile = StatsProfile::default();
35808        profile
35809            .predicate_counts
35810            .insert(StrHash::new("http://ex/u"), 100_000);
35811        profile
35812            .subjects_per_predicate
35813            .insert(StrHash::new("http://ex/u"), hll_with_n(100_000));
35814        profile
35815            .objects_per_predicate
35816            .insert(StrHash::new("http://ex/u"), hll_with_n(50_000));
35817        profile.total_puts = 100_000;
35818        // 80-arm union spine: ~161 nodes, no joins inside (so exactly ONE
35819        // walk entry — the per-entry budget is the whole story here).
35820        let mut node = PlanNode::Scan(var_scan(None, "http://ex/u", Some("g"), 1_000));
35821        for _ in 0..80 {
35822            node = PlanNode::Union {
35823                left: Box::new(PlanNode::Scan(var_scan(
35824                    None,
35825                    "http://ex/u",
35826                    Some("g"),
35827                    1_000,
35828                ))),
35829                right: Box::new(node),
35830            };
35831        }
35832        let driver = PlanNode::Scan(var_scan(None, "http://ex/u", Some("g"), 100_000));
35833        let keys = hash_keys_for(&driver.output_vars(), &node.output_vars());
35834        super::SEAT_CALLS.with(|c| c.set(0));
35835        super::WALK_VISITS.with(|c| c.set(0));
35836        let seat = seat_cost_total(Some(&profile), &driver, &node, &keys, None, None);
35837        assert_eq!(
35838            super::WALK_VISITS.with(|c| c.get()),
35839            SUBTREE_WALK_NODE_BUDGET,
35840            "the budget const is the exact visit count — raising it is a deliberate trade"
35841        );
35842        assert_eq!(
35843            super::SEAT_CALLS.with(|c| c.get()),
35844            1,
35845            "no joins, no nested seats"
35846        );
35847        assert!(seat.rows > 0, "a degraded walk still prices the arm");
35848    }
35849
35850    /// The once-roads never walk: an all-covered subtree probe (the drop
35851    /// guard grants non-scan arms) and a keys-empty join both execute the
35852    /// subtree exactly ONCE, priced at its produced clamp — one seat call,
35853    /// zero walk visits, byte-identical to the pre-leaf-walk price.
35854    #[test]
35855    fn leaf_walk_once_roads_do_not_walk() {
35856        let mut profile = StatsProfile::default();
35857        // The subtree's ?s domain (8 keys, both arms) must sit far under
35858        // the driver page's cover length — the occupancy curve over the
35859        // driver's 300-key domain — so the page list COVERS it and the
35860        // once-road is unambiguous. A1 carries its own predicate: scan
35861        // estimates read the profile's predicate counts, not the fixture
35862        // row argument.
35863        for (pred, rows, subjects) in [
35864            ("http://ex/p0", 100_000_u64, 300_u128),
35865            ("http://ex/p1", 5_000, 8),
35866            ("http://ex/p2", 1_000, 8),
35867        ] {
35868            profile.predicate_counts.insert(StrHash::new(pred), rows);
35869            profile
35870                .subjects_per_predicate
35871                .insert(StrHash::new(pred), hll_with_n(subjects));
35872            profile
35873                .objects_per_predicate
35874                .insert(StrHash::new(pred), hll_with_n(subjects));
35875        }
35876        profile.total_puts = 106_000;
35877        let subtree = PlanNode::Join {
35878            left: Box::new(PlanNode::Scan(var_scan(
35879                Some("s"),
35880                "http://ex/p1",
35881                None,
35882                5_000,
35883            ))),
35884            right: Box::new(PlanNode::Scan(var_scan(
35885                Some("s"),
35886                "http://ex/p2",
35887                Some("z"),
35888                1_000,
35889            ))),
35890            hash_keys: vec![var("s")],
35891            probe_key_domains: Vec::new(),
35892            probe_key_overlap_milli: Vec::new(),
35893            rhs_hostable_keys: Vec::new().into(),
35894            meta: JoinMeta {
35895                semi_gate: None,
35896                star_arms: None,
35897                strategy: JoinStrategy::Broadcast,
35898                produced_row_count_estimate: 4_000,
35899                own_push_removed_row_count_estimate: 4_000,
35900            },
35901        };
35902        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p0", Some("o"), 100_000));
35903        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
35904        // Premise: the drop guard grants the coverage road here (one page's
35905        // list spans the whole 8-key domain) — if this ever changes, the
35906        // fixture needs a smaller domain, not a weaker assertion.
35907        assert!(crate::query::pushdown::source_coverage_drop(
35908            &driver, &subtree, page
35909        ));
35910        let keys = hash_keys_for(&driver.output_vars(), &subtree.output_vars());
35911        super::SEAT_CALLS.with(|c| c.set(0));
35912        super::WALK_VISITS.with(|c| c.set(0));
35913        let seat = seat_cost_total(Some(&profile), &driver, &subtree, &keys, None, None);
35914        // Counters first: they fingerprint which road priced this cost estimate.
35915        assert_eq!(super::SEAT_CALLS.with(|c| c.get()), 1);
35916        assert_eq!(super::WALK_VISITS.with(|c| c.get()), 0);
35917        assert_eq!(
35918            seat,
35919            SeatCost {
35920                rows: 100_000 + 4_000,
35921                seeks: 0
35922            }
35923        );
35924        // Keys-empty join: the subtree executes once, unpushed.
35925        super::SEAT_CALLS.with(|c| c.set(0));
35926        super::WALK_VISITS.with(|c| c.set(0));
35927        let seat = seat_cost_total(Some(&profile), &driver, &subtree, &[], None, None);
35928        assert_eq!(
35929            seat,
35930            SeatCost {
35931                rows: 100_000 + 4_000,
35932                seeks: 0
35933            }
35934        );
35935        assert_eq!(super::SEAT_CALLS.with(|c| c.get()), 1);
35936        assert_eq!(super::WALK_VISITS.with(|c| c.get()), 0);
35937    }
35938
35939    /// Repro diagnostic for the transects top join: rebuilds the benched
35940    /// seat (the geo cluster join vs the transect pair) from the profile
35941    /// numbers and prints BOTH orientations, for hand-diffing against a
35942    /// live run's `join-seat-totals` debug line (`waratah standalone
35943    /// --debug`). Deliberately a print-and-diff diagnostic, not a pin:
35944    /// the printed totals are the comparator's pricing of the model's
35945    /// roads, not a wall-clock measurement — a `join-seat-totals`
35946    /// divergence line on a live run means the executed pick and the
35947    /// seating-cost model's pick have split, and this fixture is the tool that
35948    /// diffed it.
35949    #[test]
35950    fn transects_seat_repro_diagnostic() {
35951        let mut profile = StatsProfile::default();
35952        for (pred, rows, subjects, objects) in [
35953            ("http://ex/type", 500_u64, 500_u128, 500_u128),
35954            ("http://ex/hasGeom", 816_044, 793_204, 816_044),
35955            ("http://ex/asWKT", 817_201, 817_201, 795_534),
35956        ] {
35957            profile.predicate_counts.insert(StrHash::new(pred), rows);
35958            profile
35959                .subjects_per_predicate
35960                .insert(StrHash::new(pred), hll_with_n(subjects));
35961            profile
35962                .objects_per_predicate
35963                .insert(StrHash::new(pred), hll_with_n(objects));
35964        }
35965        profile.total_puts = 1_633_745;
35966        let geo_scan = PlanNode::CustomNode(CustomOp {
35967            plugin_id: "cost-test",
35968            op_id: "op",
35969            payload: crate::plugin::PluginPayloadBox::new(CostTestPayload),
35970            children: Vec::new(),
35971            variables: vec![var("wkt")],
35972            produced_row_count_estimate: 36_862,
35973            cost: Some(CustomOpCost {
35974                drain_rows: 36_862,
35975                per_key_unit: 8,
35976                inline_point_unit: 1,
35977                direct_probe: true,
35978                probe_keyed_columns: 0b1,
35979                probe_filter_unit: 8,
35980                probe_memo_entry_rows: 0,
35981            }),
35982            pinned: Vec::new(),
35983        });
35984        let cluster = PlanNode::Join {
35985            left: Box::new(geo_scan),
35986            right: Box::new(PlanNode::Scan(var_scan(
35987                Some("g"),
35988                "http://ex/asWKT",
35989                Some("wkt"),
35990                817_201,
35991            ))),
35992            hash_keys: vec![var("wkt")],
35993            probe_key_domains: Vec::new(),
35994            probe_key_overlap_milli: Vec::new(),
35995            rhs_hostable_keys: Vec::new().into(),
35996            meta: JoinMeta {
35997                semi_gate: None,
35998                star_arms: None,
35999                strategy: JoinStrategy::Broadcast,
36000                produced_row_count_estimate: 37_865,
36001                own_push_removed_row_count_estimate: 37_865,
36002            },
36003        };
36004        let transect = PlanNode::Join {
36005            left: Box::new(PlanNode::Scan(var_scan(
36006                Some("tr"),
36007                "http://ex/type",
36008                None,
36009                500,
36010            ))),
36011            right: Box::new(PlanNode::Scan(var_scan(
36012                Some("tr"),
36013                "http://ex/hasGeom",
36014                Some("g"),
36015                816_044,
36016            ))),
36017            hash_keys: vec![var("tr")],
36018            probe_key_domains: Vec::new(),
36019            probe_key_overlap_milli: Vec::new(),
36020            rhs_hostable_keys: Vec::new().into(),
36021            meta: JoinMeta {
36022                semi_gate: None,
36023                star_arms: None,
36024                strategy: JoinStrategy::Broadcast,
36025                produced_row_count_estimate: 515,
36026                own_push_removed_row_count_estimate: 515,
36027            },
36028        };
36029        let keys = hash_keys_for(&transect.output_vars(), &cluster.output_vars());
36030        super::SEAT_CALLS.with(|c| c.set(0));
36031        super::WALK_VISITS.with(|c| c.set(0));
36032        let left = seat_cost_total(Some(&profile), &cluster, &transect, &keys, None, None);
36033        let right = seat_cost_total(Some(&profile), &transect, &cluster, &keys, None, None);
36034        eprintln!(
36035            "DIAG transects-seat: keys={keys:?} left(cluster drives)={left:?} right(transects drive)={right:?} calls={} visits={}",
36036            super::SEAT_CALLS.with(|c| c.get()),
36037            super::WALK_VISITS.with(|c| c.get())
36038        );
36039    }
36040
36041    /// The claim stamp and the walk's hypothesis are ONE
36042    /// derivation. Same pusher, same receiver, same key: the list size
36043    /// comes from one function (`pushed_val_count`) and the arithmetic
36044    /// from one core (`pushed_return_bound_core`) — pinned by driving
36045    /// both wrappers with the same value count and requiring equal bounds.
36046    /// The pusher's own row estimate bounds the list (the transects
36047    /// lesson): a 500-row driver over a wide key domain pushes 500 keys,
36048    /// and the walk's per-page context derives 500 — never a page-sized
36049    /// 24,576-key list.
36050    #[test]
36051    fn push_bound_stamp_and_hypothesis_share_one_derivation() {
36052        let mut profile = StatsProfile::default();
36053        for (pred, rows) in [
36054            ("http://ex/p0", 100_000_u64),
36055            ("http://ex/p1", 817_201),
36056            ("http://ex/p2", 500),
36057        ] {
36058            profile.predicate_counts.insert(StrHash::new(pred), rows);
36059            profile
36060                .subjects_per_predicate
36061                .insert(StrHash::new(pred), hll_with_n(rows as u128));
36062            profile
36063                .objects_per_predicate
36064                .insert(StrHash::new(pred), hll_with_n(rows as u128));
36065        }
36066        profile.total_puts = 917_701;
36067        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p0", Some("o"), 100_000));
36068        let mut probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/p1", None, 817_201));
36069
36070        // The hypothesis FIRST, on the pristine probe (the clamp below
36071        // min's the cell; the stamp's price is unclamped by design, but
36072        // reading before the mutation keeps the two bases textually
36073        // identical inputs).
36074        let count = pushed_val_count(Some(&profile), &driver, &var("s"));
36075        let dom_s0 = profile
36076            .subjects_per_predicate
36077            .get(&StrHash::new("http://ex/p0"))
36078            .expect("p0 subjects HLL")
36079            .cardinality();
36080        assert_eq!(
36081            count,
36082            dom_s0.clamp(1, 100_000),
36083            "the list size is min(domain, the pusher's OWN rows)"
36084        );
36085        let hypothesis = containing_push_driver_bound(Some(&profile), &probe, &var("s"), count);
36086
36087        // The stamp path: mark the probe claimed and run the clamp.
36088        let scan = match &mut probe {
36089            PlanNode::Scan(scan) => scan,
36090            _ => unreachable!("probe is a scan"),
36091        };
36092        let slots = scan.slot_of(&var("s"));
36093        assert!(!slots.is_empty(), "the subject slot hosts ?s");
36094        scan.broadcasted = Some((var("s"), slots[0]));
36095        let keys = [var("s")];
36096        clamp_broadcast_probe_estimates(&driver, &mut probe, &keys, Some(&profile));
36097        let stamp = match &probe {
36098            PlanNode::Scan(scan) => scan.ancestor_push_return_bound,
36099            _ => unreachable!("probe is a scan"),
36100        }
36101        .expect("the clamp stamps the bound");
36102
36103        // Same count, same core → the same number. This is the agreement
36104        // that failed by coincidence before the shared derivation: two formulas, three
36105        // scattered differences (rounding, containment, fallback policy).
36106        assert_eq!(Some(stamp), hypothesis);
36107
36108        // The transects realism bound: a 500-row pusher over a wide
36109        // domain (p2 carries p0-wide HLLs... deliberately wide) pushes
36110        // 500 keys, and the per-page context — child_push_from_shape's
36111        // exact expression — derives 500, not the 24,576 page size.
36112        let small_driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/p2", Some("o"), 500));
36113        // p2's subject domain is its own HLL (500); widen it past the
36114        // page size by reusing p0's domain for the domain lookup — the
36115        // row bound must bind even when the domain is huge.
36116        profile
36117            .subjects_per_predicate
36118            .insert(StrHash::new("http://ex/p2"), hll_with_n(816_044));
36119        let small_count = pushed_val_count(Some(&profile), &small_driver, &var("s"));
36120        let page = crate::join_chunks::driver_chunk_rows(PUSHDOWN_TERMS_LIMIT as usize);
36121        assert_eq!(small_count, 500, "the pusher's rows bound the list");
36122        assert_eq!(
36123            small_count.min(page),
36124            500,
36125            "and the per-page context carries the bound"
36126        );
36127    }
36128
36129    /// Layer 1b, plan level: planning the reference-shaped query (six
36130    /// patterns, keyed subtree probe arms) through the real pipeline keeps
36131    /// total comparator work under the pinned bound. This is the gate the
36132    /// 30 ms→sub-millisecond planner work never had: exceeding it fails
36133    /// the battery and forces a conscious trade.
36134    #[test]
36135    fn leaf_walk_plan_level_seat_call_bound() {
36136        let mut profile = StatsProfile::default();
36137        for i in 0..6 {
36138            let pred = format!("http://ex/p{i}");
36139            profile.predicate_counts.insert(StrHash::new(&pred), 50_000);
36140            profile
36141                .subjects_per_predicate
36142                .insert(StrHash::new(&pred), hll_with_n(50_000));
36143            profile
36144                .objects_per_predicate
36145                .insert(StrHash::new(&pred), hll_with_n(50_000));
36146        }
36147        profile.total_puts = 300_000;
36148        let sparql = "SELECT ?d WHERE {
36149            ?a <http://ex/p0> ?b . ?b <http://ex/p1> ?c . ?c <http://ex/p2> ?d .
36150            ?a <http://ex/p3> ?e . ?e <http://ex/p4> ?f . ?f <http://ex/p5> ?d }";
36151        super::SEAT_CALLS.with(|c| c.set(0));
36152        let plan =
36153            LogicalPlan::parse_with_profile(sparql, Some(&profile)).expect("reference shape plans");
36154        let seat_calls = super::SEAT_CALLS.with(|c| c.get());
36155        // Pinned at the measured baseline (86 seat calls for this shape on
36156        // 2026-10-28) × 3 headroom. The point is the CEILING, not the
36157        // number: comparator-work growth — new passes, recursion, wider
36158        // gathers — must be a deliberate, reviewed trade, never a silent
36159        // pile-up (the 30 ms→sub-millisecond planner work has no other
36160        // gate).
36161        assert!(
36162            (1..=260).contains(&seat_calls),
36163            "planner comparator work for the reference shape: {seat_calls} seat calls"
36164        );
36165        let _ = plan;
36166    }
36167
36168    /// The `planner-time:` debug line: one line per planned query through
36169    /// the query context's debug sink, every bucket present, total at
36170    /// least the sum of the from_prepared-internal buckets (the
36171    /// Distinct/Sort/Slice wraps and regex compilation ride in the total
36172    /// only — parse is upstream and independent). Emission resets the
36173    /// parse cell, so a query never inherits the previous query's parse
36174    /// time.
36175    #[test]
36176    fn planner_time_line_lists_every_bucket_and_resets_parse() {
36177        let lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
36178        let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_log(
36179            crate::LogSink::capture(crate::context::LogLevel::Debug, lines.clone()),
36180        );
36181        LogicalPlan::parse_with_context("SELECT ?s WHERE { ?s ?p ?o } LIMIT 3", &ctx)
36182            .expect("plans");
36183        let captured = lines.lock().expect("capture mutex").clone();
36184        let line = captured
36185            .iter()
36186            .find(|line| line.contains("planner-time:"))
36187            .expect("the planner-time line is captured");
36188        for bucket in ["parse=", "lower=", "rewrite=", "seat=", "stamps=", "total="] {
36189            assert!(line.contains(bucket), "missing `{bucket}` in: {line}");
36190        }
36191        let number_after = |key: &str| -> u64 {
36192            let idx = line.find(key).expect("bucket present") + key.len();
36193            let digits: String = line[idx..]
36194                .chars()
36195                .take_while(|c| c.is_ascii_digit())
36196                .collect();
36197            digits.parse().expect("bucket carries a µs number")
36198        };
36199        let interior: u64 = ["lower=", "rewrite=", "seat=", "stamps="]
36200            .iter()
36201            .map(|key| number_after(key))
36202            .sum();
36203        assert!(
36204            number_after("total=") >= interior,
36205            "total must cover the interior buckets: {line}"
36206        );
36207        assert_eq!(
36208            0,
36209            super::PLANNER_PARSE_US.with(|cell| cell.get()),
36210            "the parse cell resets on emission"
36211        );
36212    }
36213
36214    /// Layer 3 (release builds, manual): the honest planner-latency
36215    /// number for the reference shape. Debug-build battery tests cannot
36216    /// gate on wall clock (5–20× slowdown, loaded-machine flakes), so
36217    /// this harness only REPORTS:
36218    ///
36219    /// `cargo test --release -p waratah_compute \
36220    ///              planner_latency_reference_shape -- --ignored --nocapture`
36221    #[test]
36222    #[ignore = "release timing harness — run explicitly, prints p50/p99"]
36223    fn planner_latency_reference_shape() {
36224        let mut profile = StatsProfile::default();
36225        for i in 0..6 {
36226            let pred = format!("http://ex/p{i}");
36227            profile.predicate_counts.insert(StrHash::new(&pred), 50_000);
36228            profile
36229                .subjects_per_predicate
36230                .insert(StrHash::new(&pred), hll_with_n(50_000));
36231            profile
36232                .objects_per_predicate
36233                .insert(StrHash::new(&pred), hll_with_n(50_000));
36234        }
36235        profile.total_puts = 300_000;
36236        let sparql = "SELECT ?d WHERE {
36237            ?a <http://ex/p0> ?b . ?b <http://ex/p1> ?c . ?c <http://ex/p2> ?d .
36238            ?a <http://ex/p3> ?e . ?e <http://ex/p4> ?f . ?f <http://ex/p5> ?d }";
36239        // Warm one plan (first-parse costs dominate otherwise), then time
36240        // plan-only iterations. The parse-only row splits the pipeline:
36241        // the planner's share is the difference — parse is not planning.
36242        let _ = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
36243        const ITERATIONS: usize = 500;
36244        let mut micros = Vec::with_capacity(ITERATIONS);
36245        let mut parse_only = Vec::with_capacity(ITERATIONS);
36246        for _ in 0..ITERATIONS {
36247            super::SEAT_CALLS.with(|c| c.set(0));
36248            let start = std::time::Instant::now();
36249            let _ = LogicalPlan::parse_with_profile(sparql, Some(&profile)).unwrap();
36250            micros.push(start.elapsed().as_micros());
36251            let start = std::time::Instant::now();
36252            let parsed = spargebra::SparqlParser::new().parse_query(sparql).unwrap();
36253            let _ = parsed;
36254            parse_only.push(start.elapsed().as_micros());
36255        }
36256        micros.sort_unstable();
36257        parse_only.sort_unstable();
36258        let p50 = micros[micros.len() / 2];
36259        let p99 = micros[micros.len() * 99 / 100];
36260        let parse_p50 = parse_only[parse_only.len() / 2];
36261        println!(
36262            "parse+plan over {ITERATIONS}: p50 {p50}µs, p99 {p99}µs (parse alone p50 {parse_p50}µs — the planner's share is the difference)"
36263        );
36264    }
36265}
36266
36267/// Seat cost model (`seat_cost_total`) — the whole-seating comparator that
36268/// shadows the `driver_cost` swap decision (and, under the context's
36269/// `seat_by_total_cost` flag, becomes it). These tests pin the estimators
36270/// and the arithmetic on hand-computed tables; the fixture numbers are the
36271/// q02 geometry the corpus A/B validated.
36272#[cfg(test)]
36273mod shadow_seating_tests {
36274    use super::{
36275        FetchOnceVerdict, clustered_page_distinct, fetch_once_verdict, mixed_page_distinct,
36276        probe_broadcast_price,
36277    };
36278    use super::{SeatCost, seat_beats, seat_cost_arithmetic};
36279    use crate::query::pushdown::push_list_covers_domain;
36280
36281    #[test]
36282    fn clustered_list_is_the_runtime_page_not_the_whole_domain() {
36283        // The q02 degreeFrom arm: 652,374 triples over 3,000 subjects —
36284        // fanout ≈ 217 rows/subject, so a 24,576-row page (the eager cut,
36285        // PUSHDOWN_TERMS_LIMIT) holds ~113 subjects, NOT the 3,000 the
36286        // old whole-domain list assumed.
36287        let page = clustered_page_distinct(652_374, 3_000, 24_576);
36288        assert!(
36289            (111..=115).contains(&page),
36290            "expected ~113 subjects per page, got {page}"
36291        );
36292        // The per-page list does NOT cover memberOf's 1,500-subject domain;
36293        // the old whole-domain list did — the exact mis-price the corpus
36294        // review caught. Fanout 1 (2,007-row department scan) still holds
36295        // its whole domain, where the old model was accidentally right.
36296        assert!(!push_list_covers_domain(page as usize, 1_500, 1_000));
36297        assert!(push_list_covers_domain(3_000, 1_500, 1_000));
36298        assert_eq!(clustered_page_distinct(2_007, 2_007, 24_576), 2_007);
36299    }
36300
36301    #[test]
36302    fn mixed_page_sample_never_exceeds_what_a_page_holds() {
36303        // 24,576 rows sampled from a 100,000-key population: occupancy
36304        // D·(1 − e^(−P/D)) ≈ 21,789 — and never more than the page's rows.
36305        let mixed = mixed_page_distinct(100_000, 24_576, 200_000);
36306        assert!(
36307            (21_780..=21_800).contains(&mixed),
36308            "expected ~21,789, got {mixed}"
36309        );
36310        // A small domain saturates: nearly every key lands on the page.
36311        let saturated = mixed_page_distinct(3_000, 24_576, 200_000);
36312        assert!((2_980..=3_000).contains(&saturated));
36313        assert!(mixed_page_distinct(100_000, 24_576, 200_000) <= 24_576);
36314        assert!(mixed_page_distinct(5, 24_576, 200_000) <= 5);
36315    }
36316
36317    #[test]
36318    fn short_driver_pages_hold_at_most_their_own_rows() {
36319        // A 1-row driver page holds ONE distinct value per key — however
36320        // large the predicate's key-domain HLL says. The unclamped density
36321        // formula (page_rows × domain / driver_rows) priced a 1-row arm at
36322        // millions of seeks per page and fled seats the legacy comparator
36323        // gets right in milliseconds (the q07/q09 corpus regression).
36324        assert_eq!(clustered_page_distinct(1, 2_200_000, 24_576), 1);
36325        assert_eq!(clustered_page_distinct(2, 2_200_000, 24_576), 2);
36326        // The mixed bound carries the same cap: a 2-row page cannot sample
36327        // more than 2 keys, whatever the occupancy curve says.
36328        assert_eq!(mixed_page_distinct(2_200_000, 24_576, 2), 2);
36329        // Tail pages of a big arm are capped at page_rows, unchanged.
36330        assert_eq!(clustered_page_distinct(652_374, 3_000, 24_576), 113);
36331    }
36332
36333    #[test]
36334    fn q02_walk_prefers_inverting_the_spine() {
36335        // memberOf drives (today's plan): 53 pages; ONE list broadcasts per
36336        // page — the object key's (its whole-domain return ~20k rows
36337        // undercuts the subject key's ~641k, so the reorder puts it first
36338        // and `join_keys_scan_filter` broadcasts it). The subject page holds
36339        // ~37 of 1,972 departments, the object page ~190 of 10,000; the
36340        // broadcast list matches 379 of the subtree per page.
36341        let member_of_drives = seat_cost_arithmetic(
36342            1_048_532,
36343            652_374,
36344            false,
36345            53,
36346            &[(false, 190, 326_526, 1_000), (false, 37, 2_007, 1_000)],
36347            true,
36348            false,
36349            true,
36350            true,
36351            false,
36352            None,
36353        );
36354        assert_eq!(
36355            member_of_drives,
36356            SeatCost {
36357                rows: 1_048_532 + 53 * 379,
36358                seeks: 53 * 190
36359            }
36360        );
36361        // degreeFrom's subtree drives: 33 pages; ONE list broadcasts — the
36362        // object key's (199 university terms over a 1,048,532-row probe,
36363        // matching ~199 rows; the subject key's ~60-term list would match
36364        // ~32k and sorts after it).
36365        let subtree_drives = seat_cost_arithmetic(
36366            652_374,
36367            1_048_532,
36368            false,
36369            33,
36370            &[(false, 199, 1_048_532, 1_000), (false, 60, 1_972, 1_000)],
36371            true,
36372            false,
36373            true,
36374            true,
36375            false,
36376            None,
36377        );
36378        assert_eq!(
36379            subtree_drives,
36380            SeatCost {
36381                rows: 652_374 + 33 * 199,
36382                seeks: 33 * 199
36383            }
36384        );
36385        // The inversion clears the 20% swap margin on rows alone.
36386        assert!(seat_beats(subtree_drives, member_of_drives));
36387        // The legacy comparator picks memberOf on the same numbers via the
36388        // phantom department credit — exactly the disagreement the model
36389        // exists to surface.
36390        let old_left = super::driver_cost(1_048_532, Some(1_972));
36391        let old_right = super::driver_cost(652_374, Some(2_007));
36392        assert!(
36393            old_left < old_right,
36394            "the legacy comparator must keep memberOf driving here"
36395        );
36396    }
36397
36398    #[test]
36399    fn all_keys_covered_builds_a_subtree_probe_once() {
36400        // Every key covered and the drop guard allows: a subtree probe is
36401        // executed once and reused for every later page — never per page.
36402        let built_once = seat_cost_arithmetic(
36403            100_000,
36404            50_000,
36405            false,
36406            5,
36407            &[(true, 400, 400, 1_000)],
36408            true,
36409            true,
36410            true,
36411            true,
36412            false,
36413            None,
36414        );
36415        assert_eq!(
36416            built_once,
36417            SeatCost {
36418                rows: 150_000,
36419                seeks: 0
36420            }
36421        );
36422        // A memoizable scan pays one extra read for the runtime's
36423        // memo-refusal correction (an estimate miss costs one full fetch).
36424        let memoized = seat_cost_arithmetic(
36425            100_000,
36426            20_000,
36427            true,
36428            5,
36429            &[(true, 400, 400, 1_000)],
36430            true,
36431            true,
36432            true,
36433            true,
36434            false,
36435            None,
36436        );
36437        assert_eq!(
36438            memoized,
36439            SeatCost {
36440                rows: 140_000,
36441                seeks: 0
36442            }
36443        );
36444    }
36445
36446    #[test]
36447    fn covered_but_guard_denied_broadcasts_the_list() {
36448        // Coverage passed but the amortization guard denied the drop: the
36449        // (near-whole-domain) list broadcasts — seeks + a ~whole-arm read, per
36450        // page. The old model's over-threshold "disaster" (probe × pages with no
36451        // list at all) is this, priced honestly.
36452        let broadcast = seat_cost_arithmetic(
36453            100_000,
36454            50_000,
36455            false,
36456            5,
36457            &[(true, 2_000, 2_000, 1_000)],
36458            false,
36459            true,
36460            true,
36461            true,
36462            false,
36463            None,
36464        );
36465        // The priced trigger fires: per-page mode would re-pay 2,000 seeks +
36466        // the whole arm's rows on each of 5 pages (a denied drop broadcasts the
36467        // near-whole-domain list, matching ~the whole arm). the cost model prices
36468        // the build the runtime will stamp: one drain, no seeks. The price
36469        // is comfortably past the line (286M vs 75M milli), so no
36470        // near-line risk extra.
36471        assert_eq!(
36472            broadcast,
36473            SeatCost {
36474                rows: 150_000,
36475                seeks: 0
36476            }
36477        );
36478        // The same numbers with the stamp UNREACHABLE (a subtree probe):
36479        // the cost model must price the transport the runtime will run — the
36480        // list broadcasts, per page.
36481        let unstamped = seat_cost_arithmetic(
36482            100_000,
36483            50_000,
36484            false,
36485            5,
36486            &[(true, 2_000, 2_000, 1_000)],
36487            false,
36488            false,
36489            true,
36490            true,
36491            false,
36492            None,
36493        );
36494        assert_eq!(
36495            unstamped,
36496            SeatCost {
36497                rows: 100_000 + 5 * 50_000,
36498                seeks: 5 * 2_000
36499            }
36500        );
36501    }
36502
36503    #[test]
36504    fn one_list_broadcasts_priced_from_the_first_surviving_key() {
36505        // The runtime broadcasts ONE list per page — `join_keys_scan_filter`
36506        // returns the first key that is not covered-and-droppable — so the
36507        // price takes that key's list (10 seeks) and its matched estimate
36508        // (50,000 × 10/100,000 = 5 rows), not the sum over keys: the
36509        // second key's list never crosses the wire (the hash join
36510        // constrains it after the wire).
36511        let both = seat_cost_arithmetic(
36512            100_000,
36513            50_000,
36514            false,
36515            5,
36516            &[(false, 10, 100_000, 1_000), (false, 50, 1_000, 1_000)],
36517            true,
36518            true,
36519            true,
36520            true,
36521            false,
36522            None,
36523        );
36524        assert_eq!(
36525            both,
36526            SeatCost {
36527                rows: 100_000 + 5 * 5,
36528                seeks: 5 * 10
36529            }
36530        );
36531    }
36532
36533    #[test]
36534    fn covered_keys_are_skipped_in_the_pick() {
36535        // A covered-and-droppable key broadcasts nothing (the coverage rule
36536        // drops it) — the pick walks to the next key, exactly as
36537        // `join_keys_scan_filter` does.
36538        let (seeks, matched) = probe_broadcast_price(
36539            50_000,
36540            &[(true, 10_000, 10_000, 1_000), (false, 50, 1_000, 1_000)],
36541            true,
36542        );
36543        assert_eq!((seeks, matched), (50, 2_500));
36544    }
36545
36546    #[test]
36547    fn arm_estimate_without_a_profile_never_builds() {
36548        // With no (or empty) stats the "unclamped" arm
36549        // price is the clamp fallback — a fiction. A tiny fiction plus a
36550        // few pages clears the margin and would stamp a whole-arm drain
36551        // the estimates never justified; the epistemic gate refuses the
36552        // verdict instead. The identical numbers with profile-backed
36553        // evidence still build (6 pages × 10,000 seeks × 3.6 = 216M milli
36554        // ≥ 1,500 × 3 = 4,500).
36555        assert_eq!(
36556            fetch_once_verdict(
36557                6, 10_000, 0, 3, false, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36558            ),
36559            FetchOnceVerdict::PerPage
36560        );
36561        assert_eq!(
36562            fetch_once_verdict(
36563                6, 10_000, 0, 3, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36564            ),
36565            FetchOnceVerdict::FetchOnce
36566        );
36567    }
36568
36569    #[test]
36570    fn covered_whole_read_prices_the_arm_not_the_clamp() {
36571        // The all-covered road's one read IS the
36572        // whole-arm fetch the fetch-once road prices — both roads must name the
36573        // same number. The cost model's single row basis is the whole-read
36574        // estimate (the probe/arm parameter collapse), so here the price
36575        // says 7,659 — the arm's whole read — and the memoizable extra is
36576        // a second whole read. (Before the collapse this fixture passed
36577        // 686 as the separately-clamped probe price to pin the contrast;
36578        // with one basis there is no second number to contrast against.)
36579        let covered = seat_cost_arithmetic(
36580            100_000,
36581            7_659,
36582            false,
36583            5,
36584            &[(true, 400, 400, 1_000)],
36585            true,
36586            true,
36587            true,
36588            true,
36589            false,
36590            None,
36591        );
36592        assert_eq!(
36593            covered,
36594            SeatCost {
36595                rows: 100_000 + 7_659,
36596                seeks: 0
36597            }
36598        );
36599        let memoized = seat_cost_arithmetic(
36600            100_000,
36601            7_659,
36602            true,
36603            5,
36604            &[(true, 400, 400, 1_000)],
36605            true,
36606            true,
36607            true,
36608            true,
36609            false,
36610            None,
36611        );
36612        assert_eq!(
36613            memoized,
36614            SeatCost {
36615                rows: 100_000 + 2 * 7_659,
36616                seeks: 0
36617            }
36618        );
36619    }
36620
36621    #[test]
36622    fn summed_key_lists_do_not_inflate_the_verdict_into_a_build() {
36623        // The parity-review flip shape, pinned: two surviving keys with
36624        // equal per-page lists. Summing their seeks (the old model) clears
36625        // the margin and stamps a whole-arm drain; the runtime broadcasts ONE
36626        // list (the first survivor's), and the corrected price stays in
36627        // per-page mode.
36628        let (seeks, matched) = probe_broadcast_price(
36629            277_000,
36630            &[
36631                (false, 10_000, 1_000_000_000_000, 1_000),
36632                (false, 10_000, 1_000_000_000_000, 1_000),
36633            ],
36634            false,
36635        );
36636        assert_eq!((seeks, matched), (10_000, 0));
36637        assert_eq!(
36638            fetch_once_verdict(
36639                6, seeks, matched, 277_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36640            ),
36641            FetchOnceVerdict::PerPage
36642        );
36643        // The OLD summed model (20,000 seeks/page) would have said Build:
36644        // 6 × 20,000 × 3,600 = 432M milli-rows ≥ 1,500 × 277,000 = 415.5M.
36645        assert_eq!(
36646            fetch_once_verdict(
36647                6, 20_000, matched, 277_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36648            ),
36649            FetchOnceVerdict::FetchOnce
36650        );
36651    }
36652
36653    #[test]
36654    fn one_term_list_is_a_point_lookup_never_covered() {
36655        // A single ground term is a point lookup, not a relation filter —
36656        // the runtime never covers it: the price is the (tiny) seek plus
36657        // its matched rows, per page.
36658        let point = seat_cost_arithmetic(
36659            40_000,
36660            10_000,
36661            true,
36662            2,
36663            &[(false, 1, 500, 1_000)],
36664            true,
36665            true,
36666            true,
36667            true,
36668            false,
36669            None,
36670        );
36671        assert_eq!(
36672            point,
36673            SeatCost {
36674                rows: 40_000 + 2 * 20,
36675                seeks: 2
36676            }
36677        );
36678        assert!(point.rows < 40_000 + 10_000);
36679    }
36680
36681    #[test]
36682    fn unknown_probe_domain_never_covers_and_prices_conservatively() {
36683        // Domain 0 = unknown: the runtime never covers it, and the matched
36684        // fraction falls back to the full arm (documented conservatism —
36685        // both orientations suffer it equally).
36686        let unknown = seat_cost_arithmetic(
36687            40_000,
36688            10_000,
36689            true,
36690            2,
36691            &[(false, 190, 0, 1_000)],
36692            true,
36693            true,
36694            true,
36695            true,
36696            false,
36697            None,
36698        );
36699        // Probe price would be 60,000 rows + 380 seeks, but two pages of
36700        // whole-arm matches at the bound rate (2 × (190 × 4,200 +
36701        // 10,000 × 1,200) = 25.6M milli) beat 1.4× the arm (14M) to the
36702        // build — one drain, no synthetic risk extra: rows 40,000 +
36703        // 10,000, seeks 0.
36704        assert_eq!(
36705            unknown,
36706            SeatCost {
36707                rows: 50_000,
36708                seeks: 0
36709            }
36710        );
36711    }
36712
36713    #[test]
36714    fn empty_driver_reads_nothing() {
36715        assert_eq!(
36716            seat_cost_arithmetic(
36717                0,
36718                10_000,
36719                true,
36720                1,
36721                &[(false, 5, 100, 1_000)],
36722                false,
36723                true,
36724                true,
36725                true,
36726                false,
36727                None,
36728            ),
36729            SeatCost { rows: 0, seeks: 0 },
36730        );
36731    }
36732
36733    #[test]
36734    fn seat_beats_rows_decide_and_seeks_only_break_statistical_ties() {
36735        let incumbent = SeatCost {
36736            rows: 1_000,
36737            seeks: 500,
36738        };
36739        // A challenger that reads MORE rows never wins — not for any seek
36740        // count. (The old ±20% margin let 1,199 rows / 1 seek beat
36741        // 1,000 rows / 500 seeks; that was the seek count choosing the
36742        // seat the currency split was meant to prevent.)
36743        assert!(!seat_beats(
36744            SeatCost {
36745                rows: 1_001,
36746                seeks: 0
36747            },
36748            incumbent
36749        ));
36750        // Inside the ±2% noise band the cost estimate only moves if both currencies
36751        // agree: fewer rows AND fewer seeks.
36752        assert!(!seat_beats(
36753            SeatCost {
36754                rows: 990,
36755                seeks: 600
36756            },
36757            incumbent
36758        ));
36759        assert!(seat_beats(
36760            SeatCost {
36761                rows: 990,
36762                seeks: 400
36763            },
36764            incumbent
36765        ));
36766        // Exact row tie: seeks break it, either way.
36767        assert!(seat_beats(
36768            SeatCost {
36769                rows: 1_000,
36770                seeks: 499
36771            },
36772            incumbent
36773        ));
36774        assert!(!seat_beats(
36775            SeatCost {
36776                rows: 1_000,
36777                seeks: 501
36778            },
36779            incumbent
36780        ));
36781        // Beyond the band, fewer rows decides outright — seeks are
36782        // irrelevant.
36783        assert!(seat_beats(
36784            SeatCost {
36785                rows: 900,
36786                seeks: 9_999
36787            },
36788            incumbent
36789        ));
36790    }
36791
36792    #[test]
36793    fn fetch_once_predicate_priced_in_row_equivalents() {
36794        // The canary's type arm (corrected formula): 6 driver
36795        // pages, 24,576 distinct values broadcast per page, a 1:1 match
36796        // (24,576 matched rows/page), 277,711-row arm. Probe price =
36797        // 6 × (24,576 × 3.6 + 24,576) = 678k row-equivalents ≥
36798        // 1.5 × 277,711 = 417k → BUILD. The old seeks-only formula
36799        // was knife-edged at the lowest measured rate; with the
36800        // matched-row term this fires with 1.63× headroom.
36801        assert_eq!(
36802            fetch_once_verdict(
36803                6, 24_576, 24_576, 277_711, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36804            ),
36805            FetchOnceVerdict::FetchOnce
36806        );
36807        // The siteName arm: tiny lists (674 keys/page, 674 rows/page)
36808        // against a 7,694-row arm — 18.6k vs 11.5k row-equivalents →
36809        // BUILD.
36810        assert_eq!(
36811            fetch_once_verdict(
36812                6, 674, 674, 7_694, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36813            ),
36814            FetchOnceVerdict::FetchOnce
36815        );
36816        // Counter-example (probe retention): cheap lists and a tiny
36817        // match against a huge arm — 2.76k row-equivalents vs 1.5M.
36818        // per-page mode keeps the arm; this is the shape the priced trigger
36819        // exists to PROTECT (the old fixed 3×-driver-rows rule would
36820        // have built it).
36821        assert_eq!(
36822            fetch_once_verdict(
36823                6, 100, 100, 1_000_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36824            ),
36825            FetchOnceVerdict::PerPage
36826        );
36827        // Far past the line as well — the verdict carries no risk term;
36828        // the comparator prices the build at driver + arm rows and the
36829        // bail-out bounds a wrong estimate (a +1× arm-rows extra was
36830        // measured distorting seatings on the canary and was dropped).
36831        assert_eq!(
36832            fetch_once_verdict(
36833                50, 24_576, 0, 1_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36834            ),
36835            FetchOnceVerdict::FetchOnce
36836        );
36837        // The clamp divergence: the threshold and the build price read
36838        // the UNCLAMPED arm, never the push-clamped produced estimate —
36839        // the canary's siteName arm fires against its real 7,659 rows
36840        // (11 join-output pages × (6,141 × 3.6 + 6,141) ≈ 311k ≥ 1.5 ×
36841        // 7,659), and a 686-row clamp on the same shape must not change
36842        // the verdict's inputs.
36843        assert_eq!(
36844            fetch_once_verdict(
36845                11, 6_141, 6_141, 7_659, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36846            ),
36847            FetchOnceVerdict::FetchOnce
36848        );
36849        assert_eq!(
36850            fetch_once_verdict(
36851                11, 6_141, 6_141, 686, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36852            ),
36853            FetchOnceVerdict::FetchOnce
36854        );
36855        // Degenerate inputs never fire: an empty arm is the `Empty`
36856        // verdict's business, not a build.
36857        assert_eq!(
36858            fetch_once_verdict(
36859                0, 100, 100, 1_000, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36860            ),
36861            FetchOnceVerdict::PerPage
36862        );
36863        assert_eq!(
36864            fetch_once_verdict(
36865                6, 100, 100, 0, true, true, false, 3_600, 1_000, 1_200, 1_000, 1_500
36866            ),
36867            FetchOnceVerdict::PerPage
36868        );
36869        // Saturating internals: astronomic estimates decide, never panic.
36870        assert_eq!(
36871            fetch_once_verdict(
36872                u64::MAX,
36873                u64::MAX,
36874                u64::MAX,
36875                1,
36876                true,
36877                true,
36878                false,
36879                3_600,
36880                1_000,
36881                1_200,
36882                1_000,
36883                1_500
36884            ),
36885            FetchOnceVerdict::FetchOnce
36886        );
36887        // Missing driver-domain sketch: never a build decision — a
36888        // worst-case full page of seeks is not evidence per-page mode is
36889        // expensive (the coverage gate's own epistemic rule).
36890        assert_eq!(
36891            fetch_once_verdict(
36892                6, 24_576, 24_576, 277_711, true, false, false, 3_600, 1_000, 1_200, 1_000, 1_500
36893            ),
36894            FetchOnceVerdict::PerPage
36895        );
36896    }
36897
36898    /// A matched count that has collapsed to the whole-arm bound is not an
36899    /// estimate: it is the same number for a one-key list and a million-key
36900    /// list, so it must not order a build by itself. These are the production
36901    /// rates, and the arm is the 44.8m-triple `?s ?p ?o` scan whose subject
36902    /// domain is unknown (no per-predicate sketch to consult), so the
36903    /// broadcast price returns the whole arm as the matched count.
36904    #[test]
36905    fn a_degenerate_probe_match_builds_on_pages_not_on_the_bound() {
36906        const WHOLE: u64 = 44_804_238;
36907        // One page, 16 pushed keys: the bound prices at 1.2× the arm, under
36908        // the 1.4× bar, so the probe keeps its allow-list.
36909        assert_eq!(
36910            fetch_once_verdict(
36911                1, 16, WHOLE, WHOLE, true, true, true, 4_200, 1_400, 1_200, 1_000, 1_400
36912            ),
36913            FetchOnceVerdict::PerPage
36914        );
36915        // Two pages of the same degenerate match: 2.4× the arm clears the
36916        // bar, and a whole-read-per-page road really is two reads against
36917        // one.
36918        assert_eq!(
36919            fetch_once_verdict(
36920                2, 16, WHOLE, WHOLE, true, true, true, 4_200, 1_400, 1_200, 1_000, 1_400
36921            ),
36922            FetchOnceVerdict::FetchOnce
36923        );
36924        // A real estimate below the arm keeps the measured 1400 premium:
36925        // two pages of a 550-row match on a 1,000-row arm price at 1,540k
36926        // against a 1,400k bar and build. At the bound rate they would price
36927        // at 1,320k and stay per-page, so this pins that the discount is
36928        // applied only at the bound.
36929        assert_eq!(
36930            fetch_once_verdict(
36931                2, 0, 550, 1_000, true, true, false, 4_200, 1_400, 1_200, 1_000, 1_400
36932            ),
36933            FetchOnceVerdict::FetchOnce
36934        );
36935        // A page-sized list against a tiny arm still builds on the known
36936        // seek term alone; the bound rate must not suppress that road.
36937        assert_eq!(
36938            fetch_once_verdict(
36939                1, 24_576, 10, 10, true, true, true, 4_200, 1_400, 1_200, 1_000, 1_400
36940            ),
36941            FetchOnceVerdict::FetchOnce
36942        );
36943    }
36944}
36945
36946#[cfg(test)]
36947mod const_seed_tests {
36948    //! Plan-carried const seed collection: the collector sees nested
36949    //! positions (COALESCE fallbacks, IF branches), dedupes by hash, and
36950    //! the node-level walk fills exactly the mint-capable nodes.
36951
36952    use super::*;
36953    use waratah_storage::Variable;
36954
36955    fn var(name: &str) -> Expression {
36956        Expression::Variable(Variable::new(name).unwrap())
36957    }
36958
36959    fn node(iri: &str) -> Expression {
36960        Expression::NamedNode(waratah_storage::NamedNode::new(iri).unwrap())
36961    }
36962
36963    #[test]
36964    fn collect_expression_consts_including_nested_positions() {
36965        let expression = Expression::Coalesce(vec![
36966            var("missing"),
36967            node("urn:ex:const-fallback"),
36968            Expression::If(
36969                Box::new(var("flag")),
36970                Box::new(node("urn:ex:branch-then")),
36971                Box::new(Expression::Literal(
36972                    waratah_storage::Literal::new_simple_literal("a long lexical form"),
36973                )),
36974            ),
36975        ]);
36976        let mut strings = Vec::new();
36977        let mut blobs = Vec::new();
36978        collect_expression_const_seeds(&expression, &mut strings, &mut blobs);
36979        // All three const positions, hash-deduped: the two IRIs by their
36980        // canonical hashes, the big literal by its lexical hash.
36981        let fallback = waratah_storage::StrHash::new("urn:ex:const-fallback");
36982        assert!(
36983            strings
36984                .iter()
36985                .any(|(hash, raw)| *hash == fallback && raw == "urn:ex:const-fallback"),
36986            "the COALESCE fallback IRI must be collected"
36987        );
36988        let branch = waratah_storage::StrHash::new("urn:ex:branch-then");
36989        assert!(strings.iter().any(|(hash, _)| *hash == branch));
36990        assert_eq!(
36991            strings.len(),
36992            3,
36993            "two IRIs + one big-string lexical, deduped"
36994        );
36995        assert!(blobs.is_empty(), "no plugin-owned datatype in this shape");
36996    }
36997
36998    #[test]
36999    fn attach_fills_extend_and_group_nodes_only() {
37000        let mut tree = PlanNode::Extend {
37001            inner: Box::new(PlanNode::Group {
37002                inner: Box::new(PlanNode::Unit),
37003                variables: Vec::new(),
37004                aggregates: vec![(
37005                    Variable::new("m").unwrap(),
37006                    AggregateExpression::FunctionCall {
37007                        name: spargebra::algebra::AggregateFunction::Min,
37008                        expr: node("urn:ex:agg-const"),
37009                        distinct: false,
37010                    },
37011                )],
37012                const_strings: Vec::new(),
37013                const_blobs: Vec::new(),
37014            }),
37015            variable: Variable::new("y").unwrap(),
37016            expression: Expression::Coalesce(vec![var("missing"), node("urn:ex:const-fallback")]),
37017            const_strings: Vec::new(),
37018            const_blobs: Vec::new(),
37019        };
37020        attach_const_seeds(&mut tree);
37021        let PlanNode::Extend {
37022            const_strings,
37023            inner,
37024            ..
37025        } = &tree
37026        else {
37027            panic!("expected Extend root");
37028        };
37029        assert_eq!(const_strings.len(), 1, "the COALESCE fallback IRI");
37030        let PlanNode::Group { const_strings, .. } = inner.as_ref() else {
37031            panic!("expected Group inner");
37032        };
37033        assert_eq!(const_strings.len(), 1, "the aggregate argument IRI");
37034    }
37035
37036    #[test]
37037    fn duplicate_consts_dedup_per_node() {
37038        let expression = Expression::Coalesce(vec![
37039            var("a"),
37040            node("urn:ex:same"),
37041            Expression::Coalesce(vec![var("b"), node("urn:ex:same")]),
37042        ]);
37043        let mut strings = Vec::new();
37044        let mut blobs = Vec::new();
37045        collect_expression_const_seeds(&expression, &mut strings, &mut blobs);
37046        assert_eq!(strings.len(), 1);
37047    }
37048
37049    /// The walk descends `CustomOp.children`: that field is the
37050    /// documented wrap-a-subtree extension point, the executor runs
37051    /// Extends under custom children, and an unfilled seed list there
37052    /// regresses the child's consts to `RegistryMiss` at decode.
37053    #[test]
37054    fn attach_descends_custom_op_children() {
37055        #[derive(Debug)]
37056        struct WalkTestPayload;
37057        impl crate::plugin::PluginPayload for WalkTestPayload {
37058            fn plugin_id(&self) -> &'static str {
37059                "const-seed-test"
37060            }
37061            fn memo_content(&self) -> Vec<u8> {
37062                Vec::new()
37063            }
37064        }
37065        let mut tree = PlanNode::CustomNode(CustomOp {
37066            plugin_id: "const-seed-test",
37067            op_id: "op",
37068            payload: crate::plugin::PluginPayloadBox::new(WalkTestPayload),
37069            children: vec![PlanNode::Extend {
37070                inner: Box::new(PlanNode::Unit),
37071                variable: Variable::new("y").unwrap(),
37072                expression: Expression::Coalesce(vec![var("missing"), node("urn:ex:under-custom")]),
37073                const_strings: Vec::new(),
37074                const_blobs: Vec::new(),
37075            }],
37076            variables: vec![Variable::new("y").unwrap()],
37077            produced_row_count_estimate: 1,
37078            cost: None,
37079            pinned: Vec::new(),
37080        });
37081        attach_const_seeds(&mut tree);
37082        let PlanNode::CustomNode(op) = &tree else {
37083            panic!("expected CustomNode root");
37084        };
37085        let PlanNode::Extend { const_strings, .. } = &op.children[0] else {
37086            panic!("expected Extend child");
37087        };
37088        assert_eq!(
37089            const_strings.len(),
37090            1,
37091            "the const under the custom child must be collected"
37092        );
37093    }
37094}
37095
37096/// The plan stamp half of fetch-once:
37097/// `restamp_fetch_once` prices each inner join's bare-Scan right arm with
37098/// the SAME gather, price and predicate the seating comparator used.
37099#[cfg(test)]
37100mod fetch_once_stamp_tests {
37101    use super::FetchOnceVerdict;
37102    use super::{fetch_once_verdict, probe_seek_concurrency_milli};
37103
37104    use super::restamp_fetch_once;
37105    use super::stamp_semi_join_strategy;
37106    use super::{BagMark, DomainScanKind, Liveness};
37107    use super::{GraphFilter, scan_is_key_unique};
37108    use super::{JoinMeta, JoinStrategy, LeftJoinMeta, PlanNode, ScanOp, StatsProfile};
37109    use super::{bound_constraint_count_scan, fetch_once_stampable};
37110    use crate::ValuesOp;
37111    use waratah_storage::{EncodedTerm, EncodedTriplePattern, NamedNode, Variable};
37112
37113    fn var_scan(subject: Option<&str>, predicate: &str, object: Option<&str>, rows: u64) -> ScanOp {
37114        ScanOp {
37115            ancestor_push_return_bound: None,
37116            fetch_once: None,
37117            pattern: EncodedTriplePattern {
37118                subject: None,
37119                predicate: Some(EncodedTerm::from(&NamedNode::new(predicate).unwrap())),
37120                object: None,
37121                graph_name: None,
37122            },
37123            subject: subject.map(|v| Variable::new(v).unwrap()),
37124            predicate: None,
37125            object: object.map(|v| Variable::new(v).unwrap()),
37126            graph: None,
37127            produced_row_count_estimate: rows,
37128            broadcasted: None,
37129            graph_filter: None,
37130            grounded: Vec::new(),
37131            merge_default_graph: false,
37132            marks: Vec::new(),
37133            domain_scan: None,
37134            head_scan: None,
37135            head_scan_counts: None,
37136            domain_counts: None,
37137            iri_only: Vec::new(),
37138            eager: Vec::new(),
37139            join_domains: Default::default(),
37140        }
37141    }
37142
37143    fn join(left: PlanNode, right: PlanNode, produced: u64) -> PlanNode {
37144        PlanNode::Join {
37145            left: Box::new(left),
37146            right: Box::new(right),
37147            hash_keys: vec![Variable::new("s").unwrap()],
37148            probe_key_domains: Vec::new(),
37149            probe_key_overlap_milli: Vec::new(),
37150            rhs_hostable_keys: Vec::new().into(),
37151            meta: JoinMeta {
37152                semi_gate: None,
37153                star_arms: None,
37154                strategy: JoinStrategy::Broadcast,
37155                produced_row_count_estimate: produced,
37156                own_push_removed_row_count_estimate: produced,
37157            },
37158        }
37159    }
37160
37161    fn stamp_of(node: &PlanNode) -> Option<Option<u64>> {
37162        node.as_scan().map(|scan| scan.fetch_once)
37163    }
37164
37165    fn is_stamped(node: &PlanNode) -> bool {
37166        node.as_scan().is_some_and(|scan| scan.fetch_once.is_some())
37167    }
37168
37169    fn strategy_of(node: &PlanNode) -> JoinStrategy {
37170        match node {
37171            PlanNode::Join { meta, .. } => meta.strategy,
37172            other => panic!("expected Join, got {other:?}"),
37173        }
37174    }
37175
37176    fn var(name: &str) -> Variable {
37177        Variable::new(name).unwrap()
37178    }
37179
37180    /// Profile with subject HLLs for driver + probes: the epistemic gate
37181    /// refuses to fire on missing driver sketches, so the stamp tests must
37182    /// supply real ones.
37183    fn known_profile(driver_keys: u128) -> StatsProfile {
37184        let mut profile = StatsProfile::default();
37185        // (predicate, row count — feeds the unclamped arm estimate, HLL
37186        // value count — feeds the domain).
37187        for (pred, rows, keys) in [
37188            ("http://ex/driver", 200_000u64, driver_keys),
37189            ("http://ex/probe", 50_000, 50_000),
37190            ("http://ex/a", 50_000, 50_000),
37191            ("http://ex/b", 50_000, 50_000),
37192            ("http://ex/il", 60_000, 5_000),
37193            ("http://ex/ir", 3_000, 3_000),
37194        ] {
37195            let mut hll = waratah_stats::HyperLogLog::default_params();
37196            for i in 0..keys {
37197                hll.add(i);
37198            }
37199            profile
37200                .subjects_per_predicate
37201                .insert(waratah_storage::StrHash::new(pred), hll);
37202            profile
37203                .predicate_counts
37204                .insert(waratah_storage::StrHash::new(pred), rows);
37205        }
37206        profile.total_puts = 400_000;
37207        profile
37208    }
37209
37210    /// A firing arm stamps; the driver does not. No profile: unknown
37211    /// domains price a full page of seeks and a whole-arm match per page —
37212    /// 9 pages × (24,576 seeks × 3.6 + 50k rows) ≫ 1.5 × 50k → fetch-once.
37213    /// The star fetch-concurrency divisor: a spine arm's batched probe
37214    /// prices its seeks at the batch credit, and the flagship-class polluted
37215    /// arm flips FetchOnce→PerPage at a real credit while the same numbers
37216    /// stay Build sequentially — the clean sibling stays fetch-once either way
37217    /// (the flip sorts arms by whole-read waste with no pollution input).
37218    #[test]
37219    fn star_divisor_flips_only_with_the_batch_credit() {
37220        // Sequential: 115 × (24,576 × 3.6 + 24,576) ≈ 13.0M
37221        // row-equivalents ≥ 1.5 × 7,635,119 = 11.45M → fetch-once.
37222        assert_eq!(
37223            fetch_once_verdict(
37224                115, 24_576, 24_576, 7_635_119, true, true, false, 3_600, 1_000, 1_200, 1_000,
37225                1_500
37226            ),
37227            FetchOnceVerdict::FetchOnce
37228        );
37229        // A real credit (W = 1.5): seeks × 3.6 / 1.5 → ≈9.6M < 11.45M →
37230        // Probe.
37231        assert_eq!(
37232            fetch_once_verdict(
37233                115, 24_576, 24_576, 7_635_119, true, true, false, 3_600, 1_000, 1_200, 1_500,
37234                1_500
37235            ),
37236            FetchOnceVerdict::PerPage
37237        );
37238        // The clean sibling (2.82M-row arm): 9.6M ≥ 4.23M → fetch-once stays.
37239        assert_eq!(
37240            fetch_once_verdict(
37241                115, 24_576, 24_576, 2_822_319, true, true, false, 3_600, 1_000, 1_200, 1_500,
37242                1_500
37243            ),
37244            FetchOnceVerdict::FetchOnce
37245        );
37246    }
37247
37248    /// `star_seek_concurrency_milli`: the engine fetch-concurrency credit and the
37249    /// chunk-count gate. A batch forming fewer chunks than the engine's
37250    /// fetch concurrency runs at the chunk count — one chunk is one RPC, sequential
37251    /// by construction, and a divisor on it would under-price a road
37252    /// that cannot overlap. Every batched arm prices the same fetch concurrency,
37253    /// star or not; the known bias (a spine whose arms ALL run wide
37254    /// parallel-probe roads shares the pool at execution) is documented on the
37255    /// function itself.
37256    /// The single-arm batch price: a batchable single-arm join prices at
37257    /// the engine's full fetch concurrency (3.0 funded at the default),
37258    /// chunk-gated, then mapped through the measured realized-concurrency
37259    /// curve (3.0 funded → 2.42 realized) — and the flagship-class
37260    /// polluted arm flips FetchOnce→PerPage at that credit where the
37261    /// sequential price stays fetch-once (the general road pricing the
37262    /// chain shape exactly as it prices the star).
37263    #[test]
37264    fn single_arm_batch_prices_the_fetch_concurrency() {
37265        // Not batchable: sequential.
37266        assert_eq!(probe_seek_concurrency_milli(false, 115, 24_576, 3), 1000);
37267        // Plain (non-star) join, batchable, at fetch concurrency 3: 3000 funded,
37268        // chunks 115 → the fetch concurrency binds; the curve maps funded 3.0 → 2420.
37269        assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 3), 2_420);
37270        // One page forms one chunk: sequential, whatever the fetch concurrency.
37271        assert_eq!(probe_seek_concurrency_milli(true, 1, 24_576, 3), 1000);
37272        // The flip, flagship-class numbers as a chain join:
37273        assert_eq!(
37274            fetch_once_verdict(
37275                115, 24_576, 24_576, 7_635_119, true, true, false, 3_600, 1_000, 1_200, 1_000,
37276                1_500
37277            ),
37278            FetchOnceVerdict::FetchOnce
37279        );
37280        assert_eq!(
37281            fetch_once_verdict(
37282                115, 24_576, 24_576, 7_635_119, true, true, false, 3_600, 1_000, 1_200, 3_000,
37283                1_500
37284            ),
37285            FetchOnceVerdict::PerPage
37286        );
37287    }
37288
37289    #[test]
37290    fn star_concurrency_milli_is_the_fetch_concurrency_not_the_spine_size() {
37291        // Not batchable: the sequential price.
37292        assert_eq!(probe_seek_concurrency_milli(false, 115, 24_576, 3), 1000);
37293        // Two-arm spine, flagship geometry: the engine's full fetch concurrency is
37294        // funded (the FetchOnce-built sibling holds no batch permits),
37295        // so the credit is the curve's 3000-milli point.
37296        assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 3), 2_420);
37297        // Chunk gate: ONE page of threshold seeks forms one chunk →
37298        // sequential, whatever the funded fetch concurrency.
37299        assert_eq!(probe_seek_concurrency_milli(true, 1, 24_576, 3), 1000);
37300        // The spine size does NOT divide the credit: a three-arm spine
37301        // prices the same fetch concurrency (the corpus's three-way arms stay
37302        // FetchOnce at this credit — 1657/1587 milli against the 1500
37303        // margin at 10m/100m). Known bias, documented on the function:
37304        // a spine whose arms ALL run wide parallel-probe roads shares the pool at
37305        // execution and is over-credited here; no measured corpus arm
37306        // runs that shape.
37307        assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 3), 2_420);
37308        // A wider engine still clamps at the curve's measured plateau.
37309        assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 8), 4_050);
37310    }
37311
37312    #[test]
37313    fn seek_concurrency_engine_off_floor_and_large_fetch_concurrency() {
37314        // Engine off (fetch concurrency 0 and 1): sequential pricing whatever the
37315        // stamp claims — no road delivers batch fetch concurrency.
37316        assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 0), 1000);
37317        assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 1), 1000);
37318        // Fetch concurrency 2: 2000 funded → the curve's 2000-milli point.
37319        assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 2), 1_820);
37320        // Fetch concurrency 8: 8000 funded; the curve clamps at the
37321        // measured plateau — realized speedup saturates near the box's
37322        // physical core count, however many permits exist.
37323        assert_eq!(probe_seek_concurrency_milli(true, 115, 24_576, 8), 4_050);
37324        // Zero seeks (the no-broadcast mirror road): no chunks exist, so
37325        // the divisor stays sequential rather than collapsing to zero.
37326        assert_eq!(probe_seek_concurrency_milli(true, 0, 24_576, 3), 1000);
37327        assert_eq!(probe_seek_concurrency_milli(true, 115, 0, 3), 1000);
37328    }
37329
37330    #[test]
37331    fn firing_scan_probe_is_stamped_driver_is_not() {
37332        // Pin the default fetch concurrency: the stamp walk's batch
37333        // credit reads the process-global, and an ambient
37334        // WARATAH_QUERY_FETCH_CONCURRENCY=0/1 would price sequentially
37335        // and flip this fixture's expected stamps.
37336        let _fc = crate::context::FetchConcurrencyPin::set(crate::context::QUERY_FETCH_CONCURRENCY);
37337        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
37338        let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/probe", Some("v"), 50_000));
37339        let mut tree = join(driver, probe, 200_000);
37340        let profile = known_profile(200_000);
37341        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37342        let PlanNode::Join { left, right, .. } = &tree else {
37343            panic!("expected Join, got {tree:?}")
37344        };
37345        assert!(
37346            is_stamped(right),
37347            "the firing probe stamps (carrying its arm estimate)"
37348        );
37349        assert!(!is_stamped(left), "the driver never stamps");
37350    }
37351
37352    /// Sliced coherence: beneath a Slice the cursor runs every join
37353    /// per-page — the slice star through its own demand-priced `detect` —
37354    /// so no batch fetch concurrency exists to price and the stamp pass
37355    /// suppresses the divisor ENTIRELY, star heads included (the head's
37356    /// `star_arms` stamp describes the eager road; on the slice path no
37357    /// divisor follows it). The fixture is the flagship-class chain at
37358    /// tree level — driver 115 exact pages of distinct keys (2,826,240
37359    /// rows over the same domain), arm 9,500,000 rows at one row per
37360    /// key — so the arithmetic is divisor-decisive under the pinned
37361    /// rates (SEEK_EQUIV 4.2, matched-row 1.4): sequential prices
37362    /// Build (115 × (24,576×4.2 + 24,576×1.4) ≈ 15.8G ≥ 1.5 × 9.5M =
37363    /// 14.25G) while either realized credit flips the verdict to PerPage
37364    /// (two-arm: funded 1.5 → realized 1.41, ≈ 12.4G; single-arm: funded
37365    /// 3.0 → realized 2.42, ≈ 8.9G). The eager twins therefore stay
37366    /// unstamped and both sliced twins stamp, pinning the suppression and
37367    /// the eager divisor in one table.
37368    #[test]
37369    fn sliced_stamp_suppresses_the_divisor_star_included() {
37370        // Pin the default fetch concurrency: the eager twins' expected
37371        // unstamped state depends on the batch credit, which an ambient
37372        // WARATAH_QUERY_FETCH_CONCURRENCY=0/1 would remove.
37373        let _fc = crate::context::FetchConcurrencyPin::set(crate::context::QUERY_FETCH_CONCURRENCY);
37374        let mut profile = StatsProfile::default();
37375        for (pred, rows, keys) in [
37376            ("http://ex/driver", 2_826_240u64, 2_826_240u128),
37377            ("http://ex/probe", 9_500_000, 9_500_000),
37378        ] {
37379            let mut hll = waratah_stats::HyperLogLog::default_params();
37380            for i in 0..keys {
37381                hll.add(i);
37382            }
37383            profile
37384                .subjects_per_predicate
37385                .insert(waratah_storage::StrHash::new(pred), hll);
37386            profile
37387                .predicate_counts
37388                .insert(waratah_storage::StrHash::new(pred), rows);
37389        }
37390        profile.total_puts = 12_326_240;
37391        let make_tree = |star_arms: Option<u8>| {
37392            let driver = PlanNode::Scan(var_scan(
37393                Some("s"),
37394                "http://ex/driver",
37395                Some("o"),
37396                2_826_240,
37397            ));
37398            let probe =
37399                PlanNode::Scan(var_scan(Some("s"), "http://ex/probe", Some("v"), 9_500_000));
37400            let mut tree = join(driver, probe, 9_500_000);
37401            if let PlanNode::Join { meta, .. } = &mut tree {
37402                meta.star_arms = star_arms;
37403            }
37404            tree
37405        };
37406        let probe_is_stamped = |tree: &PlanNode| match tree {
37407            PlanNode::Join { right, .. } => is_stamped(right),
37408            _ => panic!("expected Join, got {tree:?}"),
37409        };
37410
37411        // Eager single-arm: the single-arm batch share (÷3) prices PerPage — no stamp.
37412        let mut tree = make_tree(None);
37413        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37414        assert!(
37415            !probe_is_stamped(&tree),
37416            "eager single-arm: the single-arm share flips the verdict to PerPage"
37417        );
37418
37419        // Eager star: the two-arm share (÷2) prices Probe — no stamp.
37420        let mut tree = make_tree(Some(2));
37421        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37422        assert!(
37423            !probe_is_stamped(&tree),
37424            "eager star: the two-arm share flips the verdict to PerPage"
37425        );
37426
37427        // Sliced serial: the divisor is suppressed — the sequential price
37428        // the slice cursor actually runs — and it stamps FetchOnce.
37429        let mut tree = make_tree(None);
37430        restamp_fetch_once(&mut tree, Some(&profile), None, true);
37431        assert!(
37432            probe_is_stamped(&tree),
37433            "sliced single-arm: sequential price, the divisor must not fire"
37434        );
37435
37436        // Sliced star: same suppression — the star stamp alone must not
37437        // leak a divisor onto the slice path.
37438        let mut tree = make_tree(Some(2));
37439        restamp_fetch_once(&mut tree, Some(&profile), None, true);
37440        assert!(
37441            probe_is_stamped(&tree),
37442            "sliced star: sequential price, the star stamp must not restore the divisor"
37443        );
37444    }
37445
37446    /// A FetchOnce verdict writes the mark at ANY arm size — there is no
37447    /// per-query build budget to decline it. WHERE the build lives is the
37448    /// executor's per-join decision (`join_should_spill` degrades an
37449    /// over-memory arm to cached Grace partitions), so the planner keeps
37450    /// no second, row-based RAM opinion. This arm (2M rows) sits far over
37451    /// the old 1.57M-row budget that silently discarded exactly this
37452    /// stamp while logging `-> fetch-once`.
37453    #[test]
37454    fn build_verdict_writes_the_mark_at_any_arm_size() {
37455        // Pin the default fetch concurrency: the verdict's batch credit
37456        // reads the process-global, and an ambient
37457        // WARATAH_QUERY_FETCH_CONCURRENCY=0/1 would price this fixture
37458        // sequentially and change the mark.
37459        let _fc = crate::context::FetchConcurrencyPin::set(crate::context::QUERY_FETCH_CONCURRENCY);
37460        // 1M-row driver over a 1M-key domain: 41 pages of 24,576 distinct
37461        // keys — the per-page lists do not cover the 200k-key probe
37462        // domain, so per-page mode prices as 41 pages × (24,576 seeks ×
37463        // 4.2 + 245,760 matched × 1.4) ≈ 18.3M row-equivalents ≥
37464        // 1.4 × 2M (the margin): FetchOnce.
37465        // Batch-credit note: this fixture is a plain two-pattern join,
37466        // which the divisor prices at the single-arm share (funded fetch
37467        // concurrency 3 → the measured curve's 2.42; 41 chunks, so the
37468        // chunk gate does not bite). Matched rows dominate the price —
37469        // the 200k-key probe domain carries ≈10 rows per key, so
37470        // matched/page ≈ 245,760 — and the divisor divides only the seek
37471        // term, so the batched price, 41 × (24,576×4.2/2.42 +
37472        // 245,760×1.4) ≈ 15.9M, still clears the 2.8M trigger: the
37473        // test's intent (a big arm stamps FetchOnce whatever the road)
37474        // survives under the general road's honest pricing, instead of
37475        // pinning the pre-batch sequential number.
37476        let driver = PlanNode::Scan(var_scan(
37477            Some("s"),
37478            "http://ex/driver",
37479            Some("o"),
37480            1_000_000,
37481        ));
37482        let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/huge", Some("v"), 2_000_000));
37483        let mut tree = join(driver, probe, 1_000_000);
37484        let mut profile = StatsProfile::default();
37485        for (pred, rows, keys) in [
37486            ("http://ex/driver", 1_000_000u64, 1_000_000u128),
37487            ("http://ex/huge", 2_000_000, 200_000),
37488        ] {
37489            let mut hll = waratah_stats::HyperLogLog::default_params();
37490            for i in 0..keys {
37491                hll.add(i);
37492            }
37493            profile
37494                .subjects_per_predicate
37495                .insert(waratah_storage::StrHash::new(pred), hll);
37496            profile
37497                .predicate_counts
37498                .insert(waratah_storage::StrHash::new(pred), rows);
37499        }
37500        profile.total_puts = 3_000_000;
37501        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37502        let PlanNode::Join { right, .. } = &tree else {
37503            panic!("expected Join, got {tree:?}")
37504        };
37505        // The carried value is the profile estimate (sketch-derived, not
37506        // the exact ingested count) — assert presence and that the arm
37507        // dwarfs the old 1.57M-row budget, which silently discarded this
37508        // exact stamp while logging `-> fetch-once`.
37509        let stamp = stamp_of(right).expect("scan arm").expect("stamped");
37510        assert!(
37511            stamp > 1_572_864,
37512            "a FetchOnce verdict writes the mark whatever the arm size; the executor picks residency (got {stamp})"
37513        );
37514    }
37515
37516    /// Keyed-join helper for the containing-push tests: `join()` hardcodes
37517    /// the ?s key, and these fixtures key on ?geom / ?feature.
37518    fn join_on(left: PlanNode, right: PlanNode, produced: u64, key: &str) -> PlanNode {
37519        PlanNode::Join {
37520            left: Box::new(left),
37521            right: Box::new(right),
37522            hash_keys: vec![Variable::new(key).unwrap()],
37523            probe_key_domains: Vec::new(),
37524            probe_key_overlap_milli: Vec::new(),
37525            rhs_hostable_keys: Vec::new().into(),
37526            meta: JoinMeta {
37527                semi_gate: None,
37528                star_arms: None,
37529                strategy: JoinStrategy::Broadcast,
37530                produced_row_count_estimate: produced,
37531                own_push_removed_row_count_estimate: produced,
37532            },
37533        }
37534    }
37535
37536    /// Sydney-shaped stamp fixture: an inner join keyed ?feature whose
37537    /// driver hosts the ancestor key in its object slot
37538    /// (`?feature <hasGeom> ?geom`) beside a huge type arm
37539    /// (`?feature <type> ?v`), an outer cluster driver
37540    /// (`?s <cluster> ?geom`) paging ?geom lists at ~24K distinct values
37541    /// per page over a ~350K-key domain, and a control arm
37542    /// (`?feature <other> ?x`) that hosts no ?geom at all.
37543    fn push_conditioned_profile() -> StatsProfile {
37544        let mut profile = StatsProfile::default();
37545        for (pred, rows, subject_keys, object_keys) in [
37546            (
37547                "http://ex/hasGeom",
37548                8_000_000u64,
37549                7_950_000u128,
37550                Some(8_000_000u128),
37551            ),
37552            ("http://ex/type", 7_900_000, 7_900_000, None),
37553            ("http://ex/cluster", 360_000, 360_000, Some(350_000u128)),
37554            ("http://ex/other", 8_000_000, 7_950_000, None),
37555        ] {
37556            let mut subjects = waratah_stats::HyperLogLog::default_params();
37557            for i in 0..subject_keys {
37558                subjects.add(i);
37559            }
37560            profile
37561                .subjects_per_predicate
37562                .insert(waratah_storage::StrHash::new(pred), subjects);
37563            if let Some(object_keys) = object_keys {
37564                let mut objects = waratah_stats::HyperLogLog::default_params();
37565                for i in 0..object_keys {
37566                    objects.add(i);
37567                }
37568                profile
37569                    .objects_per_predicate
37570                    .insert(waratah_storage::StrHash::new(pred), objects);
37571            }
37572            profile
37573                .predicate_counts
37574                .insert(waratah_storage::StrHash::new(pred), rows);
37575        }
37576        profile.total_puts = 16_260_000;
37577        profile
37578    }
37579
37580    /// The inner sydney-shaped join: hasGeom driver ⋈ (keyed ?feature) ⋈
37581    /// the huge type arm.
37582    fn contained_type_join() -> PlanNode {
37583        let driver = PlanNode::Scan(var_scan(
37584            Some("feature"),
37585            "http://ex/hasGeom",
37586            Some("geom"),
37587            8_000_000,
37588        ));
37589        let probe = PlanNode::Scan(var_scan(
37590            Some("feature"),
37591            "http://ex/type",
37592            Some("v"),
37593            7_900_000,
37594        ));
37595        join_on(driver, probe, 8_000_000, "feature")
37596    }
37597
37598    /// PIN — the standalone geometry stamps FetchOnce: the 8M-row hasGeom
37599    /// driver streams ~326 pages × ~24.4K seeks against one 7.9M-row
37600    /// type read (326 × 24.4K × 4.6 ≈ 36.6M ≥ 1.5 × 7.9M) — the same
37601    /// near-tie Build economics as the sydney Feature arm's original
37602    /// stamp. Without this pin the unstamp tests below could pass by
37603    /// fixture accident (an arm that never stamps standalone).
37604    #[test]
37605    fn contained_type_join_stamps_build_standalone() {
37606        let mut tree = contained_type_join();
37607        let profile = push_conditioned_profile();
37608        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37609        let PlanNode::Join { right, .. } = &tree else {
37610            panic!("expected Join, got {tree:?}")
37611        };
37612        assert!(
37613            is_stamped(right),
37614            "standalone geometry: the many-page driver verdict stamps FetchOnce"
37615        );
37616    }
37617
37618    /// THE FIX — the same inner join, wrapped as the keyed probe SUBTREE
37619    /// of an outer join whose driver pages ?geom lists, no longer
37620    /// stamps: the containing push bounds the inner driver to ~one page
37621    /// of keyed answer (1 page × ~24K seeks ≪ margin × 7.9M flips the
37622    /// same verdict to PerPage), so the executor's default keyed road —
37623    /// per-page ?feature lists into the type arm — runs instead of a
37624    /// whole-arm read repeated once per execution.
37625    #[test]
37626    fn containing_push_unstamps_the_hosting_contained_join() {
37627        let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37628        let mut tree = join_on(cluster, contained_type_join(), 360_000, "geom");
37629        let profile = push_conditioned_profile();
37630        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37631        let PlanNode::Join { right: subtree, .. } = &tree else {
37632            panic!("expected Join, got {tree:?}")
37633        };
37634        let PlanNode::Join {
37635            right: inner_probe, ..
37636        } = &**subtree
37637        else {
37638            panic!("expected subtree Join, got {subtree:?}")
37639        };
37640        assert!(
37641            !is_stamped(inner_probe),
37642            "the containing push re-geometries the inner driver: no Build stamp, the keyed probe road runs"
37643        );
37644    }
37645
37646    /// CONTROL — the same wrap keyed on ?geom, but the inner driver does
37647    /// NOT host ?geom (`?feature <other> ?x`): the bound never lands
37648    /// (`probe_scan_has_key` gate), the standalone geometry stands, and
37649    /// the Build stamp survives. The carried context is just the per-page
37650    /// key width (`pushed_val_count`); the gate is what keeps this inner driver
37651    /// standalone — the host-side domain-fallback path is pinned
37652    /// separately by the `containing_push_bound_*` tests.
37653    #[test]
37654    fn non_hosting_contained_driver_keeps_the_stamp() {
37655        let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37656        let driver = PlanNode::Scan(var_scan(
37657            Some("feature"),
37658            "http://ex/other",
37659            Some("x"),
37660            8_000_000,
37661        ));
37662        let probe = PlanNode::Scan(var_scan(
37663            Some("feature"),
37664            "http://ex/type",
37665            Some("v"),
37666            7_900_000,
37667        ));
37668        let subtree = join_on(driver, probe, 8_000_000, "feature");
37669        let mut tree = join_on(cluster, subtree, 360_000, "geom");
37670        let profile = push_conditioned_profile();
37671        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37672        let PlanNode::Join { right: subtree, .. } = &tree else {
37673            panic!("expected Join, got {tree:?}")
37674        };
37675        let PlanNode::Join {
37676            right: inner_probe, ..
37677        } = &**subtree
37678        else {
37679            panic!("expected subtree Join, got {subtree:?}")
37680        };
37681        assert!(
37682            is_stamped(inner_probe),
37683            "a containing push the driver cannot host never conditions: the standalone Build stands"
37684        );
37685    }
37686
37687    /// The counterexample end to end, as a stamp
37688    /// outcome. The subtree `hasGeom ⋈ type ⋈ rare` collapses to a tiny
37689    /// output (the hand meta: 30K), but its `hasGeom` driver reuses a
37690    /// ~98K key domain across 8M rows, so the REAL keyed answer per
37691    /// ancestor page is ~2M rows. Pre-fix, the bound was the subtree
37692    /// OUTPUT (~30K → clamped to a 1-page geometry → price ≈ 24.7M milli
37693    /// < the 1.5B threshold = margin 1.5 × the rare arm's 1M rows) and
37694    /// the rare arm ran un-stamped — per-page drains. The driver-derived
37695    /// bound prices ~2M (81 pages → price ≈ 2.0B milli ≥ 1.5B) and the
37696    /// Build stamp SURVIVES, which is the honest road: the keyed answer
37697    /// really is twice the whole read per page.
37698    #[test]
37699    fn selective_tail_subtree_keeps_the_honest_driver_bound() {
37700        let mut profile = push_conditioned_profile();
37701        let mut rare_subjects = waratah_stats::HyperLogLog::default_params();
37702        for i in 0..1_000_000u128 {
37703            rare_subjects.add(i);
37704        }
37705        profile.subjects_per_predicate.insert(
37706            waratah_storage::StrHash::new("http://ex/rare"),
37707            rare_subjects,
37708        );
37709        profile
37710            .predicate_counts
37711            .insert(waratah_storage::StrHash::new("http://ex/rare"), 1_000_000);
37712        // The hasGeom OBJECT domain is the dense one (~98K distinct geoms
37713        // over 8M rows) — swap the sketch in over the fixture default.
37714        let mut dense_geoms = waratah_stats::HyperLogLog::default_params();
37715        for i in 0..98_000u128 {
37716            dense_geoms.add(i);
37717        }
37718        profile.objects_per_predicate.insert(
37719            waratah_storage::StrHash::new("http://ex/hasGeom"),
37720            dense_geoms,
37721        );
37722
37723        let has_geom = PlanNode::Scan(var_scan(
37724            Some("feature"),
37725            "http://ex/hasGeom",
37726            Some("geom"),
37727            8_000_000,
37728        ));
37729        let type_scan = PlanNode::Scan(var_scan(
37730            Some("feature"),
37731            "http://ex/type",
37732            Some("v"),
37733            7_900_000,
37734        ));
37735        let rare_scan = PlanNode::Scan(var_scan(
37736            Some("feature"),
37737            "http://ex/rare",
37738            Some("r"),
37739            1_000_000,
37740        ));
37741        let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37742        let inner = join_on(has_geom, type_scan, 7_900_000, "feature");
37743        // The selective tail: the subtree's OUTPUT collapses to 30K while
37744        // the hasGeom keyed return stays ~2M per page.
37745        let subtree = join_on(inner, rare_scan, 30_000, "feature");
37746        let mut tree = join_on(cluster, subtree, 360_000, "geom");
37747        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37748        let PlanNode::Join { right: subtree, .. } = &tree else {
37749            panic!("expected Join, got {tree:?}")
37750        };
37751        let PlanNode::Join { right: rare, .. } = &**subtree else {
37752            panic!("expected subtree Join, got {subtree:?}")
37753        };
37754        assert!(
37755            is_stamped(rare),
37756            "the honest ~2M per-page bound prices the keyed road above the margin: the Build stamp stands"
37757        );
37758    }
37759
37760    /// The GATE, isolated. The subtree's
37761    /// driver is a VALUES row set: the runtime cannot push-filter
37762    /// computed rows (there are no scans to filter), so
37763    /// `probe_scan_has_key` refuses it — but `distinct_key_count` gives
37764    /// the derivation an exact domain, so it WOULD condition this join
37765    /// if the gate were gone (bound ≈ 24.6K → one page → price ≈ 24.7M
37766    /// milli < the 45M threshold → per-page, un-stamped; verified by
37767    /// deleting the gate). With the gate, the standalone
37768    /// 60K-row geometry prices 3 pages ≈ 74M milli ≥ 45M and the Build
37769    /// stamp stands — on the gate alone. (An earlier fixture used a
37770    /// LeftJoin driver; LeftJoins are push-transparent to the
37771    /// containing push, so a Values driver took over the divergent case.)
37772    #[test]
37773    fn values_driver_with_known_domain_keeps_the_stamp() {
37774        let values = PlanNode::Values(ValuesOp {
37775            variables: vec![Variable::new("g").unwrap()],
37776            rows: (0..60_000)
37777                .map(|i| {
37778                    vec![Some(EncodedTerm::from(
37779                        &NamedNode::new(format!("http://ex/g{i}")).unwrap(),
37780                    ))]
37781                })
37782                .collect(),
37783            strings: Vec::new(),
37784            blobs: Vec::new(),
37785        });
37786        let mut profile = push_conditioned_profile();
37787        let mut vtype_subjects = waratah_stats::HyperLogLog::default_params();
37788        for i in 0..30_000u128 {
37789            vtype_subjects.add(i);
37790        }
37791        profile.subjects_per_predicate.insert(
37792            waratah_storage::StrHash::new("http://ex/vtype"),
37793            vtype_subjects,
37794        );
37795        profile
37796            .predicate_counts
37797            .insert(waratah_storage::StrHash::new("http://ex/vtype"), 30_000);
37798        let vtype = PlanNode::Scan(var_scan(Some("g"), "http://ex/vtype", Some("v"), 30_000));
37799        let subtree = join_on(values, vtype, 30_000, "g");
37800        let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37801        let mut tree = join_on(cluster, subtree, 360_000, "g");
37802        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37803        let PlanNode::Join { right: subtree, .. } = &tree else {
37804            panic!("expected Join, got {tree:?}")
37805        };
37806        let PlanNode::Join { right: vtype, .. } = &**subtree else {
37807            panic!("expected subtree Join, got {subtree:?}")
37808        };
37809        assert!(
37810            is_stamped(vtype),
37811            "a Values driver cannot be push-filtered: the standalone Build stamp stands on the gate alone"
37812        );
37813    }
37814
37815    /// The containing push crosses an
37816    /// OPTIONAL's REQUIRED arm: at runtime the required side runs with
37817    /// the ancestor's pushed stack (eval_eager's LeftJoin arm), so the
37818    /// conditioned geometry must reach it too. The conditioned bound
37819    /// (~24.6K → one page → price ≈ 24.7M milli) sits far under the
37820    /// threshold (1.5 × 7.9M = 11.85B milli) and withdraws the stamp the
37821    /// pre-fix walk wrote — it stopped the context at the LeftJoin and
37822    /// priced the chain at 326 standalone pages (price ≈ 8B milli ≥
37823    /// threshold → fetch-once, honored per ancestor page: the stale-stamp
37824    /// defect, surviving in this corner until now).
37825    #[test]
37826    fn containing_push_crosses_an_optional_required_arm() {
37827        let has_geom = PlanNode::Scan(var_scan(
37828            Some("feature"),
37829            "http://ex/hasGeom",
37830            Some("geom"),
37831            8_000_000,
37832        ));
37833        let type_scan = PlanNode::Scan(var_scan(
37834            Some("feature"),
37835            "http://ex/type",
37836            Some("v"),
37837            7_900_000,
37838        ));
37839        let label = PlanNode::Scan(var_scan(
37840            Some("feature"),
37841            "http://ex/label",
37842            Some("l"),
37843            1_000,
37844        ));
37845        let required = join_on(has_geom, type_scan, 7_900_000, "feature");
37846        let leftjoin = PlanNode::LeftJoin {
37847            left: Box::new(required),
37848            right: Box::new(label),
37849            hash_keys: vec![Variable::new("feature").unwrap()],
37850            early_filter: None,
37851            residual_filter: None,
37852            probe_key_domains: Vec::new(),
37853            probe_key_overlap_milli: Vec::new(),
37854            meta: LeftJoinMeta {
37855                produced_row_count_estimate: 7_900_000,
37856                own_push_removed_row_count_estimate: 7_900_000,
37857            },
37858        };
37859        let cluster = PlanNode::Scan(var_scan(None, "http://ex/cluster", Some("geom"), 360_000));
37860        let mut tree = join_on(cluster, leftjoin, 360_000, "geom");
37861        restamp_fetch_once(&mut tree, Some(&push_conditioned_profile()), None, false);
37862        let PlanNode::Join { right: subtree, .. } = &tree else {
37863            panic!("expected Join, got {tree:?}")
37864        };
37865        let PlanNode::LeftJoin { left: required, .. } = &**subtree else {
37866            panic!("expected subtree LeftJoin, got {subtree:?}")
37867        };
37868        let PlanNode::Join {
37869            right: type_arm, ..
37870        } = &**required
37871        else {
37872            panic!("expected required-side Join, got {required:?}")
37873        };
37874        assert!(
37875            !is_stamped(type_arm),
37876            "the containing push reaches the OPTIONAL's required arm: the keyed road runs, no whole-read stamp"
37877        );
37878    }
37879
37880    /// OPTIONAL rights never stamp: `execute_left_join` has no built slot
37881    /// (Phase 2b) — a stamp it cannot honor must not exist.
37882    #[test]
37883    fn optional_arms_never_stamp() {
37884        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
37885        let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/probe", Some("v"), 50_000));
37886        let mut tree = PlanNode::LeftJoin {
37887            left: Box::new(driver),
37888            right: Box::new(probe),
37889            hash_keys: vec![Variable::new("s").unwrap()],
37890            early_filter: None,
37891            residual_filter: None,
37892            probe_key_domains: Vec::new(),
37893            probe_key_overlap_milli: Vec::new(),
37894            meta: LeftJoinMeta {
37895                produced_row_count_estimate: 0,
37896                own_push_removed_row_count_estimate: 0,
37897            },
37898        };
37899        restamp_fetch_once(&mut tree, None, None, false);
37900        let PlanNode::LeftJoin { right, .. } = &tree else {
37901            panic!("expected LeftJoin, got {tree:?}")
37902        };
37903        assert!(
37904            !is_stamped(right),
37905            "an OPTIONAL arm has no built slot — never stamped"
37906        );
37907    }
37908
37909    /// A join keyed solely on a graph-position variable can never consume
37910    /// a stamp: the runtime broadcasts a key list only to a
37911    /// Subject/Predicate/Object slot (`first_slot_of`), so the arm probes
37912    /// unfiltered regardless. The stamp pass must not write the mark —
37913    /// an inert stamp suppresses memoization and asserts a build the
37914    /// executor never runs. The pricing machinery WOULD fire on
37915    /// this shape absent the guard (the Values driver's `?g` domain is
37916    /// sketch-known, the arm's estimate is profile-backed: 1 page ×
37917    /// (30 seeks × 3.6 + 200k matched) ≈ 200M milli ≥ 1,500 × 50,000), so
37918    /// this pins the guard, not the verdict.
37919    #[test]
37920    fn unbroadcastable_graph_key_joins_are_never_stamped() {
37921        let driver = PlanNode::Values(ValuesOp {
37922            variables: vec![Variable::new("g").unwrap()],
37923            rows: (0..30)
37924                .map(|i| {
37925                    vec![Some(EncodedTerm::from(
37926                        &NamedNode::new(format!("http://ex/g{i}")).unwrap(),
37927                    ))]
37928                })
37929                .collect(),
37930            strings: Vec::new(),
37931            blobs: Vec::new(),
37932        });
37933        let mut probe = var_scan(Some("s"), "http://ex/a", Some("v"), 200_000);
37934        probe.graph = Some(Variable::new("g").unwrap());
37935        let mut tree = PlanNode::Join {
37936            left: Box::new(driver),
37937            right: Box::new(PlanNode::Scan(probe)),
37938            hash_keys: vec![Variable::new("g").unwrap()],
37939            probe_key_domains: Vec::new(),
37940            probe_key_overlap_milli: Vec::new(),
37941            rhs_hostable_keys: Vec::new().into(),
37942            meta: JoinMeta {
37943                semi_gate: None,
37944                star_arms: None,
37945                strategy: JoinStrategy::Broadcast,
37946                produced_row_count_estimate: 200_000,
37947                own_push_removed_row_count_estimate: 200_000,
37948            },
37949        };
37950        let profile = known_profile(200_000);
37951        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37952        let PlanNode::Join { right, .. } = &tree else {
37953            panic!("expected Join, got {tree:?}")
37954        };
37955        assert!(
37956            !is_stamped(right),
37957            "a graph-position key can never broadcast a list: no stamp"
37958        );
37959    }
37960
37961    /// The guard's contrast: the same Values-driver shape with the key
37962    /// hosted on a shippable slot stamps exactly as before — the guard
37963    /// only excludes keys the runtime cannot broadcast.
37964    #[test]
37965    fn hosted_keys_still_stamp_through_a_values_driver() {
37966        let driver = PlanNode::Values(ValuesOp {
37967            variables: vec![Variable::new("s").unwrap()],
37968            rows: (0..60_000)
37969                .map(|i| {
37970                    vec![Some(EncodedTerm::from(
37971                        &NamedNode::new(format!("http://ex/s{i}")).unwrap(),
37972                    ))]
37973                })
37974                .collect(),
37975            strings: Vec::new(),
37976            blobs: Vec::new(),
37977        });
37978        let probe = var_scan(Some("s"), "http://ex/a", Some("v"), 50_000);
37979        let mut tree = PlanNode::Join {
37980            left: Box::new(driver),
37981            right: Box::new(PlanNode::Scan(probe)),
37982            hash_keys: vec![Variable::new("s").unwrap()],
37983            probe_key_domains: Vec::new(),
37984            probe_key_overlap_milli: Vec::new(),
37985            rhs_hostable_keys: Vec::new().into(),
37986            meta: JoinMeta {
37987                semi_gate: None,
37988                star_arms: None,
37989                strategy: JoinStrategy::Broadcast,
37990                produced_row_count_estimate: 50_000,
37991                own_push_removed_row_count_estimate: 50_000,
37992            },
37993        };
37994        let profile = known_profile(200_000);
37995        restamp_fetch_once(&mut tree, Some(&profile), None, false);
37996        let PlanNode::Join { right, .. } = &tree else {
37997            panic!("expected Join, got {tree:?}")
37998        };
37999        assert!(
38000            is_stamped(right),
38001            "a hosted key stamps through a Values driver"
38002        );
38003    }
38004
38005    /// An all-dropped probe arm — every hash key a covered push
38006    /// and `coverage_drop_allowed` granted — executes ONCE at runtime (the
38007    /// first fill feeds the built slot; every later batch reuses it), and
38008    /// the cost model's coverage road prices exactly that: one whole read. The
38009    /// old stamp path priced the same shape through
38010    /// `probe_broadcast_price`'s no-broadcast fallback, whose per-page
38011    /// contract the verdict scales by pages: 3 pages × 2,000k milli ≥ 1.5
38012    /// × 2,000k fired Build and suppressed the memo — for a road the
38013    /// runtime cannot take. The guard declines before any pricing: no
38014    /// stamp.
38015    #[test]
38016    fn all_dropped_probe_arms_are_never_stamped() {
38017        // 24k-row driver over a 2k-key domain it fully shares with the
38018        // probe: one page's list carries the whole probe vocabulary
38019        // (2,000 distinct ≥ 0.9 x 2,000), and the 2,000-row arm fits the
38020        // memo entry limit (SCAN_MEMO_MAX_ENTRY_ROWS), so the
38021        // amortization guard grants the drop.
38022        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 24_000));
38023        let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/tiny", Some("v"), 2_000));
38024        let mut tree = join(driver, probe, 24_000);
38025        let mut profile = StatsProfile::default();
38026        // Both predicates sketch the SAME subject vocabulary — full
38027        // containment (r = 1000), the regime where the count rule is
38028        // sound and the all-dropped shape it priced is real. Nested or
38029        // disjoint vocabularies (the containment stamp's actual cases)
38030        // would keep the push here, and the fixture would test a
38031        // different shape than its name claims.
38032        for (pred, rows, keys) in [
38033            ("http://ex/driver", 24_000u64, 2_000u128),
38034            ("http://ex/tiny", 2_000, 2_000),
38035        ] {
38036            let mut hll = waratah_stats::HyperLogLog::default_params();
38037            for i in 0..keys {
38038                hll.add(i);
38039            }
38040            profile
38041                .subjects_per_predicate
38042                .insert(waratah_storage::StrHash::new(pred), hll);
38043            profile
38044                .predicate_counts
38045                .insert(waratah_storage::StrHash::new(pred), rows);
38046        }
38047        profile.total_puts = 80_000;
38048        restamp_fetch_once(&mut tree, Some(&profile), None, false);
38049        let PlanNode::Join { right, .. } = &tree else {
38050            panic!("expected Join, got {tree:?}")
38051        };
38052        assert!(
38053            !is_stamped(right),
38054            "an all-dropped probe executes once via the built slot: no stamp"
38055        );
38056    }
38057
38058    /// Pricing-cluster follow-up: a NON-EMPTY profile that never sketched
38059    /// this pattern's predicate estimates the arm as 1 row —
38060    /// `estimate_pattern` reports a never-observed predicate as 1, not
38061    /// unknown. The gate must refuse the stamp exactly as it does for a
38062    /// missing profile: pre-fix, this shape stamped Build on
38063    /// whole_read_rows = 1 and the executor's bail-out was the only thing
38064    /// containing the drain.
38065    #[test]
38066    fn sparse_profile_without_this_predicate_never_stamps() {
38067        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
38068        // "http://ex/unsketched" is deliberately absent from known_profile.
38069        let probe = PlanNode::Scan(var_scan(
38070            Some("s"),
38071            "http://ex/unsketched",
38072            Some("v"),
38073            50_000,
38074        ));
38075        let mut tree = join(driver, probe, 200_000);
38076        let profile = known_profile(200_000);
38077        restamp_fetch_once(&mut tree, Some(&profile), None, false);
38078        let PlanNode::Join { right, .. } = &tree else {
38079            panic!("expected Join, got {tree:?}")
38080        };
38081        assert!(
38082            !is_stamped(right),
38083            "a never-observed predicate estimates as 1 row: the gate must refuse the stamp"
38084        );
38085    }
38086
38087    /// E1: a dead-column join is promoted to `Semi` only when the fetch-once
38088    /// verdict already chose the whole right-side read and the right scan is
38089    /// key-unique. Key-uniqueness is what keeps the semi road row-identical:
38090    /// a repeated right key multiplies every left column, and a plain `COUNT`
38091    /// of a left column observes that multiplication, so a bag mark on the
38092    /// key alone is not a proof.
38093    #[test]
38094    fn semi_promotion_requires_key_unique_and_the_fetch_once_verdict() {
38095        let left = || PlanNode::Scan(var_scan(Some("s"), "http://ex/union", Some("v"), 2_000_000));
38096
38097        // Right: ?s <datasetKind> <record> — one row per key, so the key is
38098        // unique whatever the bag mark says.
38099        let ground_right = |stamped: bool, bag: BagMark| {
38100            let mut scan = var_scan(Some("s"), "http://ex/datasetKind", None, 328_500);
38101            scan.pattern.object = Some(EncodedTerm::from(
38102                &NamedNode::new("http://ex/record").unwrap(),
38103            ));
38104            scan.fetch_once = stamped.then_some(328_500);
38105            scan.marks = vec![(var("s"), Liveness::Live, bag)];
38106            PlanNode::Scan(scan)
38107        };
38108
38109        // Right: ?s <kind> ?o — a variable object means one key can repeat
38110        // across rows. No bag mark makes that safe: the semi join removes the
38111        // right's multiplicity from every left column.
38112        let variable_right = |stamped: bool, bag: BagMark, object_liveness: Liveness| {
38113            let mut scan = var_scan(Some("s"), "http://ex/datasetKind", Some("o"), 328_500);
38114            scan.fetch_once = stamped.then_some(328_500);
38115            scan.marks = vec![
38116                (var("s"), Liveness::Live, bag),
38117                (var("o"), object_liveness, BagMark::Insensitive),
38118            ];
38119            PlanNode::Scan(scan)
38120        };
38121
38122        // This is also the `COUNT(*)` shape: a key-unique right produces at
38123        // most one row per key, so the semi join leaves the row count
38124        // identical and `COUNT(*)` cannot observe a difference.
38125        let mut key_unique = join(left(), ground_right(true, BagMark::Sensitive), 328_500);
38126        stamp_semi_join_strategy(&mut key_unique, None, false, None, &[]);
38127        assert_eq!(
38128            strategy_of(&key_unique),
38129            JoinStrategy::SemiScan,
38130            "a key-unique stamped right is the safe promotion"
38131        );
38132
38133        let mut unstamped = join(left(), ground_right(false, BagMark::Insensitive), 328_500);
38134        stamp_semi_join_strategy(&mut unstamped, None, false, None, &[]);
38135        assert_eq!(
38136            strategy_of(&unstamped),
38137            JoinStrategy::Broadcast,
38138            "the promotion must read the fetch-once verdict, not invent one"
38139        );
38140
38141        let mut payload = join(
38142            left(),
38143            variable_right(true, BagMark::Insensitive, Liveness::Live),
38144            328_500,
38145        );
38146        stamp_semi_join_strategy(&mut payload, None, false, None, &[]);
38147        assert_eq!(
38148            strategy_of(&payload),
38149            JoinStrategy::Broadcast,
38150            "a live right column cannot be replaced by a filter"
38151        );
38152
38153        let mut sensitive = join(
38154            left(),
38155            variable_right(true, BagMark::Sensitive, Liveness::Dead),
38156            328_500,
38157        );
38158        stamp_semi_join_strategy(&mut sensitive, None, false, None, &[]);
38159        assert_eq!(
38160            strategy_of(&sensitive),
38161            JoinStrategy::Broadcast,
38162            "a dead variable object still repeats the key across rows: a plain count sees it"
38163        );
38164
38165        let mut insensitive = join(
38166            left(),
38167            variable_right(true, BagMark::Insensitive, Liveness::Dead),
38168            328_500,
38169        );
38170        stamp_semi_join_strategy(&mut insensitive, None, false, None, &[]);
38171        assert_eq!(
38172            strategy_of(&insensitive),
38173            JoinStrategy::Broadcast,
38174            "a repeated key is not key-unique; a bag-insensitive key alone cannot preserve left row multiplicity"
38175        );
38176
38177        // Plain `COUNT(*)` promotes a dead right payload to `Counted`. The
38178        // right is still non-key-unique (a second name slot), so
38179        // key-uniqueness refuses it; the payload check would also keep the
38180        // counted column out of the key set.
38181        let mut count_star_payload = join(
38182            left(),
38183            variable_right(true, BagMark::Sensitive, Liveness::Counted),
38184            328_500,
38185        );
38186        stamp_semi_join_strategy(&mut count_star_payload, None, false, None, &[]);
38187        assert_eq!(
38188            strategy_of(&count_star_payload),
38189            JoinStrategy::Broadcast,
38190            "a COUNT(*) payload is not key-unique; the Counted mark must not admit it"
38191        );
38192
38193        // A specialized scan returns its own RPC's rows, not the pattern's, so
38194        // neither the payload nor the uniqueness argument describes it.
38195        let mut specialized_right = ground_right(true, BagMark::Insensitive);
38196        if let PlanNode::Scan(scan) = &mut specialized_right {
38197            scan.domain_counts = Some(DomainScanKind::PredicateDomain);
38198        }
38199        let mut specialized = join(left(), specialized_right, 328_500);
38200        stamp_semi_join_strategy(&mut specialized, None, false, None, &[]);
38201        assert_eq!(
38202            strategy_of(&specialized),
38203            JoinStrategy::Broadcast,
38204            "a specialized scan must never become a semi-join key set"
38205        );
38206
38207        // A one-term allow-list is a statically fixed graph: key-unique.
38208        let mut one_graph_right = ground_right(true, BagMark::Sensitive);
38209        if let PlanNode::Scan(scan) = &mut one_graph_right {
38210            scan.graph_filter = Some(GraphFilter::allow([EncodedTerm::from(
38211                &NamedNode::new("http://ex/g1").unwrap(),
38212            )]));
38213        }
38214        let mut one_graph = join(left(), one_graph_right, 328_500);
38215        stamp_semi_join_strategy(&mut one_graph, None, false, None, &[]);
38216        assert_eq!(
38217            strategy_of(&one_graph),
38218            JoinStrategy::SemiScan,
38219            "a one-term allow-list fixes the graph, so the key is unique"
38220        );
38221
38222        // A multi-term allow-list and a block-list can expose the same triple
38223        // in several graphs even with no graph variable.
38224        let mut two_graphs_right = ground_right(true, BagMark::Sensitive);
38225        if let PlanNode::Scan(scan) = &mut two_graphs_right {
38226            scan.graph_filter = Some(GraphFilter::allow([
38227                EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap()),
38228                EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap()),
38229            ]));
38230        }
38231        let mut two_graphs = join(left(), two_graphs_right, 328_500);
38232        stamp_semi_join_strategy(&mut two_graphs, None, false, None, &[]);
38233        assert_eq!(
38234            strategy_of(&two_graphs),
38235            JoinStrategy::Broadcast,
38236            "a multi-term allow-list can expose the key once per graph"
38237        );
38238
38239        let mut blocked_right = ground_right(true, BagMark::Sensitive);
38240        if let PlanNode::Scan(scan) = &mut blocked_right {
38241            scan.graph_filter = Some(GraphFilter::exclude([EncodedTerm::from(
38242                &NamedNode::new("http://ex/g1").unwrap(),
38243            )]));
38244        }
38245        let mut blocked = join(left(), blocked_right, 328_500);
38246        stamp_semi_join_strategy(&mut blocked, None, false, None, &[]);
38247        assert_eq!(
38248            strategy_of(&blocked),
38249            JoinStrategy::Broadcast,
38250            "a block-list leaves every other graph, so the key can repeat"
38251        );
38252    }
38253
38254    /// The key-unique graph guard: a single fixed graph passes; a graph
38255    /// variable alone, a multi-graph allow-list, a block-list, and the
38256    /// default-graph merge do not.
38257    #[test]
38258    fn key_unique_requires_a_fixed_graph() {
38259        let mut scan = var_scan(Some("s"), "http://ex/p", None, 10);
38260        scan.pattern.object = Some(EncodedTerm::from(&NamedNode::new("http://ex/o").unwrap()));
38261        let key = vec![var("s")];
38262        assert!(
38263            scan_is_key_unique(&scan, &key),
38264            "default graph: the key determines the triple"
38265        );
38266
38267        scan.graph_filter = Some(GraphFilter::allow([EncodedTerm::from(
38268            &NamedNode::new("http://ex/g1").unwrap(),
38269        )]));
38270        assert!(
38271            scan_is_key_unique(&scan, &key),
38272            "a one-term allow-list is a fixed graph"
38273        );
38274
38275        scan.graph = Some(var("g"));
38276        assert!(
38277            scan_is_key_unique(&scan, &key),
38278            "a graph variable confined by a one-term allow-list is fixed"
38279        );
38280
38281        scan.graph_filter = Some(GraphFilter::allow([
38282            EncodedTerm::from(&NamedNode::new("http://ex/g1").unwrap()),
38283            EncodedTerm::from(&NamedNode::new("http://ex/g2").unwrap()),
38284        ]));
38285        assert!(
38286            !scan_is_key_unique(&scan, &key),
38287            "a multi-term allow-list can repeat the key across graphs"
38288        );
38289
38290        scan.graph = None;
38291        scan.graph_filter = Some(GraphFilter::exclude([EncodedTerm::from(
38292            &NamedNode::new("http://ex/g1").unwrap(),
38293        )]));
38294        assert!(
38295            !scan_is_key_unique(&scan, &key),
38296            "a block-list leaves other graphs open"
38297        );
38298
38299        scan.graph_filter = None;
38300        scan.merge_default_graph = true;
38301        assert!(
38302            !scan_is_key_unique(&scan, &key),
38303            "the default-graph merge can surface the triple per graph"
38304        );
38305    }
38306
38307    /// The guard's contrast: the same driver against a probe whose domain
38308    /// the page lists do NOT cover (2,048 < 2,700) still prices — seeks +
38309    /// matched per page, 3 pages × (2,048 × 3.6 + 2,048) ≈ 28M
38310    /// row-equivalents ≥ 1.5 × 3k — and stamps exactly as before. The
38311    /// guard only declines the all-dropped shape; partial coverage keeps
38312    /// the first-surviving-key pick.
38313    #[test]
38314    fn uncovered_sibling_of_the_all_dropped_shape_still_stamps() {
38315        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 60_000));
38316        let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/mid", Some("v"), 3_000));
38317        let mut tree = join(driver, probe, 60_000);
38318        let mut profile = StatsProfile::default();
38319        for (pred, rows, keys) in [
38320            ("http://ex/driver", 60_000u64, 5_000u128),
38321            ("http://ex/mid", 3_000, 3_000),
38322        ] {
38323            let mut hll = waratah_stats::HyperLogLog::default_params();
38324            for i in 0..keys {
38325                hll.add(i);
38326            }
38327            profile
38328                .subjects_per_predicate
38329                .insert(waratah_storage::StrHash::new(pred), hll);
38330            profile
38331                .predicate_counts
38332                .insert(waratah_storage::StrHash::new(pred), rows);
38333        }
38334        profile.total_puts = 80_000;
38335        restamp_fetch_once(&mut tree, Some(&profile), None, false);
38336        let PlanNode::Join { right, .. } = &tree else {
38337            panic!("expected Join, got {tree:?}")
38338        };
38339        assert!(
38340            is_stamped(right),
38341            "a not-covered probe prices normally and stamps"
38342        );
38343    }
38344
38345    /// A subtree right arm is never stamped WHOLESALE: the outer join's
38346    /// stamped executor branch exists only for `right.as_scan()`, so a
38347    /// Join-shaped probe keeps its own machinery. The walk still DESCENDS
38348    /// — the subtree's own inner join has a bare-Scan right arm with its
38349    /// own driver, and that arm gets its own stamp.
38350    #[test]
38351    fn subtree_arms_are_descended_not_stamped_wholesale() {
38352        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
38353        // Inner driver `il`: 60k rows over 5k keys → ~2,048-key lists per
38354        // page. Inner probe `ir`: an honest 3k-row arm over a 3k-key
38355        // domain — the lists do not cover (2,048 < 2,700), and 3 pages ×
38356        // (2,048 × 3.6 + 2,048) ≈ 28M row-equivalents ≥ 1.5 × 3k fires.
38357        let inner_left = PlanNode::Scan(var_scan(Some("s"), "http://ex/il", Some("v"), 60_000));
38358        let inner_right = PlanNode::Scan(var_scan(Some("s"), "http://ex/ir", Some("v"), 3_000));
38359        let mut tree = join(driver, join(inner_left, inner_right, 60_000), 200_000);
38360        let profile = known_profile(200_000);
38361        restamp_fetch_once(&mut tree, Some(&profile), None, false);
38362        let PlanNode::Join { right, .. } = &tree else {
38363            panic!("expected Join, got {tree:?}")
38364        };
38365        // The outer probe is a Join — there is no scan to stamp on it;
38366        // the seating comparator's road is gated the same way
38367        // (`probe_stampable`).
38368        assert_eq!(stamp_of(right), None, "a subtree probe is not a scan");
38369        let PlanNode::Join {
38370            right: inner_right, ..
38371        } = right.as_ref()
38372        else {
38373            panic!("expected nested Join, got {right:?}")
38374        };
38375        assert!(
38376            is_stamped(inner_right),
38377            "the subtree's own inner join stamps its bare-Scan arm"
38378        );
38379    }
38380
38381    /// Probe retention (the counter-example shape): a known small driver
38382    /// domain broadcasts tiny lists whose matched fraction of a huge arm is
38383    /// noise — per-page mode wins and nothing stamps.
38384    #[test]
38385    fn cheap_lists_against_a_huge_arm_stay_per_page_mode() {
38386        let mut profile = StatsProfile::default();
38387        let driver_p = waratah_storage::StrHash::new("http://ex/driver");
38388        let probe_p = waratah_storage::StrHash::new("http://ex/probe");
38389        profile.predicate_counts.insert(driver_p, 200_000);
38390        profile.predicate_counts.insert(probe_p, 1_000_000);
38391        let mut driver_hll = waratah_stats::HyperLogLog::default_params();
38392        for i in 0..100 {
38393            driver_hll.add(i);
38394        }
38395        profile.subjects_per_predicate.insert(driver_p, driver_hll);
38396        let mut probe_hll = waratah_stats::HyperLogLog::default_params();
38397        for i in 0..1_000_000u128 {
38398            probe_hll.add(i);
38399        }
38400        profile.subjects_per_predicate.insert(probe_p, probe_hll);
38401        profile.total_puts = 1_200_000;
38402
38403        let driver = PlanNode::Scan(var_scan(Some("s"), "http://ex/driver", Some("o"), 200_000));
38404        let probe = PlanNode::Scan(var_scan(Some("s"), "http://ex/probe", Some("v"), 1_000_000));
38405        let mut tree = join(driver, probe, 1_000_000);
38406        restamp_fetch_once(&mut tree, Some(&profile), None, false);
38407        let PlanNode::Join { right, .. } = &tree else {
38408            panic!("expected Join, got {tree:?}")
38409        };
38410        // ~12 keys/page over a 1M-key domain: 9 × (12 × 3.6 + ~12
38411        // matched rows) ≈ 500 row-equivalents vs 1.5M — Probe.
38412        assert!(
38413            !is_stamped(right),
38414            "cheap lists against a huge arm keep per-page mode"
38415        );
38416    }
38417
38418    /// A `DomainScanCounts` walk whose constraint is one predicate the query
38419    /// binds reads the whole predicate — the request carries a constraint list
38420    /// and no head list, so a pushed key list cannot narrow it. That shape is
38421    /// therefore buildable once and is stamped `FetchOnce` by rule, not by
38422    /// price. The exclusions are request-shape facts: distinct-mode hits carry
38423    /// cardinalities (no row table) and a pushed-predicate arm's list *is* its
38424    /// constraint list.
38425    #[test]
38426    fn a_bound_predicate_count_walk_is_built_once() {
38427        let mut specialized = var_scan(Some("s"), "http://ex/p", Some("k"), 10);
38428        specialized.domain_counts = Some(DomainScanKind::PredicateDomain);
38429        assert!(bound_constraint_count_scan(&specialized));
38430        assert!(fetch_once_stampable(&specialized));
38431
38432        // Distinct-term mode is fold-only: the hits carry cardinalities, not
38433        // terms, so there is no row table to build.
38434        let mut distinct = specialized.clone();
38435        distinct.marks = vec![(
38436            Variable::new("k").unwrap(),
38437            Liveness::Counted,
38438            BagMark::Insensitive,
38439        )];
38440        assert_eq!(
38441            distinct.domain_count_mode(),
38442            waratah_storage::DomainCountMode::DistinctTerms
38443        );
38444        assert!(!bound_constraint_count_scan(&distinct));
38445        assert!(!fetch_once_stampable(&distinct));
38446
38447        // A pushed-predicate arm takes its constraint list from the push, so
38448        // its read is list-dependent.
38449        let mut unbound = specialized.clone();
38450        unbound.pattern.predicate = None;
38451        assert!(!bound_constraint_count_scan(&unbound));
38452        assert!(!fetch_once_stampable(&unbound));
38453
38454        // A scan constrained by one subject walks a single prefix; it is not
38455        // the whole-predicate shape.
38456        let mut subject_kind = var_scan(Some("s"), "http://ex/p", Some("o"), 10);
38457        subject_kind.domain_counts = Some(DomainScanKind::SubjectDomain);
38458        assert!(!bound_constraint_count_scan(&subject_kind));
38459
38460        // The stamp pass writes the verdict: the arm is marked even though the
38461        // priced comparison below it is never consulted.
38462        let driver = PlanNode::Scan(var_scan(
38463            Some("site"),
38464            "http://ex/hasSite",
38465            Some("s"),
38466            200_000,
38467        ));
38468        let mut tree = join(driver, PlanNode::Scan(specialized), 200_000);
38469        restamp_fetch_once(&mut tree, None, None, false);
38470        let PlanNode::Join { right, .. } = &tree else {
38471            panic!("expected Join, got {tree:?}")
38472        };
38473        assert!(
38474            is_stamped(right),
38475            "the count walk must build once instead of re-walking per page"
38476        );
38477
38478        // One page: the walk happens once either way, and the per-page read
38479        // prunes to that page's keys, so the rule does not force a build.
38480        let one_page = PlanNode::Scan(var_scan(Some("site"), "http://ex/hasSite", Some("s"), 1));
38481        let mut one_page_arm = var_scan(Some("s"), "http://ex/kind", Some("k"), 10);
38482        one_page_arm.domain_counts = Some(DomainScanKind::PredicateDomain);
38483        let mut tree = join(one_page, PlanNode::Scan(one_page_arm), 1);
38484        restamp_fetch_once(&mut tree, None, None, false);
38485        let PlanNode::Join { right, .. } = &tree else {
38486            panic!("expected Join, got {tree:?}")
38487        };
38488        assert!(
38489            !is_stamped(right),
38490            "a single-page driver is not force-built"
38491        );
38492    }
38493
38494    /// A count walk cannot be keyed, so a multi-page cost estimate prices it as one
38495    /// whole read whatever the seek arithmetic says. One page ties on the walk
38496    /// and keeps the priced roads.
38497    #[test]
38498    fn a_count_walk_prices_as_one_build_on_more_than_one_page() {
38499        use super::{SeatCost, seat_cost_arithmetic};
38500
38501        // (driver_rows, whole_read_rows, memoizable, pages, keys,
38502        //  drop_allowed, stampable, whole_read_known, domains_known,
38503        //  count_walk, subtree_page)
38504        let one_page = seat_cost_arithmetic(
38505            1,
38506            1_000,
38507            false,
38508            1,
38509            &[(false, 10, 1_000, 1_000)],
38510            true,
38511            true,
38512            true,
38513            true,
38514            true,
38515            None,
38516        );
38517        assert!(
38518            one_page.rows < 1_000,
38519            "a single page keeps the priced road, not the build: {one_page:?}"
38520        );
38521
38522        let many_pages = seat_cost_arithmetic(
38523            100_000,
38524            1_000,
38525            false,
38526            10,
38527            &[(false, 10, 1_000, 1_000)],
38528            true,
38529            true,
38530            true,
38531            true,
38532            true,
38533            None,
38534        );
38535        assert_eq!(
38536            many_pages,
38537            SeatCost {
38538                rows: 100_000 + 1_000,
38539                seeks: 0
38540            },
38541            "the build is the only road for a multi-page count walk"
38542        );
38543    }
38544}
38545
38546#[cfg(test)]
38547mod pinned_conjunct_tests {
38548    use super::*;
38549    use oxrdf::NamedNode;
38550    use spargebra::algebra::Function;
38551
38552    fn var(name: &str) -> Variable {
38553        Variable::new_unchecked(name)
38554    }
38555
38556    fn triple(subject: &str, predicate: &str, object: &str) -> TriplePattern {
38557        TriplePattern {
38558            subject: TermPattern::Variable(var(subject)),
38559            predicate: NamedNodePattern::NamedNode(NamedNode::new_unchecked(predicate)),
38560            object: TermPattern::Variable(var(object)),
38561        }
38562    }
38563
38564    fn bgp(triple: TriplePattern) -> GraphPattern {
38565        GraphPattern::Bgp {
38566            patterns: vec![triple],
38567        }
38568    }
38569
38570    /// Stand-in for a plugin's candidate-producing call: an unknown custom
38571    /// function, which is exactly what `text:query` is to the algebra.
38572    fn search(variable: &str) -> Expression {
38573        Expression::FunctionCall(
38574            Function::Custom(NamedNode::new_unchecked("http://ex/search")),
38575            vec![Expression::Variable(var(variable))],
38576        )
38577    }
38578
38579    fn is_search(expression: &Expression) -> bool {
38580        matches!(
38581            expression,
38582            Expression::FunctionCall(Function::Custom(iri), _)
38583                if iri.as_str() == "http://ex/search"
38584        )
38585    }
38586
38587    fn filtered(expression: Expression, inner: GraphPattern) -> GraphPattern {
38588        GraphPattern::Filter {
38589            expr: expression,
38590            inner: Box::new(inner),
38591        }
38592    }
38593
38594    /// Two-variable stand-in for a spatial/value comparison: a candidate
38595    /// producer whose arguments can have different binding sites.
38596    fn overlap(left: &str, right: &str) -> Expression {
38597        Expression::FunctionCall(
38598            Function::Custom(NamedNode::new_unchecked("http://ex/overlap")),
38599            vec![
38600                Expression::Variable(var(left)),
38601                Expression::Variable(var(right)),
38602            ],
38603        )
38604    }
38605
38606    fn is_overlap(expression: &Expression) -> bool {
38607        matches!(
38608            expression,
38609            Expression::FunctionCall(Function::Custom(iri), _)
38610                if iri.as_str() == "http://ex/overlap"
38611        )
38612    }
38613
38614    /// The production pipeline's pin → sparopt → restore+sink sequence with the
38615    /// plugin registry replaced by an explicit predicate (the process registry
38616    /// is empty in unit tests).
38617    fn optimized(pattern: GraphPattern) -> GraphPattern {
38618        optimized_with(pattern, &is_search)
38619    }
38620
38621    fn optimized_with(
38622        pattern: GraphPattern,
38623        pins_predicate: &dyn Fn(&Expression) -> bool,
38624    ) -> GraphPattern {
38625        let mut pins = Vec::new();
38626        let pinned = pin_candidate_conjuncts(pattern, pins_predicate, &mut pins);
38627        let optimized = optimize_preserving_graph(pinned);
38628        let mut seen = vec![0u32; pins.len()];
38629        let mut stripped = vec![0u32; pins.len()];
38630        let restored = restore_and_sink_conjuncts(optimized, &pins, &mut seen);
38631        let restored = strip_pin_extends(restored, &pins, &mut stripped);
38632        for (conjuncts, anchors) in seen.iter().zip(stripped.iter()) {
38633            assert_eq!(*conjuncts, 1, "a pinned conjunct was lost or duplicated");
38634            assert_eq!(*anchors, 1, "a pin anchor was lost or duplicated");
38635        }
38636        restored
38637    }
38638
38639    fn child_count(pattern: &GraphPattern) -> usize {
38640        match pattern {
38641            GraphPattern::Join { .. }
38642            | GraphPattern::LeftJoin { .. }
38643            | GraphPattern::Union { .. }
38644            | GraphPattern::Minus { .. } => 2,
38645            GraphPattern::Bgp { .. } | GraphPattern::Path { .. } | GraphPattern::Values { .. } => 0,
38646            _ => 1,
38647        }
38648    }
38649
38650    fn walk(
38651        pattern: &GraphPattern,
38652        path: &mut Vec<usize>,
38653        f: &mut dyn FnMut(&GraphPattern, &[usize]),
38654    ) {
38655        f(pattern, path);
38656        for index in 0..child_count(pattern) {
38657            path.push(index);
38658            walk(algebra_child(pattern, index), path, f);
38659            path.pop();
38660        }
38661    }
38662
38663    fn search_filters(pattern: &GraphPattern) -> Vec<Vec<usize>> {
38664        search_filters_of(pattern, &is_search)
38665    }
38666
38667    fn search_filters_of(
38668        pattern: &GraphPattern,
38669        predicate: &dyn Fn(&Expression) -> bool,
38670    ) -> Vec<Vec<usize>> {
38671        let mut out = Vec::new();
38672        walk(pattern, &mut Vec::new(), &mut |node, path| {
38673            if let GraphPattern::Filter { expr, .. } = node
38674                && flatten_and(expr).iter().any(predicate)
38675            {
38676                out.push(path.to_vec());
38677            }
38678        });
38679        out
38680    }
38681
38682    fn node_at<'a>(pattern: &'a GraphPattern, path: &[usize]) -> &'a GraphPattern {
38683        let mut node = pattern;
38684        for index in path {
38685            node = algebra_child(node, *index);
38686        }
38687        node
38688    }
38689
38690    fn filter_inner<'a>(pattern: &'a GraphPattern, path: &[usize]) -> &'a GraphPattern {
38691        match node_at(pattern, path) {
38692            GraphPattern::Filter { inner, .. } => inner,
38693            other => panic!("expected a FILTER at {path:?}, got {other:?}"),
38694        }
38695    }
38696
38697    #[test]
38698    fn a_candidate_producer_is_not_cloned_into_union_arms() {
38699        let pattern = filtered(
38700            search("r"),
38701            GraphPattern::Join {
38702                left: Box::new(bgp(triple("r", "http://ex/kind", "k"))),
38703                right: Box::new(GraphPattern::Union {
38704                    left: Box::new(bgp(triple("r", "http://ex/a", "v"))),
38705                    right: Box::new(GraphPattern::Union {
38706                        left: Box::new(bgp(triple("r", "http://ex/b", "v"))),
38707                        right: Box::new(bgp(triple("r", "http://ex/c", "v"))),
38708                    }),
38709                }),
38710            },
38711        );
38712        let unpinned = optimize_preserving_graph(pattern.clone());
38713        assert!(
38714            search_filters(&unpinned).len() > 1,
38715            "the unpinned filter should be cloned by the algebra optimizer, got {:?}",
38716            search_filters(&unpinned)
38717        );
38718        let pinned = optimized(pattern);
38719        assert_eq!(
38720            search_filters(&pinned).len(),
38721            1,
38722            "a pinned candidate producer must appear exactly once"
38723        );
38724    }
38725
38726    #[test]
38727    fn a_single_site_conjunct_sinks_next_to_its_binding_pattern() {
38728        // A Bgp + Bgp join is merged into one Bgp by the optimizer, so the
38729        // distinguishable single-site case is a Bgp beside a Path: two pattern
38730        // nodes, only one of which binds ?w.
38731        let pattern = filtered(
38732            search("w"),
38733            GraphPattern::Join {
38734                left: Box::new(bgp(triple("r", "http://ex/geometry", "g"))),
38735                right: Box::new(GraphPattern::Path {
38736                    subject: TermPattern::Variable(var("g")),
38737                    path: PropertyPathExpression::NamedNode(NamedNode::new_unchecked(
38738                        "http://ex/wkt",
38739                    )),
38740                    object: TermPattern::Variable(var("w")),
38741                }),
38742            },
38743        );
38744        let optimized = optimized(pattern);
38745        let filters = search_filters(&optimized);
38746        assert_eq!(filters.len(), 1);
38747        match filter_inner(&optimized, &filters[0]) {
38748            GraphPattern::Path { object, .. } => assert_eq!(
38749                *object,
38750                TermPattern::Variable(var("w")),
38751                "the filter should sit directly above the pattern that binds ?w"
38752            ),
38753            other => panic!("expected the filter above the ?g :wkt ?w path, got {other:?}"),
38754        }
38755    }
38756
38757    #[test]
38758    fn a_conjunct_bound_in_one_union_arm_stays_above_the_union() {
38759        let pattern = filtered(
38760            search("v"),
38761            GraphPattern::Union {
38762                left: Box::new(bgp(triple("v", "http://ex/a", "x"))),
38763                right: Box::new(bgp(triple("s", "http://ex/b", "y"))),
38764            },
38765        );
38766        let optimized = optimized(pattern);
38767        let filters = search_filters(&optimized);
38768        assert_eq!(filters.len(), 1);
38769        assert!(
38770            matches!(
38771                filter_inner(&optimized, &filters[0]),
38772                GraphPattern::Union { .. }
38773            ),
38774            "sinking into the binding arm would let the other arm's rows escape the filter"
38775        );
38776    }
38777
38778    #[test]
38779    fn a_conjunct_bound_in_every_union_arm_sinks_above_the_union() {
38780        let pattern = filtered(
38781            search("v"),
38782            GraphPattern::Join {
38783                left: Box::new(bgp(triple("r", "http://ex/kind", "k"))),
38784                right: Box::new(GraphPattern::Union {
38785                    left: Box::new(bgp(triple("v", "http://ex/a", "x"))),
38786                    right: Box::new(bgp(triple("v", "http://ex/b", "y"))),
38787                }),
38788            },
38789        );
38790        let optimized = optimized(pattern);
38791        let filters = search_filters(&optimized);
38792        assert_eq!(filters.len(), 1);
38793        assert!(
38794            matches!(
38795                filter_inner(&optimized, &filters[0]),
38796                GraphPattern::Union { .. }
38797            ),
38798            "the union of every arm's bindings is the lowest single covering point"
38799        );
38800    }
38801
38802    #[test]
38803    fn a_slice_boundary_keeps_the_conjunct_above_it() {
38804        let pattern = filtered(
38805            search("r"),
38806            GraphPattern::Slice {
38807                inner: Box::new(GraphPattern::Join {
38808                    left: Box::new(bgp(triple("r", "http://ex/a", "v"))),
38809                    right: Box::new(bgp(triple("r", "http://ex/b", "v"))),
38810                }),
38811                start: 0,
38812                length: Some(10),
38813            },
38814        );
38815        let optimized = optimized(pattern);
38816        let filters = search_filters(&optimized);
38817        assert_eq!(filters.len(), 1);
38818        assert!(
38819            matches!(
38820                filter_inner(&optimized, &filters[0]),
38821                GraphPattern::Slice { .. }
38822            ),
38823            "a filter below a slice would select different rows"
38824        );
38825    }
38826
38827    #[test]
38828    fn a_projected_variable_lets_the_conjunct_sink_into_the_subselect() {
38829        let pattern = filtered(
38830            search("r"),
38831            GraphPattern::Project {
38832                inner: Box::new(bgp(triple("r", "http://ex/a", "v"))),
38833                variables: vec![var("r"), var("v")],
38834            },
38835        );
38836        let optimized = optimized(pattern);
38837        let filters = search_filters(&optimized);
38838        assert_eq!(filters.len(), 1);
38839        let GraphPattern::Project { inner, .. } = &optimized else {
38840            panic!("expected the projection to survive, got {optimized:?}");
38841        };
38842        assert!(
38843            matches!(inner.as_ref(), GraphPattern::Filter { .. }),
38844            "a filter reading only projected variables may cross the projection"
38845        );
38846    }
38847
38848    #[test]
38849    fn a_hidden_variable_keeps_the_conjunct_above_the_subselect() {
38850        let pattern = filtered(
38851            search("w"),
38852            GraphPattern::Project {
38853                inner: Box::new(bgp(triple("r", "http://ex/a", "w"))),
38854                variables: vec![var("r")],
38855            },
38856        );
38857        let optimized = optimized(pattern);
38858        let filters = search_filters(&optimized);
38859        assert_eq!(filters.len(), 1);
38860        assert!(
38861            matches!(
38862                filter_inner(&optimized, &filters[0]),
38863                GraphPattern::Project { .. }
38864            ),
38865            "a filter may not cross a projection that hides a variable it reads"
38866        );
38867    }
38868
38869    #[test]
38870    fn graph_bindings_are_sites_but_the_sink_never_enters() {
38871        use spargebra::term::NamedNodePattern;
38872        let graph = GraphPattern::Graph {
38873            name: NamedNodePattern::NamedNode(NamedNode::new_unchecked("http://ex/g")),
38874            inner: Box::new(bgp(triple("s", "http://ex/label", "lit"))),
38875        };
38876        let mut sites = Vec::new();
38877        collect_binding_sites(&graph, &[var("lit")], &mut Vec::new(), &mut sites);
38878        assert_eq!(
38879            sites,
38880            vec![vec![0]],
38881            "a GRAPH's bindings flow out to the enclosing solution, so the site exists"
38882        );
38883        let optimized = optimized(filtered(search("lit"), graph));
38884        let filters = search_filters(&optimized);
38885        assert_eq!(filters.len(), 1);
38886        assert!(
38887            matches!(
38888                filter_inner(&optimized, &filters[0]),
38889                GraphPattern::Graph { .. }
38890            ),
38891            "the filter must stay above the GRAPH: entering it would change its graph scope"
38892        );
38893    }
38894
38895    #[test]
38896    fn optional_right_side_bindings_are_sites_but_not_sink_targets() {
38897        let left_join = GraphPattern::LeftJoin {
38898            left: Box::new(bgp(triple("s", "http://ex/kind", "k"))),
38899            right: Box::new(bgp(triple("s", "http://ex/other", "o"))),
38900            expression: None,
38901        };
38902        let mut sites = Vec::new();
38903        collect_binding_sites(&left_join, &[var("o")], &mut Vec::new(), &mut sites);
38904        assert_eq!(
38905            sites,
38906            vec![vec![1]],
38907            "an OPTIONAL's right side binds ?o for matching rows"
38908        );
38909        let optimized = optimized(filtered(search("o"), left_join));
38910        let filters = search_filters(&optimized);
38911        assert_eq!(filters.len(), 1);
38912        assert!(
38913            matches!(
38914                filter_inner(&optimized, &filters[0]),
38915                GraphPattern::LeftJoin { .. }
38916            ),
38917            "the filter must stay above the LeftJoin: inside the right side a miss row would survive"
38918        );
38919    }
38920
38921    fn is_iri_check(expression: &Expression) -> bool {
38922        matches!(expression, Expression::FunctionCall(Function::IsIri, _))
38923    }
38924
38925    fn count_conjuncts(pattern: &GraphPattern, predicate: &dyn Fn(&Expression) -> bool) -> usize {
38926        let mut count = 0;
38927        walk(pattern, &mut Vec::new(), &mut |node, _| {
38928            if let GraphPattern::Filter { expr, .. } = node {
38929                count += flatten_and(expr).iter().filter(|c| predicate(c)).count();
38930            }
38931        });
38932        count
38933    }
38934
38935    #[test]
38936    fn a_minus_left_variable_sinks_into_the_left_but_a_right_one_does_not() {
38937        let minus = || GraphPattern::Minus {
38938            left: Box::new(bgp(triple("s", "http://ex/kind", "k"))),
38939            right: Box::new(bgp(triple("s", "http://ex/other", "o"))),
38940        };
38941        // ?k is bound on the left: the filter sinks above that scan.
38942        let plan = optimized(filtered(search("k"), minus()));
38943        let filters = search_filters(&plan);
38944        assert_eq!(filters.len(), 1);
38945        match filter_inner(&plan, &filters[0]) {
38946            GraphPattern::Bgp { patterns } => assert_eq!(
38947                patterns[0].object,
38948                TermPattern::Variable(var("k")),
38949                "the filter should sit above the scan that binds ?k"
38950            ),
38951            other => panic!("expected the filter above the left scan, got {other:?}"),
38952        }
38953        // ?o is bound only on the right, which never contributes bindings.
38954        let plan = optimized(filtered(search("o"), minus()));
38955        let filters = search_filters(&plan);
38956        assert_eq!(filters.len(), 1);
38957        assert!(
38958            matches!(filter_inner(&plan, &filters[0]), GraphPattern::Minus { .. }),
38959            "a MINUS right side is not a result binding, so it is not a sink target"
38960        );
38961    }
38962
38963    #[test]
38964    fn a_group_key_is_a_sink_barrier_and_a_non_key_has_no_site() {
38965        let group = |keys: Vec<Variable>| GraphPattern::Group {
38966            inner: Box::new(bgp(triple("r", "http://ex/p", "v"))),
38967            variables: keys,
38968            aggregates: vec![],
38969        };
38970        // ?v is not a key: the Group hides it from above, so there is no site.
38971        let plan = optimized(filtered(search("v"), group(vec![var("r")])));
38972        let filters = search_filters(&plan);
38973        assert_eq!(filters.len(), 1);
38974        assert!(
38975            matches!(filter_inner(&plan, &filters[0]), GraphPattern::Group { .. }),
38976            "a non-key variable has no site above the Group"
38977        );
38978        // ?r is a key: the site is the Group itself, and the filter stays
38979        // above it rather than evaluating on the pre-group rows.
38980        let plan = optimized(filtered(search("r"), group(vec![var("r")])));
38981        let filters = search_filters(&plan);
38982        assert_eq!(filters.len(), 1);
38983        assert!(
38984            matches!(filter_inner(&plan, &filters[0]), GraphPattern::Group { .. }),
38985            "the filter must not cross a Group, even for a key"
38986        );
38987    }
38988
38989    #[test]
38990    fn an_extend_that_defines_the_variable_is_not_crossed() {
38991        let extend = |variable: &str| GraphPattern::Extend {
38992            inner: Box::new(bgp(triple("r", "http://ex/p", "w"))),
38993            variable: var(variable),
38994            expression: Expression::Literal(oxrdf::Literal::from("x")),
38995        };
38996        // ?v is defined by the Extend: its site is the Extend itself.
38997        let plan = optimized(filtered(search("v"), extend("v")));
38998        let filters = search_filters(&plan);
38999        assert_eq!(filters.len(), 1);
39000        assert!(
39001            matches!(
39002                filter_inner(&plan, &filters[0]),
39003                GraphPattern::Extend { .. }
39004            ),
39005            "a variable defined by an Extend cannot be evaluated below it"
39006        );
39007        // ?w is bound below the Extend: the filter may sink inside it.
39008        let plan = optimized(filtered(search("w"), extend("v")));
39009        let filters = search_filters(&plan);
39010        assert_eq!(filters.len(), 1);
39011        match filter_inner(&plan, &filters[0]) {
39012            GraphPattern::Bgp { patterns } => assert_eq!(
39013                patterns[0].object,
39014                TermPattern::Variable(var("w")),
39015                "the filter should sit above the scan that binds ?w"
39016            ),
39017            other => panic!("expected the filter inside the Extend, got {other:?}"),
39018        }
39019    }
39020
39021    #[test]
39022    fn two_pins_in_one_filter_both_restore_and_sink() {
39023        let pattern = filtered(
39024            Expression::And(Box::new(search("a")), Box::new(search("b"))),
39025            bgp(triple("a", "http://ex/link", "b")),
39026        );
39027        let optimized = optimized(pattern);
39028        let filters = search_filters(&optimized);
39029        assert_eq!(filters.len(), 2, "both pinned conjuncts are restored");
39030        let deepest = filters
39031            .iter()
39032            .max_by_key(|path| path.len())
39033            .expect("two filters");
39034        assert!(
39035            matches!(filter_inner(&optimized, deepest), GraphPattern::Bgp { .. }),
39036            "both conjuncts sink to the pattern that binds their variables"
39037        );
39038    }
39039
39040    #[test]
39041    fn a_pinned_conjunct_leaves_its_unpinned_sibling_where_the_optimizer_put_it() {
39042        let isiri =
39043            || Expression::FunctionCall(Function::IsIri, vec![Expression::Variable(var("r"))]);
39044        let both = || {
39045            filtered(
39046                Expression::And(Box::new(search("r")), Box::new(isiri())),
39047                GraphPattern::Join {
39048                    left: Box::new(bgp(triple("r", "http://ex/kind", "k"))),
39049                    right: Box::new(bgp(triple("r", "http://ex/other", "o"))),
39050                },
39051            )
39052        };
39053        // The cheap sibling keeps exactly the distribution the optimizer
39054        // chooses when nothing is pinned.
39055        let reference = optimize_preserving_graph(both());
39056        let expected = count_conjuncts(&reference, &is_iri_check);
39057        let optimized = optimized(both());
39058        assert_eq!(count_conjuncts(&optimized, &is_iri_check), expected);
39059        let filters = search_filters(&optimized);
39060        assert_eq!(filters.len(), 1);
39061        assert!(
39062            matches!(
39063                filter_inner(&optimized, &filters[0]),
39064                GraphPattern::Join { .. }
39065            ),
39066            "?r is bound in both branches, so the producer stays above the join"
39067        );
39068    }
39069
39070    #[test]
39071    fn a_ground_producer_keeps_its_join_variable() {
39072        let inner = PlanNode::Values(ValuesOp {
39073            variables: vec![var("g")],
39074            rows: vec![vec![Some(EncodedTerm::BooleanLiteral(
39075                oxsdatatypes::Boolean::from(true),
39076            ))]],
39077            strings: Vec::new(),
39078            blobs: Vec::new(),
39079        });
39080        let inner_vars = inner.output_vars();
39081        // A one-variable producer whose variable is ground: substitution would
39082        // leave a fully ground call with nothing to join back to. When the
39083        // plugin declares that it joins its variable back to the store, the
39084        // original expression is kept.
39085        let mut conjunct = search("g");
39086        ground_residual_conjunct(&mut conjunct, &inner, &inner_vars, &|_| true);
39087        assert_eq!(
39088            conjunct,
39089            search("g"),
39090            "the join variable must survive grounding"
39091        );
39092        // Without that declaration the lowering grounds it as usual.
39093        let mut conjunct = search("g");
39094        ground_residual_conjunct(&mut conjunct, &inner, &inner_vars, &|_| false);
39095        assert!(
39096            !variables_in_expression(&conjunct).contains(&var("g")),
39097            "an ordinary conjunct still grounds: {conjunct:?}"
39098        );
39099    }
39100
39101    #[test]
39102    fn the_grounding_guard_tests_the_source_shape() {
39103        // The guard must ask the plugin about the expression it claimed, not
39104        // the substituted one: a shape-sensitive predicate stops matching once
39105        // its variable is replaced. Here the predicate only holds for an
39106        // expression with a variable, so a guard that looked at the grounded
39107        // form would substitute and this assertion would fail.
39108        let inner = PlanNode::Values(ValuesOp {
39109            variables: vec![var("g")],
39110            rows: vec![vec![Some(EncodedTerm::BooleanLiteral(
39111                oxsdatatypes::Boolean::from(true),
39112            ))]],
39113            strings: Vec::new(),
39114            blobs: Vec::new(),
39115        });
39116        let inner_vars = inner.output_vars();
39117        let keeps_only_with_a_variable =
39118            |expression: &Expression| !variables_in_expression(expression).is_empty();
39119        let mut conjunct = search("g");
39120        ground_residual_conjunct(
39121            &mut conjunct,
39122            &inner,
39123            &inner_vars,
39124            &keeps_only_with_a_variable,
39125        );
39126        assert_eq!(
39127            conjunct,
39128            search("g"),
39129            "the guard must ask about the source expression"
39130        );
39131    }
39132
39133    #[test]
39134    fn a_lost_pin_is_counted_not_ignored() {
39135        let pattern = filtered(search("r"), bgp(triple("r", "http://ex/a", "v")));
39136        let mut pins = Vec::new();
39137        let pinned = pin_candidate_conjuncts(pattern.clone(), &is_search, &mut pins);
39138        assert_eq!(pins.len(), 1);
39139        assert!(matches!(
39140            &pinned,
39141            GraphPattern::Filter { expr, .. } if pinned_ghost_variable_of(expr).is_some()
39142        ));
39143        // Simulate an optimizer pass that dropped the ghost: the counter is
39144        // what turns that into a hard error in `prepare_algebra`.
39145        let mut seen = vec![0u32; pins.len()];
39146        let _ = restore_and_sink_conjuncts(pattern, &pins, &mut seen);
39147        assert_eq!(seen, vec![0]);
39148    }
39149
39150    #[test]
39151    fn a_conjunct_bound_only_in_an_optionals_right_side_is_not_sunk() {
39152        // `?o` is visible above the LeftJoin but bound only inside its right
39153        // branch, which the sink never enters. Sinking to `?g`'s site would
39154        // evaluate the predicate where `?o` is unbound: every row errors and
39155        // the semijoin cannot bring them back.
39156        let pattern = filtered(
39157            overlap("g", "o"),
39158            GraphPattern::Join {
39159                left: Box::new(bgp(triple("s", "http://ex/geometry", "g"))),
39160                right: Box::new(GraphPattern::LeftJoin {
39161                    left: Box::new(bgp(triple("s", "http://ex/kind", "k"))),
39162                    right: Box::new(bgp(triple("s", "http://ex/other", "o"))),
39163                    expression: None,
39164                }),
39165            },
39166        );
39167        let optimized = optimized_with(pattern, &is_overlap);
39168        let filters = search_filters_of(&optimized, &is_overlap);
39169        assert_eq!(filters.len(), 1);
39170        assert!(
39171            matches!(
39172                filter_inner(&optimized, &filters[0]),
39173                GraphPattern::Join { .. }
39174            ),
39175            "the filter must stay above the join, not sink under the LeftJoin"
39176        );
39177    }
39178
39179    #[test]
39180    fn a_conjunct_bound_only_behind_a_subselect_is_not_sunk() {
39181        // `?g` is projected by the sub-select and `?o` is bound by the sibling
39182        // scan. Sinking to either site alone would evaluate the predicate
39183        // where the other variable is unbound.
39184        let pattern = filtered(
39185            overlap("g", "o"),
39186            GraphPattern::Join {
39187                left: Box::new(GraphPattern::Project {
39188                    inner: Box::new(bgp(triple("s", "http://ex/geometry", "g"))),
39189                    variables: vec![var("s"), var("g")],
39190                }),
39191                right: Box::new(bgp(triple("s2", "http://ex/other", "o"))),
39192            },
39193        );
39194        let optimized = optimized_with(pattern, &is_overlap);
39195        let filters = search_filters_of(&optimized, &is_overlap);
39196        assert_eq!(filters.len(), 1);
39197        assert!(
39198            matches!(
39199                filter_inner(&optimized, &filters[0]),
39200                GraphPattern::Join { .. }
39201            ),
39202            "the filter must stay above the join that binds both variables"
39203        );
39204    }
39205
39206    #[test]
39207    fn a_provably_empty_scope_absorbs_its_pin() {
39208        // `VALUES {}` under the pinned filter: the optimizer drops the anchor
39209        // and the filter with the empty table, so both counters read zero. The
39210        // answer is empty regardless of the filter.
39211        let pattern = filtered(
39212            search("x"),
39213            GraphPattern::Values {
39214                variables: vec![var("x")],
39215                bindings: vec![],
39216            },
39217        );
39218        let mut pins = Vec::new();
39219        let pinned = pin_candidate_conjuncts(pattern, &is_search, &mut pins);
39220        let optimized = optimize_preserving_graph(pinned);
39221        assert!(
39222            pattern_is_surely_empty(&optimized),
39223            "the optimizer proves the scope empty: {optimized:?}"
39224        );
39225        let mut seen = vec![0u32; pins.len()];
39226        let mut anchors = vec![0u32; pins.len()];
39227        let restored = restore_and_sink_conjuncts(optimized, &pins, &mut seen);
39228        let restored = strip_pin_extends(restored, &pins, &mut anchors);
39229        assert_eq!(seen, vec![0]);
39230        assert_eq!(anchors, vec![0]);
39231        check_pin_survival(&restored, &pins, &seen, &anchors)
39232            .expect("an optimizer-proved empty scope absorbs its pin");
39233    }
39234
39235    #[test]
39236    fn a_filter_false_scope_absorbs_its_pin() {
39237        use oxrdf::Literal;
39238        // `FILTER(false)` beside a pinned conjunct: boolean folding replaces
39239        // the whole filter — and the anchor under it — with the empty table,
39240        // so both counters read zero. That is the shape that used to surface
39241        // as a 500.
39242        let pattern = filtered(
39243            Expression::And(
39244                Box::new(Expression::Literal(Literal::from(false))),
39245                Box::new(search("r")),
39246            ),
39247            bgp(triple("r", "http://ex/a", "v")),
39248        );
39249        let mut pins = Vec::new();
39250        let pinned = pin_candidate_conjuncts(pattern, &is_search, &mut pins);
39251        let optimized = optimize_preserving_graph(pinned);
39252        let folded = crate::expr::fold_constants(optimized, &crate::expr::ExprEvalEnv::for_tests());
39253        assert!(
39254            pattern_is_surely_empty(&folded),
39255            "the fold proves the scope empty: {folded:?}"
39256        );
39257        let mut seen = vec![0u32; pins.len()];
39258        let mut anchors = vec![0u32; pins.len()];
39259        let restored = restore_and_sink_conjuncts(folded, &pins, &mut seen);
39260        let restored = strip_pin_extends(restored, &pins, &mut anchors);
39261        assert_eq!(seen, vec![0], "the fold took the pinned conjunct with it");
39262        assert_eq!(anchors, vec![0], "the fold took the anchor with it");
39263        check_pin_survival(&restored, &pins, &seen, &anchors)
39264            .expect("boolean folding absorbs the pin with the empty table");
39265    }
39266
39267    #[test]
39268    fn surely_empty_covers_the_shapes_the_optimizer_collapses() {
39269        let empty = GraphPattern::Values {
39270            variables: vec![],
39271            bindings: vec![],
39272        };
39273        let non_empty = bgp(triple("s", "http://ex/p", "o"));
39274        assert!(pattern_is_surely_empty(&empty));
39275        assert!(!pattern_is_surely_empty(&non_empty));
39276        // An empty BGP is one empty row (the unit pattern), not the empty table.
39277        assert!(!pattern_is_surely_empty(&GraphPattern::Bgp {
39278            patterns: vec![]
39279        }));
39280        // A join with one empty side cannot produce rows; a union needs both.
39281        assert!(pattern_is_surely_empty(&GraphPattern::Join {
39282            left: Box::new(empty.clone()),
39283            right: Box::new(non_empty.clone()),
39284        }));
39285        assert!(!pattern_is_surely_empty(&GraphPattern::Union {
39286            left: Box::new(empty.clone()),
39287            right: Box::new(non_empty.clone()),
39288        }));
39289        // A left join with an empty left side is empty; the right may be empty.
39290        assert!(pattern_is_surely_empty(&GraphPattern::LeftJoin {
39291            left: Box::new(empty.clone()),
39292            right: Box::new(non_empty.clone()),
39293            expression: None,
39294        }));
39295        // An aggregate-only group keeps its single row over the empty table.
39296        assert!(!pattern_is_surely_empty(&GraphPattern::Group {
39297            inner: Box::new(empty.clone()),
39298            variables: vec![],
39299            aggregates: vec![],
39300        }));
39301        assert!(pattern_is_surely_empty(&GraphPattern::Group {
39302            inner: Box::new(empty.clone()),
39303            variables: vec![var("k")],
39304            aggregates: vec![],
39305        }));
39306        // A zero-length slice is empty whatever its input.
39307        assert!(pattern_is_surely_empty(&GraphPattern::Slice {
39308            inner: Box::new(non_empty),
39309            start: 0,
39310            length: Some(0),
39311        }));
39312    }
39313
39314    #[test]
39315    fn a_lost_pin_is_accepted_only_for_a_proved_empty_scope() {
39316        let pins = vec![PinnedConjunct {
39317            ghost: var("__waratah_pin_test"),
39318            expression: search("r"),
39319        }];
39320        let empty = GraphPattern::Values {
39321            variables: vec![],
39322            bindings: vec![],
39323        };
39324        check_pin_survival(&empty, &pins, &[0], &[0]).expect("an empty scope absorbs its pin");
39325        assert!(
39326            check_pin_survival(&bgp(triple("r", "http://ex/a", "v")), &pins, &[0], &[0]).is_err(),
39327            "a lost pin outside a proved-empty scope must fail"
39328        );
39329        assert!(
39330            check_pin_survival(&empty, &pins, &[1], &[0]).is_err(),
39331            "a surviving conjunct with a lost anchor must fail"
39332        );
39333        assert!(
39334            check_pin_survival(&empty, &pins, &[2], &[1]).is_err(),
39335            "a duplicated conjunct must fail"
39336        );
39337    }
39338}
39339
39340#[cfg(test)]
39341mod semi_admission_tests {
39342    //! General subtree-right `Semi` admission: the liveness boundary capture
39343    //! and the build-versus-per-page price. The fixture is the s32 t4 shape
39344    //! reduced to one facet union arm pair and one literal union arm pair:
39345    //!
39346    //! ```text
39347    //! Group(COUNT(DISTINCT ?r))
39348    //!   Join(
39349    //!     left  = Join(Union(facet scans), Scan(?r datasetKind <record>)),
39350    //!     right = Filter(Union(literal scans)))
39351    //! ```
39352    //!
39353    //! The left join carries the driver estimate and the right subtree the
39354    //! literal read, so the admission sees exactly the boundary t4 needs.
39355
39356    use std::collections::HashMap;
39357    use std::sync::{Arc, Mutex};
39358
39359    use super::*;
39360    use crate::context::{LogLevel, LogSink};
39361    use crate::liveness::{annotate_liveness, join_semi_context};
39362    use crate::query::fixtures::test_support::{join, scan, var};
39363    use waratah_storage::NamedNode;
39364
39365    /// The driver population is 200k distinct ?r values; the literal
39366    /// predicates have a wider 400k subject domain, so a full-domain push
39367    /// covers only half of each literal arm. That is the t4 shape: the
39368    /// build is cheaper than the unfiltered whole read only when it pushes
39369    /// the driver's domain.
39370    fn profile(rows: u64, driver_subjects: u128, probe_subjects: u128) -> StatsProfile {
39371        let mut profile = StatsProfile::default();
39372        for (predicate, subjects) in [
39373            ("http://ex/datasetKind", driver_subjects),
39374            ("http://ex/kindA", driver_subjects),
39375            ("http://ex/kindB", driver_subjects),
39376            ("http://ex/name", probe_subjects),
39377            ("http://ex/abstract", probe_subjects),
39378        ] {
39379            let mut subject_hll = waratah_stats::HyperLogLog::default_params();
39380            for i in 0..subjects {
39381                subject_hll.add(i);
39382            }
39383            let hash = StrHash::new(predicate);
39384            profile.subjects_per_predicate.insert(hash, subject_hll);
39385            profile.predicate_counts.insert(hash, rows);
39386        }
39387        profile.total_puts = rows.saturating_mul(5);
39388        profile
39389    }
39390
39391    fn record_scan() -> PlanNode {
39392        let mut scan = scan("r", "http://ex/datasetKind", "dim", 1_000_000);
39393        scan.object = None;
39394        scan.pattern.object = Some(EncodedTerm::from(
39395            &NamedNode::new("http://ex/record").unwrap(),
39396        ));
39397        PlanNode::Scan(scan)
39398    }
39399
39400    fn literal_subtree() -> PlanNode {
39401        let left = scan("r", "http://ex/name", "lit", 1_000_000);
39402        let right = scan("r", "http://ex/abstract", "lit", 1_000_000);
39403        PlanNode::Filter {
39404            inner: Box::new(PlanNode::Union {
39405                left: Box::new(PlanNode::Scan(left)),
39406                right: Box::new(PlanNode::Scan(right)),
39407            }),
39408            early: None,
39409            residual: Some(Expression::Variable(var("lit"))),
39410            exists: Vec::new(),
39411            one_to_one: false,
39412        }
39413    }
39414
39415    /// The liveness pass clears and re-derives every specialized-scan stamp,
39416    /// so a fixture that wants one must set it after annotation — the
39417    /// admission gate reads the final tree.
39418    fn mark_first_scan_specialized(node: &mut PlanNode) -> bool {
39419        match node {
39420            PlanNode::Scan(scan) => {
39421                scan.domain_scan = Some(DomainScanKind::PredicateSubjects);
39422                true
39423            }
39424            PlanNode::Join { left, right, .. }
39425            | PlanNode::LeftJoin { left, right, .. }
39426            | PlanNode::Union { left, right } => {
39427                mark_first_scan_specialized(left) || mark_first_scan_specialized(right)
39428            }
39429            PlanNode::Filter { inner, .. }
39430            | PlanNode::Extend { inner, .. }
39431            | PlanNode::Slice { inner, .. }
39432            | PlanNode::Distinct { inner, .. }
39433            | PlanNode::Sort { inner, .. }
39434            | PlanNode::Group { inner, .. }
39435            | PlanNode::JoinGraphVar { inner, .. } => mark_first_scan_specialized(inner),
39436            _ => false,
39437        }
39438    }
39439
39440    /// A key-unique scan with a ground object: the right can be a
39441    /// `SemiScan` or a general `Semi`, depending on the fetch-once verdict.
39442    fn ground_record_scan(predicate: &str) -> PlanNode {
39443        let mut scan = scan("r", predicate, "lit", 1_000_000);
39444        scan.object = None;
39445        scan.pattern.object = Some(EncodedTerm::from(
39446            &NamedNode::new("http://ex/record").unwrap(),
39447        ));
39448        PlanNode::Scan(scan)
39449    }
39450
39451    /// The t4 driver with a single ground-object scan on the right.
39452    fn semi_top_scan_right(left_rows: u64) -> PlanNode {
39453        let facet = PlanNode::Union {
39454            left: Box::new(PlanNode::Scan(scan(
39455                "r",
39456                "http://ex/kindA",
39457                "dim",
39458                1_000_000,
39459            ))),
39460            right: Box::new(PlanNode::Scan(scan(
39461                "r",
39462                "http://ex/kindB",
39463                "dim",
39464                1_000_000,
39465            ))),
39466        };
39467        let left = join(facet, record_scan(), &["r"], &[200_000], left_rows);
39468        join(
39469            left,
39470            ground_record_scan("http://ex/abstract"),
39471            &["r"],
39472            &[200_000],
39473            left_rows,
39474        )
39475    }
39476
39477    /// The same driver with a variable-object scan on the right, whose
39478    /// `?lit` column is payload when it is live above the join.
39479    fn semi_top_scan_right_payload(left_rows: u64) -> PlanNode {
39480        let facet = PlanNode::Union {
39481            left: Box::new(PlanNode::Scan(scan(
39482                "r",
39483                "http://ex/kindA",
39484                "dim",
39485                1_000_000,
39486            ))),
39487            right: Box::new(PlanNode::Scan(scan(
39488                "r",
39489                "http://ex/kindB",
39490                "dim",
39491                1_000_000,
39492            ))),
39493        };
39494        let left = join(facet, record_scan(), &["r"], &[200_000], left_rows);
39495        join(
39496            left,
39497            PlanNode::Scan(scan("r", "http://ex/abstract", "lit", 1_000_000)),
39498            &["r"],
39499            &[200_000],
39500            left_rows,
39501        )
39502    }
39503
39504    fn semi_top(left_rows: u64, multi_key: bool) -> PlanNode {
39505        let facet = PlanNode::Union {
39506            left: Box::new(PlanNode::Scan(scan(
39507                "r",
39508                "http://ex/kindA",
39509                "dim",
39510                1_000_000,
39511            ))),
39512            right: Box::new(PlanNode::Scan(scan(
39513                "r",
39514                "http://ex/kindB",
39515                "dim",
39516                1_000_000,
39517            ))),
39518        };
39519        let left = join(facet, record_scan(), &["r"], &[200_000], left_rows);
39520        let keys: &[&str] = if multi_key { &["r", "dim"] } else { &["r"] };
39521        join(left, literal_subtree(), keys, &[200_000], left_rows)
39522    }
39523
39524    /// The fixture's outer join, under the wrappers the stamp pass walks.
39525    fn outer_join(node: &PlanNode) -> &PlanNode {
39526        match node {
39527            PlanNode::Slice { inner, .. } => outer_join(inner),
39528            PlanNode::Filter { exists, .. } => outer_join(&exists[0].body),
39529            PlanNode::Group { inner, .. } => outer_join(inner),
39530            PlanNode::Join { .. } => node,
39531            other => panic!("unexpected fixture node: {other:?}"),
39532        }
39533    }
39534
39535    fn outer_join_mut(node: &mut PlanNode) -> &mut PlanNode {
39536        match node {
39537            PlanNode::Slice { inner, .. } => outer_join_mut(inner.as_mut()),
39538            PlanNode::Filter { exists, .. } => outer_join_mut(exists[0].body.as_mut()),
39539            PlanNode::Group { inner, .. } => outer_join_mut(inner.as_mut()),
39540            PlanNode::Join { .. } => node,
39541            other => panic!("unexpected fixture node: {other:?}"),
39542        }
39543    }
39544
39545    fn semi_group(top: PlanNode, aggregate: AggregateExpression, group_vars: &[&str]) -> PlanNode {
39546        PlanNode::Group {
39547            inner: Box::new(top),
39548            variables: group_vars.iter().map(|name| var(name)).collect(),
39549            aggregates: vec![(var("n"), aggregate)],
39550            const_strings: Vec::new(),
39551            const_blobs: Vec::new(),
39552        }
39553    }
39554
39555    fn semi_shape(
39556        aggregate: AggregateExpression,
39557        group_vars: &[&str],
39558        left_rows: u64,
39559        multi_key: bool,
39560    ) -> PlanNode {
39561        semi_group(semi_top(left_rows, multi_key), aggregate, group_vars)
39562    }
39563
39564    fn count_distinct() -> AggregateExpression {
39565        AggregateExpression::FunctionCall {
39566            name: AggregateFunction::Count,
39567            expr: Expression::Variable(var("r")),
39568            distinct: true,
39569        }
39570    }
39571
39572    fn count_rows() -> AggregateExpression {
39573        AggregateExpression::FunctionCall {
39574            name: AggregateFunction::Count,
39575            expr: Expression::Variable(var("r")),
39576            distinct: false,
39577        }
39578    }
39579
39580    fn count_star() -> AggregateExpression {
39581        AggregateExpression::CountSolutions { distinct: false }
39582    }
39583
39584    /// Record the semi gate facts, run the stamp pass, and return the
39585    /// `semi-admit` and `semi-payload` lines.
39586    fn admission_log(group: &mut PlanNode, profile: Option<&StatsProfile>, sliced: bool) -> String {
39587        admission_log_with_order(group, profile, sliced, &[])
39588    }
39589
39590    fn admission_log_with_order(
39591        group: &mut PlanNode,
39592        profile: Option<&StatsProfile>,
39593        sliced: bool,
39594        order_keys: &[Variable],
39595    ) -> String {
39596        admission_log_top(
39597            group,
39598            &[var("dim"), var("n")],
39599            order_keys,
39600            false,
39601            profile,
39602            sliced,
39603        )
39604    }
39605
39606    fn admission_log_top(
39607        top: &mut PlanNode,
39608        projection: &[Variable],
39609        order_keys: &[Variable],
39610        distinct: bool,
39611        profile: Option<&StatsProfile>,
39612        sliced: bool,
39613    ) -> String {
39614        let lines = Arc::new(Mutex::new(Vec::new()));
39615        let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest())
39616            .with_log(LogSink::capture(LogLevel::Debug, Arc::clone(&lines)));
39617        annotate_liveness(top, projection, order_keys, distinct, profile, Some(&ctx));
39618        if !sliced {
39619            stamp_semi_join_strategy(top, profile, sliced, Some(&ctx), &[]);
39620        }
39621        lines
39622            .lock()
39623            .unwrap()
39624            .iter()
39625            .filter(|line| line.contains("semi-admit:") || line.contains("semi-payload:"))
39626            .cloned()
39627            .collect::<Vec<_>>()
39628            .join("\n")
39629    }
39630
39631    fn admit_line(log: &str) -> &str {
39632        log.lines()
39633            .find(|line| line.contains("semi-admit: filter(union)"))
39634            .unwrap_or_else(|| panic!("no filter(union) admission line:\n{log}"))
39635    }
39636
39637    fn verdict_price(
39638        pages: u64,
39639        per_page_price_milli: u128,
39640        build_read_rows: u64,
39641        build_bar_milli: u128,
39642    ) -> SemiBuildPrice {
39643        SemiBuildPrice {
39644            pages,
39645            driver_rows: 1,
39646            page_rows: 1,
39647            seeks_per_page: 0,
39648            matched_per_page: 0,
39649            per_page_filter_cost_milli: 0,
39650            per_page_price_milli,
39651            build_read_rows,
39652            build_source: "test",
39653            build_seek_terms: 0,
39654            build_rpcs: 0,
39655            build_output_rows: 0,
39656            build_keys: 0,
39657            build_price_milli: build_bar_milli,
39658            build_bar_milli,
39659            build_filter_cost_milli: 0,
39660            unpushed_read_rows: None,
39661            unpushed_output_rows: None,
39662            ancestor_keys: 0,
39663            driver_domain: 1,
39664            probe_domain_known: true,
39665        }
39666    }
39667
39668    #[test]
39669    fn unpushed_frames_are_structural_and_ignore_the_join_cells() {
39670        let profile = profile(1_000_000, 200_000, 400_000);
39671        let join = join(
39672            PlanNode::Scan(scan("r", "http://ex/kindA", "v", 1_000_000)),
39673            PlanNode::Scan(scan("r", "http://ex/kindB", "v", 1_000_000)),
39674            &["r"],
39675            &[200_000],
39676            // Deliberately absurd staged cells: the fully unpushed frame
39677            // must not read them.
39678            1,
39679        );
39680        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39681        let read = unpushed_read_rows(Some(&profile), &join, &mut budget)
39682            .expect("both scan reads are profile-backed");
39683        assert_eq!(read, 2_000_000, "read is the sum of the two raw scans");
39684
39685        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39686        let output = unpushed_row_count_estimate(Some(&profile), &join, &mut budget)
39687            .expect("the join is structurally priceable");
39688        // 1M × 1M / HLL(200k) ≈ 4.94M; the HLL estimate is 202,545.
39689        assert!(
39690            (4_800_000..=5_100_000).contains(&output),
39691            "the join output is the uniform product over the HLL domain, got {output}"
39692        );
39693    }
39694
39695    #[test]
39696    fn an_ancestor_key_list_reduces_the_build_read() {
39697        let profile = profile(1_000_000, 200_000, 400_000);
39698        let right = literal_subtree();
39699        let key = var("r");
39700
39701        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39702        let source = SemiBuildPushSource::AncestorPushesAndDriverDomain {
39703            key: &key,
39704            domain: 200_000,
39705        };
39706        let base = estimate_semi_build_drain(Some(&profile), &right, source, &[], &mut budget)
39707            .expect("the two literal leaves are profile-backed");
39708
39709        let ancestors = [AncestorPushKey {
39710            key: key.clone(),
39711            list: 100_000,
39712        }];
39713        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39714        let reduced =
39715            estimate_semi_build_drain(Some(&profile), &right, source, &ancestors, &mut budget)
39716                .expect("the ancestor list composes with the driver list");
39717
39718        assert!(
39719            reduced.read_rows < base.read_rows,
39720            "the 100k ancestor list must reduce the 200k driver-domain build: \
39721             base={} reduced={}",
39722            base.read_rows,
39723            reduced.read_rows,
39724        );
39725        assert!(
39726            (450_000..600_000).contains(&reduced.read_rows),
39727            "the merged 100k list halves the ~1M no-ancestor build read, got {}",
39728            reduced.read_rows,
39729        );
39730        assert_eq!(
39731            reduced.pushed_terms,
39732            2 * 100_000,
39733            "the merged list is pushed once per hosted leaf"
39734        );
39735        assert_eq!(
39736            reduced.chunk_fetches,
39737            2 * 5,
39738            "two leaves at 100k keys / 24,576"
39739        );
39740    }
39741
39742    #[test]
39743    fn a_filter_without_a_selectivity_model_keeps_the_inner_domain() {
39744        let profile = profile(1_000_000, 200_000, 400_000);
39745        let scan = PlanNode::Scan(scan("r", "http://ex/name", "lit", 1));
39746        let scan_domain =
39747            join_key_domain_for_node(Some(&profile), &scan, &var("r")).expect("subject HLL");
39748        let filter = PlanNode::Filter {
39749            inner: Box::new(scan),
39750            early: None,
39751            residual: Some(Expression::Variable(var("lit"))),
39752            exists: Vec::new(),
39753            one_to_one: false,
39754        };
39755        assert_eq!(
39756            join_key_domain_for_node(Some(&profile), &filter, &var("r")),
39757            Some(scan_domain),
39758            "an absent selectivity model must not clamp a possibly push-clamped row cell"
39759        );
39760    }
39761
39762    #[test]
39763    fn a_filter_selectivity_bounds_the_surviving_key_domain() {
39764        assert_eq!(filter_domain_bound(817_000, 817_000, 500), 408_500);
39765        // The inner domain smaller than the output bound wins.
39766        assert_eq!(filter_domain_bound(100, 1_000, 500), 100);
39767        // The output bound smaller than the inner domain wins.
39768        assert_eq!(filter_domain_bound(817_000, 1_000, 500), 500);
39769    }
39770
39771    #[test]
39772    fn filter_cost_rates_follow_the_capability_split() {
39773        let encoded = Expression::Bound(var("v"));
39774        let maybe = Expression::Greater(
39775            Box::new(Expression::Variable(var("a"))),
39776            Box::new(Expression::Variable(var("b"))),
39777        );
39778        let resolved = Expression::Equal(
39779            Box::new(Expression::Variable(var("v"))),
39780            Box::new(Expression::FunctionCall(
39781                spargebra::algebra::Function::UCase,
39782                vec![Expression::Variable(var("v"))],
39783            )),
39784        );
39785        assert_eq!(classify(&encoded), ExprCapability::AlwaysEncoded);
39786        assert_eq!(classify(&maybe), ExprCapability::MaybeEncoded);
39787        assert_eq!(classify(&resolved), ExprCapability::AlwaysResolve);
39788        assert_eq!(filter_row_cost_milli(Some(&encoded), None), 5);
39789        assert_eq!(filter_row_cost_milli(Some(&maybe), None), 50);
39790        assert_eq!(filter_row_cost_milli(None, Some(&resolved)), 200);
39791        // A conjunction pays each conjunct independently.
39792        let both = Expression::And(Box::new(encoded), Box::new(resolved));
39793        assert_eq!(filter_row_cost_milli(Some(&both), None), 205);
39794    }
39795
39796    #[test]
39797    fn filter_selectivity_none_keeps_the_input_estimate() {
39798        let inner_rows = 1_000_000;
39799        let filter = PlanNode::Filter {
39800            inner: Box::new(PlanNode::Scan(scan(
39801                "r",
39802                "http://ex/name",
39803                "lit",
39804                inner_rows,
39805            ))),
39806            early: None,
39807            residual: Some(Expression::Variable(var("lit"))),
39808            exists: Vec::new(),
39809            one_to_one: false,
39810        };
39811        assert_eq!(
39812            filter.produced_row_count_estimate(),
39813            inner_rows,
39814            "no selectivity model => pass-through"
39815        );
39816        assert_eq!(
39817            apply_filter_selectivity(
39818                inner_rows,
39819                None,
39820                Some(&Expression::Variable(var("lit"))),
39821                &[],
39822            ),
39823            inner_rows,
39824        );
39825    }
39826
39827    #[test]
39828    fn filter_cost_is_added_to_the_page_and_once_costs() {
39829        let profile = profile(1_000_000, 200_000, 400_000);
39830        let scan = PlanNode::Scan(scan("r", "http://ex/name", "lit", 1_000_000));
39831        let resolved = Expression::Equal(
39832            Box::new(Expression::Variable(var("lit"))),
39833            Box::new(Expression::FunctionCall(
39834                spargebra::algebra::Function::UCase,
39835                vec![Expression::Variable(var("lit"))],
39836            )),
39837        );
39838        let filter = PlanNode::Filter {
39839            inner: Box::new(scan.clone()),
39840            early: None,
39841            residual: Some(resolved),
39842            exists: Vec::new(),
39843            one_to_one: false,
39844        };
39845        let push = ContainingPush {
39846            key: var("r"),
39847            pushed_val_count: 100_000,
39848        };
39849        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39850        let base_page = subtree_page_cost(Some(&profile), &scan, &push, None, &mut budget);
39851        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39852        let filtered_page = subtree_page_cost(Some(&profile), &filter, &push, None, &mut budget);
39853        assert_eq!(
39854            filtered_page.rows - base_page.rows,
39855            base_page.rows * crate::query::tunables::FILTER_RESOLVE_ROW_EQUIV_MILLI / 1000,
39856            "the resolve conjunct adds one rate per matched page row"
39857        );
39858        assert_eq!(filtered_page.seeks, base_page.seeks);
39859
39860        let base_once = driver_once_cost(Some(&profile), &scan, None);
39861        let filtered_once = driver_once_cost(Some(&profile), &filter, None);
39862        assert_eq!(
39863            filtered_once.rows - base_once.rows,
39864            1_000_000 * crate::query::tunables::FILTER_RESOLVE_ROW_EQUIV_MILLI / 1000,
39865            "the once-cost charges the filter over the inner's output rows"
39866        );
39867
39868        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39869        let build = estimate_semi_build_drain(
39870            Some(&profile),
39871            &filter,
39872            SemiBuildPushSource::AncestorPushesOnly,
39873            &[],
39874            &mut budget,
39875        )
39876        .expect("the scan leaf is priceable");
39877        assert!(
39878            build.filter_eval_milli > 0,
39879            "the semijoin build must charge the filter over the pushed read"
39880        );
39881    }
39882
39883    #[test]
39884    fn a_sensitivity_mark_on_a_name_the_join_does_not_produce_is_ignored() {
39885        let left = PlanNode::Scan(scan("a", "http://ex/p", "b", 10_000));
39886        let right = PlanNode::Scan(scan("a", "http://ex/q", "c", 10_000));
39887        let join = join(left, right, &["a"], &[1_000], 10_000);
39888        // DISTINCT ?a keeps the join key bag-insensitive; a filter above the
39889        // join marks ?z sensitive, but this join does not produce ?z. This
39890        // is the requirement map the liveness walk hands the join.
39891        let mut required = HashMap::new();
39892        required.insert(var("a"), SlotMark::LIVE_INSENSITIVE);
39893        required.insert(var("z"), SlotMark::LIVE_SENSITIVE);
39894        let PlanNode::Join { left, right, .. } = &join else {
39895            unreachable!()
39896        };
39897        let context = join_semi_context(&required, left, right, &HashMap::new(), false, &[], false);
39898        assert!(
39899            !context.row_multiplicity_observed,
39900            "?z belongs to another branch; it cannot observe this join's duplicates"
39901        );
39902    }
39903
39904    #[test]
39905    fn ancestor_pushes_only_equals_the_unpushed_read_without_ancestors() {
39906        let profile = profile(1_000_000, 200_000, 400_000);
39907        let right = literal_subtree();
39908
39909        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39910        let whole = estimate_semi_build_drain(
39911            Some(&profile),
39912            &right,
39913            SemiBuildPushSource::AncestorPushesOnly,
39914            &[],
39915            &mut budget,
39916        )
39917        .expect("the two literal leaves are profile-backed");
39918        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39919        let unpushed = unpushed_read_rows(Some(&profile), &right, &mut budget)
39920            .expect("the two literal leaves are profile-backed");
39921        assert_eq!(
39922            whole.read_rows, unpushed,
39923            "the regular build is the ancestor-pushes-only drain, which is the \
39924             fully unpushed read when there are no ancestors"
39925        );
39926        assert_eq!(whole.pushed_terms, 0, "no current driver list is pushed");
39927        assert_eq!(whole.chunk_fetches, 0);
39928
39929        // An inherited ancestor list still reaches the scans.
39930        let key = var("r");
39931        let ancestors = [AncestorPushKey {
39932            key: key.clone(),
39933            list: 100_000,
39934        }];
39935        let mut budget = SUBTREE_WALK_NODE_BUDGET;
39936        let reduced = estimate_semi_build_drain(
39937            Some(&profile),
39938            &right,
39939            SemiBuildPushSource::AncestorPushesOnly,
39940            &ancestors,
39941            &mut budget,
39942        )
39943        .expect("the ancestor list composes with the leaf domains");
39944        assert!(
39945            (450_000..600_000).contains(&reduced.read_rows),
39946            "the ancestor list, not the driver domain, must filter the drain: {}",
39947            reduced.read_rows
39948        );
39949        assert_eq!(reduced.pushed_terms, 2 * 100_000);
39950        assert_eq!(reduced.chunk_fetches, 2 * 5);
39951    }
39952
39953    #[test]
39954    fn the_verdict_needs_work_to_amortize_and_a_build_to_price() {
39955        assert_eq!(
39956            semi_build_verdict(&verdict_price(0, 100, 10, 10)),
39957            SemiBuildVerdict::PerPage,
39958            "no driver pages means nothing to amortize"
39959        );
39960        assert_eq!(
39961            semi_build_verdict(&verdict_price(1, 100, 0, 0)),
39962            SemiBuildVerdict::PerPage,
39963            "an empty build read must not divide by zero"
39964        );
39965        assert_eq!(
39966            semi_build_verdict(&verdict_price(1, 99, 10, 100)),
39967            SemiBuildVerdict::PerPage,
39968            "below the build bar keeps the per-page road"
39969        );
39970        assert_eq!(
39971            semi_build_verdict(&verdict_price(1, 100, 10, 100)),
39972            SemiBuildVerdict::Build,
39973            "equality meets the bar"
39974        );
39975    }
39976
39977    #[test]
39978    fn subtree_right_under_count_distinct_admits() {
39979        let profile = profile(1_000_000, 200_000, 400_000);
39980        let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
39981        let log = admission_log(&mut group, Some(&profile), false);
39982        let line = admit_line(&log);
39983        assert!(
39984            line.contains("-> admit"),
39985            "the t4-shaped boundary must admit the build-once road:\n{line}"
39986        );
39987        let build_read = line
39988            .split("build_read=")
39989            .nth(1)
39990            .expect("build_read field")
39991            .split_whitespace()
39992            .next()
39993            .expect("build_read value")
39994            .parse::<u64>()
39995            .expect("numeric build_read");
39996        assert_eq!(
39997            build_read, 2_000_000,
39998            "the regular build is the ancestor-pushes-only drain: both literal \
39999             scans read whole, with no driver-domain push:\n{line}"
40000        );
40001        assert!(
40002            line.contains("build_source=ancestor-pushes-only"),
40003            "the admission must name the build frame it priced:\n{line}"
40004        );
40005        assert!(
40006            line.contains("build_seeks=0") && line.contains("build_rpcs=0"),
40007            "no driver or ancestor lists reach this build:\n{line}"
40008        );
40009        assert!(
40010            line.contains("unpushed_read=2000000") && line.contains("unpushed_out=2000000"),
40011            "the fully unpushed frame is the two raw literal reads, not the \
40012             driver-pushed build:\n{line}"
40013        );
40014        assert!(
40015            !line.contains("refuse"),
40016            "an admitted candidate must not also name a refusal:\n{line}"
40017        );
40018    }
40019
40020    #[test]
40021    fn the_recorded_facts_are_applied_as_semi_only_after_the_specialized_claim() {
40022        let profile = profile(1_000_000, 200_000, 400_000);
40023        let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40024        let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest());
40025
40026        // Record only: the final liveness round leaves the facts on the join
40027        // and the strategy at whatever seating chose.
40028        annotate_liveness(
40029            &mut group,
40030            &[var("dim"), var("n")],
40031            &[],
40032            false,
40033            Some(&profile),
40034            Some(&ctx),
40035        );
40036        let PlanNode::Group { inner, .. } = &group else {
40037            unreachable!()
40038        };
40039        let PlanNode::Join { meta, .. } = inner.as_ref() else {
40040            unreachable!()
40041        };
40042        assert!(
40043            meta.semi_gate.is_some(),
40044            "the final liveness round records the gate facts"
40045        );
40046        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
40047
40048        stamp_semi_join_strategy(&mut group, Some(&profile), false, Some(&ctx), &[]);
40049
40050        let PlanNode::Group { inner, .. } = &group else {
40051            unreachable!()
40052        };
40053        let PlanNode::Join { meta, .. } = inner.as_ref() else {
40054            unreachable!()
40055        };
40056        assert_eq!(meta.strategy, JoinStrategy::Semi);
40057        assert!(
40058            meta.semi_gate.is_none(),
40059            "the stamp pass consumes the recorded facts"
40060        );
40061    }
40062
40063    #[test]
40064    fn an_order_key_outside_the_projection_stays_live_and_sensitive() {
40065        let mut root = PlanNode::Scan(scan("s", "http://ex/p", "o", 10_000));
40066        annotate_liveness(&mut root, &[var("s")], &[var("o")], false, None, None);
40067        let PlanNode::Scan(scan) = &root else {
40068            unreachable!()
40069        };
40070        assert!(
40071            scan.is_live(&var("o")),
40072            "a top-level ORDER BY key is read above the projection and must stay live"
40073        );
40074        assert_eq!(
40075            scan.bag_mark(&var("o")),
40076            Some(BagMark::Sensitive),
40077            "a sort key must not become a collapse key"
40078        );
40079        assert!(
40080            scan.domain_scan.is_none() && scan.head_scan.is_none(),
40081            "a live sort-key slot must block the domain/head rewrites"
40082        );
40083    }
40084
40085    #[test]
40086    fn an_order_key_only_live_above_the_join_refuses_as_payload() {
40087        let profile = profile(1_000_000, 200_000, 400_000);
40088        let mut top = semi_top(600_000, false);
40089        // DISTINCT ?r keeps the projection bag-insensitive; the sort key is
40090        // not projected, so only the ORDER BY seed makes it live above the
40091        // join.
40092        let log = admission_log_top(
40093            &mut top,
40094            &[var("r")],
40095            &[var("lit")],
40096            true,
40097            Some(&profile),
40098            false,
40099        );
40100        let line = admit_line(&log);
40101        assert!(
40102            line.contains("right payload above the join"),
40103            "a right-only ORDER BY key is live above the join and must refuse:\n{line}"
40104        );
40105        assert!(
40106            log.contains("semi-payload:") && log.contains("lit"),
40107            "the recording must name the payload column:\n{log}"
40108        );
40109    }
40110
40111    #[test]
40112    fn a_scan_right_is_a_general_semi_candidate() {
40113        let profile = profile(1_000_000, 200_000, 400_000);
40114        let mut top = semi_top_scan_right(600_000);
40115        let log = admission_log_top(
40116            &mut top,
40117            &[var("r"), var("dim")],
40118            &[],
40119            true,
40120            Some(&profile),
40121            false,
40122        );
40123        let PlanNode::Join { meta, .. } = &top else {
40124            unreachable!()
40125        };
40126        assert_eq!(meta.strategy, JoinStrategy::Semi, "{log}");
40127    }
40128
40129    #[test]
40130    fn a_scan_right_payload_refuses() {
40131        let profile = profile(1_000_000, 200_000, 400_000);
40132        let mut top = semi_top_scan_right_payload(600_000);
40133        let log = admission_log_top(
40134            &mut top,
40135            &[var("r"), var("dim"), var("lit")],
40136            &[],
40137            true,
40138            Some(&profile),
40139            false,
40140        );
40141        let PlanNode::Join { meta, .. } = &top else {
40142            unreachable!()
40143        };
40144        assert_ne!(meta.strategy, JoinStrategy::Semi, "{log}");
40145        assert!(
40146            log.contains("right payload above the join") && log.contains("lit"),
40147            "a live right column must refuse the scan-right build:\n{log}"
40148        );
40149    }
40150
40151    #[test]
40152    fn a_semiscan_eligible_scan_right_keeps_semiscan() {
40153        let profile = profile(1_000_000, 200_000, 400_000);
40154        let mut top = semi_top_scan_right(600_000);
40155        // The fixture does not run `restamp_fetch_once`; stamp the outer
40156        // right scan's verdict directly.
40157        let PlanNode::Join { right, .. } = &mut top else {
40158            unreachable!()
40159        };
40160        let PlanNode::Scan(scan) = right.as_mut() else {
40161            unreachable!()
40162        };
40163        scan.fetch_once = Some(1_000_000);
40164        let log = admission_log_top(
40165            &mut top,
40166            &[var("r"), var("dim")],
40167            &[],
40168            true,
40169            Some(&profile),
40170            false,
40171        );
40172        let PlanNode::Join { meta, .. } = &top else {
40173            unreachable!()
40174        };
40175        assert_eq!(meta.strategy, JoinStrategy::SemiScan, "{log}");
40176        assert!(
40177            meta.semi_gate.is_none(),
40178            "the general record is consumed even when the specialized claim wins"
40179        );
40180    }
40181
40182    #[test]
40183    fn the_plan_tree_names_the_general_semi_strategy() {
40184        let left = PlanNode::Scan(scan("r", "http://ex/p", "o", 10));
40185        let right = PlanNode::Scan(scan("r", "http://ex/q", "o", 10));
40186        let mut join = join(left, right, &["r"], &[10], 10);
40187        let PlanNode::Join { meta, .. } = &mut join else {
40188            unreachable!()
40189        };
40190        meta.strategy = JoinStrategy::Semi;
40191        let text = crate::explain::format_star_plan(&join);
40192        assert!(
40193            text.contains("(semi"),
40194            "EXPLAIN must name the strategy:
40195{text}"
40196        );
40197        assert!(
40198            !text.contains("(semi-scan"),
40199            "the general road must not render as the scan special case:
40200{text}"
40201        );
40202    }
40203
40204    #[test]
40205    fn a_star_arm_never_gets_the_general_semi_stamp() {
40206        let profile = profile(1_000_000, 200_000, 400_000);
40207        let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40208        let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest());
40209        annotate_liveness(
40210            &mut group,
40211            &[var("dim"), var("n")],
40212            &[],
40213            false,
40214            Some(&profile),
40215            Some(&ctx),
40216        );
40217        let PlanNode::Group { inner, .. } = &mut group else {
40218            unreachable!()
40219        };
40220        let PlanNode::Join { meta, .. } = inner.as_mut() else {
40221            unreachable!()
40222        };
40223        assert!(
40224            meta.semi_gate.is_some(),
40225            "the fixture must record the general gate facts"
40226        );
40227        // A star stamp and the general gate cannot both own the join.
40228        meta.star_arms = Some(1);
40229        stamp_semi_join_strategy(&mut group, Some(&profile), false, Some(&ctx), &[]);
40230        let PlanNode::Group { inner, .. } = &group else {
40231            unreachable!()
40232        };
40233        let PlanNode::Join { meta, .. } = inner.as_ref() else {
40234            unreachable!()
40235        };
40236        assert_ne!(
40237            meta.strategy,
40238            JoinStrategy::Semi,
40239            "a star arm is not a semi build"
40240        );
40241        assert!(meta.semi_gate.is_none(), "the record is consumed");
40242    }
40243
40244    fn count_distinct_of(variable: &str) -> AggregateExpression {
40245        AggregateExpression::FunctionCall {
40246            name: AggregateFunction::Count,
40247            expr: Expression::Variable(var(variable)),
40248            distinct: true,
40249        }
40250    }
40251
40252    #[test]
40253    fn a_right_only_count_distinct_argument_refuses_as_payload() {
40254        let profile = profile(1_000_000, 200_000, 400_000);
40255        // `?lit` is produced only by the literal subtree and is `Counted`,
40256        // not `Live`: the semi schema would drop the column the group counts.
40257        let mut group = semi_shape(count_distinct_of("lit"), &["dim"], 600_000, false);
40258        let log = admission_log(&mut group, Some(&profile), false);
40259        let line = admit_line(&log);
40260        assert!(
40261            line.contains("right payload above the join"),
40262            "a right-only COUNT(DISTINCT ?lit) argument is payload:\n{log}"
40263        );
40264        assert!(
40265            log.contains("semi-payload:") && log.contains("lit"),
40266            "the recording must name the counted column:\n{log}"
40267        );
40268    }
40269
40270    #[test]
40271    fn plain_count_refuses_row_multiplicity() {
40272        let profile = profile(1_000_000, 200_000, 400_000);
40273        let mut group = semi_shape(count_rows(), &["dim"], 600_000, false);
40274        let log = admission_log(&mut group, Some(&profile), false);
40275        assert!(
40276            admit_line(&log).contains("refuse: row multiplicity is observed above the join"),
40277            "plain COUNT(?r) observes the duplicate right rows:\n{log}"
40278        );
40279    }
40280
40281    #[test]
40282    fn count_star_is_refused_explicitly() {
40283        let profile = profile(1_000_000, 200_000, 400_000);
40284        let mut group = semi_shape(count_star(), &["dim"], 600_000, false);
40285        let log = admission_log(&mut group, Some(&profile), false);
40286        assert!(
40287            admit_line(&log).contains("refuse: plain COUNT(*) above the join"),
40288            "COUNT(*) must name its own refusal, not fall through to the bag rule:\n{log}"
40289        );
40290    }
40291
40292    #[test]
40293    fn right_payload_above_the_join_refuses() {
40294        let profile = profile(1_000_000, 200_000, 400_000);
40295        // `?lit` is a group key here, so it is live above the join and the
40296        // right subtree is its only producer.
40297        let mut group = semi_shape(count_distinct(), &["dim", "lit"], 600_000, false);
40298        let log = admission_log(&mut group, Some(&profile), false);
40299        let line = admit_line(&log);
40300        assert!(
40301            line.contains("right payload above the join"),
40302            "a right-only live column must be refused as payload:\n{line}"
40303        );
40304        assert!(
40305            log.contains("semi-payload:") && log.contains("lit"),
40306            "the recording must name the payload column:\n{log}"
40307        );
40308    }
40309
40310    #[test]
40311    fn a_specialized_scan_in_the_right_subtree_refuses() {
40312        let profile = profile(1_000_000, 200_000, 400_000);
40313        let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40314        let PlanNode::Group { inner, .. } = &mut group else {
40315            unreachable!()
40316        };
40317        let PlanNode::Join {
40318            left,
40319            right,
40320            hash_keys,
40321            meta,
40322            ..
40323        } = inner.as_mut()
40324        else {
40325            unreachable!()
40326        };
40327        assert!(
40328            mark_first_scan_specialized(right),
40329            "fixture must put a scan under the right"
40330        );
40331        // The liveness pass clears and re-derives every specialized-scan
40332        // stamp, so this gate is asserted on the admission itself rather
40333        // than through a round that would erase the fixture mark.
40334        let facts = SemiGateFacts {
40335            right_payload: false,
40336            row_multiplicity_observed: false,
40337            count_star: false,
40338        };
40339        let refusal = semi_join_admission(
40340            left,
40341            right,
40342            hash_keys,
40343            meta,
40344            &facts,
40345            &[],
40346            false,
40347            Some(&profile),
40348            None,
40349        )
40350        .expect_err("a specialized scan under the right must refuse");
40351        assert!(
40352            matches!(refusal, SemiRefusal::SpecializedScan),
40353            "a count/domain rewrite under the right is not the pattern's rows: {}",
40354            refusal.describe()
40355        );
40356    }
40357
40358    #[test]
40359    fn an_unknown_driver_domain_refuses() {
40360        let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40361        let log = admission_log(&mut group, None, false);
40362        assert!(
40363            admit_line(&log).contains("driver key domain unknown"),
40364            "no profile means no honest page geometry:\n{log}"
40365        );
40366    }
40367
40368    #[test]
40369    fn an_unknown_build_estimate_refuses() {
40370        let mut profile = profile(1_000_000, 200_000, 400_000);
40371        // The driver side is known; the literal leaves have no sketch, so
40372        // the build read is a fiction.
40373        profile
40374            .predicate_counts
40375            .remove(&StrHash::new("http://ex/name"));
40376        profile
40377            .predicate_counts
40378            .remove(&StrHash::new("http://ex/abstract"));
40379        let mut group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40380        let log = admission_log(&mut group, Some(&profile), false);
40381        assert!(
40382            admit_line(&log).contains("build read estimate unknown"),
40383            "a missing literal sketch must refuse the build price:\n{log}"
40384        );
40385    }
40386
40387    #[test]
40388    fn a_sliced_subtree_refuses() {
40389        let profile = profile(1_000_000, 200_000, 400_000);
40390        let group = semi_shape(count_distinct(), &["dim"], 600_000, false);
40391        let PlanNode::Group { inner, .. } = &group else {
40392            unreachable!()
40393        };
40394        let PlanNode::Join {
40395            left,
40396            right,
40397            hash_keys,
40398            meta,
40399            ..
40400        } = inner.as_ref()
40401        else {
40402            unreachable!()
40403        };
40404        let facts = SemiGateFacts {
40405            right_payload: false,
40406            row_multiplicity_observed: false,
40407            count_star: false,
40408        };
40409        // The stamp pass suppresses the subtree below any Slice; the gate
40410        // still refuses if it is reached, which is what this pins.
40411        let refusal = semi_join_admission(
40412            left,
40413            right,
40414            hash_keys,
40415            meta,
40416            &facts,
40417            &[],
40418            true,
40419            Some(&profile),
40420            None,
40421        )
40422        .expect_err("the OpenNode slice path never consults JoinStrategy");
40423        assert!(
40424            matches!(refusal, SemiRefusal::SlicedSubtree),
40425            "{}",
40426            refusal.describe()
40427        );
40428    }
40429
40430    #[test]
40431    fn a_join_below_a_slice_is_not_stamped() {
40432        let profile = profile(1_000_000, 200_000, 400_000);
40433        let mut root = PlanNode::Slice {
40434            inner: Box::new(semi_shape(count_distinct(), &["dim"], 600_000, false)),
40435            start: 0,
40436            length: Some(10),
40437        };
40438        let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest());
40439        annotate_liveness(
40440            &mut root,
40441            &[var("dim"), var("n")],
40442            &[],
40443            false,
40444            Some(&profile),
40445            Some(&ctx),
40446        );
40447        let PlanNode::Join { meta, .. } = outer_join(&root) else {
40448            unreachable!()
40449        };
40450        assert!(
40451            meta.semi_gate.is_some(),
40452            "the liveness round records the facts even below a Slice"
40453        );
40454
40455        stamp_semi_join_strategy(&mut root, Some(&profile), false, Some(&ctx), &[]);
40456
40457        let PlanNode::Join { meta, .. } = outer_join_mut(&mut root) else {
40458            unreachable!()
40459        };
40460        assert_ne!(
40461            meta.strategy,
40462            JoinStrategy::Semi,
40463            "the Slice path runs through OpenNode, which ignores JoinStrategy"
40464        );
40465        assert!(meta.semi_gate.is_none(), "the record is consumed");
40466    }
40467
40468    #[test]
40469    fn a_join_in_an_exists_body_is_not_stamped() {
40470        let profile = profile(1_000_000, 200_000, 400_000);
40471        let mut root = PlanNode::Filter {
40472            inner: Box::new(PlanNode::Scan(scan("s", "http://ex/p", "o", 10))),
40473            early: None,
40474            residual: None,
40475            exists: vec![ExistsClause {
40476                negated: false,
40477                body: Box::new(semi_shape(count_distinct(), &["dim"], 600_000, false)),
40478                correlation: Vec::new(),
40479                kind: ExistsKind::Uncorrelated,
40480            }],
40481            one_to_one: false,
40482        };
40483        let ctx = crate::context::QueryContext::from_snapshot(SnapshotId::latest());
40484        annotate_liveness(
40485            &mut root,
40486            &[var("dim"), var("n")],
40487            &[],
40488            false,
40489            Some(&profile),
40490            Some(&ctx),
40491        );
40492        let PlanNode::Join { meta, .. } = outer_join(&root) else {
40493            unreachable!()
40494        };
40495        assert!(
40496            meta.semi_gate.is_some(),
40497            "the liveness round records the facts inside the EXISTS body"
40498        );
40499
40500        stamp_semi_join_strategy(&mut root, Some(&profile), false, Some(&ctx), &[]);
40501
40502        let PlanNode::Join { meta, .. } = outer_join_mut(&mut root) else {
40503            unreachable!()
40504        };
40505        assert_ne!(
40506            meta.strategy,
40507            JoinStrategy::Semi,
40508            "an EXISTS body is evaluated through OpenNode"
40509        );
40510        assert!(meta.semi_gate.is_none(), "the record is consumed");
40511    }
40512
40513    #[test]
40514    fn one_page_keeps_the_per_page_road() {
40515        let profile = profile(1_000_000, 200_000, 400_000);
40516        let mut group = semi_shape(count_distinct(), &["dim"], 1_000, false);
40517        let log = admission_log(&mut group, Some(&profile), false);
40518        let line = admit_line(&log);
40519        assert!(
40520            line.contains("per-page road is cheaper") && line.contains("pages=1"),
40521            "one page of a known list cannot amortize a two-million-row build:\n{line}"
40522        );
40523    }
40524
40525    #[test]
40526    fn a_second_key_is_refused_by_the_first_cut() {
40527        let profile = profile(1_000_000, 200_000, 400_000);
40528        let mut group = semi_shape(count_distinct(), &["dim"], 600_000, true);
40529        let log = admission_log(&mut group, Some(&profile), false);
40530        assert!(
40531            admit_line(&log).contains("2 join keys"),
40532            "the first cut is deliberately one key:\n{log}"
40533        );
40534    }
40535}
40536
40537#[cfg(test)]
40538mod flat_leaf_tests {
40539    use super::*;
40540
40541    /// A FILTER that sparopt pushed onto one triple is a flat pipeline leaf:
40542    /// the pipeline orders the filtered scan with its siblings by the scan's
40543    /// estimate, and lowering wraps that scan in the filter. Before this, the
40544    /// non-pinned path bypassed the pipeline ordering entirely because
40545    /// `collect_flat_leaves` refused any Filter.
40546    #[test]
40547    fn a_pushed_single_triple_filter_is_a_flat_pipeline_leaf() {
40548        let mut profile = StatsProfile::default();
40549        profile
40550            .predicate_counts
40551            .insert(StrHash::new("http://ex/p"), 10);
40552        profile
40553            .predicate_counts
40554            .insert(StrHash::new("http://ex/q"), 1_000);
40555        let plan = LogicalPlan::parse_with_profile(
40556            r#"SELECT ?s ?o ?x WHERE {
40557                ?s <http://ex/p> ?o .
40558                FILTER(STR(?o) != "x")
40559                ?s <http://ex/q> ?x .
40560            }"#,
40561            Some(&profile),
40562        )
40563        .expect("the query plans");
40564        let PlanNode::Join { left, right, .. } = &plan.root else {
40565            panic!(
40566                "the pushed filter must flatten into one pipeline, got {:?}",
40567                plan.root
40568            );
40569        };
40570        let PlanNode::Filter { inner, .. } = left.as_ref() else {
40571            panic!("the smaller filtered scan must be the left leaf, got {left:?}");
40572        };
40573        let PlanNode::Scan(scan) = inner.as_ref() else {
40574            panic!("the filter leaf must wrap its scan, got {inner:?}");
40575        };
40576        assert_eq!(scan.object, Some(Variable::new_unchecked("o")));
40577        let PlanNode::Scan(q) = right.as_ref() else {
40578            panic!("the larger scan must be the right leaf, got {right:?}");
40579        };
40580        assert_eq!(q.object, Some(Variable::new_unchecked("x")));
40581    }
40582}