Skip to main content

waratah_storage/
text_index.rs

1//! Cross-crate vocabulary for the text plugin.
2//!
3//! The write path carries one [`TextIndexDoc`] per indexed literal from compute
4//! to the O partition, and the plugin's configuration names one analyzer from
5//! the [`ANALYZERS`] menu. Both live here — beside the geo and temporal posting
6//! types — so compute, the partition and the index engine share one definition
7//! without any of them linking Tantivy.
8
9use crate::EncodedTerm;
10
11/// Default analyzer name: tokenize, drop over-long tokens, lowercase.
12pub const DEFAULT_ANALYZER: &str = "simple";
13
14/// Default number of characters stored in the bounded prefix and suffix
15/// fields.
16///
17/// A space-versus-selectivity trade, not a correctness knob: patterns at most
18/// this long produce an exact candidate set, longer patterns are seeded with
19/// this many characters and the residual FILTER decides.
20pub const DEFAULT_SEED_CHARS: usize = 16;
21
22/// Largest accepted seed length.
23pub const MAX_SEED_CHARS: usize = 64;
24
25/// Largest string-literal lexical the text index accepts, in bytes.
26///
27/// The text plugin indexes every string literal, and the wire payload of a
28/// `PutTextIndex` document carries the full lexical — so a literal larger
29/// than a single wire frame cannot be indexed at all. Rather than fail with
30/// a transport error mid-insert (or silently skip the document, the
31/// silently-missing-candidate state), the write path REJECTS oversized
32/// lexicals fail-closed: a `PutTextIndex` frame containing one errors
33/// before any axis write, and rebuilds skip the term and refuse to stamp
34/// the epoch. One mebibyte sits far above every realistic RDF literal
35/// while leaving ample headroom under the `PutTextIndex` frame budget
36/// (`TEXT_INDEX_WIRE_BUDGET_BYTES`, 3.5 MiB). The number is deliberately the
37/// string registry's `MAX_REGISTERED_STRING_BYTES` (`waratah_registry`): on a
38/// clustered store, `RegisterStrings` precedes the text document write in the
39/// insert path, so the registry rejects these strings first, plugin on or
40/// off; this constant is the guard on in-process paths (`standalone`,
41/// `import --offline`), where the registry performs no length check. A store
42/// that must hold bigger literals is therefore an in-process store with the
43/// text plugin disabled.
44pub const MAX_INDEXED_LEXICAL_BYTES: usize = 1024 * 1024;
45
46/// Analyzer menu: config value → tokenizer name registered on the index.
47///
48/// The registered names are Waratah-owned (`waratah_*`) so a Tantivy upgrade
49/// cannot silently change the analysis of an existing store.
50pub const ANALYZERS: &[(&str, &str)] = &[
51    ("simple", "waratah_simple"),
52    ("en_stem", "waratah_en_stem"),
53    ("whitespace", "waratah_whitespace"),
54];
55
56/// Tokenizer name used by the bounded seed fields and the language field.
57pub const RAW_TOKENIZER: &str = "raw";
58
59/// Language-field sentinel for a literal without a language tag.
60pub const LANG_NONE: &str = "_none";
61
62/// The registered tokenizer name for a configuration analyzer value.
63pub fn registered_analyzer(analyzer: &str) -> Option<&'static str> {
64    ANALYZERS
65        .iter()
66        .find(|(name, _)| *name == analyzer)
67        .map(|(_, registered)| *registered)
68}
69
70/// One literal to add to the text index.
71///
72/// The partition derives the bounded prefix and suffix fields from `lexical`;
73/// carrying them would only duplicate bytes on the wire. `term` is the encoded
74/// `EncodedTerm` and stays opaque to every layer that does not need to decode
75/// it.
76///
77/// The persistent index keys one document by `(predicate, literal)`, so the
78/// same literal under two predicates is two documents (the predicate dimension
79/// is what lets a query scope its candidate set). `predicate` is the encoded
80/// predicate term. It is empty only for compute-side scratch documents built
81/// by the direct-evaluation roads, which never enter the persistent index.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct TextIndexDoc {
84    /// Encoded `EncodedTerm` bytes; the candidate-scan payload.
85    pub term: Vec<u8>,
86    /// Encoded predicate term bytes; the other half of the document identity.
87    pub predicate: Vec<u8>,
88    /// The literal's lexical form.
89    pub lexical: String,
90    /// Language tag for `rdf:langString`, `None` otherwise.
91    pub language: Option<String>,
92}
93
94impl TextIndexDoc {
95    /// Build a scratch document (no predicate identity).
96    pub fn new(term: Vec<u8>, lexical: impl Into<String>, language: Option<String>) -> Self {
97        Self {
98            term,
99            predicate: Vec::new(),
100            lexical: lexical.into(),
101            language,
102        }
103    }
104
105    /// Build a persistent document keyed by `(predicate, literal)`.
106    pub fn new_with_predicate(
107        term: Vec<u8>,
108        predicate: Vec<u8>,
109        lexical: impl Into<String>,
110        language: Option<String>,
111    ) -> Self {
112        Self {
113            term,
114            predicate,
115            lexical: lexical.into(),
116            language,
117        }
118    }
119}
120
121/// The logical identity of one text document: `(predicate, literal)`.
122///
123/// The predicate is length-prefixed so the concatenation is injective: the
124/// two encoded terms are self-delimiting only while their lengths are known,
125/// and a bare join of two variable-length byte strings can collide. The key is
126/// compared exactly by the index's indexed `key` field (`delete_term`), so any
127/// injective encoding works.
128pub fn text_index_key(predicate: &[u8], term: &[u8]) -> Vec<u8> {
129    let mut key = Vec::with_capacity(4 + predicate.len() + term.len());
130    key.extend_from_slice(&(predicate.len() as u32).to_be_bytes());
131    key.extend_from_slice(predicate);
132    key.extend_from_slice(term);
133    key
134}
135
136/// Which candidate query to run against a text index.
137///
138/// Lives here, beside the document, because compute builds one from a SPARQL
139/// rewrite and the partition executes it; neither has to link the Tantivy
140/// engine to name a mode.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
142pub enum TextCandidateMode {
143    /// Parsed full-text query over the analyzed `text` field.
144    Fts,
145    /// Literal prefix over the bounded forward field.
146    Prefix,
147    /// Literal suffix over the bounded reversed field.
148    Suffix,
149}
150
151/// One subject-resolve request: the subject form of `text:query`.
152///
153/// One search runs for the whole `predicates` set (a single OR over the stored
154/// predicate), and each matched literal is resolved against the OPSG index at
155/// the query snapshot, where the same set scopes the walk.
156///
157/// An EMPTY `predicates` list means "no predicate restriction", not
158/// "everything": the drain still returns only literals the TEXT INDEX holds
159/// for this query (there is no hexastore fallback), and each of those is then
160/// read under any predicate. That is correct only when the query really means
161/// the whole indexed universe — the planner owns that decision (the default
162/// allowlist is the built-in list; an explicit empty allowlist means all) and
163/// the partition carries no plugin config to re-check it.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct TextSubjectRequest {
166    /// Which query to build (same modes as [`TextSearchRequest`]).
167    pub mode: TextCandidateMode,
168    /// Full-text query string, or the literal prefix / suffix pattern.
169    pub query: String,
170    /// Optional language restriction (`lang:fr`, or the `_none` sentinel).
171    pub language: Option<String>,
172    /// Guard on emitted DISTINCT (subject, graph) rows; `0` means unlimited.
173    /// Exceeding it is an error, never a silent truncation.
174    pub limit: u64,
175    /// Predicate terms the resolve is restricted to; empty = no restriction.
176    pub predicates: Vec<EncodedTerm>,
177    /// Bound graph name (`None` = variable / all graphs).
178    pub graph_name: Option<EncodedTerm>,
179    /// Residual graph allow-list or block-list, same as a scan request.
180    pub graph_filter_terms: Vec<EncodedTerm>,
181    /// `true` = the filter is an allow-list (keep members).
182    pub graph_filter_allow: bool,
183    /// Same RDF-merge unique as a scan pattern's `merge_default_graph`.
184    pub merge_default_graph: bool,
185    /// Emit the graph term per row: the query binds a graph variable.
186    pub return_graph: bool,
187    /// Keep only rows whose subject term equals their graph term.
188    ///
189    /// This is the shape `GRAPH ?s { … }` with `text:query(?s, …)` on the
190    /// same variable: the one SPARQL variable must take one value, so the
191    /// matched triple's subject, its graph, and the graph name are the same
192    /// term. The resolve enforces that per row and emits the subject alone
193    /// (`return_graph` stays false); without it the op would declare the
194    /// graph variable twice and the join could keep a row whose matching
195    /// literal lives in a different graph than the solution's.
196    pub subject_equals_graph: bool,
197}
198
199/// One resolved row of a [`TextSubjectRequest`].
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct TextSubjectRow {
202    /// Encoded subject term (IRI or blank node).
203    pub subject: EncodedTerm,
204    /// Encoded graph term, present only when the request set
205    /// [`TextSubjectRequest::return_graph`].
206    pub graph: Option<EncodedTerm>,
207}
208
209/// One candidate drain request.
210#[derive(Debug, Clone, PartialEq, Eq, Hash)]
211pub struct TextSearchRequest {
212    /// Which query to build.
213    pub mode: TextCandidateMode,
214    /// Full-text query string, or the literal prefix / suffix pattern.
215    pub query: String,
216    /// Optional language restriction (`lang:fr`, or the `_none` sentinel).
217    pub language: Option<String>,
218    /// Per-drain guard on emitted distinct terms; `0` means unlimited.
219    ///
220    /// This is an execution guard, not a cursor: exceeding it is an error,
221    /// not a silent truncation, because dropped candidates would drop rows.
222    ///
223    /// NO v1 caller arms a guard: every minted request carries `0`, so a
224    /// drain is unbounded — a broad FTS query materializes its whole
225    /// distinct candidate set in one partition-side allocation. Arming a
226    /// real limit requires a policy for the error reaching the client
227    /// (refine-the-query is not always actionable), so until then the
228    /// unbounded drain is the documented contract, not an oversight.
229    pub limit: u64,
230}
231
232impl TextSearchRequest {
233    /// A full-text request.
234    pub fn fts(query: impl Into<String>) -> Self {
235        Self {
236            mode: TextCandidateMode::Fts,
237            query: query.into(),
238            language: None,
239            limit: 0,
240        }
241    }
242
243    /// A prefix request.
244    pub fn prefix(pattern: impl Into<String>) -> Self {
245        Self {
246            mode: TextCandidateMode::Prefix,
247            query: pattern.into(),
248            language: None,
249            limit: 0,
250        }
251    }
252
253    /// A suffix request.
254    pub fn suffix(pattern: impl Into<String>) -> Self {
255        Self {
256            mode: TextCandidateMode::Suffix,
257            query: pattern.into(),
258            language: None,
259            limit: 0,
260        }
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn the_menu_maps_every_name_to_a_waratah_tokenizer() {
270        for (name, registered) in ANALYZERS {
271            assert!(!name.is_empty());
272            assert!(registered.starts_with("waratah_"));
273            assert_eq!(registered_analyzer(name), Some(*registered));
274        }
275        assert_eq!(registered_analyzer("klingon"), None);
276    }
277
278    #[test]
279    fn seed_length_bounds_are_sane() {
280        const {
281            assert!(DEFAULT_SEED_CHARS > 0 && DEFAULT_SEED_CHARS <= MAX_SEED_CHARS);
282        }
283    }
284
285    #[test]
286    fn doc_holds_term_lexical_language() {
287        let doc = TextIndexDoc::new(vec![1, 2], "hello", Some("en".to_owned()));
288        assert_eq!(doc.term, vec![1, 2]);
289        assert!(
290            doc.predicate.is_empty(),
291            "scratch documents carry no predicate"
292        );
293        assert_eq!(doc.lexical, "hello");
294        assert_eq!(doc.language.as_deref(), Some("en"));
295        assert_eq!(TextIndexDoc::new(vec![], "x", None).language, None);
296
297        let keyed = TextIndexDoc::new_with_predicate(vec![2], vec![1], "hello", None);
298        assert_eq!(keyed.term, vec![2]);
299        assert_eq!(keyed.predicate, vec![1]);
300    }
301
302    #[test]
303    fn document_keys_are_injective_across_the_predicate_boundary() {
304        // A bare join would make these two pairs the same key.
305        let a = text_index_key(&[1, 2], &[3]);
306        let b = text_index_key(&[1], &[2, 3]);
307        assert_ne!(a, b);
308        assert_eq!(a, text_index_key(&[1, 2], &[3]));
309    }
310}