1use 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
31const TEMPORAL_DIRECT_EVAL_LIMIT: usize = 2_000;
36
37#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct StrippedComparison {
41 pub op: CompareOp,
43 pub const_term: EncodedTerm,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum CompareOp {
51 Less,
53 LessOrEqual,
55 Greater,
57 GreaterOrEqual,
59}
60
61impl CompareOp {
62 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#[derive(Debug, Clone, PartialEq)]
76pub struct TemporalScanPayload {
77 pub comparisons: Vec<StrippedComparison>,
80 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 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#[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 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 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 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 None => {
180 let candidates = drain_candidates(payload, &env).await?;
181 Ok(evaluate_terms(&candidates, payload))
182 }
183 }
184 })
185 }
186}
187
188async fn drain_candidates(
192 payload: &TemporalScanPayload,
193 env: &PluginEnv<'_>,
194) -> Result<Vec<EncodedTerm>, ComputeError> {
195 let window = window_of(&payload.comparisons);
198 (env.temporal_candidates)(&payload.intervals, window, 0).await
199}
200
201pub(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 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
253pub(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
272pub(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
282pub(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 (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
312pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub enum TfRelation {
349 IsBefore,
351 IsAfter,
353 Contains,
355 IsContainedBy,
357 IsInside,
359 HasInside,
361 Meets,
363 MetBy,
365 Overlaps,
367 OverlappedBy,
369 Starts,
371 StartedBy,
373 Finishes,
375 FinishedBy,
377 Equals,
379}
380
381impl TfRelation {
382 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 #[allow(dead_code)] 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 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 #[allow(dead_code)] 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
483macro_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
519pub 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 #[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 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 #[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 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 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 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 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 #[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 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 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 assert_eq!(
1100 tf_is_before(dt("2025-01-01T00:00:00Z"), gyear("2026")),
1101 "true"
1102 );
1103 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 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 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 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}