Skip to main content

waratah_storage/encode/
comparison_pushdown.rs

1//! Slot comparison pushdown for pattern scans.
2//!
3//! A planner may attach a small conjunction of `(slot, op, const)` comparisons
4//! to a scan. The partition evaluates them while walking the index, so a row
5//! that provably fails never reaches the wire. This is a **mask**, not an
6//! authority: the storage side drops only rows it can prove fail, and keeps
7//! every row whose comparison it cannot decide (a hashed string, an opaque
8//! datatype, a family the evaluator does not implement). The compute-side
9//! copy of the same conjunct remains in the plan and decides the kept rows.
10//! That is the same `mask ⊆ filter` rule as the `iri_only` pushdown.
11//!
12//! Two consequences the wire contract relies on:
13//!
14//! * The comparison is evaluated **inside** the walk's page-filling loop, so a
15//!   page still carries `limit` post-filter matches (or reports the honest
16//!   [`ScanExhaustion`] verdict). A short page is not EOF.
17//! * A comparison on a pattern-bound slot is constant; it is folded at
18//!   [`ComparisonMask::compile`] time and never evaluated per row.
19
20use std::cmp::Ordering;
21
22use super::binary::{IndexPermutation, QuadSlot, TermReader};
23use super::encoded_term::{EncodedTerm, RDF_TYPE};
24use super::pattern::EncodedTriplePattern;
25use super::str_hash::StrHash;
26
27/// Comparison applied by one [`SlotComparison`].
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum CompareOp {
30    /// `=`
31    Eq,
32    /// `!=`
33    Ne,
34    /// `<`
35    Lt,
36    /// `<=`
37    Le,
38    /// `>`
39    Gt,
40    /// `>=`
41    Ge,
42}
43
44/// One `slot OP term` comparison attached to a scan.
45///
46/// `term` is encoded exactly as it is stored. The slot must be one of
47/// subject / predicate / object; the graph slot is not pushed (the default
48/// graph's merge rewrite would change what the comparison sees).
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub struct SlotComparison {
51    /// Pattern slot the comparison applies to.
52    pub slot: QuadSlot,
53    /// Comparison operator.
54    pub op: CompareOp,
55    /// Encoded constant.
56    pub term: EncodedTerm,
57}
58
59/// Compiled slot comparisons for one scan.
60///
61/// One instance per walk. The allow-list road compiles it once against the
62/// base pattern and reuses it across every tight prefix: a comparison on the
63/// allow-listed slot is evaluated per row there, not folded per prefix. An
64/// empty mask is the identity and costs one `is_empty` check per row.
65#[derive(Debug, Clone)]
66pub struct ComparisonMask {
67    /// Permutation the slot indices were compiled against.
68    permutation: IndexPermutation,
69    /// Per-row checks grouped by key slot index (ascending). Each group
70    /// carries every comparison for that segment, so one decode answers them
71    /// all.
72    checks: Vec<(usize, Vec<(CompareOp, EncodedTerm)>)>,
73    /// A comparison on a pattern-bound slot proved false: no row can pass.
74    empty: bool,
75}
76
77impl Default for ComparisonMask {
78    fn default() -> Self {
79        Self {
80            permutation: IndexPermutation::Spog,
81            checks: Vec::new(),
82            empty: false,
83        }
84    }
85}
86
87impl ComparisonMask {
88    /// Compile `comparisons` for a scan of `pattern` through `permutation`.
89    ///
90    /// Comparisons on slots the pattern already binds are constant: a proven
91    /// false empties the scan, a proven true (or an undecidable) drops the
92    /// check. Slots the permutation omits (Tsg's implicit `rdf:type`
93    /// predicate) are folded the same way. Graph-slot comparisons are ignored:
94    /// the wire never carries them, and a `merge_default_graph` scan rewrites
95    /// G after the matcher runs.
96    pub fn compile(
97        pattern: &EncodedTriplePattern,
98        permutation: IndexPermutation,
99        comparisons: &[SlotComparison],
100    ) -> Self {
101        let order = permutation.slot_order();
102        let mut checks: Vec<(usize, Vec<(CompareOp, EncodedTerm)>)> = Vec::new();
103        let mut empty = false;
104        for comparison in comparisons {
105            // The graph slot is never pushed: the wire cannot carry it, and a
106            // `merge_default_graph` scan rewrites G before consumers see it.
107            if comparison.slot == QuadSlot::Graph {
108                continue;
109            }
110            let Some(index) = order.iter().position(|slot| *slot == comparison.slot) else {
111                // Tsg omits the predicate segment; every row's predicate is
112                // the implicit `rdf:type`.
113                if permutation == IndexPermutation::Tsg
114                    && comparison.slot == QuadSlot::Predicate
115                    && decide(&RDF_TYPE, comparison.op, &comparison.term) == Some(false)
116                {
117                    empty = true;
118                    break;
119                }
120                continue;
121            };
122            if let Some(bound) = pattern.bound_slot(comparison.slot) {
123                match decide(bound, comparison.op, &comparison.term) {
124                    Some(false) => {
125                        empty = true;
126                        break;
127                    }
128                    // Definite true and undecidable both need no per-row
129                    // check: the mask only drops proven failures.
130                    Some(true) | None => continue,
131                }
132            }
133            if let Some((_, ops)) = checks.iter_mut().find(|(slot, _)| *slot == index) {
134                ops.push((comparison.op, comparison.term.clone()));
135            } else {
136                checks.push((index, vec![(comparison.op, comparison.term.clone())]));
137            }
138        }
139        checks.sort_by_key(|(index, _)| *index);
140        Self {
141            permutation,
142            checks,
143            empty,
144        }
145    }
146
147    /// `true` when no row can pass the mask.
148    pub fn is_empty(&self) -> bool {
149        self.empty
150    }
151
152    /// `true` when the mask has no per-row work.
153    pub fn is_trivial(&self) -> bool {
154        self.empty || self.checks.is_empty()
155    }
156
157    /// Keep decision for one visible row.
158    ///
159    /// `logical` is the term prefix (no commit-ts trailer); `seg_starts` is
160    /// the walked slot-offset table. The mask carries the permutation it was
161    /// compiled against, so a filter cannot be applied to a key walked in a
162    /// different index order. A malformed segment is kept: the corruption
163    /// belongs to the decode path, not to a mask verdict.
164    pub fn keeps(&self, logical: &[u8], seg_starts: &[usize; 4]) -> bool {
165        if self.empty {
166            return false;
167        }
168        if self.checks.is_empty() {
169            return true;
170        }
171        let order_len = self.permutation.slot_order().len();
172        for (index, group) in &self.checks {
173            let end = if index + 1 < order_len {
174                seg_starts[index + 1]
175            } else {
176                logical.len()
177            };
178            let segment = &logical[seg_starts[*index]..end];
179            let mut cursor = segment;
180            let term = match cursor.read_term() {
181                Ok(term) => term,
182                Err(_) => return true,
183            };
184            for (op, target) in group {
185                if decide(&term, *op, target) == Some(false) {
186                    return false;
187                }
188            }
189        }
190        true
191    }
192}
193
194/// Decide one slot comparison against one encoded term.
195///
196/// `Some(bool)` is the partition mask's definite verdict; `None` means the
197/// mask keeps the row for the compute evaluator. Public so the compute crate's
198/// differential test can exercise this evaluator against its kernels.
199pub fn decide_slot_comparison(
200    term: &EncodedTerm,
201    op: CompareOp,
202    target: &EncodedTerm,
203) -> Option<bool> {
204    decide(term, op, target)
205}
206
207/// Three-valued comparison verdict: a row is kept only on `Unknown`.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209enum Truth {
210    True,
211    False,
212    Type,
213    Unknown,
214}
215
216/// Ordering verdict: a known incompatibility is a type error (drop), not an
217/// unknown (keep).
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219enum Cmp {
220    Ordered(Ordering),
221    Type,
222    Unknown,
223}
224
225/// Evaluate one comparison against one term. `None` = undecidable (keep).
226fn decide(term: &EncodedTerm, op: CompareOp, target: &EncodedTerm) -> Option<bool> {
227    // The compute kernel's reflexivity shortcut (`ops.rs::compare_numeric`):
228    // any non-float term compared with itself is ordered-equal. Applying it
229    // to `=`/`!=` as well is sound because encoded identity implies value
230    // equality for every non-float variant (same bits → same value / instant
231    // / lexical / term). Floats are excluded: `+0.0` and `-0.0` are distinct
232    // terms but value- and order-equal, and a same-bits NaN is one term but
233    // `<=`/`>=` on it is a type error.
234    if term == target
235        && !matches!(
236            term,
237            EncodedTerm::FloatLiteral(_) | EncodedTerm::DoubleLiteral(_)
238        )
239    {
240        return Some(matches!(op, CompareOp::Eq | CompareOp::Le | CompareOp::Ge));
241    }
242    match op {
243        CompareOp::Eq => match term_eq(term, target) {
244            Truth::True => Some(true),
245            Truth::False | Truth::Type => Some(false),
246            Truth::Unknown => None,
247        },
248        CompareOp::Ne => match term_eq(term, target) {
249            Truth::True => Some(false),
250            Truth::False => Some(true),
251            // An error operand makes `!=` an error too, which a FILTER drops.
252            Truth::Type => Some(false),
253            Truth::Unknown => None,
254        },
255        CompareOp::Lt | CompareOp::Le | CompareOp::Gt | CompareOp::Ge => {
256            match term_cmp(term, target) {
257                Cmp::Ordered(ordering) => Some(matches!(
258                    (op, ordering),
259                    (CompareOp::Lt, Ordering::Less)
260                        | (CompareOp::Le, Ordering::Less | Ordering::Equal)
261                        | (CompareOp::Gt, Ordering::Greater)
262                        | (CompareOp::Ge, Ordering::Greater | Ordering::Equal)
263                )),
264                Cmp::Type => Some(false),
265                Cmp::Unknown => None,
266            }
267        }
268    }
269}
270
271fn is_numeric(term: &EncodedTerm) -> bool {
272    matches!(
273        term,
274        EncodedTerm::IntegerLiteral(_)
275            | EncodedTerm::DecimalLiteral(_)
276            | EncodedTerm::FloatLiteral(_)
277            | EncodedTerm::DoubleLiteral(_)
278    )
279}
280
281fn is_string(term: &EncodedTerm) -> bool {
282    matches!(
283        term,
284        EncodedTerm::SmallStringLiteral(_) | EncodedTerm::BigStringLiteral { .. }
285    )
286}
287
288fn is_lang_string(term: &EncodedTerm) -> bool {
289    matches!(
290        term,
291        EncodedTerm::SmallSmallLangStringLiteral { .. }
292            | EncodedTerm::SmallBigLangStringLiteral { .. }
293            | EncodedTerm::BigSmallLangStringLiteral { .. }
294            | EncodedTerm::BigBigLangStringLiteral { .. }
295    )
296}
297
298fn is_opaque(term: &EncodedTerm) -> bool {
299    matches!(
300        term,
301        EncodedTerm::SmallTypedLiteral { .. } | EncodedTerm::BigTypedLiteral { .. }
302    )
303}
304
305fn is_geometry(term: &EncodedTerm) -> bool {
306    matches!(
307        term,
308        EncodedTerm::LiteralPoint { .. }
309            | EncodedTerm::LiteralGeometry { .. }
310            | EncodedTerm::BlobLiteral { .. }
311    )
312}
313
314/// IRI, blank node, or default graph: a term with no literal value space.
315fn is_non_literal_term(term: &EncodedTerm) -> bool {
316    matches!(
317        term,
318        EncodedTerm::NamedNode { .. }
319            | EncodedTerm::NumericalBlankNode { .. }
320            | EncodedTerm::SmallBlankNode(_)
321            | EncodedTerm::BigBlankNode { .. }
322            | EncodedTerm::DefaultGraph
323    )
324}
325
326/// Encoded string value equality, the same contract the compute evaluator
327/// uses: inline strings compare lexically, and any pair involving a hashed
328/// string compares the 128-bit SipHash of the lexical (which is the term's
329/// stored id). Exact up to a 128-bit collision.
330fn string_content_eq(a: &EncodedTerm, b: &EncodedTerm) -> bool {
331    match (a, b) {
332        (EncodedTerm::SmallStringLiteral(a), EncodedTerm::SmallStringLiteral(b)) => a == b,
333        (
334            EncodedTerm::BigStringLiteral { value_id: a },
335            EncodedTerm::BigStringLiteral { value_id: b },
336        ) => a == b,
337        (EncodedTerm::SmallStringLiteral(a), EncodedTerm::BigStringLiteral { value_id: b }) => {
338            &StrHash::new(a.as_str()) == b
339        }
340        (EncodedTerm::BigStringLiteral { value_id: a }, EncodedTerm::SmallStringLiteral(b)) => {
341            a == &StrHash::new(b.as_str())
342        }
343        _ => false,
344    }
345}
346
347/// Value equality over the encoded variants this evaluator can decide.
348///
349/// Numeric promotion, strings, language tags, booleans, temporal payloads and
350/// term identity are exact. Two opaque typed literals are `Unknown` (the
351/// compute side owns their value semantics); one opaque typed literal against
352/// an IRI, blank node, default graph or geo term is a definite inequality,
353/// and against a native literal family it is a type error. Cross-family
354/// pairings follow the SPARQL operator mapping: a definite inequality where
355/// the operator table returns `false`, a type error where it returns an
356/// error.
357fn term_eq(a: &EncodedTerm, b: &EncodedTerm) -> Truth {
358    if is_numeric(a) || is_numeric(b) {
359        if !(is_numeric(a) && is_numeric(b)) {
360            // Numeric vs non-numeric is a definite inequality; an opaque
361            // typed literal has no operator-mapping row against a numeric,
362            // so the comparison is a type error (FILTER drops it).
363            return if is_opaque(a) || is_opaque(b) {
364                Truth::Type
365            } else {
366                Truth::False
367            };
368        }
369        return numeric_eq(a, b);
370    }
371    if is_string(a) || is_string(b) {
372        if is_string(a) && is_string(b) {
373            return truth(string_content_eq(a, b));
374        }
375        // A string vs an opaque typed literal is a type error; vs a native
376        // non-string it is a definite inequality.
377        return if is_opaque(a) || is_opaque(b) {
378            Truth::Type
379        } else {
380            Truth::False
381        };
382    }
383    if is_lang_string(a) || is_lang_string(b) {
384        // SPARQL 1.1 operator mapping: same language-tagged term is equal,
385        // every other literal pairing is determinately different.
386        return truth(a == b);
387    }
388    if is_opaque(a) || is_opaque(b) {
389        // Two opaque typed literals need the compute evaluator's datatype
390        // rules: keep them.
391        if is_opaque(a) && is_opaque(b) {
392            return Truth::Unknown;
393        }
394        // One opaque typed literal against a non-literal term is a definite
395        // inequality in the compute kernel (`ops::equals`: the opaque arm maps
396        // IRI / bnode / lang to `Some(false)`, and the IRI/bnode/geo arms map
397        // an opaque counterpart to `Some(false)`). Against a native literal
398        // family (boolean, temporal, duration) it is a type error.
399        //
400        // The geo term is the one asymmetric pairing in the kernel (the geo
401        // arm answers `false`, the opaque arm answers `None`). `Truth::False`
402        // is the safe verdict there: `Eq` drops either way, and `Ne` keeps a
403        // row the compute side then drops — under-filtering, never an
404        // over-drop.
405        let other = if is_opaque(a) { b } else { a };
406        return if is_non_literal_term(other) || is_geometry(other) {
407            Truth::False
408        } else {
409            Truth::Type
410        };
411    }
412    if is_geometry(a) || is_geometry(b) {
413        return truth(a == b);
414    }
415    // Same-variant families whose `PartialEq` is the operator result.
416    match (a, b) {
417        (EncodedTerm::BooleanLiteral(x), EncodedTerm::BooleanLiteral(y)) => truth(x == y),
418        (EncodedTerm::DateTimeLiteral(x), EncodedTerm::DateTimeLiteral(y)) => truth(x == y),
419        (EncodedTerm::TimeLiteral(x), EncodedTerm::TimeLiteral(y)) => truth(x == y),
420        (EncodedTerm::DateLiteral(x), EncodedTerm::DateLiteral(y)) => {
421            // `op:date-equal` compares instants; the payload's partial order
422            // carries the timezone rules.
423            match x.partial_cmp(y) {
424                Some(Ordering::Equal) => Truth::True,
425                Some(_) => Truth::False,
426                None => Truth::Type,
427            }
428        }
429        (EncodedTerm::GYearMonthLiteral(x), EncodedTerm::GYearMonthLiteral(y)) => truth(x == y),
430        (EncodedTerm::GYearLiteral(x), EncodedTerm::GYearLiteral(y)) => truth(x == y),
431        (EncodedTerm::GMonthDayLiteral(x), EncodedTerm::GMonthDayLiteral(y)) => truth(x == y),
432        (EncodedTerm::GDayLiteral(x), EncodedTerm::GDayLiteral(y)) => truth(x == y),
433        (EncodedTerm::GMonthLiteral(x), EncodedTerm::GMonthLiteral(y)) => truth(x == y),
434        // Duration equality across the three variants is a datatype-family
435        // rule this evaluator does not need; keep it compute-side.
436        (
437            EncodedTerm::DurationLiteral(_)
438            | EncodedTerm::YearMonthDurationLiteral(_)
439            | EncodedTerm::DayTimeDurationLiteral(_),
440            EncodedTerm::DurationLiteral(_)
441            | EncodedTerm::YearMonthDurationLiteral(_)
442            | EncodedTerm::DayTimeDurationLiteral(_),
443        ) => Truth::Unknown,
444        (EncodedTerm::NamedNode { .. }, EncodedTerm::NamedNode { .. }) => truth(a == b),
445        (EncodedTerm::NumericalBlankNode { .. }, EncodedTerm::NumericalBlankNode { .. }) => {
446            truth(a == b)
447        }
448        (EncodedTerm::SmallBlankNode(_), EncodedTerm::SmallBlankNode(_)) => truth(a == b),
449        (EncodedTerm::BigBlankNode { .. }, EncodedTerm::BigBlankNode { .. }) => truth(a == b),
450        (EncodedTerm::DefaultGraph, EncodedTerm::DefaultGraph) => Truth::True,
451        (EncodedTerm::BooleanLiteral(_), _)
452        | (_, EncodedTerm::BooleanLiteral(_))
453        | (EncodedTerm::DateTimeLiteral(_), _)
454        | (_, EncodedTerm::DateTimeLiteral(_))
455        | (EncodedTerm::TimeLiteral(_), _)
456        | (_, EncodedTerm::TimeLiteral(_))
457        | (EncodedTerm::DateLiteral(_), _)
458        | (_, EncodedTerm::DateLiteral(_))
459        | (EncodedTerm::GYearMonthLiteral(_), _)
460        | (_, EncodedTerm::GYearMonthLiteral(_))
461        | (EncodedTerm::GYearLiteral(_), _)
462        | (_, EncodedTerm::GYearLiteral(_))
463        | (EncodedTerm::GMonthDayLiteral(_), _)
464        | (_, EncodedTerm::GMonthDayLiteral(_))
465        | (EncodedTerm::GDayLiteral(_), _)
466        | (_, EncodedTerm::GDayLiteral(_))
467        | (EncodedTerm::GMonthLiteral(_), _)
468        | (_, EncodedTerm::GMonthLiteral(_))
469        | (EncodedTerm::DefaultGraph, EncodedTerm::NamedNode { .. })
470        | (EncodedTerm::NamedNode { .. }, EncodedTerm::DefaultGraph)
471        | (EncodedTerm::DefaultGraph, EncodedTerm::NumericalBlankNode { .. })
472        | (EncodedTerm::NumericalBlankNode { .. }, EncodedTerm::DefaultGraph)
473        | (EncodedTerm::DefaultGraph, EncodedTerm::SmallBlankNode(_))
474        | (EncodedTerm::SmallBlankNode(_), EncodedTerm::DefaultGraph)
475        | (EncodedTerm::DefaultGraph, EncodedTerm::BigBlankNode { .. })
476        | (EncodedTerm::BigBlankNode { .. }, EncodedTerm::DefaultGraph) => Truth::False,
477        _ => Truth::Unknown,
478    }
479}
480
481fn truth(value: bool) -> Truth {
482    if value { Truth::True } else { Truth::False }
483}
484
485fn numeric_eq(a: &EncodedTerm, b: &EncodedTerm) -> Truth {
486    // Mirrors the compute evaluator's numeric arms (op:numeric-equal).
487    let equal = match (a, b) {
488        (EncodedTerm::FloatLiteral(x), EncodedTerm::FloatLiteral(y)) => x == y,
489        (EncodedTerm::FloatLiteral(x), EncodedTerm::DoubleLiteral(y)) => {
490            oxsdatatypes::Double::from(*x) == *y
491        }
492        (EncodedTerm::FloatLiteral(x), EncodedTerm::IntegerLiteral(y)) => {
493            *x == oxsdatatypes::Float::from(*y)
494        }
495        (EncodedTerm::FloatLiteral(x), EncodedTerm::DecimalLiteral(y)) => {
496            *x == oxsdatatypes::Float::from(*y)
497        }
498        (EncodedTerm::DoubleLiteral(x), EncodedTerm::FloatLiteral(y)) => {
499            *x == oxsdatatypes::Double::from(*y)
500        }
501        (EncodedTerm::DoubleLiteral(x), EncodedTerm::DoubleLiteral(y)) => x == y,
502        (EncodedTerm::DoubleLiteral(x), EncodedTerm::IntegerLiteral(y)) => {
503            *x == oxsdatatypes::Double::from(*y)
504        }
505        (EncodedTerm::DoubleLiteral(x), EncodedTerm::DecimalLiteral(y)) => {
506            *x == oxsdatatypes::Double::from(*y)
507        }
508        (EncodedTerm::IntegerLiteral(x), EncodedTerm::FloatLiteral(y)) => {
509            oxsdatatypes::Float::from(*x) == *y
510        }
511        (EncodedTerm::IntegerLiteral(x), EncodedTerm::DoubleLiteral(y)) => {
512            oxsdatatypes::Double::from(*x) == *y
513        }
514        (EncodedTerm::IntegerLiteral(x), EncodedTerm::IntegerLiteral(y)) => x == y,
515        (EncodedTerm::IntegerLiteral(x), EncodedTerm::DecimalLiteral(y)) => {
516            oxsdatatypes::Decimal::from(*x) == *y
517        }
518        (EncodedTerm::DecimalLiteral(x), EncodedTerm::FloatLiteral(y)) => {
519            oxsdatatypes::Float::from(*x) == *y
520        }
521        (EncodedTerm::DecimalLiteral(x), EncodedTerm::DoubleLiteral(y)) => {
522            oxsdatatypes::Double::from(*x) == *y
523        }
524        (EncodedTerm::DecimalLiteral(x), EncodedTerm::IntegerLiteral(y)) => {
525            *x == oxsdatatypes::Decimal::from(*y)
526        }
527        (EncodedTerm::DecimalLiteral(x), EncodedTerm::DecimalLiteral(y)) => x == y,
528        _ => return Truth::Unknown,
529    };
530    truth(equal)
531}
532
533fn term_cmp(a: &EncodedTerm, b: &EncodedTerm) -> Cmp {
534    if is_numeric(a) && is_numeric(b) {
535        return numeric_cmp(a, b);
536    }
537    if is_numeric(a) || is_numeric(b) {
538        return if is_opaque(a) || is_opaque(b) {
539            Cmp::Unknown
540        } else {
541            Cmp::Type
542        };
543    }
544    if is_string(a) && is_string(b) {
545        return match (a, b) {
546            (EncodedTerm::SmallStringLiteral(x), EncodedTerm::SmallStringLiteral(y)) => {
547                match x.as_str().partial_cmp(y.as_str()) {
548                    Some(ordering) => Cmp::Ordered(ordering),
549                    None => Cmp::Type,
550                }
551            }
552            // Big-string order needs the lexical; the compute side resolves.
553            _ => Cmp::Unknown,
554        };
555    }
556    if is_string(a) || is_string(b) {
557        return if is_opaque(a) || is_opaque(b) {
558            Cmp::Unknown
559        } else {
560            Cmp::Type
561        };
562    }
563    if is_opaque(a) || is_opaque(b) || is_geometry(a) || is_geometry(b) {
564        // Opaque / geo ordering has no operator-mapping row; leave the
565        // decision to compute rather than claiming a type error.
566        return Cmp::Unknown;
567    }
568    match (a, b) {
569        (EncodedTerm::DateTimeLiteral(x), EncodedTerm::DateTimeLiteral(y)) => {
570            cmp_opt(x.partial_cmp(y))
571        }
572        (EncodedTerm::DateLiteral(x), EncodedTerm::DateLiteral(y)) => cmp_opt(x.partial_cmp(y)),
573        // `compare_numeric` has no Time/GYear/duration ordering arm (gYear is
574        // strict-mode dependent); those stay compute-side.
575        (EncodedTerm::TimeLiteral(_), _) | (_, EncodedTerm::TimeLiteral(_)) => Cmp::Type,
576        (
577            EncodedTerm::GYearLiteral(_)
578            | EncodedTerm::GYearMonthLiteral(_)
579            | EncodedTerm::GMonthDayLiteral(_)
580            | EncodedTerm::GDayLiteral(_)
581            | EncodedTerm::GMonthLiteral(_)
582            | EncodedTerm::DurationLiteral(_)
583            | EncodedTerm::YearMonthDurationLiteral(_)
584            | EncodedTerm::DayTimeDurationLiteral(_),
585            _,
586        )
587        | (
588            _,
589            EncodedTerm::GYearLiteral(_)
590            | EncodedTerm::GYearMonthLiteral(_)
591            | EncodedTerm::GMonthDayLiteral(_)
592            | EncodedTerm::GDayLiteral(_)
593            | EncodedTerm::GMonthLiteral(_)
594            | EncodedTerm::DurationLiteral(_)
595            | EncodedTerm::YearMonthDurationLiteral(_)
596            | EncodedTerm::DayTimeDurationLiteral(_),
597        ) => Cmp::Unknown,
598        // Every remaining native pairing has no ordering row.
599        (EncodedTerm::BooleanLiteral(_), _)
600        | (_, EncodedTerm::BooleanLiteral(_))
601        | (EncodedTerm::NamedNode { .. }, _)
602        | (_, EncodedTerm::NamedNode { .. })
603        | (EncodedTerm::NumericalBlankNode { .. }, _)
604        | (_, EncodedTerm::NumericalBlankNode { .. })
605        | (EncodedTerm::SmallBlankNode(_), _)
606        | (_, EncodedTerm::SmallBlankNode(_))
607        | (EncodedTerm::BigBlankNode { .. }, _)
608        | (_, EncodedTerm::BigBlankNode { .. })
609        | (EncodedTerm::DefaultGraph, _)
610        | (_, EncodedTerm::DefaultGraph)
611        | (EncodedTerm::SmallSmallLangStringLiteral { .. }, _)
612        | (EncodedTerm::SmallBigLangStringLiteral { .. }, _)
613        | (EncodedTerm::BigSmallLangStringLiteral { .. }, _)
614        | (EncodedTerm::BigBigLangStringLiteral { .. }, _)
615        | (_, EncodedTerm::SmallSmallLangStringLiteral { .. })
616        | (_, EncodedTerm::SmallBigLangStringLiteral { .. })
617        | (_, EncodedTerm::BigSmallLangStringLiteral { .. })
618        | (_, EncodedTerm::BigBigLangStringLiteral { .. }) => Cmp::Type,
619        _ => Cmp::Unknown,
620    }
621}
622
623fn cmp_opt(ordering: Option<Ordering>) -> Cmp {
624    match ordering {
625        Some(ordering) => Cmp::Ordered(ordering),
626        // NaN: `op:numeric-less-than` is false, a type error for FILTER.
627        None => Cmp::Type,
628    }
629}
630
631fn numeric_cmp(a: &EncodedTerm, b: &EncodedTerm) -> Cmp {
632    // Mirrors `compare_numeric`'s numeric arms.
633    let ordering = match (a, b) {
634        (EncodedTerm::FloatLiteral(x), EncodedTerm::FloatLiteral(y)) => x.partial_cmp(y),
635        (EncodedTerm::FloatLiteral(x), EncodedTerm::DoubleLiteral(y)) => {
636            oxsdatatypes::Double::from(*x).partial_cmp(y)
637        }
638        (EncodedTerm::FloatLiteral(x), EncodedTerm::IntegerLiteral(y)) => {
639            x.partial_cmp(&oxsdatatypes::Float::from(*y))
640        }
641        (EncodedTerm::FloatLiteral(x), EncodedTerm::DecimalLiteral(y)) => {
642            x.partial_cmp(&oxsdatatypes::Float::from(*y))
643        }
644        (EncodedTerm::DoubleLiteral(x), EncodedTerm::FloatLiteral(y)) => {
645            x.partial_cmp(&oxsdatatypes::Double::from(*y))
646        }
647        (EncodedTerm::DoubleLiteral(x), EncodedTerm::DoubleLiteral(y)) => x.partial_cmp(y),
648        (EncodedTerm::DoubleLiteral(x), EncodedTerm::IntegerLiteral(y)) => {
649            x.partial_cmp(&oxsdatatypes::Double::from(*y))
650        }
651        (EncodedTerm::DoubleLiteral(x), EncodedTerm::DecimalLiteral(y)) => {
652            x.partial_cmp(&oxsdatatypes::Double::from(*y))
653        }
654        (EncodedTerm::IntegerLiteral(x), EncodedTerm::FloatLiteral(y)) => {
655            oxsdatatypes::Float::from(*x).partial_cmp(y)
656        }
657        (EncodedTerm::IntegerLiteral(x), EncodedTerm::DoubleLiteral(y)) => {
658            oxsdatatypes::Double::from(*x).partial_cmp(y)
659        }
660        (EncodedTerm::IntegerLiteral(x), EncodedTerm::IntegerLiteral(y)) => x.partial_cmp(y),
661        (EncodedTerm::IntegerLiteral(x), EncodedTerm::DecimalLiteral(y)) => {
662            oxsdatatypes::Decimal::from(*x).partial_cmp(y)
663        }
664        (EncodedTerm::DecimalLiteral(x), EncodedTerm::FloatLiteral(y)) => {
665            oxsdatatypes::Float::from(*x).partial_cmp(y)
666        }
667        (EncodedTerm::DecimalLiteral(x), EncodedTerm::DoubleLiteral(y)) => {
668            oxsdatatypes::Double::from(*x).partial_cmp(y)
669        }
670        (EncodedTerm::DecimalLiteral(x), EncodedTerm::IntegerLiteral(y)) => {
671            x.partial_cmp(&oxsdatatypes::Decimal::from(*y))
672        }
673        (EncodedTerm::DecimalLiteral(x), EncodedTerm::DecimalLiteral(y)) => x.partial_cmp(y),
674        _ => return Cmp::Unknown,
675    };
676    cmp_opt(ordering)
677}
678
679#[cfg(test)]
680mod tests {
681    use super::*;
682    use crate::Literal;
683    use crate::NamedNode;
684    use crate::encode::encoded_term::EncodedQuad;
685    use crate::encode::pattern::EncodedTriplePattern;
686
687    fn int(value: i64) -> EncodedTerm {
688        EncodedTerm::from(&Literal::from(value))
689    }
690
691    fn lit(value: &str) -> EncodedTerm {
692        EncodedTerm::from(&Literal::new_simple_literal(value))
693    }
694
695    fn comparison(slot: QuadSlot, op: CompareOp, term: EncodedTerm) -> SlotComparison {
696        SlotComparison { slot, op, term }
697    }
698
699    /// A row's logical key and segment table for a simple S‖P‖O‖G key is
700    /// built by the production encoder; these tests evaluate the mask on
701    /// the encoded term directly, so the full key walk is covered by the
702    /// backend scan tests.
703    fn decide_term(term: &EncodedTerm, op: CompareOp, target: &EncodedTerm) -> Option<bool> {
704        decide(term, op, target)
705    }
706
707    #[test]
708    fn numeric_range_is_decided() {
709        assert_eq!(
710            decide_term(&int(1967), CompareOp::Ge, &int(1967)),
711            Some(true)
712        );
713        assert_eq!(
714            decide_term(&int(1966), CompareOp::Ge, &int(1967)),
715            Some(false)
716        );
717        assert_eq!(
718            decide_term(&int(1971), CompareOp::Le, &int(1971)),
719            Some(true)
720        );
721        assert_eq!(
722            decide_term(&int(1972), CompareOp::Le, &int(1971)),
723            Some(false)
724        );
725        // Promotion across numeric families.
726        assert_eq!(
727            decide_term(
728                &EncodedTerm::from(&Literal::from(1967.0f64)),
729                CompareOp::Eq,
730                &int(1967)
731            ),
732            Some(true)
733        );
734    }
735
736    /// The compute kernel treats any non-float term compared with itself as
737    /// ordered-equal (`compare_numeric`'s reflexivity shortcut). Families
738    /// without an ordering arm — time, boolean, IRI, bnode, language-tagged —
739    /// would otherwise return `Type` and drop exactly the row equal to the
740    /// constant.
741    #[test]
742    fn identical_non_float_terms_are_ordered_equal() {
743        let time = EncodedTerm::from(&Literal::new_typed_literal(
744            "13:00:00",
745            NamedNode::new_unchecked("http://www.w3.org/2001/XMLSchema#time"),
746        ));
747        let boolean = EncodedTerm::from(&Literal::from(true));
748        let iri = EncodedTerm::from(&NamedNode::new_unchecked("http://ex/iri"));
749        let bnode = EncodedTerm::from(&crate::BlankNode::new("b").unwrap());
750        let lang = EncodedTerm::from(&Literal::new_language_tagged_literal("x", "en").unwrap());
751        for term in [&time, &boolean, &iri, &bnode, &lang] {
752            assert_eq!(decide_term(term, CompareOp::Le, term), Some(true));
753            assert_eq!(decide_term(term, CompareOp::Ge, term), Some(true));
754            assert_eq!(decide_term(term, CompareOp::Lt, term), Some(false));
755            assert_eq!(decide_term(term, CompareOp::Gt, term), Some(false));
756            assert_eq!(decide_term(term, CompareOp::Eq, term), Some(true));
757            assert_eq!(decide_term(term, CompareOp::Ne, term), Some(false));
758        }
759
760        // Floats are excluded from the shortcut: ±0.0 are distinct terms but
761        // still order-equal through `partial_cmp`.
762        let positive_zero = EncodedTerm::from(&Literal::from(0.0f64));
763        let negative_zero = EncodedTerm::from(&Literal::from(-0.0f64));
764        assert!(positive_zero != negative_zero);
765        assert_eq!(
766            decide_term(&positive_zero, CompareOp::Le, &negative_zero),
767            Some(true)
768        );
769        assert_eq!(
770            decide_term(&positive_zero, CompareOp::Ge, &negative_zero),
771            Some(true)
772        );
773        // Same-bits NaN is one term but `<=`/`>=` on it is a type error.
774        let nan = EncodedTerm::from(&Literal::from(f64::NAN));
775        assert_eq!(decide_term(&nan, CompareOp::Le, &nan), Some(false));
776        assert_eq!(decide_term(&nan, CompareOp::Ge, &nan), Some(false));
777    }
778
779    #[test]
780    fn type_mismatch_drops_but_undecidable_keeps() {
781        // A string vs an integer is a type error for ordering: FILTER drops.
782        assert_eq!(decide_term(&lit("x"), CompareOp::Lt, &int(1)), Some(false));
783        // A big string's order needs the registry: keep for compute.
784        let big = lit("aaaaaaaaaaaaaaaa");
785        assert!(matches!(big, EncodedTerm::BigStringLiteral { .. }));
786        assert_eq!(decide_term(&big, CompareOp::Lt, &lit("b")), None);
787        // Equality on the same hashed string is decidable.
788        assert_eq!(decide_term(&big, CompareOp::Eq, &big), Some(true));
789        assert_eq!(
790            decide_term(&big, CompareOp::Eq, &lit("bbbbbbbbbbbbbbbb")),
791            Some(false)
792        );
793        // Small-vs-big equality uses the lexical hash.
794        assert_eq!(decide_term(&big, CompareOp::Eq, &lit("short")), Some(false));
795    }
796
797    #[test]
798    fn ne_inverts_definite_equality_but_not_type_errors() {
799        assert_eq!(decide_term(&int(1), CompareOp::Ne, &int(2)), Some(true));
800        assert_eq!(decide_term(&int(1), CompareOp::Ne, &int(1)), Some(false));
801        // Opaque vs native is a type error: `!=` drops the row too.
802        let opaque = EncodedTerm::from(&Literal::new_typed_literal(
803            "x",
804            NamedNode::new_unchecked("http://example.org/things#myType"),
805        ));
806        assert_eq!(decide_term(&opaque, CompareOp::Ne, &int(1)), Some(false));
807    }
808
809    /// `equals` calls an opaque typed literal against an IRI or a blank node
810    /// a definite inequality, not a type error, so `!=` keeps the row. The
811    /// mask must agree: dropping here would lose rows the plan keeps.
812    #[test]
813    fn ne_keeps_opaque_typed_vs_iri_and_blank_node() {
814        let opaque = EncodedTerm::from(&Literal::new_typed_literal(
815            "x",
816            NamedNode::new_unchecked("http://example.org/things#myType"),
817        ));
818        let iri = EncodedTerm::from(&NamedNode::new_unchecked("http://ex/iri"));
819        let bnode = EncodedTerm::from(&crate::BlankNode::new("b").unwrap());
820
821        for other in [&iri, &bnode] {
822            assert_eq!(decide_term(&opaque, CompareOp::Ne, other), Some(true));
823            assert_eq!(decide_term(other, CompareOp::Ne, &opaque), Some(true));
824            assert_eq!(decide_term(&opaque, CompareOp::Eq, other), Some(false));
825            assert_eq!(decide_term(other, CompareOp::Eq, &opaque), Some(false));
826        }
827    }
828
829    #[test]
830    fn bound_slot_comparison_folds_to_empty() {
831        let pattern = EncodedTriplePattern {
832            subject: None,
833            predicate: Some(EncodedTerm::from(&NamedNode::new_unchecked("http://ex/p"))),
834            object: None,
835            graph_name: None,
836        };
837        // The bound predicate is `:p`, the comparison says `= :q`.
838        let mask = ComparisonMask::compile(
839            &pattern,
840            IndexPermutation::Posg,
841            &[comparison(
842                QuadSlot::Predicate,
843                CompareOp::Eq,
844                EncodedTerm::from(&NamedNode::new_unchecked("http://ex/q")),
845            )],
846        );
847        assert!(mask.is_empty());
848    }
849
850    #[test]
851    fn empty_mask_is_the_identity() {
852        let pattern = EncodedTriplePattern::default();
853        let mask = ComparisonMask::compile(&pattern, IndexPermutation::Spog, &[]);
854        assert!(mask.is_trivial());
855        assert!(mask.keeps(&[], &[0; 4]));
856    }
857
858    #[test]
859    fn full_key_mask_keeps_only_matching_rows() {
860        use crate::encode::binary::{IndexPermutation, encode_index_key};
861
862        let make = |year: i64| {
863            EncodedQuad::new(
864                EncodedTerm::from(&NamedNode::new_unchecked("http://ex/s")),
865                EncodedTerm::from(&NamedNode::new_unchecked("http://ex/year")),
866                int(year),
867                EncodedTerm::DefaultGraph,
868            )
869        };
870        let pattern = EncodedTriplePattern {
871            subject: None,
872            predicate: Some(EncodedTerm::from(&NamedNode::new_unchecked(
873                "http://ex/year",
874            ))),
875            object: None,
876            graph_name: None,
877        };
878        let mask = ComparisonMask::compile(
879            &pattern,
880            IndexPermutation::Posg,
881            &[comparison(QuadSlot::Object, CompareOp::Ge, int(1967))],
882        );
883        for (year, expected) in [(1966, false), (1967, true), (1971, true), (1972, true)] {
884            let mut key = encode_index_key(IndexPermutation::Posg, &make(year));
885            // `KeyRow` expects the versioned-key shape; the trailer is not
886            // read by the mask, but the walk needs it to locate the terms.
887            key.extend_from_slice(&[0u8; 8]);
888            let row = crate::encode::key_matcher::KeyRow::from_versioned_key(
889                &key,
890                IndexPermutation::Posg,
891            )
892            .expect("key owned by encode_index_key");
893            assert_eq!(
894                mask.keeps(row.logical(), &row.seg_starts),
895                expected,
896                "year {year}"
897            );
898        }
899    }
900}