Skip to main content

waratah_text_index/
scratch.rs

1//! Compute-side evaluation of a text request over in-house terms.
2//!
3//! The pushed-key and pinned roads of the `text_scan` executor receive the
4//! terms they must decide and evaluate them locally instead of draining the
5//! partition's index. Three modes, two mechanisms:
6//!
7//! - `FTS` builds a scratch in-memory index ([`TextIndex::create_in_ram`])
8//!   over the terms and runs it through the SAME schema, analyzer
9//!   registration, query builder, and collector the partition index uses.
10//!   Tantivy matching is per-document boolean — nothing in the match
11//!   decision depends on index-global state (document frequencies affect
12//!   only scoring order) — so the scratch answer equals the index answer
13//!   for the same value, and no second query implementation exists to
14//!   drift.
15//! - `PREFIX` / `SUFFIX` are pure string tests over the bounded seeds,
16//!   exactly the match the index performs on its stored fields: a
17//!   document's `text_begin` is [`crate::doc::prefix_seed`] of its lexical
18//!   and the query seed is [`crate::doc::prefix_seed`] of the pattern, so
19//!   a value matches iff its seed starts with the pattern's seed; the
20//!   suffix direction is the same test over the reversed seeds.
21//!
22//! Direct evaluation is equivalent to index membership because these roads
23//! only run inside a plan rewritten under the trust gate: the gate injects a
24//! candidate producer only for a variable whose object-slot scans use an
25//! allowlisted predicate, and a trusted index holds every string literal
26//! under those predicates. For every value the executor is asked about, "this
27//! value matches the query" and "the index returns this value" therefore
28//! coincide. A value from outside that universe (a `VALUES`/`BIND` binding, a
29//! non-allowlisted predicate) never reaches these roads: the rewrite declines
30//! and the exact residual answers.
31
32use waratah_storage::text_index::{TextCandidateMode, TextIndexDoc, TextSearchRequest};
33
34use crate::doc::{prefix_seed, suffix_pattern_seed_reversed, suffix_seed_reversed};
35use crate::error::TextIndexError;
36use crate::index::{TextIndex, TextIndexOptions};
37
38/// The fingerprint stamped on a scratch index. It is never compared
39/// against anything — the scratch index lives for one delivery and its
40/// schema is rebuilt from the same config — but index creation rejects an
41/// empty fingerprint, so it carries a descriptive fixed value.
42const SCRATCH_FINGERPRINT: &str = "text-index-v2;scratch-eval";
43
44/// Evaluate a full-text request over the in-house documents.
45///
46/// `analyzer` and `seed_chars` must be the values the plan was rewritten
47/// under (they ride the op payload; the plan-time fingerprint comparison
48/// ties them to the partition's stored configuration). The request's
49/// per-drain limit is deliberately ignored: it guards candidate
50/// materialization on the sweep road, while the direct road's universe is
51/// the pushed set itself, already in memory.
52pub fn evaluate_fts(
53    request: &TextSearchRequest,
54    analyzer: &str,
55    seed_chars: usize,
56    docs: &[TextIndexDoc],
57) -> Result<Vec<Vec<u8>>, TextIndexError> {
58    let unlimited = TextSearchRequest {
59        limit: 0,
60        ..request.clone()
61    };
62    let options = TextIndexOptions::new(analyzer, seed_chars, SCRATCH_FINGERPRINT);
63    let index = TextIndex::create_in_ram(&options)?;
64    index.add_batch(docs)?;
65    index.search(&unlimited)
66}
67
68/// The prefix candidate test for one lexical, exactly the index's match on
69/// its stored `text_begin` field (see the module doc). An empty lexical or
70/// pattern seeds nothing and never matches, like the index.
71fn lexical_matches_prefix(lexical: &str, pattern: &str, seed_chars: usize) -> bool {
72    let Some(seed) = prefix_seed(pattern, seed_chars) else {
73        return false;
74    };
75    let Some(begin) = prefix_seed(lexical, seed_chars) else {
76        return false;
77    };
78    begin.starts_with(seed)
79}
80
81/// The suffix candidate test for one lexical: the same test over the
82/// reversed bounded seeds, matching the index's `text_end` field.
83fn lexical_matches_suffix(lexical: &str, pattern: &str, seed_chars: usize) -> bool {
84    let Some(seed) = suffix_pattern_seed_reversed(pattern, seed_chars) else {
85        return false;
86    };
87    let Some(end) = suffix_seed_reversed(lexical, seed_chars) else {
88        return false;
89    };
90    end.starts_with(&seed)
91}
92
93/// Evaluate a prefix / suffix request over the in-house documents as pure
94/// string tests (no index construction). The mode selects the direction;
95/// anything else is a caller bug.
96pub fn evaluate_seed(
97    request: &TextSearchRequest,
98    seed_chars: usize,
99    docs: &[TextIndexDoc],
100) -> Result<Vec<Vec<u8>>, TextIndexError> {
101    let matched: Vec<&TextIndexDoc> = match request.mode {
102        TextCandidateMode::Prefix => docs
103            .iter()
104            .filter(|doc| lexical_matches_prefix(&doc.lexical, &request.query, seed_chars))
105            .collect(),
106        TextCandidateMode::Suffix => docs
107            .iter()
108            .filter(|doc| lexical_matches_suffix(&doc.lexical, &request.query, seed_chars))
109            .collect(),
110        mode => {
111            return Err(TextIndexError::Config(format!(
112                "seed evaluation does not apply to mode {mode:?}"
113            )));
114        }
115    };
116    Ok(matched.into_iter().map(|doc| doc.term.clone()).collect())
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use waratah_storage::text_index::DEFAULT_ANALYZER;
123
124    fn doc(id: u8, lexical: &str) -> TextIndexDoc {
125        TextIndexDoc::new(vec![id], lexical.to_owned(), None)
126    }
127
128    fn term_ids(mut terms: Vec<Vec<u8>>) -> Vec<u8> {
129        terms.sort();
130        terms.into_iter().map(|t| t[0]).collect()
131    }
132
133    #[test]
134    fn fts_scratch_answers_like_the_partition_index() {
135        // The same literals, the same request: the scratch answer must equal
136        // a real index's answer. "laser printer" over an en_stem-style menu
137        // value matches the laser docs and not the others.
138        let docs = vec![
139            doc(1, "laser printer"),
140            doc(2, "inkjet printer"),
141            doc(3, "laser pointer"),
142            doc(4, "copy machine"),
143        ];
144        let matched = evaluate_fts(&TextSearchRequest::fts("laser"), "simple", 16, &docs).unwrap();
145        assert_eq!(term_ids(matched), vec![1, 3]);
146    }
147
148    #[test]
149    fn fts_scratch_ignores_the_request_limit() {
150        // The direct road's universe is the pushed set; a small limit in the
151        // request must not truncate it.
152        let docs = vec![doc(1, "alpha"), doc(2, "alpha beta")];
153        let request = TextSearchRequest {
154            mode: TextCandidateMode::Fts,
155            query: "alpha".to_owned(),
156            language: None,
157            limit: 1,
158        };
159        let matched = evaluate_fts(&request, DEFAULT_ANALYZER, 16, &docs).unwrap();
160        assert_eq!(term_ids(matched), vec![1, 2]);
161    }
162
163    #[test]
164    fn seed_evaluation_matches_the_index_within_the_seed_length() {
165        // Cross-check the string tests against the scratch index over the
166        // same corpus: within seed_chars the candidate sets must agree
167        // exactly; beyond it the string test is the same superset the index
168        // produces (the stored fields are themselves truncated).
169        let corpus = [
170            "bellendena",
171            "bellini",
172            "bellingham",
173            "belle",
174            "belfast",
175            "orange",
176            "bel",
177        ];
178        let docs: Vec<TextIndexDoc> = corpus
179            .iter()
180            .enumerate()
181            .map(|(i, lexical)| doc(i as u8, lexical))
182            .collect();
183        for pattern in ["bel", "bell", "belle", "bellendena", "belmont"] {
184            for seed_chars in [3, 5, 8, 16] {
185                let by_strings =
186                    evaluate_seed(&TextSearchRequest::prefix(pattern), seed_chars, &docs).unwrap();
187                let by_index = evaluate_fts(
188                    &TextSearchRequest::prefix(pattern),
189                    DEFAULT_ANALYZER,
190                    seed_chars,
191                    &docs,
192                )
193                .unwrap();
194                assert_eq!(
195                    term_ids(by_strings),
196                    term_ids(by_index),
197                    "prefix {pattern:?} at seed_chars {seed_chars}"
198                );
199            }
200        }
201        for pattern in ["ena", "ini", "ham", "elle", "anger"] {
202            for seed_chars in [3, 5, 8, 16] {
203                let by_strings =
204                    evaluate_seed(&TextSearchRequest::suffix(pattern), seed_chars, &docs).unwrap();
205                let by_index = evaluate_fts(
206                    &TextSearchRequest::suffix(pattern),
207                    DEFAULT_ANALYZER,
208                    seed_chars,
209                    &docs,
210                )
211                .unwrap();
212                assert_eq!(
213                    term_ids(by_strings),
214                    term_ids(by_index),
215                    "suffix {pattern:?} at seed_chars {seed_chars}"
216                );
217            }
218        }
219    }
220
221    #[test]
222    fn empty_lexicals_and_patterns_never_match() {
223        let docs = vec![doc(1, "")];
224        assert!(
225            evaluate_seed(&TextSearchRequest::prefix("bel"), 16, &docs)
226                .unwrap()
227                .is_empty()
228        );
229        assert!(
230            evaluate_seed(&TextSearchRequest::prefix(""), 16, &docs)
231                .unwrap()
232                .is_empty()
233        );
234    }
235}