Skip to main content

waratah_temporal/
plan.rs

1//! PlannerPlugin: `FILTER(?t OP const)` comparison rewrites →
2//! `Join(temporal_scan, inner, ?t)`.
3//!
4//! **Rewrite scope:** `Filter.residual` AND `Filter.early` conjuncts
5//! (top-level `&&` flattening, same as `split_filter`), recursing into inner
6//! plans and EXISTS clause bodies. Unlike the geo rewrite, `early` IS walked:
7//! ordering comparisons classify `MaybeEncoded` and land in the early tree
8//! (`geof:*` custom functions never do, which is why geo skips it). A conjunct rewrites only when
9//!
10//! - it is an ordering comparison (`<` `<=` `>` `>=`),
11//! - one argument is a **ground temporal literal** (`xsd:dateTime`,
12//!   `xsd:dateTimeStamp`, `xsd:date`, and — unless `strict-sparql` is on —
13//!   the `xsd:gYear` / `xsd:gYearMonth` extension family),
14//! - the other is a **variable**,
15//! - the index is trusted (`ctx.snapshot() >= temporal epoch`; a MISSING
16//!   epoch is UNTRUSTED for temporal — temporal literals predate the plugin,
17//!   so the compute auto-rebuild stamps the epoch at startup before queries
18//!   are served).
19//!
20//! Adjacent conjuncts over the same variable merge into one window
21//! (`?t >= c1 && ?t <= c2` → one scan); each bound takes the EDGE of its
22//! const's projected interval that the operator points at (`begin` for
23//! lower bounds, `end` for upper bounds), family-agnostically — see
24//! [`crate::exec::window_of`] for the rule and its completeness argument.
25//! The scan's partition-side reject is a conservative superset for every
26//! timezone combination; the stripped comparisons ride the payload
27//! and are re-evaluated EXACTLY per candidate by the executor (which also
28//! decides strictness), so rows are kept exactly as the unindexed FILTER
29//! would keep them.
30//!
31//! **Broadcast participation** mirrors the geo rewrite: the smaller arm
32//! drives (`JoinStrategy::from_estimated_sizes` semantics), the estimate
33//! comes from the rolled-up temporal histogram when present (window width ×
34//! observed density; advisory, never pruning) with a flat fallback, and a
35//! ground-unique driver pins its term into the op.
36//!
37//! `tf:*` FILTER rewrites (the OWL-Time structure joins) are the Tier-2
38//! follow-on in this same hook.
39
40use spargebra::algebra::Expression;
41use waratah_compute::ComputeError;
42use waratah_compute::JoinStrategy;
43use waratah_compute::PlanNode;
44use waratah_compute::QueryContext;
45use waratah_compute::ground_unique_probe_term;
46use waratah_compute::plugin::{PlannerPlugin, PluginPayloadBox};
47use waratah_compute::strict_sparql::strict_sparql;
48use waratah_stats::PUSHDOWN_TERMS_LIMIT;
49use waratah_storage::{EncodedTerm, TemporalQueryPredicate, Variable};
50
51use crate::exec::{CompareOp, StrippedComparison, TemporalScanPayload, window_of};
52
53/// `temporal_scan` op id on the CustomOp node.
54pub const TEMPORAL_SCAN_OP_ID: &str = "temporal_scan";
55
56/// Flat fallback row estimate when no histogram is rolled up yet (the
57/// histogram's `estimate_window` replaces this as soon as the profile
58/// carries postings).
59const FALLBACK_WINDOW_ROWS: u64 = 1_000;
60
61/// Temporal planner hook.
62#[derive(Debug, Default)]
63pub struct TemporalPlannerPlugin;
64
65impl PlannerPlugin for TemporalPlannerPlugin {
66    /// An ordering comparison against a temporal constant that this plugin can
67    /// turn into a `temporal_scan` candidate producer. Built twice, the scan
68    /// would drain the same node-key intervals again, so it is pinned across
69    /// the algebra optimizer. The test is syntactic: a comparison that is
70    /// pinned but not rewritten (untrusted index, non-temporal constant, or
71    /// the gYear family in strict mode) stays an ordinary filter at its
72    /// binding-site ancestor.
73    fn pins_through_optimizer(&self, expression: &Expression) -> bool {
74        let (left, right) = match expression {
75            Expression::Less(left, right)
76            | Expression::LessOrEqual(left, right)
77            | Expression::Greater(left, right)
78            | Expression::GreaterOrEqual(left, right) => (left.as_ref(), right.as_ref()),
79            _ => return false,
80        };
81        let literal = match (left, right) {
82            (Expression::Variable(_), Expression::Literal(literal))
83            | (Expression::Literal(literal), Expression::Variable(_)) => literal,
84            _ => return false,
85        };
86        matches!(
87            EncodedTerm::from(literal),
88            EncodedTerm::DateTimeLiteral(_)
89                | EncodedTerm::DateLiteral(_)
90                | EncodedTerm::GYearLiteral(_)
91                | EncodedTerm::GYearMonthLiteral(_)
92        )
93    }
94
95    fn rewrite(&self, node: &mut PlanNode, ctx: &QueryContext) -> Result<(), ComputeError> {
96        // Trust gate: the temporal index is UNTRUSTED until its rebuild
97        // epoch is stamped (temporal literals predate the plugin; a legacy
98        // store has an empty index and no epoch, and trusting an empty index
99        // would answer rewritten comparisons with zero rows — answer-
100        // affecting, forbidden). Below a STAMPED epoch likewise untrusted.
101        let Some(trusted_from) = ctx.temporal_index_epoch() else {
102            return Ok(());
103        };
104        if ctx.snapshot().0 < trusted_from {
105            return Ok(());
106        }
107        match node {
108            PlanNode::Filter {
109                inner,
110                early,
111                residual,
112                exists,
113                ..
114            } => {
115                self.rewrite(inner, ctx)?;
116                for clause in exists.iter_mut() {
117                    self.rewrite(&mut clause.body, ctx)?;
118                }
119                let mut rewritten: Option<PlanNode> = None;
120                // Comparisons lower into BOTH trees: scan-local ordering
121                // conjuncts classify MaybeEncoded and land in `early` (the
122                // geo plugin never sees them; temporal comparisons are the
123                // case `split_filter` pulls early). Extract from both.
124                if let Some(early_expr) = early {
125                    let conjuncts = waratah_compute::flatten_and(early_expr);
126                    let mut remaining: Vec<Expression> = Vec::new();
127                    for conjunct in conjuncts {
128                        match match_comparison_conjunct(&conjunct)? {
129                            Some((variable, comparison)) => {
130                                rewritten = Some(merge_or_start(
131                                    rewritten.take().unwrap_or_else(|| (**inner).clone()),
132                                    variable,
133                                    comparison,
134                                    ctx,
135                                ));
136                            }
137                            None => remaining.push(conjunct),
138                        }
139                    }
140                    *early = waratah_compute::and_fold(remaining);
141                }
142                if let Some(residual_expr) = residual {
143                    let conjuncts = waratah_compute::flatten_and(residual_expr);
144                    let mut remaining: Vec<Expression> = Vec::new();
145                    for conjunct in conjuncts {
146                        match match_comparison_conjunct(&conjunct)? {
147                            Some((variable, comparison)) => {
148                                rewritten = Some(merge_or_start(
149                                    rewritten.take().unwrap_or_else(|| (**inner).clone()),
150                                    variable,
151                                    comparison,
152                                    ctx,
153                                ));
154                            }
155                            None => remaining.push(conjunct),
156                        }
157                    }
158                    *residual = waratah_compute::and_fold(remaining);
159                }
160                if let Some(join) = rewritten {
161                    // The injected node is Join(scan, inner, ?t): the Filter
162                    // keeps only the untouched conjuncts (and is dropped
163                    // entirely when nothing remains — early/exists too).
164                    if residual.is_none() && early.is_none() && exists.is_empty() {
165                        *node = join;
166                    } else {
167                        **inner = join;
168                    }
169                }
170                Ok(())
171            }
172            PlanNode::Join { left, right, .. }
173            | PlanNode::LeftJoin { left, right, .. }
174            | PlanNode::Union { left, right } => {
175                self.rewrite(left, ctx)?;
176                self.rewrite(right, ctx)
177            }
178            PlanNode::CustomNode(op) => {
179                for child in &mut op.children {
180                    self.rewrite(child, ctx)?;
181                }
182                Ok(())
183            }
184            PlanNode::Scan(_)
185            | PlanNode::Path(_)
186            | PlanNode::Unit
187            | PlanNode::Values(_)
188            | PlanNode::NamedGraphs { .. }
189            | PlanNode::NamedGraphExists { .. }
190            | PlanNode::DomainCounts { .. }
191            | PlanNode::HeadCounts { .. }
192            | PlanNode::PatternCount { .. }
193            | PlanNode::SubSelect(_) => Ok(()),
194            PlanNode::Extend { inner, .. }
195            | PlanNode::Slice { inner, .. }
196            | PlanNode::Distinct { inner, .. }
197            | PlanNode::Sort { inner, .. }
198            | PlanNode::Group { inner, .. }
199            | PlanNode::JoinGraphVar { inner, .. } => self.rewrite(inner, ctx),
200        }
201    }
202}
203
204/// One matched comparison conjunct: `(variable, stripped comparison)`.
205type ComparisonMatch = (Variable, StrippedComparison);
206
207/// Match one residual conjunct against the comparison shapes.
208fn match_comparison_conjunct(
209    conjunct: &Expression,
210) -> Result<Option<ComparisonMatch>, ComputeError> {
211    // The dedicated ordering variants (each also covers the XSD casts the
212    // operator table routes through it — the rewrite only fires on literal-
213    // vs-variable shapes, so the const's datatype gates the family).
214    let (op, left, right) = match conjunct {
215        Expression::Less(left, right) => (CompareOp::Less, left, right),
216        Expression::LessOrEqual(left, right) => (CompareOp::LessOrEqual, left, right),
217        Expression::Greater(left, right) => (CompareOp::Greater, left, right),
218        Expression::GreaterOrEqual(left, right) => (CompareOp::GreaterOrEqual, left, right),
219        _ => return Ok(None),
220    };
221    // Either orientation; normalize the variable to the left.
222    let (variable, const_literal, normalized) = match (left.as_ref(), right.as_ref()) {
223        (Expression::Variable(variable), Expression::Literal(literal)) => (variable, literal, op),
224        (Expression::Literal(literal), Expression::Variable(variable)) => {
225            (variable, literal, mirror(op))
226        }
227        _ => return Ok(None),
228    };
229    // The const must be a temporal literal whose family the comparison table
230    // serves. Strict mode drops the gYear-family extension (the conjunct
231    // stays on the unindexed FILTER, whose type error matches strict
232    // semantics).
233    let encoded = EncodedTerm::from(const_literal);
234    let served = match &encoded {
235        EncodedTerm::DateTimeLiteral(_) | EncodedTerm::DateLiteral(_) => true,
236        EncodedTerm::GYearLiteral(_) | EncodedTerm::GYearMonthLiteral(_) => !strict_sparql(),
237        _ => false,
238    };
239    if !served {
240        return Ok(None);
241    }
242    Ok(Some((
243        variable.clone(),
244        StrippedComparison {
245            op: normalized,
246            const_term: encoded,
247        },
248    )))
249}
250
251/// Mirror a comparison operator (const was on the left).
252fn mirror(op: CompareOp) -> CompareOp {
253    match op {
254        CompareOp::Less => CompareOp::Greater,
255        CompareOp::LessOrEqual => CompareOp::GreaterOrEqual,
256        CompareOp::Greater => CompareOp::Less,
257        CompareOp::GreaterOrEqual => CompareOp::LessOrEqual,
258    }
259}
260
261/// Merge one matched comparison into the growing rewrite: an existing scan
262/// over the SAME variable extends its comparison list (re-derived window,
263/// re-stamped estimate); a different variable (or none yet) chains a new
264/// join over the previous rewrite.
265fn merge_or_start(
266    previous: PlanNode,
267    variable: Variable,
268    comparison: StrippedComparison,
269    ctx: &QueryContext,
270) -> PlanNode {
271    let mut extended = previous.clone();
272    if let Some(scan) = find_scan_op_mut(&mut extended, &variable) {
273        let Some(payload) = scan.payload.downcast_ref::<TemporalScanPayload>() else {
274            return build_scan_join(previous, variable, vec![comparison], ctx);
275        };
276        let mut comparisons = payload.comparisons.clone();
277        comparisons.push(comparison);
278        let intervals = intervals_for_comparisons(&comparisons);
279        let estimate = estimate_window_rows(ctx, &comparisons);
280        // Rebuild the payload (downcast gave a shared borrow).
281        scan.payload = PluginPayloadBox::new(TemporalScanPayload {
282            comparisons,
283            intervals,
284        });
285        scan.produced_row_count_estimate = estimate;
286        // The wrapping join carries the same estimate stamp.
287        restamp_join_estimates(&mut extended, estimate);
288        return extended;
289    }
290    build_scan_join(previous, variable, vec![comparison], ctx)
291}
292
293/// Find the `temporal_scan` CustomOp over `variable` within the injected
294/// join shape (`Join(CustomNode, …, [?v])`, either arm).
295fn find_scan_op_mut<'a>(
296    node: &'a mut PlanNode,
297    variable: &Variable,
298) -> Option<&'a mut waratah_compute::CustomOp> {
299    match node {
300        PlanNode::Join {
301            left,
302            right,
303            hash_keys,
304            ..
305        } if hash_keys.len() == 1 && &hash_keys[0] == variable => {
306            find_scan_op_mut(left, variable).or_else(|| find_scan_op_mut(right, variable))
307        }
308        PlanNode::CustomNode(op)
309            if op.op_id == TEMPORAL_SCAN_OP_ID
310                && op.variables.len() == 1
311                && op.variables[0] == *variable =>
312        {
313            Some(op)
314        }
315        _ => None,
316    }
317}
318
319/// Restamp the produced-row estimates of the join directly wrapping a scan
320/// whose estimate changed (the geo rewrite's construction-time stamp
321/// contract: both fields carry the same value until the final restamp).
322fn restamp_join_estimates(node: &mut PlanNode, estimate: u64) {
323    if let PlanNode::Join {
324        meta,
325        left,
326        right,
327        hash_keys,
328        ..
329    } = node
330    {
331        // Only the single-scan join (not a chained multi-conjunct tree) is
332        // restamped here; the estimate drives arm placement only.
333        let scan_left =
334            matches!(left.as_ref(), PlanNode::CustomNode(op) if op.op_id == TEMPORAL_SCAN_OP_ID);
335        let scan_right =
336            matches!(right.as_ref(), PlanNode::CustomNode(op) if op.op_id == TEMPORAL_SCAN_OP_ID);
337        if (scan_left || scan_right) && hash_keys.len() == 1 {
338            meta.produced_row_count_estimate = estimate;
339            meta.own_push_removed_row_count_estimate = estimate;
340        }
341    }
342}
343
344/// Build `Join(temporal_scan, inner, ?t)` (or the mirrored placement for a
345/// large window estimate), mirroring the geo rewrite's broadcast contract.
346fn build_scan_join(
347    inner: PlanNode,
348    variable: Variable,
349    comparisons: Vec<StrippedComparison>,
350    ctx: &QueryContext,
351) -> PlanNode {
352    let intervals = intervals_for_comparisons(&comparisons);
353    let scan_rows = estimate_window_rows(ctx, &comparisons);
354    let inner_rows = inner.produced_row_count_estimate();
355    let mut scan = waratah_compute::CustomOp {
356        plugin_id: crate::PLUGIN_ID,
357        op_id: TEMPORAL_SCAN_OP_ID,
358        payload: PluginPayloadBox::new(TemporalScanPayload {
359            comparisons,
360            intervals,
361        }),
362        children: Vec::new(),
363        variables: vec![variable.clone()],
364        produced_row_count_estimate: scan_rows,
365        cost: None,
366        pinned: Vec::new(),
367    };
368    // Smaller arm drives. A large window makes the scan the RIGHT (probe)
369    // arm — a ground-unique driver pins its single term into the op (the
370    // executor evaluates exactly it, no scan RPC).
371    let (left, right) = if scan_rows <= inner_rows {
372        (PlanNode::CustomNode(scan), inner)
373    } else if let Some(term) = ground_unique_probe_term(&inner, &variable) {
374        scan.pinned.push((variable.clone(), term));
375        scan.produced_row_count_estimate = 1;
376        (inner, PlanNode::CustomNode(scan))
377    } else {
378        (inner, PlanNode::CustomNode(scan))
379    };
380    let strategy = if left.produced_row_count_estimate() <= PUSHDOWN_TERMS_LIMIT {
381        JoinStrategy::Broadcast
382    } else {
383        JoinStrategy::Hash
384    };
385    let join_rows = right.produced_row_count_estimate();
386    let rhs_hostable_keys =
387        std::sync::Arc::from(waratah_compute::subtree_hostable_variables(&right));
388    PlanNode::Join {
389        left: Box::new(left),
390        right: Box::new(right),
391        hash_keys: vec![variable],
392        probe_key_domains: Vec::new(),
393        probe_key_overlap_milli: Vec::new(),
394        rhs_hostable_keys,
395        meta: waratah_compute::JoinMeta {
396            star_arms: None,
397            strategy,
398            semi_gate: None,
399            produced_row_count_estimate: join_rows,
400            own_push_removed_row_count_estimate: join_rows,
401        },
402    }
403}
404
405/// The scan's interval list for a comparison set: the merged window
406/// ([lo, hi] over all comparison bounds, widened to the full axis for
407/// one-sided comparisons), covered under the ingest coverer config, merged
408/// into probe intervals (descendant ranges ∪ exact ancestors).
409fn intervals_for_comparisons(
410    comparisons: &[StrippedComparison],
411) -> Vec<waratah_storage::TemporalCellInterval> {
412    let window = window_of(comparisons);
413    let TemporalQueryPredicate::Overlaps { begin, end } = window else {
414        return Vec::new();
415    };
416    let begin_key = waratah_storage::tick_to_key_u128(begin);
417    let end_key = waratah_storage::tick_to_key_u128(end);
418    let config = crate::write::ingest_coverer_config();
419    let nodes = waratah_storage::cover_axis_range(begin_key, end_key, &config);
420    waratah_storage::intervals_for_nodes(&nodes)
421}
422
423/// Advisory row estimate for the window: the rolled-up histogram's
424/// `estimate_window` when present, else the flat fallback. Never zero —
425/// estimates order plan alternatives, they never prune.
426fn estimate_window_rows(ctx: &QueryContext, comparisons: &[StrippedComparison]) -> u64 {
427    let window = window_of(comparisons);
428    let TemporalQueryPredicate::Overlaps { begin, end } = window else {
429        return FALLBACK_WINDOW_ROWS;
430    };
431    if let Some(histogram) = ctx.temporal_histogram() {
432        return histogram.estimate_window(begin, end);
433    }
434    FALLBACK_WINDOW_ROWS
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440    use waratah_compute::CustomOp;
441    use waratah_compute::JoinMeta;
442    use waratah_compute::LogicalPlan;
443    use waratah_compute::PlanNode;
444
445    /// The plan hook only fires with the plugin + `tf:*` functions installed
446    /// (process-wide, first install wins — this test binary owns its own
447    /// process registry).
448    fn installed() {
449        crate::install();
450    }
451
452    #[test]
453    fn candidate_producers_are_pinned_through_the_optimizer() {
454        let plugin = TemporalPlannerPlugin;
455        let variable = || Expression::Variable(waratah_storage::Variable::new_unchecked("t"));
456        let date = |text: &str| {
457            Expression::Literal(oxrdf::Literal::new_typed_literal(
458                text,
459                oxrdf::NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#date"),
460            ))
461        };
462        assert!(plugin.pins_through_optimizer(&Expression::Less(
463            Box::new(variable()),
464            Box::new(date("2020-01-01"))
465        )));
466        assert!(plugin.pins_through_optimizer(&Expression::GreaterOrEqual(
467            Box::new(date("2020-01-01")),
468            Box::new(variable())
469        )));
470        assert!(
471            !plugin.pins_through_optimizer(&Expression::Less(
472                Box::new(variable()),
473                Box::new(Expression::Literal(oxrdf::Literal::from(5))),
474            )),
475            "a numeric comparison is not a temporal candidate producer"
476        );
477        assert!(!plugin.pins_through_optimizer(&Expression::Equal(
478            Box::new(variable()),
479            Box::new(variable())
480        )));
481
482        // A temporal comparison compares a value; grounding it folds to a
483        // constant, so it leaves the guard's default.
484        assert!(!plugin.keeps_variable_when_ground(&Expression::Less(
485            Box::new(variable()),
486            Box::new(date("2020-01-01"))
487        )));
488    }
489
490    /// Parse with a STAMPED temporal epoch (the trust gate refuses an
491    /// unstamped index — the compute auto-rebuild stamps it before queries
492    /// serve in production).
493    fn parse(sparql: &str) -> LogicalPlan {
494        let ctx =
495            waratah_compute::QueryContext::from_snapshot(waratah_storage::SnapshotId::latest())
496                .with_temporal_index_epoch(Some(1));
497        LogicalPlan::parse_with_context(sparql, &ctx).unwrap()
498    }
499
500    /// The first injected `Join(…, temporal_scan, [?t])` in the tree.
501    fn find_scan_join(node: &PlanNode) -> Option<(&PlanNode, &PlanNode, &JoinMeta)> {
502        match node {
503            PlanNode::Join {
504                left, right, meta, ..
505            } => {
506                let temporal = |n: &PlanNode| matches!(n, PlanNode::CustomNode(op) if op.op_id == TEMPORAL_SCAN_OP_ID);
507                if temporal(left) || temporal(right) {
508                    return Some((left, right, meta));
509                }
510                find_scan_join(left).or_else(|| find_scan_join(right))
511            }
512            PlanNode::Union { left, right } | PlanNode::LeftJoin { left, right, .. } => {
513                find_scan_join(left).or_else(|| find_scan_join(right))
514            }
515            PlanNode::Filter { inner, exists, .. } => find_scan_join(inner).or_else(|| {
516                exists
517                    .iter()
518                    .find_map(|clause| find_scan_join(&clause.body))
519            }),
520            PlanNode::CustomNode(op) => op.children.iter().find_map(find_scan_join),
521            PlanNode::Extend { inner, .. }
522            | PlanNode::Slice { inner, .. }
523            | PlanNode::Distinct { inner, .. }
524            | PlanNode::Sort { inner, .. }
525            | PlanNode::Group { inner, .. }
526            | PlanNode::JoinGraphVar { inner, .. } => find_scan_join(inner),
527            PlanNode::SubSelect(sub) => find_scan_join(&sub.inner),
528            _ => None,
529        }
530    }
531
532    fn scan_op(node: &PlanNode) -> &CustomOp {
533        let PlanNode::CustomNode(op) = node else {
534            panic!("expected the temporal_scan CustomNode, got {node:?}");
535        };
536        assert_eq!(op.op_id, TEMPORAL_SCAN_OP_ID);
537        op
538    }
539
540    const QUERY: &str = r#"
541        PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
542        SELECT ?event WHERE {
543            ?event <http://ex/observedAt> ?t .
544            FILTER(?t >= "2025-01-01T00:00:00Z"^^xsd:dateTime && ?t < "2026-01-01T00:00:00Z"^^xsd:dateTime)
545        }"#;
546
547    #[test]
548    fn range_conjuncts_merge_into_one_scan() {
549        installed();
550        let plan = parse(QUERY);
551        let (left, _, meta) = find_scan_join(&plan.root).expect("temporal join in plan");
552        let op = scan_op(left);
553        let Some(payload) = op.payload.downcast_ref::<TemporalScanPayload>() else {
554            panic!("payload type");
555        };
556        assert_eq!(payload.comparisons.len(), 2, "both conjuncts merged");
557        assert_eq!(op.variables[0].as_str(), "t");
558        // The join estimate equals the scan's (the geo stamp contract).
559        assert_eq!(
560            meta.produced_row_count_estimate,
561            op.produced_row_count_estimate
562        );
563        // Intervals are the window's budgeted covering + ancestors.
564        assert!(!payload.intervals.is_empty());
565    }
566
567    #[test]
568    fn estimate_reflects_window_width() {
569        installed();
570        // A histogram with a dense run over 2025 makes the wide window's
571        // estimate exceed the 1-second window's.
572        use waratah_storage::{ATTO_PER_SECOND, tick_to_key_u128};
573        let mut histogram = waratah_stats::TickHistogram::default();
574        let run_start = waratah_storage::tick_from_date(2025, 1, 1).unwrap();
575        for step in 0..5_000_u32 {
576            histogram.observe(tick_to_key_u128(
577                run_start + i128::from(step) * ATTO_PER_SECOND,
578            ));
579        }
580        let ctx =
581            waratah_compute::QueryContext::from_snapshot(waratah_storage::SnapshotId::latest())
582                .with_temporal_index_epoch(Some(1))
583                .with_temporal_histogram(Some(std::sync::Arc::new(histogram)));
584        let narrow = {
585            LogicalPlan::parse_with_context(
586                r#"
587                PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
588                SELECT ?event WHERE {
589                    ?event <http://ex/observedAt> ?t .
590                    FILTER(?t >= "2025-03-01T00:00:00Z"^^xsd:dateTime && ?t < "2025-03-01T00:00:01Z"^^xsd:dateTime)
591                }"#,
592                &ctx,
593            )
594            .unwrap()
595        };
596        let wide = LogicalPlan::parse_with_context(QUERY, &ctx).unwrap();
597        let narrow_rows = match find_scan_join(&narrow.root).unwrap() {
598            (PlanNode::CustomNode(op), _, _) => op.produced_row_count_estimate,
599            (_, PlanNode::CustomNode(op), _) => op.produced_row_count_estimate,
600            other => panic!("no scan: {other:?}"),
601        };
602        let wide_rows = match find_scan_join(&wide.root).unwrap() {
603            (PlanNode::CustomNode(op), _, _) => op.produced_row_count_estimate,
604            (_, PlanNode::CustomNode(op), _) => op.produced_row_count_estimate,
605            other => panic!("no scan: {other:?}"),
606        };
607        assert!(
608            wide_rows > narrow_rows,
609            "the wider window must estimate more rows: {wide_rows} vs {narrow_rows}"
610        );
611    }
612
613    #[test]
614    fn gyear_comparison_rewrites_in_non_strict_mode() {
615        installed();
616        waratah_compute::strict_sparql::set_strict_sparql(false);
617        let plan = parse(
618            r#"
619            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
620            SELECT ?era WHERE {
621                ?era <http://ex/begins> ?t .
622                FILTER(?t >= "-252000000"^^xsd:gYear)
623            }"#,
624        );
625        assert!(
626            find_scan_join(&plan.root).is_some(),
627            "gYear rewrite fires non-strict"
628        );
629        // Strict mode: the conjunct stays on the FILTER (type error there).
630        waratah_compute::strict_sparql::set_strict_sparql(true);
631        let strict_plan = parse(
632            r#"
633            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
634            SELECT ?era WHERE {
635                ?era <http://ex/begins> ?t .
636                FILTER(?t >= "-252000000"^^xsd:gYear)
637            }"#,
638        );
639        assert!(
640            find_scan_join(&strict_plan.root).is_none(),
641            "strict mode keeps the gYear conjunct unrewritten"
642        );
643        waratah_compute::strict_sparql::set_strict_sparql(false);
644    }
645
646    #[test]
647    fn non_temporal_consts_stay_unrewritten() {
648        installed();
649        let plan = parse(
650            r#"
651            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
652            SELECT ?thing WHERE {
653                ?thing <http://ex/size> ?t .
654                FILTER(?t >= "42"^^xsd:integer)
655            }"#,
656        );
657        assert!(
658            find_scan_join(&plan.root).is_none(),
659            "integer comparison untouched"
660        );
661    }
662
663    #[test]
664    fn equality_and_ne_stay_unrewritten() {
665        installed();
666        let plan = parse(
667            r#"
668            PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
669            SELECT ?event WHERE {
670                ?event <http://ex/observedAt> ?t .
671                FILTER(?t = "2025-01-01T00:00:00Z"^^xsd:dateTime)
672            }"#,
673        );
674        assert!(
675            find_scan_join(&plan.root).is_none(),
676            "equality untouched in v1"
677        );
678    }
679}