Skip to main content

waratah_geo/
exec.rs

1//! ExecutorPlugin: materialize `geo_scan` (S2 candidates → exact Relate) and
2//! the unindexed `geof:*` custom functions.
3//!
4//! The scan is a **broadcast-participating** materializing leaf with FOUR
5//! runtime behaviors, picked per execution by what the op carries (see
6//! `take_direct_road` and the planner's placement contract):
7//!
8//! 1. **Pinned candidate** (`CustomOp.pinned`): relate exactly that one
9//!    geometry — no candidate scan.
10//! 2. **Direct relate**: relate the (deduped) driver keys directly — no
11//!    candidate scan RPC at all. The road is CHOSEN by the stamped
12//!    `CustomOpCost` break-even over the actual key mix: `LiteralPoint`
13//!    keys relate from their stored coordinates with no blob fetch, so a
14//!    point-heavy key list takes this road far past any count limit.
15//!    Without a stamp, a list at or below `GEO_DIRECT_RELATE_LIMIT` takes
16//!    it (legacy fallback).
17//! 3. **Semi-join**: one candidate drain, then filter the candidates
18//!    against the key set before relating (relate survivors only, all
19//!    compute-side) — the road the break-even picks when the drain is
20//!    cheaper than relating keys that mostly discard.
21//! 4. **No pushed keys** (driver side): one candidate drain, relate all —
22//!    the original sweep.
23//!
24//! Every drain path drains exactly once (`GeoCandidateScan` is never
25//! cursor-paged — a second RPC would restart the partition's DISTINCT
26//! seen-set), then fetches blob payloads BEFORE the relate loop, then
27//! prepares the constant once. The drain itself is memoized per WINDOW on
28//! the engine side (`PluginEnv::geo_candidates` → `QueryCaches::geo_drains`):
29//! the candidate list is key-invariant, so behavior 3's "one drain" holds
30//! across the driver's WHOLE page sequence — page 1 drains, pages 2..N hit
31//! the memo — and keyed results, which the whole-result CustomOp memo
32//! refuses (keys-dependent result, see the `ExecutorPlugin` contract), still
33//! reuse the window. The surrounding hash join
34//! on the key variable already handles row multiplicity from the sibling
35//! side, so every branch emits one row per distinct matching term.
36
37use std::collections::HashSet;
38use std::future::Future;
39use std::pin::Pin;
40use std::sync::Arc;
41
42use geo::Geometry;
43use geo::algorithm::Relate;
44use waratah_compute::ComputeError;
45use waratah_compute::CustomOp;
46use waratah_compute::CustomOpCost;
47use waratah_compute::PreparedLiteralCache;
48use waratah_compute::plugin::{ExecutorPlugin, PluginEnv, PluginPayload};
49use waratah_compute::{CustomEval, CustomFunction};
50use waratah_storage::{EncodedTerm, GeoCellInterval, GeoEnvelope, StrHash};
51
52use crate::relate::{GeoPredicate, PreparedQuery};
53use crate::validation::{prepare_spatial_geometry, reduce_tolerated_spikes};
54
55/// LEGACY fallback only: for an op WITHOUT a stamped `CustomOpCost`,
56/// pushed-key lists at or below this length relate directly (behavior 2)
57/// and larger ones take the drain + semi-join (behavior 3). Stamped ops
58/// decide by the cost-model break-even over the actual key mix instead
59/// (`take_direct_road`) — a fixed count cannot see the two inputs that
60/// matter: the drain's window cost, and whether the keys are fetch-free
61/// inline points.
62const GEO_DIRECT_RELATE_LIMIT: usize = 500;
63
64/// Typed payload of the `geo_scan` CustomOp (downcast by the executor).
65#[derive(Debug, Clone, PartialEq)]
66pub struct GeoScanPayload {
67    /// Effective predicate orientation (candidate as DE-9IM subject):
68    /// see the inversion table in the planner.
69    pub predicate: GeoPredicate,
70    /// The constant geometry's native term (diagnostic / EXPLAIN).
71    pub const_term: EncodedTerm,
72    /// The constant CRS84 geometry (prepared once at execution).
73    pub query_geometry: Geometry<f64>,
74    /// CRS84 envelope of the constant (partition-side AABB reject).
75    pub query_envelope: GeoEnvelope,
76    /// Merged cell-id intervals (descendant ranges ∪ exact ancestors).
77    pub intervals: Vec<GeoCellInterval>,
78}
79
80impl PluginPayload for GeoScanPayload {
81    fn plugin_id(&self) -> &'static str {
82        crate::PLUGIN_ID
83    }
84
85    fn dyn_eq(&self, other: &dyn PluginPayload) -> bool {
86        other
87            .as_any()
88            .downcast_ref::<GeoScanPayload>()
89            .is_some_and(|other| *other == *self)
90    }
91
92    /// Deterministic payload-content bytes for the query-local CustomOp memo
93    /// key: the predicate IRI, the const term's canonical storage bytes
94    /// ([`waratah_storage::encode_term_bytes`]), the geometry kind + CRS84
95    /// coordinates, the envelope, and the covering intervals — every field
96    /// the scan depends on, little-endian binary.
97    fn memo_content(&self) -> Vec<u8> {
98        use geo::algorithm::CoordsIter;
99        let mut out = Vec::new();
100        out.extend_from_slice(self.predicate.iri().as_bytes());
101        out.push(0xFF);
102        out.extend_from_slice(&waratah_storage::encode_term_bytes(&self.const_term));
103        out.push(0xFF);
104        let kind: u8 = match &self.query_geometry {
105            Geometry::Point(_) => 0,
106            Geometry::LineString(_) => 1,
107            Geometry::Polygon(_) => 2,
108            Geometry::MultiPoint(_) => 3,
109            Geometry::MultiLineString(_) => 4,
110            Geometry::MultiPolygon(_) => 5,
111            Geometry::GeometryCollection(_) => 6,
112            Geometry::Rect(_) => 7,
113            Geometry::Triangle(_) => 8,
114            Geometry::Line(_) => 9,
115        };
116        out.push(kind);
117        for coord in self.query_geometry.coords_iter() {
118            out.extend_from_slice(&coord.x.to_le_bytes());
119            out.extend_from_slice(&coord.y.to_le_bytes());
120        }
121        out.push(0xFF);
122        out.extend_from_slice(&self.query_envelope.encode());
123        out.push(0xFF);
124        for interval in &self.intervals {
125            out.extend_from_slice(&interval.min_cell_id.to_le_bytes());
126            out.extend_from_slice(&interval.max_cell_id.to_le_bytes());
127        }
128        out
129    }
130}
131
132/// GeoSPARQL executor hook.
133#[derive(Debug, Default)]
134pub struct GeoExecutorPlugin;
135
136impl ExecutorPlugin for GeoExecutorPlugin {
137    fn execute<'a>(
138        &'a self,
139        op: &'a CustomOp,
140        env: PluginEnv<'a>,
141    ) -> Pin<Box<dyn Future<Output = Result<Vec<Vec<EncodedTerm>>, ComputeError>> + Send + 'a>>
142    {
143        Box::pin(async move {
144            if op.op_id != crate::plan::GEO_SCAN_OP_ID {
145                return Err(ComputeError::UnsupportedSparql(format!(
146                    "unknown geo op {}",
147                    op.op_id
148                )));
149            }
150            if op.variables.len() != 1 {
151                return Err(ComputeError::UnsupportedSparql(
152                    "geo_scan emits exactly one variable".into(),
153                ));
154            }
155            let Some(payload) = op.payload.downcast_ref::<GeoScanPayload>() else {
156                return Err(ComputeError::UnsupportedSparql(
157                    "geo_scan payload is not a GeoScanPayload".into(),
158                ));
159            };
160            let output_variable = &op.variables[0];
161
162            // Runtime behavior selection, in priority order. Every branch
163            // ends in `relate_terms`, which batches the blob fetch before
164            // the relate loop so `PreparedGeometry` never lives across an
165            // await point.
166            //
167            // 1. Pinned candidate (plan-stamped broadcast ground driver):
168            //    relate exactly the driver's term — no candidate scan.
169            if let Some((_, term)) = op
170                .pinned
171                .iter()
172                .find(|(variable, _)| variable == output_variable)
173            {
174                return relate_terms(std::slice::from_ref(term), payload, &env, false).await;
175            }
176            let Some(keys) = env.pushed_vals else {
177                // 4. No pushed keys (driver side): the original sweep.
178                let candidates = drain_candidates(payload, &env).await?;
179                return relate_terms(&candidates, payload, &env, true).await;
180            };
181            // Pushed-key delivery: dedup once, then pick the road by the
182            // stamped cost model's break-even over the ACTUAL term mix
183            // (`take_direct_road`; legacy count fallback when unstamped).
184            let distinct: HashSet<&EncodedTerm> = keys.iter().collect();
185            let terms: Vec<EncodedTerm> = distinct.into_iter().cloned().collect();
186            if take_direct_road(&terms, op.cost.as_ref(), op.produced_row_count_estimate) {
187                // 2. Direct relate — no candidate scan RPC. Inline-point
188                //    keys price at the relate-only unit, so point-heavy
189                //    drivers take this road far past the legacy limit.
190                return relate_terms(&terms, payload, &env, false).await;
191            }
192            // 3. Semi-join: one candidate drain (behavior 4's sweep), then
193            //    filter the candidates against the key set BEFORE relating
194            //    — only survivors fetch payloads and relate. All
195            //    compute-side; one scan call.
196            let key_set: HashSet<&EncodedTerm> = terms.iter().collect();
197            let candidates = drain_candidates(payload, &env).await?;
198            let survivors: Vec<EncodedTerm> = candidates
199                .into_iter()
200                .filter(|term| key_set.contains(term))
201                .collect();
202            relate_terms(&survivors, payload, &env, true).await
203        })
204    }
205}
206
207/// The keyed-regime road: relate the deduped driver keys directly
208/// (behavior 2), or drain once and semi-join before relating (behavior 3)?
209///
210/// With a stamped [`CustomOpCost`] the choice is the cost-model break-even
211/// over the ACTUAL deduped key mix: a `LiteralPoint` relates from its
212/// stored coordinates with no blob fetch and no parse, so it prices at
213/// `inline_point_unit`; every other shape pays the blob-backed
214/// `per_key_unit`. The semi-join road prices the drain plus at most
215/// `min(keys, sweep output)` survivors — survivors are bounded by both the
216/// key set and the window, and their mix is unknown before the drain, so
217/// they price conservatively at `per_key_unit` (a key list mostly OUTSIDE
218/// the window therefore biases this road toward the direct relate; the
219/// true survivor count only the drain knows).
220///
221/// This break-even is the REFERENCE pricing of the keyed regime;
222/// `CustomOp::keyed_cost` is its conservative planner bound — every key
223/// at `per_key_unit` on ESTIMATED counts — so the two can differ on a
224/// point-heavy mix (the executor re-prices those keys here at
225/// `inline_point_unit`).
226///
227/// An op without a stamped cost (`None`) falls back to the legacy count
228/// limit: at or below [`GEO_DIRECT_RELATE_LIMIT`] keys relates directly.
229/// The count is over the DEDUPED key list — the pre-cost-model rule
230/// counted the raw pushed list, but a duplicate adds no relate work, so
231/// the deduped count is the honest basis for the same limit.
232fn take_direct_road(
233    deduped_keys: &[EncodedTerm],
234    cost: Option<&CustomOpCost>,
235    sweep_rows: u64,
236) -> bool {
237    let Some(cost) = cost else {
238        return deduped_keys.len() <= GEO_DIRECT_RELATE_LIMIT;
239    };
240    let keys = deduped_keys.len() as u64;
241    if keys == 0 {
242        return true;
243    }
244    let direct = deduped_keys
245        .iter()
246        .map(|term| match term {
247            EncodedTerm::LiteralPoint { .. } => cost.inline_point_unit,
248            _ => cost.per_key_unit,
249        })
250        .fold(0u64, u64::saturating_add);
251    let semi_join = cost
252        .drain_rows
253        .saturating_add(keys.min(sweep_rows).saturating_mul(cost.per_key_unit));
254    direct <= semi_join
255}
256
257/// One `GeoCandidateScan` drain — never cursor-paged (a second RPC would
258/// restart the partition's DISTINCT seen-set). No per-drain limit: SPARQL
259/// LIMIT applies above the join.
260async fn drain_candidates(
261    payload: &GeoScanPayload,
262    env: &PluginEnv<'_>,
263) -> Result<Vec<EncodedTerm>, ComputeError> {
264    (env.geo_candidates)(&payload.intervals, Some(payload.query_envelope), 0).await
265}
266
267/// Relate `terms` against the scan's prepared constant, emitting one row per
268/// distinct matching term. Points relate from their inline coordinates;
269/// geometries from their batch-fetched blob payload. A native geometry carrying
270/// `requires_spike_reduction` is reduced after decode; ordinary geometries stay
271/// on the direct decode-and-relate path. Geo-datatype typed literals
272/// (`geo:wktLiteral` / `geo:wkbLiteral` — legacy plugin-less rows or
273/// query-authored fallback values) use their lexical, parsed through the same
274/// encode path the ground FILTER evaluation uses.
275///
276/// `strict = true` rejects non-geo terms (index postings must only carry geo
277/// terms — a consistency violation); a geo-datatype typed literal IS a geo
278/// term and is processed there too, never an error. The pinned / pushed-key
279/// paths pass `false` because sibling join bindings may legitimately carry
280/// any term, and a non-geo term never relates (skip, not error).
281///
282/// All awaits happen BEFORE the relate loop: `PreparedGeometry` holds
283/// non-Send internals (Rc/rstar), so it must never live across an await
284/// point — created after the payload fetch, it stays out of the generator
285/// state and the future remains Send.
286async fn relate_terms(
287    terms: &[EncodedTerm],
288    payload: &GeoScanPayload,
289    env: &PluginEnv<'_>,
290    strict: bool,
291) -> Result<Vec<Vec<EncodedTerm>>, ComputeError> {
292    // The two geo datatype hashes: the typed-literal arm matches a
293    // candidate's `datatype_id` against these (the same IRIs the encode
294    // path and the unindexed FILTER dispatch on).
295    let wkt_id = StrHash::new(crate::GEO_WKT_LITERAL);
296    let wkb_id = StrHash::new(crate::GEO_WKB_LITERAL);
297    // Partition candidates; fetch every blob payload and big-literal
298    // lexical BEFORE the relate loop (the last awaits — see the Send note
299    // above).
300    let mut inline: Vec<EncodedTerm> = Vec::new();
301    let mut blob_terms: Vec<EncodedTerm> = Vec::new();
302    let mut typed: Vec<TypedCandidate> = Vec::new();
303    for term in terms {
304        match term {
305            EncodedTerm::LiteralPoint { .. } => inline.push(term.clone()),
306            EncodedTerm::LiteralGeometry { .. } => blob_terms.push(term.clone()),
307            EncodedTerm::SmallTypedLiteral { value, datatype_id } => {
308                match geo_datatype_iri(*datatype_id, wkt_id, wkb_id) {
309                    // Geo-datatype typed literal, lexical INLINE (small
310                    // value): parse + relate below, no registry resolve.
311                    Some(datatype_iri) => typed.push(TypedCandidate {
312                        term: term.clone(),
313                        datatype_iri,
314                        lexical: Some(value.as_str().to_owned()),
315                    }),
316                    None => reject_non_geo(strict, term)?,
317                }
318            }
319            EncodedTerm::BigTypedLiteral { datatype_id, .. } => {
320                match geo_datatype_iri(*datatype_id, wkt_id, wkb_id) {
321                    // Geo-datatype typed literal, big value: the lexical
322                    // resolves below, batched alongside the blob fetch.
323                    Some(datatype_iri) => typed.push(TypedCandidate {
324                        term: term.clone(),
325                        datatype_iri,
326                        lexical: None,
327                    }),
328                    None => reject_non_geo(strict, term)?,
329                }
330            }
331            other => reject_non_geo(strict, other)?,
332        }
333    }
334    let mut payloads: Vec<Option<Vec<u8>>> = Vec::new();
335    if !blob_terms.is_empty() {
336        let blob_ids: Vec<StrHash> = blob_terms
337            .iter()
338            .map(|term| match term {
339                EncodedTerm::LiteralGeometry { blob_id, .. } => *blob_id,
340                _ => unreachable!("only geometries collected"),
341            })
342            .collect();
343        payloads = (env.blobs)(&blob_ids).await?;
344    }
345    // Big typed-literal lexicals: ONE batched resolve for all of them —
346    // the executor env's string closure probes the query-local strings
347    // map first (query-authored constants are seeded at mint; the
348    // registry string store has never seen them), then the registry. A
349    // resolve miss after both is a consistency violation, not stale
350    // data: v1 never retracts registry strings on delete, so postings
351    // referencing an unanswerable value hash mean the string store lost
352    // an entry — fail the scan loudly instead of silently dropping the
353    // row (a RESOLVED-but-ill-formed lexical below is the ordinary SPARQL
354    // type error and still skips).
355    if typed.iter().any(|candidate| candidate.lexical.is_none()) {
356        let value_ids: Vec<StrHash> = typed
357            .iter()
358            .filter(|candidate| candidate.lexical.is_none())
359            .map(|candidate| match candidate.term {
360                EncodedTerm::BigTypedLiteral { value_id, .. } => value_id,
361                _ => unreachable!("only big typed literals carry no inline lexical"),
362            })
363            .collect();
364        let resolved = (env.strings)(&value_ids).await?;
365        let mut resolved = resolved.into_iter();
366        for candidate in &mut typed {
367            if candidate.lexical.is_none() {
368                candidate.lexical = resolved.next().flatten();
369            }
370        }
371        if let Some(candidate) = typed.iter().find(|candidate| candidate.lexical.is_none()) {
372            return Err(ComputeError::UnsupportedSparql(format!(
373                "indexed geometry lexical {:?} references a value hash
374                 missing from the registry string store and the query-local cache",
375                candidate.term
376            )));
377        }
378    }
379    // No awaits past this point: prepare the constant ONCE for the whole
380    // bulk and relate every candidate.
381    let query = PreparedQuery::new(payload.query_geometry.clone(), payload.predicate);
382    let mut out_rows: Vec<Vec<EncodedTerm>> = Vec::new();
383    for term in &inline {
384        if let Some(geometry) = candidate_geometry(term, None)?
385            && query.relates_candidate(&geometry)
386        {
387            out_rows.push(vec![term.clone()]);
388        }
389    }
390    for (term, payload) in blob_terms.into_iter().zip(payloads) {
391        let Some(payload) = payload else {
392            // The indexed term's blob vanished (no GC in v1, so this is a
393            // consistency violation, not a miss).
394            return Err(ComputeError::UnsupportedSparql(format!(
395                "indexed geometry blob {term:?} is missing from the blob store"
396            )));
397        };
398        if let Some(geometry) = candidate_geometry(&term, Some(&payload))?
399            && query.relates_candidate(&geometry)
400        {
401            out_rows.push(vec![term]);
402        }
403    }
404    for candidate in typed {
405        let Some(lexical) = candidate.lexical else {
406            // Registry miss on a big lexical: documented above — skip, the
407            // unindexed path drops the row identically.
408            continue;
409        };
410        let Some(geometry) = typed_candidate_geometry(&lexical, candidate.datatype_iri) else {
411            // Ill-formed / unsupported lexical: a SPARQL type error on the
412            // unindexed path (row dropped) — skip likewise, never error
413            // the whole scan.
414            continue;
415        };
416        if query.relates_candidate(&geometry) {
417            out_rows.push(vec![candidate.term]);
418        }
419    }
420    Ok(out_rows)
421}
422
423/// One typed-literal candidate (a geo-datatype `SmallTypedLiteral` /
424/// `BigTypedLiteral`): the term, which geo datatype IRI its hash matched,
425/// and its lexical when inline (small value). Big lexicals resolve through
426/// [`PluginEnv::strings`] in the fetch phase (`None` = pending until then;
427/// a post-resolve `None` is a consistency violation and errors the scan —
428/// see the resolve block in `relate_terms`).
429struct TypedCandidate {
430    /// The candidate term (emitted verbatim on a match).
431    term: EncodedTerm,
432    /// The matched geo datatype IRI (`geo:wktLiteral` / `geo:wkbLiteral`).
433    datatype_iri: &'static str,
434    /// Inline lexical (`SmallTypedLiteral`); `None` = big, pending resolve.
435    lexical: Option<String>,
436}
437
438/// Which geo datatype IRI a hashed `datatype_id` is, if either — the
439/// typed-literal arm's match key (hashes of the two geo datatype IRIs,
440/// computed once per `relate_terms` call).
441fn geo_datatype_iri(
442    datatype_id: StrHash,
443    wkt_id: StrHash,
444    wkb_id: StrHash,
445) -> Option<&'static str> {
446    if datatype_id == wkt_id {
447        Some(crate::GEO_WKT_LITERAL)
448    } else if datatype_id == wkb_id {
449        Some(crate::GEO_WKB_LITERAL)
450    } else {
451        None
452    }
453}
454
455/// Strict-path guard (see `relate_terms`): a term that is neither native
456/// geo nor a geo-datatype typed literal never relates. On the strict
457/// (index-sweep) path its presence is a consistency violation; the lenient
458/// pinned / pushed-key paths skip it silently.
459fn reject_non_geo(strict: bool, term: &EncodedTerm) -> Result<(), ComputeError> {
460    if strict {
461        return Err(ComputeError::UnsupportedSparql(format!(
462            "geo index posting carries a non-geo term: {term:?}"
463        )));
464    }
465    Ok(())
466}
467
468/// CRS84 geometry of one typed-literal candidate: parse + transform through
469/// the SAME encode functions the ground evaluation uses
470/// (`eval_geof_function`) — no parallel parser. `None` = ill-formed /
471/// unsupported lexical, which the unindexed FILTER type-errors (dropping
472/// the row); the exact path skips the candidate instead of erroring.
473fn typed_candidate_geometry(lexical: &str, datatype_iri: &str) -> Option<Geometry<f64>> {
474    let literal =
475        oxrdf::Literal::new_typed_literal(lexical, oxrdf::NamedNode::new_unchecked(datatype_iri));
476    let geometry = crate::encode::parse_geometry_literal(&literal)
477        .ok()
478        .and_then(|(source, crs)| crate::encode::transform_geometry_to_crs84(&source, crs).ok())?;
479    prepare_spatial_geometry(geometry).ok()
480}
481
482/// CRS84 geometry of one candidate: points from inline coords, geometries
483/// from the blob EWKB.
484fn candidate_geometry(
485    term: &EncodedTerm,
486    payload: Option<&[u8]>,
487) -> Result<Option<Geometry<f64>>, ComputeError> {
488    match term {
489        EncodedTerm::LiteralPoint { x, y, .. } => {
490            Ok(Some(Geometry::Point(geo::Point::new(*x, *y))))
491        }
492        EncodedTerm::LiteralGeometry {
493            requires_spike_reduction,
494            ..
495        } => {
496            let payload = payload.ok_or_else(|| {
497                ComputeError::UnsupportedSparql(
498                    "geometry candidate without a fetched blob payload".into(),
499                )
500            })?;
501            let geometry = crate::relate::candidate_from_ewkb(payload).map_err(|error| {
502                ComputeError::UnsupportedSparql(format!("candidate EWKB: {error}"))
503            })?;
504            if *requires_spike_reduction {
505                let reduced = reduce_tolerated_spikes(&geometry).map_err(|error| {
506                    ComputeError::UnsupportedSparql(format!(
507                        "candidate zero-area spike reduction: {error}"
508                    ))
509                })?;
510                if reduced.removed_vertices == 0 {
511                    return Err(ComputeError::UnsupportedSparql(
512                        "candidate carries the spike-reduction flag but its blob contains no reducible spike".into(),
513                    ));
514                }
515                Ok(Some(reduced.geometry))
516            } else {
517                Ok(Some(geometry))
518            }
519        }
520        _ => Ok(None),
521    }
522}
523
524/// Evaluate one unindexed `geof:*` call over RESOLVED terms (ground fallback).
525/// Native geo terms normally use the cache-aware encoded evaluator; this path
526/// still handles typed literals and any cache miss. Both arguments parse +
527/// transform to CRS84 here. Stored geometries arrive with their materialized
528/// lexical pre-seeded: the eval prefetch windows (residual FILTER, aggregates,
529/// Extend) fetch blob-backed
530/// payloads and decode through the plugin before the ground pass, and points
531/// materialize from their inline coords — so a type-error on a stored
532/// geometry is the missed-prefetch case (or an ill-formed literal), not an
533/// unreachable blob. The "correct, slow" v1 bar for shapes the rewrite did
534/// not take.
535pub fn eval_geof_function(iri: &str, args: &[oxrdf::Term]) -> CustomEval {
536    let Some(predicate) = GeoPredicate::from_iri(iri) else {
537        return CustomEval::Error;
538    };
539    if args.len() != 2 {
540        return CustomEval::Error;
541    }
542    let mut geometries: Vec<Geometry<f64>> = Vec::with_capacity(2);
543    for arg in args {
544        let oxrdf::Term::Literal(literal) = arg else {
545            return CustomEval::Error;
546        };
547        match crate::encode::parse_geometry_literal(literal)
548            .and_then(|(source, crs)| crate::encode::transform_geometry_to_crs84(&source, crs))
549            .map_err(|error| error.to_string())
550            .and_then(prepare_spatial_geometry)
551        {
552            Ok(geometry) => geometries.push(geometry),
553            // Ill-formed / Other-CRS geometry argument: SPARQL type error
554            // (EBV error, not a query failure).
555            Err(_) => return CustomEval::Error,
556        }
557    }
558    let matrix = geometries[0].relate(&geometries[1]);
559    CustomEval::Term(oxrdf::Term::Literal(oxrdf::Literal::from(
560        predicate.evaluate(&matrix),
561    )))
562}
563
564// Plain `fn` pointers (custom functions cannot capture): one shim per IRI.
565fn eval_sf_contains(args: &[oxrdf::Term]) -> CustomEval {
566    eval_geof_named(GeoPredicate::Contains, args)
567}
568
569fn eval_sf_within(args: &[oxrdf::Term]) -> CustomEval {
570    eval_geof_named(GeoPredicate::Within, args)
571}
572
573fn eval_sf_intersects(args: &[oxrdf::Term]) -> CustomEval {
574    eval_geof_named(GeoPredicate::Intersects, args)
575}
576
577fn eval_geof_named(predicate: GeoPredicate, args: &[oxrdf::Term]) -> CustomEval {
578    eval_geof_function(predicate.iri(), args)
579}
580
581enum PreparedGeoArgument {
582    Ready(Arc<Geometry<f64>>),
583    NeedsResolve,
584    Error,
585}
586
587/// Resolve one encoded geo argument through the query-local prepared-value
588/// cache. Native terms use `geo_lexical_key`, so CRS, datatype, and spike flag
589/// remain part of the cache identity. A stored geometry whose lexical has not
590/// been prefetched yet returns `NeedsResolve`; the residual retry calls this
591/// again after the lexical window lands.
592fn prepared_geo_argument(
593    term: &EncodedTerm,
594    cache: &dyn PreparedLiteralCache,
595) -> PreparedGeoArgument {
596    let Some(key) = waratah_storage::geo_lexical_key(term) else {
597        return PreparedGeoArgument::NeedsResolve;
598    };
599    if let Some(value) = cache.prepared_value(&key)
600        && let Ok(geometry) = value.downcast::<Geometry<f64>>()
601    {
602        return PreparedGeoArgument::Ready(geometry);
603    }
604
605    let source = match term {
606        EncodedTerm::LiteralPoint { x, y, .. } => Geometry::Point(geo::Point::new(*x, *y)),
607        EncodedTerm::LiteralGeometry {
608            geo_datatype,
609            blob_id,
610            ..
611        } => {
612            if let Some(payload) = cache.blob_payload(blob_id) {
613                match crate::relate::candidate_from_ewkb(payload) {
614                    Ok(geometry) => geometry,
615                    Err(_) => return PreparedGeoArgument::Error,
616                }
617            } else if let Some(lexical) = cache.resolved_string(&key) {
618                let literal = oxrdf::Literal::new_typed_literal(
619                    lexical,
620                    oxrdf::NamedNode::new_unchecked(geo_datatype.iri()),
621                );
622                match crate::encode::parse_geometry_literal(&literal).and_then(|(source, crs)| {
623                    crate::encode::transform_geometry_to_crs84(&source, crs)
624                }) {
625                    Ok(geometry) => geometry,
626                    Err(_) => return PreparedGeoArgument::Error,
627                }
628            } else {
629                return PreparedGeoArgument::NeedsResolve;
630            }
631        }
632        _ => return PreparedGeoArgument::NeedsResolve,
633    };
634
635    let geometry = match prepare_spatial_geometry(source) {
636        Ok(geometry) => geometry,
637        Err(_) => return PreparedGeoArgument::Error,
638    };
639    let cost = geometry_retained_bytes(&geometry);
640    let geometry = Arc::new(geometry);
641    cache.insert_prepared_value(key, geometry.clone(), cost);
642    PreparedGeoArgument::Ready(geometry)
643}
644
645fn eval_geof_encoded_cached(
646    predicate: GeoPredicate,
647    args: &[EncodedTerm],
648    cache: &dyn PreparedLiteralCache,
649) -> CustomEval {
650    if args.len() != 2 {
651        return CustomEval::Error;
652    }
653    let mut geometries = Vec::with_capacity(2);
654    for arg in args {
655        match prepared_geo_argument(arg, cache) {
656            PreparedGeoArgument::Ready(geometry) => geometries.push(geometry),
657            PreparedGeoArgument::NeedsResolve => return CustomEval::NeedsResolve,
658            PreparedGeoArgument::Error => return CustomEval::Error,
659        }
660    }
661    let matrix = geometries[0].as_ref().relate(geometries[1].as_ref());
662    CustomEval::Encoded(EncodedTerm::BooleanLiteral(
663        predicate.evaluate(&matrix).into(),
664    ))
665}
666
667fn eval_sf_contains_cached(args: &[EncodedTerm], cache: &dyn PreparedLiteralCache) -> CustomEval {
668    eval_geof_encoded_cached(GeoPredicate::Contains, args, cache)
669}
670
671fn eval_sf_within_cached(args: &[EncodedTerm], cache: &dyn PreparedLiteralCache) -> CustomEval {
672    eval_geof_encoded_cached(GeoPredicate::Within, args, cache)
673}
674
675fn eval_sf_intersects_cached(args: &[EncodedTerm], cache: &dyn PreparedLiteralCache) -> CustomEval {
676    eval_geof_encoded_cached(GeoPredicate::Intersects, args, cache)
677}
678
679/// Approximate retained heap cost used by the query-local prepared-value byte
680/// limit. Coordinate counts dominate geometry retention; container overhead is
681/// included once per geometry and ring.
682fn geometry_retained_bytes(geometry: &Geometry<f64>) -> usize {
683    fn line_cost(line: &geo::LineString<f64>) -> usize {
684        std::mem::size_of::<geo::LineString<f64>>()
685            + line.0.len() * std::mem::size_of::<geo::Coord<f64>>()
686    }
687    fn polygon_cost(polygon: &geo::Polygon<f64>) -> usize {
688        std::mem::size_of::<geo::Polygon<f64>>()
689            + line_cost(polygon.exterior())
690            + polygon.interiors().iter().map(line_cost).sum::<usize>()
691    }
692    std::mem::size_of::<Geometry<f64>>()
693        + match geometry {
694            Geometry::Point(point) => std::mem::size_of_val(point),
695            Geometry::Line(line) => std::mem::size_of_val(line),
696            Geometry::LineString(line) => line_cost(line),
697            Geometry::Polygon(polygon) => polygon_cost(polygon),
698            Geometry::MultiPoint(points) => {
699                std::mem::size_of::<geo::MultiPoint<f64>>()
700                    + points.0.len() * std::mem::size_of::<geo::Point<f64>>()
701            }
702            Geometry::MultiLineString(lines) => {
703                std::mem::size_of::<geo::MultiLineString<f64>>()
704                    + lines.0.iter().map(line_cost).sum::<usize>()
705            }
706            Geometry::MultiPolygon(polygons) => {
707                std::mem::size_of::<geo::MultiPolygon<f64>>()
708                    + polygons.0.iter().map(polygon_cost).sum::<usize>()
709            }
710            Geometry::GeometryCollection(collection) => {
711                std::mem::size_of::<geo::GeometryCollection<f64>>()
712                    + collection
713                        .0
714                        .iter()
715                        .map(geometry_retained_bytes)
716                        .sum::<usize>()
717            }
718            Geometry::Rect(rect) => std::mem::size_of_val(rect),
719            Geometry::Triangle(triangle) => std::mem::size_of_val(triangle),
720        }
721}
722
723/// Register the three `geof:*` custom functions. The cache-aware encoded path
724/// avoids repeated parse/validate/reduce work for native geo terms; a miss
725/// escalates to the existing residual ground implementation.
726pub fn geof_custom_functions() -> Vec<CustomFunction> {
727    [
728        (
729            GeoPredicate::Contains,
730            eval_sf_contains as fn(&[oxrdf::Term]) -> CustomEval,
731            eval_sf_contains_cached as fn(&[EncodedTerm], &dyn PreparedLiteralCache) -> CustomEval,
732        ),
733        (
734            GeoPredicate::Within,
735            eval_sf_within as fn(&[oxrdf::Term]) -> CustomEval,
736            eval_sf_within_cached as fn(&[EncodedTerm], &dyn PreparedLiteralCache) -> CustomEval,
737        ),
738        (
739            GeoPredicate::Intersects,
740            eval_sf_intersects as fn(&[oxrdf::Term]) -> CustomEval,
741            eval_sf_intersects_cached
742                as fn(&[EncodedTerm], &dyn PreparedLiteralCache) -> CustomEval,
743        ),
744    ]
745    .into_iter()
746    .map(
747        |(predicate, eval_ground, eval_encoded_cached)| CustomFunction {
748            iri: oxrdf::NamedNode::new_unchecked(predicate.iri()),
749            min_args: 2,
750            max_args: 2,
751            eval_ground,
752            eval_encoded: None,
753            eval_encoded_cached: Some(eval_encoded_cached),
754        },
755    )
756    .collect()
757}
758
759#[cfg(test)]
760mod tests {
761    use super::*;
762    use std::any::Any;
763    use std::collections::HashMap;
764    use std::sync::Mutex;
765    use std::sync::atomic::{AtomicUsize, Ordering};
766
767    use waratah_compute::CustomOp;
768    use waratah_compute::ExprCapability;
769    use waratah_compute::TextSubjectWindow;
770    use waratah_compute::plugin::PluginPayloadBox;
771    use waratah_storage::{SmallString, SnapshotId, TemporalCellInterval, TemporalQueryPredicate};
772
773    /// In-process blob store for the mock env: content id → EWKB payload.
774    type BlobMap = HashMap<StrHash, Vec<u8>>;
775    /// In-process registry for the mock env: value hash → lexical string.
776    type StringMap = HashMap<StrHash, String>;
777
778    #[derive(Default)]
779    struct TestPreparedCache {
780        strings: StringMap,
781        blobs: BlobMap,
782        prepared: Mutex<HashMap<StrHash, Arc<dyn Any + Send + Sync>>>,
783        inserts: AtomicUsize,
784    }
785
786    impl PreparedLiteralCache for TestPreparedCache {
787        fn prepared_value(&self, key: &StrHash) -> Option<Arc<dyn Any + Send + Sync>> {
788            self.prepared
789                .lock()
790                .expect("prepared cache")
791                .get(key)
792                .cloned()
793        }
794
795        fn insert_prepared_value(
796            &self,
797            key: StrHash,
798            value: Arc<dyn Any + Send + Sync>,
799            _cost: usize,
800        ) -> bool {
801            let mut prepared = self.prepared.lock().expect("prepared cache");
802            if prepared.contains_key(&key) {
803                return true;
804            }
805            self.inserts.fetch_add(1, Ordering::Relaxed);
806            prepared.insert(key, value);
807            true
808        }
809
810        fn resolved_string(&self, key: &StrHash) -> Option<&str> {
811            self.strings.get(key).map(String::as_str)
812        }
813
814        fn blob_payload(&self, key: &StrHash) -> Option<&[u8]> {
815            self.blobs.get(key).map(Vec::as_slice)
816        }
817    }
818
819    const SEQ_POLY_WKT: &str =
820        "POLYGON((152.5 -28.0, 153.5 -28.0, 153.5 -27.0, 152.5 -27.0, 152.5 -28.0))";
821
822    /// Bind the four mock closures and the [`PluginEnv`] in the CALLING
823    /// test's body: the env's `&dyn Fn` fields borrow closure locals, so
824    /// they cannot be built inside a helper's scope. `$candidates`
825    /// (`Vec<EncodedTerm>`), `$blobs` ([`BlobMap`]), and `$strings`
826    /// ([`StringMap`]) are captured by reference; `$pushed` is the
827    /// `Option<&[EncodedTerm]>` for [`PluginEnv::pushed_vals`]. Mirrors the
828    /// one production construction site (`run_executor`), with local maps
829    /// instead of RPCs.
830    macro_rules! mock_env {
831        ($candidates:expr, $blobs:expr, $strings:expr, $pushed:expr => $env:ident) => {
832            // Candidate drain: the prepared list, ignoring the intervals
833            // (the real drain is the partition's GeoCandidateScan RPC).
834            let geo_candidates = |_: &[GeoCellInterval], _: Option<GeoEnvelope>, _: u64| {
835                let out = ($candidates).clone();
836                Box::pin(std::future::ready(Ok(out)))
837                    as Pin<Box<dyn Future<Output = Result<Vec<EncodedTerm>, ComputeError>> + Send>>
838            };
839            // Never drained by these tests (no temporal op reaches here).
840            let temporal_candidates = |_: &[TemporalCellInterval],
841                                       _: TemporalQueryPredicate,
842                                       _: u64| {
843                let out = Vec::new();
844                Box::pin(std::future::ready(Ok(out)))
845                    as Pin<Box<dyn Future<Output = Result<Vec<EncodedTerm>, ComputeError>> + Send>>
846            };
847            // Text drains never fire in the geo tests (no text rewrite runs).
848            let text_candidates = |_: &waratah_storage::TextSearchRequest| {
849                let out = Vec::new();
850                Box::pin(std::future::ready(Ok(out)))
851                    as Pin<Box<dyn Future<Output = Result<Vec<EncodedTerm>, ComputeError>> + Send>>
852            };
853            // The subject resolve never fires in the geo tests either: an
854            // empty window, built the way the engine builds one.
855            let text_subjects = |_: &waratah_storage::TextSubjectRequest| {
856                let out = std::sync::Arc::new(
857                    waratah_compute::TextSubjectWindowBuilder::new(
858                        std::sync::Arc::new(waratah_compute::TermDict::new()),
859                        false,
860                    )
861                    .finish(),
862                );
863                Box::pin(std::future::ready(Ok(out)))
864                    as Pin<
865                        Box<
866                            dyn Future<
867                                    Output = Result<
868                                        std::sync::Arc<TextSubjectWindow>,
869                                        ComputeError,
870                                    >,
871                                > + Send,
872                        >,
873                    >
874            };
875            // In-process blob store lookup (aligned with the request).
876            let blobs_fn = |ids: &[StrHash]| {
877                let out: Vec<Option<Vec<u8>>> =
878                    ids.iter().map(|id| ($blobs).get(id).cloned()).collect();
879                Box::pin(std::future::ready(Ok(out)))
880                    as Pin<
881                        Box<dyn Future<Output = Result<Vec<Option<Vec<u8>>>, ComputeError>> + Send>,
882                    >
883            };
884            // In-process registry lookup (aligned with the request; `None`
885            // = miss, exactly the contract the engine resolve provides).
886            let strings_fn = |hashes: &[StrHash]| {
887                let out: Vec<Option<String>> = hashes
888                    .iter()
889                    .map(|hash| ($strings).get(hash).cloned())
890                    .collect();
891                Box::pin(std::future::ready(Ok(out)))
892                    as Pin<
893                        Box<dyn Future<Output = Result<Vec<Option<String>>, ComputeError>> + Send>,
894                    >
895            };
896            let $env = PluginEnv {
897                snapshot: SnapshotId::latest(),
898                geo_candidates: &geo_candidates,
899                temporal_candidates: &temporal_candidates,
900                text_candidates: &text_candidates,
901                text_subjects: &text_subjects,
902                blobs: &blobs_fn,
903                strings: &strings_fn,
904                pushed_vals: $pushed,
905                pushed_variable: None,
906            };
907        };
908    }
909
910    fn wkt_literal(wkt: &str) -> oxrdf::Literal {
911        oxrdf::Literal::new_typed_literal(
912            wkt,
913            oxrdf::NamedNode::new_unchecked(crate::GEO_WKT_LITERAL),
914        )
915    }
916
917    /// Parse a CRS84 WKT lexical through the same encode path as ingest.
918    fn crs84(wkt: &str) -> Geometry<f64> {
919        crate::encode::parse_geometry_literal(&wkt_literal(wkt))
920            .and_then(|(source, crs)| crate::encode::transform_geometry_to_crs84(&source, crs))
921            .expect("test WKT must parse as CRS84")
922    }
923
924    /// The storage encoding of a typed literal (the hashed fallback the
925    /// encode hook leaves for non-native shapes): short lexicals land in
926    /// [`EncodedTerm::SmallTypedLiteral`], long ones in
927    /// [`EncodedTerm::BigTypedLiteral`] with `value_id = StrHash(lexical)`.
928    fn typed_term(literal: &oxrdf::Literal) -> EncodedTerm {
929        EncodedTerm::from(literal)
930    }
931
932    /// A `geo_scan` op over the SEQ polygon const with `?g` as its output.
933    fn scan_op(predicate: GeoPredicate) -> CustomOp {
934        scan_op_over(predicate, SEQ_POLY_WKT)
935    }
936
937    /// A `geo_scan` op over an arbitrary CRS84 WKT const (`?g` output).
938    fn scan_op_over(predicate: GeoPredicate, const_wkt: &str) -> CustomOp {
939        let geometry = crs84(const_wkt);
940        let covering = crate::covering::geometry_covering(&geometry);
941        CustomOp {
942            plugin_id: crate::PLUGIN_ID,
943            op_id: crate::plan::GEO_SCAN_OP_ID,
944            payload: PluginPayloadBox::new(GeoScanPayload {
945                predicate,
946                const_term: EncodedTerm::from(&wkt_literal(const_wkt)),
947                query_envelope: crate::covering::geometry_envelope(&geometry)
948                    .expect("polygon has an envelope"),
949                query_geometry: geometry,
950                intervals: crate::covering::intervals_for_covering(&covering),
951            }),
952            children: Vec::new(),
953            variables: vec![waratah_compute::plugin::variable("g")],
954            produced_row_count_estimate: 1,
955            cost: None,
956            pinned: Vec::new(),
957        }
958    }
959
960    /// The registry map answering every lexical in `lexicals` (a value hash
961    /// missing from the map is a resolve miss).
962    fn string_map(literals: &[oxrdf::Literal]) -> StringMap {
963        literals
964            .iter()
965            .map(|literal| (StrHash::new(literal.value()), literal.value().to_owned()))
966            .collect()
967    }
968
969    /// The n-th distinct inline POINT term, well inside the SEQ polygon.
970    /// A `LiteralPoint` relates from its stored coordinates — the
971    /// fetch-free key shape the direct-road pricing singles out.
972    fn point_term(n: u32) -> EncodedTerm {
973        let wkt = format!("POINT({} -27.5)", 152.6 + f64::from(n) * 0.0004);
974        crate::encode::prepare_geometry_literal(&wkt_literal(&wkt))
975            .expect("point prepares native")
976            .term
977    }
978
979    /// The n-th distinct blob-backed LINESTRING term (native
980    /// `LiteralGeometry`), inside the SEQ polygon.
981    fn linestring_term(n: u32) -> EncodedTerm {
982        let wkt = format!(
983            "LINESTRING({} -27.5, {} -27.4)",
984            152.6 + f64::from(n) * 0.0004,
985            152.7 + f64::from(n) * 0.0004
986        );
987        crate::encode::prepare_geometry_literal(&wkt_literal(&wkt))
988            .expect("linestring prepares native")
989            .term
990    }
991
992    #[test]
993    fn geo_prepared_cache_does_not_change_planning_capability() {
994        for function in geof_custom_functions() {
995            assert!(function.eval_encoded_cached.is_some());
996            assert_eq!(function.capability(), ExprCapability::AlwaysResolve);
997        }
998    }
999
1000    #[test]
1001    fn cached_encoded_geo_evaluator_prepares_each_term_once() {
1002        let spike = crate::encode::prepare_geometry_literal(&wkt_literal(
1003            "POLYGON((154.000000 -28.797429, 154.000000 -27.760501, \
1004             153.834707 -27.678942, 153.018589 -27.558772, \
1005             152.746796 -28.041757, 152.170156 -29.032803, \
1006             153.097669 -29.526447, 154.000000 -29.270522, \
1007             154.000000 -29.550790, 154.000000 -28.797429))",
1008        ))
1009        .unwrap();
1010        let inside =
1011            crate::encode::prepare_geometry_literal(&wkt_literal("POINT(153 -28.5)")).unwrap();
1012        let mut cache = TestPreparedCache::default();
1013        cache
1014            .blobs
1015            .insert(spike.blobs[0].0, spike.blobs[0].1.clone());
1016
1017        let args = [spike.term.clone(), inside.term.clone()];
1018        for _ in 0..2 {
1019            assert!(matches!(
1020                eval_sf_intersects_cached(&args, &cache),
1021                CustomEval::Encoded(EncodedTerm::BooleanLiteral(value)) if bool::from(value)
1022            ));
1023        }
1024        assert_eq!(cache.inserts.load(Ordering::Relaxed), 2);
1025
1026        let removed_spike =
1027            crate::encode::prepare_geometry_literal(&wkt_literal("POINT(154 -29.4)")).unwrap();
1028        assert!(matches!(
1029            eval_sf_intersects_cached(&[spike.term, removed_spike.term], &cache),
1030            CustomEval::Encoded(EncodedTerm::BooleanLiteral(value)) if !bool::from(value)
1031        ));
1032        assert_eq!(cache.inserts.load(Ordering::Relaxed), 3);
1033    }
1034
1035    #[test]
1036    fn direct_road_falls_back_to_the_count_limit_without_a_stamp() {
1037        // cost: None is the legacy shape: the count limit decides, whatever
1038        // the key shapes are.
1039        let points: Vec<EncodedTerm> = (0..501).map(point_term).collect();
1040        assert!(!take_direct_road(&points, None, 1000));
1041        assert!(take_direct_road(&points[..500], None, 1000));
1042    }
1043
1044    #[test]
1045    fn point_heavy_keys_take_the_direct_road_far_past_the_legacy_limit() {
1046        // 2000 fetch-free points: direct prices 2000 × 1 against the drain
1047        // road's 900 + min(2000, 1000) × 8 = 8900. The old count rule
1048        // would have sent this to the drain.
1049        let cost = CustomOpCost {
1050            drain_rows: 900,
1051            per_key_unit: 8,
1052            inline_point_unit: 1,
1053            direct_probe: true,
1054            probe_keyed_columns: 0b1,
1055            probe_filter_unit: 8,
1056            probe_memo_entry_rows: 0,
1057        };
1058        let points: Vec<EncodedTerm> = (0..2000).map(point_term).collect();
1059        assert!(take_direct_road(&points, Some(&cost), 1000));
1060    }
1061
1062    #[test]
1063    fn key_shapes_flip_the_verdict_at_the_same_count() {
1064        // Same count, same sweep bound, same cost stamp — only the term
1065        // SHAPES differ: 2000 points relate directly (2000 < 7000 + 1000×8),
1066        // 2000 blob-backed keys do not (2000×8 = 16000 > 15000). This is
1067        // exactly the decision a count threshold cannot make.
1068        let cost = CustomOpCost {
1069            drain_rows: 7000,
1070            per_key_unit: 8,
1071            inline_point_unit: 1,
1072            direct_probe: true,
1073            probe_keyed_columns: 0b1,
1074            probe_filter_unit: 8,
1075            probe_memo_entry_rows: 0,
1076        };
1077        let points: Vec<EncodedTerm> = (0..2000).map(point_term).collect();
1078        let blobs: Vec<EncodedTerm> = (0..2000).map(linestring_term).collect();
1079        assert!(take_direct_road(&points, Some(&cost), 1000));
1080        assert!(!take_direct_road(&blobs, Some(&cost), 1000));
1081    }
1082
1083    #[test]
1084    fn blob_backed_keys_still_lose_to_a_cheap_drain() {
1085        // The semi-join's home ground: 50 expensive keys, a near-free drain,
1086        // and a tiny survivor bound (min(50, 5) = 5): 50×100 = 5000 against
1087        // 10 + 5×100 = 510.
1088        let cost = CustomOpCost {
1089            drain_rows: 10,
1090            per_key_unit: 100,
1091            inline_point_unit: 1,
1092            direct_probe: true,
1093            probe_keyed_columns: 0b1,
1094            probe_filter_unit: 100,
1095            probe_memo_entry_rows: 0,
1096        };
1097        let blobs: Vec<EncodedTerm> = (0..50).map(linestring_term).collect();
1098        assert!(!take_direct_road(&blobs, Some(&cost), 5));
1099    }
1100
1101    /// The calibration audit: the planner's
1102    /// `CustomOp::keyed_cost` is the CONSERVATIVE BOUND of the keyed
1103    /// regime, and [`take_direct_road`]'s break-even is its REFERENCE
1104    /// pricing — inline points at `inline_point_unit`, every other shape
1105    /// blob-backed at `per_key_unit`, against a semi-join both sides
1106    /// price with the same formula (drain + survivors on the produced
1107    /// estimate). Three properties pin the relationship:
1108    ///
1109    /// 1. SOUNDNESS — for every key mix, the bound never under-prices
1110    ///    the executor's direct road: blob-backed keys price identically
1111    ///    on both sides, and an inline point prices at
1112    ///    `inline_point_unit` ≤ `per_key_unit`.
1113    /// 2. SEMI-JOIN PARITY — the planner's semi-join term and the
1114    ///    executor's are the same formula on the same produced estimate.
1115    /// 3. THE GAP IS BOUNDED AND KNOWN-SHAPED — the over-price is at
1116    ///    most `per_key_unit - inline_point_unit` per inline point (the
1117    ///    all-point mix is the worst case). On the bench-realistic shape
1118    ///    (the transects 514-value ?g push against the real stamp) the
1119    ///    gap is 4,112 − 514 = 3,598 work units of a ~333,812-value cost estimate
1120    ///    — ~1.1%, inside `SEAT_NOISE_BAND_PCT`'s 2%: the transects
1121    ///    placement cannot flip on the conservative bound (post-G
1122    ///    diagnostic numbers).
1123    ///
1124    /// Verdict: the bound is sound and the over-price is bounded
1125    /// and known-shaped — NO cost-stamp extension ships. A plan-time mix
1126    /// estimate would be an invented number (the planner knows value
1127    /// counts, never term shapes — the same epistemics as pushed value
1128    /// counts), and a runtime hook cannot inform a plan-time comparison:
1129    /// the executor's own road choice is the correction, and the
1130    /// constant calibration (`per_key_unit` = 8 against the wall-clock
1131    /// relate cost) is the bench round's trace-signature measurement.
1132    #[test]
1133    fn keyed_cost_is_a_sound_conservative_bound_of_the_inline_path() {
1134        let cost = CustomOpCost {
1135            drain_rows: 36_862,
1136            per_key_unit: 8,
1137            inline_point_unit: 1,
1138            direct_probe: true,
1139            probe_keyed_columns: 0b1,
1140            probe_filter_unit: 8,
1141            probe_memo_entry_rows: 0,
1142        };
1143        let mut op = scan_op(GeoPredicate::Intersects);
1144        op.produced_row_count_estimate = 36_862;
1145        op.cost = Some(cost);
1146
1147        // The reference price of the direct road over one deduped mix —
1148        // take_direct_road's own arm formula (the executor relates each
1149        // shape at its unit and sums).
1150        let direct_price = |mix: &[EncodedTerm]| -> u64 {
1151            mix.iter()
1152                .map(|term| match term {
1153                    EncodedTerm::LiteralPoint { .. } => 1,
1154                    _ => 8,
1155                })
1156                .fold(0u64, u64::saturating_add)
1157        };
1158
1159        let n = 500usize;
1160        for points_pct in [0usize, 25, 50, 75, 100] {
1161            let point_n = n * points_pct / 100;
1162            let mix: Vec<EncodedTerm> = (0..point_n)
1163                .map(|i| point_term(i as u32))
1164                .chain((0..(n - point_n)).map(|i| linestring_term(i as u32)))
1165                .collect();
1166            // Distinct terms — the executor dedups before pricing.
1167            let set: std::collections::HashSet<&EncodedTerm> = mix.iter().collect();
1168            let mix: Vec<EncodedTerm> = set.into_iter().cloned().collect();
1169            let executor_direct = direct_price(&mix);
1170            let executor_semi = 36_862u64.saturating_add((n as u64).min(36_862) * 8);
1171            let executor_regime = executor_direct.min(executor_semi);
1172            let bound = op.keyed_cost(n as u64, Some(0)).unwrap();
1173            // 1. Soundness: the bound never under-prices the regime.
1174            assert!(
1175                bound >= executor_regime,
1176                "{points_pct}% points: bound {bound} < actual {executor_regime}"
1177            );
1178            // 2. Semi-join parity on the shared formula.
1179            assert_eq!(executor_semi, 36_862 + 500 * 8);
1180            // 3. All-blob: blob-backed keys price identically on both
1181            //    sides, so the bound meets the reference exactly.
1182            if points_pct == 0 {
1183                assert_eq!(bound, executor_direct, "all-blob: bound == actual");
1184            }
1185        }
1186        // The worst case, quantified on the bench shape: 514 point keys —
1187        // actual 514, bound 4,112, gap 3,598 (≈1.1% of the post-G
1188        // transects seat, inside the 2% noise band).
1189        let points: Vec<EncodedTerm> = (0..514).map(point_term).collect();
1190        assert_eq!(direct_price(&points), 514);
1191        assert_eq!(op.keyed_cost(514, Some(0)).unwrap(), 4_112);
1192    }
1193
1194    /// Lowercase hex of bytes (test-local: the lexical form of a
1195    /// `geo:wkbLiteral` candidate).
1196    fn hex(bytes: &[u8]) -> String {
1197        bytes.iter().map(|byte| format!("{byte:02x}")).collect()
1198    }
1199
1200    #[tokio::test]
1201    async fn big_typed_literal_candidate_is_kept_when_it_intersects() {
1202        // The ingest fallback shape (a geo:wktLiteral that stayed an
1203        // ordinary typed literal) must relate exactly like a native term:
1204        // the planner strips the geof FILTER, so geo_scan IS the FILTER
1205        // for every binding class the store can hold. Pinned path
1206        // (strict=false): the driver's term, related directly.
1207        let literal = wkt_literal(SEQ_POLY_WKT);
1208        let term = typed_term(&literal);
1209        assert!(
1210            matches!(term, EncodedTerm::BigTypedLiteral { .. }),
1211            "the 62-byte lexical must encode big: {term:?}"
1212        );
1213        let candidates = Vec::new();
1214        let blobs: BlobMap = HashMap::new();
1215        let strings = string_map(std::slice::from_ref(&literal));
1216        mock_env!(candidates, blobs, strings, None => env);
1217        let mut op = scan_op(GeoPredicate::Intersects);
1218        op.pinned
1219            .push((waratah_compute::plugin::variable("g"), term.clone()));
1220        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1221        assert_eq!(rows, vec![vec![term]]);
1222    }
1223
1224    #[tokio::test]
1225    async fn ill_formed_typed_literal_is_dropped_not_an_error() {
1226        // A geo-datatype typed literal with an unparseable lexical is a
1227        // SPARQL type error on the unindexed FILTER path (row dropped);
1228        // the exact path skips it instead of failing the scan.
1229        let literal = wkt_literal("POLYGON((not a geometry");
1230        let term = typed_term(&literal);
1231        let candidates = Vec::new();
1232        let blobs: BlobMap = HashMap::new();
1233        let strings = string_map(std::slice::from_ref(&literal));
1234        mock_env!(candidates, blobs, strings, None => env);
1235        let mut op = scan_op(GeoPredicate::Intersects);
1236        op.pinned
1237            .push((waratah_compute::plugin::variable("g"), term));
1238        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1239        assert!(rows.is_empty());
1240    }
1241
1242    #[tokio::test]
1243    async fn registry_miss_typed_literal_errors() {
1244        // A big typed literal whose value hash nothing can answer — neither
1245        // the query-local strings map nor the registry — is a consistency
1246        // violation, not stale data: v1 never retracts registry strings on
1247        // delete, so a posting referencing an unanswerable value hash means
1248        // the string store lost an entry. The scan fails loudly instead of
1249        // silently dropping the row.
1250        let term = typed_term(&wkt_literal(SEQ_POLY_WKT));
1251        let candidates = Vec::new();
1252        let blobs: BlobMap = HashMap::new();
1253        let strings: StringMap = HashMap::new();
1254        mock_env!(candidates, blobs, strings, None => env);
1255        let mut op = scan_op(GeoPredicate::Intersects);
1256        op.pinned
1257            .push((waratah_compute::plugin::variable("g"), term));
1258        let result = GeoExecutorPlugin.execute(&op, env).await;
1259        assert!(
1260            result.is_err(),
1261            "an unresolvable lexical must error the scan, not drop the row"
1262        );
1263    }
1264
1265    #[tokio::test]
1266    async fn non_geo_typed_literal_drops_lenient_and_errors_strict() {
1267        // A typed literal whose datatype is neither geo IRI never relates:
1268        // the lenient pinned / pushed paths skip it, the strict index
1269        // sweep rejects it as a consistency violation.
1270        let term = EncodedTerm::SmallTypedLiteral {
1271            value: SmallString::try_from("42").unwrap(),
1272            datatype_id: StrHash::new("http://www.w3.org/2001/XMLSchema#integer"),
1273        };
1274
1275        // Lenient (pinned): skip silently.
1276        let candidates = Vec::new();
1277        let blobs: BlobMap = HashMap::new();
1278        let strings: StringMap = HashMap::new();
1279        mock_env!(candidates, blobs, strings, None => env);
1280        let mut op = scan_op(GeoPredicate::Intersects);
1281        op.pinned
1282            .push((waratah_compute::plugin::variable("g"), term.clone()));
1283        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1284        assert!(rows.is_empty());
1285
1286        // Strict (driver sweep, no pushed keys): the guard errors.
1287        let candidates = vec![term];
1288        let blobs: BlobMap = HashMap::new();
1289        let strings: StringMap = HashMap::new();
1290        mock_env!(candidates, blobs, strings, None => env);
1291        let op = scan_op(GeoPredicate::Intersects);
1292        let error = GeoExecutorPlugin.execute(&op, env).await.unwrap_err();
1293        assert!(
1294            error.to_string().contains("carries a non-geo term"),
1295            "strict guard must reject the non-geo posting: {error}"
1296        );
1297    }
1298
1299    #[tokio::test]
1300    async fn geo_typed_literal_on_the_strict_sweep_is_processed_not_an_error() {
1301        // The strict guard's new shape: a geo-datatype typed literal IS a
1302        // geo term — the sweep processes it (and keeps it on a match),
1303        // never errors.
1304        let literal = wkt_literal(SEQ_POLY_WKT);
1305        let term = typed_term(&literal);
1306        let candidates = vec![term.clone()];
1307        let blobs: BlobMap = HashMap::new();
1308        let strings = string_map(std::slice::from_ref(&literal));
1309        mock_env!(candidates, blobs, strings, None => env);
1310        let op = scan_op(GeoPredicate::Intersects);
1311        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1312        assert_eq!(rows, vec![vec![term]]);
1313    }
1314
1315    #[tokio::test]
1316    async fn typed_literal_candidates_answer_like_the_ground_filter() {
1317        // Differential: the same candidate set carried as typed literals
1318        // (small + big, WKT + WKB, valid + ill-formed + EMPTY) answers
1319        // `geof:sfContains(const, ?g)` identically through the scan's
1320        // exact relate (relate_terms via execute) and through the
1321        // unindexed ground custom fn (eval_geof_function) — the rewrite
1322        // must be a COMPLETE implementation of the stripped conjunct.
1323        let wkt_lexicals = [
1324            "POINT(153 -27)", // small typed literal, ON the const's top edge (dropped by both paths)
1325            "POINT(0 0)",     // small typed literal, outside
1326            "POINT(153.0 -27.5)", // big typed literal, inside
1327            "POLYGON((152.6 -27.9, 152.8 -27.9, 152.8 -27.7, 152.6 -27.7, 152.6 -27.9))", // big, inside
1328            "POLYGON((153.4 -27.1, 153.6 -27.1, 153.6 -26.9, 153.4 -26.9, 153.4 -27.1))", // big, overlaps
1329            "POLYGON((not a geometry", // big, ill-formed: type error both paths
1330            "POINT EMPTY",             // small, EMPTY: type error by design
1331        ];
1332        // One wkbLiteral candidate (inside the const): the second geo
1333        // datatype hash, hex EWKB lon/lat.
1334        let wkb_point = Geometry::Point(geo::Point::new(152.7, -27.8));
1335        let wkb_lexical =
1336            hex(&crate::encode::geometry_to_crs84_ewkb(&wkb_point)
1337                .expect("test point encodes to EWKB"));
1338        let mut literals: Vec<oxrdf::Literal> = wkt_lexicals
1339            .iter()
1340            .map(|lexical| wkt_literal(lexical))
1341            .collect();
1342        literals.push(oxrdf::Literal::new_typed_literal(
1343            &wkb_lexical,
1344            oxrdf::NamedNode::new_unchecked(crate::GEO_WKB_LITERAL),
1345        ));
1346        let terms: Vec<EncodedTerm> = literals.iter().map(typed_term).collect();
1347
1348        // Exact path: small pushed list (behavior 2 — strict=false), the
1349        // arm under test reached the way a broadcast join delivers keys.
1350        // sfContains(const, ?g) inverts to candidate-WITHIN-const (the
1351        // planner's orientation table: relates_candidate evaluates
1352        // `candidate relate const`).
1353        let candidates = Vec::new();
1354        let blobs: BlobMap = HashMap::new();
1355        let strings = string_map(&literals);
1356        mock_env!(candidates, blobs, strings, Some(terms.as_slice()) => env);
1357        let op = scan_op(GeoPredicate::Within);
1358        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1359        let exact: HashMap<EncodedTerm, ()> =
1360            rows.into_iter().flatten().map(|term| (term, ())).collect();
1361
1362        // Ground path: the unindexed custom fn over the SAME candidate
1363        // literals (what a resolve would hand it), const as first argument.
1364        let const_arg = oxrdf::Term::Literal(wkt_literal(SEQ_POLY_WKT));
1365        let mut ground = HashMap::new();
1366        for (term, literal) in terms.iter().zip(&literals) {
1367            if matches!(
1368                eval_geof_function(
1369                    GeoPredicate::Contains.iri(),
1370                    &[const_arg.clone(), oxrdf::Term::Literal(literal.clone())],
1371                ),
1372                CustomEval::Term(answer)
1373                    if answer == oxrdf::Term::Literal(oxrdf::Literal::from(true))
1374            ) {
1375                ground.insert(term.clone(), ());
1376            }
1377        }
1378
1379        assert_eq!(
1380            exact.len(),
1381            3,
1382            "kept set must be the 3 contained candidates: {exact:?}"
1383        );
1384        assert_eq!(exact, ground, "exact relate and ground FILTER must agree");
1385    }
1386
1387    #[tokio::test]
1388    async fn small_typed_literal_candidate_is_kept_from_inline_lexical() {
1389        // The ≤ 15-byte lexical is INLINE in the term (`SmallTypedLiteral`)
1390        // — related without any registry resolve (the strings map is empty
1391        // here, so a resolve attempt would drop the candidate). The pushed
1392        // small-list path (behavior 2, strict=false) delivers the term.
1393        let literal = wkt_literal("POINT(2 2)");
1394        let term = typed_term(&literal);
1395        assert!(
1396            matches!(term, EncodedTerm::SmallTypedLiteral { .. }),
1397            "the 10-byte lexical must encode small: {term:?}"
1398        );
1399        let candidates = Vec::new();
1400        let blobs: BlobMap = HashMap::new();
1401        let strings: StringMap = HashMap::new();
1402        mock_env!(candidates, blobs, strings, Some(&[term.clone()][..]) => env);
1403        let op = scan_op_over(GeoPredicate::Within, "POLYGON((0 0, 4 0, 4 4, 0 4, 0 0))");
1404        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1405        assert_eq!(rows, vec![vec![term]]);
1406    }
1407
1408    #[tokio::test]
1409    async fn point_heavy_pushed_keys_take_direct_relate_without_a_drain() {
1410        // 2000 inline-point keys (well past the legacy 500) against a
1411        // stamped op: the break-even picks the direct road, so the
1412        // candidate drain NEVER fires. Every point sits inside the SEQ
1413        // const polygon, so the exact relate keeps all of them. The old
1414        // count rule would have drained the window for this shape.
1415        let drain_calls = Arc::new(AtomicUsize::new(0));
1416        let candidates = Vec::new();
1417        let blobs: BlobMap = HashMap::new();
1418        let strings: StringMap = HashMap::new();
1419        let keys: Vec<EncodedTerm> = (0..2000).map(point_term).collect();
1420        mock_env!({ drain_calls.fetch_add(1, Ordering::SeqCst); candidates.clone() },
1421                  blobs, strings, Some(keys.as_slice()) => env);
1422        let mut op = scan_op(GeoPredicate::Intersects);
1423        op.produced_row_count_estimate = 1000;
1424        op.cost = Some(CustomOpCost {
1425            drain_rows: 900,
1426            per_key_unit: 8,
1427            inline_point_unit: 1,
1428            direct_probe: true,
1429            probe_keyed_columns: 0b1,
1430            probe_filter_unit: 8,
1431            probe_memo_entry_rows: 0,
1432        });
1433        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1434        assert_eq!(
1435            drain_calls.load(Ordering::SeqCst),
1436            0,
1437            "direct road: no drain"
1438        );
1439        assert_eq!(rows.len(), 2000, "one row per matching key");
1440    }
1441
1442    #[tokio::test]
1443    async fn blob_backed_keys_take_the_semi_join_when_the_drain_is_cheap() {
1444        // 50 blob-backed keys, a near-free drain, and a tiny sweep bound:
1445        // the break-even picks the semi-join (one drain, survivors only
1446        // fetch + relate). The drain returns the keys themselves; every
1447        // survivor's payload relates inside the const polygon, so all 50
1448        // come back as rows.
1449        let drain_calls = Arc::new(AtomicUsize::new(0));
1450        let keys: Vec<EncodedTerm> = (0..50).map(linestring_term).collect();
1451        let candidates = keys.clone();
1452        // Survivors' blob fetches answer with parseable EWKB of a
1453        // linestring inside the polygon. (Content addressing is enforced
1454        // on WRITE, never re-checked on read, so the payload bytes — not
1455        // their hash — are what the relate sees.)
1456        let mut blobs: BlobMap = HashMap::new();
1457        for term in &keys {
1458            if let EncodedTerm::LiteralGeometry { blob_id, .. } = term {
1459                let payload = crate::encode::geometry_to_crs84_ewkb(&crs84(
1460                    "LINESTRING(152.6 -27.9, 152.8 -27.7)",
1461                ))
1462                .expect("test payload encodes");
1463                blobs.insert(*blob_id, payload);
1464            } else {
1465                panic!("linestring_term must mint LiteralGeometry: {term:?}");
1466            }
1467        }
1468        let strings: StringMap = HashMap::new();
1469        mock_env!({ drain_calls.fetch_add(1, Ordering::SeqCst); candidates.clone() },
1470                  blobs, strings, Some(keys.as_slice()) => env);
1471        let mut op = scan_op(GeoPredicate::Intersects);
1472        op.produced_row_count_estimate = 5;
1473        op.cost = Some(CustomOpCost {
1474            drain_rows: 10,
1475            per_key_unit: 100,
1476            inline_point_unit: 1,
1477            direct_probe: true,
1478            probe_keyed_columns: 0b1,
1479            probe_filter_unit: 100,
1480            probe_memo_entry_rows: 0,
1481        });
1482        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1483        assert_eq!(
1484            drain_calls.load(Ordering::SeqCst),
1485            1,
1486            "semi-join: one drain"
1487        );
1488        assert_eq!(rows.len(), 50, "one row per distinct matching term");
1489    }
1490
1491    #[tokio::test]
1492    async fn unstamped_op_keeps_the_legacy_count_fallback() {
1493        // cost: None: 500 point keys → direct (no drain), 501 → semi-join
1494        // (one drain, empty candidates → zero rows). Shapes are
1495        // irrelevant on this road — that is exactly its limitation.
1496        let candidates = Vec::new();
1497        let blobs: BlobMap = HashMap::new();
1498        let strings: StringMap = HashMap::new();
1499
1500        let keys_500: Vec<EncodedTerm> = (0..500).map(point_term).collect();
1501        let drain_calls_500 = Arc::new(AtomicUsize::new(0));
1502        mock_env!({ drain_calls_500.fetch_add(1, Ordering::SeqCst); candidates.clone() },
1503                  blobs, strings, Some(keys_500.as_slice()) => env);
1504        let op = scan_op(GeoPredicate::Intersects);
1505        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1506        assert_eq!(drain_calls_500.load(Ordering::SeqCst), 0, "≤ 500: direct");
1507        assert_eq!(rows.len(), 500);
1508
1509        let keys_501: Vec<EncodedTerm> = (0..501).map(point_term).collect();
1510        let drain_calls_501 = Arc::new(AtomicUsize::new(0));
1511        mock_env!({ drain_calls_501.fetch_add(1, Ordering::SeqCst); candidates.clone() },
1512                  blobs, strings, Some(keys_501.as_slice()) => env);
1513        let op = scan_op(GeoPredicate::Intersects);
1514        let rows = GeoExecutorPlugin.execute(&op, env).await.unwrap();
1515        assert_eq!(
1516            drain_calls_501.load(Ordering::SeqCst),
1517            1,
1518            "> 500: semi-join"
1519        );
1520        assert!(rows.is_empty(), "empty candidates: no survivors");
1521    }
1522}