Skip to main content

waratah_text/
lib.rs

1//! Waratah text plugin: Jena-style `FILTER text:query` plus index-accelerated
2//! `STRSTARTS` / `STRENDS` / anchored-`REGEX` candidate injection, backed by a
3//! Tantivy index owned by the O partition.
4//!
5//! One crate implements the [`waratah_compute::plugin`] hooks the other two
6//! plugins use — write ([`TextWritePlugin`]) and plan/execute
7//! ([`TextPlannerPlugin`] / [`TextExecutorPlugin`]; the text plugin claims no
8//! datatypes, string literals are storage-native). Register at compute startup
9//! via [`register`]: the binary composes every plugin crate onto ONE
10//! [`waratah_compute::PluginHost`] and installs the composed set exactly once,
11//! BEFORE any query is lowered.
12//!
13//! v1 boundaries (scope S4): `text:query` FILTER position only (graph-pattern
14//! use is a plan error); `CONTAINS` and general `REGEX` are out (no candidate
15//! producer without a raw-lexical / n-gram field); score, limit, highlighting,
16//! `STR(?v)` wrappers, and `field:term` syntax are out. The index is derived
17//! data: one Tantivy document per distinct string-literal term, never
18//! retracted on delete, rebuilt from the hexastore when lost.
19
20#![warn(missing_docs)]
21
22mod config;
23mod exec;
24mod plan;
25mod rebuild;
26mod write;
27
28/// Stable plugin id carried by every CustomOp the text plugin mints.
29pub const PLUGIN_ID: &str = "text";
30
31pub use config::TextPluginConfig;
32pub use exec::{
33    TEXT_SCAN_OP_ID, TEXT_SUBJECTS_OP_ID, TextExecutorPlugin, TextScanPayload, TextSubjectsPayload,
34    text_query_eval_ground,
35};
36pub use plan::{TEXT_QUERY_IRI, TextPlannerPlugin};
37pub use rebuild::{
38    HEAD_PAGE, RebuildReport, assemble_batch, drive_text_rebuild, group_predicates, hashes_of,
39    is_text_term, text_head_prefixes,
40};
41pub use write::TextWritePlugin;
42
43use waratah_compute::ComputeError;
44use waratah_compute::CustomFunction;
45use waratah_compute::plugin::{PluginHost, RegisteredPlugin};
46/// Register the text plugin bundle + the `text:query` pass-through on
47/// `host` (the composition point every plugin crate shares; the binary then
48/// installs the composed host exactly once, BEFORE any `QueryEngine` is
49/// constructed).
50///
51/// `config` decides whether the plugin participates at all: `enabled =
52/// false` registers nothing (the index would be maintained by nobody), and
53/// the caller still owns the config file plumbing. The fingerprint travels
54/// with the planner so every rewrite compares against the same settings the
55/// build used.
56pub fn register(host: &mut PluginHost, config: &TextPluginConfig) -> Result<(), ComputeError> {
57    if !config.enabled {
58        return Ok(());
59    }
60    config.validate().map_err(|message| {
61        ComputeError::UnsupportedSparql(format!("invalid text plugin config: {message}"))
62    })?;
63    host.register(RegisteredPlugin {
64        id: PLUGIN_ID,
65        write: Some(std::sync::Arc::new(TextWritePlugin::new(
66            &config.predicates,
67        ))),
68        // No datatype claims: string literals are storage-native already.
69        encode: None,
70        planner: Some(std::sync::Arc::new(TextPlannerPlugin::new(config.clone()))),
71        executor: Some(std::sync::Arc::new(TextExecutorPlugin)),
72    })?;
73    host.register_functions(text_custom_functions())
74}
75
76/// The `text:query` custom-function entry: a lowering pass-through.
77///
78/// It exists on the map so `split_filter` classifies the IRI
79/// (AlwaysResolve → residual) instead of erroring `Unsupported` before the
80/// planner sees it. The planner strips every form it accepts and hard-fails
81/// every form it does not, so the row evaluation here is a backstop that
82/// must never decide answers.
83pub fn text_custom_functions() -> Vec<CustomFunction> {
84    vec![CustomFunction {
85        iri: oxrdf::NamedNode::new_unchecked(TEXT_QUERY_IRI),
86        // Literal mode (2 args), subject mode (3+), with the trailing lang.
87        min_args: 2,
88        max_args: 6,
89        eval_ground: text_query_eval_ground,
90        eval_encoded: None,
91        eval_encoded_cached: None,
92    }]
93}
94
95/// Test convenience: install ONLY the text plugin on the process registries
96/// with a default-enabled config (first install wins; one guarded host
97/// install per process, so repeat calls are no-ops). Production composes
98/// every plugin crate via [`register`] + one
99/// [`waratah_compute::PluginHost::install_process_wide`] instead.
100pub fn install() {
101    install_with(TextPluginConfig {
102        enabled: true,
103        // The test suite indexes arbitrary `http://ex/...` predicates, so it
104        // opts out of the built-in allowlist.
105        predicates: Vec::new(),
106        ..TextPluginConfig::default()
107    });
108}
109
110/// Test convenience with an explicit config (see [`install`]).
111pub fn install_with(config: TextPluginConfig) {
112    static INSTALLED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
113    INSTALLED.get_or_init(|| {
114        let mut host = PluginHost::new();
115        register(&mut host, &config)
116            .expect("the text plugin registers no datatype set, so no conflicts");
117        host.install_process_wide();
118    });
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn disabled_config_registers_nothing() {
127        let mut host = PluginHost::new();
128        register(&mut host, &TextPluginConfig::default()).unwrap();
129        assert!(
130            host.registry_is_empty(),
131            "disabled config must not install any hook"
132        );
133    }
134
135    #[test]
136    fn enabled_config_registers_all_hooks_and_the_function() {
137        let mut host = PluginHost::new();
138        register(
139            &mut host,
140            &TextPluginConfig {
141                enabled: true,
142                ..TextPluginConfig::default()
143            },
144        )
145        .unwrap();
146        assert!(!host.registry_is_empty());
147    }
148
149    #[test]
150    fn the_function_entry_classifies_as_always_resolve() {
151        let functions = text_custom_functions();
152        assert_eq!(functions.len(), 1);
153        assert_eq!(functions[0].iri.as_str(), TEXT_QUERY_IRI);
154        assert!(matches!(
155            functions[0].capability(),
156            waratah_compute::ExprCapability::AlwaysResolve
157        ));
158    }
159}