Skip to main content

waratah_compute/custom_fns/
mod.rs

1//! Custom SPARQL function registry.
2//!
3//! A [`CustomFunctions`] map maps function IRIs to pure callables. Entries are
4//! registered at engine startup ([`CustomFunctions::with_builtins`]) or later
5//! via [`CustomFunctions::register`] (the seam for user-defined functions).
6//!
7//! Every function has ONE required implementation over resolved [`Term`]s
8//! ([`CustomFunction::eval_ground`], the residual path) and an OPTIONAL fast
9//! path over [`EncodedTerm`]s ([`CustomFunction::eval_encoded`], the early
10//! path — no registry I/O). A cache-aware encoded implementation
11//! ([`CustomFunction::eval_encoded_cached`]) may additionally reuse type-erased
12//! query-local prepared values through [`PreparedLiteralCache`]. Either encoded
13//! implementation may return [`CustomEval::NeedsResolve`] for term variants
14//! whose lexical form is hash-only or for results that would not fit an inline
15//! variant; those rows escalate to the ground path through the existing per-row
16//! mechanism. [`ExprCapability`] is DERIVED only from `eval_encoded`
17//! (`Some` → `MaybeEncoded`, `None` → `AlwaysResolve`): the cache-aware
18//! evaluator runs on residual retry and deliberately does not alter planning.
19//!
20//! The 7 mandatory XSD constructor functions (SPARQL 1.1 §17.5) are registered
21//! as built-in customs; see the `casts` submodule.
22
23mod casts;
24
25use std::any::Any;
26use std::collections::HashMap;
27use std::fmt;
28use std::sync::{Arc, OnceLock};
29
30use oxrdf::{NamedNode, Term};
31use waratah_storage::{EncodedTerm, StrHash};
32
33use crate::error::ComputeError;
34use crate::expr::ExprCapability;
35
36/// Outcome of a custom function invocation.
37#[derive(Debug, Clone, PartialEq)]
38pub enum CustomEval {
39    /// A resolved RDF term (ground path).
40    Term(Term),
41    /// An encoded term (early path). Must be constructible without registry
42    /// I/O: inline variants only — never a new hash-referenced variant.
43    Encoded(EncodedTerm),
44    /// SPARQL type error (invalid cast pair, bad lexical form, wrong arity
45    /// value). Becomes an EBV error, not a query failure.
46    Error,
47    /// Early path only: this row's arguments need string materialization.
48    NeedsResolve,
49}
50
51impl CustomEval {
52    /// Type error shorthand.
53    pub fn error() -> Self {
54        Self::Error
55    }
56}
57
58/// Query-local source data and prepared values available to a cache-aware
59/// encoded custom function.
60///
61/// The prepared-value slot is type-erased so `waratah_compute` does not depend
62/// on plugin geometry types. Values are keyed by the plugin's deterministic
63/// term key and shared across parallel query workspaces.
64pub trait PreparedLiteralCache: Send + Sync {
65    /// Clone a prepared value from the query-local cache.
66    fn prepared_value(&self, key: &StrHash) -> Option<Arc<dyn Any + Send + Sync>>;
67
68    /// Insert a prepared value with an approximate retained-byte cost.
69    /// Returns `false` when the query-local byte limit refuses admission.
70    fn insert_prepared_value(
71        &self,
72        key: StrHash,
73        value: Arc<dyn Any + Send + Sync>,
74        cost: usize,
75    ) -> bool;
76
77    /// Resolved lexical string under a plugin-defined key.
78    fn resolved_string(&self, key: &StrHash) -> Option<&str>;
79
80    /// Query-local blob payload under its content address.
81    fn blob_payload(&self, key: &StrHash) -> Option<&[u8]>;
82}
83
84/// A registered custom function: IRI, arity bounds, and its callables.
85///
86/// Plain `fn` pointers — deterministic, no captures, no allocations at
87/// registration beyond the map entry (systems-minded per AGENTS.md).
88#[derive(Clone)]
89pub struct CustomFunction {
90    /// Invoking IRI, e.g. `xsd:integer` for the cast.
91    pub iri: NamedNode,
92    /// Minimum argument count.
93    pub min_args: usize,
94    /// Maximum argument count.
95    pub max_args: usize,
96    /// Required: evaluate over resolved terms (residual / ground path).
97    pub eval_ground: fn(&[Term]) -> CustomEval,
98    /// Optional: evaluate over encoded terms (early path, no registry I/O).
99    /// Returning [`CustomEval::NeedsResolve`] escalates the row to the ground
100    /// path through the standard mechanism.
101    pub eval_encoded: Option<fn(&[EncodedTerm]) -> CustomEval>,
102    /// Optional encoded evaluator that may reuse query-local prepared values.
103    /// A cache miss returns [`CustomEval::NeedsResolve`] so the ordinary
104    /// encoded/ground fallback remains unchanged.
105    pub eval_encoded_cached: Option<fn(&[EncodedTerm], &dyn PreparedLiteralCache) -> CustomEval>,
106}
107
108impl CustomFunction {
109    /// Planning capability, derived from the encoded impl's presence.
110    ///
111    /// Planning capability follows only `eval_encoded`. A cache-aware
112    /// evaluator is a residual-retry optimization: changing classification
113    /// here would move a function out of the residual stage before planner
114    /// rewrites that own that stage have run.
115    pub fn capability(&self) -> ExprCapability {
116        if self.eval_encoded.is_some() {
117            ExprCapability::MaybeEncoded
118        } else {
119            ExprCapability::AlwaysResolve
120        }
121    }
122}
123
124/// IRI-keyed map of custom functions.
125#[derive(Clone, Default)]
126pub struct CustomFunctions {
127    map: HashMap<String, CustomFunction>,
128}
129
130impl fmt::Debug for CustomFunctions {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.debug_map()
133            .entries(self.map.keys().map(|k| (k, ())))
134            .finish()
135    }
136}
137
138impl CustomFunctions {
139    /// Empty registry (no builtins).
140    pub fn empty() -> Self {
141        Self::default()
142    }
143
144    /// Registry with the 7 mandatory XSD casts pre-registered.
145    pub fn with_builtins() -> Self {
146        let mut registry = Self::empty();
147        for cast in casts::builtin_casts() {
148            registry
149                .register(cast)
150                .expect("builtin cast IRIs are distinct");
151        }
152        registry
153    }
154
155    /// Register `function`. Errors on a duplicate IRI.
156    pub fn register(&mut self, function: CustomFunction) -> Result<(), ComputeError> {
157        if self.map.contains_key(function.iri.as_str()) {
158            return Err(ComputeError::UnsupportedSparql(format!(
159                "custom function {} is already registered",
160                function.iri
161            )));
162        }
163        self.map.insert(function.iri.as_str().to_owned(), function);
164        Ok(())
165    }
166
167    /// Look up by IRI.
168    pub fn get(&self, iri: &NamedNode) -> Option<&CustomFunction> {
169        self.map.get(iri.as_str())
170    }
171
172    /// Whether `iri` is registered.
173    pub fn contains(&self, iri: &NamedNode) -> bool {
174        self.map.contains_key(iri.as_str())
175    }
176
177    /// Number of registered functions.
178    pub fn len(&self) -> usize {
179        self.map.len()
180    }
181
182    /// Whether the registry is empty.
183    pub fn is_empty(&self) -> bool {
184        self.map.is_empty()
185    }
186}
187
188/// Process-lifetime registry used by the eval paths (`filter.rs` /
189/// `filter_residual.rs` / `expr::capability`). First installation wins —
190/// [`install_process_registry`] at engine startup, or the builtins via
191/// `get_or_init` when an early caller (unit tests, plan lowering before any
192/// engine exists) gets there first.
193///
194/// A [`OnceLock`] read after init is a relaxed atomic load of the pointer; the
195/// per-row call sites never take a lock and never touch the `Arc` refcount
196/// (they borrow the `'static` reference), so there is no cross-core cacheline
197/// traffic on the hot filter paths. A [`RwLock`] slot was rejected: it can
198/// poison (silently degrading every lookup to a per-call registry rebuild)
199/// and its read path is a CAS, not free.
200///
201/// This mirrors the existing `set_scan_batch` / residual-window process knobs
202/// and matches reality: the XSD casts are defined by the SPARQL spec, not by
203/// engine instance. If per-engine function libraries ever become a real
204/// feature, thread `&CustomFunctions` through the eval signatures then — with
205/// a two-engines-with-different-registries test as the acceptance criterion —
206/// rather than growing this global into a two-sources-of-truth trap.
207static PROCESS_REGISTRY: OnceLock<Arc<CustomFunctions>> = OnceLock::new();
208
209/// Install the process-lifetime custom-function registry (first install wins).
210///
211/// Called by `QueryEngine::new` as the documented seam; if the registry is
212/// already initialized the call is a no-op and `registry` is dropped. There is
213/// deliberately no replace: swapping the set under live readers would make a
214/// second engine's construction silently reshape the first engine's queries.
215pub fn install_process_registry(registry: Arc<CustomFunctions>) {
216    let _ = PROCESS_REGISTRY.set(registry);
217}
218
219/// The process registry, initializing it to the builtins on first use so unit
220/// tests and early callers (before any engine exists) still see the 7 XSD
221/// casts.
222///
223/// Public so composition points and tests can verify what actually landed on
224/// the process map (the read is the same relaxed atomic the eval paths use —
225/// no locking, no `Arc` refcount traffic).
226pub fn process_registry() -> &'static Arc<CustomFunctions> {
227    PROCESS_REGISTRY.get_or_init(|| Arc::new(CustomFunctions::with_builtins()))
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use oxrdf::vocab::xsd;
234
235    fn noop_ground(_: &[Term]) -> CustomEval {
236        CustomEval::Error
237    }
238
239    fn noop_encoded(_: &[EncodedTerm]) -> CustomEval {
240        CustomEval::Error
241    }
242
243    fn sample(iri: &'static str, encoded: bool) -> CustomFunction {
244        CustomFunction {
245            iri: NamedNode::new_unchecked(iri),
246            min_args: 1,
247            max_args: 1,
248            eval_ground: noop_ground,
249            eval_encoded: encoded.then_some(noop_encoded as fn(&[EncodedTerm]) -> CustomEval),
250            eval_encoded_cached: None,
251        }
252    }
253
254    #[test]
255    fn builtins_are_registered() {
256        let registry = CustomFunctions::with_builtins();
257        assert_eq!(registry.len(), 7);
258        for iri in [
259            xsd::STRING,
260            xsd::BOOLEAN,
261            xsd::DECIMAL,
262            xsd::FLOAT,
263            xsd::DOUBLE,
264            xsd::INTEGER,
265            xsd::DATE_TIME,
266        ] {
267            assert!(registry.get(&iri.into_owned()).is_some(), "{iri}");
268        }
269    }
270
271    #[test]
272    fn unknown_iri_is_none() {
273        let registry = CustomFunctions::with_builtins();
274        assert!(
275            registry
276                .get(&NamedNode::new_unchecked("http://example.org/nope"))
277                .is_none()
278        );
279        assert!(CustomFunctions::empty().is_empty());
280    }
281
282    #[test]
283    fn duplicate_registration_errors() {
284        let mut registry = CustomFunctions::empty();
285        registry
286            .register(sample("http://example.org/fn", false))
287            .unwrap();
288        let duplicate = registry.register(sample("http://example.org/fn", false));
289        assert!(matches!(duplicate, Err(ComputeError::UnsupportedSparql(_))));
290    }
291
292    #[test]
293    fn capability_is_derived_from_encoded_impl() {
294        assert_eq!(
295            sample("http://example.org/enc", true).capability(),
296            ExprCapability::MaybeEncoded
297        );
298        assert_eq!(
299            sample("http://example.org/ground", false).capability(),
300            ExprCapability::AlwaysResolve
301        );
302    }
303}