Skip to main content

waratah_text/
plan.rs

1//! PlannerPlugin: the two rewrite families over `Filter.residual` conjuncts.
2//!
3//! **`text:query`** (Jena-style, FILTER position only) — the conjunct is
4//! stripped and the op joined on its variable:
5//!
6//! - `text:query(?lit, "q" [, "lang:xx"])` — literal mode: one childless
7//!   `text_scan` (FTS) emitting the distinct matching string-literal terms;
8//!   the join is 1:1 per row (the op dedups), so multiplicity is unchanged.
9//! - `text:query(?s, <field> [, <field2>…], "q" [, "lang:xx"])` — subject
10//!   mode: one childless `text_subjects` op makes the O partition search
11//!   the index for the whole named predicate set and walk the matched
12//!   literals' OPSG rows at the query snapshot, returning DISTINCT
13//!   `(subject[, graph])` rows. The op is a semi-join by construction, so a
14//!   subject with several matching objects is emitted ONCE (never a plain
15//!   inner join, which would multiply rows). The OPSG walk is
16//!   snapshot-visible, strictly stronger than an index-only answer; the
17//!   graph window is the FILTER's own group window
18//!   (`resolve_subject_scopes`).
19//!
20//! **`STRSTARTS` / `STRENDS` / anchored `REGEX`** — candidate injection only:
21//! a `text_scan` (prefix / suffix mode) joined on the variable, and the
22//! conjunct STAYS in the residual. For patterns within the stored seed
23//! length the candidate set is exact; longer patterns seed the leading
24//! (or trailing) characters and the residual FILTER decides. Either way the
25//! exact SPARQL string evaluator answers, so the producer only has to be a
26//! superset.
27//!
28//! **Trust gate.** `text:query` has no residual implementation: a missing
29//! epoch, a fingerprint mismatch, or a shape the rewriter does not support
30//! is a plan-time ERROR naming the repair command — never zero rows from an
31//! unusable index (the forbidden trusted-but-empty state). The string
32//! functions degrade the opposite way: untrusted → no rewrite → the exact
33//! residual answers (slow, correct).
34
35use spargebra::algebra::{Expression, Function};
36use waratah_compute::ComputeError;
37use waratah_compute::JoinStrategy;
38use waratah_compute::PlanNode;
39use waratah_compute::QueryContext;
40use waratah_compute::ground_unique_probe_term;
41use waratah_compute::plugin::{PlannerPlugin, PluginPayloadBox};
42use waratah_stats::PUSHDOWN_TERMS_LIMIT;
43use waratah_storage::{EncodedTerm, TextCandidateMode, TextSearchRequest, TextSubjectRequest};
44
45use crate::config::TextPluginConfig;
46use crate::exec::{TEXT_SCAN_OP_ID, TEXT_SUBJECTS_OP_ID, TextScanPayload, TextSubjectsPayload};
47
48/// `text:query` IRI (Jena Text index vocabulary).
49pub const TEXT_QUERY_IRI: &str = "http://jena.apache.org/text#query";
50
51/// Regex metacharacters: an anchored `REGEX` body containing any of these is
52/// regex syntax, not literal text. Such a body cannot seed a prefix/suffix
53/// candidate request, because the seed would send its characters to the index
54/// as literals while the regex engine reads them as operators — the candidate
55/// set would exclude values the real regex matches (e.g. `^a.c` matches
56/// "abc", which does not start with the characters `a.c`).
57const REGEX_METACHARACTERS: &[char] = &[
58    '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '^', '$',
59];
60
61/// Seating cost of an UNPRICED candidate drain, in rows. Advisory only
62/// (ARCH.md §10): some drains have no honest cardinality estimate the
63/// planner can compute locally — an FTS query's token statistics are not
64/// sketched, and a seed pattern LONGER than the index's stored seed cannot
65/// bound its drain at all (the drain's size is the seed-prefix population,
66/// unknowable without a stats sketch). This value exists to SEAT those
67/// ops, not to predict their row counts.
68///
69/// The magnitude is 2× the broadcast boundary, derived from the three
70/// comparisons the stamp feeds (battery-verified on the bellendena-sparql-1m
71/// store; a stamp one above the boundary itself lost two of the three):
72/// - CONSTRUCTION PLACEMENT (`join_text_scan`): "smaller arm drives" seats
73///   the op by this stamp against the inner plan's estimate. The stamp must
74///   exceed the inner's estimate so the op takes the PROBE (right) arm and
75///   the keyed regime engages. At the boundary it barely won the driver
76///   seat against broadcast-class inners (~28k on the battery store) and
77///   drained unconditionally.
78/// - THE seating-cost model: a driver `CustomNode` prices `sweep_cost()` ≈ twice
79///   its row estimate. At 2× the boundary the op-as-driver sweep prices
80///   4× the boundary, which loses to scan-as-driver + keyed probe for
81///   broadcast-class inner plans, so no later pass swaps the op back into
82///   the driver seat (a stamp AT the boundary priced the sweep at 2× the
83///   boundary, BEATING the scan-driver seat, and the executor drained).
84/// - THE RUNTIME ROAD CHOICE: with the op probe-side, `take_direct_road`
85///   compares `pushed × unit` against `stamp + min(pushed, produced) ×
86///   unit` from the ACTUAL pushed counts — direct wins for pushed below
87///   2× this value (~4× the broadcast boundary), so no drain runs; beyond
88///   it the semi-join road drains once and prunes, which is the win that
89///   keeps selective super-seed patterns (huge pushed set, tiny seed
90///   population) worth having. The drain's true (unbounded) size remains
91///   the accepted unknown until the seed-prefix population sketch prices
92///   it.
93///
94/// Pricing such a drain as a tiny fraction of the vocabulary (the original
95/// code) lost all three: the op won the driver seat in every plan and the
96/// executor drained the whole match up front on fat-prefix patterns — a
97/// measured 2–2.6× regression over the plugin-off plan at 1M scale. The
98/// exact residual decides the rows on every road; a fat-prefix super-seed
99/// pattern still pays the arm's join machinery (measured +10–30% over the
100/// plugin-off plan) — the seed-prefix sketch is the follow-up that prices
101/// the arm out of exactly those plans.
102const UNPRICED_DRAIN_SEAT_ESTIMATE: u64 = PUSHDOWN_TERMS_LIMIT * 2;
103
104/// Text plugin planner hook, parameterized by the plugin config (the
105/// fingerprint rides every rewrite decision).
106#[derive(Debug, Clone)]
107pub struct TextPlannerPlugin {
108    config: TextPluginConfig,
109}
110
111impl TextPlannerPlugin {
112    /// Build from the validated plugin config.
113    pub fn new(config: TextPluginConfig) -> Self {
114        Self { config }
115    }
116
117    /// Trusted = an epoch is stamped AND the partition's fingerprint matches
118    /// this plugin's config, STRICTLY: an empty partition fingerprint means
119    /// "no usable Describe state", not "anything matches" — trusting it
120    /// would accept documents built by an unknown analyzer and seed length.
121    fn trusted(&self, ctx: &QueryContext) -> bool {
122        ctx.text_index_epoch().is_some()
123            && ctx.text_index_fingerprint() == self.config.fingerprint()
124    }
125
126    /// The seed length the READER must assume. The partition seeds from its
127    /// stored config, so the request pattern is sent whole and the
128    /// partition truncates; this value only prices estimates.
129    fn seed_chars(&self) -> usize {
130        self.config.seed_chars
131    }
132}
133
134impl PlannerPlugin for TextPlannerPlugin {
135    fn rewrite(&self, node: &mut PlanNode, ctx: &QueryContext) -> Result<(), ComputeError> {
136        // Fresh track per query root: sibling scans stamp the applied graph
137        // scope of their branch as the descent visits them (see ScopeTrack).
138        let mut scope = ScopeTrack::default();
139        self.rewrite_scoped(node, ctx, &mut scope)
140    }
141
142    /// The conjuncts this plugin can turn into a `text_scan` candidate
143    /// producer. Evaluating a producer twice is never worthwhile: the
144    /// subject form joins the candidate literals back through the hexastore,
145    /// so a duplicate means re-scanning the predicate's literal domain, and
146    /// the literal/string-function forms drain the index again.
147    ///
148    /// Only the shapes the rewrites can actually seed are marked — a variable
149    /// haystack and a ground needle/pattern (`parse_var_and_pattern`,
150    /// `parse_anchored_regex`). The plan-level gates (index trust, the
151    /// predicate allowlist) are not visible here, so a marked conjunct can
152    /// still decline the rewrite and answer as a plain filter; a conjunct that
153    /// can never seed at all keeps the optimizer's own pushdown instead.
154    fn pins_through_optimizer(&self, expression: &Expression) -> bool {
155        match expression {
156            Expression::FunctionCall(Function::Custom(iri), _) => iri.as_str() == TEXT_QUERY_IRI,
157            Expression::FunctionCall(Function::StrStarts | Function::StrEnds, args) => {
158                parse_var_and_pattern(args).is_some_and(|(_, pattern)| !pattern.is_empty())
159            }
160            Expression::FunctionCall(Function::Regex, args) => parse_anchored_regex(args).is_some(),
161            _ => false,
162        }
163    }
164
165    /// `text:query` needs its variable kept: both modes join the candidate set
166    /// back to it, and a fully ground call has no recognisable form (the
167    /// lowering would substitute the literal/IRI into the first argument). The
168    /// string functions are left on the default: grounded, they are exact
169    /// per-row predicates, and a rewrite would only add a candidate drain for a
170    /// single key.
171    fn keeps_variable_when_ground(&self, expression: &Expression) -> bool {
172        matches!(
173            expression,
174            Expression::FunctionCall(Function::Custom(iri), _) if iri.as_str() == TEXT_QUERY_IRI
175        )
176    }
177}
178
179/// Graph-scope tracking threaded through the walk: which graphs the branch
180/// being rewritten may read, and whether it sits inside a `GRAPH ?g`
181/// subtree.
182///
183/// A lowered scan's own fields are ground truth for its plan position, so
184/// every sibling scan stamps the track as the descent visits it, and a
185/// subject-mode rewrite copies that stamp instead of re-deriving the dataset
186/// window (which knows nothing about `GRAPH` blocks). Boundaries restore the
187/// outer stamp so a scope never crosses into the wrong branch.
188#[derive(Default)]
189struct ScopeTrack {
190    /// Every DISTINCT applied scope stamped by sibling scans in this
191    /// branch, in walk order. Subject mode consults the set to pick the
192    /// FILTER's graph window (`resolve_subject_scopes`): a sibling in the
193    /// dataset default window wins, a single surviving window is used
194    /// as-is, and no pattern at all leaves the graph unbound. Branch
195    /// boundaries: `Join` children SHARE the track (both are elements of
196    /// the same enclosing group); `Union` arms and `LeftJoin` bodies are
197    /// independent group patterns and start stamp-free (stamps never cross
198    /// the boundary in either direction — a leaked stamp would resolve
199    /// against a sibling arm's graphs, and subject mode has no residual to
200    /// refine the extra rows away); `JoinGraphVar` and `SubSelect` take and
201    /// restore the whole track.
202    applied_scopes: Vec<waratah_compute::AppliedGraph>,
203    /// True inside a `GRAPH ?g` subtree: with no sibling scan to stamp from,
204    /// the scope is unguessable and a subject-mode rewrite must fail the
205    /// plan rather than answer from the wrong graphs. Isolated children
206    /// (union arms, OPTIONAL bodies) inherit the flag so an arm inside a
207    /// `GRAPH ?g` block with no scans of its own still fails instead of
208    /// answering from the dataset window.
209    in_graph_scope: bool,
210}
211
212impl TextPlannerPlugin {
213    /// The walk proper. `scope` carries the branch's applied graph scope:
214    /// stamped by sibling scans, saved/restored at `GRAPH ?g` / subselect
215    /// boundaries, consulted by subject-mode rewrites.
216    fn rewrite_scoped(
217        &self,
218        node: &mut PlanNode,
219        ctx: &QueryContext,
220        scope: &mut ScopeTrack,
221    ) -> Result<(), ComputeError> {
222        match node {
223            PlanNode::Filter {
224                inner,
225                early,
226                residual,
227                exists,
228                ..
229            } => {
230                // Depth-first: inner rewrites land first.
231                self.rewrite_scoped(inner, ctx, scope)?;
232                for clause in exists.iter_mut() {
233                    self.rewrite_scoped(&mut clause.body, ctx, scope)?;
234                }
235                let Some(residual_expr) = residual else {
236                    return Ok(());
237                };
238                let conjuncts = waratah_compute::flatten_and(residual_expr);
239                // The branch's own bindings, captured before any rewrite
240                // changes the subtree: a searched variable the branch never
241                // binds makes the whole filter unsatisfiable (see the Terms
242                // arm).
243                let inner_variables = inner.variables();
244                let mut unsatisfiable = false;
245                let mut remaining: Vec<Expression> = Vec::new();
246                let mut rewritten: Option<PlanNode> = None;
247                for conjunct in conjuncts {
248                    match self.match_conjunct(&conjunct, inner, ctx)? {
249                        TextMatch::None => remaining.push(conjunct),
250                        TextMatch::Terms {
251                            request,
252                            variable,
253                            strip,
254                        } => {
255                            if !inner_variables.contains(&variable) {
256                                // SPARQL: a FILTER expression that errors on
257                                // a solution removes that solution, and
258                                // text:query on a variable the branch never
259                                // binds errors on EVERY solution — the whole
260                                // filter answers empty. Joining the
261                                // candidate op on a join key the inner side
262                                // does not carry would instead die at
263                                // runtime (join key arity 0 vs 1).
264                                unsatisfiable = true;
265                                break;
266                            }
267                            // The candidate producer: a childless text_scan
268                            // joined on the variable.
269                            let join = self.join_text_scan(
270                                rewritten.take().unwrap_or_else(|| (**inner).clone()),
271                                request,
272                                variable,
273                                ctx,
274                            );
275                            rewritten = Some(join);
276                            if !strip {
277                                // Candidate injection only: the exact SPARQL
278                                // evaluator keeps deciding the row.
279                                remaining.push(conjunct);
280                            }
281                        }
282                        TextMatch::Subject {
283                            request,
284                            variable,
285                            predicates,
286                        } => {
287                            // Semi-join shape: one `text_subjects` op
288                            // resolves the subjects in the FILTER's group
289                            // window, then joins the inner plan on the
290                            // subject variable. The conjunct is stripped.
291                            // The window is resolved once, before the op is
292                            // minted (`resolve_subject_scopes`).
293                            let inner = rewritten.take().unwrap_or_else(|| (**inner).clone());
294                            let window = resolve_subject_scopes(scope, ctx)?;
295                            let join = self.join_subject_scan(
296                                inner,
297                                request,
298                                variable,
299                                &predicates,
300                                &window,
301                                ctx,
302                            )?;
303                            rewritten = Some(join);
304                        }
305                    }
306                }
307                if unsatisfiable {
308                    // The empty table: zero rows over the branch's own
309                    // columns (the established lowering idiom for a
310                    // provably-empty subtree). Everything above — joins,
311                    // projection, modifiers — propagates zero rows, which
312                    // is exactly the SPARQL answer.
313                    *node = PlanNode::Values(waratah_compute::ValuesOp {
314                        variables: inner_variables,
315                        rows: Vec::new(),
316                        strings: Vec::new(),
317                        blobs: Vec::new(),
318                    });
319                    return Ok(());
320                }
321                // Re-&& the untouched conjuncts; drop the Filter node
322                // entirely when nothing remains.
323                *residual = waratah_compute::and_fold(remaining);
324                // THE BELT (unconditional, before the node swap so the
325                // expression borrows end): a text:query the walk did not
326                // rewrite must fail the plan, never evaluate. The rewriter
327                // consumes only BARE top-level conjuncts; a call nested
328                // inside `||`, `!`, `IF`, or `COALESCE` survives here, and
329                // its per-row evaluation goes through the custom function's
330                // error backstop — a FILTER error DROPS THE ROW, so a
331                // trusted index would silently answer zero rows (the
332                // forbidden trusted-but-empty state). `early` is
333                // belt-scanned too: text:query classifies AlwaysResolve and
334                // should never land there, but the belt does not trust the
335                // classifier.
336                for expression in [early.as_ref(), residual.as_ref()].into_iter().flatten() {
337                    ensure_no_surviving_text_query(expression)?;
338                }
339                if let Some(join) = rewritten {
340                    if residual.is_none() && early.is_none() && exists.is_empty() {
341                        *node = join;
342                    } else {
343                        **inner = join;
344                    }
345                }
346                Ok(())
347            }
348            // text:query used as a graph-pattern PREDICATE lowers to a scan
349            // with the Jena IRI in its predicate slot — a plan-time error,
350            // not an empty scan.
351            PlanNode::Scan(scan) if is_text_query_predicate(scan) => {
352                Err(ComputeError::UnsupportedSparql(
353                    "text:query is a FILTER function, not a graph pattern; write \
354                     FILTER text:query(?lit, \"terms\") instead"
355                        .to_owned(),
356                ))
357            }
358            // Every other node: recurse through children where present. The
359            // descent list mirrors the geo planner (`waratah_geo/src/plan.rs`
360            // — every node a lowered FILTER can hide under: BIND, LIMIT /
361            // OFFSET, DISTINCT, ORDER BY, GROUP BY, `GRAPH ?g`) plus
362            // `SubSelect.inner`, which geo skips: geo's exact residual
363            // fallback makes a missed filter merely slow, while text:query's
364            // backstop would make it a WRONG answer — so the descent must be
365            // exhaustive, and the belt below catches whatever shape a future
366            // lowering adds.
367            PlanNode::Join { left, right, .. } => {
368                // Both children are elements of the SAME enclosing group
369                // pattern (`A . B`), so a sibling scan's stamp applies to a
370                // filter in the other child (invariant C — the candidates
371                // see exactly the graphs the surrounding BGP sees, which is
372                // what the mixed-scope group pins). The shared track is the
373                // mechanism; the boundaries below are where sharing stops.
374                self.rewrite_scoped(left, ctx, scope)?;
375                self.rewrite_scoped(right, ctx, scope)
376            }
377            PlanNode::Union { left, right } => {
378                // UNION arms are independent group patterns: a solution
379                // comes from ONE arm, so an arm's rewrite resolves only ITS
380                // OWN scans' scopes. A shared track would leak a sibling
381                // arm's stamp into this arm's resolve — a window scoped to
382                // the other arm's graphs, and subject mode has no residual
383                // to refine the extra rows away (a subject matching the text
384                // in the other arm's graph but not this arm's answers with
385                // this arm's non-matching binding). The leak also flows
386                // outward: a
387                // filter beside the union (same enclosing group) must not
388                // inherit an arm's stamps — the arm's GRAPH block scopes
389                // only the arm. Each arm starts stamp-free but KEEPS the
390                // enclosing in_graph_scope flag (an arm inside a GRAPH ?g
391                // block with no scans of its own must still fail the plan,
392                // not answer from the dataset window), and stamps collected
393                // inside an arm die with the arm's track.
394                let mut left_scope = ScopeTrack {
395                    applied_scopes: Vec::new(),
396                    in_graph_scope: scope.in_graph_scope,
397                };
398                self.rewrite_scoped(left, ctx, &mut left_scope)?;
399                let mut right_scope = ScopeTrack {
400                    applied_scopes: Vec::new(),
401                    in_graph_scope: scope.in_graph_scope,
402                };
403                self.rewrite_scoped(right, ctx, &mut right_scope)?;
404                Ok(())
405            }
406            PlanNode::LeftJoin {
407                left,
408                right,
409                early_filter,
410                residual_filter,
411                ..
412            } => {
413                // The OPTIONAL's own condition is a row-decision site: an
414                // unrewritten text:query there evaluates through the error
415                // backstop and silently drops outer rows. v1 does not rewrite
416                // inside a join condition, so the belt fails the plan — with
417                // the OPTIONAL-specific message, since a body filter can be
418                // hoisted here while written as its own FILTER.
419                for expression in [early_filter, residual_filter].into_iter().flatten() {
420                    ensure_no_surviving_text_query_in_optional(expression)?;
421                }
422                self.rewrite_scoped(left, ctx, scope)?;
423                // The OPTIONAL body is its own group pattern (same
424                // reasoning as the union arms): stamps do not cross the
425                // boundary in either direction, and the enclosing
426                // in_graph_scope flag carries (an OPTIONAL inside a GRAPH
427                // block stays ?g-scoped).
428                let mut body_scope = ScopeTrack {
429                    applied_scopes: Vec::new(),
430                    in_graph_scope: scope.in_graph_scope,
431                };
432                self.rewrite_scoped(right, ctx, &mut body_scope)?;
433                Ok(())
434            }
435            PlanNode::CustomNode(op) => {
436                for child in &mut op.children {
437                    self.rewrite_scoped(child, ctx, scope)?;
438                }
439                Ok(())
440            }
441            PlanNode::Extend {
442                expression, inner, ..
443            } => {
444                // The belt covers BIND too: a surviving text:query inside a
445                // BIND would reach the row-evaluation backstop (an unbound
446                // BIND variable, a silently-empty answer) instead of the
447                // plan error the trust contract promises.
448                ensure_no_surviving_text_query(expression)?;
449                self.rewrite_scoped(inner, ctx, scope)
450            }
451            PlanNode::Sort { keys, inner } => {
452                // ORDER BY expressions are row decisions as well — a
453                // surviving text:query there evaluates per row through the
454                // backstop.
455                for key in keys {
456                    ensure_no_surviving_text_query(&key.expression)?;
457                }
458                self.rewrite_scoped(inner, ctx, scope)
459            }
460            PlanNode::Group {
461                aggregates, inner, ..
462            } => {
463                // GROUP BY keys are plain variables; the aggregate
464                // arguments are the only expressions a text:query could
465                // hide in. HAVING is a Filter above the Group and is
466                // belted there.
467                for (_, aggregate) in aggregates {
468                    if let spargebra::algebra::AggregateExpression::FunctionCall { expr, .. } =
469                        aggregate
470                    {
471                        ensure_no_surviving_text_query(expr)?;
472                    }
473                }
474                self.rewrite_scoped(inner, ctx, scope)
475            }
476            PlanNode::Slice { inner, .. } | PlanNode::Distinct { inner, .. } => {
477                self.rewrite_scoped(inner, ctx, scope)
478            }
479            PlanNode::JoinGraphVar { inner, .. } => {
480                // Scope boundary: the inner scans see the variable graph, not
481                // the outer scope. Inner scans re-stamp the track; the outer
482                // stamp is restored on exit so it never crosses the boundary.
483                let outer = std::mem::take(scope);
484                scope.in_graph_scope = true;
485                let result = self.rewrite_scoped(inner, ctx, scope);
486                *scope = outer;
487                result
488            }
489            PlanNode::SubSelect(sub) => {
490                // Scope boundary: a subselect lowers its own patterns at
491                // dataset scope, so its scans re-stamp from scratch. The
492                // outer stamp is restored on exit.
493                let outer = std::mem::take(scope);
494                let result = self.rewrite_scoped(&mut sub.inner, ctx, scope);
495                *scope = outer;
496                result
497            }
498            // True leaves: no inner plan, so nothing can hide here. The
499            // shapes mirror the geo planner's leaf list exactly.
500            PlanNode::Scan(scan) => {
501                // Sibling ground truth: a lowered scan carries exactly the
502                // applied scope its position sees. Subject mode picks the
503                // FILTER's window from the distinct stamps in the branch —
504                // see ScopeTrack and `resolve_subject_scopes`. Duplicates
505                // from multiple scans in the same window collapse here, by
506                // a conservative comparison (never-equal-when-different;
507                // see same_scope).
508                let stamp = scan.applied_graph();
509                if !scope
510                    .applied_scopes
511                    .iter()
512                    .any(|known| same_scope(known, &stamp))
513                {
514                    scope.applied_scopes.push(stamp);
515                }
516                Ok(())
517            }
518            PlanNode::Path(_)
519            | PlanNode::Unit
520            | PlanNode::Values(_)
521            | PlanNode::NamedGraphs { .. }
522            | PlanNode::NamedGraphExists { .. }
523            | PlanNode::DomainCounts { .. }
524            | PlanNode::HeadCounts { .. }
525            | PlanNode::PatternCount { .. } => Ok(()),
526        }
527    }
528}
529
530/// The graph window a subject-mode rewrite inherits at its FILTER.
531///
532/// The subject form implicitly adds the triple `?s <pred> ?lit`. That triple
533/// belongs at the FILTER's own group level, so it takes the graph context of
534/// a triple/path pattern the FILTER applies to at that level (a sibling BGP
535/// or path). The window is chosen from what the lowered plan still shows:
536///
537/// - A sibling whose applied graph IS the dataset's default window wins,
538///   even when a `GRAPH` block is also a sibling. A mixed group
539///   (`GRAPH <g1> { … }` beside a bare pattern) therefore resolves in the
540///   default graph: the bare pattern is the sibling the FILTER joins at its
541///   level, and the named-graph pattern is a different window the filter
542///   does not claim.
543/// - With no default sibling, exactly one surviving window is used as-is.
544///   This covers a filter inside `GRAPH <g1>` / `GRAPH ?g` (the sibling
545///   pattern's window) and a filter beside a single GRAPH block.
546/// - No sibling pattern at all: the implicit triple has no graph context to
547///   inherit, so the graph is left unbound (any graph).
548/// - Several distinct non-default windows and no default: the plugin cannot
549///   choose one, so the graph is left unbound.
550///
551/// Lowering ERASES a fixed `GRAPH <g1>` boundary (the graph lands on the
552/// scans), and a `GRAPH ?g` boundary node exists only when the variable is
553/// also used inside the block. A filter written outside such a block is
554/// therefore indistinguishable from one written inside it; both keep the
555/// block's window. That blindness is deliberate: recovering the exact
556/// position would mean stamping graph context onto every FILTER node.
557fn resolve_subject_scopes(
558    scope: &ScopeTrack,
559    ctx: &QueryContext,
560) -> Result<waratah_compute::AppliedGraph, ComputeError> {
561    let default_window = waratah_compute::applied_default_graph(ctx.dataset());
562    if let Some(sibling) = scope
563        .applied_scopes
564        .iter()
565        .find(|sibling| same_scope(sibling, &default_window))
566    {
567        return Ok(sibling.clone());
568    }
569    if scope.applied_scopes.is_empty() {
570        if scope.in_graph_scope {
571            return Err(ComputeError::UnsupportedSparql(
572                "subject-mode text:query inside GRAPH requires a triple pattern in the \
573                 same graph group (the resolve must inherit the group's graph scope)"
574                    .to_owned(),
575            ));
576        }
577        return Ok(any_graph_window());
578    }
579    if scope.applied_scopes.len() == 1 {
580        return Ok(scope.applied_scopes[0].clone());
581    }
582    Ok(any_graph_window())
583}
584
585/// `graph_name: None` with no filter: every graph, the unnamed graph included.
586fn any_graph_window() -> waratah_compute::AppliedGraph {
587    waratah_compute::AppliedGraph {
588        graph_name: None,
589        graph: None,
590        graph_filter: None,
591        merge_default_graph: false,
592    }
593}
594
595/// Whether two sibling stamps are the same window for the subject resolve.
596///
597/// CONSERVATIVE by design: the comparison must never say equal for two
598/// different windows (a wrong collapse drops subjects), but may say
599/// different for two identical ones (duplicate resolve ops, folded by the
600/// union's Distinct). Ground graph names compare by encoded bytes, graph
601/// variables by name, and filters by allocation identity — the lowering
602/// clones ONE filter allocation per window, so pointer identity is the
603/// practical equality (`GraphFilter::same_allocation`).
604fn same_scope(a: &waratah_compute::AppliedGraph, b: &waratah_compute::AppliedGraph) -> bool {
605    match (&a.graph_name, &b.graph_name) {
606        (Some(x), Some(y)) => {
607            if waratah_storage::encode_term_bytes(x) != waratah_storage::encode_term_bytes(y) {
608                return false;
609            }
610        }
611        (None, None) => {}
612        _ => return false,
613    }
614    if a.graph != b.graph {
615        return false;
616    }
617    if a.merge_default_graph != b.merge_default_graph {
618        return false;
619    }
620    match (&a.graph_filter, &b.graph_filter) {
621        (None, None) => true,
622        (Some(x), Some(y)) => x.same_allocation(y),
623        _ => false,
624    }
625}
626
627/// The belt: fail the plan when a `text:query` call survives the walk inside
628/// any row-decision expression.
629///
630/// The rewriter only consumes BARE top-level `&&` conjuncts. A call nested
631/// inside `||`, `!`, `IF`, or `COALESCE` (or an OPTIONAL's condition) is
632/// never rewritten; it evaluates per-row through the custom function's error
633/// backstop, and a FILTER error DROPS THE ROW — so a TRUSTED index would
634/// silently answer zero rows for every row: the forbidden trusted-but-empty
635/// state. `text:query` has no exact per-row fallback, so the only honest
636/// answer to an unsupported shape is a plan error.
637fn ensure_no_surviving_text_query(expression: &Expression) -> Result<(), ComputeError> {
638    if expression_references_text_query(expression) {
639        return Err(ComputeError::UnsupportedSparql(
640            "text:query is only supported as a top-level FILTER conjunct (ANDed with \
641             the other conditions); it cannot be nested inside ||, !, IF, COALESCE, \
642             or an OPTIONAL's condition. Restructure the query so the text:query \
643             call is its own FILTER"
644                .to_owned(),
645        ));
646    }
647    Ok(())
648}
649
650/// The belt for the OPTIONAL's join-condition slots. The lowering can move
651/// an OPTIONAL body's filter into the `LeftJoin` condition (shape-dependent
652/// on the surrounding pattern), so a text:query written as its own FILTER
653/// inside the body lands here — the generic nesting-list message would read
654/// as if the user had written the call inside `||`. This message names the
655/// actual situation and the way out.
656fn ensure_no_surviving_text_query_in_optional(expression: &Expression) -> Result<(), ComputeError> {
657    if expression_references_text_query(expression) {
658        return Err(ComputeError::UnsupportedSparql(
659            "text:query cannot answer inside an OPTIONAL: this query lowered the \
660             body's filter into the OPTIONAL's join condition, where the injected \
661             candidate scan would decide whether outer rows survive. Move the \
662             pattern and its text:query FILTER out of the OPTIONAL (a plain group \
663             pattern), or run the OPTIONAL without the text filter"
664                .to_owned(),
665        ));
666    }
667    Ok(())
668}
669
670/// Whether any `text:query` call appears anywhere in `expression`.
671fn expression_references_text_query(expression: &Expression) -> bool {
672    match expression {
673        Expression::FunctionCall(spargebra::algebra::Function::Custom(iri), args) => {
674            iri.as_str() == TEXT_QUERY_IRI || args.iter().any(expression_references_text_query)
675        }
676        Expression::Or(l, r)
677        | Expression::And(l, r)
678        | Expression::Equal(l, r)
679        | Expression::SameTerm(l, r)
680        | Expression::Greater(l, r)
681        | Expression::GreaterOrEqual(l, r)
682        | Expression::Less(l, r)
683        | Expression::LessOrEqual(l, r)
684        | Expression::Add(l, r)
685        | Expression::Subtract(l, r)
686        | Expression::Multiply(l, r)
687        | Expression::Divide(l, r) => {
688            expression_references_text_query(l) || expression_references_text_query(r)
689        }
690        Expression::In(first, rest) => {
691            expression_references_text_query(first)
692                || rest.iter().any(expression_references_text_query)
693        }
694        Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) | Expression::Not(inner) => {
695            expression_references_text_query(inner)
696        }
697        Expression::If(condition, then, otherwise) => {
698            expression_references_text_query(condition)
699                || expression_references_text_query(then)
700                || expression_references_text_query(otherwise)
701        }
702        Expression::Coalesce(arms) | Expression::FunctionCall(_, arms) => {
703            arms.iter().any(expression_references_text_query)
704        }
705        // Ground leaves: no nested expression to recurse into.
706        Expression::NamedNode(_)
707        | Expression::Literal(_)
708        | Expression::Variable(_)
709        | Expression::Bound(_) => false,
710        // A nested `EXISTS` never reaches a lowered plan expression:
711        // `split_filter`'s capability classification rejects `Exists` as
712        // `Unsupported` (`waratah_compute/src/expr/capability.rs`), so the
713        // query errors before plans exist. Top-level EXISTS lowers to
714        // `Filter.exists` clauses instead, which the walk descends into.
715        Expression::Exists(_) => false,
716    }
717}
718
719/// What one residual conjunct matched to.
720enum TextMatch {
721    /// Not a text conjunct (or not one this plugin rewrites).
722    None,
723    /// Candidate injection over one variable: the op emits the matching
724    /// terms. `strip` distinguishes text:query (strip — the op is the
725    /// complete answer) from the string functions (keep — the conjunct is
726    /// the exact evaluator, the op only prunes).
727    Terms {
728        request: TextSearchRequest,
729        variable: waratah_storage::Variable,
730        strip: bool,
731    },
732    /// Subject-mode text:query: distinct subjects for the predicate set.
733    Subject {
734        request: TextSearchRequest,
735        variable: waratah_storage::Variable,
736        predicates: Vec<oxrdf::NamedNode>,
737    },
738}
739
740fn is_text_query_predicate(scan: &waratah_compute::ScanOp) -> bool {
741    // The plan stores encoded terms only (hash, not IRI), so the check
742    // compares the encoded IRI hash of `text:query`.
743    scan.pattern.predicate.as_ref().is_some_and(|term| {
744        matches!(term, EncodedTerm::NamedNode { .. })
745            && *term
746                == EncodedTerm::NamedNode {
747                    iri_id: waratah_storage::StrHash::new(TEXT_QUERY_IRI),
748                }
749    })
750}
751
752impl TextPlannerPlugin {
753    /// Match one residual conjunct.
754    fn match_conjunct(
755        &self,
756        conjunct: &Expression,
757        inner: &PlanNode,
758        ctx: &QueryContext,
759    ) -> Result<TextMatch, ComputeError> {
760        match conjunct {
761            Expression::FunctionCall(Function::Custom(iri), args)
762                if iri.as_str() == TEXT_QUERY_IRI =>
763            {
764                self.match_text_query(args, inner, ctx)
765            }
766            Expression::FunctionCall(Function::StrStarts, args) => {
767                self.match_string_function(args, inner, ctx, TextCandidateMode::Prefix)
768            }
769            Expression::FunctionCall(Function::StrEnds, args) => {
770                self.match_string_function(args, inner, ctx, TextCandidateMode::Suffix)
771            }
772            Expression::FunctionCall(Function::Regex, args) => {
773                self.match_anchored_regex(args, inner, ctx)
774            }
775            _ => Ok(TextMatch::None),
776        }
777    }
778
779    /// Parse the `text:query` argument forms.
780    ///
781    /// Dispatch is forced by what is indexed: only literal objects carry
782    /// searchable text, so a 2-argument call can only be the literal form,
783    /// and a NamedNode second argument can only be the predicate of the
784    /// triple whose object must match. No role inference.
785    fn match_text_query(
786        &self,
787        args: &[Expression],
788        inner: &PlanNode,
789        ctx: &QueryContext,
790    ) -> Result<TextMatch, ComputeError> {
791        // The trust gate FIRST: a text:query conjunct under an untrusted or
792        // mismatched index is a query failure, never a silent fallback.
793        if !self.trusted(ctx) {
794            return Err(ComputeError::UnsupportedSparql(untrusted_message()));
795        }
796        match args {
797            // Literal mode: text:query(?lit, "q" [, "lang:xx"]) — the query
798            // is a plain literal, so a NamedNode second argument can only be
799            // the subject form's predicate.
800            [Expression::Variable(variable), rest @ ..]
801                if matches!(rest.first(), Some(Expression::Literal(_))) && rest.len() <= 2 =>
802            {
803                let (query, language) = parse_query_and_lang(rest, 0)?;
804                self.check_literal_variable(inner, variable)?;
805                Ok(TextMatch::Terms {
806                    request: TextSearchRequest {
807                        mode: TextCandidateMode::Fts,
808                        query,
809                        language,
810                        limit: 0,
811                    },
812                    variable: variable.clone(),
813                    strip: true,
814                })
815            }
816            // Subject mode: text:query(?s, <field>+ , "q" [, "lang:xx"])
817            [Expression::Variable(variable), rest @ ..]
818                if rest.len() >= 2 && matches!(rest.first(), Some(Expression::NamedNode(_))) =>
819            {
820                let split = rest
821                    .iter()
822                    .position(|arg| matches!(arg, Expression::Literal(_)))
823                    .ok_or_else(|| {
824                        ComputeError::UnsupportedSparql(
825                            "text:query subject mode needs a query string after the predicate IRIs"
826                                .to_owned(),
827                        )
828                    })?;
829                if split == 0 {
830                    return Err(ComputeError::UnsupportedSparql(
831                        "text:query subject mode needs at least one predicate IRI".to_owned(),
832                    ));
833                }
834                let mut predicates = Vec::with_capacity(split);
835                for arg in &rest[..split] {
836                    match arg {
837                        Expression::NamedNode(node) => predicates.push(node.clone()),
838                        _ => {
839                            return Err(ComputeError::UnsupportedSparql(
840                                "text:query subject mode takes predicate IRIs, then the query string"
841                                    .to_owned(),
842                            ));
843                        }
844                    }
845                }
846                let (query, language) = parse_query_and_lang(&rest[split..], split)?;
847                // The index holds literals from the allowlisted predicates
848                // only. Naming a predicate it does not index would silently
849                // return nothing for that predicate, so it is a plan error
850                // (the same refusal as an unknown search field).
851                if let Some(allow) = self.config.predicate_allowlist() {
852                    for predicate in &predicates {
853                        if !allow.contains(&waratah_storage::StrHash::new(predicate.as_str())) {
854                            return Err(ComputeError::UnsupportedSparql(format!(
855                                "text:query names {predicate}, which is not an indexed text \
856                                 predicate; add it to `predicates` in text.toml (and rebuild \
857                                 the index), or remove it from the query"
858                            )));
859                        }
860                    }
861                }
862                self.check_subject_variable(inner, variable)?;
863                Ok(TextMatch::Subject {
864                    request: TextSearchRequest {
865                        mode: TextCandidateMode::Fts,
866                        query,
867                        language,
868                        limit: 0,
869                    },
870                    variable: variable.clone(),
871                    predicates,
872                })
873            }
874            _ => Err(ComputeError::UnsupportedSparql(format!(
875                "unsupported text:query form; expected \
876                 text:query(?lit, \"query\" [, \"lang:xx\"]) or \
877                 text:query(?s, <field>+, \"query\" [, \"lang:xx\"]), got {args:?}"
878            ))),
879        }
880    }
881
882    /// Literal-mode contradiction check: a variable provably bound ONLY in
883    /// subject slots of the inner plan cannot hold literals — the Jena
884    /// reflex `?s text:query "word"` wants subject mode.
885    fn check_literal_variable(
886        &self,
887        inner: &PlanNode,
888        variable: &waratah_storage::Variable,
889    ) -> Result<(), ComputeError> {
890        let slots = variable_slots(inner, variable);
891        if !slots.is_empty() && slots.iter().all(|slot| *slot == SlotKind::Subject) {
892            return Err(ComputeError::UnsupportedSparql(format!(
893                "text:query bound {variable}, which only appears in subject position; \
894                 the subject form is text:query({variable}, <predicate>, \"query\")"
895            )));
896        }
897        Ok(())
898    }
899
900    /// Subject-mode contradiction check: a variable provably bound ONLY in
901    /// object slots cannot hold subjects — the literal form is wanted.
902    fn check_subject_variable(
903        &self,
904        inner: &PlanNode,
905        variable: &waratah_storage::Variable,
906    ) -> Result<(), ComputeError> {
907        let slots = variable_slots(inner, variable);
908        if !slots.is_empty() && slots.iter().all(|slot| *slot == SlotKind::Object) {
909            return Err(ComputeError::UnsupportedSparql(format!(
910                "text:query bound {variable}, which only appears in object position; \
911                 the literal form is text:query({variable}, \"query\")"
912            )));
913        }
914        Ok(())
915    }
916
917    /// `STRSTARTS(?l, p)` / `STRENDS(?l, p)` with a ground, non-empty,
918    /// string pattern. Candidate injection only: the conjunct stays in the
919    /// residual and the exact SPARQL evaluator answers. UNTRUSTED → no
920    /// rewrite (the degradation contract: the exact residual answers, slow
921    /// but correct).
922    fn match_string_function(
923        &self,
924        args: &[Expression],
925        inner: &PlanNode,
926        ctx: &QueryContext,
927        mode: TextCandidateMode,
928    ) -> Result<TextMatch, ComputeError> {
929        if !self.trusted(ctx) {
930            return Ok(TextMatch::None);
931        }
932        let Some((variable, pattern)) = parse_var_and_pattern(args) else {
933            return Ok(TextMatch::None);
934        };
935        // The index holds literals from the allowlisted predicates only; a
936        // candidate injection is a sound superset only when the branch proves
937        // coverage for every value the variable can take. Otherwise the exact
938        // residual answers.
939        if !self.text_index_applies(inner, &variable) {
940            return Ok(TextMatch::None);
941        }
942        let Some(request) = seed_request(mode, &pattern, self.seed_chars()) else {
943            return Ok(TextMatch::None);
944        };
945        Ok(TextMatch::Terms {
946            request,
947            variable,
948            strip: false,
949        })
950    }
951
952    /// Whether the text index covers every value the variable can take.
953    ///
954    /// The index holds literals under the allowlisted predicates only, and the
955    /// string functions' rewrite is candidate injection with the exact
956    /// conjunct kept in the residual. That is a sound superset only when both
957    /// hold:
958    ///
959    /// - at least one scan binds the variable in an OBJECT slot with an
960    ///   allowed constant predicate (the coverage evidence), and
961    /// - nothing else in the branch can hand it a value the index does not own
962    ///   (`VALUES`, `BIND`, a property-path object, or a scan under another
963    ///   predicate).
964    ///
965    /// The first condition is what keeps the test from being vacuous. A
966    /// variable bound only by `VALUES` or `BIND` has no scan proving coverage,
967    /// and the injected candidate set is only a superset over the indexed
968    /// universe: a value from outside it survives only if the executor happens
969    /// to test it locally, a road detail the plan must not rely on.
970    ///
971    /// Subject/predicate slots are neither evidence nor a disqualifier on
972    /// their own: the string functions are type errors on non-literals, so
973    /// rows bound only there are removed by the exact evaluator anyway. They
974    /// still cannot stand in for an object-slot site — a `UNION` arm or a
975    /// `BIND` can hand the variable a literal from outside the index.
976    fn text_index_applies(&self, node: &PlanNode, variable: &waratah_storage::Variable) -> bool {
977        let allow = self.config.predicate_allowlist();
978        let mut applies = true;
979        let mut object_slot_evidence = false;
980        walk_text_index_applies(
981            node,
982            variable,
983            allow.as_ref(),
984            &mut applies,
985            &mut object_slot_evidence,
986        );
987        applies && object_slot_evidence
988    }
989
990    /// `REGEX(?l, "^lit")` / `REGEX(?l, ".*lit$")` — exactly an anchored
991    /// literal (optionally `.*` before it), no flags, no alternation.
992    /// Anything else stays unindexed.
993    fn match_anchored_regex(
994        &self,
995        args: &[Expression],
996        inner: &PlanNode,
997        ctx: &QueryContext,
998    ) -> Result<TextMatch, ComputeError> {
999        if !self.trusted(ctx) {
1000            return Ok(TextMatch::None);
1001        }
1002        let Some((variable, mode, anchored)) = parse_anchored_regex(args) else {
1003            return Ok(TextMatch::None);
1004        };
1005        if !self.text_index_applies(inner, variable) {
1006            return Ok(TextMatch::None);
1007        }
1008        let Some(request) = seed_request(mode, anchored, self.seed_chars()) else {
1009            return Ok(TextMatch::None);
1010        };
1011        Ok(TextMatch::Terms {
1012            request,
1013            variable: variable.clone(),
1014            strip: false,
1015        })
1016    }
1017
1018    /// Join a childless `text_scan` op with the inner plan on `variable`,
1019    /// placing the smaller arm on the left (same seating discipline as the
1020    /// geo rewrite).
1021    fn join_text_scan(
1022        &self,
1023        inner: PlanNode,
1024        request: TextSearchRequest,
1025        variable: waratah_storage::Variable,
1026        ctx: &QueryContext,
1027    ) -> PlanNode {
1028        let inner_rows = inner.produced_row_count_estimate();
1029        let scan_rows = candidate_estimate(
1030            &request,
1031            ctx.text_seed_sketch().map(|sketch| sketch.as_ref()),
1032            ctx.text_index_epoch(),
1033        );
1034        // FTS has no local per-key test (the answer is membership in the
1035        // index's match set); prefix/suffix keep their exact seed test.
1036        let fts = request.mode == TextCandidateMode::Fts;
1037        let mut scan = waratah_compute::CustomOp {
1038            plugin_id: crate::PLUGIN_ID,
1039            op_id: TEXT_SCAN_OP_ID,
1040            payload: PluginPayloadBox::new(TextScanPayload {
1041                request,
1042                analyzer: self.config.analyzer.clone(),
1043                seed_chars: self.config.seed_chars,
1044            }),
1045            children: Vec::new(),
1046            variables: vec![variable.clone()],
1047            produced_row_count_estimate: scan_rows,
1048            cost: Some(waratah_compute::CustomOpCost {
1049                drain_rows: scan_rows,
1050                // One hash lookup per pushed key on the probe road.
1051                per_key_unit: 1,
1052                inline_point_unit: 1,
1053                direct_probe: !fts,
1054                // The drain is driven by the seed/query; a filter page
1055                // examines the whole candidate list, not just the survivors.
1056                probe_keyed_columns: 0,
1057                probe_filter_unit: 1,
1058                // The candidate-drain memo can pay the drain once per
1059                // window when the list fits its admission limit.
1060                probe_memo_entry_rows: waratah_compute::text_probe_memo_entry_terms(),
1061            }),
1062            pinned: Vec::new(),
1063        };
1064        let (left, right) = if scan_rows <= inner_rows {
1065            (PlanNode::CustomNode(scan), inner)
1066        } else {
1067            // Ground-unique driver: pin the driver's single term into the
1068            // op — the executor answers with a membership test, no drain.
1069            if let Some(term) = ground_unique_probe_term(&inner, &variable) {
1070                scan.pinned.push((variable.clone(), term));
1071                scan.produced_row_count_estimate = 1;
1072            }
1073            (inner, PlanNode::CustomNode(scan))
1074        };
1075        let strategy = if left.produced_row_count_estimate() <= PUSHDOWN_TERMS_LIMIT {
1076            JoinStrategy::Broadcast
1077        } else {
1078            JoinStrategy::Hash
1079        };
1080        let rhs_hostable_keys =
1081            std::sync::Arc::from(waratah_compute::subtree_hostable_variables(&right));
1082        PlanNode::Join {
1083            left: Box::new(left),
1084            right: Box::new(right),
1085            hash_keys: vec![variable],
1086            probe_key_domains: Vec::new(),
1087            probe_key_overlap_milli: Vec::new(),
1088            rhs_hostable_keys,
1089            meta: waratah_compute::JoinMeta {
1090                star_arms: None,
1091                strategy,
1092                semi_gate: None,
1093                produced_row_count_estimate: inner_rows,
1094                own_push_removed_row_count_estimate: inner_rows,
1095            },
1096        }
1097    }
1098
1099    /// Subject mode: one partition-side `text_subjects` op, joined with the
1100    /// inner plan on the subject variable.
1101    ///
1102    /// The op replaces the compute-side arm joins this rewrite used to mint
1103    /// (`Union_i (scan_i ⋈ candidates_i)`, one arm per predicate): the O
1104    /// partition searches the index for the whole predicate set and walks
1105    /// the matched literals' OPSG rows itself, returning DISTINCT
1106    /// `(subject, graph)` rows. The graph window is the one
1107    /// [`resolve_subject_scopes`] picks for the FILTER — the sibling BGP's
1108    /// context, the dataset default when a bare sibling is present, or
1109    /// unbound when no pattern supplies one.
1110    ///
1111    /// A graph column is emitted when that window binds a graph variable
1112    /// (the filter sits in a `GRAPH ?g` block): one value per solution, and
1113    /// the join's shared column enforces "the match is in the solution's
1114    /// graph". `GRAPH ?s { … }` with `text:query(?s, …)` on the same
1115    /// variable is the one shape where the graph variable IS the subject:
1116    /// one variable takes one value, so the matched row's subject and graph
1117    /// must be the same term. The op then emits the subject alone and the
1118    /// partition keeps only subject-equals-graph rows
1119    /// (`subject_equals_graph`); declaring the variable twice would let the
1120    /// join keep a row whose matching literal lives in a different graph
1121    /// than the solution's.
1122    fn join_subject_scan(
1123        &self,
1124        inner: PlanNode,
1125        request: TextSearchRequest,
1126        variable: waratah_storage::Variable,
1127        predicates: &[oxrdf::NamedNode],
1128        scope: &waratah_compute::AppliedGraph,
1129        ctx: &QueryContext,
1130    ) -> Result<PlanNode, ComputeError> {
1131        // The predicate set is the request's, not an arm dimension: encoding
1132        // it once here is the only translation between the SPARQL predicate
1133        // IRIs and the index's stored bytes.
1134        let encoded_predicates: Vec<EncodedTerm> =
1135            predicates.iter().map(EncodedTerm::from).collect();
1136        // The sketch prices the op like any text drain; the estimate sizes
1137        // the join's broadcast frame and is advisory.
1138        // The subject form is FTS today: price its output (and its drain
1139        // work — the resolve visits roughly one row per output) from the
1140        // length placeholder, scaled by the observed fan-out. A seed-mode
1141        // subject request would use the sketch path instead.
1142        let subject_rows = match request.mode {
1143            TextCandidateMode::Fts => {
1144                fts_placeholder_literals(&request.query).saturating_mul(TEXT_SUBJECT_FANOUT)
1145            }
1146            _ => candidate_estimate(
1147                &request,
1148                ctx.text_seed_sketch().map(|sketch| sketch.as_ref()),
1149                ctx.text_index_epoch(),
1150            ),
1151        };
1152        let subject_equals_graph = scope.graph.as_ref() == Some(&variable);
1153        // A graph column is emitted only for a variable window that is not
1154        // the subject itself; a ground window (dataset, `GRAPH <g1>`) needs
1155        // no column, and `GRAPH ?s` is the one-column subject-equals-graph
1156        // shape.
1157        let emit_graph = scope.graph.as_ref().is_some_and(|graph| graph != &variable);
1158        let mut variables = vec![variable.clone()];
1159        if emit_graph {
1160            variables.push(
1161                scope
1162                    .graph
1163                    .clone()
1164                    .expect("emit_graph implies a graph variable"),
1165            );
1166        }
1167        let (graph_filter_terms, graph_filter_allow) =
1168            waratah_compute::GraphFilter::to_wire(scope.graph_filter.as_ref());
1169        let payload = TextSubjectsPayload {
1170            request: TextSubjectRequest {
1171                mode: request.mode,
1172                query: request.query.clone(),
1173                language: request.language.clone(),
1174                limit: request.limit,
1175                predicates: encoded_predicates,
1176                graph_name: scope.graph_name.clone(),
1177                graph_filter_terms: graph_filter_terms.to_vec(),
1178                graph_filter_allow,
1179                merge_default_graph: scope.merge_default_graph,
1180                return_graph: emit_graph,
1181                subject_equals_graph,
1182            },
1183        };
1184        let subjects = PlanNode::CustomNode(waratah_compute::CustomOp {
1185            plugin_id: crate::PLUGIN_ID,
1186            op_id: TEXT_SUBJECTS_OP_ID,
1187            payload: PluginPayloadBox::new(payload),
1188            children: Vec::new(),
1189            variables,
1190            produced_row_count_estimate: subject_rows,
1191            cost: Some(waratah_compute::CustomOpCost {
1192                drain_rows: subject_rows,
1193                per_key_unit: 1,
1194                inline_point_unit: 1,
1195                // The resolve is driven by the query and the predicate
1196                // set; a pushed subject key cannot be decided locally.
1197                direct_probe: false,
1198                // The DRAIN is key-independent (the resolve runs the
1199                // same for any pushed list); the mask names the column
1200                // the per-page filter can answer by key. The memoized
1201                // window is sorted and interned by SUBJECT, so a pushed
1202                // subject is a dictionary peek + binary search, while a
1203                // pushed GRAPH still scans the window (bit 1 clear).
1204                // One mask prices both pushes; the cost model passes the
1205                // column the runtime actually pushes.
1206                probe_keyed_columns: 0b1,
1207                probe_filter_unit: 1,
1208                // The subject memo admits INTERNED IDS: one per subject
1209                // id, a second per graph id. The planner and the runtime
1210                // share one budget accessor, so a window the cost model prices
1211                // as one drain is exactly a window the memo admits.
1212                probe_memo_entry_rows: waratah_compute::text_subject_memo_entry_rows(emit_graph),
1213            }),
1214            pinned: Vec::new(),
1215        });
1216        let inner_rows = inner.produced_row_count_estimate();
1217        // The driver is the LEFT arm (`subjects`): broadcast pushes its key
1218        // list into the inner scans, so its size decides the strategy — same
1219        // rule as `join_text_scan`.
1220        let strategy = if subjects.produced_row_count_estimate() <= PUSHDOWN_TERMS_LIMIT {
1221            JoinStrategy::Broadcast
1222        } else {
1223            JoinStrategy::Hash
1224        };
1225        let rhs_hostable_keys =
1226            std::sync::Arc::from(waratah_compute::subtree_hostable_variables(&inner));
1227        Ok(PlanNode::Join {
1228            left: Box::new(subjects),
1229            right: Box::new(inner),
1230            hash_keys: vec![variable],
1231            probe_key_domains: Vec::new(),
1232            probe_key_overlap_milli: Vec::new(),
1233            rhs_hostable_keys,
1234            meta: waratah_compute::JoinMeta {
1235                star_arms: None,
1236                strategy,
1237                semi_gate: None,
1238                produced_row_count_estimate: inner_rows,
1239                own_push_removed_row_count_estimate: inner_rows,
1240            },
1241        })
1242    }
1243}
1244
1245/// The untrusted / mismatched-index failure for `text:query`.
1246fn untrusted_message() -> String {
1247    "text:query requires a trusted text index (no build epoch is stamped, or the partition's \
1248     index was built by different settings); run `waratah text rebuild-index`, or start the \
1249     cluster with the text plugin enabled so the startup build stamps the epoch"
1250        .to_owned()
1251}
1252
1253/// Parse the trailing `"query"` (and optional `"lang:xx"`) arguments.
1254fn parse_query_and_lang(
1255    args: &[Expression],
1256    offset: usize,
1257) -> Result<(String, Option<String>), ComputeError> {
1258    // The query argument must be a PLAIN string: a simple literal or an
1259    // explicit xsd:string, never a language-tagged string and never another
1260    // datatype. The old guard's second arm accepted ANY non-language
1261    // literal, so `text:query(?l, 42)` silently searched the string "42".
1262    let query = match args.first() {
1263        Some(Expression::Literal(literal))
1264            if literal.language().is_none()
1265                && literal.datatype().as_str() == "http://www.w3.org/2001/XMLSchema#string" =>
1266        {
1267            literal.value().to_owned()
1268        }
1269        _ => {
1270            return Err(ComputeError::UnsupportedSparql(format!(
1271                "text:query argument {} must be a plain string literal (the query)",
1272                offset + 1
1273            )));
1274        }
1275    };
1276    if query.trim().is_empty() {
1277        return Err(ComputeError::UnsupportedSparql(
1278            "text:query with an empty query is not answerable (every string matches); \
1279             write a real query"
1280                .to_owned(),
1281        ));
1282    }
1283    let language = match args.get(1) {
1284        None => None,
1285        // The "lang:xx" argument is likewise a plain string only.
1286        Some(Expression::Literal(literal))
1287            if literal.language().is_none()
1288                && literal.datatype().as_str() == "http://www.w3.org/2001/XMLSchema#string" =>
1289        {
1290            let value = literal.value();
1291            let Some(tag) = value.strip_prefix("lang:") else {
1292                return Err(ComputeError::UnsupportedSparql(format!(
1293                    "text:query trailing argument must be \"lang:xx\", got {value:?}"
1294                )));
1295            };
1296            Some(tag.to_owned())
1297        }
1298        Some(other) => {
1299            return Err(ComputeError::UnsupportedSparql(format!(
1300                "text:query trailing argument must be \"lang:xx\", got {other:?}"
1301            )));
1302        }
1303    };
1304    if args.len() > 2 {
1305        return Err(ComputeError::UnsupportedSparql(
1306            "text:query takes at most a query and a \"lang:xx\" argument after the variable / predicates"
1307                .to_owned(),
1308        ));
1309    }
1310    Ok((query, language))
1311}
1312
1313/// `STRSTARTS(?l, p)` / `STRENDS(?l, p)`: variable + ground string pattern.
1314fn parse_var_and_pattern(args: &[Expression]) -> Option<(waratah_storage::Variable, String)> {
1315    // The slice pattern matches EXACTLY two arguments; anything else (one
1316    // arg, three, a non-variable first, a non-literal second) is `None`.
1317    let [Expression::Variable(variable), Expression::Literal(pattern)] = args else {
1318        return None;
1319    };
1320    if pattern.language().is_some() {
1321        return None;
1322    }
1323    Some((variable.clone(), pattern.value().to_owned()))
1324}
1325
1326/// The rewritable shape of an anchored `REGEX(?v, "^body")` /
1327/// `REGEX(?v, ".*body$")`: the variable, the mode, and the seedable body.
1328///
1329/// A three-argument call (flags) is not rewritten — only `"i"` would be
1330/// meaningful, and case-insensitive prefix/suffix is a different candidate
1331/// set. The body must be a plain character sequence: a metacharacter is read
1332/// as syntax by the regex engine but would be sent to the index as literal
1333/// text, excluding values the regex matches.
1334fn parse_anchored_regex(
1335    args: &[Expression],
1336) -> Option<(&waratah_storage::Variable, TextCandidateMode, &str)> {
1337    let [Expression::Variable(variable), Expression::Literal(pattern)] = args else {
1338        return None;
1339    };
1340    let raw = pattern.value();
1341    let (mode, body) = if let Some(body) = raw.strip_prefix('^') {
1342        (TextCandidateMode::Prefix, body)
1343    } else if let Some(body) = raw
1344        .strip_prefix(".*")
1345        .and_then(|rest| rest.strip_suffix('$'))
1346    {
1347        (TextCandidateMode::Suffix, body)
1348    } else {
1349        return None;
1350    };
1351    if body.is_empty() || body.chars().any(|c| REGEX_METACHARACTERS.contains(&c)) {
1352        return None;
1353    }
1354    Some((variable, mode, body))
1355}
1356
1357/// The candidate request for a prefix / suffix pattern, or `None` when the
1358/// pattern is empty (it matches every string — rewriting would be a useless
1359/// full drain) or not a plain string.
1360///
1361/// The pattern is sent WHOLE: the partition seeds it to its own stored
1362/// `seed_chars`, so the requester's idea of the length can never disagree
1363/// with the index's.
1364fn seed_request(
1365    mode: TextCandidateMode,
1366    pattern: &str,
1367    _seed_chars: usize,
1368) -> Option<TextSearchRequest> {
1369    if pattern.is_empty() {
1370        return None;
1371    }
1372    Some(match mode {
1373        TextCandidateMode::Prefix => TextSearchRequest::prefix(pattern.to_owned()),
1374        TextCandidateMode::Suffix => TextSearchRequest::suffix(pattern.to_owned()),
1375        TextCandidateMode::Fts => return None,
1376    })
1377}
1378
1379/// Advisory candidate estimate for join costing: FTS prices the cost-estimate value
1380/// (see `UNPRICED_DRAIN_SEAT_ESTIMATE` — a placement number, not a row
1381/// prediction);
1382/// a seed matches a fraction that SHRINKS with every leading (or trailing)
1383/// character — the same direction the partition's FST walk gets cheaper.
1384/// Bounded below at 1 (an empty candidate set is a legitimate answer) and
1385/// above at the whole-vocabulary placeholder.
1386/// Advisor placeholder for an FTS query's matching-LITERAL count, from the
1387/// query string's length.
1388///
1389/// The seed sketch prices seed modes only; an FTS token match has no
1390/// planner-local frequency source (the token-frequency sketch is a separate,
1391/// later feature). Until then this length band is the placeholder, calibrated
1392/// on `s32-synth-full` (44.8M-put store, v2 text index):
1393///
1394/// | query chars | observed matching literals | band |
1395/// |---|---|---|
1396/// | ≤ 4 | 182k (`zinc`) … 700k (`data`) | 8 × `PUSHDOWN_TERMS_LIMIT` (196,608) |
1397/// | 5–7 | `report` 643k, `geology`/`deposit` ~150k | 4 × `PUSHDOWN_TERMS_LIMIT` (98,304) |
1398/// | ≥ 8 | `cache-creek` 38k subjects | `PUSHDOWN_TERMS_LIMIT / 4` (6,144) |
1399///
1400/// The band sizes the subject op's OUTPUT estimate (`subject_rows`, scaled by
1401/// [`TEXT_SUBJECT_FANOUT`]): the enclosing join's cardinality, and the
1402/// driver-side sweep price. It is deliberately NOT a memo-admission input any
1403/// more — the compact subject memo admits 16.7M ids (8.4M graph-carrying
1404/// rows), which is an order of magnitude above every band, so the cost model prices
1405/// the resolve once per window for any query length. That also means the
1406/// probe page is priced by its pushed keys (the memoized window answers each
1407/// with a membership lookup), not by this number. A real token sketch replaces
1408/// the band; the constants are the tuning surface until then.
1409///
1410/// The placeholder is deliberately coarse: a frequent 6-letter token like
1411/// `report` sits ~6× above the 5–7 band's literal count while `geology` and
1412/// `deposit` sit near it, because length cannot separate a common word from a
1413/// rare one. The resulting subject-count miss only shifts the op's output /
1414/// join-cardinality estimate and the driver-side sweep price; it no longer
1415/// decides memo admission, and it does not price a probe page.
1416fn fts_placeholder_literals(query: &str) -> u64 {
1417    match query.trim().chars().count() {
1418        0..=4 => PUSHDOWN_TERMS_LIMIT * 8,
1419        5..=7 => PUSHDOWN_TERMS_LIMIT * 4,
1420        _ => PUSHDOWN_TERMS_LIMIT / 4,
1421    }
1422}
1423
1424/// Observed matching-subject rows per matching literal on the calibration
1425/// corpus (`report`: 2,036,197 subjects from 642,958 literals ≈ 3.2). The
1426/// subject resolve's output and its drain work both scale with this.
1427const TEXT_SUBJECT_FANOUT: u64 = 4;
1428
1429/// Advisory candidate estimate for join costing. FTS prices the cost-estimate value
1430/// (see `UNPRICED_DRAIN_SEAT_ESTIMATE` — a placement number, not a row
1431/// prediction); a seed match prices a fraction that SHRINKS with every
1432/// leading (or trailing) character — the same direction the partition's FST
1433/// walk gets cheaper — until the seed length, where the index's
1434/// discrimination ends. Bounded below at 1 (an empty candidate set is a
1435/// legitimate answer).
1436///
1437/// `seed_chars` is the index's stored seed length: the caller's config, not
1438/// the request's, so the estimate can never disagree with the index about
1439/// where pattern discrimination ends.
1440fn candidate_estimate(
1441    request: &TextSearchRequest,
1442    sketch: Option<&waratah_stats::TextSeedSketch>,
1443    index_epoch: Option<u64>,
1444) -> u64 {
1445    match request.mode {
1446        TextCandidateMode::Fts => UNPRICED_DRAIN_SEAT_ESTIMATE,
1447        TextCandidateMode::Prefix | TextCandidateMode::Suffix => {
1448            // THE SKETCHED PATH: the seed-population sketch prices every
1449            // seed mode from the index's own numbers — in-band patterns
1450            // exactly where their path is stored, everything else as the
1451            // nearest stored ancestor's upper bound, and a SUPER-SEED
1452            // pattern (longer than the stored seed) as its seed-prefix
1453            // population, which is precisely that drain's size. The
1454            // estimate feeds three consumers (the seating bid against the
1455            // sibling scan's key domain, `take_direct_road`'s break-even,
1456            // and the fetch-once whole-read verdict); a true number fixes
1457            // all three — the measured failure modes of the flat stamp
1458            // (4.6× fat-prefix loss at 10M, selective winners denied the
1459            // driver seat) are exactly the cells a constant cannot win.
1460            if let Some(rows) = match (sketch, request.mode) {
1461                (Some(sketch), _) if sketch.prices_at(index_epoch) => match request.mode {
1462                    TextCandidateMode::Prefix => {
1463                        sketch.estimate_prefix(&request.query, index_epoch)
1464                    }
1465                    TextCandidateMode::Suffix => {
1466                        sketch.estimate_suffix(&request.query, index_epoch)
1467                    }
1468                    TextCandidateMode::Fts => None,
1469                },
1470                _ => None,
1471            } {
1472                return rows.max(1);
1473            }
1474            // THE UNPRICED FALLBACK (no sketch, undecodable, or epoch
1475            // mismatch): the flat cost stamp. Length-based decay was
1476            // measured and removed — a per-length number cannot see the
1477            // pattern's fatness (the win/loss discriminator is the
1478            // candidate-to-scan ratio, which pattern length does not
1479            // encode), and below the seating-cost-model flip it seated fat-prefix
1480            // ops as the driver — the keyless unconditional drain — at a
1481            // measured 2–2.6× regression. Above the flip the seating-cost model
1482            // seats the scan as driver, the op answers keyed from the
1483            // pushed values (direct road, drain-memo served), fat prefixes
1484            // land at +19–34%, and selective prefixes keep their win
1485            // (pruning happens in TermId space before string resolution).
1486            // FTS token statistics are a different sketch family and stay
1487            // unpriced indefinitely under current plans.
1488            UNPRICED_DRAIN_SEAT_ESTIMATE
1489        }
1490    }
1491}
1492
1493/// Which BGP slot(s) bind `variable` in the inner plan's scans.
1494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1495enum SlotKind {
1496    Subject,
1497    Predicate,
1498    Object,
1499}
1500
1501fn variable_slots(node: &PlanNode, variable: &waratah_storage::Variable) -> Vec<SlotKind> {
1502    let mut out = Vec::new();
1503    collect_variable_slots(node, variable, &mut out);
1504    out
1505}
1506
1507fn collect_variable_slots(
1508    node: &PlanNode,
1509    variable: &waratah_storage::Variable,
1510    out: &mut Vec<SlotKind>,
1511) {
1512    match node {
1513        PlanNode::Scan(scan) => {
1514            if scan.subject.as_ref() == Some(variable) {
1515                out.push(SlotKind::Subject);
1516            }
1517            if scan.predicate.as_ref() == Some(variable) {
1518                out.push(SlotKind::Predicate);
1519            }
1520            if scan.object.as_ref() == Some(variable) {
1521                out.push(SlotKind::Object);
1522            }
1523        }
1524        PlanNode::Path(op) => {
1525            // A path endpoint binds the slot it sits in, exactly like a
1526            // scan slot: the subject slot binds hop subjects (never
1527            // literals in RDF), the object slot binds whatever the final
1528            // hop's object position holds (IRIs or literals — the engine
1529            // cannot know the kind at plan time, so Object is the sound
1530            // classification, the same as a scan object slot).
1531            if op.subject.as_ref() == Some(variable) {
1532                out.push(SlotKind::Subject);
1533            }
1534            if op.object.as_ref() == Some(variable) {
1535                out.push(SlotKind::Object);
1536            }
1537        }
1538        PlanNode::Values(values) => {
1539            // A VALUES row GROUND-binds the variable: the term kinds in the
1540            // variable's column are slot evidence, exactly like a scan slot.
1541            // A literal bound by VALUES can never be a subject (the
1542            // subject-mode contradiction fires), and an IRI bound by VALUES
1543            // can never be a searched literal (the literal-mode contradiction
1544            // fires) — the same answers the scan-slot evidence produces.
1545            let Some(column) = values.variables.iter().position(|v| v == variable) else {
1546                return;
1547            };
1548            for row in &values.rows {
1549                if let Some(term) = row.get(column).and_then(|term| term.as_ref()) {
1550                    out.push(ground_term_slot(term));
1551                }
1552            }
1553        }
1554        PlanNode::Extend {
1555            inner,
1556            variable: bound,
1557            expression,
1558            ..
1559        } => {
1560            // A BIND of a GROUND expression to the variable is slot evidence
1561            // too (`BIND("x" AS ?s)` binds a literal; `BIND(<iri> AS ?s)` an
1562            // IRI). A computed or copied expression binds nothing provable —
1563            // no evidence, like an unvisited node.
1564            if bound == variable {
1565                match expression {
1566                    Expression::Literal(_) => out.push(SlotKind::Object),
1567                    Expression::NamedNode(_) => out.push(SlotKind::Subject),
1568                    _ => {}
1569                }
1570            }
1571            collect_variable_slots(inner, variable, out);
1572        }
1573        PlanNode::Join { left, right, .. }
1574        | PlanNode::LeftJoin { left, right, .. }
1575        | PlanNode::Union { left, right } => {
1576            collect_variable_slots(left, variable, out);
1577            collect_variable_slots(right, variable, out);
1578        }
1579        PlanNode::CustomNode(op) => {
1580            for child in &op.children {
1581                collect_variable_slots(child, variable, out);
1582            }
1583        }
1584        PlanNode::Filter { inner, .. }
1585        | PlanNode::Slice { inner, .. }
1586        | PlanNode::Distinct { inner, .. }
1587        | PlanNode::Sort { inner, .. }
1588        | PlanNode::Group { inner, .. }
1589        | PlanNode::JoinGraphVar { inner, .. } => collect_variable_slots(inner, variable, out),
1590        PlanNode::SubSelect(sub) => collect_variable_slots(&sub.inner, variable, out),
1591        _ => {}
1592    }
1593}
1594
1595/// The [`TextPlannerPlugin::text_index_applies`] walk: recurse the plan and
1596/// fail on any binding of the variable the predicate allowlist cannot prove
1597/// covered, setting `object_slot_evidence` for the scan that proves it.
1598/// Mirrors [`collect_variable_slots`]'s traversal so a node kind added there
1599/// cannot silently escape this gate.
1600fn walk_text_index_applies(
1601    node: &PlanNode,
1602    variable: &waratah_storage::Variable,
1603    allow: Option<&std::collections::HashSet<waratah_storage::StrHash>>,
1604    applies: &mut bool,
1605    object_slot_evidence: &mut bool,
1606) {
1607    if !*applies {
1608        return;
1609    }
1610    match node {
1611        PlanNode::Scan(scan) => {
1612            if scan.object.as_ref() != Some(variable) {
1613                return;
1614            }
1615            // A variable (or non-named) predicate has no fixed allowlist
1616            // answer; the index cannot be proven to cover its values.
1617            let Some(EncodedTerm::NamedNode { iri_id }) = &scan.pattern.predicate else {
1618                *applies = false;
1619                return;
1620            };
1621            if allow.is_some_and(|allow| !allow.contains(iri_id)) {
1622                *applies = false;
1623                return;
1624            }
1625            // An allowed constant predicate under an object slot is the only
1626            // proof of coverage this walk accepts.
1627            *object_slot_evidence = true;
1628        }
1629        PlanNode::Path(op) => {
1630            if op.object.as_ref() == Some(variable) {
1631                *applies = false;
1632            }
1633        }
1634        // A VALUES column binds the variable to constants no scan constrains:
1635        // the candidate join would drop any the index does not hold. This also
1636        // catches a `UNION` whose other arm is an allowed object-slot scan —
1637        // the table's values still reach the filter unindexed.
1638        PlanNode::Values(values) if values.variables.contains(variable) => {
1639            *applies = false;
1640        }
1641        // `BIND` mints the variable's value from an expression, ground or
1642        // computed; nothing proves the index holds it.
1643        PlanNode::Extend {
1644            variable: bound, ..
1645        } if bound == variable => {
1646            *applies = false;
1647        }
1648        PlanNode::Join { left, right, .. }
1649        | PlanNode::LeftJoin { left, right, .. }
1650        | PlanNode::Union { left, right } => {
1651            walk_text_index_applies(left, variable, allow, applies, object_slot_evidence);
1652            walk_text_index_applies(right, variable, allow, applies, object_slot_evidence);
1653        }
1654        PlanNode::CustomNode(op) => {
1655            for child in &op.children {
1656                walk_text_index_applies(child, variable, allow, applies, object_slot_evidence);
1657            }
1658        }
1659        PlanNode::Filter { inner, .. }
1660        | PlanNode::Slice { inner, .. }
1661        | PlanNode::Distinct { inner, .. }
1662        | PlanNode::Sort { inner, .. }
1663        | PlanNode::Group { inner, .. }
1664        | PlanNode::JoinGraphVar { inner, .. }
1665        | PlanNode::Extend { inner, .. } => {
1666            walk_text_index_applies(inner, variable, allow, applies, object_slot_evidence);
1667        }
1668        PlanNode::SubSelect(sub) => {
1669            walk_text_index_applies(&sub.inner, variable, allow, applies, object_slot_evidence);
1670        }
1671        _ => {}
1672    }
1673}
1674
1675/// The slot kind a GROUND term's RDF kind proves: an IRI or blank node is
1676/// subject-side material; every literal kind (strings, lang strings, typed,
1677/// numeric, geo) is object-side.
1678fn ground_term_slot(term: &EncodedTerm) -> SlotKind {
1679    match term {
1680        EncodedTerm::NamedNode { .. }
1681        | EncodedTerm::NumericalBlankNode { .. }
1682        | EncodedTerm::SmallBlankNode(_)
1683        | EncodedTerm::BigBlankNode { .. } => SlotKind::Subject,
1684        // All remaining kinds are literals (object-side). `DefaultGraph` and
1685        // the intern placeholder never appear in a VALUES column; the
1686        // classification is unreachable for them either way.
1687        _ => SlotKind::Object,
1688    }
1689}
1690
1691#[cfg(test)]
1692mod tests {
1693    use super::*;
1694
1695    #[test]
1696    fn candidate_producers_are_pinned_through_the_optimizer() {
1697        let plugin = TextPlannerPlugin::new(TextPluginConfig::default());
1698        let variable =
1699            |name: &str| Expression::Variable(waratah_storage::Variable::new_unchecked(name));
1700        let literal = |value: &str| Expression::Literal(waratah_storage::Literal::from(value));
1701        let function =
1702            |function: Function, args: Vec<Expression>| Expression::FunctionCall(function, args);
1703        let custom = |iri: &str, args: Vec<Expression>| {
1704            Expression::FunctionCall(
1705                Function::Custom(waratah_storage::NamedNode::new_unchecked(iri)),
1706                args,
1707            )
1708        };
1709
1710        // Both text:query modes build a producer.
1711        assert!(plugin.pins_through_optimizer(&custom(TEXT_QUERY_IRI, vec![variable("r")])));
1712
1713        // Only the shapes the rewrites can seed are pinned: a variable
1714        // haystack and a ground needle/pattern.
1715        assert!(plugin.pins_through_optimizer(&function(
1716            Function::StrStarts,
1717            vec![variable("lit"), literal("abc")]
1718        )));
1719        assert!(!plugin.pins_through_optimizer(&function(
1720            Function::StrStarts,
1721            vec![variable("lit"), variable("needle")]
1722        )));
1723        assert!(!plugin.pins_through_optimizer(&function(
1724            Function::StrEnds,
1725            vec![literal("abc"), literal("abc")]
1726        )));
1727        assert!(plugin.pins_through_optimizer(&function(
1728            Function::Regex,
1729            vec![variable("lit"), literal("^abc")]
1730        )));
1731        assert!(!plugin.pins_through_optimizer(&function(
1732            Function::Regex,
1733            vec![variable("lit"), literal("abc")]
1734        )));
1735        assert!(
1736            !plugin.pins_through_optimizer(&function(
1737                Function::Regex,
1738                vec![variable("lit"), literal("^a.c")]
1739            )),
1740            "a metacharacter body is not a seedable prefix"
1741        );
1742        assert!(!plugin.pins_through_optimizer(&function(
1743            Function::Regex,
1744            vec![variable("lit"), literal("^abc"), literal("i")]
1745        )));
1746
1747        assert!(
1748            !plugin.pins_through_optimizer(&custom(
1749                "http://example.org/not-text",
1750                vec![variable("r")]
1751            )),
1752            "an unrelated custom function is not a text candidate producer"
1753        );
1754        assert!(!plugin.pins_through_optimizer(&variable("r")));
1755
1756        // The ground-substitution guard: only text:query needs its variable
1757        // kept. The string functions ground to exact per-row predicates, so a
1758        // rewrite would only add a candidate drain for a single key.
1759        assert!(plugin.keeps_variable_when_ground(&custom(TEXT_QUERY_IRI, vec![variable("r")])));
1760        for kind in [Function::StrStarts, Function::StrEnds, Function::Regex] {
1761            assert!(
1762                !plugin.keeps_variable_when_ground(&function(
1763                    kind,
1764                    vec![variable("lit"), literal("abc")]
1765                )),
1766                "a string function grounds to an exact per-row predicate"
1767            );
1768        }
1769        assert!(!plugin.keeps_variable_when_ground(&custom(
1770            "http://example.org/not-text",
1771            vec![variable("r")]
1772        )));
1773    }
1774
1775    #[test]
1776    fn seed_requests_skip_empty_patterns_and_fts() {
1777        assert!(seed_request(TextCandidateMode::Prefix, "", 16).is_none());
1778        assert!(seed_request(TextCandidateMode::Fts, "abc", 16).is_none());
1779        let request = seed_request(TextCandidateMode::Prefix, "abc", 16).unwrap();
1780        assert_eq!(request.mode, TextCandidateMode::Prefix);
1781        assert_eq!(request.query, "abc");
1782        assert_eq!(request.limit, 0);
1783    }
1784
1785    #[test]
1786    fn anchored_regex_shapes_parse() {
1787        // The parse logic is exercised through the executor-side request
1788        // builder; here only the mode table is pinned.
1789        let prefix = seed_request(TextCandidateMode::Prefix, "abc", 16).unwrap();
1790        let suffix = seed_request(TextCandidateMode::Suffix, "cba", 16).unwrap();
1791        assert_eq!(prefix.mode, TextCandidateMode::Prefix);
1792        assert_eq!(suffix.mode, TextCandidateMode::Suffix);
1793    }
1794
1795    #[test]
1796    fn unpriced_stamp_seats_every_in_band_seed_above_broadcast() {
1797        let fts = TextSearchRequest::fts("word");
1798        // The estimate is a cost-estimate value, not a row prediction: it must price
1799        // above the seating-cost-model flip so the scan wins the driver seat, the
1800        // op answers keyed from pushed values (direct road), and the
1801        // keyless unconditional drain never runs on fat prefixes (see
1802        // UNPRICED_DRAIN_SEAT_ESTIMATE for the derivation and the battery
1803        // evidence).
1804        assert!(candidate_estimate(&fts, None, None) > PUSHDOWN_TERMS_LIMIT);
1805        // EVERY in-band length prices at the same flat cost-estimate value. The
1806        // per-length decay this test used to pin was measured and removed:
1807        // a function of length alone cannot see the pattern's fatness (the
1808        // win/loss discriminator is the candidate-to-scan ratio), and its
1809        // low values seated fat-prefix ops as the keyless drain driver at
1810        // a measured 2–2.6× regression over the plugin-off plan.
1811        for pattern in [
1812            "a",
1813            "ab",
1814            "abc",
1815            "abcd",
1816            "abcde",
1817            "abcdefghij",
1818            "abcdefghijklmnop",
1819        ] {
1820            assert_eq!(
1821                candidate_estimate(&TextSearchRequest::prefix(pattern), None, None),
1822                UNPRICED_DRAIN_SEAT_ESTIMATE,
1823                "in-band prefix {pattern} seats at the flat value"
1824            );
1825            assert_eq!(
1826                candidate_estimate(&TextSearchRequest::suffix(pattern), None, None),
1827                UNPRICED_DRAIN_SEAT_ESTIMATE,
1828                "in-band suffix {pattern} seats at the flat value"
1829            );
1830        }
1831        // The seed bound prices identically in the fallback: past the
1832        // stored seed the drain is the seed-prefix population, and the
1833        // flat stamp is the honest answer a constant can give.
1834        let past_seed = TextSearchRequest::prefix("abcdefghijklmnopq"); // 17 chars
1835        assert_eq!(
1836            candidate_estimate(&past_seed, None, None),
1837            UNPRICED_DRAIN_SEAT_ESTIMATE,
1838            "past the seed the drain is unpriced"
1839        );
1840        assert_eq!(
1841            candidate_estimate(&TextSearchRequest::prefix("abcdefghi"), None, None),
1842            UNPRICED_DRAIN_SEAT_ESTIMATE,
1843            "9 chars is past an 8-char seed"
1844        );
1845    }
1846
1847    #[test]
1848    fn sketched_estimate_prices_from_the_cms() {
1849        use waratah_stats::TextSeedSketch;
1850        const EPOCH: u64 = 1794192803976;
1851        // A collector over the session's measured shapes: a fat family
1852        // (2,000 identifiers × 140 postings each — posting counts, the
1853        // over-count contract) and a tiny selective family.
1854        let mut sketch = TextSeedSketch::collector(16);
1855        for i in 0..2000u64 {
1856            for _ in 0..140 {
1857                sketch.record(&format!("eco-watchdataset1{i:08}"));
1858            }
1859        }
1860        sketch.record("windy");
1861        sketch.epoch = EPOCH;
1862        let epoch = Some(EPOCH);
1863        // Sub-seed selective: "win"'s true population is 1 ("windy"); a
1864        // CMS over this sparse corpus (280k inserts / 19k columns ≈ 15
1865        // expected noise per cell, row-min pulls lower) estimates a small
1866        // upper bound — near-exact, never under.
1867        let win = candidate_estimate(&TextSearchRequest::prefix("win"), Some(&sketch), epoch);
1868        assert!(win >= 1, "never under the true family of 1");
1869        assert!(win <= 60, "near-exact on this corpus, got {win}");
1870        // Super-seed fat: priced from the 8-char prefix's family — the
1871        // whole 280k, a number the flat stamp could never express (this
1872        // is the 4.6×-loss fix at 10M: fat priced as fat).
1873        let fat = candidate_estimate(
1874            &TextSearchRequest::prefix("eco-watchdataset1submission30"),
1875            Some(&sketch),
1876            epoch,
1877        );
1878        assert!(fat >= 2_000 * 140, "never under the family total");
1879        assert!(
1880            fat <= 2_000 * 140 + 600,
1881            "near-exact (noise ≈ 280k/19k ≈ 15k per cell, row-min far below), got {fat}"
1882        );
1883        // Epoch mismatch: the sketch must not price — the stale-sketch
1884        // discipline mirrors the trust gate.
1885        assert_eq!(
1886            candidate_estimate(
1887                &TextSearchRequest::prefix("eco-watchdataset1"),
1888                Some(&sketch),
1889                Some(999),
1890            ),
1891            UNPRICED_DRAIN_SEAT_ESTIMATE,
1892            "a stale sketch never prices"
1893        );
1894        assert_eq!(
1895            candidate_estimate(&TextSearchRequest::prefix("x"), Some(&sketch), None),
1896            UNPRICED_DRAIN_SEAT_ESTIMATE,
1897            "no trusted index epoch, no price"
1898        );
1899        // Suffix pricing reverses into the end direction, which the same
1900        // records populated ("windy" contributes "ydniw"): STRENDS "dy"
1901        // prices ≥ 1.
1902        let suffix = candidate_estimate(&TextSearchRequest::suffix("dy"), Some(&sketch), epoch);
1903        assert!(suffix >= 1, "the end direction carries the same walk");
1904    }
1905
1906    // ---- Plan-level tests over parsed SPARQL (the geo planner's harness).
1907
1908    use waratah_compute::LogicalPlan;
1909    use waratah_storage::SnapshotId;
1910
1911    fn installed() {
1912        crate::install();
1913    }
1914
1915    /// The injected `text_scan` op of a rewritten plan, joined with `inner`
1916    /// (under a surviving Filter for the keep-the-conjunct shapes, and
1917    /// through the wrappers the descent enters: GROUP BY, GRAPH, BIND,
1918    /// DISTINCT, ORDER BY, LIMIT, sub-SELECT).
1919    fn find_text_join(node: &PlanNode) -> Option<&waratah_compute::CustomOp> {
1920        match node {
1921            PlanNode::Filter { inner, .. } => find_text_join(inner),
1922            PlanNode::Join { left, right, .. } => {
1923                find_text_join(left).or_else(|| find_text_join(right))
1924            }
1925            PlanNode::LeftJoin { left, right, .. } => {
1926                find_text_join(left).or_else(|| find_text_join(right))
1927            }
1928            PlanNode::Union { left, right } => {
1929                find_text_join(left).or_else(|| find_text_join(right))
1930            }
1931            PlanNode::Extend { inner, .. }
1932            | PlanNode::Slice { inner, .. }
1933            | PlanNode::Distinct { inner, .. }
1934            | PlanNode::Sort { inner, .. }
1935            | PlanNode::Group { inner, .. }
1936            | PlanNode::JoinGraphVar { inner, .. } => find_text_join(inner),
1937            PlanNode::SubSelect(sub) => find_text_join(&sub.inner),
1938            PlanNode::CustomNode(op) if op.op_id == TEXT_SCAN_OP_ID => Some(op),
1939            _ => None,
1940        }
1941    }
1942
1943    /// The subject-mode resolve op (the partition-side `text_subjects` node).
1944    fn find_subject_op(node: &PlanNode) -> Option<&waratah_compute::CustomOp> {
1945        let mut ops = Vec::new();
1946        subject_ops(node, &mut ops);
1947        ops.into_iter().next()
1948    }
1949
1950    /// Every subject-mode resolve op in the tree, in walk order (one per
1951    /// distinct applied scope).
1952    fn subject_ops<'a>(node: &'a PlanNode, out: &mut Vec<&'a waratah_compute::CustomOp>) {
1953        match node {
1954            PlanNode::CustomNode(op) if op.op_id == TEXT_SUBJECTS_OP_ID => out.push(op),
1955            PlanNode::Filter { inner, .. }
1956            | PlanNode::Extend { inner, .. }
1957            | PlanNode::Slice { inner, .. }
1958            | PlanNode::Distinct { inner, .. }
1959            | PlanNode::Sort { inner, .. }
1960            | PlanNode::Group { inner, .. }
1961            | PlanNode::JoinGraphVar { inner, .. } => subject_ops(inner, out),
1962            PlanNode::Join { left, right, .. }
1963            | PlanNode::LeftJoin { left, right, .. }
1964            | PlanNode::Union { left, right } => {
1965                subject_ops(left, out);
1966                subject_ops(right, out);
1967            }
1968            PlanNode::SubSelect(sub) => subject_ops(&sub.inner, out),
1969            _ => {}
1970        }
1971    }
1972
1973    /// The subject request carried by a `text_subjects` op.
1974    fn subject_request(op: &waratah_compute::CustomOp) -> &waratah_storage::TextSubjectRequest {
1975        &op.payload
1976            .downcast_ref::<TextSubjectsPayload>()
1977            .expect("text_subjects payload")
1978            .request
1979    }
1980
1981    /// Whether any Filter node survives in the tree.
1982    fn find_filter(node: &PlanNode) -> bool {
1983        match node {
1984            PlanNode::Filter { .. } => true,
1985            PlanNode::Join { left, right, .. }
1986            | PlanNode::LeftJoin { left, right, .. }
1987            | PlanNode::Union { left, right } => find_filter(left) || find_filter(right),
1988            PlanNode::CustomNode(op) => op.children.iter().any(find_filter),
1989            _ => false,
1990        }
1991    }
1992
1993    /// The Distinct node the rewrite mints when a branch holds MORE THAN ONE
1994    /// applied scope (a single scope's op already returns distinct rows).
1995    fn find_subject_distinct(node: &PlanNode) -> Option<&PlanNode> {
1996        match node {
1997            PlanNode::Join { left, right, .. } => {
1998                find_subject_distinct(left).or_else(|| find_subject_distinct(right))
1999            }
2000            PlanNode::Distinct { inner, .. } => {
2001                let mut ops = Vec::new();
2002                subject_ops(inner, &mut ops);
2003                (!ops.is_empty()).then_some(node)
2004            }
2005            PlanNode::Filter { inner, .. }
2006            | PlanNode::JoinGraphVar { inner, .. }
2007            | PlanNode::Slice { inner, .. } => find_subject_distinct(inner),
2008            _ => None,
2009        }
2010    }
2011
2012    /// Trusted-index context (the startup Describe payload, stamped).
2013    fn trusted_ctx() -> waratah_compute::QueryContext {
2014        waratah_compute::QueryContext::from_snapshot(SnapshotId::latest()).with_text_index_state(
2015            Some(1),
2016            crate::TextPluginConfig {
2017                enabled: true,
2018                // Match `install()`: the tests index arbitrary `http://ex/`
2019                // predicates, so the allowlist is off (all predicates).
2020                predicates: Vec::new(),
2021                ..crate::TextPluginConfig::default()
2022            }
2023            .fingerprint(),
2024        )
2025    }
2026
2027    fn rewrite_plan(sparql: &str) -> Result<LogicalPlan, ComputeError> {
2028        installed();
2029        // `parse_with_context` runs the planner-plugin rewrites with the
2030        // given context (index epochs ride it — the trust gate sees them).
2031        LogicalPlan::parse_with_context(sparql, &trusted_ctx())
2032    }
2033
2034    const TEXT: &str = "http://jena.apache.org/text#";
2035
2036    #[test]
2037    fn fts_placeholder_bands_all_fit_the_subject_memo() {
2038        // The compact subject memo admits 16.7M subject ids (8.4M with the
2039        // graph column), an order of magnitude above the broadest calibration
2040        // window. The length band therefore no longer decides whether a
2041        // resolve is paid once per window: every band is admissible for both
2042        // row shapes. (The literal-mode candidate memo is a separate, smaller
2043        // budget and is not what this prices.)
2044        let subject_only = waratah_compute::text_subject_memo_entry_rows(false);
2045        let with_graph = waratah_compute::text_subject_memo_entry_rows(true);
2046        for query in [
2047            "zinc",
2048            "data",
2049            "report",
2050            "geology",
2051            "deposit",
2052            "kalgoorlie",
2053            "cache-creek",
2054            "comodoro-rivadavia",
2055        ] {
2056            let subjects = fts_placeholder_literals(query).saturating_mul(TEXT_SUBJECT_FANOUT);
2057            assert!(
2058                subjects <= subject_only,
2059                "{query}: {subjects} subject ids must fit the {subject_only}-id memo"
2060            );
2061            assert!(
2062                subjects <= with_graph,
2063                "{query}: {subjects} rows must fit the {with_graph}-row graph memo"
2064            );
2065        }
2066        // The calibration corpus's real window must also fit: `report`
2067        // resolves 2,036,197 subjects from 642,958 matching literals.
2068        assert!(
2069            2_036_197 <= with_graph,
2070            "the measured report window must be memoizable with its graph column"
2071        );
2072    }
2073
2074    #[test]
2075    fn literal_mode_text_query_strips_the_conjunct_and_joins_the_scan() {
2076        let plan = rewrite_plan(&format!(
2077            "PREFIX text: <{TEXT}>
2078            SELECT ?name WHERE {{
2079                ?x <http://ex/name> ?name .
2080                FILTER(text:query(?name, \"laser printer\"))
2081            }}"
2082        ))
2083        .unwrap();
2084        let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
2085        assert_eq!(op.op_id, TEXT_SCAN_OP_ID);
2086        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
2087        assert_eq!(payload.request.mode, TextCandidateMode::Fts);
2088        assert_eq!(payload.request.query, "laser printer");
2089        assert_eq!(payload.request.language, None);
2090        // The conjunct is STRIPPED: with text:query as the only conjunct the
2091        // Filter node folds away entirely (the join replaces it).
2092        assert!(
2093            !find_filter(&plan.root),
2094            "a fully-stripped text:query leaves no Filter node"
2095        );
2096    }
2097
2098    #[test]
2099    fn literal_mode_with_a_language_restriction_carries_the_tag() {
2100        let plan = rewrite_plan(&format!(
2101            "PREFIX text: <{TEXT}>
2102            SELECT ?name WHERE {{
2103                ?x <http://ex/name> ?name .
2104                FILTER(text:query(?name, \"bonjour\", \"lang:fr\"))
2105            }}"
2106        ))
2107        .unwrap();
2108        let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
2109        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
2110        assert_eq!(payload.request.language.as_deref(), Some("fr"));
2111    }
2112
2113    #[test]
2114    fn subject_mode_joins_the_partition_resolve_on_the_subject() {
2115        let plan = rewrite_plan(&format!(
2116            "PREFIX text: <{TEXT}>
2117            SELECT ?person WHERE {{
2118                ?person <http://ex/livesIn> ?city .
2119                FILTER(text:query(?person, <http://ex/bio>, \"mountain\"))
2120            }}"
2121        ))
2122        .unwrap();
2123        // One scope → one op, no arm union and no Distinct (the resolve
2124        // already returns distinct rows); the op is the join's left side.
2125        let op = find_subject_op(&plan.root).expect("the subject resolve op");
2126        assert_eq!(op.op_id, TEXT_SUBJECTS_OP_ID);
2127        let request = subject_request(op);
2128        assert_eq!(request.mode, TextCandidateMode::Fts);
2129        assert_eq!(request.query, "mountain");
2130        assert_eq!(
2131            request.predicates,
2132            vec![EncodedTerm::from(
2133                &oxrdf::NamedNode::new("http://ex/bio").unwrap()
2134            )],
2135            "the predicate IRI is encoded into the request"
2136        );
2137        assert!(!request.return_graph, "no graph variable is bound");
2138        assert_eq!(
2139            op.variables,
2140            vec![waratah_storage::Variable::new_unchecked("person")]
2141        );
2142        // The conjunct is stripped and the join keys on the subject.
2143        assert!(
2144            !find_filter(&plan.root),
2145            "a fully-stripped text:query leaves no Filter node"
2146        );
2147        assert!(
2148            matches!(&plan.root, PlanNode::Join { hash_keys, .. }
2149                if hash_keys == &vec![waratah_storage::Variable::new_unchecked("person")]),
2150            "the resolve joins the branch on the subject: {:?}",
2151            plan.root
2152        );
2153    }
2154
2155    /// The cost model and the runtime must agree on one admission budget: the
2156    /// subject op's `probe_memo_entry_rows` IS the memo's row limit for its
2157    /// row shape, so a window the cost model prices as a single resolve is exactly
2158    /// a window the memo admits. The probe page is priced by its pushed keys
2159    /// (the memoized window answers each with a dictionary peek + binary
2160    /// search), not by a scan of every resolved row.
2161    #[test]
2162    fn subject_op_prices_its_memo_and_its_keyed_probe() {
2163        let plan = rewrite_plan(
2164            "SELECT ?s WHERE {
2165                ?s <http://ex/bio> ?v .
2166                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2167            }",
2168        )
2169        .unwrap();
2170        let op = find_subject_op(&plan.root).expect("dataset-scope resolve op");
2171        let cost = op.cost.expect("the subject op is stamped");
2172        assert!(
2173            !cost.direct_probe,
2174            "a pushed subject cannot be decided without the resolve"
2175        );
2176        assert_eq!(
2177            cost.probe_keyed_columns, 0b1,
2178            "the subject column is keyed (the memoized window is sorted by it)"
2179        );
2180        assert_eq!(
2181            cost.probe_memo_entry_rows,
2182            waratah_compute::text_subject_memo_entry_rows(false),
2183            "the subject-only shape's admission limit"
2184        );
2185        assert!(
2186            op.probe_drain_amortized(),
2187            "the calibration window fits the subject memo"
2188        );
2189        assert_eq!(
2190            op.probe_page_cost(1_000, Some(0)),
2191            Some((1_000, true)),
2192            "one membership decision per pushed subject, not the whole window"
2193        );
2194
2195        // The graph shape stores two ids per row, so its row budget halves.
2196        let plan = rewrite_plan(
2197            "SELECT ?g ?s WHERE {
2198                GRAPH ?g {
2199                    ?s <http://ex/bio> ?v .
2200                    FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2201                }
2202            }",
2203        )
2204        .unwrap();
2205        let op = find_subject_op(&plan.root).expect("graph-scope resolve op");
2206        let cost = op.cost.expect("the graph-shape op is stamped");
2207        assert_eq!(
2208            cost.probe_keyed_columns, 0b1,
2209            "the graph column is NOT keyed: the window is sorted by subject"
2210        );
2211        assert_eq!(
2212            cost.probe_memo_entry_rows,
2213            waratah_compute::text_subject_memo_entry_rows(true),
2214            "the graph shape's row limit is half the id budget"
2215        );
2216        assert_eq!(
2217            waratah_compute::text_subject_memo_entry_rows(true) * 2,
2218            waratah_compute::text_subject_memo_entry_rows(false),
2219            "two ids per graph row"
2220        );
2221        // A subject push is keyed; a graph push scans the whole window. The
2222        // cost model must price them differently, or an ancestor join keyed on
2223        // the graph would look as cheap as the rewrite's subject join.
2224        assert_eq!(op.probe_page_cost(1_000, Some(0)), Some((1_000, true)));
2225        assert_eq!(
2226            op.probe_page_cost(1_000, Some(1)),
2227            Some((op.produced_row_count_estimate, true)),
2228            "a pushed graph has no index in a subject-sorted window"
2229        );
2230        assert_eq!(
2231            op.probe_page_cost(1_000, None),
2232            Some((op.produced_row_count_estimate, true)),
2233            "an unknown pushed column must price as a scan, never as keyed"
2234        );
2235    }
2236
2237    #[test]
2238    fn two_predicates_are_one_resolve_request() {
2239        let plan = rewrite_plan(&format!(
2240            "PREFIX text: <{TEXT}>
2241            SELECT ?person WHERE {{
2242                ?person <http://ex/livesIn> ?city .
2243                FILTER(text:query(?person, <http://ex/bio>, <http://ex/note>, \"mountain\"))
2244            }}"
2245        ))
2246        .unwrap();
2247        let mut ops = Vec::new();
2248        subject_ops(&plan.root, &mut ops);
2249        assert_eq!(
2250            ops.len(),
2251            1,
2252            "the predicate set is one request, not an arm dimension"
2253        );
2254        assert_eq!(
2255            subject_request(ops[0]).predicates,
2256            vec![
2257                EncodedTerm::from(&oxrdf::NamedNode::new("http://ex/bio").unwrap()),
2258                EncodedTerm::from(&oxrdf::NamedNode::new("http://ex/note").unwrap()),
2259            ],
2260            "both predicate IRIs travel in the one request"
2261        );
2262    }
2263
2264    #[test]
2265    fn strstarts_and_strends_inject_candidates_and_keep_the_conjunct() {
2266        let plan = rewrite_plan(
2267            "SELECT ?name WHERE {
2268                ?x <http://ex/name> ?name .
2269                FILTER(STRSTARTS(?name, \"Bel\"))
2270            }",
2271        )
2272        .unwrap();
2273        let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
2274        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
2275        assert_eq!(payload.request.mode, TextCandidateMode::Prefix);
2276        assert_eq!(payload.request.query, "Bel");
2277        // The conjunct STAYS: the residual decides exactly.
2278        assert!(
2279            format!("{:?}", plan.root).contains("Filter"),
2280            "the Filter node must survive with the exact conjunct"
2281        );
2282    }
2283
2284    #[test]
2285    fn strends_seeds_the_suffix_mode() {
2286        let plan = rewrite_plan(
2287            "SELECT ?name WHERE {
2288                ?x <http://ex/name> ?name .
2289                FILTER(STRENDS(?name, \"lin\"))
2290            }",
2291        )
2292        .unwrap();
2293        let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
2294        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
2295        assert_eq!(payload.request.mode, TextCandidateMode::Suffix);
2296        assert_eq!(payload.request.query, "lin");
2297    }
2298
2299    fn allowlist_config(predicates: &[&str]) -> TextPluginConfig {
2300        TextPluginConfig {
2301            enabled: true,
2302            predicates: predicates
2303                .iter()
2304                .map(|predicate| (*predicate).to_owned())
2305                .collect(),
2306            ..TextPluginConfig::default()
2307        }
2308    }
2309
2310    #[test]
2311    fn text_index_applies_requires_an_allowed_constant_predicate() {
2312        let variable = waratah_storage::Variable::new_unchecked("l");
2313        let plan = LogicalPlan::parse("SELECT ?l WHERE { ?s <http://ex/name> ?l }").unwrap();
2314        assert!(
2315            TextPlannerPlugin::new(allowlist_config(&["http://ex/name"]))
2316                .text_index_applies(&plan.root, &variable)
2317        );
2318        assert!(
2319            !TextPlannerPlugin::new(allowlist_config(&["https://schema.org/name"]))
2320                .text_index_applies(&plan.root, &variable),
2321            "an excluded predicate is not covered"
2322        );
2323        assert!(
2324            TextPlannerPlugin::new(allowlist_config(&[])).text_index_applies(&plan.root, &variable),
2325            "an explicit empty allowlist indexes every predicate"
2326        );
2327
2328        let wild = LogicalPlan::parse("SELECT ?l WHERE { ?s ?p ?l }").unwrap();
2329        assert!(
2330            !TextPlannerPlugin::new(allowlist_config(&["http://ex/name"]))
2331                .text_index_applies(&wild.root, &variable),
2332            "a variable predicate cannot be proven covered"
2333        );
2334
2335        let path =
2336            LogicalPlan::parse("SELECT ?o WHERE { <http://ex/s> <http://ex/p>+ ?o }").unwrap();
2337        let object = waratah_storage::Variable::new_unchecked("o");
2338        assert!(
2339            !TextPlannerPlugin::new(allowlist_config(&["http://ex/p"]))
2340                .text_index_applies(&path.root, &object),
2341            "a property-path object is conservatively not covered"
2342        );
2343    }
2344
2345    #[test]
2346    fn text_index_applies_needs_an_object_slot_scan_not_just_values_or_bind() {
2347        let variable = waratah_storage::Variable::new_unchecked("l");
2348        // The allowlist is off, so every constant predicate is allowed: a
2349        // false answer here can only come from missing coverage evidence.
2350        let plugin = TextPlannerPlugin::new(allowlist_config(&[]));
2351
2352        let values = LogicalPlan::parse(r#"SELECT ?l WHERE { VALUES ?l { "alba" } }"#).unwrap();
2353        assert!(
2354            !plugin.text_index_applies(&values.root, &variable),
2355            "a VALUES-only binding proves no index coverage"
2356        );
2357
2358        let bind = LogicalPlan::parse(r#"SELECT ?l WHERE { BIND("alba" AS ?l) }"#).unwrap();
2359        assert!(
2360            !plugin.text_index_applies(&bind.root, &variable),
2361            "a BIND-only binding proves no index coverage"
2362        );
2363
2364        // A subject-slot binding is not object-slot evidence: the string
2365        // functions type-error on IRIs, and another arm can bind a literal.
2366        let subject =
2367            LogicalPlan::parse("SELECT ?l WHERE { ?l <http://ex/p> <http://ex/o> }").unwrap();
2368        assert!(
2369            !plugin.text_index_applies(&subject.root, &variable),
2370            "a subject-slot binding is not object-slot coverage"
2371        );
2372
2373        // An allowed scan in one UNION arm does not cover a VALUES (or BIND)
2374        // arm that binds the same variable: those values reach the filter
2375        // without an index document behind them.
2376        let values_arm = LogicalPlan::parse(
2377            r#"SELECT ?l WHERE { { ?s <http://ex/name> ?l } UNION { VALUES ?l { "alba" } } }"#,
2378        )
2379        .unwrap();
2380        assert!(
2381            !plugin.text_index_applies(&values_arm.root, &variable),
2382            "a VALUES arm reaches the filter unindexed"
2383        );
2384
2385        let bind_arm = LogicalPlan::parse(
2386            r#"SELECT ?l WHERE { { ?s <http://ex/name> ?l } UNION { BIND("alba" AS ?l) } }"#,
2387        )
2388        .unwrap();
2389        assert!(
2390            !plugin.text_index_applies(&bind_arm.root, &variable),
2391            "a BIND arm reaches the filter unindexed"
2392        );
2393
2394        // The ordinary scan shape keeps its evidence.
2395        let scanned = LogicalPlan::parse("SELECT ?l WHERE { ?s <http://ex/name> ?l }").unwrap();
2396        assert!(plugin.text_index_applies(&scanned.root, &variable));
2397    }
2398
2399    #[test]
2400    fn a_values_only_string_filter_keeps_the_exact_residual() {
2401        // No index evidence behind the value: joining a candidate set would
2402        // drop VALUES rows the index does not hold, so the rewrite declines
2403        // and the exact SPARQL evaluator answers.
2404        //
2405        // Two rows on purpose: a single-row VALUES is folded into the
2406        // expression by the lowering (a ground predicate is exact per row),
2407        // which would make this case pass without the gate ever running.
2408        let plan = rewrite_plan(
2409            r#"SELECT ?l WHERE { VALUES ?l { "alba" "beta" } FILTER(STRSTARTS(?l, "al")) }"#,
2410        )
2411        .unwrap();
2412        assert!(
2413            find_text_join(&plan.root).is_none(),
2414            "a VALUES-only binding has no coverage evidence, so no text_scan is injected"
2415        );
2416    }
2417
2418    #[test]
2419    fn a_subject_slot_string_filter_keeps_the_exact_residual() {
2420        // A subject-slot binding is not object-slot coverage, and a sibling
2421        // UNION arm (or a BIND) could put a literal there. The exact
2422        // evaluator answers; the candidate drain is not injected.
2423        let plan = rewrite_plan(
2424            r#"SELECT ?s WHERE { ?s <http://ex/p> <http://ex/o> FILTER(STRSTARTS(?s, "ex")) }"#,
2425        )
2426        .unwrap();
2427        assert!(
2428            find_text_join(&plan.root).is_none(),
2429            "a subject-slot binding has no coverage evidence, so no text_scan is injected"
2430        );
2431    }
2432
2433    #[test]
2434    fn text_query_subject_mode_rejects_an_unindexed_predicate() {
2435        let config = allowlist_config(&["http://ex/indexed"]);
2436        let ctx = waratah_compute::QueryContext::from_snapshot(SnapshotId::latest())
2437            .with_text_index_state(Some(1), config.fingerprint());
2438        let plugin = TextPlannerPlugin::new(config);
2439        let plan = LogicalPlan::parse("SELECT ?s WHERE { ?s <http://ex/indexed> ?o }").unwrap();
2440        let args = vec![
2441            Expression::Variable(waratah_storage::Variable::new_unchecked("s")),
2442            Expression::NamedNode(oxrdf::NamedNode::new("http://ex/other").unwrap()),
2443            Expression::Literal(oxrdf::Literal::new_simple_literal("word")),
2444        ];
2445        let error = match plugin.match_text_query(&args, &plan.root, &ctx) {
2446            Ok(_) => panic!("an unindexed predicate is a plan error"),
2447            Err(error) => error,
2448        };
2449        assert!(
2450            error.to_string().contains("not an indexed text predicate"),
2451            "{error}"
2452        );
2453    }
2454
2455    #[test]
2456    fn anchored_regex_rewrites_only_the_two_anchored_shapes() {
2457        // ^lit → prefix.
2458        let plan = rewrite_plan(
2459            "SELECT ?name WHERE {
2460                ?x <http://ex/name> ?name .
2461                FILTER(REGEX(?name, \"^Bel\"))
2462            }",
2463        )
2464        .unwrap();
2465        let payload = find_text_join(&plan.root)
2466            .expect("anchored ^ prefix rewrite")
2467            .payload
2468            .downcast_ref::<TextScanPayload>()
2469            .unwrap();
2470        assert_eq!(payload.request.mode, TextCandidateMode::Prefix);
2471        // .*lit$ → suffix.
2472        let plan = rewrite_plan(
2473            "SELECT ?name WHERE {
2474                ?x <http://ex/name> ?name .
2475                FILTER(REGEX(?name, \".*lin$\"))
2476            }",
2477        )
2478        .unwrap();
2479        let payload = find_text_join(&plan.root)
2480            .expect("anchored .* suffix rewrite")
2481            .payload
2482            .downcast_ref::<TextScanPayload>()
2483            .unwrap();
2484        assert_eq!(payload.request.mode, TextCandidateMode::Suffix);
2485        // A general regex stays unindexed (no text_scan in the plan).
2486        let plan = rewrite_plan(
2487            "SELECT ?name WHERE {
2488                ?x <http://ex/name> ?name .
2489                FILTER(REGEX(?name, \"Be.*lin\"))
2490            }",
2491        )
2492        .unwrap();
2493        assert!(
2494            find_text_join(&plan.root).is_none(),
2495            "a general regex has no candidate producer"
2496        );
2497    }
2498
2499    #[test]
2500    fn anchored_regex_bodies_with_metacharacters_stay_unindexed() {
2501        // A metacharacter in the anchored body is regex syntax. Seeding the
2502        // candidate request with those characters would treat them as
2503        // literal text, and the join would drop values the real regex
2504        // matches before the exact residual could keep them (e.g. "abc"
2505        // matches `^a.c` but does not start with the characters "a.c").
2506        // Every such body must refuse the rewrite and keep the exact
2507        // residual; each case below would be a WRONG answer if rewritten.
2508        for pattern in [
2509            "^a.c",   // `.` matches any char ("abc" matches, "a.c" seed misses it)
2510            "^a|b",   // alternation: matches every value containing "b" anywhere
2511            "^a.*",   // trailing `.*` is part of the body ("apple" matches, seed "a.*" misses it)
2512            "^Bel$",  // the `$` survives the `^` strip; seed "Bel$" misses the exact match "Bel"
2513            ".*a.c$", // suffix mode with the same `.` problem
2514            // SPARQL source below is "^a\\.c", so the parsed pattern value is
2515            // `a\.c`: the regex means a literal dot, but the body carries a
2516            // raw backslash, so seeding it as literal text would miss "a.c".
2517            "^a\\\\.c",
2518            "^a[bc]d", // a character class: "abd" matches, the seed is literal brackets
2519        ] {
2520            let sparql = format!(
2521                "SELECT ?name WHERE {{
2522                    ?x <http://ex/name> ?name .
2523                    FILTER(REGEX(?name, \"{pattern}\"))
2524                }}"
2525            );
2526            let plan = rewrite_plan(&sparql).unwrap();
2527            assert!(
2528                find_text_join(&plan.root).is_none(),
2529                "REGEX body {pattern:?} must stay unindexed (not a literal seed)"
2530            );
2531        }
2532    }
2533
2534    #[test]
2535    fn anchored_regex_literal_bodies_with_plain_specials_still_rewrite() {
2536        // Non-regex characters that merely look special stay literal: the
2537        // gate refuses only true regex syntax.
2538        let plan = rewrite_plan(
2539            "SELECT ?name WHERE {
2540                ?x <http://ex/name> ?name .
2541                FILTER(REGEX(?name, \"^a-b_c\"))
2542            }",
2543        )
2544        .unwrap();
2545        let payload = find_text_join(&plan.root)
2546            .expect("a hyphen is not regex syntax; the body is literal")
2547            .payload
2548            .downcast_ref::<TextScanPayload>()
2549            .unwrap();
2550        assert_eq!(payload.request.mode, TextCandidateMode::Prefix);
2551    }
2552
2553    #[test]
2554    fn untrusted_text_query_fails_the_plan_with_the_repair_hint() {
2555        installed();
2556        // No epoch: UNTRUSTED. The lowering runs the rewrite, which fails.
2557        let error = LogicalPlan::parse_with_context(
2558            &format!(
2559                "PREFIX text: <{TEXT}>
2560                SELECT ?name WHERE {{
2561                    ?x <http://ex/name> ?name .
2562                    FILTER(text:query(?name, \"laser\"))
2563                }}"
2564            ),
2565            &waratah_compute::QueryContext::from_snapshot(SnapshotId::latest()),
2566        )
2567        .expect_err("text:query under an untrusted index must fail the plan");
2568        assert!(
2569            error.to_string().contains("waratah text rebuild-index"),
2570            "the failure names the repair command: {error}"
2571        );
2572    }
2573
2574    #[test]
2575    fn an_empty_partition_fingerprint_is_not_trusted() {
2576        // Trust is epoch AND strict fingerprint equality: an empty partition
2577        // fingerprint (a Describe that carried an epoch but no fingerprint)
2578        // must NOT count as "anything matches" — documents built by unknown
2579        // settings must never be trusted.
2580        installed();
2581        let ctx = waratah_compute::QueryContext::from_snapshot(SnapshotId::latest())
2582            .with_text_index_state(Some(1), "");
2583        let error = LogicalPlan::parse_with_context(
2584            &format!(
2585                "PREFIX text: <{TEXT}>
2586                SELECT ?name WHERE {{
2587                    ?x <http://ex/name> ?name .
2588                    FILTER(text:query(?name, \"laser\"))
2589                }}"
2590            ),
2591            &ctx,
2592        )
2593        .expect_err("an empty partition fingerprint must not satisfy the trust gate");
2594        assert!(
2595            error.to_string().contains("waratah text rebuild-index"),
2596            "the failure names the repair command: {error}"
2597        );
2598    }
2599
2600    #[test]
2601    fn subject_mode_keys_follow_the_bound_graph_variable() {
2602        // A single scope's op already returns DISTINCT rows, so it needs no
2603        // Distinct node. Dataset scope emits the subject alone; a bound
2604        // graph variable adds the graph column, and that column must survive
2605        // into the join — a subject matched in several graphs would
2606        // otherwise collapse to one arbitrary graph and the join's soft-pair
2607        // reconciliation would drop the other graphs' inner rows. The
2608        // engine-level pin lives in `tests/subject_mode_graphs.rs`.
2609        let plan = rewrite_plan(
2610            "SELECT ?s WHERE {
2611                ?s <http://ex/bio> ?v .
2612                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2613            }",
2614        )
2615        .unwrap();
2616        let op = find_subject_op(&plan.root).expect("dataset-scope resolve op");
2617        assert_eq!(
2618            op.variables,
2619            vec![waratah_storage::Variable::new_unchecked("s")]
2620        );
2621        assert!(!subject_request(op).return_graph);
2622        assert!(
2623            find_subject_distinct(&plan.root).is_none(),
2624            "a single scope's op needs no Distinct"
2625        );
2626
2627        // One `GRAPH ?g` scope: the op emits [s, ?g] itself.
2628        let plan = rewrite_plan(
2629            "SELECT ?g ?s WHERE {
2630                GRAPH ?g {
2631                    ?s <http://ex/bio> ?v .
2632                    FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2633                }
2634            }",
2635        )
2636        .unwrap();
2637        let op = find_subject_op(&plan.root).expect("graph-scope resolve op");
2638        assert_eq!(
2639            op.variables,
2640            vec![
2641                waratah_storage::Variable::new_unchecked("s"),
2642                waratah_storage::Variable::new_unchecked("g"),
2643            ]
2644        );
2645        assert!(subject_request(op).return_graph);
2646        assert!(
2647            find_subject_distinct(&plan.root).is_none(),
2648            "one scope, even a graph variable, needs no union Distinct"
2649        );
2650
2651        // A MIXED group (`GRAPH ?g` beside a bare pattern) resolves once,
2652        // in the BARE sibling's window: the implicit text triple belongs at
2653        // the FILTER's level, where the dataset default is the only pattern
2654        // context. The named-graph pattern is a different window the filter
2655        // does not claim, so the op is subject-only and needs no union.
2656        let plan = rewrite_plan(
2657            "SELECT ?s WHERE {
2658                GRAPH ?g { ?s <http://ex/bio> ?v }
2659                ?s <http://ex/note> ?x
2660                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2661            }",
2662        )
2663        .unwrap();
2664        let op = find_subject_op(&plan.root).expect("mixed-group resolve op");
2665        assert_eq!(
2666            op.variables,
2667            vec![waratah_storage::Variable::new_unchecked("s")],
2668            "a mixed group emits the subject alone"
2669        );
2670        assert_eq!(
2671            subject_request(op).graph_name,
2672            Some(EncodedTerm::DefaultGraph),
2673            "the bare sibling's window is the dataset default"
2674        );
2675        assert!(!subject_request(op).return_graph);
2676        assert!(
2677            find_subject_distinct(&plan.root).is_none(),
2678            "one window needs no union Distinct"
2679        );
2680    }
2681
2682    #[test]
2683    fn mixed_group_resolves_the_bgp_siblings_window() {
2684        // The implicit text triple belongs at the FILTER's own group level:
2685        // a BARE sibling is that level's pattern, so a mixed group resolves
2686        // in the dataset default window and the GRAPH-block pattern is a
2687        // different window the filter does not claim. One op, no union.
2688        for graph in ["<http://ex/g1>", "?g"] {
2689            let plan = rewrite_plan(&format!(
2690                "SELECT ?s WHERE {{
2691                    GRAPH {graph} {{ ?s <http://ex/bio> ?v }}
2692                    ?s <http://ex/note> ?x
2693                    FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2694                }}"
2695            ))
2696            .unwrap();
2697            let mut ops = Vec::new();
2698            subject_ops(&plan.root, &mut ops);
2699            assert_eq!(
2700                ops.len(),
2701                1,
2702                "GRAPH {graph}: one op, the BGP sibling's window"
2703            );
2704            assert_eq!(
2705                subject_request(ops[0]).graph_name,
2706                Some(EncodedTerm::DefaultGraph),
2707                "GRAPH {graph}: the bare sibling is the default graph"
2708            );
2709            assert!(!subject_request(ops[0]).return_graph);
2710            assert!(
2711                find_subject_distinct(&plan.root).is_none(),
2712                "one window needs no union Distinct"
2713            );
2714        }
2715    }
2716
2717    #[test]
2718    fn a_single_graph_block_keeps_its_window_when_no_bgp_sibling_exists() {
2719        // Lowering erases the inside/outside position of a single GRAPH
2720        // block (a fixed graph lands on the scans; a variable graph gets a
2721        // boundary node only when the variable is also used inside), so the
2722        // plugin cannot tell a filter written outside the block from one
2723        // written inside it. Both keep the block's window — deliberate
2724        // blindness, documented in `resolve_subject_scopes`.
2725        let plan = rewrite_plan(
2726            "SELECT ?s WHERE {
2727                GRAPH ?g { ?s <http://ex/bio> ?v }
2728                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2729            }",
2730        )
2731        .unwrap();
2732        let op = find_subject_op(&plan.root).expect("variable-graph resolve op");
2733        assert_eq!(
2734            op.variables.len(),
2735            2,
2736            "the graph column survives: {:?}",
2737            op.variables
2738        );
2739        assert!(subject_request(op).return_graph);
2740        assert_eq!(subject_request(op).graph_name, None);
2741
2742        let plan = rewrite_plan(
2743            "SELECT ?s WHERE {
2744                GRAPH <http://ex/g1> { ?s <http://ex/bio> ?v }
2745                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2746            }",
2747        )
2748        .unwrap();
2749        let op = find_subject_op(&plan.root).expect("fixed-graph resolve op");
2750        assert_eq!(op.variables.len(), 1);
2751        assert_eq!(
2752            subject_request(op).graph_name,
2753            Some(EncodedTerm::from(
2754                &oxrdf::NamedNode::new("http://ex/g1").unwrap()
2755            ))
2756        );
2757
2758        // Two GRAPH blocks and no BGP sibling: no single window to claim,
2759        // so the resolve is left unbound.
2760        let plan = rewrite_plan(
2761            "SELECT ?s WHERE {
2762                GRAPH <http://ex/g1> { ?s <http://ex/bio> ?v }
2763                GRAPH <http://ex/g2> { ?s <http://ex/note> ?x }
2764                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2765            }",
2766        )
2767        .unwrap();
2768        let op = find_subject_op(&plan.root).expect("two-graph resolve op");
2769        assert_eq!(subject_request(op).graph_name, None);
2770        assert!(subject_request(op).graph_filter_terms.is_empty());
2771        assert!(!subject_request(op).return_graph);
2772    }
2773
2774    #[test]
2775    fn graph_variable_equal_to_the_subject_emits_one_column() {
2776        // `GRAPH ?s { … }` plus `text:query(?s, …)`: one variable takes one
2777        // value, so the matched row's subject AND graph are ?s. The op emits
2778        // the subject alone and the resolve keeps only subject-equals-graph
2779        // rows; declaring ?s twice would let the join keep a row whose
2780        // matching literal lives in another graph.
2781        let plan = rewrite_plan(
2782            "SELECT ?s WHERE {
2783                GRAPH ?s { ?x <http://ex/p> ?o }
2784                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
2785            }",
2786        )
2787        .unwrap();
2788        let op = find_subject_op(&plan.root).expect("resolve op");
2789        assert_eq!(
2790            op.variables,
2791            vec![waratah_storage::Variable::new_unchecked("s")],
2792            "the op declares the subject once"
2793        );
2794        let request = subject_request(op);
2795        assert!(request.subject_equals_graph);
2796        assert!(!request.return_graph);
2797        assert_eq!(request.graph_name, None);
2798        assert!(
2799            request
2800                .graph_filter_terms
2801                .contains(&EncodedTerm::DefaultGraph)
2802                && !request.graph_filter_allow,
2803            "the GRAPH ?s scope still blocks the unnamed graph"
2804        );
2805    }
2806
2807    #[test]
2808    fn belt_fails_bind_order_by_and_aggregate_nesting() {
2809        // The belt must inspect every row-decision expression, not just
2810        // FILTER conditions: a surviving text:query inside BIND / ORDER BY
2811        // / an aggregate argument would reach the per-row backstop (a
2812        // per-row type error that filters rows) instead of the plan error
2813        // the trust contract promises.
2814        let error = rewrite_plan(
2815            "SELECT ?x WHERE {
2816                ?s <http://ex/tag> ?l .
2817                BIND(<http://jena.apache.org/text#query>(?l, \"mountain\") AS ?x)
2818            }",
2819        )
2820        .expect_err("BIND of text:query must fail the plan");
2821        assert!(
2822            error.to_string().contains("top-level FILTER conjunct"),
2823            "{error}"
2824        );
2825
2826        let error = rewrite_plan(
2827            "SELECT ?l WHERE {
2828                ?s <http://ex/tag> ?l .
2829            }
2830            ORDER BY <http://jena.apache.org/text#query>(?l, \"mountain\")",
2831        )
2832        .expect_err("ORDER BY text:query must fail the plan");
2833        assert!(
2834            error.to_string().contains("top-level FILTER conjunct"),
2835            "{error}"
2836        );
2837
2838        let error = rewrite_plan(
2839            "SELECT ?s (COUNT(<http://jena.apache.org/text#query>(?l, \"mountain\")) AS ?c) WHERE {
2840                ?s <http://ex/tag> ?l .
2841            }
2842            GROUP BY ?s",
2843        )
2844        .expect_err("an aggregate argument of text:query must fail the plan");
2845        assert!(
2846            error.to_string().contains("top-level FILTER conjunct"),
2847            "{error}"
2848        );
2849    }
2850
2851    #[test]
2852    fn parse_query_and_lang_reject_non_plain_string_arguments() {
2853        // The query and the "lang:xx" argument must be PLAIN strings: the
2854        // old guard's second arm accepted ANY non-language literal, so
2855        // `text:query(?l, 42)` silently searched the string "42".
2856        let error = rewrite_plan(
2857            "SELECT ?l WHERE {
2858                ?s <http://ex/tag> ?l .
2859                FILTER(<http://jena.apache.org/text#query>(?l, 42))
2860            }",
2861        )
2862        .expect_err("a numeric query literal must fail the plan");
2863        assert!(
2864            error.to_string().contains("must be a plain string literal"),
2865            "{error}"
2866        );
2867
2868        let error = rewrite_plan(
2869            "SELECT ?l WHERE {
2870                ?s <http://ex/tag> ?l .
2871                FILTER(<http://jena.apache.org/text#query>(?l, \"mountain\"@en))
2872            }",
2873        )
2874        .expect_err("a language-tagged query literal must fail the plan");
2875        assert!(
2876            error.to_string().contains("must be a plain string literal"),
2877            "{error}"
2878        );
2879
2880        let error = rewrite_plan(
2881            "SELECT ?l WHERE {
2882                ?s <http://ex/tag> ?l .
2883                FILTER(<http://jena.apache.org/text#query>(?l, \"mountain\", 42))
2884            }",
2885        )
2886        .expect_err("a non-string trailing argument must fail the plan");
2887        assert!(error.to_string().contains("trailing argument"), "{error}");
2888
2889        // Plain strings still rewrite: explicit xsd:string passes the guard
2890        // the same way a simple literal does.
2891        rewrite_plan(
2892            "SELECT ?l WHERE {
2893                ?s <http://ex/tag> ?l .
2894                FILTER(<http://jena.apache.org/text#query>(?l, \"mountain\"^^<http://www.w3.org/2001/XMLSchema#string>))
2895            }",
2896        )
2897        .expect("an explicit xsd:string query literal is a plain string");
2898    }
2899
2900    #[test]
2901    fn text_query_in_a_hoisted_optional_condition_names_the_boundary() {
2902        // m5: a body filter can be HOISTED into the OPTIONAL's join
2903        // condition (shape-dependent on the surrounding pattern — a
2904        // graph-scoped sibling triggers it), so a text:query written as its
2905        // own FILTER inside the body errors. The message must name the
2906        // OPTIONAL situation, not read as if the user had nested the call
2907        // inside `||`.
2908        let error = rewrite_plan(
2909            "SELECT ?s ?v WHERE { \
2910                GRAPH <http://ex/g1> { ?s <http://ex/note> ?y } \
2911                OPTIONAL { ?s <http://ex/bio> ?v \
2912                    FILTER(<http://jena.apache.org/text#query>(?v, \"mountain\")) } \
2913            }",
2914        )
2915        .expect_err("a hoisted OPTIONAL condition cannot run text:query");
2916        assert!(
2917            error
2918                .to_string()
2919                .contains("cannot answer inside an OPTIONAL"),
2920            "the message names the OPTIONAL situation: {error}"
2921        );
2922    }
2923
2924    #[test]
2925    fn literal_mode_over_an_unbound_variable_answers_the_empty_table() {
2926        // A text:query argument the branch never binds errors on every
2927        // solution — SPARQL drops every row — so the rewrite emits the
2928        // empty table (zero rows over the branch's columns) instead of a
2929        // join whose key the inner side does not carry (a runtime join
2930        // arity error). The engine pin is
2931        // literal_mode_with_an_unbound_variable_answers_zero_rows.
2932        let plan = rewrite_plan(&format!(
2933            "PREFIX text: <{TEXT}>
2934            SELECT ?l WHERE {{ FILTER(text:query(?l, \"mountain\")) }}"
2935        ))
2936        .expect("the unsatisfiable filter rewrites, not errors");
2937        let PlanNode::Values(values) = &plan.root else {
2938            panic!("the filter rewrites to the empty table: {:?}", plan.root);
2939        };
2940        assert!(values.rows.is_empty(), "zero rows: {values:?}");
2941
2942        // A branch binding OTHER variables answers empty the same way —
2943        // every row's filter error drops the row.
2944        let plan = rewrite_plan(&format!(
2945            "PREFIX text: <{TEXT}>
2946            SELECT ?s WHERE {{
2947                ?s <http://ex/note> ?x .
2948                FILTER(text:query(?l, \"mountain\"))
2949            }}"
2950        ))
2951        .unwrap();
2952        let PlanNode::Values(values) = &plan.root else {
2953            panic!("the filter rewrites to the empty table: {:?}", plan.root);
2954        };
2955        assert!(values.rows.is_empty(), "zero rows: {values:?}");
2956    }
2957
2958    #[test]
2959    fn union_arms_do_not_inherit_sibling_arm_scopes() {
2960        // UNION arms are independent group patterns — the right arm's
2961        // rewrite must resolve only ITS OWN scans' scopes. The old shared
2962        // track leaked the left arm's GRAPH <g1> stamp into the right arm,
2963        // injecting a g1-scoped candidate arm; subject mode has no residual
2964        // to refine the extra candidates away, so they are final rows (the
2965        // engine pin is union_arms_search_only_their_own_scope).
2966        let plan = rewrite_plan(
2967            "SELECT ?s ?v WHERE {
2968                { GRAPH <http://ex/g1> { ?x <http://ex/note> ?y } }
2969                UNION
2970                { ?s <http://ex/bio> ?v
2971                  FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\")) }
2972            }",
2973        )
2974        .unwrap();
2975        let mut ops = Vec::new();
2976        subject_ops(&plan.root, &mut ops);
2977        assert_eq!(
2978            ops.len(),
2979            1,
2980            "exactly one resolve op, from the filter's own branch: {ops:?}"
2981        );
2982        assert_eq!(
2983            subject_request(ops[0]).graph_name,
2984            Some(EncodedTerm::DefaultGraph),
2985            "the op is scoped to the filter's own dataset window, not the \
2986             sibling arm's g1"
2987        );
2988    }
2989
2990    #[test]
2991    fn path_endpoints_are_slot_evidence() {
2992        // A variable bound ONLY by a property-path endpoint carries the
2993        // endpoint's slot kind, exactly like a scan slot: without this the
2994        // contradiction diagnostics never fire, literal mode rewrites, and
2995        // the IRI-bound subjects join string candidates — a silent
2996        // zero-row answer instead of the diagnostic.
2997        let error = rewrite_plan(
2998            "SELECT ?s WHERE {
2999                ?s <http://ex/knows>+ ?o .
3000                FILTER(<http://jena.apache.org/text#query>(?s, \"word\"))
3001            }",
3002        )
3003        .expect_err("a path-subject endpoint cannot be a searched literal");
3004        assert!(
3005            error.to_string().contains("subject position"),
3006            "the subject form is named: {error}"
3007        );
3008
3009        let error = rewrite_plan(
3010            "SELECT ?s WHERE {
3011                ?x <http://ex/knows>+ ?s .
3012                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3013            }",
3014        )
3015        .expect_err("a path-object endpoint cannot be a searched subject");
3016        assert!(
3017            error.to_string().contains("object position"),
3018            "the literal form is named: {error}"
3019        );
3020
3021        // Positive control: subject mode over a path SUBJECT endpoint is
3022        // the right form — the endpoint binds hop subjects, no
3023        // contradiction, the plan rewrites.
3024        let plan = rewrite_plan(
3025            "SELECT ?s WHERE {
3026                ?s <http://ex/knows>+ ?o .
3027                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3028            }",
3029        )
3030        .unwrap();
3031        assert!(
3032            find_subject_op(&plan.root).is_some(),
3033            "subject mode over a path-subject endpoint rewrites"
3034        );
3035    }
3036
3037    #[test]
3038    fn subject_mode_ops_emit_only_user_visible_columns() {
3039        // The op's schema is the user's variable set — the subject, plus the
3040        // bound graph variable. The literal-carrier design (and its gensym'd
3041        // `__text_h…` column) is gone: the partition resolves literals to
3042        // subjects, so nothing hidden rides the join.
3043        let plan = rewrite_plan(
3044            "SELECT ?s WHERE {
3045                ?s <http://ex/p> ?l .
3046                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3047            }",
3048        )
3049        .unwrap();
3050        let op = find_subject_op(&plan.root).expect("the resolve op");
3051        assert_eq!(
3052            op.variables,
3053            vec![waratah_storage::Variable::new_unchecked("s")]
3054        );
3055
3056        let plan = rewrite_plan(
3057            "SELECT ?g ?s WHERE {
3058                GRAPH ?g {
3059                    ?s <http://ex/p> ?l .
3060                    FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3061                }
3062            }",
3063        )
3064        .unwrap();
3065        let op = find_subject_op(&plan.root).expect("the resolve op");
3066        assert_eq!(
3067            op.variables,
3068            vec![
3069                waratah_storage::Variable::new_unchecked("s"),
3070                waratah_storage::Variable::new_unchecked("g"),
3071            ],
3072            "the graph column is the user's variable, not a carrier"
3073        );
3074        assert!(
3075            op.variables
3076                .iter()
3077                .all(|variable| !variable.as_str().starts_with("__text_h")),
3078            "no hidden carrier column exists"
3079        );
3080    }
3081
3082    #[test]
3083    fn values_and_bind_ground_terms_are_slot_evidence() {
3084        // A VALUES row or a BIND of a ground expression proves the
3085        // variable's RDF kind, exactly like a scan slot: the contradiction
3086        // diagnostics fire instead of a silent zero-row answer.
3087        let error = rewrite_plan(
3088            "SELECT ?s WHERE {
3089                VALUES ?s { <http://ex/a> <http://ex/b> }
3090                FILTER(<http://jena.apache.org/text#query>(?s, \"word\"))
3091            }",
3092        )
3093        .expect_err("a VALUES-bound IRI cannot be a searched literal");
3094        assert!(
3095            error.to_string().contains("subject position"),
3096            "the literal form is named: {error}"
3097        );
3098
3099        // A PARTIAL column (UNDEF rows) keeps the variable alive in the call
3100        // — the fully-ground shapes are constant-folded by the lowering
3101        // before the plugin sees them, and the ground call fails the
3102        // unsupported-form error (also a plan error, never silent rows).
3103        let error = rewrite_plan(
3104            "SELECT ?s WHERE {
3105                VALUES ?s { \"a\" UNDEF }
3106                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3107            }",
3108        )
3109        .expect_err("a VALUES literal row is object evidence; subject mode is contradicted");
3110        assert!(
3111            error.to_string().contains("object position"),
3112            "the subject form is named: {error}"
3113        );
3114
3115        // A fully-ground multi-row VALUES keeps the variable alive in the
3116        // call (nothing to fold to a single term): the walk's slot evidence
3117        // fires the tailored contradiction — every row is a literal, so the
3118        // subject form is the wrong one.
3119        let error = rewrite_plan(
3120            "SELECT ?s WHERE {
3121                VALUES ?s { \"a\" \"b\" }
3122                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3123            }",
3124        )
3125        .expect_err("a VALUES literal column contradicts subject mode");
3126        assert!(
3127            error.to_string().contains("object position"),
3128            "the subject form is named: {error}"
3129        );
3130
3131        // Same for a BIND of a ground expression. The ground-substitution
3132        // guard keeps the subject variable (text:query joins its candidate set
3133        // back to it), so the call reaches the plugin as a variable form and
3134        // the slot evidence names the right contradiction: a BIND-ground
3135        // literal cannot be a subject.
3136        let error = rewrite_plan(
3137            "SELECT ?s WHERE {
3138                BIND(\"word\" AS ?s)
3139                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3140            }",
3141        )
3142        .expect_err("a BIND-ground literal subject contradicts subject mode");
3143        assert!(error.to_string().contains("object position"), "{error}");
3144
3145        // Positive control: subject mode over a PARTIAL VALUES column whose
3146        // only ground row is an IRI rewrites — the right form, no
3147        // contradiction.
3148        let plan = rewrite_plan(
3149            "SELECT ?s WHERE {
3150                VALUES ?s { <http://ex/a> UNDEF }
3151                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/field>, \"word\"))
3152            }",
3153        )
3154        .unwrap();
3155        assert!(
3156            find_subject_op(&plan.root).is_some(),
3157            "subject mode over a VALUES-bound IRI rewrites"
3158        );
3159    }
3160
3161    #[test]
3162    fn a_ground_subject_keeps_its_variable_and_rewrites() {
3163        // A single-row VALUES binds the subject to one IRI. Without the
3164        // ground-substitution guard the lowering would fold the IRI into the
3165        // call, which has no recognised form; keeping the variable lets the
3166        // subject-mode rewrite join the candidate set back to it.
3167        let plan = rewrite_plan(
3168            "SELECT ?s WHERE {
3169                VALUES ?s { <http://ex/a> }
3170                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3171            }",
3172        )
3173        .unwrap();
3174        let op = find_subject_op(&plan.root).expect("the subject resolve op");
3175        assert_eq!(
3176            op.pinned.len(),
3177            1,
3178            "the ground subject is pinned into the resolve"
3179        );
3180        assert_eq!(
3181            op.variables,
3182            vec![waratah_storage::Variable::new_unchecked("s")],
3183            "the variable survives; the op still joins back to it"
3184        );
3185    }
3186
3187    #[test]
3188    fn a_ground_literal_pins_its_term_into_the_text_op() {
3189        // A single-row VALUES binds the literal. The guard keeps the variable,
3190        // and literal mode seats the one-row driver as a pinned membership test
3191        // instead of draining the candidate set.
3192        let plan = rewrite_plan(
3193            "SELECT ?lit WHERE {
3194                VALUES ?lit { \"report\" }
3195                FILTER(<http://jena.apache.org/text#query>(?lit, \"report\"))
3196            }",
3197        )
3198        .unwrap();
3199        let op = find_text_join(&plan.root).expect("text_scan joined into the plan");
3200        assert_eq!(
3201            op.pinned.len(),
3202            1,
3203            "the ground literal is pinned into the op"
3204        );
3205        assert_eq!(op.produced_row_count_estimate, 1);
3206    }
3207
3208    #[test]
3209    fn fingerprint_mismatch_fails_the_plan_like_an_untrusted_index() {
3210        installed();
3211        let ctx = waratah_compute::QueryContext::from_snapshot(SnapshotId::latest())
3212            .with_text_index_state(Some(1), "text-index-v1;analyzer=other;seed_chars=8");
3213        let error = LogicalPlan::parse_with_context(
3214            &format!(
3215                "PREFIX text: <{TEXT}>
3216                SELECT ?name WHERE {{
3217                    ?x <http://ex/name> ?name .
3218                    FILTER(text:query(?name, \"laser\"))
3219                }}"
3220            ),
3221            &ctx,
3222        )
3223        .expect_err("a fingerprint mismatch must fail the plan");
3224        assert!(error.to_string().contains("waratah text rebuild-index"));
3225    }
3226
3227    #[test]
3228    fn the_jena_reflex_is_the_contradiction_error() {
3229        // ?s only ever appears in subject slots: literal mode cannot bind it.
3230        let error = rewrite_plan(&format!(
3231            "PREFIX text: <{TEXT}>
3232            SELECT ?s WHERE {{
3233                ?s <http://ex/type> <http://ex/Person> .
3234                FILTER(text:query(?s, \"word\"))
3235            }}"
3236        ))
3237        .expect_err("literal mode over a subject-only variable is a plan error");
3238        assert!(
3239            error.to_string().contains("subject position"),
3240            "the error names the subject form: {error}"
3241        );
3242    }
3243
3244    #[test]
3245    fn text_query_as_a_graph_pattern_predicate_is_a_plan_error() {
3246        let error = rewrite_plan(&format!(
3247            "PREFIX text: <{TEXT}>
3248            SELECT ?s WHERE {{
3249                ?s text:query \"word\" .
3250            }}"
3251        ))
3252        .expect_err("text:query in predicate position is a plan error");
3253        assert!(error.to_string().contains("FILTER function"));
3254    }
3255
3256    #[test]
3257    fn untrusted_string_functions_fall_back_to_the_exact_residual() {
3258        // No epoch: STRSTARTS keeps its conjunct and no text_scan is injected.
3259        installed();
3260        let plan = LogicalPlan::parse_with_context(
3261            "SELECT ?name WHERE {
3262                ?x <http://ex/name> ?name .
3263                FILTER(STRSTARTS(?name, \"Bel\"))
3264            }",
3265            &waratah_compute::QueryContext::from_snapshot(SnapshotId::latest()),
3266        )
3267        .unwrap();
3268        assert!(
3269            find_text_join(&plan.root).is_none(),
3270            "untrusted string functions rewrite nothing (the residual answers exactly)"
3271        );
3272    }
3273
3274    // ---- Blocker 1 pinning: the walk must reach every node a lowered
3275    // FILTER can hide under, and the belt must fail every shape it cannot
3276    // rewrite. A missed filter is a WRONG answer (the per-row backstop
3277    // drops rows from a trusted index), never a slow one.
3278
3279    #[test]
3280    fn text_query_rewrites_under_group_by() {
3281        let plan = rewrite_plan(
3282            "SELECT ?name (COUNT(?x) AS ?n) WHERE {
3283                ?x <http://ex/name> ?name .
3284                FILTER(<http://jena.apache.org/text#query>(?name, \"laser\"))
3285            } GROUP BY ?name",
3286        )
3287        .unwrap();
3288        let op = find_text_join(&plan.root).expect("the GROUP BY must not hide the filter");
3289        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3290        assert_eq!(payload.request.query, "laser");
3291    }
3292
3293    #[test]
3294    fn text_query_rewrites_under_graph_variable() {
3295        let plan = rewrite_plan(
3296            "SELECT ?g ?name WHERE {
3297                GRAPH ?g {
3298                    ?x <http://ex/name> ?name .
3299                    FILTER(<http://jena.apache.org/text#query>(?name, \"laser\"))
3300                }
3301            }",
3302        )
3303        .unwrap();
3304        let op = find_text_join(&plan.root).expect("the GRAPH ?g wrapper must not hide the filter");
3305        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3306        assert_eq!(payload.request.query, "laser");
3307    }
3308
3309    #[test]
3310    fn text_query_rewrites_inside_a_subselect() {
3311        let plan = rewrite_plan(
3312            "SELECT ?name WHERE {
3313                {
3314                    SELECT ?name WHERE {
3315                        ?x <http://ex/name> ?name .
3316                        FILTER(<http://jena.apache.org/text#query>(?name, \"laser\"))
3317                    }
3318                }
3319            }",
3320        )
3321        .unwrap();
3322        let op = find_text_join(&plan.root).expect("the sub-SELECT must not hide the filter");
3323        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3324        assert_eq!(payload.request.query, "laser");
3325    }
3326
3327    #[test]
3328    fn text_query_rewrites_wrapped_by_a_later_bind() {
3329        // BIND after the FILTER wraps the lowered filter in an Extend; the
3330        // descent must enter it.
3331        let plan = rewrite_plan(
3332            "SELECT ?name ?shout WHERE {
3333                ?x <http://ex/name> ?name .
3334                FILTER(<http://jena.apache.org/text#query>(?name, \"laser\"))
3335                BIND(CONCAT(?name, \"!\") AS ?shout)
3336            }",
3337        )
3338        .unwrap();
3339        let op = find_text_join(&plan.root).expect("the BIND wrapper must not hide the filter");
3340        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3341        assert_eq!(payload.request.query, "laser");
3342    }
3343
3344    #[test]
3345    fn nested_text_query_fails_the_plan() {
3346        // `||` hides the call from the conjunct matcher; the belt must fail
3347        // the plan instead of letting the per-row backstop drop every row.
3348        let error = rewrite_plan(
3349            "SELECT ?name WHERE {
3350                ?x <http://ex/name> ?name .
3351                FILTER(<http://jena.apache.org/text#query>(?name, \"laser\") || ?name = \"x\")
3352            }",
3353        )
3354        .expect_err("a text:query nested in || must fail the plan");
3355        assert!(
3356            error.to_string().contains("top-level FILTER conjunct"),
3357            "the belt names the supported shape: {error}"
3358        );
3359    }
3360
3361    #[test]
3362    fn negated_text_query_fails_the_plan() {
3363        let error = rewrite_plan(
3364            "SELECT ?name WHERE {
3365                ?x <http://ex/name> ?name .
3366                FILTER(!<http://jena.apache.org/text#query>(?name, \"laser\"))
3367            }",
3368        )
3369        .expect_err("a negated text:query must fail the plan");
3370        assert!(error.to_string().contains("top-level FILTER conjunct"));
3371    }
3372
3373    #[test]
3374    fn text_query_in_an_if_branch_fails_the_plan() {
3375        let error = rewrite_plan(
3376            "SELECT ?name WHERE {
3377                ?x <http://ex/name> ?name .
3378                FILTER(IF(<http://jena.apache.org/text#query>(?name, \"laser\"), true, false))
3379            }",
3380        )
3381        .expect_err("a text:query inside IF must fail the plan");
3382        assert!(error.to_string().contains("top-level FILTER conjunct"));
3383    }
3384
3385    #[test]
3386    fn text_query_inside_an_optional_rewrites_in_the_right_arm() {
3387        // A FILTER inside the OPTIONAL's right arm lowers as a Filter node
3388        // within that arm (not into the LeftJoin's condition slots), where
3389        // the descent reaches and rewrites it. The rewrite is sound there:
3390        // the text scan joins inside the right arm, so matching notes extend
3391        // the solution and non-matching ones leave ?note unbound — exactly
3392        // the filter's own semantics. The belt on the LeftJoin condition
3393        // slots (early_filter / residual_filter) stays as defense for any
3394        // lowering that places a text:query directly in the condition.
3395        let plan = rewrite_plan(
3396            "SELECT ?name ?note WHERE {
3397                ?x <http://ex/name> ?name .
3398                OPTIONAL {
3399                    ?x <http://ex/note> ?note .
3400                    FILTER(<http://jena.apache.org/text#query>(?note, \"laser\"))
3401                }
3402            }",
3403        )
3404        .expect("a text:query inside the OPTIONAL's right arm rewrites in place");
3405        let op = find_text_join(&plan.root).expect("the LeftJoin right arm must be rewritten");
3406        let payload = op.payload.downcast_ref::<TextScanPayload>().unwrap();
3407        assert_eq!(payload.request.query, "laser");
3408    }
3409
3410    #[test]
3411    fn text_query_in_a_leftjoin_condition_slot_fails_the_plan() {
3412        // Defense-in-depth pin: if a lowering ever places a text:query
3413        // directly into the OPTIONAL's condition slots, the belt must fail
3414        // the plan. Built by hand because today's lowering never produces
3415        // this shape (the filter lands in the right arm instead, where the
3416        // descent rewrites it — see the test above).
3417        let mut plan = rewrite_plan(
3418            "SELECT ?name ?note WHERE {
3419                ?x <http://ex/name> ?name .
3420                OPTIONAL { ?x <http://ex/note> ?note . }
3421            }",
3422        )
3423        .unwrap();
3424        let call = Expression::FunctionCall(
3425            Function::Custom(spargebra::term::NamedNode::new_unchecked(TEXT_QUERY_IRI)),
3426            vec![
3427                Expression::Variable(spargebra::term::Variable::new_unchecked("note")),
3428                Expression::Literal(spargebra::term::Literal::new_simple_literal("laser")),
3429            ],
3430        );
3431        let PlanNode::LeftJoin { early_filter, .. } = &mut plan.root else {
3432            panic!("expected a LeftJoin root for the OPTIONAL");
3433        };
3434        *early_filter = Some(call);
3435        crate::TextPlannerPlugin::new(crate::TextPluginConfig {
3436            enabled: true,
3437            predicates: Vec::new(),
3438            ..crate::TextPluginConfig::default()
3439        })
3440        .rewrite(&mut plan.root, &trusted_ctx())
3441        .expect_err("a text:query in the LeftJoin condition slots must fail the plan");
3442    }
3443
3444    // ---- Graph-scope inheritance (invariant C): the subject resolve must
3445    // see exactly the graphs the surrounding BGP sees. The scope is copied
3446    // from a sibling scan; with no sibling anywhere in the branch, the
3447    // dataset's default window is the fallback (RdfDefault →
3448    // Some(DefaultGraph), AllGraphs → None), and inside GRAPH with no
3449    // pattern to stamp from the plan fails rather than guessing.
3450
3451    #[test]
3452    fn subject_mode_resolve_inherits_the_default_graph_scope() {
3453        let plan = rewrite_plan(
3454            "SELECT ?s WHERE {
3455                ?s <http://ex/livesIn> ?city .
3456                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3457            }",
3458        )
3459        .unwrap();
3460        let request = subject_request(find_subject_op(&plan.root).expect("resolve op"));
3461        // The sibling scan's shape: RdfDefault window grounds the unnamed
3462        // graph, no G-slot, no filter, no merge.
3463        assert_eq!(request.graph_name, Some(EncodedTerm::DefaultGraph));
3464        assert!(request.graph_filter_terms.is_empty());
3465        assert!(!request.graph_filter_allow);
3466        assert!(!request.merge_default_graph);
3467        assert!(!request.return_graph);
3468    }
3469
3470    #[test]
3471    fn subject_mode_resolve_inherits_a_single_from_graph_scope() {
3472        let plan = rewrite_plan(
3473            "SELECT ?s FROM <http://ex/g> WHERE {
3474                ?s <http://ex/livesIn> ?city .
3475                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3476            }",
3477        )
3478        .unwrap();
3479        let request = subject_request(find_subject_op(&plan.root).expect("resolve op"));
3480        // FROM <g> lowers Ground(g): the resolve must be restricted to that
3481        // graph, not see every graph.
3482        assert_eq!(
3483            request.graph_name,
3484            Some(EncodedTerm::from(
3485                &spargebra::term::NamedNode::new_unchecked("http://ex/g")
3486            ))
3487        );
3488    }
3489
3490    #[test]
3491    fn subject_mode_resolve_inherits_the_from_allow_scope() {
3492        let plan = rewrite_plan(
3493            "SELECT ?s FROM <http://ex/g1> FROM <http://ex/g2> WHERE {
3494                ?s <http://ex/livesIn> ?city .
3495                FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3496            }",
3497        )
3498        .unwrap();
3499        let request = subject_request(find_subject_op(&plan.root).expect("resolve op"));
3500        // Several FROM IRIs lower an allow-list: unbound G plus the filter,
3501        // merged like the lowering's own scans.
3502        assert_eq!(request.graph_name, None);
3503        assert!(!request.graph_filter_terms.is_empty());
3504        assert!(request.graph_filter_allow, "FROM windows are an allow-list");
3505        assert!(request.merge_default_graph);
3506    }
3507
3508    #[test]
3509    fn subject_mode_resolve_inherits_the_graph_variable_scope() {
3510        let plan = rewrite_plan(
3511            "SELECT ?g ?s WHERE {
3512                GRAPH ?g {
3513                    ?s <http://ex/bio> ?v .
3514                    FILTER(<http://jena.apache.org/text#query>(?s, <http://ex/bio>, \"mountain\"))
3515                }
3516            }",
3517        )
3518        .unwrap();
3519        let op = find_subject_op(&plan.root).expect("resolve op");
3520        let request = subject_request(op);
3521        // Inside GRAPH ?g the op binds the same G slot as the sibling and
3522        // blocks the unnamed graph — a subject in a graph other than the
3523        // one its bio triple lives in must not match.
3524        assert_eq!(request.graph_name, None);
3525        assert!(
3526            request.return_graph,
3527            "the graph variable asks for the column"
3528        );
3529        assert!(
3530            request
3531                .graph_filter_terms
3532                .contains(&EncodedTerm::DefaultGraph)
3533                && !request.graph_filter_allow,
3534            "the unnamed graph stays blocked"
3535        );
3536        // The G slot must be the SIBLING's variable, not a fresh one: both
3537        // sides join their G values through the same column.
3538        fn sibling_graph_slot(node: &PlanNode) -> Option<&waratah_storage::Variable> {
3539            match node {
3540                PlanNode::Scan(op) => op.graph.as_ref(),
3541                PlanNode::Filter { inner, .. } => sibling_graph_slot(inner),
3542                PlanNode::Join { left, right, .. } => {
3543                    sibling_graph_slot(left).or_else(|| sibling_graph_slot(right))
3544                }
3545                PlanNode::Union { left, right } => {
3546                    sibling_graph_slot(left).or_else(|| sibling_graph_slot(right))
3547                }
3548                PlanNode::JoinGraphVar { inner, .. } => sibling_graph_slot(inner),
3549                PlanNode::Distinct { inner, .. } => sibling_graph_slot(inner),
3550                _ => None,
3551            }
3552        }
3553        assert_eq!(
3554            op.variables.get(1),
3555            sibling_graph_slot(&plan.root),
3556            "the op and the sibling scan bind the same G slot"
3557        );
3558    }
3559
3560    /// Hand-built subject-mode filter over an empty input: exercises the
3561    /// no-sibling fallback (`inner` carries no scan to stamp from).
3562    fn rewrite_bare_subject_filter(
3563        ctx: &waratah_compute::QueryContext,
3564    ) -> Result<PlanNode, ComputeError> {
3565        installed();
3566        let call = Expression::FunctionCall(
3567            Function::Custom(spargebra::term::NamedNode::new_unchecked(TEXT_QUERY_IRI)),
3568            vec![
3569                Expression::Variable(spargebra::term::Variable::new_unchecked("s")),
3570                Expression::NamedNode(spargebra::term::NamedNode::new_unchecked("http://ex/bio")),
3571                Expression::Literal(spargebra::term::Literal::new_simple_literal("mountain")),
3572            ],
3573        );
3574        let mut node = PlanNode::Filter {
3575            inner: Box::new(PlanNode::Unit),
3576            early: None,
3577            residual: Some(call),
3578            exists: Vec::new(),
3579            one_to_one: false,
3580        };
3581        crate::TextPlannerPlugin::new(crate::TextPluginConfig {
3582            enabled: true,
3583            predicates: Vec::new(),
3584            ..crate::TextPluginConfig::default()
3585        })
3586        .rewrite(&mut node, ctx)?;
3587        Ok(node)
3588    }
3589
3590    #[test]
3591    fn subject_mode_without_a_sibling_pattern_leaves_the_graph_unbound() {
3592        // No triple/path pattern at the FILTER's level: the implicit text
3593        // triple has no graph context to inherit, so the resolve matches in
3594        // every graph (the unnamed graph included) instead of guessing the
3595        // dataset window.
3596        let node = rewrite_bare_subject_filter(&trusted_ctx()).unwrap();
3597        let request = subject_request(find_subject_op(&node).expect("resolve op"));
3598        assert_eq!(request.graph_name, None);
3599        assert!(request.graph_filter_terms.is_empty());
3600        assert!(!request.graph_filter_allow);
3601        assert!(!request.merge_default_graph);
3602        assert!(!request.return_graph);
3603    }
3604
3605    #[test]
3606    fn subject_mode_without_a_sibling_pattern_is_unbound_under_all_graphs() {
3607        // default-union ON: still no BGP to name a window, so the resolve is
3608        // unbound. The dataset's merge flag belongs to the default window;
3609        // an unbound resolve must not merge named graphs into it (that would
3610        // collapse the graph column and hide the graphs a match lives in).
3611        let ctx = trusted_ctx().with_default_union(true);
3612        let node = rewrite_bare_subject_filter(&ctx).unwrap();
3613        let request = subject_request(find_subject_op(&node).expect("resolve op"));
3614        assert_eq!(request.graph_name, None);
3615        assert!(request.graph_filter_terms.is_empty());
3616        assert!(!request.graph_filter_allow);
3617        assert!(!request.merge_default_graph);
3618        assert!(!request.return_graph);
3619    }
3620
3621    #[test]
3622    fn subject_mode_inside_graph_without_a_pattern_fails_the_plan() {
3623        // The degenerate scope: subject-mode text:query is the ONLY thing in
3624        // its GRAPH group, so nothing stamps the ?g scope and the dataset
3625        // window would answer from the wrong graphs. Fail the plan.
3626        let call = Expression::FunctionCall(
3627            Function::Custom(spargebra::term::NamedNode::new_unchecked(TEXT_QUERY_IRI)),
3628            vec![
3629                Expression::Variable(spargebra::term::Variable::new_unchecked("s")),
3630                Expression::NamedNode(spargebra::term::NamedNode::new_unchecked("http://ex/bio")),
3631                Expression::Literal(spargebra::term::Literal::new_simple_literal("mountain")),
3632            ],
3633        );
3634        let mut node = PlanNode::JoinGraphVar {
3635            inner: Box::new(PlanNode::Filter {
3636                inner: Box::new(PlanNode::Unit),
3637                early: None,
3638                residual: Some(call),
3639                exists: Vec::new(),
3640                one_to_one: false,
3641            }),
3642            graph_var: spargebra::term::Variable::new_unchecked("g"),
3643            active_var: spargebra::term::Variable::new_unchecked("__active_g"),
3644        };
3645        let error = crate::TextPlannerPlugin::new(crate::TextPluginConfig {
3646            enabled: true,
3647            predicates: Vec::new(),
3648            ..crate::TextPluginConfig::default()
3649        })
3650        .rewrite(&mut node, &trusted_ctx())
3651        .expect_err("an unstampable GRAPH scope must fail the plan");
3652        assert!(
3653            error
3654                .to_string()
3655                .contains("requires a triple pattern in the same graph group"),
3656            "the error names the limitation: {error}"
3657        );
3658    }
3659}