Skip to main content

waratah_geo/
plan.rs

1//! PlannerPlugin: `FILTER geof:*(const, ?g)` → `Join(geo_scan, inner, ?g)`.
2//!
3//! **Rewrite scope (plan §5):** `Filter.residual` conjuncts (top-level `&&`
4//! flattening, same as `split_filter`), recursing into inner plans and EXISTS
5//! clause bodies — never `early`; the SPARQL algebra FILTER tree is gone
6//! after `lower_pattern`. A conjunct rewrites only when
7//!
8//! - it is `geof:sfContains` / `sfWithin` / `sfIntersects`,
9//! - one argument is a **ground** geometry literal (plan-time const),
10//! - the other is a **variable**,
11//! - the constant is a supported CRS and passes validation (so it has a
12//!   native term, covering, and envelope).
13//!
14//! The stripped conjunct is a complete implementation: `geo_scan` relates
15//! every candidate exactly (PreparedGeometry) before the join, so rows are
16//! kept exactly as SPARQL `FILTER` would (an error in the geo side drops the
17//! row, same as `error && rest`). Unbound `?g` (OPTIONAL miss, TermId 0)
18//! never matches the scan output because the hash key is always bound on
19//! scan rows. Both-args-variable / BIND wrappers / `Other` CRS: no rewrite;
20//! the residual custom fn handles them (slow path). Repeat executions of the
21//! injected childless `geo_scan` op — EXISTS NestedProbe re-opens per outer
22//! page, expr-substitution groups, duplicate identical conjuncts — are
23//! covered by the query-local CustomOp memo (one drain per query, see
24//! `ARCH.md` §7).
25//!
26//! **Broadcast participation:** the injected join puts the smaller arm on
27//! the left (geo estimate = covered area × placeholder density). A small
28//! geo scan stays the LEFT (build) arm and sweeps once; a large one becomes
29//! the RIGHT (probe) arm and at execution receives the driver's pushed join
30//! keys — the executor relates small key lists directly, semi-joins large
31//! ones against the candidate sweep, and sweeps unconditionally without
32//! keys (see `waratah_geo/src/exec.rs`). A ground-unique driver pins its
33//! single term into the op (`CustomOp.pinned`), mirroring a Scan's grounded
34//! pattern slot.
35
36use s2rst::s2::CellUnion;
37use spargebra::algebra::Expression;
38use waratah_compute::ComputeError;
39use waratah_compute::JoinStrategy;
40use waratah_compute::PlanNode;
41use waratah_compute::QueryContext;
42use waratah_compute::ground_unique_probe_term;
43use waratah_compute::plugin::{PlannerPlugin, PluginPayloadBox};
44use waratah_stats::PUSHDOWN_TERMS_LIMIT;
45use waratah_storage::{EncodedTerm, Variable};
46
47use crate::relate::GeoPredicate;
48
49/// `geo_scan` op id on the CustomOp node.
50pub const GEO_SCAN_OP_ID: &str = "geo_scan";
51
52/// Priced work of one keyed-regime key — and one keyless-regime candidate —
53/// in the seating-cost model's rows currency: a blob-backed geometry costs one
54/// amortized batched blob fetch, an EWKB parse, and an exact Relate, call it
55/// 8 row-units against a ~1-unit inline-point relate. Conservative
56/// placeholder until bench calibration; consumed through `CustomOpCost` by
57/// EXPLAIN today and by the executor's regime choice and the planner's
58/// placement in follow-ups.
59pub const GEO_RELATE_UNIT_ROWS: u64 = 8;
60
61/// Priced work of one INLINE key — a `LiteralPoint` relates from its stored
62/// coordinates with no blob fetch and no parse, so its cost is the bare
63/// relate itself. The executor prices the direct road per ACTUAL key shape
64/// with this unit (`CustomOpCost::inline_point_unit`); the planner's
65/// `keyed_cost` never uses it (it knows counts, not shapes).
66pub const GEO_INLINE_POINT_UNIT_ROWS: u64 = 1;
67
68/// GeoSPARQL planner hook.
69#[derive(Debug, Default)]
70pub struct GeoPlannerPlugin;
71
72/// Whether `expression` is a `geof:sf*` comparison this plugin turns into a
73/// `geo_scan` candidate producer. The pin and the ground-substitution guard
74/// both key on this one predicate, so they cannot drift apart.
75fn is_geo_scan_conjunct(expression: &Expression) -> bool {
76    matches!(
77        expression,
78        Expression::FunctionCall(spargebra::algebra::Function::Custom(iri), _)
79            if GeoPredicate::from_iri(iri.as_str()).is_some()
80    )
81}
82
83impl PlannerPlugin for GeoPlannerPlugin {
84    /// A `geof:sf*` comparison this plugin can turn into a `geo_scan`
85    /// candidate producer. A producer built twice would drain the S2 covering
86    /// again and re-join it into the plan, so it is pinned across the algebra
87    /// optimizer. The test is syntactic: a conjunct that is pinned but left
88    /// unrewritten (untrusted index, non-native geometry) stays an ordinary
89    /// filter at its binding-site ancestor.
90    fn pins_through_optimizer(&self, expression: &Expression) -> bool {
91        is_geo_scan_conjunct(expression)
92    }
93
94    /// The geo rewrite joins the covered geometry back to the filtered
95    /// variable, so grounding that variable would leave a per-row relate
96    /// instead of a `geo_scan` joining the candidate set. Same conjunct set as
97    /// [`Self::pins_through_optimizer`], shared through
98    /// [`is_geo_scan_conjunct`] so the two answers cannot drift.
99    fn keeps_variable_when_ground(&self, expression: &Expression) -> bool {
100        is_geo_scan_conjunct(expression)
101    }
102
103    fn rewrite(
104        &self,
105        node: &mut waratah_compute::PlanNode,
106        ctx: &QueryContext,
107    ) -> Result<(), ComputeError> {
108        // Trust gate: rebuilt postings are stamped with the persisted rebuild
109        // epoch, so a snapshot BELOW the epoch must not consult the index —
110        // the geof FILTER stays unrewritten and the residual path answers
111        // (slow, correct, already built). A missing epoch (`None`) means
112        // trusted: the geo plugin is always on in deployment, so the index is
113        // incrementally valid from store creation; a future indexing toggle
114        // must stamp an epoch when it re-enables indexing. `SnapshotId::latest()`
115        // is `u64::MAX` today, so every current query passes; the gate becomes
116        // load-bearing with bounded snapshots.
117        let trusted_from = ctx.geo_index_epoch().unwrap_or(0);
118        if ctx.snapshot().0 < trusted_from {
119            return Ok(());
120        }
121        match node {
122            PlanNode::Filter {
123                inner,
124                early,
125                residual,
126                exists,
127                ..
128            } => {
129                // Depth-first: inner rewrites land first.
130                self.rewrite(inner, ctx)?;
131                // EXISTS clause bodies are walked: an uncorrelated
132                // constant-argument geo conjunct inside an arm rewrites to
133                // the same childless `geo_scan` CustomOp, and the
134                // query-local CustomOp memo covers the NestedProbe re-open
135                // cost (one drain per query).
136                for clause in exists.iter_mut() {
137                    self.rewrite(&mut clause.body, ctx)?;
138                }
139                let Some(residual_expr) = residual else {
140                    return Ok(());
141                };
142                let conjuncts = waratah_compute::flatten_and(residual_expr);
143                let mut remaining: Vec<Expression> = Vec::new();
144                let mut rewritten: Option<PlanNode> = None;
145                for conjunct in conjuncts {
146                    match match_geo_conjunct(&conjunct)? {
147                        Some(geo_shape) => {
148                            // The sink may have left the conjunct above a
149                            // whole join tree (its binding-site unit is the
150                            // BGP set). Inject the candidate join at the
151                            // variable's producer when the inner is a join
152                            // tree; a union or a scope boundary keeps the
153                            // single join above the whole inner.
154                            let mut plan = rewritten.take().unwrap_or_else(|| (**inner).clone());
155                            let variable = geo_shape.variable.clone();
156                            // The covering was computed ONCE in
157                            // `match_geo_conjunct` (payload intervals share
158                            // it). The row estimate reads the rolled-up geo
159                            // cell-count histogram when the profile carries
160                            // one (exact per-bucket counts, over-estimate
161                            // biased); otherwise it falls back to the
162                            // covering area × placeholder density — a bigger
163                            // polygon costs more candidates than a point.
164                            let geo_rows = match ctx.geo_cell_histogram() {
165                                Some(histogram) => {
166                                    crate::covering::covering_estimate_rows_from_histogram(
167                                        histogram,
168                                        &geo_shape.covering,
169                                    )
170                                }
171                                None => {
172                                    crate::covering::covering_estimate_rows(&geo_shape.covering)
173                                }
174                            };
175                            let scan = waratah_compute::CustomOp {
176                                plugin_id: crate::PLUGIN_ID,
177                                op_id: GEO_SCAN_OP_ID,
178                                payload: PluginPayloadBox::new(geo_shape.payload),
179                                children: Vec::new(),
180                                variables: vec![variable.clone()],
181                                produced_row_count_estimate: geo_rows,
182                                // The drain's priced walk and the candidate
183                                // estimate share one number: with a profile
184                                // histogram it is the bucket-count ladder;
185                                // without one, the covering-area fallback.
186                                cost: Some(waratah_compute::CustomOpCost {
187                                    drain_rows: geo_rows,
188                                    per_key_unit: GEO_RELATE_UNIT_ROWS,
189                                    inline_point_unit: GEO_INLINE_POINT_UNIT_ROWS,
190                                    direct_probe: true,
191                                    probe_keyed_columns: 0b1,
192                                    probe_filter_unit: GEO_RELATE_UNIT_ROWS,
193                                    // Deliberately 0: the geo drain memo DOES
194                                    // amortize the candidate window at
195                                    // runtime, but the cost model's
196                                    // `probe_drain_amortized` compares this
197                                    // limit with the op's OUTPUT estimate,
198                                    // while the memo admits the candidate
199                                    // WINDOW (`drain_rows`). A polygon's
200                                    // output can be far smaller than its
201                                    // drain, so a non-zero limit here would
202                                    // let the cost model charge the drain once for
203                                    // a window the memo refuses — an
204                                    // under-price. 0 charges the drain per
205                                    // page (over-price, never under). Making
206                                    // it honest needs the comparison to use
207                                    // `drain_rows`, plus a geo benchmark run.
208                                    probe_memo_entry_rows: 0,
209                                }),
210                                pinned: Vec::new(),
211                            };
212                            let mut op = Some(scan);
213                            let injected = inject_at_producer(&mut plan, &variable, &mut op);
214                            rewritten = Some(if injected {
215                                plan
216                            } else {
217                                build_geo_scan_join(
218                                    plan,
219                                    op.take()
220                                        .expect("the uninjected producer op is still owned"),
221                                    variable,
222                                )
223                            });
224                        }
225                        None => remaining.push(conjunct),
226                    }
227                }
228                if let Some(join) = rewritten {
229                    // Re-&& the untouched conjuncts; drop the Filter node
230                    // entirely when nothing remains (early/exists included).
231                    *residual = waratah_compute::and_fold(remaining);
232                    if residual.is_none() && early.is_none() && exists.is_empty() {
233                        *node = join;
234                    } else {
235                        **inner = join;
236                    }
237                }
238                Ok(())
239            }
240            // Every other node: recurse through children where present.
241            PlanNode::Join { left, right, .. }
242            | PlanNode::LeftJoin { left, right, .. }
243            | PlanNode::Union { left, right } => {
244                self.rewrite(left, ctx)?;
245                self.rewrite(right, ctx)
246            }
247            PlanNode::CustomNode(op) => {
248                for child in &mut op.children {
249                    self.rewrite(child, ctx)?;
250                }
251                Ok(())
252            }
253            PlanNode::Scan(_)
254            | PlanNode::Path(_)
255            | PlanNode::Unit
256            | PlanNode::Values(_)
257            | PlanNode::NamedGraphs { .. }
258            | PlanNode::NamedGraphExists { .. }
259            | PlanNode::DomainCounts { .. }
260            | PlanNode::HeadCounts { .. }
261            | PlanNode::PatternCount { .. }
262            | PlanNode::SubSelect(_) => Ok(()),
263            PlanNode::Extend { inner, .. }
264            | PlanNode::Slice { inner, .. }
265            | PlanNode::Distinct { inner, .. }
266            | PlanNode::Sort { inner, .. }
267            | PlanNode::Group { inner, .. }
268            | PlanNode::JoinGraphVar { inner, .. } => self.rewrite(inner, ctx),
269        }
270    }
271}
272
273/// Join one geo candidate op with the plan it filters.
274///
275/// `site` is either the whole inner (the UNION / scope-boundary fallback) or
276/// the filtered variable's producer inside a join tree. `site_rows` is that
277/// plan's estimate, so the injected join is priced against the subtree it
278/// actually joins rather than the outer BGP.
279fn build_geo_scan_join(
280    site: waratah_compute::PlanNode,
281    mut op: waratah_compute::CustomOp,
282    variable: Variable,
283) -> waratah_compute::PlanNode {
284    let site_rows = site.produced_row_count_estimate();
285    // Smaller arm drives. The geo estimate sits against the site plan's: a
286    // small polygon stays the LEFT (build) arm and sweeps once; a large one
287    // becomes the RIGHT (probe) arm and receives the driver's pushed `?g`
288    // keys at execution (direct relate / semi-join sweep — the executor
289    // decides by key count).
290    let mut pinned = false;
291    let (left, right) = if op.produced_row_count_estimate <= site_rows {
292        (waratah_compute::PlanNode::CustomNode(op), site)
293    } else {
294        // Ground-unique driver: pin the driver's single term into the op —
295        // the generic emulation of a Scan's grounded pattern slot. The
296        // executor relates exactly it, no candidate scan, no key delivery.
297        if let Some(term) = ground_unique_probe_term(&site, &variable) {
298            op.pinned.push((variable.clone(), term));
299            op.produced_row_count_estimate = 1;
300            pinned = true;
301        }
302        (site, waratah_compute::PlanNode::CustomNode(op))
303    };
304    // Rewrite-time estimate = the DRIVER arm's rows, not the join's output.
305    // The rewrite stage has no key domains, and pricing the cluster at the
306    // site's whole read leaves a selective op invisible to the seed choice
307    // (the association then starts on the scan side and the cluster joins
308    // last — the regression this replaces). The smaller arm is the left
309    // (driver), so its rows are the estimate; a pinned point probe keeps
310    // the site's rows, which is its driver. This value only seeds the
311    // association: `refinalize_joins` replaces it with the domain-aware
312    // `finalize_inner_join_meta` output estimate before any ancestor join,
313    // broadcast clamp, or seating price reads it. The seed bias is m× when
314    // the site has more than one row per ?wkt (shared geometry literals);
315    // the two-start comparison and the arm swap bound the damage.
316    let produced = if pinned {
317        site_rows
318    } else {
319        waratah_stats::estimate_join_rows_multi(
320            left.produced_row_count_estimate(),
321            right.produced_row_count_estimate(),
322            &[(None, None)],
323        )
324    };
325    // Broadcast iff the LEFT (build) arm is small — the semantics of
326    // `JoinStrategy::from_estimated_sizes`. A non-broadcast stamp costs the
327    // join as Hash; runtime key delivery is the executor's own size-based
328    // decision either way.
329    let strategy = if left.produced_row_count_estimate() <= PUSHDOWN_TERMS_LIMIT {
330        JoinStrategy::Broadcast
331    } else {
332        JoinStrategy::Hash
333    };
334    // No probe marking here: `restamp_broadcast_marks` (waratah_compute,
335    // sole writer of `ScanOp::broadcasted`) claims this injected join's right
336    // arm in the planning loop that follows, and its claim-clamp derives the
337    // same bound from the geo op's CustomNode key domain
338    // (`op.produced_row_count_estimate`). If a later pass swaps the arms, the
339    // swap-time `clear_broadcast_marks` unmarks the old probe and the next
340    // boundary restamp re-derives. When the geo op is the RIGHT (probe) arm
341    // there is no scan mark: the op itself receives the driver's pushed keys.
342    let rhs_hostable_keys =
343        std::sync::Arc::from(waratah_compute::subtree_hostable_variables(&right));
344    waratah_compute::PlanNode::Join {
345        left: Box::new(left),
346        right: Box::new(right),
347        hash_keys: vec![variable],
348        probe_key_domains: Vec::new(),
349        // The boundary restamp re-derives both stamps for the settled
350        // seating (same pass).
351        probe_key_overlap_milli: Vec::new(),
352        rhs_hostable_keys,
353        meta: waratah_compute::JoinMeta {
354            star_arms: None,
355            strategy,
356            semi_gate: None,
357            produced_row_count_estimate: produced,
358            // Construction-time stamp: both fields carry the same value
359            // until the final estimate-only restamp conditions `produced`
360            // by the planned pushes.
361            own_push_removed_row_count_estimate: produced,
362        },
363    }
364}
365
366/// Replace the filtered variable's producer inside a join tree with the geo
367/// join, so the candidate op is pushed to the producer instead of wrapping
368/// the whole BGP.
369///
370/// The filter sink places a pinned conjunct at the lowest point whose
371/// *binding site* covers the variable; a `Bgp` is one such site, so the
372/// conjunct can sit above a whole join tree. This walk moves the geo join
373/// back down to the node that actually introduces the variable. It crosses
374/// only binding-preserving containers (inner joins, FILTER, BIND, DISTINCT,
375/// SORT) and returns `false` for a UNION, OPTIONAL, MINUS, GROUP, SUBSELECT
376/// or SLICE: those change which rows the filter sees, so the caller keeps
377/// the single join above the whole inner. A variable with no always-bound
378/// producer (a path, another custom op) also returns `false`.
379fn inject_at_producer(
380    node: &mut waratah_compute::PlanNode,
381    variable: &Variable,
382    op: &mut Option<waratah_compute::CustomOp>,
383) -> bool {
384    match node {
385        waratah_compute::PlanNode::Scan(scan)
386            if scan.variables().iter().any(|bound| bound == variable) =>
387        {
388            let Some(op) = op.take() else {
389                return false;
390            };
391            let site = std::mem::replace(node, waratah_compute::PlanNode::Unit);
392            *node = build_geo_scan_join(site, op, variable.clone());
393            true
394        }
395        waratah_compute::PlanNode::Values(values)
396            if values.variables.iter().any(|bound| bound == variable) =>
397        {
398            let Some(op) = op.take() else {
399                return false;
400            };
401            let site = std::mem::replace(node, waratah_compute::PlanNode::Unit);
402            *node = build_geo_scan_join(site, op, variable.clone());
403            true
404        }
405        waratah_compute::PlanNode::Join { left, right, .. } => {
406            let left_binds = left
407                .output_vars()
408                .always_bound
409                .iter()
410                .any(|bound| bound == variable);
411            let right_binds = right
412                .output_vars()
413                .always_bound
414                .iter()
415                .any(|bound| bound == variable);
416            (left_binds && inject_at_producer(left, variable, op))
417                || (right_binds && inject_at_producer(right, variable, op))
418        }
419        waratah_compute::PlanNode::Filter { inner, .. }
420        | waratah_compute::PlanNode::Extend { inner, .. }
421        | waratah_compute::PlanNode::Distinct { inner, .. }
422        | waratah_compute::PlanNode::Sort { inner, .. } => inject_at_producer(inner, variable, op),
423        _ => false,
424    }
425}
426
427/// One matched geo conjunct, ready to become a `geo_scan` CustomOp.
428struct GeoScanShape {
429    variable: Variable,
430    payload: crate::exec::GeoScanPayload,
431    /// The query geometry's covering: the payload intervals derive from it
432    /// AND the rewrite stamps the area-based row estimate from it — computed
433    /// exactly once here.
434    covering: CellUnion,
435}
436
437/// Match one residual conjunct against the v1 geo FILTER shapes.
438fn match_geo_conjunct(conjunct: &Expression) -> Result<Option<GeoScanShape>, ComputeError> {
439    let Expression::FunctionCall(spargebra::algebra::Function::Custom(iri), args) = conjunct else {
440        return Ok(None);
441    };
442    let Some(predicate) = GeoPredicate::from_iri(iri.as_str()) else {
443        return Ok(None);
444    };
445    if args.len() != 2 {
446        return Ok(None);
447    }
448    // Exactly one ground literal + one variable.
449    let (const_arg, var_arg) = match (&args[0], &args[1]) {
450        (Expression::Literal(literal), Expression::Variable(variable)) => (Some(literal), variable),
451        (Expression::Variable(variable), Expression::Literal(literal)) => (Some(literal), variable),
452        _ => return Ok(None),
453    };
454    let const_first = matches!(&args[0], Expression::Literal(_));
455    let Some(literal) = const_arg else {
456        return Ok(None);
457    };
458    // Plan-time const: parse once via the same encode path as ingest. A
459    // non-native const (Other CRS / invalid / unparseable) leaves the
460    // conjunct to the unindexed custom fn.
461    let prepared = match crate::encode::prepare_geometry_literal(literal) {
462        Ok(prepared) if prepared.is_native() => prepared,
463        _ => return Ok(None),
464    };
465    let Some(envelope) = prepared.envelope else {
466        return Ok(None);
467    };
468    // Covering + merged intervals (descendant ranges ∪ exact ancestors).
469    let covering = crate::covering::geometry_covering(&prepared.geometry);
470    let intervals = crate::covering::intervals_for_covering(&covering);
471    // Effective Relate orientation: the scan evaluates
472    // `candidate P const` with the candidate as DE-9IM subject A, so a
473    // const-first SPARQL shape inverts the predicate (see plan §5 table).
474    let effective = match (predicate, const_first) {
475        (GeoPredicate::Intersects, _) => GeoPredicate::Intersects,
476        (GeoPredicate::Contains, true) | (GeoPredicate::Within, false) => GeoPredicate::Within,
477        (GeoPredicate::Contains, false) | (GeoPredicate::Within, true) => GeoPredicate::Contains,
478    };
479    Ok(Some(GeoScanShape {
480        variable: var_arg.clone(),
481        covering,
482        payload: crate::exec::GeoScanPayload {
483            predicate: effective,
484            const_term: prepared.term,
485            query_geometry: prepared.geometry,
486            query_envelope: envelope,
487            intervals,
488        },
489    }))
490}
491
492/// `EncodedTerm` re-export for the payload (the const term rides the scan).
493const _: Option<EncodedTerm> = None;
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498    use waratah_compute::CustomOp;
499    use waratah_compute::JoinMeta;
500    use waratah_compute::LogicalPlan;
501    use waratah_compute::PlanNode;
502    use waratah_proto::PatternSlot;
503    use waratah_stats::{LiveQuadsProfile, StatsProfile, observe_quad};
504    use waratah_storage::{Literal, NamedNode, StorageOp, encode_quad};
505
506    #[test]
507    fn candidate_producers_are_pinned_through_the_optimizer() {
508        let plugin = GeoPlannerPlugin;
509        let call = |iri: &str| {
510            Expression::FunctionCall(
511                spargebra::algebra::Function::Custom(oxrdf::NamedNode::new_unchecked(iri)),
512                vec![Expression::Variable(
513                    waratah_storage::Variable::new_unchecked("w"),
514                )],
515            )
516        };
517        for predicate in [
518            GeoPredicate::Contains,
519            GeoPredicate::Within,
520            GeoPredicate::Intersects,
521        ] {
522            assert!(
523                plugin.pins_through_optimizer(&call(predicate.iri())),
524                "{} builds a geo candidate producer",
525                predicate.iri()
526            );
527        }
528        assert!(!plugin.pins_through_optimizer(&call(
529            "http://www.opengis.net/def/function/geosparql/sfTouches"
530        )));
531        assert!(!plugin.pins_through_optimizer(&Expression::Variable(
532            waratah_storage::Variable::new_unchecked("w")
533        )));
534
535        // The ground-substitution guard keys on the same conjunct set: the geo
536        // rewrite joins the covered geometry back to the filtered variable.
537        for predicate in [
538            GeoPredicate::Contains,
539            GeoPredicate::Within,
540            GeoPredicate::Intersects,
541        ] {
542            assert!(plugin.keeps_variable_when_ground(&call(predicate.iri())));
543        }
544        assert!(!plugin.keeps_variable_when_ground(&call(
545            "http://www.opengis.net/def/function/geosparql/sfTouches"
546        )));
547        assert!(!plugin.keeps_variable_when_ground(&Expression::Variable(
548            waratah_storage::Variable::new_unchecked("w")
549        )));
550    }
551
552    #[test]
553    fn geo_predicates_parse_from_the_geof_iris() {
554        for predicate in [
555            GeoPredicate::Contains,
556            GeoPredicate::Within,
557            GeoPredicate::Intersects,
558        ] {
559            assert_eq!(GeoPredicate::from_iri(predicate.iri()), Some(predicate));
560        }
561        assert_eq!(
562            GeoPredicate::from_iri("http://www.opengis.net/def/function/geosparql/sfTouches"),
563            None
564        );
565    }
566
567    const SEQ_POLY_WKT: &str =
568        "POLYGON((152.5 -28.0, 153.5 -28.0, 153.5 -27.0, 152.5 -27.0, 152.5 -28.0))";
569    /// ~180°×90° box: roughly 19M estimate rows at the placeholder density —
570    /// larger than any no-profile inner scan estimate (3M).
571    const HUGE_POLY_WKT: &str =
572        "POLYGON((-90.0 -45.0, 90.0 -45.0, 90.0 45.0, -90.0 45.0, -90.0 -45.0))";
573
574    /// The plan hook only fires with the plugin + `geof:*` functions
575    /// installed (process-wide, first install wins).
576    fn installed() {
577        crate::install();
578    }
579
580    fn polygon(wkt_text: &str) -> geo::Geometry<f64> {
581        match crate::encode::prepare_geometry_literal(&oxrdf::Literal::new_typed_literal(
582            wkt_text,
583            oxrdf::NamedNode::new_unchecked(crate::GEO_WKT_LITERAL),
584        )) {
585            Ok(prepared) => prepared.geometry,
586            Err(error) => panic!("test polygon must prepare: {error}"),
587        }
588    }
589
590    /// The injected `Join(…, geo_scan, [?g])` node of a parsed query plan.
591    fn find_geo_join(node: &PlanNode) -> Option<(&PlanNode, &PlanNode, &JoinMeta)> {
592        match node {
593            PlanNode::Join {
594                left, right, meta, ..
595            } => {
596                let geo = |n: &PlanNode| matches!(n, PlanNode::CustomNode(op) if op.op_id == GEO_SCAN_OP_ID);
597                if geo(left) || geo(right) {
598                    return Some((left, right, meta));
599                }
600                find_geo_join(left).or_else(|| find_geo_join(right))
601            }
602            PlanNode::Union { left, right } | PlanNode::LeftJoin { left, right, .. } => {
603                find_geo_join(left).or_else(|| find_geo_join(right))
604            }
605            PlanNode::Filter { inner, exists, .. } => find_geo_join(inner)
606                .or_else(|| exists.iter().find_map(|clause| find_geo_join(&clause.body))),
607            PlanNode::CustomNode(op) => op.children.iter().find_map(find_geo_join),
608            PlanNode::Extend { inner, .. }
609            | PlanNode::Slice { inner, .. }
610            | PlanNode::Distinct { inner, .. }
611            | PlanNode::Sort { inner, .. }
612            | PlanNode::Group { inner, .. }
613            | PlanNode::JoinGraphVar { inner, .. } => find_geo_join(inner),
614            PlanNode::SubSelect(sub) => find_geo_join(&sub.inner),
615            _ => None,
616        }
617    }
618
619    fn geo_op(node: &PlanNode) -> &CustomOp {
620        let PlanNode::CustomNode(op) = node else {
621            panic!("expected the geo_scan CustomNode, got {node:?}");
622        };
623        assert_eq!(op.op_id, GEO_SCAN_OP_ID);
624        op
625    }
626
627    /// The first broadcast-stamped scan in the tree.
628    fn find_scan_with_broadcast(node: &PlanNode) -> Option<&waratah_compute::ScanOp> {
629        match node {
630            PlanNode::Scan(scan) => scan.broadcasted.as_ref().map(|_| scan),
631            PlanNode::Join { left, right, .. }
632            | PlanNode::LeftJoin { left, right, .. }
633            | PlanNode::Union { left, right } => {
634                find_scan_with_broadcast(left).or_else(|| find_scan_with_broadcast(right))
635            }
636            PlanNode::Filter { inner, .. }
637            | PlanNode::Extend { inner, .. }
638            | PlanNode::Slice { inner, .. }
639            | PlanNode::Distinct { inner, .. }
640            | PlanNode::Sort { inner, .. }
641            | PlanNode::Group { inner, .. }
642            | PlanNode::JoinGraphVar { inner, .. } => find_scan_with_broadcast(inner),
643            PlanNode::CustomNode(op) => op.children.iter().find_map(find_scan_with_broadcast),
644            _ => None,
645        }
646    }
647
648    #[test]
649    fn geo_rewrite_stamps_the_regime_cost() {
650        // The rewrite stamps the op's explicit cost model: the drain shares
651        // the row estimate (the histogram ladder when the profile carries
652        // one; this test has no profile, so the covering-area fallback) and
653        // the units are the conservative relate constants. The executor's
654        // regime choice consumes the stamp (`take_direct_road`'s break-even
655        // over the actual key shapes); EXPLAIN renders it; arm placement
656        // does not price it yet (the seating-cost-model integration is pending).
657        installed();
658        let plan = LogicalPlan::parse(&format!(
659            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
660            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
661            SELECT ?city WHERE {{
662                ?city <http://ex/hasLocation> ?loc .
663                FILTER(geof:sfContains(\"{SEQ_POLY_WKT}\"^^geo:wktLiteral, ?loc))
664            }}"
665        ))
666        .unwrap();
667        let op = match find_geo_join(&plan.root).expect("geo join in plan") {
668            (PlanNode::CustomNode(op), _, _) | (_, PlanNode::CustomNode(op), _) => op,
669            other => panic!("no geo op: {other:?}"),
670        };
671        let cost = op.cost.expect("geo rewrite stamps the cost model");
672        assert_eq!(cost.per_key_unit, GEO_RELATE_UNIT_ROWS);
673        assert_eq!(cost.inline_point_unit, GEO_INLINE_POINT_UNIT_ROWS);
674        let covering_rows = crate::covering::covering_estimate_rows(
675            &crate::covering::geometry_covering(&polygon(SEQ_POLY_WKT)),
676        );
677        assert_eq!(cost.drain_rows, covering_rows);
678        // The formulas are live on the stamped op. Keyed at covering-estimate
679        // keys: direct (n×unit) beats the semi-join road (drain + the same
680        // survivors, since the op's sweep output IS n here). Sweep: drain +
681        // every candidate.
682        assert_eq!(
683            op.keyed_cost(covering_rows, Some(0)),
684            Some(covering_rows * GEO_RELATE_UNIT_ROWS)
685        );
686        assert_eq!(
687            op.sweep_cost(),
688            Some(covering_rows + op.produced_row_count_estimate * GEO_RELATE_UNIT_ROWS)
689        );
690    }
691
692    /// The filter sink places a pinned conjunct at the lowest *binding site*;
693    /// a `Bgp` is one site, so the conjunct can sit above the whole join
694    /// tree. The rewrite must inject the geo join at the filtered variable's
695    /// producer inside that tree rather than wrap the tree: wrapping it makes
696    /// the point scan the driver and re-executes the occurrence side per
697    /// page.
698    #[test]
699    fn geo_join_injects_at_the_filtered_variables_producer() {
700        installed();
701        let plan = LogicalPlan::parse(&format!(
702            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
703            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
704            SELECT ?occ WHERE {{
705                ?occ <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ex/Occurrence> ;
706                     geo:hasGeometry ?g .
707                ?g geo:asWKT ?wkt .
708                FILTER(geof:sfWithin(?wkt, \"{SEQ_POLY_WKT}\"^^geo:wktLiteral))
709            }}"
710        ))
711        .unwrap();
712        let (left, right, _) = find_geo_join(&plan.root).expect("geo join in plan");
713        let (geo_arm, site) = if matches!(
714            left,
715            PlanNode::CustomNode(op) if op.op_id == GEO_SCAN_OP_ID
716        ) {
717            (left, right)
718        } else {
719            (right, left)
720        };
721        assert!(matches!(
722            geo_arm,
723            PlanNode::CustomNode(op) if op.op_id == GEO_SCAN_OP_ID
724        ));
725        let PlanNode::Scan(scan) = site else {
726            panic!("the geo join must inject at the asWKT producer scan, got {site:?}");
727        };
728        assert_eq!(
729            scan.object,
730            Some(waratah_storage::Variable::new_unchecked("wkt")),
731            "the producer scan binds the filtered variable in its object slot"
732        );
733    }
734
735    /// A single conjunct above a UNION must stay one join above the union:
736    /// the arms are alternatives, so pushing into one arm is not a valid
737    /// rewrite, and pushing into every arm would build one candidate drain
738    /// per arm. The per-arm form is only for a conjunct written inside an
739    /// arm.
740    #[test]
741    fn geo_join_above_a_union_stays_single() {
742        installed();
743        fn count_geo_ops(node: &PlanNode) -> usize {
744            match node {
745                PlanNode::CustomNode(op) => {
746                    usize::from(op.op_id == GEO_SCAN_OP_ID)
747                        + op.children.iter().map(count_geo_ops).sum::<usize>()
748                }
749                PlanNode::Join { left, right, .. }
750                | PlanNode::LeftJoin { left, right, .. }
751                | PlanNode::Union { left, right } => count_geo_ops(left) + count_geo_ops(right),
752                PlanNode::Filter { inner, exists, .. } => {
753                    count_geo_ops(inner)
754                        + exists
755                            .iter()
756                            .map(|clause| count_geo_ops(&clause.body))
757                            .sum::<usize>()
758                }
759                PlanNode::Extend { inner, .. }
760                | PlanNode::Slice { inner, .. }
761                | PlanNode::Distinct { inner, .. }
762                | PlanNode::Sort { inner, .. }
763                | PlanNode::Group { inner, .. }
764                | PlanNode::JoinGraphVar { inner, .. } => count_geo_ops(inner),
765                PlanNode::SubSelect(sub) => count_geo_ops(&sub.inner),
766                _ => 0,
767            }
768        }
769        let plan = LogicalPlan::parse(&format!(
770            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
771            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
772            SELECT ?occ WHERE {{
773                {{ ?occ geo:hasGeometry ?g . ?g geo:asWKT ?wkt . }}
774                UNION
775                {{ ?occ geo:hasGeometry ?g2 . ?g2 geo:asWKT ?wkt . }}
776                FILTER(geof:sfWithin(?wkt, \"{SEQ_POLY_WKT}\"^^geo:wktLiteral))
777            }}"
778        ))
779        .unwrap();
780        assert_eq!(
781            count_geo_ops(&plan.root),
782            1,
783            "one conjunct above a union builds one candidate op, not one per arm"
784        );
785        let (left, right, _) = find_geo_join(&plan.root).expect("geo join in plan");
786        assert!(
787            matches!(left, PlanNode::Union { .. }) || matches!(right, PlanNode::Union { .. }),
788            "the single geo join must wrap the union, got {left:?} / {right:?}"
789        );
790    }
791
792    #[test]
793    fn refined_type_restriction_flips_the_geo_op_to_the_probe_side() {
794        // The transects failure shape, at the plan level: a type-restricted
795        // BGP collapses under the profile (3 transects), so the rewrite's
796        // PRE-refinement verdict (op ~1.2k ≤ raw BGP ~3M → op drives) is
797        // wrong by refinement time. `replan_custom_node_arms` re-derives it
798        // on the settled estimates: the op ends on the PROBE side, where it
799        // receives the driver's pushed ?loc keys instead of sweeping the
800        // window.
801        installed();
802        let mut live = LiveQuadsProfile::default();
803        let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
804        let transect = NamedNode::new("http://ex/Transect").unwrap();
805        let has_loc = NamedNode::new("http://ex/hasLocation").unwrap();
806        for i in 0..3 {
807            let s = NamedNode::new(format!("http://ex/t{i}")).unwrap();
808            observe_quad(
809                &mut live,
810                &encode_quad(&waratah_storage::Quad::new(
811                    s.clone(),
812                    type_pred.clone(),
813                    transect.clone(),
814                    waratah_storage::GraphName::DefaultGraph,
815                ))
816                .unwrap(),
817                StorageOp::Put,
818            );
819            observe_quad(
820                &mut live,
821                &encode_quad(&waratah_storage::Quad::new(
822                    s,
823                    has_loc.clone(),
824                    Literal::new_typed_literal(
825                        "POINT(152.7 -27.5)",
826                        NamedNode::new_unchecked(crate::GEO_WKT_LITERAL),
827                    ),
828                    waratah_storage::GraphName::DefaultGraph,
829                ))
830                .unwrap(),
831                StorageOp::Put,
832            );
833        }
834        let profile = StatsProfile::from(live);
835        let plan = LogicalPlan::parse_with_profile(
836            &format!(
837                "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
838                PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
839                SELECT ?poi WHERE {{
840                    ?poi a <http://ex/Transect> .
841                    ?poi <http://ex/hasLocation> ?loc .
842                    FILTER(geof:sfContains(\"{SEQ_POLY_WKT}\"^^geo:wktLiteral, ?loc))
843                }}"
844            ),
845            Some(&profile),
846        )
847        .unwrap();
848        let (left, right, meta) = find_geo_join(&plan.root).expect("geo join in plan");
849        // The op probes on the RIGHT; the type-restricted spine drives.
850        assert!(
851            !matches!(left, PlanNode::CustomNode(_)),
852            "inner must drive, got {left:?}"
853        );
854        let op = geo_op(right);
855        assert!(op.pinned.is_empty(), "a scan driver is not ground-unique");
856        // 3 driver rows ≤ PUSHDOWN_TERMS_LIMIT: the driver broadcasts its
857        // keys into the op.
858        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
859        // The executor's break-even on this shape (blob-backed linestring
860        // keys would relate directly; points even cheaper) is what makes the
861        // flip profitable — the planner only had to stop sweeping.
862        assert!(op.cost.is_some());
863    }
864
865    #[test]
866    fn small_geo_estimate_keeps_the_scan_as_broadcast_build_side() {
867        // No profile: the inner BGP scan estimates 3M, the 1° polygon's
868        // covering-area estimate is ~1k — the smaller geo arm stays LEFT and
869        // broadcasts as the build side (the historical shape).
870        installed();
871        let plan = LogicalPlan::parse(&format!(
872            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
873            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
874            SELECT ?city WHERE {{
875                ?city <http://ex/hasLocation> ?loc .
876                FILTER(geof:sfContains(\"{SEQ_POLY_WKT}\"^^geo:wktLiteral, ?loc))
877            }}"
878        ))
879        .unwrap();
880        let (left, right, meta) = find_geo_join(&plan.root).expect("geo join in plan");
881        let op = geo_op(left);
882        assert!(
883            !matches!(right, PlanNode::CustomNode(_)),
884            "inner plan must be the probe arm"
885        );
886        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
887        // The estimate is the covering area × placeholder density — the same
888        // number the covering helper computes for this polygon.
889        let expected = crate::covering::covering_estimate_rows(
890            &crate::covering::geometry_covering(&polygon(SEQ_POLY_WKT)),
891        );
892        assert_eq!(op.produced_row_count_estimate, expected);
893        assert!(op.pinned.is_empty(), "driver side never pins");
894    }
895
896    #[test]
897    fn large_geo_estimate_moves_the_scan_to_the_probe_side() {
898        // The huge polygon's area estimate (~19M) exceeds the inner scan's
899        // no-profile estimate (3M): the inner plan drives on the LEFT and
900        // the geo scan probes on the RIGHT — it receives the driver's pushed
901        // keys at execution.
902        installed();
903        let plan = LogicalPlan::parse(&format!(
904            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
905            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
906            SELECT ?city WHERE {{
907                ?city <http://ex/hasLocation> ?loc .
908                FILTER(geof:sfContains(\"{HUGE_POLY_WKT}\"^^geo:wktLiteral, ?loc))
909            }}"
910        ))
911        .unwrap();
912        let (left, right, _meta) = find_geo_join(&plan.root).expect("geo join in plan");
913        assert!(
914            !matches!(left, PlanNode::CustomNode(_)),
915            "inner plan must drive"
916        );
917        let op = geo_op(right);
918        assert!(
919            op.produced_row_count_estimate > 1_000_000,
920            "the huge polygon must estimate in the millions: {}",
921            op.produced_row_count_estimate
922        );
923        assert!(op.pinned.is_empty(), "a scan driver is not ground-unique");
924    }
925
926    #[test]
927    fn estimate_reflects_covering_area() {
928        // Install before parsing: this is the alphabetically first test in
929        // the binary that touches the planner, and `process_plugins()`'
930        // lazy init latches an EMPTY registry when read before any install
931        // (first install wins) — without this, serial test order poisons
932        // every later plugin-dependent test.
933        installed();
934        // Bigger polygon → bigger stamped estimate, straight from the
935        // covering areas.
936        let small = LogicalPlan::parse(&format!(
937            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
938            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
939            SELECT ?city WHERE {{
940                ?city <http://ex/hasLocation> ?loc .
941                FILTER(geof:sfContains(\"{SEQ_POLY_WKT}\"^^geo:wktLiteral, ?loc))
942            }}"
943        ))
944        .unwrap();
945        let big = LogicalPlan::parse(&format!(
946            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
947            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
948            SELECT ?city WHERE {{
949                ?city <http://ex/hasLocation> ?loc .
950                FILTER(geof:sfContains(\"{HUGE_POLY_WKT}\"^^geo:wktLiteral, ?loc))
951            }}"
952        ))
953        .unwrap();
954        let small_rows = match find_geo_join(&small.root).unwrap() {
955            (PlanNode::CustomNode(op), _, _) => op.produced_row_count_estimate,
956            (_, PlanNode::CustomNode(op), _) => op.produced_row_count_estimate,
957            other => panic!("no geo op: {other:?}"),
958        };
959        let big_rows = match find_geo_join(&big.root).unwrap() {
960            (PlanNode::CustomNode(op), _, _) => op.produced_row_count_estimate,
961            (_, PlanNode::CustomNode(op), _) => op.produced_row_count_estimate,
962            other => panic!("no geo op: {other:?}"),
963        };
964        assert!(big_rows > small_rows, "{big_rows} must exceed {small_rows}");
965    }
966
967    #[test]
968    fn ground_unique_driver_pins_its_term_into_the_probe_scan() {
969        // The BIND binds ?poi to ONE ground geo term and the inner scan is
970        // grounded into a point lookup (estimate 1), so the huge polygon's
971        // geo scan probes on the RIGHT with the driver's term PINNED into
972        // the op — the generic emulation of the Scan's grounded pattern
973        // slot (executor relates exactly it, no key delivery needed).
974        installed();
975        let plan = LogicalPlan::parse(&format!(
976            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
977            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
978            SELECT ?poi WHERE {{
979                VALUES ?anchor {{ 1 }}
980                BIND(\"POINT(153.0 -27.5)\"^^geo:wktLiteral AS ?poi)
981                <http://ex/landmark> <http://ex/hasLocation> ?poi .
982                FILTER(geof:sfContains(\"{HUGE_POLY_WKT}\"^^geo:wktLiteral, ?poi))
983            }}"
984        ))
985        .unwrap();
986        let (_, right, _) = find_geo_join(&plan.root).expect("geo join in plan");
987        let op = geo_op(right);
988        assert_eq!(
989            op.produced_row_count_estimate, 1,
990            "a pinned op estimates one row"
991        );
992        assert_eq!(op.pinned.len(), 1);
993        let (variable, term) = &op.pinned[0];
994        assert_eq!(variable.as_str(), "poi");
995        assert!(
996            matches!(term, EncodedTerm::LiteralPoint { .. }),
997            "the pinned term is the driver's native point: {term:?}"
998        );
999    }
1000
1001    #[test]
1002    fn geo_driver_broadcast_stamps_the_probe_side_scan() {
1003        // Small polygon: the geo op drives LEFT under a Broadcast stamp and
1004        // the inner is a bare scan (`?city hasLocation ?loc`), so the
1005        // planning loop's `restamp_broadcast_marks` claims the probe scan:
1006        // broadcast `(?loc, Object)` and the estimate clamped to the geo
1007        // op's key domain (its output estimate).
1008        installed();
1009        let plan = LogicalPlan::parse(&format!(
1010            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
1011            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
1012            SELECT ?city WHERE {{
1013                ?city <http://ex/hasLocation> ?loc .
1014                FILTER(geof:sfContains(\"{SEQ_POLY_WKT}\"^^geo:wktLiteral, ?loc))
1015            }}"
1016        ))
1017        .unwrap();
1018        let (left, right, meta) = find_geo_join(&plan.root).expect("geo join in plan");
1019        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
1020        let op = geo_op(left);
1021        let scan = right.as_broadcast_scan().expect("inner is a bare scan");
1022        let (variable, slot) = scan
1023            .broadcasted
1024            .as_ref()
1025            .expect("probe scan stamped for the Broadcast probe");
1026        assert_eq!(variable.as_str(), "loc");
1027        assert!(matches!(slot, PatternSlot::Object));
1028        assert_eq!(
1029            scan.produced_row_count_estimate, op.produced_row_count_estimate,
1030            "estimate clamped to the driving geo op's domain"
1031        );
1032    }
1033
1034    #[test]
1035    fn join_tree_inner_claimed_by_boundary_restamp() {
1036        // The inner is the whole pattern below the FILTER — NOT always a
1037        // scan. Chained geo conjuncts are the common case: the second
1038        // rewrite's inner is the FIRST geo join (a join tree), so the
1039        // rewrite itself stamps nothing. The planning loop's
1040        // `restamp_broadcast_marks` (sole writer of `ScanOp::broadcasted`)
1041        // closes the old gap afterwards: its claim descends into the join
1042        // tree and marks the inner's scans hosting the geo key. Here the
1043        // big polygon's iteration runs first and puts the geo op on the
1044        // RIGHT (probe — it receives pushed keys, no mark by design); the
1045        // driving iteration's inner is then the join tree, and the boundary
1046        // restamp claims the `?loc`-hosting city scan under it.
1047        installed();
1048        const HUGE_POLY_WKT: &str =
1049            "POLYGON((-90.0 -45.0, 90.0 -45.0, 90.0 45.0, -90.0 45.0, -90.0 -45.0))";
1050        let plan = LogicalPlan::parse(&format!(
1051            "PREFIX geo: <http://www.opengis.net/ont/geosparql#>
1052            PREFIX geof: <http://www.opengis.net/def/function/geosparql/>
1053            SELECT ?city WHERE {{
1054                ?city <http://ex/hasLocation> ?loc .
1055                FILTER(geof:sfContains(\"{SEQ_POLY_WKT}\"^^geo:wktLiteral, ?loc))
1056                FILTER(geof:sfContains(\"{HUGE_POLY_WKT}\"^^geo:wktLiteral, ?loc))
1057            }}"
1058        ))
1059        .unwrap();
1060        let (left, right, meta) = find_geo_join(&plan.root).expect("geo join in plan");
1061        assert_eq!(meta.strategy, JoinStrategy::Broadcast);
1062        // The chained conjuncts both inject at the `?loc` producer scan, so
1063        // the outer geo join's other arm is a join tree, not the bare scan.
1064        // Whichever arm carries the outer geo op, the claim must reach the
1065        // scan under the other one.
1066        let geo_on_left = matches!(
1067            left,
1068            PlanNode::CustomNode(op) if op.op_id == GEO_SCAN_OP_ID
1069        );
1070        let (geo_arm, inner) = if geo_on_left {
1071            (left, right)
1072        } else {
1073            (right, left)
1074        };
1075        geo_op(geo_arm);
1076        let PlanNode::Join { .. } = inner else {
1077            panic!("the outer geo join's inner is a join tree, got {inner:?}");
1078        };
1079        assert!(
1080            inner.as_broadcast_scan().is_none(),
1081            "join-tree inner is not scan-shaped, so the join itself carries no mark"
1082        );
1083        // The claim under the outer geo join reached through the join tree
1084        // and marked the `?loc`-hosting scan (the geo CustomOp itself is an
1085        // opaque leaf for claims — it receives pushed keys, not marks).
1086        let claimed = find_scan_with_broadcast(&plan.root)
1087            .expect("boundary restamp claims the join-tree inner's ?loc scan");
1088        assert!(
1089            claimed
1090                .broadcasted
1091                .as_ref()
1092                .is_some_and(|(v, _)| v.as_str() == "loc"),
1093            "the claim names the geo key: {:?}",
1094            claimed.broadcasted
1095        );
1096    }
1097}