Skip to main content

waratah_text/
exec.rs

1//! Executor hook: answer one `text_scan` op with the matching literal terms,
2//! or one `text_subjects` op with the resolved `(subject, graph)` rows.
3//!
4//! `text_scan` is always childless and always emits exactly one variable — a
5//! value-typed variable: the literal variable in literal-mode rewrites (and
6//! in the `STRSTARTS` / `STRENDS` / anchored-`REGEX` candidate injection) or
7//! the literal variable the string functions compare. That op never sees
8//! subjects; pushed keys are always the literal values the decision is about.
9//! Four runtime roads mirror the geo executor, picked per execution by the
10//! request's mode and what the op carries:
11//!
12//! 1. **Pinned candidate** (`CustomOp.pinned`): the driver resolved to one
13//!    ground value.
14//! 2. **Direct evaluation**: the (deduped) pushed keys, decided in-process
15//!    with no candidate scan RPC, chosen by the stamped `CustomOpCost`
16//!    break-even over the actual key mix (`take_direct_road`; legacy count
17//!    fallback when unstamped). Seed modes only.
18//! 3. **Semi-join**: one candidate drain, then keep only the candidates in
19//!    the pushed key set.
20//! 4. **No pushed keys** (driver side): one candidate drain, emit every
21//!    candidate.
22//!
23//! `text_subjects` is the subject form's resolve node: also childless, but it
24//! emits `subject`, or `subject` + `graph` when the query binds the graph.
25//! Its whole answer comes from one `TextSubjectScan` — the partition searches
26//! the index AND walks the OPSG rows of every matched literal, so compute
27//! receives subjects rather than a literal carrier to join. Its only local
28//! work is the pushed-column semi-join (the RPC has no subject pre-filter)
29//! and pinned-column filtering; see [`execute_subjects`].
30//!
31//! Literal mode (`Fts`) answers **from the index** on every road: it asks
32//! "is this literal in the index's match set?", and since the predicate
33//! allowlist a local evaluation ("this value matches") is a different
34//! question — the value may sit under a predicate the index does not hold.
35//! Roads 1 and 2 therefore drain and filter for `Fts` too, so the answer
36//! cannot depend on the join seat or on a cardinality estimate. The
37//! candidate-injection modes (`Prefix` / `Suffix`) keep their exact conjunct
38//! in the residual, so a local evaluation of a pushed value is a sound
39//! SUPERSET and may answer in-process: roads 1–2 resolve each pushed value's
40//! lexical through one batched registry resolve and apply the bounded seed
41//! test. (The `scratch` FTS evaluator stays the in-memory twin of the index
42//! for tests; the executor does not call it for a literal-mode request.)
43//!
44//! Every drain path drains exactly once and is memoized per WINDOW on the
45//! engine side (`PluginEnv::text_candidates` → `QueryCaches::text_drains`):
46//! the candidate list is key-invariant, so behavior 3's "one drain" holds
47//! across the driver's WHOLE page sequence — page 1 drains, pages 2..N hit
48//! the memo. The direct and pinned roads never touch the window (their
49//! result is key-dependent). The surrounding hash join on the key variable
50//! already handles row multiplicity from the sibling side, so every branch
51//! emits one row per distinct matching term.
52//!
53//! The whole-result CustomOp memo covers repeats only for childless,
54//! unpinned, keyless executions; the drain memo below the plugin boundary
55//! covers every other repeat of the same window.
56
57use std::collections::HashSet;
58
59use waratah_compute::ComputeError;
60use waratah_compute::CustomOp;
61use waratah_compute::CustomOpCost;
62use waratah_compute::plugin::{ExecutorPlugin, PluginEnv, PluginPayload};
63use waratah_storage::{
64    EncodedTerm, StrHash, TextCandidateMode, TextSearchRequest, TextSubjectRequest,
65    encode_term_bytes,
66};
67
68use crate::rebuild::{document_for, hashes_of, is_text_term};
69
70/// `text_scan` op id on the CustomNode.
71pub const TEXT_SCAN_OP_ID: &str = "text_scan";
72
73/// Payload of one `text_scan` op.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct TextScanPayload {
76    /// The candidate request (mode, query, language, per-drain guard).
77    pub request: TextSearchRequest,
78    /// The analyzer the plan was rewritten under (menu value). The direct
79    /// evaluation roads build their scratch index with it; the plan-time
80    /// fingerprint comparison ties it to the partition's stored config.
81    pub analyzer: String,
82    /// The seed length the plan was rewritten under, for the seed-mode
83    /// string tests (the same bound the partition stores in its fields).
84    pub seed_chars: usize,
85}
86
87impl PluginPayload for TextScanPayload {
88    fn plugin_id(&self) -> &'static str {
89        crate::PLUGIN_ID
90    }
91
92    fn dyn_eq(&self, other: &dyn PluginPayload) -> bool {
93        other
94            .as_any()
95            .downcast_ref::<Self>()
96            .is_some_and(|other| *other == *self)
97    }
98}
99
100/// `text_subjects` op id on the CustomNode: the subject form's resolve node.
101pub const TEXT_SUBJECTS_OP_ID: &str = "text_subjects";
102
103/// Payload of one `text_subjects` op.
104///
105/// The executor hands [`Self::request`] to the O partition, which runs the
106/// candidate search and the literal→subject resolve itself. The planner
107/// builds the request from the branch's `AppliedGraph` — `graph_name`, the
108/// `graph_filter_terms` / `graph_filter_allow` pair (from
109/// `GraphFilter::to_wire`, which owns the allow/block polarity) and
110/// `merge_default_graph` — so the resolve sees the same graphs the
111/// surrounding BGP sees, and chooses the row shape in the same place:
112///
113/// - `variables = [subject]` with `return_graph: false` (no graph column);
114/// - `variables = [subject, graph]` with `return_graph: true` when every
115///   scope binds the same graph variable (the branch's solutions bind it);
116/// - `variables = [subject]` with `subject_equals_graph: true` when the
117///   graph variable IS the subject (`GRAPH ?s` plus `text:query(?s, …)`) —
118///   the partition keeps only rows whose subject equals their graph.
119///
120/// The executor rejects a request whose `return_graph` disagrees with the
121/// op's arity, so a builder that bound a graph variable but forgot the
122/// output column fails loudly instead of dropping the graph constraint.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct TextSubjectsPayload {
125    /// The subject resolve request: mode, query, language, guard, the named
126    /// predicates, and the applied graph window.
127    pub request: TextSubjectRequest,
128}
129
130impl PluginPayload for TextSubjectsPayload {
131    fn plugin_id(&self) -> &'static str {
132        crate::PLUGIN_ID
133    }
134
135    fn dyn_eq(&self, other: &dyn PluginPayload) -> bool {
136        other
137            .as_any()
138            .downcast_ref::<Self>()
139            .is_some_and(|other| *other == *self)
140    }
141}
142
143/// Execution hook for `text_scan`.
144#[derive(Debug, Default)]
145pub struct TextExecutorPlugin;
146
147impl ExecutorPlugin for TextExecutorPlugin {
148    fn execute<'a>(
149        &'a self,
150        op: &'a CustomOp,
151        env: PluginEnv<'a>,
152    ) -> waratah_compute::plugin::ExecuteFuture<'a> {
153        Box::pin(async move {
154            if op.op_id == TEXT_SUBJECTS_OP_ID {
155                return execute_subjects(op, env).await;
156            }
157            if op.op_id != TEXT_SCAN_OP_ID {
158                return Err(ComputeError::UnsupportedSparql(format!(
159                    "unknown text op {}",
160                    op.op_id
161                )));
162            }
163            if op.variables.len() != 1 {
164                return Err(ComputeError::UnsupportedSparql(
165                    "text_scan emits exactly one variable".into(),
166                ));
167            }
168            let Some(payload) = op.payload.downcast_ref::<TextScanPayload>() else {
169                return Err(ComputeError::UnsupportedSparql(
170                    "text_scan payload is not a TextScanPayload".into(),
171                ));
172            };
173            if !op.children.is_empty() {
174                return Err(ComputeError::UnsupportedSparql(
175                    "text_scan takes no children".into(),
176                ));
177            }
178            let output_variable = &op.variables[0];
179
180            // Literal mode answers "is this literal in the index's match
181            // set?" — the index defines that mode's universe, and since the
182            // predicate allowlist "this value matches" and "the index returns
183            // this value" are no longer the same question. Every road for
184            // `Fts` therefore drains and filters, so the answer cannot depend
185            // on the join seat. The candidate-injection modes (prefix /
186            // suffix) keep their exact conjunct in the residual, so a local
187            // evaluation of a pushed value is a sound SUPERSET and may answer
188            // in-process.
189            let answers_from_the_index = payload.request.mode == TextCandidateMode::Fts;
190            // 1. Pinned candidate (plan-stamped broadcast ground driver): a
191            //    seed mode evaluates exactly the driver's value; literal mode
192            //    tests it against the index's match set.
193            if let Some((_, pinned)) = op
194                .pinned
195                .iter()
196                .find(|(variable, _)| variable == output_variable)
197            {
198                if !answers_from_the_index {
199                    return evaluate_terms(std::slice::from_ref(pinned), payload, &env).await;
200                }
201                let candidates: Vec<EncodedTerm> = (env.text_candidates)(&payload.request).await?;
202                return Ok(candidates
203                    .into_iter()
204                    .filter(|term| term == pinned)
205                    .map(|term| vec![term])
206                    .collect());
207            }
208            let Some(keys) = env.pushed_vals else {
209                // 4. No pushed keys (driver side): the original sweep, one
210                // drain per window (memoized under the closure). The request
211                // carries its own per-drain guard; an over-limit window
212                // errors rather than truncating (dropped candidates would
213                // drop rows).
214                let candidates: Vec<EncodedTerm> = (env.text_candidates)(&payload.request).await?;
215                return Ok(candidates.into_iter().map(|term| vec![term]).collect());
216            };
217            // Pushed-key delivery: dedup once, then pick the road by the
218            // stamped cost model's break-even over the ACTUAL key mix
219            // (`take_direct_road`; legacy count fallback when unstamped).
220            let distinct: HashSet<&EncodedTerm> = keys.iter().collect();
221            let terms: Vec<EncodedTerm> = distinct.into_iter().cloned().collect();
222            if !answers_from_the_index
223                && take_direct_road(&terms, op.cost.as_ref(), op.produced_row_count_estimate)
224            {
225                // 2. Direct evaluation — no candidate scan RPC. Candidate
226                //    injection only: the residual still decides the row.
227                return evaluate_terms(&terms, payload, &env).await;
228            }
229            // 3. Semi-join: one candidate drain (behavior 4's sweep — the
230            // drain memo shares it across the driver's page sequence), then
231            // keep only the candidates in the key set. All compute-side; one
232            // scan call.
233            let key_set: HashSet<&EncodedTerm> = terms.iter().collect();
234            let candidates = (env.text_candidates)(&payload.request).await?;
235            let survivors: Vec<EncodedTerm> = candidates
236                .into_iter()
237                .filter(|term| key_set.contains(term))
238                .collect();
239            Ok(survivors.into_iter().map(|term| vec![term]).collect())
240        })
241    }
242}
243
244/// Resolve the subject form: one `TextSubjectScan` resolve, then the local
245/// semi-join on a pushed subject column.
246///
247/// The O partition does the work the compute-side arm joins used to do — it
248/// searches the index for the named predicates and walks the OPSG rows of
249/// every matched literal, returning DISTINCT `(subject, graph)` rows. This
250/// executor therefore has no local evaluation and no literal table: its only
251/// computation is dropping rows a pinned or pushed column already excludes.
252///
253/// Output schema: `variables[0]` is the subject; `variables[1]`, when the op
254/// has one, is the subject's graph. The request's `return_graph` decides the
255/// partition's row shape, so it MUST agree with that arity — a disagreement
256/// is a plan error, never a silently missing or extra column.
257///
258/// A pushed key list (the driver materialized the column) is an exact
259/// matching domain, applied to the column [`PluginEnv::pushed_variable`]
260/// names — subject or graph. Filtering the graph here is a valid semi-join
261/// (the surrounding join's other keys narrow further); the column name is
262/// what keeps an unlabelled term list from being read as subject keys, which
263/// would drop every row.
264async fn execute_subjects(
265    op: &CustomOp,
266    env: PluginEnv<'_>,
267) -> Result<Vec<Vec<EncodedTerm>>, ComputeError> {
268    let Some(payload) = op.payload.downcast_ref::<TextSubjectsPayload>() else {
269        return Err(ComputeError::UnsupportedSparql(
270            "text_subjects payload is not a TextSubjectsPayload".into(),
271        ));
272    };
273    if !op.children.is_empty() {
274        return Err(ComputeError::UnsupportedSparql(
275            "text_subjects takes no children".into(),
276        ));
277    }
278    if op.variables.is_empty() || op.variables.len() > 2 {
279        return Err(ComputeError::UnsupportedSparql(format!(
280            "text_subjects emits one or two variables (subject, optional graph), got {}",
281            op.variables.len()
282        )));
283    }
284    let subject_variable = &op.variables[0];
285    let graph_variable = op.variables.get(1);
286    let return_graph = graph_variable.is_some();
287    if payload.request.return_graph != return_graph {
288        return Err(ComputeError::UnsupportedSparql(format!(
289            "text_subjects output schema and payload disagree about the graph column: \
290             the op emits {} variable(s), the request has return_graph = {}",
291            op.variables.len(),
292            payload.request.return_graph
293        )));
294    }
295
296    let window = (env.text_subjects)(&payload.request).await?;
297    let subject_keys =
298        allowed_column_terms(op, subject_variable, env.pushed_vals, env.pushed_variable);
299    // The graph column is only membership-tested, so a set is the right
300    // shape; the ordered list is for the subject column's emission order.
301    let graph_keys = graph_variable
302        .and_then(|graph| allowed_column_terms(op, graph, env.pushed_vals, env.pushed_variable))
303        .map(|terms| terms.into_iter().collect::<HashSet<_>>());
304
305    let mut out = Vec::with_capacity(window.len());
306    if let Some(subjects) = &subject_keys {
307        // Probe: answer from the pushed/pinned subject list. The window's
308        // binary search replaces a scan of every resolved row per page; the
309        // emitted term is the pushed one (same interned identity). The list
310        // is ordered (pinned first, then the driver's distinct-value order),
311        // so the emitted rows do not depend on a hash seed.
312        for subject in subjects {
313            if !window.contains_subject(subject) {
314                continue;
315            }
316            if return_graph {
317                for graph in window.graphs_for(subject)? {
318                    if graph_keys
319                        .as_ref()
320                        .is_some_and(|keys| !keys.contains(&graph))
321                    {
322                        continue;
323                    }
324                    out.push(vec![subject.clone(), graph]);
325                }
326            } else {
327                out.push(vec![subject.clone()]);
328            }
329        }
330    } else {
331        // Keyless (driver side): emit the whole window, chunk-decoded.
332        for row in window.rows() {
333            let row = row?;
334            let graph_column = if return_graph {
335                let Some(graph) = row.graph else {
336                    return Err(ComputeError::Internal(
337                        "text_subjects returned a row without its requested graph column".into(),
338                    ));
339                };
340                if graph_keys
341                    .as_ref()
342                    .is_some_and(|keys| !keys.contains(&graph))
343                {
344                    continue;
345                }
346                Some(graph)
347            } else {
348                None
349            };
350            out.push(match graph_column {
351                Some(graph) => vec![row.subject, graph],
352                None => vec![row.subject],
353            });
354        }
355    }
356    Ok(out)
357}
358
359/// The exact allowed value list for one output column, from the op's pinned
360/// bindings (a ground driver) and the driver's pushed key list (when it
361/// belongs to this column). `None` means the column is unconstrained.
362///
363/// Both constraints are memberships on the same column, so a column that has
364/// both keeps their intersection. The result is ORDERED and deduped: pinned
365/// terms first (their plan order), then the driver's distinct-value order.
366/// The probe road iterates this list, so the emitted row order is the
367/// driver's order rather than a hash-set order — `LIMIT` without `ORDER BY`
368/// and golden outputs stay reproducible across runs.
369fn allowed_column_terms(
370    op: &CustomOp,
371    variable: &waratah_storage::Variable,
372    pushed_vals: Option<&[EncodedTerm]>,
373    pushed_variable: Option<&waratah_storage::Variable>,
374) -> Option<Vec<EncodedTerm>> {
375    let pinned: Vec<&EncodedTerm> = op
376        .pinned
377        .iter()
378        .filter(|(pinned_variable, _)| pinned_variable == variable)
379        .map(|(_, term)| term)
380        .collect();
381    let pushed = pushed_variable
382        .filter(|pushed| *pushed == variable)
383        .and(pushed_vals);
384    match (pinned.is_empty(), pushed) {
385        // No constraint on this column: unconstrained (the keyless road).
386        (true, None) => None,
387        // Driver-side push only: keep the pushed order, drop repeats. An
388        // empty list is an empty matching domain, not "no filter".
389        (true, Some(pushed)) => {
390            let mut seen = HashSet::with_capacity(pushed.len());
391            let mut terms = Vec::with_capacity(pushed.len());
392            for term in pushed {
393                if seen.insert(term) {
394                    terms.push(term.clone());
395                }
396            }
397            Some(terms)
398        }
399        // Pinned only: a ground driver's single term, in plan order.
400        (false, None) => {
401            let mut seen = HashSet::with_capacity(pinned.len());
402            let mut terms = Vec::with_capacity(pinned.len());
403            for term in pinned {
404                if seen.insert(term) {
405                    terms.push(term.clone());
406                }
407            }
408            Some(terms)
409        }
410        // Both: the intersection, in pinned order. A column can be pinned
411        // at most once per variable, so the scan over the pushed list runs
412        // at most once.
413        (false, Some(pushed)) => {
414            let mut seen = HashSet::with_capacity(pinned.len());
415            let mut terms = Vec::with_capacity(pinned.len());
416            for term in pinned {
417                if pushed.iter().any(|candidate| candidate == term) && seen.insert(term) {
418                    terms.push(term.clone());
419                }
420            }
421            Some(terms)
422        }
423    }
424}
425
426/// LEGACY fallback only: for a seed-mode op WITHOUT a stamped `CustomOpCost`,
427/// pushed key lists at or below this length evaluate directly (behavior 2)
428/// and larger ones take the drain + semi-join (behavior 3). Stamped ops
429/// decide by the cost-model break-even over the actual key mix instead
430/// (`take_direct_road`). Literal mode never uses either road: it always
431/// drains the index.
432const TEXT_DIRECT_EVALUATE_LIMIT: usize = 500;
433
434/// The keyed-regime road for a seed mode: evaluate the deduped driver keys
435/// directly (behavior 2), or drain once and semi-join before filtering
436/// (behavior 3)? Literal mode skips this choice — its answer is the index's
437/// match set, so it always drains and filters.
438///
439/// The geo executor's `take_direct_road` is the reference pricing of the
440/// keyed regime; the text variant prices every key alike (one local
441/// evaluation — tokenize + decide — regardless of shape), so with a stamped
442/// [`CustomOpCost`] the choice is `keys × per_key_unit` against
443/// `drain_rows + min(keys, sweep) × per_key_unit`. An op without a stamp
444/// falls back to the legacy deduped-count limit: at or below
445/// [`TEXT_DIRECT_EVALUATE_LIMIT`] keys evaluate directly.
446fn take_direct_road(
447    deduped_keys: &[EncodedTerm],
448    cost: Option<&CustomOpCost>,
449    sweep_rows: u64,
450) -> bool {
451    let Some(cost) = cost else {
452        return deduped_keys.len() <= TEXT_DIRECT_EVALUATE_LIMIT;
453    };
454    let keys = deduped_keys.len() as u64;
455    if keys == 0 {
456        return true;
457    }
458    let direct = keys.saturating_mul(cost.per_key_unit);
459    let semi_join = cost
460        .drain_rows
461        .saturating_add(keys.min(sweep_rows).saturating_mul(cost.per_key_unit));
462    direct <= semi_join
463}
464
465/// Direct evaluation of `terms` against the op's request — the seed modes'
466/// pinned and pushed-key roads. One batched registry resolve covers the
467/// big-literal
468/// variants; a non-string term never matches and is skipped without error:
469/// the index never carried one, and sibling join bindings may legitimately
470/// carry any term (the same epistemics as the geo executor's non-geo keys).
471/// A registry miss also skips the value: without its lexical it cannot be
472/// analyzed, and the sweep road's index could not have returned it either.
473async fn evaluate_terms(
474    terms: &[EncodedTerm],
475    payload: &TextScanPayload,
476    env: &PluginEnv<'_>,
477) -> Result<Vec<Vec<EncodedTerm>>, ComputeError> {
478    let hashes: Vec<StrHash> = terms.iter().flat_map(hashes_of).collect();
479    let resolved = if hashes.is_empty() {
480        Vec::new()
481    } else {
482        (env.strings)(&hashes).await?
483    };
484    let mut docs = Vec::with_capacity(terms.len());
485    let mut offset = 0usize;
486    for term in terms {
487        let needed = hashes_of(term).len();
488        let slice = &resolved[offset..offset + needed];
489        offset += needed;
490        if is_text_term(term) {
491            if let Some(doc) = document_for(term, slice) {
492                docs.push(doc);
493            }
494        } else {
495            // Positional bookkeeping: hashes_of returns empty for
496            // non-string terms, so the slice stays aligned either way.
497            debug_assert_eq!(needed, 0);
498        }
499    }
500    let matched: HashSet<Vec<u8>> = match payload.request.mode {
501        TextCandidateMode::Fts => waratah_text_index::scratch::evaluate_fts(
502            &payload.request,
503            &payload.analyzer,
504            payload.seed_chars,
505            &docs,
506        ),
507        TextCandidateMode::Prefix | TextCandidateMode::Suffix => {
508            waratah_text_index::scratch::evaluate_seed(&payload.request, payload.seed_chars, &docs)
509        }
510    }
511    .map_err(|error| {
512        ComputeError::UnsupportedSparql(format!("text candidate evaluation failed: {error}"))
513    })?
514    .into_iter()
515    .collect();
516    // Currency: match by encoded term bytes, emit the original terms.
517    Ok(terms
518        .iter()
519        .filter(|term| matched.contains(&encode_term_bytes(term)))
520        .map(|term| vec![(*term).clone()])
521        .collect())
522}
523
524/// The `text:query` registration payload: a lowering pass-through.
525///
526/// The function exists on the custom-function map ONLY so `split_filter`
527/// classifies the IRI (AlwaysResolve → residual) instead of erroring
528/// `Unsupported` before the planner sees it. The planner strips it when the
529/// index is trusted; when it is not, this evaluation runs and fails the
530/// query with the repair hint — the deliberate deviation from geo/temporal:
531/// `text:query` has no per-row evaluation to fall back on, and returning
532/// zero rows from an unusable index (the trusted-but-empty state) is
533/// forbidden.
534pub fn text_query_eval_ground(_args: &[oxrdf::Term]) -> waratah_compute::CustomEval {
535    // Per-row SPARQL type error. This fires ONLY if a text:query conjunct
536    // survived the planner walk (a plugin bug): the planner hard-fails every
537    // shape it cannot rewrite, so this backstop must never decide answers —
538    // a per-row error that silently filters rows would be the
539    // trusted-but-empty state by the back door.
540    waratah_compute::CustomEval::Error
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546    use crate::config::TextPluginConfig;
547    use waratah_compute::plugin::PluginPayloadBox;
548    use waratah_compute::{TextSubjectWindow, TextSubjectWindowBuilder};
549    use waratah_storage::{SnapshotId, StrHash, Variable};
550
551    /// Build the window the engine's `text_subjects` closure returns: the
552    /// test's rows interned into a dictionary, shared by `Arc`. The executor
553    /// then exercises the real membership / binary-search and chunk-decode
554    /// paths instead of a mock row list.
555    fn subject_window(
556        rows: Vec<waratah_storage::TextSubjectRow>,
557    ) -> std::sync::Arc<TextSubjectWindow> {
558        let with_graph = rows.iter().any(|row| row.graph.is_some());
559        let mut builder = TextSubjectWindowBuilder::new(
560            std::sync::Arc::new(waratah_compute::TermDict::new()),
561            with_graph,
562        );
563        for row in rows {
564            builder.push(row).expect("test subject rows intern");
565        }
566        std::sync::Arc::new(builder.finish())
567    }
568
569    fn payload(request: TextSearchRequest) -> PluginPayloadBox {
570        PluginPayloadBox::new(TextScanPayload {
571            request,
572            analyzer: crate::TextPluginConfig::default().analyzer,
573            seed_chars: crate::TextPluginConfig::default().seed_chars,
574        })
575    }
576
577    fn op(request: TextSearchRequest) -> CustomOp {
578        CustomOp {
579            plugin_id: crate::PLUGIN_ID,
580            op_id: TEXT_SCAN_OP_ID,
581            payload: payload(request),
582            children: Vec::new(),
583            variables: vec![Variable::new_unchecked("lit")],
584            produced_row_count_estimate: 10,
585            cost: None,
586            pinned: Vec::new(),
587        }
588    }
589
590    /// One mock env per test scope (the geo tests' pattern): local closures,
591    /// local op, one direct `execute` call — no helper fn crossing
592    /// lifetimes. `$candidates` is the drained `Vec<EncodedTerm>` window;
593    /// `$pushed` is the `Option<&[EncodedTerm]>` for
594    /// [`PluginEnv::pushed_vals`]; the optional `$strings` map answers the
595    /// registry resolves (default: everything misses).
596    macro_rules! mock_env {
597        ($candidates:expr, $pushed:expr => $env:ident) => {
598            mock_env!($candidates, $pushed, [] => $env);
599        };
600        ($candidates:expr, $pushed:expr, $strings:expr => $env:ident) => {
601            let candidates_window: Vec<EncodedTerm> = ($candidates).clone();
602            let text_candidates = |_: &TextSearchRequest| {
603                let out = candidates_window.clone();
604                Box::pin(std::future::ready(Ok(out)))
605                    as std::pin::Pin<
606                        Box<
607                            dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>>
608                                + Send,
609                        >,
610                    >
611            };
612            let text_subjects = |_: &TextSubjectRequest| {
613                let out = subject_window(Vec::new());
614                Box::pin(std::future::ready(Ok(out)))
615                    as std::pin::Pin<
616                        Box<
617                            dyn std::future::Future<
618                                    Output = Result<
619                                        std::sync::Arc<TextSubjectWindow>,
620                                        ComputeError,
621                                    >,
622                                > + Send,
623                        >,
624                    >
625            };
626            let geo_candidates = |_: &[waratah_storage::GeoCellInterval],
627                                  _: Option<waratah_storage::GeoEnvelope>,
628                                  _: u64| {
629                let out = Vec::new();
630                Box::pin(std::future::ready(Ok(out)))
631                    as std::pin::Pin<
632                        Box<
633                            dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>>
634                                + Send,
635                        >,
636                    >
637            };
638            let temporal_candidates = |_: &[waratah_storage::TemporalCellInterval],
639                                       _: waratah_storage::TemporalQueryPredicate,
640                                       _: u64| {
641                let out = Vec::new();
642                Box::pin(std::future::ready(Ok(out)))
643                    as std::pin::Pin<
644                        Box<
645                            dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>>
646                                + Send,
647                        >,
648                    >
649            };
650            let blobs_fn = |_: &[StrHash]| {
651                let out: Vec<Option<Vec<u8>>> = Vec::new();
652                Box::pin(std::future::ready(Ok(out)))
653                    as std::pin::Pin<
654                        Box<
655                            dyn std::future::Future<
656                                    Output = Result<Vec<Option<Vec<u8>>>, ComputeError>,
657                                > + Send,
658                        >,
659                    >
660            };
661            let strings_map: std::collections::HashMap<StrHash, String> = ($strings)
662                .into_iter()
663                .collect();
664            let strings_fn = move |ids: &[StrHash]| {
665                let out: Vec<Option<String>> = ids
666                    .iter()
667                    .map(|id| strings_map.get(id).cloned())
668                    .collect();
669                Box::pin(std::future::ready(Ok(out)))
670                    as std::pin::Pin<
671                        Box<
672                            dyn std::future::Future<
673                                    Output = Result<Vec<Option<String>>, ComputeError>,
674                                > + Send,
675                        >,
676                    >
677            };
678            let $env = PluginEnv {
679                snapshot: SnapshotId::latest(),
680                geo_candidates: &geo_candidates,
681                temporal_candidates: &temporal_candidates,
682                text_candidates: &text_candidates,
683                text_subjects: &text_subjects,
684                blobs: &blobs_fn,
685                strings: &strings_fn,
686                pushed_vals: $pushed,
687                pushed_variable: None,
688            };
689        };
690    }
691
692    /// Same as [`mock_env!`], but the candidate drain PANICS: the direct and
693    /// pinned roads must never touch the window.
694    macro_rules! mock_env_no_drain {
695        ($pushed:expr => $env:ident) => {
696            let text_candidates = |_: &TextSearchRequest| -> std::pin::Pin<
697                Box<
698                    dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>> + Send,
699                >,
700            > {
701                panic!("direct evaluation must not drain the candidate window");
702            };
703            let text_subjects = |_: &TextSubjectRequest| {
704                let out = subject_window(Vec::new());
705                Box::pin(std::future::ready(Ok(out)))
706                    as std::pin::Pin<
707                        Box<
708                            dyn std::future::Future<
709                                    Output = Result<
710                                        std::sync::Arc<TextSubjectWindow>,
711                                        ComputeError,
712                                    >,
713                                > + Send,
714                        >,
715                    >
716            };
717            let geo_candidates = |_: &[waratah_storage::GeoCellInterval],
718                                  _: Option<waratah_storage::GeoEnvelope>,
719                                  _: u64| {
720                let out = Vec::new();
721                Box::pin(std::future::ready(Ok(out)))
722                    as std::pin::Pin<
723                        Box<
724                            dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>>
725                                + Send,
726                        >,
727                    >
728            };
729            let temporal_candidates = |_: &[waratah_storage::TemporalCellInterval],
730                                       _: waratah_storage::TemporalQueryPredicate,
731                                       _: u64| {
732                let out = Vec::new();
733                Box::pin(std::future::ready(Ok(out)))
734                    as std::pin::Pin<
735                        Box<
736                            dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>>
737                                + Send,
738                        >,
739                    >
740            };
741            let blobs_fn = |_: &[StrHash]| {
742                let out: Vec<Option<Vec<u8>>> = Vec::new();
743                Box::pin(std::future::ready(Ok(out)))
744                    as std::pin::Pin<
745                        Box<
746                            dyn std::future::Future<
747                                    Output = Result<Vec<Option<Vec<u8>>>, ComputeError>,
748                                > + Send,
749                        >,
750                    >
751            };
752            let strings_fn = |_: &[StrHash]| {
753                let out: Vec<Option<String>> = Vec::new();
754                Box::pin(std::future::ready(Ok(out)))
755                    as std::pin::Pin<
756                        Box<
757                            dyn std::future::Future<
758                                    Output = Result<Vec<Option<String>>, ComputeError>,
759                                > + Send,
760                        >,
761                    >
762            };
763            let $env = PluginEnv {
764                snapshot: SnapshotId::latest(),
765                geo_candidates: &geo_candidates,
766                temporal_candidates: &temporal_candidates,
767                text_candidates: &text_candidates,
768                text_subjects: &text_subjects,
769                blobs: &blobs_fn,
770                strings: &strings_fn,
771                pushed_vals: $pushed,
772                pushed_variable: None,
773            };
774        };
775    }
776
777    /// Env for the `text_subjects` tests: `$rows` is the resolve window the
778    /// mock partition returns, and `$pushed` / `$pushed_var` are the driver's
779    /// push (the text-candidate drain and the other plugin drains are never
780    /// called by that op, so they answer empty).
781    macro_rules! mock_subject_env {
782        ($rows:expr, $pushed:expr, $pushed_var:expr => $env:ident) => {
783            let rows_window = subject_window(($rows).clone());
784            let text_subjects = move |_: &TextSubjectRequest| {
785                let out = std::sync::Arc::clone(&rows_window);
786                Box::pin(std::future::ready(Ok(out)))
787                    as std::pin::Pin<
788                        Box<
789                            dyn std::future::Future<
790                                    Output = Result<
791                                        std::sync::Arc<TextSubjectWindow>,
792                                        ComputeError,
793                                    >,
794                                > + Send,
795                        >,
796                    >
797            };
798            let text_candidates = |_: &TextSearchRequest| {
799                let out: Vec<EncodedTerm> = Vec::new();
800                Box::pin(std::future::ready(Ok(out)))
801                    as std::pin::Pin<
802                        Box<
803                            dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>>
804                                + Send,
805                        >,
806                    >
807            };
808            let geo_candidates = |_: &[waratah_storage::GeoCellInterval],
809                                  _: Option<waratah_storage::GeoEnvelope>,
810                                  _: u64| {
811                let out = Vec::new();
812                Box::pin(std::future::ready(Ok(out)))
813                    as std::pin::Pin<
814                        Box<
815                            dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>>
816                                + Send,
817                        >,
818                    >
819            };
820            let temporal_candidates = |_: &[waratah_storage::TemporalCellInterval],
821                                       _: waratah_storage::TemporalQueryPredicate,
822                                       _: u64| {
823                let out = Vec::new();
824                Box::pin(std::future::ready(Ok(out)))
825                    as std::pin::Pin<
826                        Box<
827                            dyn std::future::Future<Output = Result<Vec<EncodedTerm>, ComputeError>>
828                                + Send,
829                        >,
830                    >
831            };
832            let blobs_fn = |_: &[StrHash]| {
833                let out: Vec<Option<Vec<u8>>> = Vec::new();
834                Box::pin(std::future::ready(Ok(out)))
835                    as std::pin::Pin<
836                        Box<
837                            dyn std::future::Future<
838                                    Output = Result<Vec<Option<Vec<u8>>>, ComputeError>,
839                                > + Send,
840                        >,
841                    >
842            };
843            let strings_fn = |_: &[StrHash]| {
844                let out: Vec<Option<String>> = Vec::new();
845                Box::pin(std::future::ready(Ok(out)))
846                    as std::pin::Pin<
847                        Box<
848                            dyn std::future::Future<
849                                    Output = Result<Vec<Option<String>>, ComputeError>,
850                                > + Send,
851                        >,
852                    >
853            };
854            let $env = PluginEnv {
855                snapshot: SnapshotId::latest(),
856                geo_candidates: &geo_candidates,
857                temporal_candidates: &temporal_candidates,
858                text_candidates: &text_candidates,
859                text_subjects: &text_subjects,
860                blobs: &blobs_fn,
861                strings: &strings_fn,
862                pushed_vals: $pushed,
863                pushed_variable: $pushed_var,
864            };
865        };
866    }
867
868    fn term(n: u8) -> EncodedTerm {
869        EncodedTerm::from(&oxrdf::Literal::new_simple_literal(format!("t{n}")))
870    }
871
872    fn term_idx(n: usize) -> EncodedTerm {
873        EncodedTerm::from(&oxrdf::Literal::new_simple_literal(format!("k{n}")))
874    }
875
876    #[tokio::test]
877    async fn driver_road_emits_every_candidate() {
878        let candidates = vec![term(1), term(2)];
879        mock_env!(candidates, None => env);
880        let rows = TextExecutorPlugin
881            .execute(&op(TextSearchRequest::fts("x")), env)
882            .await
883            .unwrap();
884        assert_eq!(rows, vec![vec![term(1)], vec![term(2)]]);
885    }
886
887    #[tokio::test]
888    async fn semi_join_road_keeps_only_the_pushed_key_survivors() {
889        // A stamped cost whose break-even picks the drain road: direct =
890        // 2 keys × 1; semi-join = 0 drain + min(2 keys, sweep 1) × 1 = 1.
891        let candidates = vec![term(1), term(2), term(3)];
892        let pushed = vec![term(2), term(9)];
893        mock_env!(candidates, Some(pushed.as_slice()) => env);
894        let mut semi = op(TextSearchRequest::fts("x"));
895        semi.produced_row_count_estimate = 1;
896        semi.cost = Some(waratah_compute::CustomOpCost {
897            drain_rows: 0,
898            per_key_unit: 1,
899            inline_point_unit: 1,
900            direct_probe: true,
901            // Literal mode filters its drained candidate window by scan.
902            probe_keyed_columns: 0,
903            probe_filter_unit: 1,
904            probe_memo_entry_rows: 0,
905        });
906        let rows = TextExecutorPlugin.execute(&semi, env).await.unwrap();
907        assert_eq!(rows, vec![vec![term(2)]]);
908    }
909
910    #[tokio::test]
911    async fn fts_pushed_keys_answer_from_the_index_not_the_local_match() {
912        // Literal mode is scoped to the indexed universe. `term(9)` matches
913        // the query locally but the index's match set is empty, so it must
914        // not survive; the local evaluation would have kept it.
915        let candidates: Vec<EncodedTerm> = Vec::new();
916        let pushed = vec![term(9)];
917        mock_env!(candidates, Some(pushed.as_slice()) => env);
918        let rows = TextExecutorPlugin
919            .execute(&op(TextSearchRequest::fts("t9")), env)
920            .await
921            .unwrap();
922        assert!(
923            rows.is_empty(),
924            "a pushed literal outside the index's match set must be dropped"
925        );
926    }
927
928    #[tokio::test]
929    async fn direct_seed_road_matches_by_the_bounded_seed() {
930        // STRSTARTS-style candidate test on the pushed values: the prefix
931        // seed matches "t2" but not "t9".
932        let pushed = vec![term(2), term(9)];
933        mock_env_no_drain!(Some(pushed.as_slice()) => env);
934        let rows = TextExecutorPlugin
935            .execute(&op(TextSearchRequest::prefix("t2")), env)
936            .await
937            .unwrap();
938        assert_eq!(rows, vec![vec![term(2)]]);
939    }
940
941    #[tokio::test]
942    async fn fts_pinned_value_is_membership_tested() {
943        let pinned = term(1);
944        let mut hit = op(TextSearchRequest::fts("t1"));
945        hit.pinned
946            .push((Variable::new_unchecked("lit"), pinned.clone()));
947        mock_env!(vec![pinned.clone()], None => env);
948        assert_eq!(
949            TextExecutorPlugin.execute(&hit, env).await.unwrap(),
950            vec![vec![pinned.clone()]]
951        );
952
953        let mut miss = op(TextSearchRequest::fts("t1"));
954        miss.pinned.push((Variable::new_unchecked("lit"), term(7)));
955        mock_env!(vec![pinned], None => env);
956        assert!(
957            TextExecutorPlugin
958                .execute(&miss, env)
959                .await
960                .unwrap()
961                .is_empty(),
962            "a pinned literal outside the index's match set must be dropped"
963        );
964    }
965
966    #[tokio::test]
967    async fn pinned_seed_value_evaluates_without_draining() {
968        // A seed mode keeps its residual, so the pinned value is decided
969        // in-process.
970        let mut pinned = op(TextSearchRequest::prefix("t1"));
971        pinned
972            .pinned
973            .push((Variable::new_unchecked("lit"), term(1)));
974        mock_env_no_drain!(None => env);
975        assert_eq!(
976            TextExecutorPlugin.execute(&pinned, env).await.unwrap(),
977            vec![vec![term(1)]]
978        );
979    }
980
981    fn small(value: &str) -> waratah_storage::SmallString {
982        value.parse().expect("short inline string")
983    }
984
985    #[tokio::test]
986    async fn lang_tagged_values_match_only_their_language() {
987        // The scratch FTS evaluator carries the pushed value's language tag.
988        // Literal mode answers from the index, so this drives the evaluator
989        // directly.
990        let french = EncodedTerm::SmallSmallLangStringLiteral {
991            value: small("salut"),
992            language: small("fr"),
993        };
994        let pushed = vec![french.clone()];
995        let request_for = |language: Option<&str>| TextSearchRequest {
996            mode: TextCandidateMode::Fts,
997            query: "salut".to_owned(),
998            language: language.map(str::to_owned),
999            limit: 0,
1000        };
1001        let evaluate = |request| {
1002            let boxed = payload(request);
1003            let terms = pushed.clone();
1004            async move {
1005                let payload = boxed
1006                    .downcast_ref::<TextScanPayload>()
1007                    .expect("text payload");
1008                mock_env_no_drain!(None => env);
1009                evaluate_terms(&terms, payload, &env).await.unwrap()
1010            }
1011        };
1012        // Restricted to its own tag: match.
1013        assert_eq!(
1014            evaluate(request_for(Some("fr"))).await,
1015            vec![vec![french.clone()]]
1016        );
1017        // Restricted to another tag: no match — the lang field of the
1018        // scratch document carries the pushed value's tag.
1019        assert!(evaluate(request_for(Some("en"))).await.is_empty());
1020        // Unrestricted: match.
1021        assert_eq!(evaluate(request_for(None)).await, vec![vec![french]]);
1022    }
1023
1024    #[tokio::test]
1025    async fn big_literal_values_resolve_through_the_registry() {
1026        // A big plain literal carries only its value hash: the direct road
1027        // resolves the lexical through one batched registry call, then
1028        // evaluates it like any other value.
1029        let big = EncodedTerm::BigStringLiteral {
1030            value_id: StrHash::new("laser printer"),
1031        };
1032        let pushed = vec![big.clone()];
1033        mock_env!(Vec::new(), Some(pushed.as_slice()),
1034            [(StrHash::new("laser printer"), "laser printer".to_owned())] => env);
1035        let rows = TextExecutorPlugin
1036            .execute(&op(TextSearchRequest::prefix("laser")), env)
1037            .await
1038            .unwrap();
1039        assert_eq!(rows, vec![vec![big.clone()]]);
1040        // A registry miss skips the value: without its lexical it cannot be
1041        // analyzed (and the sweep road could not have returned it either).
1042        mock_env!(Vec::new(), Some(pushed.as_slice()) => env);
1043        let rows = TextExecutorPlugin
1044            .execute(&op(TextSearchRequest::prefix("laser")), env)
1045            .await
1046            .unwrap();
1047        assert!(rows.is_empty());
1048    }
1049
1050    #[tokio::test]
1051    async fn non_string_pushed_values_are_skipped_not_errors() {
1052        // Sibling join bindings may carry any term; a non-string never
1053        // matches (the index never carried one) — skip, not error.
1054        let iri = EncodedTerm::NamedNode {
1055            iri_id: StrHash::new("http://ex/thing"),
1056        };
1057        let pushed = vec![term(2), iri.clone()];
1058        mock_env_no_drain!(Some(pushed.as_slice()) => env);
1059        let rows = TextExecutorPlugin
1060            .execute(&op(TextSearchRequest::prefix("t2")), env)
1061            .await
1062            .unwrap();
1063        assert_eq!(rows, vec![vec![term(2)]]);
1064    }
1065
1066    #[test]
1067    fn the_break_even_picks_the_cheap_road() {
1068        let cost = waratah_compute::CustomOpCost {
1069            drain_rows: 1_000,
1070            per_key_unit: 1,
1071            inline_point_unit: 1,
1072            direct_probe: true,
1073            // Literal mode filters its drained candidate window by scan.
1074            probe_keyed_columns: 0,
1075            probe_filter_unit: 1,
1076            probe_memo_entry_rows: 0,
1077        };
1078        // Few keys against a wide window: direct wins (2 vs 1002).
1079        assert!(take_direct_road(
1080            &[term(1), term(2)],
1081            Some(&cost),
1082            1_000_000
1083        ));
1084        // Many keys against a narrow window: drain + filter wins
1085        // (2000 direct vs 1000 drain + 500 survivors).
1086        let many: Vec<EncodedTerm> = (0..2000).map(term_idx).collect();
1087        assert!(!take_direct_road(&many, Some(&cost), 500));
1088        // Legacy fallback without a stamp: the deduped-count limit.
1089        assert!(take_direct_road(&[term(1)], None, 0));
1090        assert!(!take_direct_road(&vec![term(1); 501], None, 0));
1091        // Zero keys: nothing to drain for.
1092        assert!(take_direct_road(&[], Some(&cost), 0));
1093    }
1094
1095    #[test]
1096    fn payload_equality_follows_the_request() {
1097        let a = payload(TextSearchRequest::prefix("ab"));
1098        let b = payload(TextSearchRequest::prefix("ab"));
1099        let c = payload(TextSearchRequest::suffix("ba"));
1100        assert_eq!(a, b);
1101        assert_ne!(a, c);
1102    }
1103
1104    #[test]
1105    fn the_pass_through_eval_is_the_row_error_backstop() {
1106        // The planner hard-fails untrusted / unrewritable text:query before
1107        // this fires; the backstop must be an error, never a false answer.
1108        assert!(matches!(
1109            text_query_eval_ground(&[]),
1110            waratah_compute::CustomEval::Error
1111        ));
1112    }
1113
1114    fn subject_row(subject: u8, graph: Option<u8>) -> waratah_storage::TextSubjectRow {
1115        waratah_storage::TextSubjectRow {
1116            subject: EncodedTerm::from(
1117                &oxrdf::NamedNode::new(format!("http://ex/s{subject}")).unwrap(),
1118            ),
1119            graph: graph.map(|g| {
1120                EncodedTerm::from(&oxrdf::NamedNode::new(format!("http://ex/g{g}")).unwrap())
1121            }),
1122        }
1123    }
1124
1125    fn subject_request(return_graph: bool) -> TextSubjectRequest {
1126        TextSubjectRequest {
1127            mode: TextCandidateMode::Fts,
1128            query: "report".to_owned(),
1129            language: None,
1130            limit: 0,
1131            predicates: Vec::new(),
1132            graph_name: None,
1133            graph_filter_terms: Vec::new(),
1134            graph_filter_allow: false,
1135            merge_default_graph: false,
1136            subject_equals_graph: false,
1137            return_graph,
1138        }
1139    }
1140
1141    fn subject_op(request: TextSubjectRequest, variables: Vec<Variable>) -> CustomOp {
1142        CustomOp {
1143            plugin_id: crate::PLUGIN_ID,
1144            op_id: TEXT_SUBJECTS_OP_ID,
1145            payload: PluginPayloadBox::new(TextSubjectsPayload { request }),
1146            children: Vec::new(),
1147            variables,
1148            produced_row_count_estimate: 10,
1149            cost: None,
1150            pinned: Vec::new(),
1151        }
1152    }
1153
1154    #[tokio::test]
1155    async fn subjects_road_emits_the_resolved_rows() {
1156        let rows = vec![subject_row(1, None), subject_row(2, None)];
1157        let op = subject_op(subject_request(false), vec![Variable::new_unchecked("s")]);
1158        mock_subject_env!(rows, None, None => env);
1159        let out = TextExecutorPlugin.execute(&op, env).await.unwrap();
1160        assert_eq!(
1161            out,
1162            vec![vec![rows[0].subject.clone()], vec![rows[1].subject.clone()]]
1163        );
1164    }
1165
1166    #[tokio::test]
1167    async fn subjects_road_emits_the_graph_column_when_requested() {
1168        let rows = vec![subject_row(1, Some(7)), subject_row(2, Some(8))];
1169        let op = subject_op(
1170            subject_request(true),
1171            vec![Variable::new_unchecked("s"), Variable::new_unchecked("g")],
1172        );
1173        mock_subject_env!(rows, None, None => env);
1174        let out = TextExecutorPlugin.execute(&op, env).await.unwrap();
1175        assert_eq!(out.len(), 2);
1176        assert_eq!(out[0][0], rows[0].subject);
1177        assert_eq!(out[0][1], *rows[0].graph.as_ref().unwrap());
1178        assert_eq!(out[1][0], rows[1].subject);
1179        assert_eq!(out[1][1], *rows[1].graph.as_ref().unwrap());
1180    }
1181
1182    #[tokio::test]
1183    async fn subjects_road_filters_a_pushed_subject_column() {
1184        let rows = vec![subject_row(1, None), subject_row(2, None)];
1185        let subject = Variable::new_unchecked("s");
1186        let pushed = vec![rows[1].subject.clone()];
1187        let op = subject_op(subject_request(false), vec![subject.clone()]);
1188        mock_subject_env!(rows, Some(pushed.as_slice()), Some(&subject) => env);
1189        let out = TextExecutorPlugin.execute(&op, env).await.unwrap();
1190        assert_eq!(out, vec![vec![rows[1].subject.clone()]]);
1191
1192        // An empty pushed list is an empty matching domain, not "no filter".
1193        let op = subject_op(subject_request(false), vec![subject.clone()]);
1194        mock_subject_env!(rows, Some(&[]), Some(&subject) => env);
1195        let out = TextExecutorPlugin.execute(&op, env).await.unwrap();
1196        assert!(out.is_empty());
1197    }
1198
1199    #[tokio::test]
1200    async fn subjects_road_preserves_the_pushed_subject_order() {
1201        // The allowed list is ordered (pinned first, then the driver's
1202        // distinct-value order), not a hash set: `LIMIT` without `ORDER BY`
1203        // and golden outputs must not depend on a hash seed.
1204        let rows = vec![
1205            subject_row(1, None),
1206            subject_row(2, None),
1207            subject_row(3, None),
1208        ];
1209        let subject = Variable::new_unchecked("s");
1210        let pushed = vec![
1211            rows[2].subject.clone(),
1212            rows[0].subject.clone(),
1213            rows[1].subject.clone(),
1214        ];
1215        let op = subject_op(subject_request(false), vec![subject.clone()]);
1216        mock_subject_env!(rows, Some(pushed.as_slice()), Some(&subject) => env);
1217        let out = TextExecutorPlugin.execute(&op, env).await.unwrap();
1218        assert_eq!(
1219            out,
1220            vec![
1221                vec![rows[2].subject.clone()],
1222                vec![rows[0].subject.clone()],
1223                vec![rows[1].subject.clone()],
1224            ],
1225            "the probe emits in the pushed list's order"
1226        );
1227    }
1228
1229    #[tokio::test]
1230    async fn subjects_road_dedupes_a_repeated_pushed_subject() {
1231        // A repeated pushed term is emitted once, at its first position.
1232        let rows = vec![subject_row(1, None), subject_row(2, None)];
1233        let subject = Variable::new_unchecked("s");
1234        let pushed = vec![
1235            rows[1].subject.clone(),
1236            rows[0].subject.clone(),
1237            rows[1].subject.clone(),
1238        ];
1239        let op = subject_op(subject_request(false), vec![subject.clone()]);
1240        mock_subject_env!(rows, Some(pushed.as_slice()), Some(&subject) => env);
1241        let out = TextExecutorPlugin.execute(&op, env).await.unwrap();
1242        assert_eq!(
1243            out,
1244            vec![vec![rows[1].subject.clone()], vec![rows[0].subject.clone()],],
1245            "the first pushed position wins"
1246        );
1247    }
1248
1249    #[tokio::test]
1250    async fn subjects_road_filters_a_pushed_graph_column_not_the_subject() {
1251        // The engine names the pushed column. A push on `g` filters the GRAPH
1252        // column — reading the unlabelled list as subject keys would drop
1253        // every row. The same subject in two graphs makes the distinction
1254        // observable.
1255        let rows = vec![subject_row(1, Some(7)), subject_row(1, Some(8))];
1256        let graph = Variable::new_unchecked("g");
1257        let pushed = vec![rows[0].graph.clone().unwrap()];
1258        let op = subject_op(
1259            subject_request(true),
1260            vec![Variable::new_unchecked("s"), graph.clone()],
1261        );
1262        mock_subject_env!(rows, Some(pushed.as_slice()), Some(&graph) => env);
1263        let out = TextExecutorPlugin.execute(&op, env).await.unwrap();
1264        assert_eq!(out.len(), 1, "only the pushed graph survives");
1265        assert_eq!(out[0][0], rows[0].subject);
1266        assert_eq!(out[0][1], *rows[0].graph.as_ref().unwrap());
1267    }
1268
1269    #[tokio::test]
1270    async fn subjects_road_pins_the_subject() {
1271        let rows = vec![subject_row(1, None), subject_row(2, None)];
1272        let subject = Variable::new_unchecked("s");
1273        let mut op = subject_op(subject_request(false), vec![subject.clone()]);
1274        op.pinned.push((subject, rows[0].subject.clone()));
1275        mock_subject_env!(rows, None, None => env);
1276        let out = TextExecutorPlugin.execute(&op, env).await.unwrap();
1277        assert_eq!(out, vec![vec![rows[0].subject.clone()]]);
1278    }
1279
1280    #[tokio::test]
1281    async fn subjects_road_requires_the_graph_column_and_the_request_to_agree() {
1282        let rows = vec![subject_row(1, None)];
1283
1284        // Two output variables but the request would not send the graph term.
1285        let op = subject_op(
1286            subject_request(false),
1287            vec![Variable::new_unchecked("s"), Variable::new_unchecked("g")],
1288        );
1289        mock_subject_env!(rows, None, None => env);
1290        assert!(TextExecutorPlugin.execute(&op, env).await.is_err());
1291
1292        // One output variable but the request would send (and the executor
1293        // would then drop) the graph term.
1294        let op = subject_op(subject_request(true), vec![Variable::new_unchecked("s")]);
1295        mock_subject_env!(rows, None, None => env);
1296        assert!(TextExecutorPlugin.execute(&op, env).await.is_err());
1297    }
1298
1299    #[tokio::test]
1300    async fn subjects_road_rejects_children_and_a_bad_arity() {
1301        let rows = vec![subject_row(1, None)];
1302        let mut op = subject_op(subject_request(false), vec![Variable::new_unchecked("s")]);
1303        op.children
1304            .push(waratah_compute::PlanNode::CustomNode(CustomOp {
1305                plugin_id: crate::PLUGIN_ID,
1306                op_id: TEXT_SCAN_OP_ID,
1307                payload: payload(TextSearchRequest::fts("x")),
1308                children: Vec::new(),
1309                variables: vec![Variable::new_unchecked("lit")],
1310                produced_row_count_estimate: 1,
1311                cost: None,
1312                pinned: Vec::new(),
1313            }));
1314        mock_subject_env!(rows, None, None => env);
1315        assert!(TextExecutorPlugin.execute(&op, env).await.is_err());
1316
1317        let op = subject_op(
1318            subject_request(false),
1319            vec![
1320                Variable::new_unchecked("s"),
1321                Variable::new_unchecked("g"),
1322                Variable::new_unchecked("extra"),
1323            ],
1324        );
1325        mock_subject_env!(rows, None, None => env);
1326        assert!(TextExecutorPlugin.execute(&op, env).await.is_err());
1327    }
1328
1329    #[test]
1330    fn config_defaults_validate() {
1331        TextPluginConfig::default().validate().unwrap();
1332    }
1333}