Skip to main content

waratah_temporal/
exec.rs

1//! ExecutorPlugin: materialize `temporal_scan` (dyadic candidates → exact
2//! comparison residual) and the unindexed `tf:*` custom functions.
3//!
4//! The scan mirrors `geo_scan`'s FOUR runtime behaviors (pinned candidate /
5//! small pushed key list / large pushed list semi-join / driver sweep), but
6//! the exact residual is integer-cheap: each candidate is projected onto the
7//! tick axis ([`waratah_storage::temporal_term_interval`]) and evaluated
8//! against the stripped comparisons with SPARQL/XSD semantics ([`compare`]).
9//! The partition's exact-interval reject already dropped the definitely-false
10//! postings; this residual re-implements the FILTER truth table (timezone
11//! partial order, cross-family type errors) so rows are kept exactly as the
12//! unindexed FILTER would keep them.
13//!
14//! Every drain path drains exactly once (`TemporalCandidateScan` is never
15//! cursor-paged). Pushed-key executions are not memoizable; driver-side
16//! executions keep the query-local CustomOp memo.
17
18use std::collections::HashSet;
19use std::future::Future;
20use std::pin::Pin;
21
22use waratah_compute::ComputeError;
23use waratah_compute::CustomEval;
24use waratah_compute::CustomFunction;
25use waratah_compute::CustomOp;
26use waratah_compute::plugin::{ExecutorPlugin, PluginEnv, PluginPayload};
27use waratah_storage::{EncodedTerm, TemporalCellInterval, TemporalQueryPredicate};
28
29use crate::TF_NAMESPACE;
30
31/// Pushed-key lists at or below this length are evaluated DIRECTLY against
32/// the stripped comparisons — no `TemporalCandidateScan` RPC at all (the
33/// projection is pure integer work, so the direct branch tolerates a larger
34/// list than geo's relate limit; the semi-join still wins beyond it).
35const TEMPORAL_DIRECT_EVAL_LIMIT: usize = 2_000;
36
37/// One stripped comparison conjunct: `?var OP const` (orientation
38/// normalized at rewrite time — the variable is always the left operand).
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct StrippedComparison {
41    /// Normalized operator (variable on the left).
42    pub op: CompareOp,
43    /// The const's native temporal term.
44    pub const_term: EncodedTerm,
45}
46
47/// Comparison operators the rewrite serves (SPARQL numeric-style ordering
48/// operators over temporal values).
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum CompareOp {
51    /// `<`
52    Less,
53    /// `<=`
54    LessOrEqual,
55    /// `>`
56    Greater,
57    /// `>=`
58    GreaterOrEqual,
59}
60
61impl CompareOp {
62    /// Apply the operator to an ordering.
63    fn decide(self, ordering: std::cmp::Ordering) -> bool {
64        use std::cmp::Ordering::*;
65        match self {
66            Self::Less => ordering == Less,
67            Self::LessOrEqual => ordering != Greater,
68            Self::Greater => ordering == Greater,
69            Self::GreaterOrEqual => ordering != Less,
70        }
71    }
72}
73
74/// Typed payload of the `temporal_scan` CustomOp (downcast by the executor).
75#[derive(Debug, Clone, PartialEq)]
76pub struct TemporalScanPayload {
77    /// The stripped comparisons (the exact residual, evaluated per
78    /// candidate after the partition's conservative reject).
79    pub comparisons: Vec<StrippedComparison>,
80    /// The conservative query window as merged key intervals (descendant
81    /// ranges ∪ exact ancestor keys).
82    pub intervals: Vec<TemporalCellInterval>,
83}
84
85impl PluginPayload for TemporalScanPayload {
86    fn plugin_id(&self) -> &'static str {
87        crate::PLUGIN_ID
88    }
89
90    fn dyn_eq(&self, other: &dyn PluginPayload) -> bool {
91        other
92            .as_any()
93            .downcast_ref::<TemporalScanPayload>()
94            .is_some_and(|other| *other == *self)
95    }
96
97    /// Deterministic payload-content bytes for the query-local CustomOp memo
98    /// key: every field the scan depends on, little-endian binary.
99    fn memo_content(&self) -> Vec<u8> {
100        let mut out = Vec::new();
101        for comparison in &self.comparisons {
102            out.push(match comparison.op {
103                CompareOp::Less => 0,
104                CompareOp::LessOrEqual => 1,
105                CompareOp::Greater => 2,
106                CompareOp::GreaterOrEqual => 3,
107            });
108            out.extend_from_slice(&waratah_storage::encode_term_bytes(&comparison.const_term));
109        }
110        out.push(0xFF);
111        for interval in &self.intervals {
112            out.extend_from_slice(&interval.min_key.to_le_bytes());
113            out.extend_from_slice(&interval.max_key.to_le_bytes());
114        }
115        out
116    }
117}
118
119/// Temporal executor hook.
120#[derive(Debug, Default)]
121pub struct TemporalExecutorPlugin;
122
123impl ExecutorPlugin for TemporalExecutorPlugin {
124    fn execute<'a>(
125        &'a self,
126        op: &'a CustomOp,
127        env: PluginEnv<'a>,
128    ) -> Pin<Box<dyn Future<Output = Result<Vec<Vec<EncodedTerm>>, ComputeError>> + Send + 'a>>
129    {
130        Box::pin(async move {
131            if op.op_id != crate::plan::TEMPORAL_SCAN_OP_ID {
132                return Err(ComputeError::UnsupportedSparql(format!(
133                    "unknown temporal op {}",
134                    op.op_id
135                )));
136            }
137            if op.variables.len() != 1 {
138                return Err(ComputeError::UnsupportedSparql(
139                    "temporal_scan emits exactly one variable".into(),
140                ));
141            }
142            let Some(payload) = op.payload.downcast_ref::<TemporalScanPayload>() else {
143                return Err(ComputeError::UnsupportedSparql(
144                    "temporal_scan payload is not a TemporalScanPayload".into(),
145                ));
146            };
147            let output_variable = &op.variables[0];
148
149            // Runtime behavior selection, in priority order (the geo scan's
150            // four behaviors; the exact test is integer-cheap, no blobs).
151            // 1. Pinned candidate (plan-stamped broadcast ground driver).
152            if let Some((_, term)) = op
153                .pinned
154                .iter()
155                .find(|(variable, _)| variable == output_variable)
156            {
157                return Ok(evaluate_terms(std::slice::from_ref(term), payload));
158            }
159            match env.pushed_vals {
160                // 2. Small pushed list: evaluate the deduped driver keys
161                //    directly — no candidate scan RPC.
162                Some(keys) if keys.len() <= TEMPORAL_DIRECT_EVAL_LIMIT => {
163                    let distinct: HashSet<&EncodedTerm> = keys.iter().collect();
164                    let terms: Vec<EncodedTerm> = distinct.into_iter().cloned().collect();
165                    Ok(evaluate_terms(&terms, payload))
166                }
167                // 3. Large pushed list: one candidate drain, then semi-join
168                //    the candidates against the key set BEFORE evaluating.
169                Some(keys) => {
170                    let key_set: HashSet<&EncodedTerm> = keys.iter().collect();
171                    let candidates = drain_candidates(payload, &env).await?;
172                    let survivors: Vec<EncodedTerm> = candidates
173                        .into_iter()
174                        .filter(|term| key_set.contains(term))
175                        .collect();
176                    Ok(evaluate_terms(&survivors, payload))
177                }
178                // 4. No pushed keys (driver side): the sweep.
179                None => {
180                    let candidates = drain_candidates(payload, &env).await?;
181                    Ok(evaluate_terms(&candidates, payload))
182                }
183            }
184        })
185    }
186}
187
188/// One `TemporalCandidateScan` drain — never cursor-paged (a second RPC
189/// would restart the partition's DISTINCT seen-set). No per-drain limit:
190/// SPARQL LIMIT applies above the join.
191async fn drain_candidates(
192    payload: &TemporalScanPayload,
193    env: &PluginEnv<'_>,
194) -> Result<Vec<EncodedTerm>, ComputeError> {
195    // The scan's predicate is the conservative window reject (the merged
196    // comparisons' span); the exact per-row truth is `evaluate_terms`.
197    let window = window_of(&payload.comparisons);
198    (env.temporal_candidates)(&payload.intervals, window, 0).await
199}
200
201/// The conservative partition-side window implied by the stripped
202/// comparisons (the same bounds the rewrite scanned with).
203///
204/// Every temporal term projects to a CLOSED tick interval
205/// ([`waratah_storage::temporal_term_interval`]), so each bound takes the
206/// EDGE of the const's interval that its operator points at: lower bounds
207/// (`>=` / `>`) take `begin`, upper bounds (`<=` / `<`) take `end`.
208///
209/// The rule is **family-agnostic**: `dateTime` (both timezone flavors),
210/// `date`, `gYear` and `gYearMonth` are all read through their projected
211/// shape, and the derivation never asks which datatype it is looking at.
212/// That is deliberate — a per-family rule has to be justified per family,
213/// and the one that landed before this (the interval MIDPOINT for every
214/// non-instant shape) was only defensible for the timezone-absent
215/// `dateTime`/`date` case, where the interval is uncertainty symmetric
216/// around a reading. A `gYear`'s interval is a real span compared by its
217/// START ([`compare`]), so a midpoint floor dropped candidates the residual
218/// keeps: `FILTER(?t >= "2025"^^xsd:gYear)` scored a satisfying
219/// `"2025-01"^^xsd:gYearMonth` against a floor in July and lost it.
220///
221/// Why the edges are a superset for every family: the residual keeps a
222/// candidate only when it is ordered at-or-after the const, which forces
223/// `candidate.begin >= const.begin`, so the candidate's shape must reach
224/// past a `begin` floor; upper bounds are the mirror image (`candidate.begin
225/// <= const.begin <= const.end`). Both sides of both arguments use nothing
226/// but interval ordering (`begin <= end`), which all four families share by
227/// construction. An instant is the degenerate interval (`begin == end`), so
228/// it needs no special case.
229///
230/// Strictness is deliberately NOT expressed here — `>` draws the same
231/// `begin` as `>=`, `<` the same `end` as `<=`. The exact residual decides
232/// strictness per row, and a one-attosecond nudge would reject a candidate
233/// sitting exactly on a closed-interval const's edge. One-sided comparisons
234/// leave the opposite bound at the axis extreme, which makes the window a
235/// strict superset of the previous (nudged, midpoint-centred) one.
236pub(crate) fn window_of(comparisons: &[StrippedComparison]) -> TemporalQueryPredicate {
237    let mut lo = i128::MIN;
238    let mut hi = i128::MAX;
239    for comparison in comparisons {
240        // Unprojectable const (non-temporal term): no bound contribution.
241        // The rewrite never strips such a comparison, so this is defensive.
242        let Some(shape) = waratah_storage::temporal_term_interval(&comparison.const_term) else {
243            continue;
244        };
245        match comparison.op {
246            CompareOp::Less | CompareOp::LessOrEqual => hi = hi.min(shape.end),
247            CompareOp::Greater | CompareOp::GreaterOrEqual => lo = lo.max(shape.begin),
248        }
249    }
250    TemporalQueryPredicate::Overlaps { begin: lo, end: hi }
251}
252
253/// Evaluate the stripped comparisons exactly over `terms`, emitting one row
254/// per distinct term that satisfies ALL of them under SPARQL semantics.
255///
256/// A term that does not project (non-temporal term in the join key column —
257/// possible on the pushed-key paths) never satisfies a comparison: skip,
258/// same as a FILTER type error dropping the row.
259pub(crate) fn evaluate_terms(
260    terms: &[EncodedTerm],
261    payload: &TemporalScanPayload,
262) -> Vec<Vec<EncodedTerm>> {
263    let mut out_rows = Vec::new();
264    for term in terms {
265        if comparisons_hold(term, &payload.comparisons) {
266            out_rows.push(vec![term.clone()]);
267        }
268    }
269    out_rows
270}
271
272/// The exact per-row truth of the stripped comparisons (the FILTER
273/// re-implementation): every comparison must hold; `false` on projection
274/// failure, cross-family pairs, or indeterminate timezone orderings — the
275/// same rows an unindexed `FILTER(... && ...)` keeps.
276pub(crate) fn comparisons_hold(term: &EncodedTerm, comparisons: &[StrippedComparison]) -> bool {
277    comparisons
278        .iter()
279        .all(|comparison| compare(term, comparison.op, &comparison.const_term) == Some(true))
280}
281
282/// Exact SPARQL comparison `term OP const` over temporal values.
283///
284/// Returns `None` where SPARQL's FILTER would error (non-temporal operand,
285/// cross-family pair) — the caller drops the row, as `FILTER` does.
286///
287/// | Left family | Right family | Semantics |
288/// |---|---|---|
289/// | dateTime(Stamp) | dateTime(Stamp) | XSD partial order (`oxsdatatypes`: timezone-present exact; timezone-absent true only outside the ±14 h uncertainty) |
290/// | date | date | XSD partial order, same rules |
291/// | gYear / gYearMonth | gYear / gYearMonth | documented extension: compare projected interval START ticks |
292/// | anything else | — | type error |
293pub(crate) fn compare(term: &EncodedTerm, op: CompareOp, const_term: &EncodedTerm) -> Option<bool> {
294    use waratah_storage::EncodedTerm::*;
295    match (term, const_term) {
296        (DateTimeLiteral(a), DateTimeLiteral(b)) => {
297            a.partial_cmp(b).map(|ordering| op.decide(ordering))
298        }
299        (DateLiteral(a), DateLiteral(b)) => a.partial_cmp(b).map(|ordering| op.decide(ordering)),
300        // The documented extension for the pair SPARQL 1.1 forgot (gated by
301        // `strict-sparql` at rewrite time; the residual keeps the extension
302        // semantics so index and unindexed paths agree in either mode).
303        (GYearLiteral(_) | GYearMonthLiteral(_), GYearLiteral(_) | GYearMonthLiteral(_)) => {
304            let a = waratah_storage::temporal_term_interval(term)?;
305            let b = waratah_storage::temporal_term_interval(const_term)?;
306            Some(op.decide(a.begin.cmp(&b.begin)))
307        }
308        _ => None,
309    }
310}
311
312/// Evaluate one unindexed `tf:*` call over RESOLVED terms (ground path).
313///
314/// Both arguments must be temporal LITERALS — the relation reduces to
315/// interval arithmetic over their projections. An entity (IRI / blank node)
316/// argument has NO position on the axis without its OWL-Time structure
317/// triples, which a ground evaluation cannot fetch (the Tier-2 rewrite
318/// serves those shapes with structure joins; until a call with entity
319/// arguments is rewritten it errors here, and a FILTER error drops the
320/// row). This is the documented v1 boundary.
321pub fn eval_tf_function(iri: &str, args: &[oxrdf::Term]) -> CustomEval {
322    let Some(relation) = TfRelation::from_iri(iri) else {
323        return CustomEval::Error;
324    };
325    if args.len() != 2 {
326        return CustomEval::Error;
327    }
328    let mut shapes: Vec<waratah_storage::TemporalShape> = Vec::with_capacity(2);
329    for arg in args {
330        let oxrdf::Term::Literal(literal) = arg else {
331            return CustomEval::Error;
332        };
333        let encoded = waratah_storage::EncodedTerm::from(literal);
334        match waratah_storage::temporal_term_interval(&encoded) {
335            Some(shape) => shapes.push(shape),
336            None => return CustomEval::Error,
337        }
338    }
339    let (a, b) = (shapes[0], shapes[1]);
340    CustomEval::Term(oxrdf::Term::Literal(oxrdf::Literal::from(
341        relation.holds(a, b),
342    )))
343}
344
345/// The timefuncs / Allen relations (both timefuncs' own eight names and the
346/// completing Allen set the vocabulary owner approved adding under `tf:`).
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub enum TfRelation {
349    /// `tf:isBefore` — a ends before b begins.
350    IsBefore,
351    /// `tf:isAfter` — a begins after b ends.
352    IsAfter,
353    /// `tf:contains` / `tf:hasDuring` — a strictly contains b.
354    Contains,
355    /// `tf:isContainedBy` / `tf:isDuring` — a strictly inside b.
356    IsContainedBy,
357    /// `tf:isInside` — instant a within interval b.
358    IsInside,
359    /// `tf:hasInside` — interval a contains instant b.
360    HasInside,
361    /// `tf:meets` — a ends exactly where b begins.
362    Meets,
363    /// `tf:metBy` — b ends exactly where a begins.
364    MetBy,
365    /// `tf:overlaps` — a and b intersect with a starting first.
366    Overlaps,
367    /// `tf:overlappedBy` — a and b intersect with b starting first.
368    OverlappedBy,
369    /// `tf:starts` — a shares b's begin and ends earlier.
370    Starts,
371    /// `tf:startedBy` — a shares b's begin and ends later.
372    StartedBy,
373    /// `tf:finishes` — a shares b's end and begins later.
374    Finishes,
375    /// `tf:finishedBy` — a shares b's end and begins earlier.
376    FinishedBy,
377    /// `tf:equals` — identical intervals.
378    Equals,
379}
380
381impl TfRelation {
382    /// Parse one `tf:` function IRI's local name.
383    pub fn from_iri(iri: &str) -> Option<Self> {
384        let local = iri.strip_prefix(TF_NAMESPACE)?;
385        Some(match local {
386            "isBefore" => Self::IsBefore,
387            "isAfter" => Self::IsAfter,
388            "contains" | "hasDuring" => Self::Contains,
389            "isContainedBy" | "isDuring" => Self::IsContainedBy,
390            "isInside" => Self::IsInside,
391            "hasInside" => Self::HasInside,
392            "meets" => Self::Meets,
393            "metBy" => Self::MetBy,
394            "overlaps" => Self::Overlaps,
395            "overlappedBy" => Self::OverlappedBy,
396            "starts" => Self::Starts,
397            "startedBy" => Self::StartedBy,
398            "finishes" => Self::Finishes,
399            "finishedBy" => Self::FinishedBy,
400            "equals" => Self::Equals,
401            _ => return None,
402        })
403    }
404
405    /// The function IRI.
406    #[allow(dead_code)] // exercised by unit tests below + future rewrite tier
407    pub fn iri(self) -> &'static str {
408        match self {
409            Self::IsBefore => concat!("https://w3id.org/timefuncs/", "isBefore"),
410            Self::IsAfter => concat!("https://w3id.org/timefuncs/", "isAfter"),
411            Self::Contains => concat!("https://w3id.org/timefuncs/", "contains"),
412            Self::IsContainedBy => concat!("https://w3id.org/timefuncs/", "isContainedBy"),
413            Self::IsInside => concat!("https://w3id.org/timefuncs/", "isInside"),
414            Self::HasInside => concat!("https://w3id.org/timefuncs/", "hasInside"),
415            Self::Meets => concat!("https://w3id.org/timefuncs/", "meets"),
416            Self::MetBy => concat!("https://w3id.org/timefuncs/", "metBy"),
417            Self::Overlaps => concat!("https://w3id.org/timefuncs/", "overlaps"),
418            Self::OverlappedBy => concat!("https://w3id.org/timefuncs/", "overlappedBy"),
419            Self::Starts => concat!("https://w3id.org/timefuncs/", "starts"),
420            Self::StartedBy => concat!("https://w3id.org/timefuncs/", "startedBy"),
421            Self::Finishes => concat!("https://w3id.org/timefuncs/", "finishes"),
422            Self::FinishedBy => concat!("https://w3id.org/timefuncs/", "finishedBy"),
423            Self::Equals => concat!("https://w3id.org/timefuncs/", "equals"),
424        }
425    }
426
427    /// Interval-arithmetic truth of the relation for shapes `a` and `b`.
428    /// Instants are degenerate intervals; `contains`/`isContainedBy` follow
429    /// timefuncs' "proper" reading (equal intervals do not contain).
430    pub fn holds(
431        self,
432        a: waratah_storage::TemporalShape,
433        b: waratah_storage::TemporalShape,
434    ) -> bool {
435        let (ab, ae) = (a.begin, a.end);
436        let (bb, be) = (b.begin, b.end);
437        match self {
438            Self::IsBefore => ae < bb,
439            Self::IsAfter => ab > be,
440            Self::Contains => ab < bb && ae > be,
441            Self::IsContainedBy => bb < ab && be > ae,
442            Self::IsInside => bb <= ab && ae <= be,
443            Self::HasInside => ab <= bb && be <= ae,
444            Self::Meets => ae == bb,
445            Self::MetBy => be == ab,
446            Self::Overlaps => ab < bb && bb < ae && ae < be,
447            Self::OverlappedBy => bb < ab && ab < be && be < ae,
448            Self::Starts => ab == bb && ae < be,
449            Self::StartedBy => ab == bb && ae > be,
450            Self::Finishes => ae == be && ab > bb,
451            Self::FinishedBy => ae == be && ab < bb,
452            Self::Equals => ab == bb && ae == be,
453        }
454    }
455
456    /// Every registered relation with its callable names (synonyms share a
457    /// relation with distinct IRIs).
458    #[allow(dead_code)] // exercised by unit tests below + future rewrite tier
459    pub fn all_named() -> Vec<(Self, &'static str)> {
460        use TfRelation::*;
461        vec![
462            (IsBefore, "isBefore"),
463            (IsAfter, "isAfter"),
464            (Contains, "contains"),
465            (Contains, "hasDuring"),
466            (IsContainedBy, "isContainedBy"),
467            (IsContainedBy, "isDuring"),
468            (IsInside, "isInside"),
469            (HasInside, "hasInside"),
470            (Meets, "meets"),
471            (MetBy, "metBy"),
472            (Overlaps, "overlaps"),
473            (OverlappedBy, "overlappedBy"),
474            (Starts, "starts"),
475            (StartedBy, "startedBy"),
476            (Finishes, "finishes"),
477            (FinishedBy, "finishedBy"),
478            (Equals, "equals"),
479        ]
480    }
481}
482
483// Plain `fn` pointers (custom functions cannot capture): one shim per IRI,
484// generated by the macro below and dispatched through [`eval_tf_named`].
485macro_rules! tf_shims {
486    ($($name:ident => $local:literal),* $(,)?) => {
487        $(
488            fn $name(args: &[oxrdf::Term]) -> CustomEval {
489                eval_tf_named(concat!("https://w3id.org/timefuncs/", $local), args)
490            }
491        )*
492    };
493}
494
495fn eval_tf_named(iri: &str, args: &[oxrdf::Term]) -> CustomEval {
496    eval_tf_function(iri, args)
497}
498
499tf_shims! {
500    eval_tf_is_before => "isBefore",
501    eval_tf_is_after => "isAfter",
502    eval_tf_contains => "contains",
503    eval_tf_has_during => "hasDuring",
504    eval_tf_is_contained_by => "isContainedBy",
505    eval_tf_is_during => "isDuring",
506    eval_tf_is_inside => "isInside",
507    eval_tf_has_inside => "hasInside",
508    eval_tf_meets => "meets",
509    eval_tf_met_by => "metBy",
510    eval_tf_overlaps => "overlaps",
511    eval_tf_overlapped_by => "overlappedBy",
512    eval_tf_starts => "starts",
513    eval_tf_started_by => "startedBy",
514    eval_tf_finishes => "finishes",
515    eval_tf_finished_by => "finishedBy",
516    eval_tf_equals => "equals",
517}
518
519/// Register the `tf:*` custom functions (unindexed ground fallback).
520///
521/// `eval_encoded = None` ⇒ [`waratah_compute::ExprCapability::AlwaysResolve`]
522/// semantics: the ground evaluator needs resolved terms.
523pub fn tf_custom_functions() -> Vec<CustomFunction> {
524    type TfShim = (&'static str, fn(&[oxrdf::Term]) -> CustomEval);
525    let shims: Vec<TfShim> = vec![
526        ("isBefore", eval_tf_is_before),
527        ("isAfter", eval_tf_is_after),
528        ("contains", eval_tf_contains),
529        ("hasDuring", eval_tf_has_during),
530        ("isContainedBy", eval_tf_is_contained_by),
531        ("isDuring", eval_tf_is_during),
532        ("isInside", eval_tf_is_inside),
533        ("hasInside", eval_tf_has_inside),
534        ("meets", eval_tf_meets),
535        ("metBy", eval_tf_met_by),
536        ("overlaps", eval_tf_overlaps),
537        ("overlappedBy", eval_tf_overlapped_by),
538        ("starts", eval_tf_starts),
539        ("startedBy", eval_tf_started_by),
540        ("finishes", eval_tf_finishes),
541        ("finishedBy", eval_tf_finished_by),
542        ("equals", eval_tf_equals),
543    ];
544    shims
545        .into_iter()
546        .map(|(local, eval_ground)| CustomFunction {
547            iri: oxrdf::NamedNode::new_unchecked(format!("{TF_NAMESPACE}{local}")),
548            min_args: 2,
549            max_args: 2,
550            eval_ground,
551            eval_encoded: None,
552            eval_encoded_cached: None,
553        })
554        .collect()
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560    use waratah_storage::EncodedTerm;
561
562    fn dt(text: &str) -> EncodedTerm {
563        EncodedTerm::DateTimeLiteral(text.parse().unwrap())
564    }
565
566    fn date(text: &str) -> EncodedTerm {
567        EncodedTerm::DateLiteral(text.parse().unwrap())
568    }
569
570    fn gyear(text: &str) -> EncodedTerm {
571        EncodedTerm::GYearLiteral(text.parse().unwrap())
572    }
573
574    fn gyear_month(text: &str) -> EncodedTerm {
575        EncodedTerm::GYearMonthLiteral(text.parse().unwrap())
576    }
577
578    #[test]
579    fn datetime_comparisons_follow_the_timezone_partial_order() {
580        // Same instants, different offsets: equal values compare equal.
581        assert_eq!(
582            compare(
583                &dt("2025-03-15T12:00:00Z"),
584                CompareOp::GreaterOrEqual,
585                &dt("2025-03-15T13:00:00+01:00")
586            ),
587            Some(true)
588        );
589        // Naive term more than 14h after the tz const: DEFINITELY greater
590        // (even at the maximum offset it is after).
591        assert_eq!(
592            compare(
593                &dt("2025-03-20T00:00:00"),
594                CompareOp::Greater,
595                &dt("2025-03-15T00:00:00Z")
596            ),
597            Some(true)
598        );
599        // Naive within the ±14h uncertainty (10h after): indeterminate →
600        // row dropped, exactly as the unindexed FILTER errors it away.
601        assert_eq!(
602            compare(
603                &dt("2025-03-15T10:00:00"),
604                CompareOp::Greater,
605                &dt("2025-03-15T00:00:00Z")
606            ),
607            None
608        );
609        // Naive more than 14h before: definitely less.
610        assert_eq!(
611            compare(
612                &dt("2025-03-10T00:00:00"),
613                CompareOp::Greater,
614                &dt("2025-03-15T00:00:00Z")
615            ),
616            Some(false)
617        );
618    }
619
620    #[test]
621    fn gyear_family_compares_by_start_ticks() {
622        assert_eq!(
623            compare(&gyear("2025"), CompareOp::Greater, &gyear("2024")),
624            Some(true)
625        );
626        assert_eq!(
627            compare(&gyear("-252000000"), CompareOp::Less, &gyear("-251000000")),
628            Some(true)
629        );
630        assert_eq!(
631            compare(
632                &gyear_month("2025-03"),
633                CompareOp::GreaterOrEqual,
634                &gyear("2025")
635            ),
636            Some(true),
637            "March 2025 starts after (or at) the start of 2025"
638        );
639        assert_eq!(
640            compare(
641                &gyear("2025"),
642                CompareOp::LessOrEqual,
643                &gyear_month("2025-03")
644            ),
645            Some(true),
646            "2025-01-01 starts before 2025-03-01"
647        );
648    }
649
650    #[test]
651    fn cross_family_pairs_are_type_errors() {
652        assert_eq!(
653            compare(
654                &date("2025-03-15"),
655                CompareOp::Less,
656                &dt("2025-03-15T00:00:00Z")
657            ),
658            None
659        );
660        assert_eq!(
661            compare(&gyear("2025"), CompareOp::Less, &dt("2025-01-01T00:00:00Z")),
662            None
663        );
664        assert_eq!(
665            compare(&dt("2025-01-01T00:00:00Z"), CompareOp::Less, &gyear("2025")),
666            None
667        );
668    }
669
670    #[test]
671    fn stripped_comparison_evaluation_drops_errors() {
672        // One failing (cross-family) comparison fails the conjunction.
673        let comparisons = vec![
674            StrippedComparison {
675                op: CompareOp::Greater,
676                const_term: dt("2020-01-01T00:00:00Z"),
677            },
678            StrippedComparison {
679                op: CompareOp::Less,
680                const_term: date("2030-01-01"),
681            },
682        ];
683        let candidate = dt("2025-06-01T00:00:00Z");
684        assert!(!comparisons_hold(&candidate, &comparisons));
685        let all_datetime = vec![StrippedComparison {
686            op: CompareOp::Less,
687            const_term: dt("2030-01-01T00:00:00Z"),
688        }];
689        assert!(comparisons_hold(&candidate, &all_datetime));
690    }
691
692    #[test]
693    fn window_bounds_follow_operator_direction() {
694        let comparisons = vec![
695            StrippedComparison {
696                op: CompareOp::GreaterOrEqual,
697                const_term: dt("2025-01-01T00:00:00Z"),
698            },
699            StrippedComparison {
700                op: CompareOp::Less,
701                const_term: dt("2026-01-01T00:00:00Z"),
702            },
703        ];
704        let TemporalQueryPredicate::Overlaps { begin, end } = window_of(&comparisons) else {
705            panic!("window");
706        };
707        let lo = waratah_storage::temporal_term_interval(&dt("2025-01-01T00:00:00Z")).unwrap();
708        assert_eq!(begin, lo.begin, ">= uses the const's projected start");
709        let hi = waratah_storage::temporal_term_interval(&dt("2026-01-01T00:00:00Z")).unwrap();
710        assert_eq!(
711            end, hi.end,
712            "< uses the const's projected end — no one-attosecond nudge"
713        );
714    }
715
716    #[test]
717    fn window_bounds_are_family_agnostic() {
718        // Lower bounds are always the projected BEGIN, upper bounds the
719        // projected END, whatever the const's datatype family. A naive
720        // dateTime's shape is its ±14 h uncertainty band, a gYear's is the
721        // whole calendar year, a gYearMonth's the whole month — and the
722        // derivation never asks which one it is reading.
723        for (const_term, note) in [
724            (dt("2025-03-15T12:00:00Z"), "tz-present dateTime (instant)"),
725            (dt("2025-03-15T12:00:00"), "tz-absent dateTime (±14 h band)"),
726            (date("2025-03-15"), "date (tz-absent)"),
727            (gyear("2025"), "gYear (whole year)"),
728            (gyear_month("2025-03"), "gYearMonth (whole month)"),
729        ] {
730            let shape = waratah_storage::temporal_term_interval(&const_term).unwrap();
731            let lower = window_of(&[StrippedComparison {
732                op: CompareOp::GreaterOrEqual,
733                const_term: const_term.clone(),
734            }]);
735            let upper = window_of(&[StrippedComparison {
736                op: CompareOp::LessOrEqual,
737                const_term,
738            }]);
739            let TemporalQueryPredicate::Overlaps {
740                begin: lower_begin,
741                end: lower_end,
742            } = lower
743            else {
744                panic!("window");
745            };
746            let TemporalQueryPredicate::Overlaps {
747                begin: upper_begin,
748                end: upper_end,
749            } = upper
750            else {
751                panic!("window");
752            };
753            assert_eq!(lower_begin, shape.begin, "{note}: floor is the begin");
754            assert_eq!(
755                lower_end,
756                i128::MAX,
757                "{note}: lower-only window is open above"
758            );
759            assert_eq!(
760                upper_begin,
761                i128::MIN,
762                "{note}: upper-only window is open below"
763            );
764            assert_eq!(upper_end, shape.end, "{note}: ceiling is the end");
765            if shape.is_instant() {
766                assert_eq!(shape.begin, shape.end, "{note}: instant is degenerate");
767            } else {
768                // The old rule took the interval MIDPOINT for every
769                // non-instant shape; both edges must now sit strictly outside
770                // of it, which is what makes the window a superset.
771                let midpoint = shape.begin / 2 + shape.end / 2;
772                assert!(shape.begin < midpoint && midpoint < shape.end, "{note}");
773                assert!(
774                    lower_begin < midpoint,
775                    "{note}: floor is below the midpoint"
776                );
777                assert!(
778                    midpoint < upper_end,
779                    "{note}: ceiling is above the midpoint"
780                );
781            }
782        }
783    }
784
785    #[test]
786    fn window_strictness_is_left_to_the_residual() {
787        // `>` draws the same begin as `>=`, `<` the same end as `<=`: the
788        // residual decides strictness per row, so an attosecond nudge would
789        // only risk rejecting a candidate sitting exactly on a closed
790        // interval's edge.
791        for const_term in [
792            dt("2025-03-15T12:00:00Z"),
793            dt("2025-03-15T12:00:00"),
794            date("2025-03-15"),
795            gyear("2025"),
796            gyear_month("2025-03"),
797        ] {
798            assert_eq!(
799                window_of(&[StrippedComparison {
800                    op: CompareOp::GreaterOrEqual,
801                    const_term: const_term.clone(),
802                }]),
803                window_of(&[StrippedComparison {
804                    op: CompareOp::Greater,
805                    const_term: const_term.clone(),
806                }]),
807                "`>` and `>=` must draw the same bound"
808            );
809            assert_eq!(
810                window_of(&[StrippedComparison {
811                    op: CompareOp::LessOrEqual,
812                    const_term: const_term.clone(),
813                }]),
814                window_of(&[StrippedComparison {
815                    op: CompareOp::Less,
816                    const_term,
817                }]),
818                "`<` and `<=` must draw the same bound"
819            );
820        }
821    }
822
823    /// The partition-side exact reject's verdict on one candidate term:
824    /// whether ANY of its postings survives. The term's postings each carry
825    /// the term's exact interval in the posting value, so a posting survives
826    /// iff the term's interval overlaps the window — the scan emits a term
827    /// once one posting clears the reject.
828    ///
829    /// This is the exact-interval half only; the probe intervals' key-range
830    /// half is covered by the store-level scan (see `tests/`).
831    fn candidate_passes_exact_reject(term: &EncodedTerm, window: &TemporalQueryPredicate) -> bool {
832        let puts = waratah_storage::postings_for_term(
833            term,
834            waratah_storage::CommitTs(1),
835            &waratah_storage::DyadicCovererConfig::default(),
836        );
837        assert!(!puts.is_empty(), "every temporal term posts");
838        puts.iter().any(|put| put.matches(window))
839    }
840
841    /// Parse a gYear / gYearMonth lexical (a second `-` ⇒ the month form;
842    /// negative years carry a leading `-` of their own).
843    fn gyear_like(text: &str) -> EncodedTerm {
844        let unsigned = text.strip_prefix('-').unwrap_or(text);
845        if unsigned.contains('-') {
846            gyear_month(text)
847        } else {
848            gyear(text)
849        }
850    }
851
852    /// The soundness direction of the partition-side reject: every candidate
853    /// the residual keeps must also clear it. (The reject is a superset by
854    /// design, so the converse is deliberately NOT asserted.)
855    fn assert_window_complete(
856        candidates: &[EncodedTerm],
857        comparisons: &[StrippedComparison],
858        window: &TemporalQueryPredicate,
859    ) {
860        for candidate in candidates {
861            if comparisons_hold(candidate, comparisons) {
862                assert!(
863                    candidate_passes_exact_reject(candidate, window),
864                    "{candidate:?} rejected partition-side although the residual keeps it"
865                );
866            }
867        }
868    }
869
870    /// Regression (the false negative this window rule exists to fix): a
871    /// gYear-family const's lower bound was drawn from the const's interval
872    /// MIDPOINT. That is defensible for a timezone-absent dateTime, whose
873    /// interval is ±14 h uncertainty around a reading, but a `gYear`'s
874    /// interval is a real span that `compare` orders by its START — so
875    /// `FILTER(?t >= "2025"^^xsd:gYear)` floored the scan at ≈ 2 July and
876    /// silently dropped every first-half `gYearMonth` row.
877    ///
878    /// Geological dates hit the same shape at depth: the window for
879    /// `>= "-252000000"` (Permian–Triassic) used to start in the middle of
880    /// that era's year.
881    #[test]
882    fn gyear_lower_bound_keeps_every_candidate_the_residual_keeps() {
883        for const_year in ["2025", "-252000000"] {
884            let comparisons = vec![StrippedComparison {
885                op: CompareOp::GreaterOrEqual,
886                const_term: gyear(const_year),
887            }];
888            let window = window_of(&comparisons);
889            let shape = waratah_storage::temporal_term_interval(&gyear(const_year)).unwrap();
890            let midpoint = shape.begin / 2 + shape.end / 2;
891            let TemporalQueryPredicate::Overlaps { begin, .. } = window else {
892                panic!("window");
893            };
894            assert_eq!(
895                begin, shape.begin,
896                "{const_year}: the floor is the interval start"
897            );
898            assert!(
899                begin < midpoint,
900                "{const_year}: the floor must sit below the midpoint the old rule used"
901            );
902
903            let mut candidates: Vec<EncodedTerm> = Vec::new();
904            candidates.push(gyear(const_year));
905            for month in 1..=12 {
906                candidates.push(gyear_month(&format!("{const_year}-{month:02}")));
907            }
908            let later: &[&str] = match const_year {
909                "2025" => &["2026", "2026-01"],
910                _ => &["-251000000", "-251000000-06"],
911            };
912            for text in later {
913                candidates.push(gyear_like(text));
914            }
915            // All of the above are kept by the residual (their start ticks
916            // are at or after the const's), so all must ALSO survive the
917            // reject. Assert it explicitly rather than folding it into the
918            // helper, so the regression reads as "everything survived".
919            for candidate in &candidates {
920                assert!(
921                    comparisons_hold(candidate, &comparisons),
922                    "{candidate:?} should satisfy the residual"
923                );
924                assert!(
925                    candidate_passes_exact_reject(candidate, &window),
926                    "{candidate:?} rejected partition-side although the residual keeps it"
927                );
928            }
929        }
930    }
931
932    /// The tz-qualified-date shape of the same property — and the written
933    /// calendar date is NOT the ordering: `2025-03-15+14:00` starts
934    /// 2025-03-14T10:00Z, *earlier* than `2025-03-14-14:00`, which starts
935    /// 2025-03-14T14:00Z. So for `?d >= "2025-03-15+14:00"` the window must
936    /// open at the const's LOCAL midnight; under the old UTC-midnight-
937    /// instant projection it opened at 2025-03-15T00:00Z and the stored
938    /// day's posting (2025-03-14T00:00Z) sat below it — the row was
939    /// silently dropped although XSD order keeps it.
940    #[test]
941    fn date_window_edges_cover_mixed_offset_days() {
942        let comparisons = vec![StrippedComparison {
943            op: CompareOp::GreaterOrEqual,
944            const_term: date("2025-03-15+14:00"),
945        }];
946        let window = window_of(&comparisons);
947        let TemporalQueryPredicate::Overlaps { begin, .. } = window else {
948            panic!("window");
949        };
950        // The window floor is the const day's local midnight.
951        assert_eq!(
952            begin,
953            waratah_storage::temporal_term_interval(&date("2025-03-15+14:00"))
954                .unwrap()
955                .begin
956        );
957
958        let candidate = date("2025-03-14-14:00");
959        assert!(
960            comparisons_hold(&candidate, &comparisons),
961            "XSD order keeps the later-starting day"
962        );
963        assert!(
964            candidate_passes_exact_reject(&candidate, &window),
965            "candidate rejected partition-side although the residual keeps it"
966        );
967    }
968
969    /// The mirror property on the upper edge. `?t <= "2025-06"` keeps
970    /// `"2025"^^xsd:gYear` (the year's start precedes the month's) whose
971    /// postings run to December — the ceiling must be the const's END, and
972    /// in particular not its end minus an attosecond, which would reject a
973    /// candidate whose interval closes exactly on that boundary.
974    #[test]
975    fn gyear_upper_bound_keeps_every_candidate_the_residual_keeps() {
976        let comparisons = vec![StrippedComparison {
977            op: CompareOp::LessOrEqual,
978            const_term: gyear_month("2025-06"),
979        }];
980        let window = window_of(&comparisons);
981        let shape = waratah_storage::temporal_term_interval(&gyear_month("2025-06")).unwrap();
982        let TemporalQueryPredicate::Overlaps { end, .. } = window else {
983            panic!("window");
984        };
985        assert_eq!(end, shape.end, "the ceiling is the interval end, unnudged");
986
987        let mut candidates: Vec<EncodedTerm> = vec![gyear("2025"), gyear("2024")];
988        for month in 1..=6 {
989            candidates.push(gyear_month(&format!("2025-{month:02}")));
990        }
991        // Soundness: everything the residual keeps clears the reject.
992        assert_window_complete(&candidates, &comparisons, &window);
993    }
994
995    #[test]
996    fn tf_relations_cover_the_allen_algebra() {
997        let instant =
998            |t: i128| waratah_storage::TemporalShape::instant(t * waratah_storage::ATTO_PER_SECOND);
999        let span = |b: i128, e: i128| waratah_storage::TemporalShape {
1000            begin: b * waratah_storage::ATTO_PER_SECOND,
1001            end: e * waratah_storage::ATTO_PER_SECOND,
1002        };
1003        let a = span(10, 20);
1004        let b = span(15, 30);
1005        assert!(TfRelation::Overlaps.holds(a, b));
1006        assert!(TfRelation::OverlappedBy.holds(b, a));
1007        assert!(!TfRelation::Contains.holds(a, b));
1008        assert!(TfRelation::Contains.holds(span(10, 40), b));
1009        assert!(
1010            !TfRelation::Contains.holds(span(10, 40), span(10, 40)),
1011            "proper containment excludes equality"
1012        );
1013        assert!(TfRelation::Equals.holds(span(10, 40), span(10, 40)));
1014        assert!(TfRelation::Meets.holds(span(0, 15), b));
1015        assert!(TfRelation::MetBy.holds(b, span(0, 15)));
1016        assert!(TfRelation::Starts.holds(span(15, 20), b));
1017        assert!(TfRelation::StartedBy.holds(b, span(15, 20)));
1018        assert!(TfRelation::Finishes.holds(span(25, 30), b));
1019        assert!(TfRelation::FinishedBy.holds(b, span(25, 30)));
1020        assert!(TfRelation::IsBefore.holds(span(0, 5), b));
1021        assert!(TfRelation::IsAfter.holds(span(40, 50), b));
1022        assert!(TfRelation::IsInside.holds(instant(20), b));
1023        assert!(!TfRelation::IsInside.holds(instant(35), b));
1024        assert!(TfRelation::HasInside.holds(b, instant(20)));
1025        assert!(!TfRelation::HasInside.holds(b, instant(35)));
1026    }
1027
1028    #[test]
1029    fn tf_iris_round_trip_and_cover_the_vocabulary() {
1030        for (relation, local) in TfRelation::all_named() {
1031            let iri = format!("{}{local}", crate::TF_NAMESPACE);
1032            assert_eq!(TfRelation::from_iri(&iri), Some(relation), "{iri}");
1033        }
1034        // The timefuncs v0.1.0 vocabulary's own names all parse.
1035        for local in [
1036            "isBefore",
1037            "isAfter",
1038            "contains",
1039            "hasDuring",
1040            "isContainedBy",
1041            "isDuring",
1042            "isInside",
1043            "hasInside",
1044        ] {
1045            let iri = format!("{}{local}", crate::TF_NAMESPACE);
1046            assert!(TfRelation::from_iri(&iri).is_some(), "{iri}");
1047        }
1048        assert_eq!(TfRelation::from_iri("http://example.com/notTf"), None);
1049    }
1050
1051    /// A typed temporal literal as an `oxrdf::Term`.
1052    fn tf_literal(lexical: &str, datatype_local: &str) -> oxrdf::Term {
1053        oxrdf::Term::Literal(oxrdf::Literal::new_typed_literal(
1054            lexical,
1055            oxrdf::NamedNode::new_unchecked(format!(
1056                "http://www.w3.org/2001/XMLSchema#{datatype_local}"
1057            )),
1058        ))
1059    }
1060
1061    /// `tf:isBefore(a, b)` evaluated through the ground path, as its lexical
1062    /// boolean (`"true"` / `"false"`).
1063    fn tf_is_before(a: oxrdf::Term, b: oxrdf::Term) -> String {
1064        let iri = oxrdf::NamedNode::new_unchecked(format!("{}isBefore", crate::TF_NAMESPACE));
1065        match eval_tf_function(iri.as_str(), &[a, b]) {
1066            CustomEval::Term(oxrdf::Term::Literal(value)) => value.value().to_owned(),
1067            other => panic!("expected a boolean term, got {other:?}"),
1068        }
1069    }
1070
1071    /// B56's answer-surface test: `tf:*` over mixed literal families must
1072    /// compare on the SHARED tick axis, not on split sub-axes.
1073    ///
1074    /// Before the fix, `xsd:date` and `xsd:gYear` projected from a different
1075    /// era zero than `xsd:dateTime` (306 days apart) while `eval_tf_function`
1076    /// mixes families freely — so an instant sitting exactly ON a year's start
1077    /// read as 306 days *before* it and `isBefore` answered `true`. Every
1078    /// within-family test passed either way, which is how this hid.
1079    #[test]
1080    fn cross_family_tf_pairs_share_one_axis() {
1081        let dt = |t: &str| tf_literal(t, "dateTime");
1082        let date = |t: &str| tf_literal(t, "date");
1083        let gyear = |t: &str| tf_literal(t, "gYear");
1084        let gyear_month = |t: &str| tf_literal(t, "gYearMonth");
1085
1086        // THE bug: an instant exactly on the year's start is not before it.
1087        assert_eq!(
1088            tf_is_before(dt("2025-01-01T00:00:00Z"), gyear("2025")),
1089            "false",
1090            "midnight of Jan 1 sits ON the year's start, so it cannot be before it"
1091        );
1092        // Mirror direction agrees — the pair is symmetric, not just one-sided.
1093        assert_eq!(
1094            tf_is_before(gyear("2025"), dt("2025-01-01T00:00:00Z")),
1095            "false",
1096            "a year containing the instant is not before it either"
1097        );
1098        // A year genuinely after the instant still reads as after.
1099        assert_eq!(
1100            tf_is_before(dt("2025-01-01T00:00:00Z"), gyear("2026")),
1101            "true"
1102        );
1103        // date against dateTime: the same instant must compare equal-bound.
1104        assert_eq!(
1105            tf_is_before(date("2025-01-01Z"), dt("2025-01-01T00:00:00Z")),
1106            "false",
1107            "a date and its midnight instant are the same point on the axis"
1108        );
1109        assert_eq!(
1110            tf_is_before(dt("2024-12-31T23:59:59Z"), date("2025-01-01Z")),
1111            "true"
1112        );
1113        // gYearMonth on the same axis as its own month start.
1114        assert_eq!(
1115            tf_is_before(gyear_month("2025-01"), dt("2025-01-15T00:00:00Z")),
1116            "false",
1117            "the month of Jan 1 contains Jan 15, so the month is not before it"
1118        );
1119        // Deep time keeps the alignment (the geological use case).
1120        assert_eq!(
1121            tf_is_before(dt("-252000000-01-01T00:00:00Z"), gyear("-252000000")),
1122            "false",
1123            "the era's first midnight is not before the era itself"
1124        );
1125    }
1126
1127    #[test]
1128    fn ground_tf_evaluation_requires_temporal_literals() {
1129        let t1 = oxrdf::Literal::new_typed_literal(
1130            "2025-03-15T00:00:00Z",
1131            oxrdf::NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#dateTime"),
1132        );
1133        let t2 = oxrdf::Literal::new_typed_literal(
1134            "2025-06-01T00:00:00Z",
1135            oxrdf::NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#dateTime"),
1136        );
1137        let iri = oxrdf::NamedNode::new_unchecked(format!("{}isBefore", crate::TF_NAMESPACE));
1138        match eval_tf_function(iri.as_str(), &[t1.clone().into(), t2.clone().into()]) {
1139            CustomEval::Term(oxrdf::Term::Literal(value)) => assert_eq!(value.value(), "true"),
1140            other => panic!("expected boolean term, got {other:?}"),
1141        }
1142        // Entity argument: the documented v1 boundary (error).
1143        let entity = oxrdf::NamedNode::new_unchecked("http://ex/event").into();
1144        assert!(matches!(
1145            eval_tf_function(iri.as_str(), &[entity, t1.into()]),
1146            CustomEval::Error
1147        ));
1148    }
1149}