Skip to main content

waratah_compute/expr/
capability.rs

1//! Static capability of SPARQL expressions for early vs residual FILTER.
2
3use spargebra::algebra::{Expression, Function};
4use waratah_storage::{StrHash, Term, vocab::xsd, well_known_iri};
5
6use crate::custom_fns::process_registry;
7use crate::error::ComputeError;
8
9/// How far an expression can be evaluated without the string registry.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
11pub enum ExprCapability {
12    /// Correct on [`EncodedTerm`](waratah_storage::EncodedTerm) alone.
13    AlwaysEncoded,
14    /// Often encoded; some term variants need registry resolve.
15    MaybeEncoded,
16    /// Requires resolved strings (deferred residual path).
17    AlwaysResolve,
18    /// Not implemented.
19    Unsupported,
20}
21
22/// Classify `expression` for planning (early vs residual).
23pub fn classify(expression: &Expression) -> ExprCapability {
24    match expression {
25        Expression::NamedNode(_) | Expression::Literal(_) | Expression::Variable(_) => {
26            ExprCapability::AlwaysEncoded
27        }
28        Expression::Bound(_) => ExprCapability::AlwaysEncoded,
29        Expression::Not(inner) => classify(inner),
30        Expression::And(left, right) | Expression::Or(left, right) => {
31            max_cap(classify(left), classify(right))
32        }
33        Expression::SameTerm(left, right) => {
34            max_cap(classify(left), classify(right)).max(ExprCapability::AlwaysEncoded)
35        }
36        // `value_equals` / `equals` are total over encoded terms: every
37        // pairing yields `Some(bool)` or a decidable type error (`None`),
38        // never `NeedsResolve`. Only operand evaluation can need the
39        // registry (`STR(?v) = "a"`), and `max_cap` already carries that.
40        Expression::Equal(left, right) => max_cap(classify(left), classify(right)),
41        Expression::Greater(left, right)
42        | Expression::GreaterOrEqual(left, right)
43        | Expression::Less(left, right)
44        | Expression::LessOrEqual(left, right) => {
45            // Ordering is the one comparison family with a resolve arm:
46            // `compare_numeric` needs the registry for big-string order. A
47            // literal of a resolve-free scalar type pins it — whichever term
48            // the other side carries, the kernel answers `Ord`/`TypeError`,
49            // never `NeedsResolve`. Without such an operand the historical
50            // `MaybeEncoded` floor applies. The operands' own capabilities
51            // still hold: `STR(?v) < 2` stays `MaybeEncoded` because
52            // producing the left term may resolve.
53            let operands = max_cap(classify(left), classify(right));
54            if is_resolve_free_comparison_literal(left) || is_resolve_free_comparison_literal(right)
55            {
56                operands
57            } else {
58                operands.max(ExprCapability::MaybeEncoded)
59            }
60        }
61        // The numeric kernels (`numeric_add` … `numeric_unary_minus`) return
62        // `Option<EncodedTerm>`: a non-numeric operand is a type error, never
63        // a resolve request. Operand evaluation is the only resolve source.
64        Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => classify(inner),
65        Expression::Add(left, right)
66        | Expression::Subtract(left, right)
67        | Expression::Multiply(left, right)
68        | Expression::Divide(left, right) => max_cap(classify(left), classify(right)),
69        Expression::FunctionCall(
70            Function::IsIri
71            | Function::IsLiteral
72            | Function::IsBlank
73            | Function::IsNumeric
74            | Function::Datatype,
75            args,
76        ) => args
77            .iter()
78            .map(classify)
79            .fold(ExprCapability::AlwaysEncoded, max_cap),
80        // Hashed language tags / long range strings need the registry — or
81        // the query-local cache, when the caller supplies the read ladder
82        // (`MaybeEncoded` still holds: the resolver may miss).
83        Expression::FunctionCall(Function::Lang | Function::LangMatches, args) => args
84            .iter()
85            .map(classify)
86            .fold(ExprCapability::AlwaysEncoded, max_cap)
87            .max(ExprCapability::MaybeEncoded),
88        Expression::Coalesce(args) => args
89            .iter()
90            .map(classify)
91            .fold(ExprCapability::AlwaysEncoded, max_cap),
92        Expression::FunctionCall(Function::Now, args) => args
93            .iter()
94            .map(classify)
95            .fold(ExprCapability::AlwaysEncoded, max_cap),
96        // Native numerics and calendar EncodedTerms need no registry. Nested
97        // AlwaysResolve / MaybeEncoded children still raise the whole call
98        // (`ABS(STR(?x))` is residual). Wrong arity is an eval type error,
99        // not Unsupported.
100        Expression::FunctionCall(
101            Function::Abs
102            | Function::Ceil
103            | Function::Floor
104            | Function::Round
105            | Function::Year
106            | Function::Month
107            | Function::Day
108            | Function::Hours
109            | Function::Minutes
110            | Function::Seconds
111            | Function::Timezone
112            | Function::Tz,
113            args,
114        ) => args
115            .iter()
116            .map(classify)
117            .fold(ExprCapability::AlwaysEncoded, max_cap),
118        Expression::FunctionCall(Function::BNode, args) if args.is_empty() => {
119            ExprCapability::AlwaysEncoded
120        }
121        Expression::FunctionCall(
122            Function::Str
123            | Function::Iri
124            | Function::BNode
125            | Function::StrLen
126            | Function::StrLang
127            | Function::StrDt,
128            args,
129        ) => args
130            .iter()
131            .map(classify)
132            .fold(ExprCapability::AlwaysEncoded, max_cap)
133            .max(ExprCapability::MaybeEncoded),
134        // `CONCAT()` with no arguments is `""` (encoded empty small string).
135        Expression::FunctionCall(Function::Concat, args) if args.is_empty() => {
136            ExprCapability::AlwaysEncoded
137        }
138        Expression::FunctionCall(
139            Function::Concat
140            | Function::SubStr
141            | Function::Replace
142            | Function::UCase
143            | Function::LCase
144            | Function::EncodeForUri
145            | Function::Md5
146            | Function::Sha1
147            | Function::Sha256
148            | Function::Sha384
149            | Function::Sha512
150            | Function::Contains
151            | Function::StrStarts
152            | Function::StrEnds
153            | Function::StrBefore
154            | Function::StrAfter
155            | Function::Regex,
156            args,
157        ) => args
158            .iter()
159            .map(classify)
160            .fold(ExprCapability::AlwaysResolve, max_cap)
161            .max(ExprCapability::AlwaysResolve),
162        Expression::Exists(_) => ExprCapability::Unsupported,
163        // IF is lazy: only the selected branch is evaluated. The max over all
164        // three children is the honest requirement — the condition always runs,
165        // and either branch may be the selected one.
166        Expression::If(condition, then_branch, else_branch) => max_cap(
167            max_cap(classify(condition), classify(then_branch)),
168            classify(else_branch),
169        ),
170        // IN folds the `=` operator, which is total over encoded terms (see
171        // the `Equal` arm): no comparison-level resolve floor. An
172        // AlwaysResolve child (e.g. `STR(?x) IN (...)`) still escalates the
173        // whole expression to residual through the fold.
174        Expression::In(left, args) => args.iter().map(classify).fold(classify(left), max_cap),
175        Expression::FunctionCall(Function::Custom(iri), args) => {
176            match process_registry().get(iri) {
177                Some(function) => {
178                    let mut cap = function.capability();
179                    for arg in args {
180                        cap = cap.max(classify(arg));
181                    }
182                    cap
183                }
184                None => ExprCapability::Unsupported,
185            }
186        }
187        Expression::FunctionCall(_, _) => ExprCapability::Unsupported,
188    }
189}
190
191/// Whether an operand is a literal whose encoded form can never force a
192/// registry resolve in a comparison kernel.
193///
194/// [`compare_numeric`](crate::expr::compare_numeric) returns
195/// [`CmpResult::NeedsResolve`](crate::expr::CmpResult) only from its string
196/// arms: a `BigStringLiteral` against a different big string, or a
197/// small/big string pair whose contents differ. Every numeric and temporal
198/// arm is total — it yields `Ord` or `TypeError`, never `NeedsResolve`. The
199/// equality kernel has the same split. A literal of one of the datatypes
200/// below is inline-encoded and lands in one of those total arms, so
201/// whichever term the other operand carries, the comparison stays
202/// `Ord`/`TypeError`/encoded-equality and never needs the registry.
203///
204/// String literals are deliberately absent: a plain string literal compared
205/// against a big-string term can reach the small-vs-big `NeedsResolve` arm.
206/// Language-tagged literals are absent too — they are not inline scalars.
207///
208/// This list is a proof, not a heuristic. Extend it only with a datatype
209/// whose encoded variant has a total comparison arm, and revisit it if
210/// `compare_numeric` / the equality kernel gains an arm that can return
211/// `NeedsResolve`.
212fn is_resolve_free_comparison_literal(expression: &Expression) -> bool {
213    let Expression::Literal(literal) = expression else {
214        return false;
215    };
216    if literal.language().is_some() {
217        return false;
218    }
219    let datatype = literal.datatype();
220    datatype == xsd::INTEGER
221        || datatype == xsd::NON_POSITIVE_INTEGER
222        || datatype == xsd::NEGATIVE_INTEGER
223        || datatype == xsd::LONG
224        || datatype == xsd::INT
225        || datatype == xsd::SHORT
226        || datatype == xsd::BYTE
227        || datatype == xsd::NON_NEGATIVE_INTEGER
228        || datatype == xsd::UNSIGNED_LONG
229        || datatype == xsd::UNSIGNED_INT
230        || datatype == xsd::UNSIGNED_SHORT
231        || datatype == xsd::UNSIGNED_BYTE
232        || datatype == xsd::POSITIVE_INTEGER
233        || datatype == xsd::DECIMAL
234        || datatype == xsd::FLOAT
235        || datatype == xsd::DOUBLE
236        || datatype == xsd::DATE_TIME
237        || datatype == xsd::DATE_TIME_STAMP
238        || datatype == xsd::DATE
239        || datatype == xsd::G_YEAR
240        || datatype == xsd::G_YEAR_MONTH
241}
242
243/// Split a FILTER into early (encoded / maybe) and residual (always-resolve) parts.
244///
245/// Top-level `&&` conjuncts are classified independently. An `||` / `!` tree that
246/// contains any AlwaysResolve conjunct is moved entirely to residual (no partial
247/// OR across stages). Unsupported expressions error here.
248pub fn split_filter(
249    expression: &Expression,
250) -> Result<(Option<Expression>, Option<Expression>), ComputeError> {
251    let conjuncts = flatten_and(expression);
252    if conjuncts.len() == 1 {
253        return match classify(expression) {
254            ExprCapability::AlwaysEncoded | ExprCapability::MaybeEncoded => {
255                Ok((Some(expression.clone()), None))
256            }
257            ExprCapability::AlwaysResolve => Ok((None, Some(expression.clone()))),
258            ExprCapability::Unsupported => Err(ComputeError::UnsupportedSparql(format!(
259                "FILTER expression is not supported: {expression}"
260            ))),
261        };
262    }
263
264    let mut early = Vec::new();
265    let mut residual = Vec::new();
266    for conjunct in conjuncts {
267        match classify(&conjunct) {
268            ExprCapability::AlwaysEncoded | ExprCapability::MaybeEncoded => early.push(conjunct),
269            ExprCapability::AlwaysResolve => residual.push(conjunct),
270            ExprCapability::Unsupported => {
271                return Err(ComputeError::UnsupportedSparql(format!(
272                    "FILTER expression is not supported: {conjunct}"
273                )));
274            }
275        }
276    }
277    Ok((and_fold(early), and_fold(residual)))
278}
279
280/// Variables referenced by `expression` (for selective hash resolve).
281pub fn variables_in_expression(expression: &Expression) -> Vec<waratah_storage::Variable> {
282    let mut out = Vec::new();
283    collect_vars(expression, &mut out);
284    out.sort_by(|a, b| a.as_str().cmp(b.as_str()));
285    out.dedup();
286    out
287}
288
289fn collect_vars(expression: &Expression, out: &mut Vec<waratah_storage::Variable>) {
290    match expression {
291        Expression::Variable(v) | Expression::Bound(v) => out.push(v.clone()),
292        Expression::NamedNode(_) | Expression::Literal(_) => {}
293        Expression::Not(inner) | Expression::UnaryPlus(inner) | Expression::UnaryMinus(inner) => {
294            collect_vars(inner, out)
295        }
296        Expression::And(a, b)
297        | Expression::Or(a, b)
298        | Expression::SameTerm(a, b)
299        | Expression::Equal(a, b)
300        | Expression::Greater(a, b)
301        | Expression::GreaterOrEqual(a, b)
302        | Expression::Less(a, b)
303        | Expression::LessOrEqual(a, b)
304        | Expression::Add(a, b)
305        | Expression::Subtract(a, b)
306        | Expression::Multiply(a, b)
307        | Expression::Divide(a, b) => {
308            collect_vars(a, out);
309            collect_vars(b, out);
310        }
311        Expression::FunctionCall(_, args) => {
312            for arg in args {
313                collect_vars(arg, out);
314            }
315        }
316        Expression::If(a, b, c) => {
317            collect_vars(a, out);
318            collect_vars(b, out);
319            collect_vars(c, out);
320        }
321        Expression::Coalesce(args) => {
322            for arg in args {
323                collect_vars(arg, out);
324            }
325        }
326        Expression::In(inner, args) => {
327            collect_vars(inner, out);
328            for arg in args {
329                collect_vars(arg, out);
330            }
331        }
332        Expression::Exists(_) => {}
333    }
334}
335
336/// Flatten top-level `&&` into conjuncts (cloned).
337pub fn flatten_and(expression: &Expression) -> Vec<Expression> {
338    match expression {
339        Expression::And(left, right) => {
340            let mut out = flatten_and(left);
341            out.extend(flatten_and(right));
342            out
343        }
344        other => vec![other.clone()],
345    }
346}
347
348/// Rebuild `&&` from conjuncts (`None` when `parts` is empty).
349pub fn and_fold(parts: Vec<Expression>) -> Option<Expression> {
350    parts
351        .into_iter()
352        .reduce(|a, b| Expression::And(Box::new(a), Box::new(b)))
353}
354
355fn max_cap(a: ExprCapability, b: ExprCapability) -> ExprCapability {
356    a.max(b)
357}
358
359/// Mint provenance of an expression's encoded-path term construction: what
360/// it takes to resolve the bytes of a term the evaluator mints from this
361/// expression, and therefore what seeding the constant positions of the
362/// expression owe the query-local cache.
363///
364/// ADVISORY ONLY: evaluation and escalation are driven by
365/// [`classify`]/[`ExprCapability`]. Nothing behavioral reads this axis
366/// today — it documents the seeding contract (the plan-carried const seed
367/// lists in `PlanNode::Extend` / `PlanNode::Group` install every
368/// `Wellknown`-or-stronger constant position) and is the substrate the
369/// deferred runtime mint channel (per-row mints like `IRI(?x)` over
370/// small strings, base-resolved `IRI()`) will consume when it lands.
371#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
372pub enum Mints {
373    /// Mints no term that can escape into a result column: variable
374    /// passthrough, boolean results, inline-only shapes (numerics, small
375    /// strings, calendar terms, numerical blank nodes). No seeding
376    /// obligation; internal const mints in boolean operators never escape.
377    Never,
378    /// Every string it can mint is answerable without the cache: the
379    /// mint's hash decodes from the static well-known table. No seeding
380    /// obligation; a redundant seed can never shadow (the table wins over
381    /// the cache at decode).
382    Wellknown,
383    /// Every string it can mint comes from the expression itself — a
384    /// constant position's own text. Seeding obligation: the plan-carried
385    /// seed list for this expression's node must register those strings.
386    /// Runtime-computed strings are [`Mints::Ground`], not `Locally`,
387    /// even though the computed bytes exist once evaluation produced
388    /// them — the distinction is WHERE the text comes from, not when. A
389    /// `Locally`-stamped function can still mint runtime-derived strings
390    /// from row arguments (`IRI(?x)`); those are the deferred runtime
391    /// mint channel's territory, not a seeding obligation.
392    Locally,
393    /// Its mints may need runtime evaluation (row-derived strings,
394    /// hash-only passthrough, blob-backed geometry, custom functions): no
395    /// plan-carried seeding obligation. Whether a given row escalates to
396    /// the ground arm is a cache-content question that `classify` and the
397    /// read ladder answer at run time; when a row does escalate, the
398    /// ground arm seeds its mint via `seed_eval_term_caches`.
399    /// `AlwaysResolve` string functions land here even though their const
400    /// arguments are entry-walk-seeded — the ROW-dependent mints are the
401    /// reason for the stamp.
402    Ground,
403}
404
405/// Mint-provenance classification — see [`Mints`]. Composition is `max`
406/// over children, the same discipline as [`classify`].
407///
408/// Plugin-state caveat: the `Literal` stamp mints through
409/// [`crate::query::caches::mint_const_entries`] (the plugin registry's
410/// encode hook under the hood), so a WKT literal stamps through whichever
411/// encoding the installed plugins give it — the stamp predicts seeding in
412/// the CURRENT plugin state. The unit matrix below asserts only
413/// plugin-independent shapes; plugin-dependent literal stamps are pinned
414/// by the integration gates, which run with the plugins installed.
415pub fn mint_provenance(expression: &Expression) -> Mints {
416    match expression {
417        Expression::Variable(_) | Expression::Bound(_) => Mints::Never,
418        Expression::NamedNode(node) => {
419            if well_known_iri(StrHash::new(node.as_str())).is_some() {
420                Mints::Wellknown
421            } else {
422                Mints::Locally
423            }
424        }
425        Expression::Literal(literal) => {
426            let term = Term::Literal(literal.clone());
427            // Analyze-only: mint + derive the seed entries through the one
428            // entry point, install nothing (this stamps what a decode of
429            // this literal would need, not what this query holds).
430            let (_encoded, (strings, blobs)) = crate::query::caches::mint_const_entries(&term);
431            if strings.is_empty() && blobs.is_empty() {
432                // Inline-encoded (native numerics, small strings): the
433                // term carries its own bytes.
434                Mints::Never
435            } else if strings
436                .iter()
437                .all(|(hash, _)| well_known_iri(*hash).is_some())
438            {
439                Mints::Wellknown
440            } else {
441                Mints::Locally
442            }
443        }
444        // Booleans, inline numerics, and calendar/blank results: nothing
445        // minted here escapes into a result column, whatever the children
446        // do internally.
447        Expression::Not(_)
448        | Expression::UnaryPlus(_)
449        | Expression::UnaryMinus(_)
450        | Expression::And(_, _)
451        | Expression::Or(_, _)
452        | Expression::SameTerm(_, _)
453        | Expression::Equal(_, _)
454        | Expression::Greater(_, _)
455        | Expression::GreaterOrEqual(_, _)
456        | Expression::Less(_, _)
457        | Expression::LessOrEqual(_, _)
458        | Expression::Add(_, _)
459        | Expression::Subtract(_, _)
460        | Expression::Multiply(_, _)
461        | Expression::Divide(_, _)
462        | Expression::In(_, _) => Mints::Never,
463        Expression::FunctionCall(
464            Function::IsIri | Function::IsLiteral | Function::IsBlank | Function::IsNumeric,
465            _,
466        ) => Mints::Never,
467        // DATATYPE(?x) returns the literal's own datatype IRI. For native
468        // datatypes that IRI is table-covered, so Wellknown holds. For an
469        // exotic stored datatype the IRI is a passthrough — its string
470        // rode the stored literal's own entries and is store-backed, never
471        // freshly minted by this expression — so no query-const seeding
472        // obligation arises either way, which is what this axis tracks.
473        Expression::FunctionCall(Function::Datatype, _) => Mints::Wellknown,
474        // Calendar terms and the numerical blank node are inline.
475        Expression::FunctionCall(Function::Now | Function::BNode, _) => Mints::Never,
476        Expression::FunctionCall(
477            Function::Abs
478            | Function::Ceil
479            | Function::Floor
480            | Function::Round
481            | Function::Year
482            | Function::Month
483            | Function::Day
484            | Function::Hours
485            | Function::Minutes
486            | Function::Seconds
487            | Function::Timezone
488            | Function::Tz
489            | Function::StrLen,
490            _,
491        ) => Mints::Never,
492        // Mint string/IRI terms from expression text or inline arguments.
493        Expression::FunctionCall(
494            Function::Str | Function::Iri | Function::StrLang | Function::StrDt,
495            _,
496        ) => Mints::Locally,
497        // Fresh random values. Currently unsupported end-to-end (no eval
498        // arm) — forward-looking stamps so the match stays exhaustive and
499        // the table honest. RAND() is an inline numeric; UUID()/STRUUID()
500        // mint fresh hash-only IRIs whose strings are in hand at mint
501        // time.
502        Expression::FunctionCall(Function::Rand, _) => Mints::Never,
503        Expression::FunctionCall(Function::Uuid | Function::StrUuid, _) => Mints::Locally,
504        // LANG(?x) returns the tag STRING — a term that can escape into a
505        // result column — and the tag may be hash-only passthrough;
506        // conservative until the runtime channel exists.
507        Expression::FunctionCall(Function::Lang, _) => Mints::Ground,
508        // Boolean-result string predicates. classify stamps these
509        // AlwaysResolve — they EVALUATE against runtime strings — but this
510        // axis is mint provenance, not evaluation cost: a boolean result
511        // mints no escapable term, so they are Never and the escalation
512        // requirement stays classify's job.
513        Expression::FunctionCall(
514            Function::Contains
515            | Function::StrStarts
516            | Function::StrEnds
517            | Function::Regex
518            | Function::LangMatches,
519            _,
520        ) => Mints::Never,
521        // Runtime-computed STRING results (concatenations, substrings,
522        // digests, case/encode transforms): the minted term escapes into
523        // result columns and only the ground arm can seed it.
524        Expression::FunctionCall(
525            Function::Concat
526            | Function::SubStr
527            | Function::Replace
528            | Function::UCase
529            | Function::LCase
530            | Function::EncodeForUri
531            | Function::Md5
532            | Function::Sha1
533            | Function::Sha256
534            | Function::Sha384
535            | Function::Sha512
536            | Function::StrBefore
537            | Function::StrAfter,
538            _,
539        ) => Mints::Ground,
540        // Conservative until the registry carries mint provenance for
541        // custom functions.
542        Expression::FunctionCall(Function::Custom(_), _) => Mints::Ground,
543        // Unreachable via Extend/Group (classify rejects EXISTS); stamped
544        // for match exhaustiveness.
545        Expression::Exists(_) => Mints::Ground,
546        // Term-valued passthrough-or-const: the max over children.
547        Expression::If(a, b, c) => mint_provenance(a)
548            .max(mint_provenance(b))
549            .max(mint_provenance(c)),
550        Expression::Coalesce(args) => args
551            .iter()
552            .map(mint_provenance)
553            .max()
554            .unwrap_or(Mints::Never),
555    }
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use spargebra::SparqlParser;
562    use spargebra::algebra::{Function, GraphPattern};
563
564    fn filter_expr(sparql: &str) -> Expression {
565        let q = SparqlParser::new().parse_query(sparql).unwrap();
566        let spargebra::Query::Select { pattern, .. } = q else {
567            panic!("expected SELECT");
568        };
569        match pattern {
570            GraphPattern::Project { inner, .. } => match *inner {
571                GraphPattern::Filter { expr, .. } => expr,
572                GraphPattern::Join { left, right, .. } => {
573                    // FILTER may be wrapped
574                    match (*left, *right) {
575                        (GraphPattern::Filter { expr, .. }, _)
576                        | (_, GraphPattern::Filter { expr, .. }) => expr,
577                        _ => panic!("no filter"),
578                    }
579                }
580                other => panic!("unexpected {other:?}"),
581            },
582            GraphPattern::Filter { expr, .. } => expr,
583            other => panic!("unexpected root {other:?}"),
584        }
585    }
586
587    #[test]
588    fn and_split_bound_and_regex() {
589        let expr = filter_expr(
590            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(BOUND(?v) && REGEX(STR(?v), "a")) }"#,
591        );
592        let (early, residual) = split_filter(&expr).unwrap();
593        assert!(early.is_some());
594        assert!(matches!(
595            classify(early.as_ref().unwrap()),
596            ExprCapability::AlwaysEncoded
597        ));
598        assert!(residual.is_some());
599        assert_eq!(
600            classify(residual.as_ref().unwrap()),
601            ExprCapability::AlwaysResolve
602        );
603    }
604
605    #[test]
606    fn literal_bounded_comparisons_are_encoded() {
607        // A numeric literal pins the comparison: no registry resolve is
608        // reachable through it, so the `MaybeEncoded` floor does not apply.
609        let expr = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v < 2) }"#);
610        assert_eq!(classify(&expr), ExprCapability::AlwaysEncoded);
611        let (early, residual) = split_filter(&expr).unwrap();
612        assert!(early.is_some());
613        assert!(residual.is_none());
614
615        // The motivating shape: a two-sided integer range.
616        let range = filter_expr(
617            r#"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
618            SELECT ?x WHERE { ?x <http://ex/p> ?v .
619                FILTER(?v >= 1967 && ?v <= 1971) }"#,
620        );
621        assert_eq!(classify(&range), ExprCapability::AlwaysEncoded);
622
623        // Value equality is decidable through the same literal kinds.
624        let eq = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = 1967) }"#);
625        assert_eq!(classify(&eq), ExprCapability::AlwaysEncoded);
626    }
627
628    #[test]
629    fn kernel_total_operators_are_encoded() {
630        // `=` is total over encoded terms, including strings and language
631        // tags; only operand evaluation can resolve.
632        let string_eq =
633            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = "abc") }"#);
634        assert_eq!(classify(&string_eq), ExprCapability::AlwaysEncoded);
635        let lang_eq =
636            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = "abc"@en) }"#);
637        assert_eq!(classify(&lang_eq), ExprCapability::AlwaysEncoded);
638        let iri_eq = filter_expr(
639            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = <http://ex/iri>) }"#,
640        );
641        assert_eq!(classify(&iri_eq), ExprCapability::AlwaysEncoded);
642        // Numeric kernels are `Option`-returning: no resolve arm at all.
643        let add = filter_expr(
644            r#"SELECT ?x WHERE { ?x <http://ex/p> ?a . ?x <http://ex/q> ?b .
645                FILTER(?a + ?b > 3) }"#,
646        );
647        assert_eq!(classify(&add), ExprCapability::AlwaysEncoded);
648        // A resolve-needing operand still raises the comparison.
649        let resolved_eq =
650            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v = UCASE(?v)) }"#);
651        assert_eq!(classify(&resolved_eq), ExprCapability::AlwaysResolve);
652    }
653
654    #[test]
655    fn unresolvable_comparison_bounds_keep_maybe_encoded() {
656        // Variable-vs-variable: either side can be a big string.
657        let var_var = filter_expr(
658            r#"SELECT ?x WHERE { ?x <http://ex/p> ?a . ?x <http://ex/q> ?b .
659                FILTER(?a < ?b) }"#,
660        );
661        assert_eq!(classify(&var_var), ExprCapability::MaybeEncoded);
662        // A plain string literal can reach the small-vs-big resolve arm.
663        let string_bound =
664            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v < "abc") }"#);
665        assert_eq!(classify(&string_bound), ExprCapability::MaybeEncoded);
666        // Language-tagged literals are not inline scalars.
667        let lang_bound =
668            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v < "abc"@en) }"#);
669        assert_eq!(classify(&lang_bound), ExprCapability::MaybeEncoded);
670        // A resolve-needing operand raises the whole comparison.
671        let str_operand =
672            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(STR(?v) < 2) }"#);
673        assert_eq!(classify(&str_operand), ExprCapability::MaybeEncoded);
674    }
675
676    #[test]
677    fn is_numeric_and_coalesce_are_encoded() {
678        let numeric =
679            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(isNUMERIC(?v)) }"#);
680        assert_eq!(classify(&numeric), ExprCapability::AlwaysEncoded);
681        let coalesce =
682            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(COALESCE(?v, 1) = 1) }"#);
683        assert_ne!(classify(&coalesce), ExprCapability::Unsupported);
684        let with_div = filter_expr(
685            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(COALESCE(?v / 1, 1) = 1) }"#,
686        );
687        assert_eq!(classify(&with_div), ExprCapability::AlwaysEncoded);
688        let datatype = filter_expr(
689            r#"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
690            SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(DATATYPE(?v) = xsd:integer) }"#,
691        );
692        assert_eq!(classify(&datatype), ExprCapability::AlwaysEncoded);
693        let langmatches = filter_expr(
694            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(LANGMATCHES(LANG(?v), "en")) }"#,
695        );
696        assert_eq!(classify(&langmatches), ExprCapability::MaybeEncoded);
697        let (early, residual) = split_filter(&langmatches).unwrap();
698        assert!(early.is_some());
699        assert!(residual.is_none());
700    }
701
702    #[test]
703    fn xsd_casts_classify_through_the_registry() {
704        // Registered custom functions: capability derived from eval_encoded.
705        let cast_eq = filter_expr(
706            r#"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
707            SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(xsd:integer(?v) = 5) }"#,
708        );
709        assert_eq!(classify(&cast_eq), ExprCapability::MaybeEncoded);
710        let (early, residual) = split_filter(&cast_eq).unwrap();
711        assert!(early.is_some(), "cast conjunct stays on the early path");
712        assert!(residual.is_none());
713
714        let cast_same = filter_expr(
715            r#"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
716            SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(sameTerm(DATATYPE(xsd:string(?v)), xsd:string)) }"#,
717        );
718        assert_eq!(classify(&cast_same), ExprCapability::MaybeEncoded);
719        let (early, residual) = split_filter(&cast_same).unwrap();
720        assert!(early.is_some());
721        assert!(residual.is_none());
722    }
723
724    #[test]
725    fn unknown_custom_functions_stay_unsupported() {
726        let unknown = filter_expr(
727            r#"PREFIX ex: <http://example.org/fns#>
728            SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(ex:explode(?v)) }"#,
729        );
730        assert_eq!(classify(&unknown), ExprCapability::Unsupported);
731        assert!(split_filter(&unknown).is_err());
732    }
733
734    #[test]
735    fn if_classifies_honestly() {
736        // Lazy IF over encoded operands stays on the early path. `1/0` is an
737        // encoded-kernel type error (division by zero), not a resolve.
738        let lazy = filter_expr(
739            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(IF(BOUND(?v), ?v, 1/0)) }"#,
740        );
741        assert_eq!(classify(&lazy), ExprCapability::AlwaysEncoded);
742        let (early, residual) = split_filter(&lazy).unwrap();
743        assert!(early.is_some());
744        assert!(residual.is_none());
745        // An Unsupported branch propagates — the old classifier claimed
746        // AlwaysResolve here and hard-errored at residual eval time instead.
747        let with_exists = filter_expr(
748            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v .
749                FILTER(IF(BOUND(?v), EXISTS { ?x <http://ex/q> ?w }, 1)) }"#,
750        );
751        assert_eq!(classify(&with_exists), ExprCapability::Unsupported);
752        assert!(split_filter(&with_exists).is_err());
753    }
754
755    #[test]
756    fn in_classifies_as_comparison() {
757        // IN folds `=`, which is total over encoded terms: no comparison
758        // floor, even for string entries.
759        let plain =
760            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v IN (1, 2)) }"#);
761        assert_eq!(classify(&plain), ExprCapability::AlwaysEncoded);
762        let (early, residual) = split_filter(&plain).unwrap();
763        assert!(early.is_some());
764        assert!(residual.is_none());
765        let strings =
766            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v IN ("a", "b")) }"#);
767        assert_eq!(classify(&strings), ExprCapability::AlwaysEncoded);
768        // An AlwaysResolve child still escalates the whole IN to residual.
769        let with_ucase = filter_expr(
770            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(?v IN (UCASE(?v), 2)) }"#,
771        );
772        assert_eq!(classify(&with_ucase), ExprCapability::AlwaysResolve);
773        let (early, residual) = split_filter(&with_ucase).unwrap();
774        assert!(early.is_none());
775        assert!(residual.is_some());
776    }
777
778    #[test]
779    fn now_is_always_encoded_str_is_maybe() {
780        let now = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(NOW()) }"#);
781        assert_eq!(classify(&now), ExprCapability::AlwaysEncoded);
782        let strlen =
783            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(STRLEN(?v) > 0) }"#);
784        assert_eq!(classify(&strlen), ExprCapability::MaybeEncoded);
785        let regex =
786            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(REGEX(?v, "a")) }"#);
787        assert_eq!(classify(&regex), ExprCapability::AlwaysResolve);
788    }
789
790    #[test]
791    fn abs_and_year_are_always_encoded_unless_the_arg_resolves() {
792        use waratah_storage::Variable;
793        let abs_call = Expression::FunctionCall(
794            Function::Abs,
795            vec![Expression::Variable(Variable::new("v").unwrap())],
796        );
797        assert_eq!(classify(&abs_call), ExprCapability::AlwaysEncoded);
798        let year_call = Expression::FunctionCall(
799            Function::Year,
800            vec![Expression::Variable(Variable::new("d").unwrap())],
801        );
802        assert_eq!(classify(&year_call), ExprCapability::AlwaysEncoded);
803        // A literal bound pins the comparison, so the call's own encoded
804        // capability is the whole answer; the call itself is still early-path.
805        let abs = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(ABS(?v) > 0) }"#);
806        assert_eq!(classify(&abs), ExprCapability::AlwaysEncoded);
807        let year =
808            filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?d . FILTER(YEAR(?d) = 2010) }"#);
809        assert_eq!(classify(&year), ExprCapability::AlwaysEncoded);
810        let (early, residual) = split_filter(&abs).unwrap();
811        assert!(early.is_some());
812        assert!(residual.is_none());
813        let abs_ucase = filter_expr(
814            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(ABS(STRLEN(UCASE(?v))) > 0) }"#,
815        );
816        assert_eq!(classify(&abs_ucase), ExprCapability::AlwaysResolve);
817        let (early, residual) = split_filter(&abs_ucase).unwrap();
818        assert!(early.is_none());
819        assert!(residual.is_some());
820    }
821
822    #[test]
823    fn empty_concat_is_always_encoded() {
824        let empty = Expression::FunctionCall(Function::Concat, Vec::new());
825        assert_eq!(classify(&empty), ExprCapability::AlwaysEncoded);
826        let nonempty = filter_expr(
827            r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(CONCAT(?v, "a") = "xa") }"#,
828        );
829        assert_eq!(classify(&nonempty), ExprCapability::AlwaysResolve);
830    }
831
832    #[test]
833    fn hash_functions_are_always_resolve() {
834        let expr = filter_expr(r#"SELECT ?x WHERE { ?x <http://ex/p> ?v . FILTER(MD5(?v)) }"#);
835        assert_eq!(classify(&expr), ExprCapability::AlwaysResolve);
836        let (early, residual) = split_filter(&expr).unwrap();
837        assert!(early.is_none());
838        assert!(residual.is_some());
839    }
840
841    /// Mint-provenance matrix — plugin-independent rows only. The
842    /// `Literal` stamps that depend on the installed plugins (WKT
843    /// literals and other plugin-owned datatypes) are pinned by the
844    /// integration gates, which run with the plugins installed; asserting
845    /// them here would latch the no-plugin encoding of the shared test
846    /// binary into the contract.
847    #[test]
848    fn mint_provenance_stamps() {
849        use waratah_storage::{Literal as RdfLiteral, NamedNode as RdfNamedNode, Variable};
850        let var = |name: &str| Expression::Variable(Variable::new(name).unwrap());
851        let node = |iri: &str| Expression::NamedNode(RdfNamedNode::new(iri).unwrap());
852        let lit = |value: &str| Expression::Literal(RdfLiteral::new_simple_literal(value));
853
854        // Passthrough and booleans never mint escapable terms; children
855        // are not even consulted.
856        assert_eq!(mint_provenance(&var("x")), Mints::Never);
857        assert_eq!(
858            mint_provenance(&Expression::Equal(
859                Box::new(var("a")),
860                Box::new(node("urn:ex:a"))
861            )),
862            Mints::Never
863        );
864        assert_eq!(
865            mint_provenance(&Expression::In(
866                Box::new(var("a")),
867                vec![node("urn:ex:a"), lit("big-value-in-a-list")]
868            )),
869            Mints::Never
870        );
871
872        // Value-dependent NamedNode stamps: the well-known table answers
873        // rdf:type, nothing answers a fresh IRI.
874        assert_eq!(
875            mint_provenance(&node("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")),
876            Mints::Wellknown
877        );
878        assert_eq!(mint_provenance(&node("urn:ex:a")), Mints::Locally);
879
880        // Inline-encoded literals carry their own bytes; a hash-only
881        // literal needs the seed list.
882        assert_eq!(mint_provenance(&lit("1")), Mints::Never);
883        assert_eq!(mint_provenance(&lit("abc")), Mints::Never);
884        assert_eq!(
885            mint_provenance(&lit("a long lexical form with many characters")),
886            Mints::Locally
887        );
888
889        // Composition is max over children.
890        assert_eq!(
891            mint_provenance(&Expression::Coalesce(vec![
892                var("missing"),
893                node("urn:ex:a")
894            ])),
895            Mints::Locally
896        );
897        assert_eq!(
898            mint_provenance(&Expression::If(
899                Box::new(var("flag")),
900                Box::new(node("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")),
901                Box::new(var("x"))
902            )),
903            Mints::Wellknown
904        );
905
906        // Row-dependent and conservative sites.
907        assert_eq!(
908            mint_provenance(&Expression::FunctionCall(Function::Str, vec![var("x")])),
909            Mints::Locally
910        );
911        assert_eq!(
912            mint_provenance(&Expression::FunctionCall(Function::Lang, vec![var("x")])),
913            Mints::Ground
914        );
915        // Boolean-result string predicates are Never (mint provenance),
916        // even though classify stamps them AlwaysResolve (evaluation cost)
917        // — the two axes answer different questions.
918        assert_eq!(
919            mint_provenance(&Expression::FunctionCall(
920                Function::Regex,
921                vec![var("x"), lit("a")]
922            )),
923            Mints::Never
924        );
925        assert_eq!(
926            mint_provenance(&Expression::FunctionCall(
927                Function::StrStarts,
928                vec![var("x"), lit("a")]
929            )),
930            Mints::Never
931        );
932        // Runtime-computed STRING results stay Ground.
933        assert_eq!(
934            mint_provenance(&Expression::FunctionCall(
935                Function::StrBefore,
936                vec![var("x"), lit("a")]
937            )),
938            Mints::Ground
939        );
940        // Custom functions stamp Ground without consulting the registry —
941        // the stamp must not depend on install state.
942        assert_eq!(
943            mint_provenance(&Expression::FunctionCall(
944                Function::Custom(RdfNamedNode::new("http://ex/unknown-fn").unwrap()),
945                vec![var("x")]
946            )),
947            Mints::Ground
948        );
949        // Forward-looking stamps (currently unsupported end-to-end).
950        assert_eq!(
951            mint_provenance(&Expression::FunctionCall(Function::Rand, vec![])),
952            Mints::Never
953        );
954        assert_eq!(
955            mint_provenance(&Expression::FunctionCall(Function::Uuid, vec![])),
956            Mints::Locally
957        );
958    }
959}