waratah_compute/plugin.rs
1//! Generic plugin seams: writes, plan, and execution.
2//!
3//! Four traits; `waratah_geo` implements all of them, `waratah_temporal` the
4//! write/planner/executor trio (its terms are storage-native, no encode hook):
5//!
6//! - [`WritePlugin`] runs **before** the hexastore RPC on the insert path
7//! (gRPC fan-out and offline import alike). It returns a sparse
8//! object-rewrite overlay ([`PreparedInsert::object_rewrites`]), registry
9//! blob puts, and opaque O-axis index postings (geo + temporal) sent with
10//! the same `commit_ts` — Put-shaped only: on Delete batches the fan-out
11//! discards the postings (term-keyed indexes are never retracted on
12//! delete; the rebuilds GC dead terms). Compute itself contains no
13//! geozero, PROJ, S2, or temporal datatype logic.
14//! - [`EncodePlugin`] claims datatype IRIs (`geo:wktLiteral`,
15//! `geo:wkbLiteral`). Every SPARQL/RDF user literal of a claimed datatype
16//! routes through [`encode_user_literal`] (FILTER / CONSTRUCT / BIND / BGP
17//! constants included); native terms decode back through
18//! [`decode_user_literal`] at materialization. The temporal plugin claims
19//! NO datatypes: its terms (`xsd:dateTime`, `xsd:date`, `xsd:gYear`, …)
20//! are storage-native already.
21//! - [`PlannerPlugin`] rewrites lowered [`PlanNode`] trees. The geo rewrite
22//! inspects **`Filter.residual`** conjuncts and recurses into inner plans
23//! and EXISTS clause bodies (never `early`; that tree is all that survives
24//! `lower_pattern` + `split_filter`), and must not drop rows unless its
25//! custom op is a complete implementation of the stripped conjunct.
26//! Repeat executions of an uncorrelated (childless) custom op — EXISTS
27//! NestedProbe re-opens, expr-subst groups, duplicate identical conjuncts —
28//! are covered by the query-local CustomOp memo (see [`ExecutorPlugin`]).
29//! - [`ExecutorPlugin`] dispatches [`PlanNode::CustomNode`] on both evaluation
30//! paths. A `geo_scan` / `temporal_scan` op **materializes** (drains its
31//! stream once) — OpenNode pages the local table, never a second scan RPC.
32//!
33//! Registration is COMPOSED through [`PluginHost`]: every plugin crate
34//! exposes a `register(&mut PluginHost)` that adds its [`RegisteredPlugin`]
35//! and its custom functions to ONE host, and the binary installs the
36//! composed host process-wide exactly once
37//! ([`PluginHost::install_process_wide`]) BEFORE any query is lowered —
38//! `QueryEngine::new` installs the plain builtin casts on the same process
39//! [`CustomFunctions`] map (first install wins), so a late or second
40//! registration would leave `geof:*` / `tf:*` FILTERs erroring `Unsupported`
41//! in `split_filter` rather than planning wrong.
42
43use std::any::Any;
44use std::collections::HashMap;
45use std::future::Future;
46use std::pin::Pin;
47use std::sync::{Arc, OnceLock};
48
49use oxrdf::{Literal, NamedNode};
50use spargebra::algebra::Expression;
51use waratah_storage::{
52 CommitTs, EncodedTerm, GeoCellInterval, GeoEnvelope, GeoIndexPut, StorageOp, StrHash,
53 TemporalCellInterval, TemporalIndexPut, TemporalQueryPredicate, TextIndexDoc,
54 TextSearchRequest, TextSubjectRequest, Variable,
55};
56
57use crate::custom_fns::{CustomFunction, CustomFunctions};
58use crate::error::ComputeError;
59use crate::plan::PlanNode;
60use crate::subject_window::TextSubjectWindow;
61
62/// Typed payload of a [`PlanNode::CustomNode`] (downcast inside the plugin —
63/// never a stringly blob).
64pub trait PluginPayload: Any + Send + Sync + std::fmt::Debug {
65 /// Plugin that minted this payload (`"geosparql"` in v1).
66 fn plugin_id(&self) -> &'static str;
67
68 /// Structural equality for plan reuse/dedup comparisons. The default is
69 /// "never equal", which is safe for opaque payloads (they only lose
70 /// plan-dedup optimizations, never correctness).
71 fn dyn_eq(&self, other: &dyn PluginPayload) -> bool {
72 let _ = other;
73 false
74 }
75
76 /// Deterministic content bytes of the payload, used as the payload
77 /// component of the query-local CustomOp memo key (see
78 /// [`ExecutorPlugin`] for the memoization contract). Two payloads with
79 /// equal `memo_content` bytes must produce identical childless-op
80 /// results within one query. The default — the payload's `Debug`
81 /// rendering — is deterministic for derived `Debug` impls; a plugin
82 /// whose `Debug` is not content-stable should override this with a
83 /// structured binary serialization.
84 fn memo_content(&self) -> Vec<u8> {
85 format!("{self:?}").into_bytes()
86 }
87}
88
89/// Cloneable, comparable box over [`PluginPayload`] so `PlanNode` can keep
90/// its derived `Clone` / `PartialEq` / `Debug`.
91#[derive(Clone, Debug)]
92pub struct PluginPayloadBox(Arc<dyn PluginPayload>);
93
94impl PluginPayloadBox {
95 /// Box a payload.
96 pub fn new(payload: impl PluginPayload + 'static) -> Self {
97 Self(Arc::new(payload))
98 }
99
100 /// Downcast to a concrete payload type.
101 pub fn downcast_ref<T: PluginPayload>(&self) -> Option<&T> {
102 self.0.as_ref().as_any().downcast_ref()
103 }
104
105 /// Plugin id of the boxed payload.
106 pub fn plugin_id(&self) -> &'static str {
107 self.0.plugin_id()
108 }
109
110 /// Deterministic payload-content bytes for the CustomOp memo key
111 /// (forwards to the inner [`PluginPayload::memo_content`]).
112 pub fn memo_content(&self) -> Vec<u8> {
113 self.0.memo_content()
114 }
115}
116
117impl PluginPayload for PluginPayloadBox {
118 fn plugin_id(&self) -> &'static str {
119 self.0.plugin_id()
120 }
121
122 fn dyn_eq(&self, other: &dyn PluginPayload) -> bool {
123 self.0.dyn_eq(other)
124 }
125}
126
127impl PartialEq for PluginPayloadBox {
128 fn eq(&self, other: &Self) -> bool {
129 self.0.dyn_eq(other.0.as_ref())
130 }
131}
132
133impl dyn PluginPayload {
134 /// Downcast hook for [`PluginPayloadBox::downcast_ref`].
135 pub fn as_any(&self) -> &dyn Any {
136 self
137 }
138}
139
140/// What a [`WritePlugin`] returns for one insert batch.
141///
142/// Term rewriting is a **sparse overlay**: `object_rewrites` carries only the
143/// quad positions the plugin actually rewrote (index into the input slice →
144/// native object term), so several write plugins compose — each contributes
145/// its own rewrites and postings over the same plain encoding of the input,
146/// and the fan-out applies them in registration order (two plugins rewriting
147/// one position with DIFFERENT terms is an error; the same term twice is
148/// idempotent).
149#[derive(Debug, Clone, Default)]
150pub struct PreparedInsert {
151 /// Sparse object rewrites: `(input quad index, native object term)`.
152 /// Sorted by index ascending is not required (the applier tolerates any
153 /// order) but plugins emit ascending.
154 pub object_rewrites: Vec<(usize, EncodedTerm)>,
155 /// Content-addressed blobs to put **before** hexastore inserts.
156 /// Payloads are shared from the plugin boundary on (`Arc<[u8]>`): the
157 /// write fan-out clones per batch frame and per retry attempt and
158 /// pre-warms the blob cache without ever copying payload bytes. The
159 /// encoder side (`PreparedGeometryLiteral.blobs`) still owns
160 /// `Vec<u8>` and converts with `Arc::from` — a move, not a copy.
161 pub blobs: Vec<(StrHash, Arc<[u8]>)>,
162 /// Opaque O-axis geometry-index postings (compute-derived S2 cells).
163 /// Sent with the same `commit_ts` as the hexastore records; on Delete
164 /// batches the fan-out discards them (term-liveness: postings are
165 /// keyed by term, never retracted on delete — the rebuilds GC them).
166 pub geo_puts: Vec<GeoIndexPut>,
167 /// Opaque O-axis temporal-index postings (compute-derived dyadic nodes).
168 /// Sent with the same `commit_ts` as the hexastore records; on Delete
169 /// batches the fan-out discards them (term-liveness: postings are
170 /// keyed by term, never retracted on delete — the rebuilds GC them).
171 pub temporal_puts: Vec<TemporalIndexPut>,
172 /// Text-index documents (one per distinct string literal). Unlike the
173 /// geo / temporal postings these are sent BEFORE the three axis
174 /// `InsertQuads` calls (ordering C3: a visible row must never lack its
175 /// document), and Delete batches discard them exactly the same way —
176 /// documents are per-term and never retracted; the rebuild GCs.
177 pub text_docs: Vec<TextIndexDoc>,
178 /// Non-fatal diagnostics produced while preparing the batch. The write
179 /// shells emit these after the batch commits successfully.
180 pub warnings: Vec<String>,
181 /// Number of object rewrites accepted through zero-area geo spike
182 /// reduction. Kept separate from generic warnings so import totals remain
183 /// correct when other plugins add diagnostics.
184 pub spike_reductions: u64,
185}
186
187impl PreparedInsert {
188 /// Encoded size of the geometry-index postings (wire budget accounting).
189 pub fn geo_posting_bytes(&self) -> usize {
190 self.geo_puts
191 .iter()
192 .map(|put| 8 + put.term.len() + 8 + 21)
193 .sum()
194 }
195
196 /// Encoded size of the temporal-index postings (wire budget accounting:
197 /// 16-byte key + term + 8-byte ts + 37-byte value).
198 pub fn temporal_posting_bytes(&self) -> usize {
199 self.temporal_puts
200 .iter()
201 .map(|put| 16 + put.term.len() + 8 + 37)
202 .sum()
203 }
204}
205
206/// Write-path hook (runs on ingest and offline import alike).
207pub trait WritePlugin: Send + Sync {
208 /// Prepare one batch. `commit_ts` is the batch's assigned timestamp; the
209 /// plugin stamps postings with it. `op` distinguishes a put from a delete:
210 /// a plugin may rewrite both to the same native term key, while only puts
211 /// contribute index postings. Must be pure (no I/O, no storage). Term
212 /// rewrites are sparse ([`PreparedInsert::object_rewrites`]) so several
213 /// write plugins compose over one plain encoding.
214 fn prepare_insert(
215 &self,
216 quads: &[oxrdf::Quad],
217 commit_ts: CommitTs,
218 op: StorageOp,
219 ) -> Result<PreparedInsert, ComputeError>;
220}
221
222/// Datatype-owner hook: encode + decode user literals of claimed IRIs.
223pub trait EncodePlugin: Send + Sync {
224 /// Datatype IRIs this plugin owns. Two plugins claiming one IRI is a
225 /// startup error.
226 fn datatypes(&self) -> &[NamedNode];
227
228 /// Parse / transform / mint a native term, or return a hashed typed
229 /// literal on failure. Query constants never create index entries, so
230 /// this hook remains total even when the same literal would be a hard
231 /// error on the stored-geometry write path.
232 ///
233 /// The second component carries the content-addressed payload entries
234 /// (`blob_id → payload bytes`) the encode computed while minting
235 /// (canonical CRS84 EWKB for geometries). Query constants are not
236 /// store data, so these pairs are the ONLY copy of the payload: the
237 /// seeding predicate installs them in the query-local blob map under
238 /// the blob id, where runtime payload fetches (the geo relate loop)
239 /// read them instead of miss-firing a registry RPC for a blob the
240 /// store has never seen. Empty for inline terms (points) and for the
241 /// hashed typed-literal fallback.
242 fn encode_literal(&self, literal: &Literal) -> (EncodedTerm, Vec<(StrHash, Vec<u8>)>);
243
244 /// Render the lexical form of a native term this plugin minted.
245 ///
246 /// `payload` carries the blob bytes for blob-backed terms
247 /// ([`EncodedTerm::LiteralGeometry`] / [`EncodedTerm::BlobLiteral`]);
248 /// compute fetched them before calling. Inline terms (points) get
249 /// `None`. Returns `None` when the term is not this plugin's.
250 fn decode_literal(&self, term: &EncodedTerm, payload: Option<&[u8]>) -> Option<String>;
251}
252
253/// Plan-rewrite hook over the LOWERED plan tree.
254pub trait PlannerPlugin: Send + Sync {
255 /// Walk `node` in place. `ctx` carries the running query's view of the
256 /// store — MVCC snapshot, engine knobs — so a plugin can gate an
257 /// index-only rewrite on index freshness (the geo plugin skips its
258 /// rewrite below the persisted geo-index rebuild epoch). Geo inspects
259 /// `PlanNode::Filter::residual` conjuncts and recurses into inner plans
260 /// and EXISTS clause bodies; repeat executions of the injected childless
261 /// op are covered by the query-local CustomOp memo. Must not drop rows
262 /// unless the injected op is a complete implementation of every stripped
263 /// conjunct.
264 fn rewrite(
265 &self,
266 node: &mut PlanNode,
267 ctx: &crate::context::QueryContext,
268 ) -> Result<(), ComputeError>;
269
270 /// Whether the algebra optimizer must not duplicate this FILTER conjunct.
271 ///
272 /// `true` means the conjunct expands into a **candidate producer** when
273 /// the plan is rewritten — a childless scan op (text / geo / temporal)
274 /// joined into the plan — and a producer built more than once is never
275 /// worth its cost. The algebra optimizer (sparopt) clones a conjunct into
276 /// both inputs of an inner join that binds its variables, and into every
277 /// UNION arm; a subject-mode `text:query` on a seven-arm dimension union
278 /// therefore becomes one full candidate semi-join per binding site of the
279 /// subject.
280 ///
281 /// Pinned conjuncts are substituted behind a variable bound nowhere before
282 /// the optimizer runs, reinstated afterwards, and each placed at the
283 /// lowest common ancestor of its binding sites (see `plan::prepare_algebra`
284 /// and `plan::sink_pinned_conjunct`).
285 ///
286 /// The test must be **purely syntactic**: the algebra carries no query
287 /// context, so a plugin cannot check index trust, configuration gates, or
288 /// whether the filtered variable is bound to an indexed predicate. A
289 /// conjunct pinned but not rewritten stays an ordinary filter evaluated at
290 /// its binding-site ancestor — the same placement the optimizer would pick
291 /// whenever the variable has a single binding site.
292 fn pins_through_optimizer(&self, expression: &Expression) -> bool {
293 let _ = expression;
294 false
295 }
296
297 /// Whether a candidate producer needs its filtered variable to survive the
298 /// lowering's ground-value substitution.
299 ///
300 /// The lowering folds a sibling `VALUES` row or ground `BIND` into the
301 /// conjunct before plan rewrites run (so `VALUES ?poly { … }
302 /// FILTER(geof:sfContains(?poly, ?g))` indexes like the inline form). A
303 /// producer whose rewrite joins its filtered variable back to the store has
304 /// nothing to join on once that variable is grounded, so it answers per row
305 /// instead. Geo answers `true` for its `geof:sf*` comparisons; text answers
306 /// `true` for `text:query` (both modes), whose rewrite needs the variable.
307 /// A producer that only compares a value (temporal) can be folded into a
308 /// constant and leaves the default, as do text's string functions, which
309 /// ground to an exact per-row predicate.
310 ///
311 /// The answer is a property of the **source** expression the plugin claims:
312 /// the guard asks it before substituting, because a shape-sensitive
313 /// predicate stops matching the substituted form.
314 fn keeps_variable_when_ground(&self, expression: &Expression) -> bool {
315 let _ = expression;
316 false
317 }
318}
319
320/// Execution environment handed to [`ExecutorPlugin`].
321///
322/// The closures keep the plugin crate free of client/gRPC types: compute
323/// adapts its hexastore + registry clients into six calls (three candidate
324/// drains — geo, temporal, text literals — the text subject resolve, one blob
325/// fetch, one string resolve).
326pub struct PluginEnv<'a> {
327 /// MVCC snapshot of the running query.
328 pub snapshot: waratah_storage::SnapshotId,
329 /// Drain one `GeoCandidateScan`: merged cell-id intervals + optional
330 /// query envelope + per-drain limit → distinct visible candidate terms.
331 /// Never re-issued with a cursor (see the partition contract). The
332 /// service memoizes per window (`QueryCaches::geo_drains`): the
333 /// candidate list is key-invariant, so repeat drains of one window —
334 /// a keyed execution's later driver pages, EXISTS re-opens — are
335 /// served without an RPC.
336 pub geo_candidates: &'a GeoCandidatesFn<'a>,
337 /// Drain one `TemporalCandidateScan`: merged node-key intervals + the
338 /// exact interval predicate + per-drain limit → distinct visible
339 /// candidate terms. Never re-issued with a cursor (see the partition
340 /// contract — a second RPC would restart the DISTINCT seen-set).
341 pub temporal_candidates: &'a TemporalCandidatesFn<'a>,
342 /// Drain one `TextCandidateScan`: search request → distinct candidate
343 /// terms. One call drains the whole set (never cursor-paged); the
344 /// engine memoizes per window (`QueryCaches::text_drains`) so repeat
345 /// drains of one window within the query are served without an RPC.
346 pub text_candidates: &'a TextCandidatesFn<'a>,
347 /// Resolve one `TextSubjectScan`: the subject-form request → DISTINCT
348 /// `(subject, graph)` rows. The partition runs the candidate search and
349 /// the OPSG resolve itself (the literal→subject join never crosses the
350 /// wire), streams framed pages, and enforces the request's guard: an
351 /// over-limit set is an ERROR after the pages already sent, so a
352 /// consumer must treat a stream error as fatal and discard its rows.
353 /// The engine memoizes per window (`QueryCaches::text_subjects`) so a
354 /// re-execution of one window — a later driver page, an EXISTS re-open —
355 /// is served without a second resolve.
356 pub text_subjects: &'a TextSubjectsFn<'a>,
357 /// Batched blob fetch: content ids → payloads aligned with the request
358 /// (`None` = miss). The executor's 256 MiB LRU sits behind this in the
359 /// compute client adapter, so Relate and output materialization share
360 /// one cache.
361 pub blobs: &'a BlobsFn<'a>,
362 /// Batched registry-string resolve: encoded term value-hashes → raw
363 /// lexical strings aligned with the request (`None` = miss). Sits behind
364 /// the engine's resolve cache like every other resolve path.
365 pub strings: &'a StringsFn<'a>,
366 /// Join-key values pushed from the driver into this op's OUTPUT
367 /// variable (`Some` only on the probe side of a join whose driver
368 /// materialized the key column; `None` = driver side / no pushdown).
369 /// The list is the driver's complete distinct binding set for the
370 /// variable, so an executor may treat it as the exact matching domain —
371 /// relating the keys directly or semi-joining a candidate sweep against
372 /// them. Executions WITH pushed values are not result-memoizable (see the
373 /// [`ExecutorPlugin`] contract); the candidate DRAIN behind
374 /// [`Self::geo_candidates`] is (key-invariant window), so a keyed
375 /// execution still shares one drain with the driver's other pages.
376 pub pushed_vals: Option<&'a [EncodedTerm]>,
377 /// The variable [`Self::pushed_vals`] belongs to: the first output
378 /// variable of the op that the driver materialized. A single-output
379 /// plugin can ignore it; a multi-output one (the text subject form emits
380 /// `subject` and, when the query binds the graph, `graph`) needs it to
381 /// tell a push on one column from a push on the other, because
382 /// `pushed_vals` alone is an unlabelled term list.
383 pub pushed_variable: Option<&'a Variable>,
384}
385
386/// Candidate-drain closure type ([`PluginEnv::geo_candidates`]).
387pub type GeoCandidatesFn<'a> = dyn Fn(
388 &[GeoCellInterval],
389 Option<GeoEnvelope>,
390 u64,
391 ) -> Pin<Box<dyn Future<Output = Result<Vec<EncodedTerm>, ComputeError>> + Send + 'a>>
392 + Send
393 + Sync
394 + 'a;
395
396/// Candidate-drain closure type ([`PluginEnv::temporal_candidates`]).
397pub type TemporalCandidatesFn<'a> = dyn Fn(
398 &[TemporalCellInterval],
399 TemporalQueryPredicate,
400 u64,
401 ) -> Pin<Box<dyn Future<Output = Result<Vec<EncodedTerm>, ComputeError>> + Send + 'a>>
402 + Send
403 + Sync
404 + 'a;
405
406/// Candidate-drain closure type ([`PluginEnv::text_candidates`]).
407pub type TextCandidatesFn<'a> = dyn Fn(
408 &TextSearchRequest,
409 ) -> Pin<Box<dyn Future<Output = Result<Vec<EncodedTerm>, ComputeError>> + Send + 'a>>
410 + Send
411 + Sync
412 + 'a;
413
414/// Subject-resolve closure type ([`PluginEnv::text_subjects`]).
415pub type TextSubjectsFn<'a> = dyn Fn(
416 &TextSubjectRequest,
417 ) -> Pin<
418 Box<
419 dyn Future<Output = Result<std::sync::Arc<TextSubjectWindow>, ComputeError>>
420 + Send
421 + 'a,
422 >,
423 > + Send
424 + Sync
425 + 'a;
426
427/// Batched blob-fetch closure type ([`PluginEnv::blobs`]).
428pub type BlobsFn<'a> = dyn Fn(
429 &[StrHash],
430 ) -> Pin<Box<dyn Future<Output = Result<Vec<Option<Vec<u8>>>, ComputeError>> + Send + 'a>>
431 + Send
432 + Sync
433 + 'a;
434
435/// Batched registry-string-resolve closure type ([`PluginEnv::strings`]).
436pub type StringsFn<'a> = dyn Fn(
437 &[StrHash],
438 ) -> Pin<Box<dyn Future<Output = Result<Vec<Option<String>>, ComputeError>> + Send + 'a>>
439 + Send
440 + Sync
441 + 'a;
442
443/// Materialized-row future of [`ExecutorPlugin::execute`].
444pub type ExecuteFuture<'a> =
445 Pin<Box<dyn Future<Output = Result<Vec<Vec<EncodedTerm>>, ComputeError>> + Send + 'a>>;
446
447/// Executor hook for [`PlanNode::CustomNode`].
448///
449/// # Memoization contract (query-local CustomOp memo)
450///
451/// Compute memoizes the result of every **childless** CustomOp executed
452/// WITHOUT pushed values for the lifetime of ONE query, keyed by
453/// (plugin id, op id, payload content bytes, output variables, snapshot id,
454/// geo index epoch). Therefore a childless CustomOp must be a **pure
455/// function of (payload, snapshot) when executed without pushed values**:
456/// memoization pins every repeated execution within the query — EXISTS
457/// NestedProbe page re-opens, expr-substitution groups, parked-outer pages,
458/// duplicate identical conjuncts — to the first execution's result. The memo
459/// lives in the query's [`crate::filter_residual::QueryCaches`], so it dies
460/// with the query and never crosses queries. An op WITH children depends on
461/// its children's outputs and is never memoized; an execution WITH pushed
462/// keys (or a `pinned` op, whose pinned terms are not part of the memo key)
463/// depends on runtime inputs outside the key and is never memoized either —
464/// its result must be recomputed per execution.
465///
466/// Below the result memo sits the **geo drain memo**
467/// (`QueryCaches::geo_drains`): a `GeoCandidateScan` window's candidate
468/// list is a pure function of (intervals, envelope, limit, snapshot, geo
469/// epoch) — invariant under the pushed-value list — so the engine's
470/// [`PluginEnv::geo_candidates`] service memoizes it per window and a keyed
471/// execution's later pages are served without an RPC. A plugin therefore
472/// gets repeat-drain reuse for its candidate sweeps even where the result
473/// memo refuses (keyed, pinned, children); what it must NOT expect is a
474/// result-level hit for those executions.
475pub trait ExecutorPlugin: Send + Sync {
476 /// Execute the op, returning **materialized rows** — one inner `Vec` per
477 /// row, one [`EncodedTerm`] per op output variable (`op.variables`).
478 /// Both evaluation paths materialize; the OpenNode cursor pages this
479 /// table locally afterwards.
480 fn execute<'a>(
481 &'a self,
482 op: &'a crate::plan::CustomOp,
483 env: PluginEnv<'a>,
484 ) -> ExecuteFuture<'a>;
485}
486
487/// One registered plugin bundle.
488pub struct RegisteredPlugin {
489 /// Stable plugin id (`"geosparql"`).
490 pub id: &'static str,
491 /// Write hook (insert + import).
492 pub write: Option<Arc<dyn WritePlugin>>,
493 /// Datatype encode/decode hook.
494 pub encode: Option<Arc<dyn EncodePlugin>>,
495 /// Plan rewrite hook.
496 pub planner: Option<Arc<dyn PlannerPlugin>>,
497 /// CustomOp execution hook.
498 pub executor: Option<Arc<dyn ExecutorPlugin>>,
499}
500
501/// Process-wide plugin set: datatype map + hooks, registered at startup.
502#[derive(Default)]
503pub struct PluginRegistry {
504 plugins: Vec<RegisteredPlugin>,
505 /// Datatype IRI → owning plugin index (built once at registration).
506 datatype_map: HashMap<String, usize>,
507}
508
509impl PluginRegistry {
510 /// An empty registry (no plugins).
511 pub fn empty() -> Self {
512 Self::default()
513 }
514
515 /// Register `plugin`. Errors when its `EncodePlugin` claims a datatype
516 /// another plugin already owns.
517 pub fn register(&mut self, plugin: RegisteredPlugin) -> Result<(), ComputeError> {
518 if let Some(encode) = &plugin.encode {
519 for datatype in encode.datatypes() {
520 let key = datatype.as_str().to_owned();
521 if self.datatype_map.contains_key(&key) {
522 return Err(ComputeError::UnsupportedSparql(format!(
523 "datatype {key} is already claimed by another plugin"
524 )));
525 }
526 self.datatype_map.insert(key, self.plugins.len());
527 }
528 }
529 self.plugins.push(plugin);
530 Ok(())
531 }
532
533 /// Plugin index owning `datatype`, if any.
534 pub fn plugin_for_datatype(&self, datatype: &NamedNode) -> Option<&dyn EncodePlugin> {
535 self.datatype_map
536 .get(datatype.as_str())
537 .and_then(|&index| self.plugins[index].encode.as_deref())
538 }
539
540 /// Every registered write plugin (registration order).
541 pub fn write_plugins(&self) -> impl Iterator<Item = &dyn WritePlugin> {
542 self.plugins
543 .iter()
544 .filter_map(|plugin| plugin.write.as_deref())
545 }
546
547 /// Every registered planner plugin (registration order).
548 pub fn planner_plugins(&self) -> impl Iterator<Item = &dyn PlannerPlugin> {
549 self.plugins
550 .iter()
551 .filter_map(|plugin| plugin.planner.as_deref())
552 }
553
554 /// Executor plugin minted by `plugin_id`, if any.
555 pub fn executor_for(&self, plugin_id: &str) -> Option<&dyn ExecutorPlugin> {
556 self.plugins
557 .iter()
558 .find(|plugin| plugin.id == plugin_id)
559 .and_then(|plugin| plugin.executor.as_deref())
560 }
561
562 /// Whether any plugin is registered (cheap check on hot paths).
563 pub fn is_empty(&self) -> bool {
564 self.plugins.is_empty()
565 }
566}
567
568/// Composition point for the process-wide plugin + custom-function
569/// registries.
570///
571/// Each plugin crate exposes a `register(&mut PluginHost)` that adds its
572/// [`RegisteredPlugin`] and its custom functions to ONE host; the binary
573/// (e.g. `waratah_bin/src/main.rs`) then installs the composed host
574/// process-wide EXACTLY ONCE, before any `QueryEngine` exists. This is the
575/// fix for the first-install-wins trap: two self-installing plugins would
576/// silently drop the second plugin's registry entries, and the loser would
577/// also have dropped the winner's custom functions (each map starting from
578/// `with_builtins()`). Registration-time conflicts — a datatype IRI claimed
579/// by two plugins, a duplicate function IRI — error here, at the composition
580/// site, instead of silently no-op'ing at install time.
581pub struct PluginHost {
582 /// The one plugin registry (datatype map + hooks).
583 registry: PluginRegistry,
584 /// The one custom-function map, starting from the builtin XSD casts.
585 functions: CustomFunctions,
586}
587
588impl Default for PluginHost {
589 fn default() -> Self {
590 Self {
591 registry: PluginRegistry::empty(),
592 functions: CustomFunctions::with_builtins(),
593 }
594 }
595}
596
597impl PluginHost {
598 /// An empty host over the builtin XSD casts.
599 pub fn new() -> Self {
600 Self::default()
601 }
602
603 /// Whether any plugin bundle is registered (test / composition checks).
604 pub fn registry_is_empty(&self) -> bool {
605 self.registry.is_empty()
606 }
607
608 /// Merge one plugin bundle into the shared registry. A datatype-IRI
609 /// claim conflict with an already-registered plugin errors here
610 /// ([`PluginRegistry::register`]).
611 pub fn register(&mut self, plugin: RegisteredPlugin) -> Result<(), ComputeError> {
612 self.registry.register(plugin)
613 }
614
615 /// Add custom functions to the ONE shared map (the builtin XSD casts are
616 /// already on it). Duplicate IRIs error ([`CustomFunctions::register`]).
617 pub fn register_functions(
618 &mut self,
619 functions: Vec<CustomFunction>,
620 ) -> Result<(), ComputeError> {
621 for function in functions {
622 self.functions.register(function)?;
623 }
624 Ok(())
625 }
626
627 /// Set BOTH process-wide registries from the composed host.
628 ///
629 /// Builtins + every registered plugin's functions live on one map: the
630 /// engine's own install is a no-op once this landed first (first install
631 /// wins, both are correct registries). The underlying setters keep their
632 /// first-wins semantics — a second install is a silent no-op — so this
633 /// must be the process's ONLY host install, and it must happen BEFORE
634 /// any `QueryEngine` is constructed (the engine would otherwise install
635 /// plain builtins on the custom-function map, after which plugin
636 /// functions can never land).
637 pub fn install_process_wide(self) {
638 debug_assert!(
639 PROCESS_PLUGINS.get().is_none(),
640 "PluginHost::install_process_wide called twice; the second composed set is dropped"
641 );
642 install_process_plugins(Arc::new(self.registry));
643 crate::install_process_registry(Arc::new(self.functions));
644 }
645}
646
647static PROCESS_PLUGINS: OnceLock<Arc<PluginRegistry>> = OnceLock::new();
648
649/// Install the process-lifetime plugin registry (first install wins, like
650/// the custom-function registry). Called by `ComputeNode` startup; a second
651/// call is a no-op and `registry` is dropped.
652pub fn install_process_plugins(registry: Arc<PluginRegistry>) {
653 let _ = PROCESS_PLUGINS.set(registry);
654}
655
656/// The process plugin registry (empty when nothing was installed, so
657/// library tests and plugin-less deployments take the plain path).
658pub fn process_plugins() -> &'static Arc<PluginRegistry> {
659 static EMPTY: OnceLock<Arc<PluginRegistry>> = OnceLock::new();
660 PROCESS_PLUGINS.get_or_init(|| {
661 EMPTY
662 .get_or_init(|| Arc::new(PluginRegistry::empty()))
663 .clone()
664 })
665}
666
667/// Encode a SPARQL/RDF **user literal** through the plugin datatype map.
668///
669/// The ONE helper every `EncodedTerm::from(literal)` call site for user
670/// literals must go through (plan lowering, FILTER, CONSTRUCT, BIND, VALUES):
671/// a claimed datatype routes to the owning plugin's `encode_literal`, a miss
672/// falls back to the storage-native `From<&Literal>` (xsd integers, strings,
673/// unknown typed literals). `xsd:string` / `rdf:langString` stay on the
674/// storage path — the geo plugin does not claim them.
675///
676/// Missing a call site (still using raw `From`) is a bug: the map only
677/// decides *which plugin*, not *whether compute remembered the helper*.
678pub fn encode_user_literal(literal: &Literal) -> EncodedTerm {
679 encode_user_literal_with_payloads(literal).0
680}
681
682/// [`encode_user_literal`] with the mint's payload pairs retained — the
683/// form every seeding site uses (the term-only wrapper serves matching
684/// and comparison sites that never decode). The pairs are the only copy
685/// of a query constant's blob payload; see [`EncodePlugin::encode_literal`].
686pub fn encode_user_literal_with_payloads(
687 literal: &Literal,
688) -> (EncodedTerm, Vec<(StrHash, Vec<u8>)>) {
689 let registry = process_plugins();
690 if registry.is_empty() {
691 return (EncodedTerm::from(literal), Vec::new());
692 }
693 match registry.plugin_for_datatype(&literal.datatype().into_owned()) {
694 Some(plugin) => plugin.encode_literal(literal),
695 None => (EncodedTerm::from(literal), Vec::new()),
696 }
697}
698
699/// Decode a native plugin term back to its lexical form.
700///
701/// `payload` is the blob payload for blob-backed terms (the caller fetched
702/// it — compute materialization prefetches blobs of projected columns before
703/// calling this). Returns `None` when no plugin owns the term.
704pub fn decode_user_literal(term: &EncodedTerm, payload: Option<&[u8]>) -> Option<String> {
705 let registry = process_plugins();
706 if registry.is_empty() {
707 return None;
708 }
709 registry.plugins.iter().find_map(|registered| {
710 registered
711 .encode
712 .as_deref()
713 .and_then(|encode| encode.decode_literal(term, payload))
714 })
715}
716
717/// Variable helper: build a plan-time `Variable`.
718pub fn variable(name: &str) -> Variable {
719 Variable::new(name).expect("plugin variables are valid SPARQL names")
720}
721
722#[cfg(test)]
723mod tests {
724 use super::*;
725 use waratah_storage::CrsId;
726
727 #[derive(Debug, PartialEq)]
728 struct TestPayload {
729 cell: u64,
730 }
731
732 impl PluginPayload for TestPayload {
733 fn plugin_id(&self) -> &'static str {
734 "test"
735 }
736
737 fn dyn_eq(&self, other: &dyn PluginPayload) -> bool {
738 other
739 .as_any()
740 .downcast_ref::<TestPayload>()
741 .is_some_and(|other| *other == *self)
742 }
743 }
744
745 #[test]
746 fn payload_box_downcasts_and_compares() {
747 let a = PluginPayloadBox::new(TestPayload { cell: 7 });
748 let b = PluginPayloadBox::new(TestPayload { cell: 7 });
749 let c = PluginPayloadBox::new(TestPayload { cell: 8 });
750 assert_eq!(a, b);
751 assert_ne!(a, c);
752 assert_eq!(a.downcast_ref::<TestPayload>().unwrap().cell, 7);
753 assert_eq!(a.plugin_id(), "test");
754 }
755
756 #[test]
757 fn empty_registry_falls_back_to_storage_encoding() {
758 // No plugins installed in this test binary (first install wins and
759 // nothing installed the geo plugin here).
760 let literal = Literal::new_typed_literal("POINT(1 2)", {
761 NamedNode::new_unchecked("http://www.opengis.net/ont/geosparql#wktLiteral")
762 });
763 let encoded = encode_user_literal(&literal);
764 match encoded {
765 EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. } => {}
766 EncodedTerm::LiteralPoint { crs, .. } => {
767 // If another test in this binary installed the geo plugin,
768 // the datatype map correctly claims this literal.
769 assert_eq!(crs, CrsId::Crs84);
770 }
771 other => panic!("unexpected encoding {other:?}"),
772 }
773 }
774}