Skip to main content

mz_expr/
interpret.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11use std::fmt::Debug;
12
13use mz_repr::{Datum, ReprColumnType, ReprRelationType, ReprScalarType, Row, RowArena};
14
15use crate::scalar::func::variadic::And;
16use crate::scalar::optimizable::OptimizableExpr;
17use crate::{
18    BinaryFunc, Eval, EvalError, MapFilterProject, MfpPlan, MirScalarExpr, UnaryFunc,
19    UnmaterializableFunc, VariadicFunc, func,
20};
21/// Whether a datum is a floating-point or numeric `NaN`.
22///
23/// `NaN` sorts as the maximum of the numeric/float [Datum] ordering, but it is
24/// a fixed point of most functions we treat as monotone (e.g. negation maps
25/// `NaN` to `NaN` while flipping the sign of every other value). A range whose
26/// bounds include `NaN` therefore breaks the monotonicity assumption that
27/// [ResultSpec::flat_map] relies on, so the range-narrowing shortcut must be
28/// skipped in that case.
29fn datum_is_nan(datum: Datum) -> bool {
30    match datum {
31        Datum::Float32(f) => f.is_nan(),
32        Datum::Float64(f) => f.is_nan(),
33        Datum::Numeric(n) => n.0.is_nan(),
34        _ => false,
35    }
36}
37
38/// Whether a datum is a floating-point or numeric infinity.
39fn datum_is_infinite(datum: Datum) -> bool {
40    match datum {
41        Datum::Float32(f) => f.is_infinite(),
42        Datum::Float64(f) => f.is_infinite(),
43        Datum::Numeric(n) => n.0.is_infinite(),
44        _ => false,
45    }
46}
47
48/// An inclusive range of non-null datum values.
49#[derive(Clone, Eq, PartialEq, Debug)]
50enum Values<'a> {
51    /// This range contains no values.
52    Empty,
53    /// An inclusive range. Invariant: the first element is always <= the second.
54    // TODO: a variant for small sets of data would avoid losing precision here.
55    Within(Datum<'a>, Datum<'a>),
56    /// Constraints on structured fields, useful for recursive structures like maps.
57    /// Fields that are not present in the map default to Values::All.
58    // TODO: consider using this variant, or similar, for Datum::List.
59    Nested(BTreeMap<Datum<'a>, ResultSpec<'a>>),
60    /// This range might contain any value. Since we're overapproximating, this is often used
61    /// as a "safe fallback" when we can't determine the right boundaries for a range.
62    All,
63}
64
65impl<'a> Values<'a> {
66    fn just(a: Datum<'a>) -> Values<'a> {
67        match a {
68            Datum::Map(datum_map) => Values::Nested(
69                datum_map
70                    .iter()
71                    .map(|(key, val)| (key.into(), ResultSpec::value(val)))
72                    .collect(),
73            ),
74            other => Self::Within(other, other),
75        }
76    }
77
78    fn union(self, other: Values<'a>) -> Values<'a> {
79        match (self, other) {
80            (Values::Empty, r) => r,
81            (r, Values::Empty) => r,
82            (Values::Within(a0, a1), Values::Within(b0, b1)) => {
83                Values::Within(a0.min(b0), a1.max(b1))
84            }
85            (Values::Nested(a), Values::Nested(mut b)) => {
86                // `Nested(map)` treats keys missing from `map` as fully unconstrained, so a
87                // key present in only one side of the union must be treated as `anything`
88                // on the other side. Because `x ∪ anything = anything`, such keys drop
89                // out of the merged map (the Nested default is already "anything").
90                let mut merged = BTreeMap::new();
91                for (key, a_spec) in a {
92                    if let Some(b_spec) = b.remove(&key) {
93                        let unioned = a_spec.union(b_spec);
94                        if unioned != ResultSpec::anything() {
95                            merged.insert(key, unioned);
96                        }
97                    }
98                }
99                if merged.is_empty() {
100                    Values::All
101                } else {
102                    Values::Nested(merged)
103                }
104            }
105            _ => Values::All,
106        }
107    }
108
109    fn intersect(self, other: Values<'a>) -> Values<'a> {
110        match (self, other) {
111            (Values::Empty, _) => Values::Empty,
112            (_, Values::Empty) => Values::Empty,
113            (Values::Within(a0, a1), Values::Within(b0, b1)) => {
114                let min = a0.max(b0);
115                let max = a1.min(b1);
116                if min <= max {
117                    Values::Within(min, max)
118                } else {
119                    Values::Empty
120                }
121            }
122            (Values::Nested(mut a), Values::Nested(b)) => {
123                for (datum, other_spec) in b {
124                    let spec = a.entry(datum).or_insert_with(ResultSpec::anything);
125                    *spec = spec.clone().intersect(other_spec);
126                }
127                Values::Nested(a)
128            }
129            (Values::All, v) => v,
130            (v, Values::All) => v,
131            // A `Within` range and a `Nested` (map) spec can genuinely overlap:
132            // `Datum` order places `Map` between `List` and `Numeric`, so a
133            // range straddling those tags contains map values. We can't compute
134            // the precise intersection, so return the (more structured) `Nested`
135            // side as a sound over-approximation. Returning `Empty` here would
136            // drop real values and let pushdown wrongly discard a part.
137            (nested @ Values::Nested(_), Values::Within(_, _))
138            | (Values::Within(_, _), nested @ Values::Nested(_)) => nested,
139        }
140    }
141
142    fn may_contain(&self, value: Datum<'a>) -> bool {
143        match self {
144            Values::Empty => false,
145            Values::Within(min, max) => *min <= value && value <= *max,
146            Values::All => true,
147            Values::Nested(field_map) => match value {
148                Datum::Map(datum_map) => {
149                    datum_map
150                        .iter()
151                        .all(|(key, val)| match field_map.get(&key.into()) {
152                            None => true,
153                            Some(nested) => nested.may_contain(val),
154                        })
155                }
156                _ => false,
157            },
158        }
159    }
160
161    /// Returns the sole datum in this value set, if it is known to be a single
162    /// value. Returns `None` otherwise (for empty sets, ranges with distinct
163    /// endpoints, structured constraints, and the unconstrained set).
164    ///
165    /// Prefer this over pattern-matching on [Values::Within] directly when you
166    /// only need the "single known value" case: it's robust against future
167    /// variants of [Values] (e.g. a small-set representation) automatically
168    /// degrading to "not a single value" rather than silently mis-matching.
169    fn as_single(&self) -> Option<Datum<'a>> {
170        match self {
171            Values::Within(a, b) if a == b => Some(*a),
172            _ => None,
173        }
174    }
175}
176
177/// An approximation of the set of values an expression might have, including whether or not it
178/// might be null or an error value. This is generally an _overapproximation_, in the sense that
179/// [ResultSpec::may_contain] may return true even if the argument is not included in the set.
180/// (However, it should never return false when the value _is_ included!)
181#[derive(Debug, Clone, Eq, PartialEq)]
182pub struct ResultSpec<'a> {
183    /// True if the expression may evaluate to [Datum::Null].
184    nullable: bool,
185    /// True if the expression may evaluate to an error.
186    fallible: bool,
187    /// The range of possible (non-null) values that the expression may evaluate to.
188    values: Values<'a>,
189}
190
191impl<'a> ResultSpec<'a> {
192    /// No results match this spec. (For example, an empty table.)
193    pub fn nothing() -> Self {
194        ResultSpec {
195            nullable: false,
196            fallible: false,
197            values: Values::Empty,
198        }
199    }
200
201    /// Every result matches this spec.
202    pub fn anything() -> Self {
203        ResultSpec {
204            nullable: true,
205            fallible: true,
206            values: Values::All,
207        }
208    }
209
210    /// Every result matches this spec.
211    pub fn any_infallible() -> Self {
212        ResultSpec {
213            nullable: true,
214            fallible: false,
215            values: Values::All,
216        }
217    }
218
219    /// A spec that only matches null.
220    pub fn null() -> Self {
221        ResultSpec {
222            nullable: true,
223            ..Self::nothing()
224        }
225    }
226
227    /// A spec that only matches error values.
228    pub fn fails() -> Self {
229        ResultSpec {
230            fallible: true,
231            ..Self::nothing()
232        }
233    }
234
235    /// A spec that matches all values of a given type.
236    pub fn has_type(col: &ReprColumnType, fallible: bool) -> ResultSpec<'a> {
237        let values = match &col.scalar_type {
238            ReprScalarType::Bool => Values::Within(Datum::False, Datum::True),
239            // TODO: add bounds for other bounded types, like integers
240            _ => Values::All,
241        };
242        ResultSpec {
243            nullable: col.nullable,
244            fallible,
245            values,
246        }
247    }
248
249    /// A spec that only matches the given value.
250    pub fn value(value: Datum<'a>) -> ResultSpec<'a> {
251        match value {
252            Datum::Null => Self::null(),
253            nonnull => ResultSpec {
254                values: Values::just(nonnull),
255                ..Self::nothing()
256            },
257        }
258    }
259
260    /// A spec for the values between `min` and `max` inclusive.
261    ///
262    /// Unordered bounds widen to [`ResultSpec::value_all`] instead of collapsing
263    /// to [`ResultSpec::nothing`]: they mean the bounds are unusable, not that
264    /// the column holds nothing. Persist float stats produce them, because arrow
265    /// orders floats totally, putting `-NaN` below `-Infinity`, while the
266    /// [`Datum`] order compared here ranks every NaN above every finite value.
267    /// Collapsing lost every other row in such a part (PER-53).
268    pub fn value_between(min: Datum<'a>, max: Datum<'a>) -> ResultSpec<'a> {
269        assert!(!min.is_null());
270        assert!(!max.is_null());
271        if min <= max {
272            ResultSpec {
273                values: Values::Within(min, max),
274                ..ResultSpec::nothing()
275            }
276        } else {
277            ResultSpec::value_all()
278        }
279    }
280
281    /// A spec that matches any non-null value.
282    pub fn value_all() -> ResultSpec<'a> {
283        ResultSpec {
284            values: Values::All,
285            ..ResultSpec::nothing()
286        }
287    }
288
289    /// A spec that matches Datum::Maps of the given type.
290    pub fn map_spec(map: BTreeMap<Datum<'a>, ResultSpec<'a>>) -> ResultSpec<'a> {
291        ResultSpec {
292            values: Values::Nested(map),
293            ..ResultSpec::nothing()
294        }
295    }
296
297    /// Given two specs, returns a new spec that matches anything that either original spec would match.
298    pub fn union(self, other: ResultSpec<'a>) -> ResultSpec<'a> {
299        ResultSpec {
300            nullable: self.nullable || other.nullable,
301            fallible: self.fallible || other.fallible,
302            values: self.values.union(other.values),
303        }
304    }
305
306    /// Given two specs, returns a new spec that only matches things that both original specs would match.
307    pub fn intersect(self, other: ResultSpec<'a>) -> ResultSpec<'a> {
308        ResultSpec {
309            nullable: self.nullable && other.nullable,
310            fallible: self.fallible && other.fallible,
311            values: self.values.intersect(other.values),
312        }
313    }
314
315    /// Check if a particular value matches the spec.
316    pub fn may_contain(&self, value: Datum<'a>) -> bool {
317        if value == Datum::Null {
318            return self.nullable;
319        }
320
321        self.values.may_contain(value)
322    }
323
324    /// Check if an error value matches the spec.
325    pub fn may_fail(&self) -> bool {
326        self.fallible
327    }
328
329    /// Whether this spec is pinned to a single concrete (non-null) value.
330    ///
331    /// When it is, evaluating a function on the input is exact rather than an
332    /// endpoint-sampled approximation of a range, so the interpreter can trust
333    /// the sampled fallibility. When it isn't, endpoint sampling cannot prove a
334    /// `could_error` function infallible over the range (see the fallibility
335    /// handling in [`ColumnSpecs::unary`] and friends).
336    fn is_single_value(&self) -> bool {
337        self.values.as_single().is_some()
338    }
339
340    /// Whether the value range might include a floating-point or numeric
341    /// infinity. Infinities sort at the extremes of the order, so a `Within`
342    /// range includes one only as an endpoint.
343    fn may_be_infinite(&self) -> bool {
344        match &self.values {
345            Values::Within(min, max) => datum_is_infinite(*min) || datum_is_infinite(*max),
346            Values::All => true,
347            Values::Empty | Values::Nested(_) => false,
348        }
349    }
350
351    /// This method "maps" a function across the `ResultSpec`.
352    ///
353    /// As mentioned above, `ResultSpec` represents an approximate set of results.
354    /// If we actually stored each result in the set, `flat_map` could be implemented by passing
355    /// each result to the function one-by-one and unioning the resulting sets. This is possible
356    /// when our values set is empty or contains a single datum, but when it contains a range,
357    /// we can't enumerate all possible values of the set. We handle this by:
358    /// - tracking whether the function is monotone, in which case we can map the range by just
359    ///   mapping the endpoints;
360    /// - using a safe default when we can't infer a tighter bound on the set, eg. [Self::anything].
361    fn flat_map(
362        &self,
363        is_monotone: bool,
364        mut result_map: impl FnMut(Result<Datum<'a>, EvalError>) -> ResultSpec<'a>,
365    ) -> ResultSpec<'a> {
366        let null_spec = if self.nullable {
367            result_map(Ok(Datum::Null))
368        } else {
369            ResultSpec::nothing()
370        };
371
372        let error_spec = if self.fallible {
373            // Since we only care about whether / not an error is possible, and not the specific
374            // error, create an arbitrary error here.
375            // NOTE! This assumes that functions do not discriminate on the type of the error.
376            let map_err = result_map(Err(EvalError::Internal("".into())));
377            let raise_err = ResultSpec::fails();
378            // SQL has a very loose notion of evaluation order: https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-EXPRESS-EVAL
379            // Here, we account for the possibility that the expression is evaluated strictly,
380            // raising the error, or that it's evaluated lazily by the result_map function
381            // (which may return a non-error result even when given an error as input).
382            raise_err.union(map_err)
383        } else {
384            ResultSpec::nothing()
385        };
386
387        let values_spec = match self.values {
388            Values::Empty => ResultSpec::nothing(),
389            // If this range contains a single datum, just call the function.
390            Values::Within(min, max) if min == max => result_map(Ok(min)),
391            // If this is a range of booleans, we know all the values... just try them.
392            Values::Within(Datum::False, Datum::True) => {
393                result_map(Ok(Datum::False)).union(result_map(Ok(Datum::True)))
394            }
395            // Otherwise, if our function is monotonic, we can try mapping the input
396            // range to an output range. A range whose bounds include `NaN` is
397            // excluded: `NaN` is ordered as the maximum but is a fixed point of
398            // most monotone functions, so evaluating the endpoints does not
399            // bound the interior. Such ranges fall through to the
400            // overapproximation below.
401            Values::Within(min, max) if is_monotone && !datum_is_nan(min) && !datum_is_nan(max) => {
402                let min_result = result_map(Ok(min));
403                let max_result = result_map(Ok(max));
404                // Value, null, and error are orthogonal channels. Monotonicity
405                // lets us bound the *values* by the endpoints, but only when both
406                // endpoints actually produced a value; null and error can't be
407                // bounded from value endpoints, so we just union whatever the
408                // endpoints reported on those channels. (A function that errors
409                // on an interior value while the endpoints don't is handled by
410                // the fallibility guard in `unary`/`binary`/`variadic`, not
411                // here.)
412                match (min_result, max_result) {
413                    // Both endpoints produced a value: bound the interior values
414                    // by their union, and carry any null/error from the endpoints.
415                    (
416                        ResultSpec {
417                            nullable: n1,
418                            fallible: f1,
419                            values: a_values @ Values::Within(..),
420                        },
421                        ResultSpec {
422                            nullable: n2,
423                            fallible: f2,
424                            values: b_values @ Values::Within(..),
425                        },
426                    ) => ResultSpec {
427                        nullable: n1 || n2,
428                        fallible: f1 || f2,
429                        values: a_values.union(b_values),
430                    },
431                    // If both endpoints map purely to null, assume the whole
432                    // range maps to null. (Both endpoints *erroring* is NOT
433                    // enough: an interior input can still produce a value, e.g.
434                    // a cast that rejects both bounds but accepts a value
435                    // between them.)
436                    (
437                        ResultSpec {
438                            nullable: true,
439                            fallible: false,
440                            values: Values::Empty,
441                        },
442                        ResultSpec {
443                            nullable: true,
444                            fallible: false,
445                            values: Values::Empty,
446                        },
447                    ) => ResultSpec::null(),
448                    // Otherwise we can't bound the interior values.
449                    _ => ResultSpec::anything(),
450                }
451            }
452            // TODO: we could return a narrower result for eg. `Values::Nested` with all-`Within` fields.
453            Values::Within(_, _) | Values::Nested(_) | Values::All => ResultSpec::anything(),
454        };
455
456        null_spec.union(error_spec).union(values_spec)
457    }
458}
459
460/// [Abstract interpretation](https://en.wikipedia.org/wiki/Abstract_interpretation) for
461/// [MirScalarExpr].
462///
463/// [MirScalarExpr::eval] implements a "concrete interpreter" for the expression type: given an
464/// expression and specific column values as input, it returns a specific value for the output.
465/// This could be reimplemented using this trait... but it's most useful for "abstract"
466/// interpretations of the expression, where we generalize about sets of possible inputs and outputs.
467/// See [Trace] and [ColumnSpecs] for how this can be useful in practice.
468pub trait Interpreter {
469    type Summary: Clone + Debug + Sized;
470
471    /// A column of the input row.
472    fn column(&self, id: usize) -> Self::Summary;
473
474    /// A literal value.
475    /// (Stored as a row, because we can't own a Datum.)
476    fn literal(&self, result: &Result<Row, EvalError>, col_type: &ReprColumnType) -> Self::Summary;
477    /// A call to an unmaterializable function.
478    ///
479    /// These functions cannot be evaluated by `MirScalarExpr::eval`. They must
480    /// be transformed away by a higher layer.
481    fn unmaterializable(&self, func: &UnmaterializableFunc) -> Self::Summary;
482
483    /// A function call that takes one expression as an argument.
484    fn unary(&self, func: &UnaryFunc, expr: Self::Summary) -> Self::Summary;
485
486    /// A function call that takes two expressions as arguments.
487    fn binary(&self, func: &BinaryFunc, left: Self::Summary, right: Self::Summary)
488    -> Self::Summary;
489
490    /// A function call that takes an arbitrary number of arguments.
491    fn variadic(&self, func: &VariadicFunc, exprs: Vec<Self::Summary>) -> Self::Summary;
492
493    /// Conditionally evaluated expressions.
494    fn cond(&self, cond: Self::Summary, then: Self::Summary, els: Self::Summary) -> Self::Summary;
495
496    /// Evaluate an entire expression, by delegating to the fine-grained methods on [Interpreter].
497    fn expr<X: Interpretable>(&self, expr: &X) -> Self::Summary {
498        expr.interpret(self)
499    }
500
501    /// Specifically, this evaluates the map and filters stages of an MFP: summarize each of the
502    /// map expressions, then `and` together all of the filters.
503    fn mfp_filter<X: Interpretable + OptimizableExpr>(
504        &self,
505        mfp: &MapFilterProject<X>,
506    ) -> Self::Summary {
507        let mfp_eval = MfpEval::new(self, mfp.input_arity, &mfp.expressions);
508        // NB: self should not be used after this point!
509        let predicates = mfp
510            .predicates
511            .iter()
512            .map(|(_, e)| mfp_eval.expr(e))
513            .collect();
514        mfp_eval.variadic(&And.into(), predicates)
515    }
516
517    /// Similar to [Self::mfp_filter], but includes the additional temporal filters that have been
518    /// broken out.
519    fn mfp_plan_filter<X: Interpretable + OptimizableExpr>(
520        &self,
521        plan: &MfpPlan<X>,
522    ) -> Self::Summary {
523        let mfp_eval = MfpEval::new(self, plan.mfp.input_arity, &plan.mfp.expressions);
524        // NB: self should not be used after this point!
525        let mut results: Vec<_> = plan
526            .mfp
527            .predicates
528            .iter()
529            .map(|(_, e)| mfp_eval.expr(e))
530            .collect();
531        let mz_now = mfp_eval.unmaterializable(&UnmaterializableFunc::MzNow);
532        for bound in &plan.lower_bounds {
533            let bound_range = mfp_eval.expr(bound);
534            let result = mfp_eval.binary(&BinaryFunc::Lte(func::Lte), bound_range, mz_now.clone());
535            results.push(result);
536        }
537        for bound in &plan.upper_bounds {
538            let bound_range = mfp_eval.expr(bound);
539            let result = mfp_eval.binary(&BinaryFunc::Gte(func::Gte), bound_range, mz_now.clone());
540            results.push(result);
541        }
542        self.variadic(&And.into(), results)
543    }
544}
545
546/// A scalar expression an [Interpreter] can summarize.
547///
548/// Implemented by `MirScalarExpr`, and by the LIR scalar expression in
549/// `mz_compute_types`, so the interpreter runs over a plan in either form.
550pub trait Interpretable {
551    /// Summarize `self` by delegating each node to `interpreter`.
552    fn interpret<I: Interpreter + ?Sized>(&self, interpreter: &I) -> I::Summary;
553}
554
555impl Interpretable for MirScalarExpr {
556    fn interpret<I: Interpreter + ?Sized>(&self, interpreter: &I) -> I::Summary {
557        match self {
558            MirScalarExpr::Column(id, _name) => interpreter.column(*id),
559            MirScalarExpr::Literal(value, col_type) => interpreter.literal(value, col_type),
560            MirScalarExpr::CallUnmaterializable(func) => interpreter.unmaterializable(func),
561            MirScalarExpr::CallUnary { func, expr } => {
562                let expr_range = expr.interpret(interpreter);
563                interpreter.unary(func, expr_range)
564            }
565            MirScalarExpr::CallBinary { func, expr1, expr2 } => {
566                let expr1_range = expr1.interpret(interpreter);
567                let expr2_range = expr2.interpret(interpreter);
568                interpreter.binary(func, expr1_range, expr2_range)
569            }
570            MirScalarExpr::CallVariadic { func, exprs } => {
571                let exprs: Vec<_> = exprs.iter().map(|e| e.interpret(interpreter)).collect();
572                interpreter.variadic(func, exprs)
573            }
574            MirScalarExpr::If { cond, then, els } => {
575                let cond_range = cond.interpret(interpreter);
576                let then_range = then.interpret(interpreter);
577                let els_range = els.interpret(interpreter);
578                interpreter.cond(cond_range, then_range, els_range)
579            }
580        }
581    }
582}
583
584/// Wrap another interpreter, but tack a few extra columns on at the end. An internal implementation
585/// detail of `eval_mfp` and `eval_mfp_plan`.
586pub(crate) struct MfpEval<'a, E: Interpreter + ?Sized> {
587    evaluator: &'a E,
588    input_arity: usize,
589    expressions: Vec<E::Summary>,
590}
591
592impl<'a, E: Interpreter + ?Sized> MfpEval<'a, E> {
593    pub(crate) fn new<X: Interpretable>(
594        evaluator: &'a E,
595        input_arity: usize,
596        expressions: &[X],
597    ) -> Self {
598        let mut mfp_eval = MfpEval {
599            evaluator,
600            input_arity,
601            expressions: vec![],
602        };
603        for expr in expressions {
604            let result = mfp_eval.expr(expr);
605            mfp_eval.expressions.push(result);
606        }
607        mfp_eval
608    }
609}
610
611impl<'a, E: Interpreter + ?Sized> Interpreter for MfpEval<'a, E> {
612    type Summary = E::Summary;
613
614    fn column(&self, id: usize) -> Self::Summary {
615        if id < self.input_arity {
616            self.evaluator.column(id)
617        } else {
618            self.expressions[id - self.input_arity].clone()
619        }
620    }
621
622    fn literal(&self, result: &Result<Row, EvalError>, col_type: &ReprColumnType) -> Self::Summary {
623        self.evaluator.literal(result, col_type)
624    }
625
626    fn unmaterializable(&self, func: &UnmaterializableFunc) -> Self::Summary {
627        self.evaluator.unmaterializable(func)
628    }
629
630    fn unary(&self, func: &UnaryFunc, expr: Self::Summary) -> Self::Summary {
631        self.evaluator.unary(func, expr)
632    }
633
634    fn binary(
635        &self,
636        func: &BinaryFunc,
637        left: Self::Summary,
638        right: Self::Summary,
639    ) -> Self::Summary {
640        self.evaluator.binary(func, left, right)
641    }
642
643    fn variadic(&self, func: &VariadicFunc, exprs: Vec<Self::Summary>) -> Self::Summary {
644        self.evaluator.variadic(func, exprs)
645    }
646
647    fn cond(&self, cond: Self::Summary, then: Self::Summary, els: Self::Summary) -> Self::Summary {
648        self.evaluator.cond(cond, then, els)
649    }
650}
651
652/// A unary function we've added special-case handling for; including:
653/// - A three-argument function, taking and returning [ResultSpec]s. This
654///   overrides the default function-handling logic entirely.
655/// - Metadata on whether / not this function is pushdownable. See [Trace].
656struct SpecialUnary {
657    map_fn: for<'a, 'b> fn(&'b ColumnSpecs<'a>, ResultSpec<'a>) -> ResultSpec<'a>,
658    pushdownable: bool,
659}
660
661impl SpecialUnary {
662    /// Returns the special-case handling for a particular function, if it exists.
663    fn for_func(func: &UnaryFunc) -> Option<SpecialUnary> {
664        /// Eager in the same sense as `func.rs` uses the term; this assumes that
665        /// nulls and errors propagate up, and we only need to define the behaviour
666        /// on values.
667        fn eagerly<'b>(
668            spec: ResultSpec<'b>,
669            value_fn: impl FnOnce(Values<'b>) -> ResultSpec<'b>,
670        ) -> ResultSpec<'b> {
671            let result = match spec.values {
672                Values::Empty => ResultSpec::nothing(),
673                other => value_fn(other),
674            };
675            ResultSpec {
676                fallible: spec.fallible || result.fallible,
677                nullable: spec.nullable || result.nullable,
678                values: result.values,
679            }
680        }
681        match func {
682            UnaryFunc::TryParseMonotonicIso8601Timestamp(_) => Some(SpecialUnary {
683                map_fn: |specs, range| {
684                    let expr = MirScalarExpr::CallUnary {
685                        func: UnaryFunc::TryParseMonotonicIso8601Timestamp(
686                            crate::func::TryParseMonotonicIso8601Timestamp,
687                        ),
688                        expr: Box::new(MirScalarExpr::column(0)),
689                    };
690                    let eval = |d| specs.eval_result(expr.eval(&[d], specs.arena));
691
692                    eagerly(range, |values| {
693                        match values {
694                            Values::Within(a, b) if a == b => eval(a),
695                            Values::Within(a, b) => {
696                                let spec = eval(a).union(eval(b));
697                                let values_spec = if spec.nullable {
698                                    // At least one of the endpoints of the range wasn't a valid
699                                    // timestamp. We can't compute a precise range in this case.
700                                    // If we used the general is_monotone handling, that code would
701                                    // incorrectly assume the whole range mapped to null if each
702                                    // endpoint did.
703                                    ResultSpec::value_all()
704                                } else {
705                                    spec
706                                };
707                                // A range of strings will always contain strings that don't parse
708                                // as timestamps - so unlike the general case, we'll assume null
709                                // is present in every range of output values.
710                                values_spec.union(ResultSpec::null())
711                            }
712                            // Otherwise, assume the worst: this function may return either a valid
713                            // value or null.
714                            _ => ResultSpec::any_infallible(),
715                        }
716                    })
717                },
718                pushdownable: true,
719            }),
720            _ => None,
721        }
722    }
723}
724
725/// The abstract-domain counterpart of a [BinaryFunc]: a binary function
726/// we've added special-case handling for; including:
727/// - Either a complete override of [ResultSpec] computation, or a way to
728///   compute monotonicity dynamically from the input specs.
729/// - Metadata on whether / not this function is pushdownable. See [Trace].
730///
731/// Note: today a function can have *either* a handler override *or* a
732/// dynamic-monotonicity verdict, but not both. If a future function wants
733/// both, promote [AbstractFuncHandler] from an enum to a struct with two
734/// optional fields.
735struct AbstractFunc {
736    handler: AbstractFuncHandler,
737    /// `(left, right)`: per-argument pushdownability hint consumed by
738    /// [Trace]. `true` for an argument means the function preserves enough
739    /// structure that, with sufficient information about that argument's
740    /// range, the output spec can be predicted — i.e. the predicate is a
741    /// pushdown candidate when that argument is constant or a tight range.
742    pushdownable: (bool, bool),
743}
744
745/// How an [AbstractFunc] computes the output [ResultSpec].
746enum AbstractFuncHandler {
747    /// Completely override the spec computation; the default flat-map machinery
748    /// is bypassed.
749    Override(for<'a> fn(ResultSpec<'a>, ResultSpec<'a>) -> ResultSpec<'a>),
750    /// Use the default flat-map machinery, but with a monotonicity verdict that
751    /// depends on the input specs. This lets us claim monotonicity for cases
752    /// the static `LazyBinaryFunc::is_monotone` annotation can't safely claim:
753    /// for instance, `t + INTERVAL '1' day` is monotone in `t`, but `t + i`
754    /// generally isn't (the calendar-month / day-clamping arithmetic in
755    /// `add_timestamp_interval` is non-monotone when `i.months != 0`).
756    DynamicMonotone(fn(&ResultSpec<'_>, &ResultSpec<'_>) -> (bool, bool)),
757}
758
759impl AbstractFunc {
760    /// Returns the special-case handling for a particular function, if it exists.
761    fn for_func(func: &BinaryFunc) -> Option<AbstractFunc> {
762        /// Eager in the same sense as `func.rs` uses the term; this assumes that
763        /// nulls and errors propagate up, and we only need to define the behaviour
764        /// on values.
765        fn eagerly<'b>(
766            left: ResultSpec<'b>,
767            right: ResultSpec<'b>,
768            value_fn: impl FnOnce(Values<'b>, Values<'b>) -> ResultSpec<'b>,
769        ) -> ResultSpec<'b> {
770            let result = match (left.values, right.values) {
771                (Values::Empty, _) | (_, Values::Empty) => ResultSpec::nothing(),
772                (l, r) => value_fn(l, r),
773            };
774            ResultSpec {
775                fallible: left.fallible || right.fallible || result.fallible,
776                nullable: left.nullable || right.nullable || result.nullable,
777                values: result.values,
778            }
779        }
780
781        fn jsonb_get_string<'b>(
782            left: ResultSpec<'b>,
783            right: ResultSpec<'b>,
784            stringify: bool,
785        ) -> ResultSpec<'b> {
786            eagerly(left, right, |left, right| {
787                let nested_spec = match (left, right) {
788                    (Values::Nested(mut map_spec), Values::Within(key, key2)) if key == key2 => {
789                        map_spec.remove(&key)
790                    }
791                    _ => None,
792                };
793
794                if let Some(field_spec) = nested_spec {
795                    if stringify {
796                        // We only preserve value-range information when stringification
797                        // is a noop. (Common in real queries.)
798                        let values = match field_spec.values {
799                            Values::Empty => Values::Empty,
800                            Values::Within(min @ Datum::String(_), max @ Datum::String(_)) => {
801                                Values::Within(min, max)
802                            }
803                            Values::Within(_, _) | Values::Nested(_) | Values::All => Values::All,
804                        };
805                        ResultSpec {
806                            values,
807                            ..field_spec
808                        }
809                    } else {
810                        field_spec
811                    }
812                } else {
813                    // The implementation of `jsonb_get_string` always returns
814                    // `Ok(...)`. Morally, everything has a string
815                    // representation, and the worst you can get is a NULL,
816                    // which maps to a NULL.
817                    ResultSpec::any_infallible()
818                }
819            })
820        }
821
822        fn eq<'b>(left: ResultSpec<'b>, right: ResultSpec<'b>) -> ResultSpec<'b> {
823            eagerly(left, right, |left, right| {
824                // `eq` might return true if there's any overlap between the range of its two arguments...
825                let maybe_true = match left.clone().intersect(right.clone()) {
826                    Values::Empty => ResultSpec::nothing(),
827                    _ => ResultSpec::value(Datum::True),
828                };
829
830                // ...and may return false if the union contains at least two distinct values.
831                // Note that the `Empty` case is handled by `eagerly` above.
832                let maybe_false = match left.union(right) {
833                    Values::Within(a, b) if a == b => ResultSpec::nothing(),
834                    _ => ResultSpec::value(Datum::False),
835                };
836
837                maybe_true.union(maybe_false)
838            })
839        }
840
841        /// `add_timestamp_interval` and friends do calendar-month arithmetic
842        /// with day-clamping, which is non-monotone in either argument when
843        /// `interval.months != 0`. But when `interval.months == 0` the
844        /// operation reduces to adding a fixed number of microseconds, which
845        /// *is* monotone in both arguments. The static `is_monotone`
846        /// annotation has to pick the conservative answer; this dynamic check
847        /// recovers filter pushdown for the common case of literal
848        /// `INTERVAL '<N>' day`-style predicates.
849        fn timestamp_plus_interval_monotone(
850            _left: &ResultSpec<'_>,
851            right: &ResultSpec<'_>,
852        ) -> (bool, bool) {
853            let months_zero = matches!(
854                right.values.as_single(),
855                Some(Datum::Interval(i)) if i.months == 0,
856            );
857            (months_zero, months_zero)
858        }
859
860        match func {
861            BinaryFunc::JsonbGetString(_) => Some(AbstractFunc {
862                handler: AbstractFuncHandler::Override(|l, r| jsonb_get_string(l, r, false)),
863                pushdownable: (true, false),
864            }),
865            BinaryFunc::JsonbGetStringStringify(_) => Some(AbstractFunc {
866                handler: AbstractFuncHandler::Override(|l, r| jsonb_get_string(l, r, true)),
867                pushdownable: (true, false),
868            }),
869            BinaryFunc::Eq(_) => Some(AbstractFunc {
870                handler: AbstractFuncHandler::Override(eq),
871                pushdownable: (true, true),
872            }),
873            BinaryFunc::AddTimestampInterval(_)
874            | BinaryFunc::AddTimestampTzInterval(_)
875            | BinaryFunc::SubTimestampInterval(_)
876            | BinaryFunc::SubTimestampTzInterval(_) => Some(AbstractFunc {
877                handler: AbstractFuncHandler::DynamicMonotone(timestamp_plus_interval_monotone),
878                // For [Trace]: we *might* be pushdownable in the first argument
879                // (we are when the interval is a literal with no months). The
880                // interval argument is reported as non-pushdownable so that
881                // `t_col +/- col_interval` doesn't get routed through pushdown
882                // for no benefit; if both sides are constants the predicate
883                // collapses anyway.
884                pushdownable: (true, false),
885            }),
886            _ => None,
887        }
888    }
889}
890
891#[derive(Clone, Debug)]
892pub struct ColumnSpec<'a> {
893    pub col_type: ReprColumnType,
894    pub range: ResultSpec<'a>,
895}
896
897/// An interpreter that:
898/// - stores both the type and the range of possible values for every column and
899///   unmaterializable function. (See the `push_` methods.)
900/// - given an expression (or MFP, etc.), returns the range of possible results that evaluating that
901///   expression might have. (See the `eval_` methods.)
902#[derive(Clone, Debug)]
903pub struct ColumnSpecs<'a> {
904    pub relation: &'a ReprRelationType,
905    pub columns: Vec<ResultSpec<'a>>,
906    pub unmaterializables: BTreeMap<UnmaterializableFunc, ResultSpec<'a>>,
907    pub arena: &'a RowArena,
908}
909
910impl<'a> ColumnSpecs<'a> {
911    // Interpreting a variadic function can lead to exponential blowup: there are up to 4 possibly-
912    // interesting values for each argument (error, null, range bounds...) and in the worst case
913    // we may need to test every combination. We mitigate that here in two ways:
914    // - Adding a linear-time optimization for associative functions like AND, OR, COALESCE.
915    // - Limiting the number of arguments we'll pass on to eval. If this limit is crossed, we'll
916    //   return our default / safe overapproximation instead.
917    const MAX_EVAL_ARGS: usize = 6;
918
919    /// Create a new, empty set of column specs. (Initially, the only assumption we make about the
920    /// data in the column is that it matches the type.)
921    pub fn new(relation: &'a ReprRelationType, arena: &'a RowArena) -> Self {
922        let columns = relation
923            .column_types
924            .iter()
925            .map(|ct| ResultSpec::has_type(ct, false))
926            .collect();
927        ColumnSpecs {
928            relation,
929            columns,
930            unmaterializables: Default::default(),
931            arena,
932        }
933    }
934
935    /// Restrict the set of possible values in a given column. (By intersecting it with the existing
936    /// spec.)
937    pub fn push_column(&mut self, id: usize, update: ResultSpec<'a>) {
938        let range = self.columns.get_mut(id).expect("valid column id");
939        *range = range.clone().intersect(update);
940    }
941
942    /// Restrict the set of possible values a given unmaterializable func might return. (By
943    /// intersecting it with the existing spec.)
944    pub fn push_unmaterializable(&mut self, func: UnmaterializableFunc, update: ResultSpec<'a>) {
945        let range = self
946            .unmaterializables
947            .entry(func.clone())
948            .or_insert_with(|| ResultSpec::has_type(&func.output_type(), true));
949        *range = range.clone().intersect(update);
950    }
951
952    fn eval_result<'b, E>(&self, result: Result<Datum<'b>, E>) -> ResultSpec<'a> {
953        match result {
954            Ok(Datum::Null) => ResultSpec {
955                nullable: true,
956                ..ResultSpec::nothing()
957            },
958            Ok(d) => ResultSpec {
959                values: Values::just(self.arena.make_datum(|packer| packer.push(d))),
960                ..ResultSpec::nothing()
961            },
962            Err(_) => ResultSpec {
963                fallible: true,
964                ..ResultSpec::nothing()
965            },
966        }
967    }
968
969    fn set_literal(expr: &mut MirScalarExpr, update: Result<Datum, EvalError>) {
970        match expr {
971            MirScalarExpr::Literal(literal, col_type) => match update {
972                Err(error) => *literal = Err(error),
973                Ok(datum) => {
974                    assert!(
975                        datum.is_instance_of(col_type),
976                        "{datum:?} must be an instance of {col_type:?}"
977                    );
978                    match literal {
979                        // Reuse the allocation if we can
980                        Ok(row) => row.packer().push(datum),
981                        literal => *literal = Ok(Row::pack_slice(&[datum])),
982                    }
983                }
984            },
985            _ => panic!("not a literal"),
986        }
987    }
988
989    fn set_argument(expr: &mut MirScalarExpr, arg: usize, value: Result<Datum, EvalError>) {
990        match (expr, arg) {
991            (MirScalarExpr::CallUnary { expr, .. }, 0) => Self::set_literal(expr, value),
992            (MirScalarExpr::CallBinary { expr1, .. }, 0) => Self::set_literal(expr1, value),
993            (MirScalarExpr::CallBinary { expr2, .. }, 1) => Self::set_literal(expr2, value),
994            (MirScalarExpr::CallVariadic { exprs, .. }, n) if n < exprs.len() => {
995                Self::set_literal(&mut exprs[n], value)
996            }
997            _ => panic!("illegal argument for expression"),
998        }
999    }
1000
1001    /// A literal with the given type and a trivial default value. Callers should ensure that
1002    /// [Self::set_literal] is called on the resulting expression to give it a meaningful value
1003    /// before evaluating.
1004    fn placeholder(col_type: ReprColumnType) -> MirScalarExpr {
1005        MirScalarExpr::Literal(Err(EvalError::Internal("".into())), col_type)
1006    }
1007}
1008
1009impl<'a> Interpreter for ColumnSpecs<'a> {
1010    type Summary = ColumnSpec<'a>;
1011
1012    fn column(&self, id: usize) -> Self::Summary {
1013        let col_type = self.relation.column_types[id].clone();
1014        let range = self.columns[id].clone();
1015        ColumnSpec { col_type, range }
1016    }
1017
1018    fn literal(&self, result: &Result<Row, EvalError>, col_type: &ReprColumnType) -> Self::Summary {
1019        let col_type = col_type.clone();
1020        let range = self.eval_result(result.as_ref().map(|row| {
1021            self.arena
1022                .make_datum(|packer| packer.push(row.unpack_first()))
1023        }));
1024        ColumnSpec { col_type, range }
1025    }
1026
1027    fn unmaterializable(&self, func: &UnmaterializableFunc) -> Self::Summary {
1028        let col_type = func.output_type();
1029        let range = self
1030            .unmaterializables
1031            .get(func)
1032            .cloned()
1033            .unwrap_or_else(|| ResultSpec::has_type(&func.output_type(), true));
1034        ColumnSpec { col_type, range }
1035    }
1036
1037    fn unary(&self, func: &UnaryFunc, summary: Self::Summary) -> Self::Summary {
1038        let fallible = func.could_error() || summary.range.fallible;
1039        // Endpoint sampling proves a monotone function's output value range, but
1040        // it cannot prove the function never errors on an interior value of a
1041        // multi-valued range: monotonicity says nothing about where errors
1042        // occur (e.g. `round(_, scale)` overflows on inputs whose exponent hits
1043        // a bad branch, `numeric::mz_timestamp` rejects fractional inputs). So
1044        // we do not let it conclude a could-error function is infallible over
1045        // such a range.
1046        let input_multivalued = !summary.range.is_single_value();
1047        let mapped_spec = if let Some(special) = SpecialUnary::for_func(func) {
1048            (special.map_fn)(self, summary.range)
1049        } else if func.is_unbounded() {
1050            // The call must not be evaluated, so nothing is known about its result.
1051            // TODO: This also stops clusters, which may evaluate the call, from pruning on its
1052            // result. Revisit once jq's evaluation is bounded, as materialize#40133 proposes.
1053            ResultSpec::anything()
1054        } else {
1055            let is_monotone = func.is_monotone();
1056            let mut expr = MirScalarExpr::CallUnary {
1057                func: func.clone(),
1058                expr: Box::new(Self::placeholder(summary.col_type.clone())),
1059            };
1060            summary.range.flat_map(is_monotone, |datum| {
1061                Self::set_argument(&mut expr, 0, datum);
1062                self.eval_result(expr.eval(&[], self.arena))
1063            })
1064        };
1065
1066        let col_type = func.output_type(summary.col_type);
1067
1068        let mut range = mapped_spec.intersect(ResultSpec::has_type(&col_type, fallible));
1069        // `intersect` only ANDs the fallible flag, so `has_type` above narrows
1070        // the value and null domain but cannot surface an error that endpoint
1071        // sampling missed. Force it for a could-error function over a range.
1072        if fallible && input_multivalued {
1073            range.fallible = true;
1074        }
1075        ColumnSpec { col_type, range }
1076    }
1077
1078    fn binary(
1079        &self,
1080        func: &BinaryFunc,
1081        left: Self::Summary,
1082        right: Self::Summary,
1083    ) -> Self::Summary {
1084        let fallible = func.could_error() || left.range.fallible || right.range.fallible;
1085        // See the note in `unary`: endpoint sampling cannot rule out an interior
1086        // error, so a could-error function is fallible over a multi-valued range.
1087        let inputs_multivalued = !left.range.is_single_value() || !right.range.is_single_value();
1088        let operand_may_be_infinite = left.range.may_be_infinite() || right.range.may_be_infinite();
1089
1090        let special = AbstractFunc::for_func(func);
1091        let (left_monotonic, right_monotonic) = match &special {
1092            Some(AbstractFunc {
1093                handler: AbstractFuncHandler::DynamicMonotone(monotone_fn),
1094                ..
1095            }) => monotone_fn(&left.range, &right.range),
1096            _ => func.is_monotone(),
1097        };
1098
1099        let mapped_spec = match special {
1100            Some(AbstractFunc {
1101                handler: AbstractFuncHandler::Override(f),
1102                ..
1103            }) => f(left.range, right.range),
1104            _ => {
1105                let mut expr = MirScalarExpr::CallBinary {
1106                    func: func.clone(),
1107                    expr1: Box::new(Self::placeholder(left.col_type.clone())),
1108                    expr2: Box::new(Self::placeholder(right.col_type.clone())),
1109                };
1110                left.range.flat_map(left_monotonic, |left_result| {
1111                    Self::set_argument(&mut expr, 0, left_result);
1112                    right.range.flat_map(right_monotonic, |right_result| {
1113                        Self::set_argument(&mut expr, 1, right_result);
1114                        self.eval_result(expr.eval(&[], self.arena))
1115                    })
1116                })
1117            }
1118        };
1119
1120        let col_type = func.output_type(&[left.col_type, right.col_type]);
1121
1122        let mut range = mapped_spec.intersect(ResultSpec::has_type(&col_type, fallible));
1123        // `intersect` only ANDs the fallible flag, so force the interior
1124        // fallibility it cannot add (see the note in `unary`).
1125        if fallible && inputs_multivalued {
1126            range.fallible = true;
1127        }
1128        // Some functions (multiplication, division) are not corner-sampleable
1129        // when an operand may be infinite: their indeterminate forms (`∞ * 0`,
1130        // `∞ / ∞`) evaluate to a value the endpoints don't bound, and that value
1131        // can be reached only from the interior (e.g. `[-∞, +∞] * 0` maps both
1132        // endpoints to `NaN` while its finite interior maps to `0`, and
1133        // `finite / ∞ = 0` is stepped over when both endpoints are `∞ / ∞ =
1134        // NaN`). Fall back to the full value domain for them.
1135        if operand_may_be_infinite && !func.is_infinity_monotone() {
1136            range.values = Values::All;
1137        }
1138        ColumnSpec { col_type, range }
1139    }
1140
1141    fn variadic(&self, func: &VariadicFunc, args: Vec<Self::Summary>) -> Self::Summary {
1142        let fallible = func.could_error() || args.iter().any(|s| s.range.fallible);
1143        let inputs_multivalued = args.iter().any(|s| !s.range.is_single_value());
1144        if func.is_associative() && args.len() > 2 {
1145            // To avoid a combinatorial explosion, evaluate large variadic calls as a series of
1146            // smaller ones, since associativity guarantees we'll get compatible results.
1147            return args
1148                .into_iter()
1149                .reduce(|a, b| self.variadic(func, vec![a, b]))
1150                .expect("reducing over a non-empty argument list");
1151        }
1152
1153        let mapped_spec = if args.len() >= Self::MAX_EVAL_ARGS {
1154            ResultSpec::anything()
1155        } else {
1156            fn eval_loop<'a>(
1157                is_monotonic: bool,
1158                expr: &mut MirScalarExpr,
1159                args: &[ColumnSpec<'a>],
1160                index: usize,
1161                datum_map: &mut impl FnMut(&MirScalarExpr) -> ResultSpec<'a>,
1162            ) -> ResultSpec<'a> {
1163                if index >= args.len() {
1164                    datum_map(expr)
1165                } else {
1166                    args[index].range.flat_map(is_monotonic, |datum| {
1167                        ColumnSpecs::set_argument(expr, index, datum);
1168                        eval_loop(is_monotonic, expr, args, index + 1, datum_map)
1169                    })
1170                }
1171            }
1172
1173            let mut fn_expr = MirScalarExpr::CallVariadic {
1174                func: func.clone(),
1175                exprs: args
1176                    .iter()
1177                    .map(|spec| Self::placeholder(spec.col_type.clone()))
1178                    .collect(),
1179            };
1180            eval_loop(func.is_monotone(), &mut fn_expr, &args, 0, &mut |expr| {
1181                self.eval_result(expr.eval(&[], self.arena))
1182            })
1183        };
1184
1185        let col_types = args.into_iter().map(|spec| spec.col_type).collect();
1186        let col_type = func.output_type(col_types);
1187
1188        let mut range = mapped_spec.intersect(ResultSpec::has_type(&col_type, fallible));
1189        // `intersect` only ANDs the fallible flag, so force the interior
1190        // fallibility it cannot add (see the note in `unary`).
1191        if fallible && inputs_multivalued {
1192            range.fallible = true;
1193        }
1194
1195        ColumnSpec { col_type, range }
1196    }
1197
1198    fn cond(&self, cond: Self::Summary, then: Self::Summary, els: Self::Summary) -> Self::Summary {
1199        let col_type = then
1200            .col_type
1201            .union(&els.col_type)
1202            .expect("failed type union for cond during abstract interpretation");
1203
1204        let range = cond
1205            .range
1206            .flat_map(true, |datum| match datum {
1207                Ok(Datum::True) => then.range.clone(),
1208                // A false OR null condition takes the `els` branch, matching
1209                // `MirScalarExpr::eval` (`Datum::False | Datum::Null => els`).
1210                // Mapping null to `fails()` here would drop `els` from the value
1211                // channel and let pushdown wrongly rule out the else result.
1212                Ok(Datum::False) | Ok(Datum::Null) => els.range.clone(),
1213                _ => ResultSpec::fails(),
1214            })
1215            .intersect(ResultSpec::has_type(&col_type, true));
1216
1217        ColumnSpec { col_type, range }
1218    }
1219
1220    /// Override the default implementations of [Self::mfp_filter] and
1221    /// [Self::mfp_plan_filter] so that the fallibility of MFP expressions
1222    /// surfaces in the result, even when the expression's result column isn't
1223    /// referenced by a predicate or temporal bound.
1224    ///
1225    /// The runtime MFP evaluator runs every expression once all the preceding
1226    /// predicates pass (see [`crate::SafeMfpPlan::evaluate_inner`]), so an
1227    /// expression that errors on the actual data will turn the whole row into
1228    /// an `Err` — even if no predicate or bound mentions that expression. The
1229    /// default `mfp_filter` / `mfp_plan_filter` only AND together the
1230    /// predicates and bounds, so the AND result misses the expression's
1231    /// `fallible` flag and persist filter pushdown can wrongly discard a part
1232    /// that actually produces error rows. See database-issues#9656.
1233    fn mfp_filter<X: Interpretable + OptimizableExpr>(
1234        &self,
1235        mfp: &MapFilterProject<X>,
1236    ) -> Self::Summary {
1237        let mfp_eval = MfpEval::new(self, mfp.input_arity, &mfp.expressions);
1238        let predicates = mfp
1239            .predicates
1240            .iter()
1241            .map(|(_, e)| mfp_eval.expr(e))
1242            .collect();
1243        let mut result = self.variadic(&And.into(), predicates);
1244        if mfp_eval.expressions.iter().any(|s| s.range.fallible) {
1245            result.range.fallible = true;
1246        }
1247        result
1248    }
1249
1250    fn mfp_plan_filter<X: Interpretable + OptimizableExpr>(
1251        &self,
1252        plan: &MfpPlan<X>,
1253    ) -> Self::Summary {
1254        let mfp_eval = MfpEval::new(self, plan.mfp.input_arity, &plan.mfp.expressions);
1255        let mut results: Vec<_> = plan
1256            .mfp
1257            .predicates
1258            .iter()
1259            .map(|(_, e)| mfp_eval.expr(e))
1260            .collect();
1261        let mz_now = mfp_eval.unmaterializable(&UnmaterializableFunc::MzNow);
1262        for bound in &plan.lower_bounds {
1263            let bound_range = mfp_eval.expr(bound);
1264            let result = mfp_eval.binary(&BinaryFunc::Lte(func::Lte), bound_range, mz_now.clone());
1265            results.push(result);
1266        }
1267        for bound in &plan.upper_bounds {
1268            let bound_range = mfp_eval.expr(bound);
1269            let result = mfp_eval.binary(&BinaryFunc::Gte(func::Gte), bound_range, mz_now.clone());
1270            results.push(result);
1271        }
1272        let mut result = self.variadic(&And.into(), results);
1273        if mfp_eval.expressions.iter().any(|s| s.range.fallible) {
1274            result.range.fallible = true;
1275        }
1276        result
1277    }
1278}
1279
1280/// An interpreter that returns whether or not a particular expression is "pushdownable".
1281/// Broadly speaking, an expression is pushdownable if the result of evaluating the expression
1282/// depends on the range of possible column values in a way that `ColumnSpecs` is able to reason about.
1283///
1284/// In practice, we internally need to distinguish between expressions that are trivially predicable
1285/// (because they're constant) and expressions that depend on the column ranges themselves.
1286/// See the [TraceSummary] variants for those distinctions, and [TraceSummary::pushdownable] for
1287/// the overall assessment.
1288#[derive(Debug)]
1289pub struct Trace;
1290
1291/// A summary type for the [Trace] interpreter.
1292///
1293/// The ordering of this type is meaningful: the "smaller" the summary, the more information we have
1294/// about the possible values of the expression. This means we can eg. use `max` in the
1295/// interpreter below to find the summary for a function-call expression based on the summaries
1296/// of its arguments.
1297#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)]
1298pub enum TraceSummary {
1299    /// The expression is constant: we can evaluate it without any runtime information.
1300    /// This corresponds to a `ResultSpec` of a single value.
1301    Constant,
1302    /// The expression depends on runtime information, but in "predictable" way... ie. if we know
1303    /// the range of possible values for all columns and unmaterializable functions, we can
1304    /// predict the possible values of the output.
1305    /// This corresponds to a `ResultSpec` of a perhaps range of values.
1306    Dynamic,
1307    /// The expression depends on runtime information in an unpredictable way.
1308    /// This corresponds to a `ResultSpec::value_all()` or something similarly vague.
1309    Unknown,
1310}
1311
1312impl TraceSummary {
1313    /// We say that a function is "pushdownable" for a particular
1314    /// argument if `ColumnSpecs` can determine the spec of the function's output given the input spec for
1315    /// that argument. (In practice, this is true when either the function is monotone in that argument
1316    /// or it's been special-cased in the interpreter.)
1317    fn apply_fn(self, pushdownable: bool) -> Self {
1318        match self {
1319            TraceSummary::Constant => TraceSummary::Constant,
1320            TraceSummary::Dynamic => match pushdownable {
1321                true => TraceSummary::Dynamic,
1322                false => TraceSummary::Unknown,
1323            },
1324            TraceSummary::Unknown => TraceSummary::Unknown,
1325        }
1326    }
1327
1328    /// We say that an expression is "pushdownable" if it's either constant or dynamic.
1329    pub fn pushdownable(self) -> bool {
1330        match self {
1331            TraceSummary::Constant | TraceSummary::Dynamic => true,
1332            TraceSummary::Unknown => false,
1333        }
1334    }
1335}
1336
1337impl Interpreter for Trace {
1338    type Summary = TraceSummary;
1339
1340    fn column(&self, _id: usize) -> Self::Summary {
1341        TraceSummary::Dynamic
1342    }
1343
1344    fn literal(
1345        &self,
1346        _result: &Result<Row, EvalError>,
1347        _col_type: &ReprColumnType,
1348    ) -> Self::Summary {
1349        TraceSummary::Constant
1350    }
1351
1352    fn unmaterializable(&self, _func: &UnmaterializableFunc) -> Self::Summary {
1353        TraceSummary::Dynamic
1354    }
1355
1356    fn unary(&self, func: &UnaryFunc, expr: Self::Summary) -> Self::Summary {
1357        // `ColumnSpecs` does not evaluate an unbounded call, not even on a constant.
1358        if func.is_unbounded() {
1359            return TraceSummary::Unknown;
1360        }
1361        let pushdownable = match SpecialUnary::for_func(func) {
1362            None => func.is_monotone(),
1363            Some(special) => special.pushdownable,
1364        };
1365        expr.apply_fn(pushdownable)
1366    }
1367
1368    fn binary(
1369        &self,
1370        func: &BinaryFunc,
1371        left: Self::Summary,
1372        right: Self::Summary,
1373    ) -> Self::Summary {
1374        let (left_pushdownable, right_pushdownable) = match AbstractFunc::for_func(func) {
1375            None => func.is_monotone(),
1376            Some(special) => special.pushdownable,
1377        };
1378        left.apply_fn(left_pushdownable)
1379            .max(right.apply_fn(right_pushdownable))
1380    }
1381
1382    fn variadic(&self, func: &VariadicFunc, exprs: Vec<Self::Summary>) -> Self::Summary {
1383        if !func.is_associative() && exprs.len() >= ColumnSpecs::MAX_EVAL_ARGS {
1384            // We can't efficiently evaluate functions with very large argument lists;
1385            // see the comment on ColumnSpecs::MAX_EVAL_ARGS for details.
1386            return TraceSummary::Unknown;
1387        }
1388
1389        let pushdownable_fn = func.is_monotone();
1390        exprs
1391            .into_iter()
1392            .map(|pushdownable_arg| pushdownable_arg.apply_fn(pushdownable_fn))
1393            .max()
1394            .unwrap_or(TraceSummary::Constant)
1395    }
1396
1397    fn cond(&self, cond: Self::Summary, then: Self::Summary, els: Self::Summary) -> Self::Summary {
1398        // We don't actually need to be able to predict the condition precisely to predict the output,
1399        // since we can union the ranges of the two branches for a conservative estimate.
1400        let cond = cond.min(TraceSummary::Dynamic);
1401        cond.max(then).max(els)
1402    }
1403}
1404
1405#[cfg(test)]
1406mod tests {
1407    use itertools::Itertools;
1408    use mz_repr::adt::datetime::DateTimeUnits;
1409    use mz_repr::{Datum, PropDatum, RowArena, SqlScalarType};
1410    use proptest::prelude::*;
1411    use proptest::sample::{Index, select};
1412
1413    use crate::func::*;
1414    use crate::scalar::func::variadic::Concat;
1415    use crate::{BinaryFunc, MirScalarExpr, UnaryFunc};
1416
1417    use super::*;
1418
1419    #[derive(Debug)]
1420    struct ExpressionData {
1421        relation_type: ReprRelationType,
1422        specs: Vec<ResultSpec<'static>>,
1423        rows: Vec<Row>,
1424        expr: MirScalarExpr,
1425    }
1426
1427    // Currently there's no good way to check whether a particular function accepts a particular
1428    // type as argument, which means we need to list everything out explicitly here. Restrict our interest
1429    // to a reasonable number of functions, to keep things tractable
1430    // TODO: replace this with function-level info once it's available.
1431    const NUM_TYPE: ReprScalarType = ReprScalarType::Numeric;
1432    static SCALAR_TYPES: &[ReprScalarType] = &[
1433        ReprScalarType::Bool,
1434        ReprScalarType::Jsonb,
1435        NUM_TYPE,
1436        ReprScalarType::Int16,
1437        ReprScalarType::Int32,
1438        ReprScalarType::Int64,
1439        ReprScalarType::UInt16,
1440        ReprScalarType::UInt32,
1441        ReprScalarType::UInt64,
1442        ReprScalarType::Float32,
1443        ReprScalarType::Float64,
1444        ReprScalarType::Date,
1445        ReprScalarType::Time,
1446        ReprScalarType::Timestamp,
1447        ReprScalarType::TimestampTz,
1448        ReprScalarType::MzTimestamp,
1449        ReprScalarType::Interval,
1450        ReprScalarType::String,
1451    ];
1452
1453    const INTERESTING_UNARY_FUNCS: &[UnaryFunc] = {
1454        &[
1455            UnaryFunc::CastNumericToMzTimestamp(CastNumericToMzTimestamp),
1456            UnaryFunc::CastTimestampToMzTimestamp(CastTimestampToMzTimestamp),
1457            UnaryFunc::NegNumeric(NegNumeric),
1458            UnaryFunc::NegFloat64(NegFloat64),
1459            UnaryFunc::CastJsonbToNumeric(CastJsonbToNumeric(None)),
1460            UnaryFunc::CastJsonbToBool(CastJsonbToBool),
1461            UnaryFunc::CastJsonbToString(CastJsonbToString),
1462            UnaryFunc::DateTruncTimestamp(DateTruncTimestamp(DateTimeUnits::Epoch)),
1463            UnaryFunc::ExtractTimestamp(ExtractTimestamp(DateTimeUnits::Epoch)),
1464            UnaryFunc::ExtractDate(ExtractDate(DateTimeUnits::Epoch)),
1465            UnaryFunc::Not(Not),
1466            UnaryFunc::IsNull(IsNull),
1467            UnaryFunc::IsFalse(IsFalse),
1468            UnaryFunc::TryParseMonotonicIso8601Timestamp(TryParseMonotonicIso8601Timestamp),
1469            // Declared-monotone functions whose claims are otherwise
1470            // unvalidated, chosen for fallible or lossy interiors: the
1471            // equivalence proptests catch a wrong claim as a spec that fails
1472            // to contain the evaluated result.
1473            UnaryFunc::NegInt32(NegInt32),
1474            UnaryFunc::NegInt64(NegInt64),
1475            UnaryFunc::CastInt32ToUint32(CastInt32ToUint32),
1476            UnaryFunc::CastInt64ToInt32(CastInt64ToInt32),
1477            UnaryFunc::CastInt64ToNumeric(CastInt64ToNumeric(None)),
1478            UnaryFunc::CastFloat64ToInt64(CastFloat64ToInt64),
1479            UnaryFunc::CastFloat64ToFloat32(CastFloat64ToFloat32),
1480            UnaryFunc::CastFloat32ToFloat64(CastFloat32ToFloat64),
1481            UnaryFunc::CastNumericToInt64(CastNumericToInt64),
1482            UnaryFunc::CeilNumeric(CeilNumeric),
1483            UnaryFunc::FloorNumeric(FloorNumeric),
1484            UnaryFunc::CastDateToTimestamp(CastDateToTimestamp(None)),
1485            UnaryFunc::CastTimestampToTimestampTz(CastTimestampToTimestampTz {
1486                from: None,
1487                to: None,
1488            }),
1489            UnaryFunc::CastTimestampTzToTimestamp(CastTimestampTzToTimestamp {
1490                from: None,
1491                to: None,
1492            }),
1493            // Conditionally monotone (most significant unit) and its
1494            // non-monotone sibling.
1495            UnaryFunc::ExtractTimestamp(ExtractTimestamp(DateTimeUnits::Year)),
1496            UnaryFunc::ExtractTimestamp(ExtractTimestamp(DateTimeUnits::Month)),
1497            UnaryFunc::ExtractTimestampTz(ExtractTimestampTz(DateTimeUnits::Epoch)),
1498            UnaryFunc::ExtractTimestampTz(ExtractTimestampTz(DateTimeUnits::Year)),
1499            // Batch 2 of the declared-monotone sweep: the remaining cast
1500            // families, ordered-domain arithmetic helpers, and functions with
1501            // partial domains (errors on part of the range).
1502            UnaryFunc::CastBoolToInt32(CastBoolToInt32),
1503            UnaryFunc::CastBoolToString(CastBoolToString),
1504            UnaryFunc::NegInt16(NegInt16),
1505            UnaryFunc::CastInt16ToInt32(CastInt16ToInt32),
1506            UnaryFunc::CastInt16ToInt64(CastInt16ToInt64),
1507            UnaryFunc::CastInt16ToFloat32(CastInt16ToFloat32),
1508            UnaryFunc::CastInt16ToFloat64(CastInt16ToFloat64),
1509            UnaryFunc::CastInt16ToUint16(CastInt16ToUint16),
1510            UnaryFunc::CastInt16ToNumeric(CastInt16ToNumeric(None)),
1511            UnaryFunc::CastInt32ToInt16(CastInt32ToInt16),
1512            UnaryFunc::CastInt32ToInt64(CastInt32ToInt64),
1513            UnaryFunc::CastInt32ToFloat32(CastInt32ToFloat32),
1514            UnaryFunc::CastInt32ToFloat64(CastInt32ToFloat64),
1515            UnaryFunc::CastInt32ToUint16(CastInt32ToUint16),
1516            UnaryFunc::CastInt32ToNumeric(CastInt32ToNumeric(None)),
1517            UnaryFunc::CastInt32ToMzTimestamp(CastInt32ToMzTimestamp),
1518            UnaryFunc::CastInt64ToInt16(CastInt64ToInt16),
1519            UnaryFunc::CastInt64ToFloat32(CastInt64ToFloat32),
1520            UnaryFunc::CastInt64ToFloat64(CastInt64ToFloat64),
1521            UnaryFunc::CastInt64ToUint64(CastInt64ToUint64),
1522            UnaryFunc::CastInt64ToMzTimestamp(CastInt64ToMzTimestamp),
1523            UnaryFunc::CastUint64ToUint32(CastUint64ToUint32),
1524            UnaryFunc::CastUint64ToInt32(CastUint64ToInt32),
1525            UnaryFunc::CastUint64ToNumeric(CastUint64ToNumeric(None)),
1526            UnaryFunc::CastUint64ToMzTimestamp(CastUint64ToMzTimestamp),
1527            UnaryFunc::NegFloat32(NegFloat32),
1528            UnaryFunc::FloorFloat32(FloorFloat32),
1529            UnaryFunc::CastFloat32ToInt32(CastFloat32ToInt32),
1530            UnaryFunc::CastFloat32ToNumeric(CastFloat32ToNumeric(None)),
1531            UnaryFunc::FloorFloat64(FloorFloat64),
1532            UnaryFunc::CastFloat64ToInt32(CastFloat64ToInt32),
1533            UnaryFunc::CastFloat64ToUint64(CastFloat64ToUint64),
1534            UnaryFunc::CastFloat64ToNumeric(CastFloat64ToNumeric(None)),
1535            UnaryFunc::RoundNumeric(RoundNumeric),
1536            UnaryFunc::TruncNumeric(TruncNumeric),
1537            UnaryFunc::Log10Numeric(Log10Numeric),
1538            UnaryFunc::CastNumericToFloat64(CastNumericToFloat64),
1539            UnaryFunc::CastNumericToInt32(CastNumericToInt32),
1540            UnaryFunc::CastTimestampToDate(CastTimestampToDate),
1541            UnaryFunc::CastDateToMzTimestamp(CastDateToMzTimestamp),
1542            UnaryFunc::StepMzTimestamp(StepMzTimestamp),
1543            // Batch 3: every remaining declared-monotone cast family, the
1544            // anti-monotone bitwise complements, and the conditional
1545            // most-significant-unit extracts for date and timestamptz.
1546            UnaryFunc::CastBoolToStringNonstandard(CastBoolToStringNonstandard),
1547            UnaryFunc::CastBoolToInt64(CastBoolToInt64),
1548            UnaryFunc::CastInt16ToUint32(CastInt16ToUint32),
1549            UnaryFunc::CastInt16ToUint64(CastInt16ToUint64),
1550            UnaryFunc::CastInt32ToUint64(CastInt32ToUint64),
1551            UnaryFunc::CastInt64ToUint16(CastInt64ToUint16),
1552            UnaryFunc::CastInt64ToUint32(CastInt64ToUint32),
1553            UnaryFunc::CastUint16ToUint32(CastUint16ToUint32),
1554            UnaryFunc::CastUint16ToUint64(CastUint16ToUint64),
1555            UnaryFunc::CastUint16ToInt16(CastUint16ToInt16),
1556            UnaryFunc::CastUint16ToInt32(CastUint16ToInt32),
1557            UnaryFunc::CastUint16ToFloat32(CastUint16ToFloat32),
1558            UnaryFunc::CastUint16ToFloat64(CastUint16ToFloat64),
1559            UnaryFunc::CastUint16ToNumeric(CastUint16ToNumeric(None)),
1560            UnaryFunc::CastUint16ToInt64(CastUint16ToInt64),
1561            UnaryFunc::BitNotUint16(BitNotUint16),
1562            UnaryFunc::CastUint32ToUint16(CastUint32ToUint16),
1563            UnaryFunc::CastUint32ToUint64(CastUint32ToUint64),
1564            UnaryFunc::CastUint32ToInt32(CastUint32ToInt32),
1565            UnaryFunc::CastUint32ToInt64(CastUint32ToInt64),
1566            UnaryFunc::CastUint32ToFloat32(CastUint32ToFloat32),
1567            UnaryFunc::CastUint32ToFloat64(CastUint32ToFloat64),
1568            UnaryFunc::CastUint32ToNumeric(CastUint32ToNumeric(None)),
1569            UnaryFunc::CastUint32ToInt16(CastUint32ToInt16),
1570            UnaryFunc::CastUint32ToMzTimestamp(CastUint32ToMzTimestamp),
1571            UnaryFunc::BitNotUint32(BitNotUint32),
1572            UnaryFunc::CastUint64ToUint16(CastUint64ToUint16),
1573            UnaryFunc::CastUint64ToInt16(CastUint64ToInt16),
1574            UnaryFunc::CastUint64ToInt64(CastUint64ToInt64),
1575            UnaryFunc::CastUint64ToFloat32(CastUint64ToFloat32),
1576            UnaryFunc::CastUint64ToFloat64(CastUint64ToFloat64),
1577            UnaryFunc::BitNotUint64(BitNotUint64),
1578            UnaryFunc::CastFloat32ToInt16(CastFloat32ToInt16),
1579            UnaryFunc::CastFloat32ToInt64(CastFloat32ToInt64),
1580            UnaryFunc::CastFloat32ToUint16(CastFloat32ToUint16),
1581            UnaryFunc::CastFloat32ToUint32(CastFloat32ToUint32),
1582            UnaryFunc::CastFloat32ToUint64(CastFloat32ToUint64),
1583            UnaryFunc::CastFloat64ToInt16(CastFloat64ToInt16),
1584            UnaryFunc::CastFloat64ToUint16(CastFloat64ToUint16),
1585            UnaryFunc::CastFloat64ToUint32(CastFloat64ToUint32),
1586            UnaryFunc::CastJsonbToInt16(CastJsonbToInt16),
1587            UnaryFunc::CastJsonbToInt32(CastJsonbToInt32),
1588            UnaryFunc::CastJsonbToInt64(CastJsonbToInt64),
1589            UnaryFunc::CastJsonbToFloat32(CastJsonbToFloat32),
1590            UnaryFunc::CastJsonbToFloat64(CastJsonbToFloat64),
1591            UnaryFunc::CastNumericToInt16(CastNumericToInt16),
1592            UnaryFunc::CastNumericToFloat32(CastNumericToFloat32),
1593            UnaryFunc::CastNumericToUint16(CastNumericToUint16),
1594            UnaryFunc::CastNumericToUint32(CastNumericToUint32),
1595            UnaryFunc::CastNumericToUint64(CastNumericToUint64),
1596            UnaryFunc::CastTimestampTzToDate(CastTimestampTzToDate),
1597            UnaryFunc::CastTimestampTzToMzTimestamp(CastTimestampTzToMzTimestamp),
1598            UnaryFunc::DateTruncTimestampTz(DateTruncTimestampTz(DateTimeUnits::Epoch)),
1599            UnaryFunc::CastDateToTimestampTz(CastDateToTimestampTz(None)),
1600            UnaryFunc::ExtractDate(ExtractDate(DateTimeUnits::Year)),
1601            UnaryFunc::ExtractDate(ExtractDate(DateTimeUnits::Day)),
1602        ]
1603    };
1604
1605    fn unary_typecheck(func: &UnaryFunc, arg: &ReprColumnType) -> bool {
1606        use UnaryFunc::*;
1607        match func {
1608            CastNumericToMzTimestamp(_)
1609            | NegNumeric(_)
1610            | CastNumericToInt64(_)
1611            | CeilNumeric(_)
1612            | FloorNumeric(_)
1613            | RoundNumeric(_)
1614            | TruncNumeric(_)
1615            | Log10Numeric(_)
1616            | CastNumericToFloat64(_)
1617            | CastNumericToInt32(_)
1618            | CastNumericToInt16(_)
1619            | CastNumericToFloat32(_)
1620            | CastNumericToUint16(_)
1621            | CastNumericToUint32(_)
1622            | CastNumericToUint64(_) => arg.scalar_type == NUM_TYPE,
1623            NegFloat64(_)
1624            | CastFloat64ToInt64(_)
1625            | CastFloat64ToFloat32(_)
1626            | FloorFloat64(_)
1627            | CastFloat64ToInt32(_)
1628            | CastFloat64ToUint64(_)
1629            | CastFloat64ToNumeric(_)
1630            | CastFloat64ToInt16(_)
1631            | CastFloat64ToUint16(_)
1632            | CastFloat64ToUint32(_) => arg.scalar_type == ReprScalarType::Float64,
1633            CastFloat32ToFloat64(_)
1634            | NegFloat32(_)
1635            | FloorFloat32(_)
1636            | CastFloat32ToInt32(_)
1637            | CastFloat32ToNumeric(_)
1638            | CastFloat32ToInt16(_)
1639            | CastFloat32ToInt64(_)
1640            | CastFloat32ToUint16(_)
1641            | CastFloat32ToUint32(_)
1642            | CastFloat32ToUint64(_) => arg.scalar_type == ReprScalarType::Float32,
1643            NegInt16(_)
1644            | CastInt16ToInt32(_)
1645            | CastInt16ToInt64(_)
1646            | CastInt16ToFloat32(_)
1647            | CastInt16ToFloat64(_)
1648            | CastInt16ToUint16(_)
1649            | CastInt16ToNumeric(_)
1650            | CastInt16ToUint32(_)
1651            | CastInt16ToUint64(_) => arg.scalar_type == ReprScalarType::Int16,
1652            NegInt32(_)
1653            | CastInt32ToUint32(_)
1654            | CastInt32ToInt16(_)
1655            | CastInt32ToInt64(_)
1656            | CastInt32ToFloat32(_)
1657            | CastInt32ToFloat64(_)
1658            | CastInt32ToUint16(_)
1659            | CastInt32ToNumeric(_)
1660            | CastInt32ToMzTimestamp(_)
1661            | CastInt32ToUint64(_) => arg.scalar_type == ReprScalarType::Int32,
1662            NegInt64(_)
1663            | CastInt64ToInt32(_)
1664            | CastInt64ToNumeric(_)
1665            | CastInt64ToInt16(_)
1666            | CastInt64ToFloat32(_)
1667            | CastInt64ToFloat64(_)
1668            | CastInt64ToUint64(_)
1669            | CastInt64ToMzTimestamp(_)
1670            | CastInt64ToUint16(_)
1671            | CastInt64ToUint32(_) => arg.scalar_type == ReprScalarType::Int64,
1672            CastUint16ToUint32(_)
1673            | CastUint16ToUint64(_)
1674            | CastUint16ToInt16(_)
1675            | CastUint16ToInt32(_)
1676            | CastUint16ToFloat32(_)
1677            | CastUint16ToFloat64(_)
1678            | CastUint16ToNumeric(_)
1679            | CastUint16ToInt64(_)
1680            | BitNotUint16(_) => arg.scalar_type == ReprScalarType::UInt16,
1681            CastUint32ToUint16(_)
1682            | CastUint32ToUint64(_)
1683            | CastUint32ToInt32(_)
1684            | CastUint32ToInt64(_)
1685            | CastUint32ToFloat32(_)
1686            | CastUint32ToFloat64(_)
1687            | CastUint32ToNumeric(_)
1688            | CastUint32ToInt16(_)
1689            | CastUint32ToMzTimestamp(_)
1690            | BitNotUint32(_) => arg.scalar_type == ReprScalarType::UInt32,
1691            CastUint64ToUint32(_)
1692            | CastUint64ToInt32(_)
1693            | CastUint64ToNumeric(_)
1694            | CastUint64ToMzTimestamp(_)
1695            | CastUint64ToUint16(_)
1696            | CastUint64ToInt16(_)
1697            | CastUint64ToInt64(_)
1698            | CastUint64ToFloat32(_)
1699            | CastUint64ToFloat64(_)
1700            | BitNotUint64(_) => arg.scalar_type == ReprScalarType::UInt64,
1701            StepMzTimestamp(_) => arg.scalar_type == ReprScalarType::MzTimestamp,
1702            CastBoolToInt32(_)
1703            | CastBoolToString(_)
1704            | CastBoolToStringNonstandard(_)
1705            | CastBoolToInt64(_) => arg.scalar_type == ReprScalarType::Bool,
1706            CastTimestampToMzTimestamp(_)
1707            | CastTimestampToTimestampTz(_)
1708            | CastTimestampToDate(_) => arg.scalar_type == ReprScalarType::Timestamp,
1709            CastTimestampTzToTimestamp(_)
1710            | ExtractTimestampTz(_)
1711            | CastTimestampTzToDate(_)
1712            | CastTimestampTzToMzTimestamp(_)
1713            | DateTruncTimestampTz(_) => arg.scalar_type == ReprScalarType::TimestampTz,
1714            CastJsonbToNumeric(_)
1715            | CastJsonbToBool(_)
1716            | CastJsonbToString(_)
1717            | CastJsonbToInt16(_)
1718            | CastJsonbToInt32(_)
1719            | CastJsonbToInt64(_)
1720            | CastJsonbToFloat32(_)
1721            | CastJsonbToFloat64(_) => arg.scalar_type == ReprScalarType::Jsonb,
1722            ExtractTimestamp(_) | DateTruncTimestamp(_) => {
1723                arg.scalar_type == ReprScalarType::Timestamp
1724            }
1725            ExtractDate(_)
1726            | CastDateToTimestamp(_)
1727            | CastDateToMzTimestamp(_)
1728            | CastDateToTimestampTz(_) => arg.scalar_type == ReprScalarType::Date,
1729            Not(_) => arg.scalar_type == ReprScalarType::Bool,
1730            IsNull(_) => true,
1731            TryParseMonotonicIso8601Timestamp(_) => arg.scalar_type == ReprScalarType::String,
1732            TryCast(f) => unary_typecheck(f.inner(), arg),
1733            _ => false,
1734        }
1735    }
1736
1737    /// Fallible casts to wrap in `TryCast`, as the planner does for `TRY_CAST`:
1738    /// narrowing integer casts, float to integer, numeric to integer, and the
1739    /// jsonb casts that reject the wrong kind of value.
1740    const TRY_CAST_INNER_FUNCS: &[UnaryFunc] = &[
1741        UnaryFunc::CastInt64ToInt32(CastInt64ToInt32),
1742        UnaryFunc::CastInt32ToInt16(CastInt32ToInt16),
1743        UnaryFunc::CastInt64ToUint64(CastInt64ToUint64),
1744        UnaryFunc::CastFloat64ToInt64(CastFloat64ToInt64),
1745        UnaryFunc::CastFloat64ToFloat32(CastFloat64ToFloat32),
1746        UnaryFunc::CastNumericToInt32(CastNumericToInt32),
1747        UnaryFunc::CastNumericToMzTimestamp(CastNumericToMzTimestamp),
1748        UnaryFunc::CastJsonbToNumeric(CastJsonbToNumeric(None)),
1749        UnaryFunc::CastJsonbToBool(CastJsonbToBool),
1750        UnaryFunc::CastTimestampToMzTimestamp(CastTimestampToMzTimestamp),
1751    ];
1752
1753    /// The declared unary functions, plus `TryCast` around each fallible cast
1754    /// in `TRY_CAST_INNER_FUNCS`, so the interpreter's properties are checked
1755    /// over the null-fallback wrapper as well.
1756    fn interesting_unary_funcs() -> Vec<UnaryFunc> {
1757        let mut funcs = INTERESTING_UNARY_FUNCS.to_vec();
1758        funcs.extend(TRY_CAST_INNER_FUNCS.iter().map(|cast| {
1759            assert!(
1760                cast.could_error(),
1761                "{cast} never errors, so wrapping it is pointless"
1762            );
1763            UnaryFunc::try_cast_if_fallible(cast.clone())
1764        }));
1765        funcs
1766    }
1767
1768    fn interesting_binary_funcs() -> Vec<BinaryFunc> {
1769        vec![
1770            AddTimestampInterval.into(),
1771            AddNumeric.into(),
1772            SubNumeric.into(),
1773            MulNumeric.into(),
1774            DivNumeric.into(),
1775            AddFloat64.into(),
1776            SubFloat64.into(),
1777            MulFloat64.into(),
1778            DivFloat64.into(),
1779            MulFloat32.into(),
1780            DivFloat32.into(),
1781            RoundNumericBinary.into(),
1782            Eq.into(),
1783            Lt.into(),
1784            Gt.into(),
1785            Lte.into(),
1786            Gte.into(),
1787            DateTruncUnitsTimestamp.into(),
1788            JsonbGetString.into(),
1789            JsonbGetStringStringify.into(),
1790            // Declared-monotone integer arithmetic: overflow and
1791            // division-by-zero are interior error conditions the endpoints
1792            // need not reveal.
1793            AddInt32.into(),
1794            SubInt32.into(),
1795            MulInt32.into(),
1796            DivInt32.into(),
1797            AddInt64.into(),
1798            MulInt64.into(),
1799            AddFloat32.into(),
1800            SubFloat32.into(),
1801            // Monotone in the right argument only.
1802            TextConcatBinary.into(),
1803            // Monotone left, and a declared non-monotone control.
1804            AddDateInterval.into(),
1805            AddTimeInterval.into(),
1806            // Batch 2: remaining ordered-domain arithmetic.
1807            SubInt64.into(),
1808            DivInt64.into(),
1809            SubTimestamp.into(),
1810            SubDate.into(),
1811            AddInterval.into(),
1812            SubInterval.into(),
1813            // Batch 3: the int16 and unsigned arithmetic families, remaining
1814            // date/time arithmetic, and binary date_bin.
1815            AddInt16.into(),
1816            SubInt16.into(),
1817            MulInt16.into(),
1818            DivInt16.into(),
1819            AddUint16.into(),
1820            SubUint16.into(),
1821            MulUint16.into(),
1822            DivUint16.into(),
1823            AddUint32.into(),
1824            SubUint32.into(),
1825            MulUint32.into(),
1826            DivUint32.into(),
1827            AddUint64.into(),
1828            SubUint64.into(),
1829            MulUint64.into(),
1830            DivUint64.into(),
1831            SubTime.into(),
1832            SubTimestampTz.into(),
1833            AddDateTime.into(),
1834            SubDateInterval.into(),
1835            DateBinTimestamp.into(),
1836        ]
1837    }
1838
1839    fn binary_typecheck(func: &BinaryFunc, arg0: &ReprColumnType, arg1: &ReprColumnType) -> bool {
1840        use BinaryFunc::*;
1841        match func {
1842            AddTimestampInterval(_) => {
1843                arg0.scalar_type == ReprScalarType::Timestamp
1844                    && arg1.scalar_type == ReprScalarType::Interval
1845            }
1846            AddNumeric(_) | SubNumeric(_) | MulNumeric(_) | DivNumeric(_) => {
1847                arg0.scalar_type == NUM_TYPE && arg1.scalar_type == NUM_TYPE
1848            }
1849            AddFloat64(_) | SubFloat64(_) | MulFloat64(_) | DivFloat64(_) => {
1850                arg0.scalar_type == ReprScalarType::Float64
1851                    && arg1.scalar_type == ReprScalarType::Float64
1852            }
1853            MulFloat32(_) | DivFloat32(_) => {
1854                arg0.scalar_type == ReprScalarType::Float32
1855                    && arg1.scalar_type == ReprScalarType::Float32
1856            }
1857            RoundNumeric(_) => {
1858                arg0.scalar_type == NUM_TYPE && arg1.scalar_type == ReprScalarType::Int32
1859            }
1860            Eq(_) | Lt(_) | Gt(_) | Lte(_) | Gte(_) => arg0.scalar_type == arg1.scalar_type,
1861            DateTruncTimestamp(_) => {
1862                arg0.scalar_type == ReprScalarType::String
1863                    && arg1.scalar_type == ReprScalarType::Timestamp
1864            }
1865            JsonbGetString(_) | JsonbGetStringStringify(_) => {
1866                arg0.scalar_type == ReprScalarType::Jsonb
1867                    && arg1.scalar_type == ReprScalarType::String
1868            }
1869            AddInt32(_) | SubInt32(_) | MulInt32(_) | DivInt32(_) => {
1870                arg0.scalar_type == ReprScalarType::Int32
1871                    && arg1.scalar_type == ReprScalarType::Int32
1872            }
1873            AddInt64(_) | MulInt64(_) | SubInt64(_) | DivInt64(_) => {
1874                arg0.scalar_type == ReprScalarType::Int64
1875                    && arg1.scalar_type == ReprScalarType::Int64
1876            }
1877            SubTimestamp(_) => {
1878                arg0.scalar_type == ReprScalarType::Timestamp
1879                    && arg1.scalar_type == ReprScalarType::Timestamp
1880            }
1881            SubDate(_) => {
1882                arg0.scalar_type == ReprScalarType::Date && arg1.scalar_type == ReprScalarType::Date
1883            }
1884            AddInterval(_) | SubInterval(_) => {
1885                arg0.scalar_type == ReprScalarType::Interval
1886                    && arg1.scalar_type == ReprScalarType::Interval
1887            }
1888            AddInt16(_) | SubInt16(_) | MulInt16(_) | DivInt16(_) => {
1889                arg0.scalar_type == ReprScalarType::Int16
1890                    && arg1.scalar_type == ReprScalarType::Int16
1891            }
1892            AddUint16(_) | SubUint16(_) | MulUint16(_) | DivUint16(_) => {
1893                arg0.scalar_type == ReprScalarType::UInt16
1894                    && arg1.scalar_type == ReprScalarType::UInt16
1895            }
1896            AddUint32(_) | SubUint32(_) | MulUint32(_) | DivUint32(_) => {
1897                arg0.scalar_type == ReprScalarType::UInt32
1898                    && arg1.scalar_type == ReprScalarType::UInt32
1899            }
1900            AddUint64(_) | SubUint64(_) | MulUint64(_) | DivUint64(_) => {
1901                arg0.scalar_type == ReprScalarType::UInt64
1902                    && arg1.scalar_type == ReprScalarType::UInt64
1903            }
1904            SubTime(_) => {
1905                arg0.scalar_type == ReprScalarType::Time && arg1.scalar_type == ReprScalarType::Time
1906            }
1907            SubTimestampTz(_) => {
1908                arg0.scalar_type == ReprScalarType::TimestampTz
1909                    && arg1.scalar_type == ReprScalarType::TimestampTz
1910            }
1911            AddDateTime(_) => {
1912                arg0.scalar_type == ReprScalarType::Date && arg1.scalar_type == ReprScalarType::Time
1913            }
1914            SubDateInterval(_) => {
1915                arg0.scalar_type == ReprScalarType::Date
1916                    && arg1.scalar_type == ReprScalarType::Interval
1917            }
1918            DateBinTimestamp(_) => {
1919                arg0.scalar_type == ReprScalarType::Interval
1920                    && arg1.scalar_type == ReprScalarType::Timestamp
1921            }
1922            AddFloat32(_) | SubFloat32(_) => {
1923                arg0.scalar_type == ReprScalarType::Float32
1924                    && arg1.scalar_type == ReprScalarType::Float32
1925            }
1926            TextConcat(_) => {
1927                arg0.scalar_type == ReprScalarType::String
1928                    && arg1.scalar_type == ReprScalarType::String
1929            }
1930            AddDateInterval(_) => {
1931                arg0.scalar_type == ReprScalarType::Date
1932                    && arg1.scalar_type == ReprScalarType::Interval
1933            }
1934            AddTimeInterval(_) => {
1935                arg0.scalar_type == ReprScalarType::Time
1936                    && arg1.scalar_type == ReprScalarType::Interval
1937            }
1938            _ => false,
1939        }
1940    }
1941
1942    const INTERESTING_VARIADIC_FUNCS: &[VariadicFunc] = {
1943        use crate::scalar::func::variadic as v;
1944        use VariadicFunc::*;
1945        &[
1946            Coalesce(v::Coalesce),
1947            Greatest(v::Greatest),
1948            Least(v::Least),
1949            And(v::And),
1950            Or(v::Or),
1951            Concat(v::Concat),
1952            ConcatWs(v::ConcatWs),
1953        ]
1954    };
1955
1956    fn variadic_typecheck(func: &VariadicFunc, args: &[ReprColumnType]) -> bool {
1957        use VariadicFunc::*;
1958        fn all_eq<'a>(
1959            iter: impl IntoIterator<Item = &'a ReprColumnType>,
1960            other: &ReprScalarType,
1961        ) -> bool {
1962            iter.into_iter().all(|t| t.scalar_type == *other)
1963        }
1964        match func {
1965            Coalesce(_) | Greatest(_) | Least(_) => match args {
1966                [] => true,
1967                [first, rest @ ..] => all_eq(rest, &first.scalar_type),
1968            },
1969            And(_) | Or(_) => all_eq(args, &ReprScalarType::Bool),
1970            Concat(_) => all_eq(args, &ReprScalarType::String),
1971            ConcatWs(_) => args.len() > 1 && all_eq(args, &ReprScalarType::String),
1972            _ => false,
1973        }
1974    }
1975
1976    fn gen_datums_for_type(typ: &ReprColumnType) -> BoxedStrategy<Datum<'static>> {
1977        let mut values: Vec<Datum<'static>> = SqlScalarType::from_repr(&typ.scalar_type)
1978            .interesting_datums()
1979            .collect();
1980        if typ.nullable {
1981            values.push(Datum::Null)
1982        }
1983        select(values).boxed()
1984    }
1985
1986    fn gen_column() -> impl Strategy<Value = (ReprColumnType, Datum<'static>, ResultSpec<'static>)>
1987    {
1988        let col_type = (select(SCALAR_TYPES), any::<bool>())
1989            .prop_map(|(t, b)| t.nullable(b))
1990            .prop_filter("need at least one value", |c| {
1991                SqlScalarType::from_repr(&c.scalar_type)
1992                    .interesting_datums()
1993                    .count()
1994                    > 0
1995            });
1996
1997        let result_spec = select(vec![
1998            ResultSpec::nothing(),
1999            ResultSpec::null(),
2000            ResultSpec::anything(),
2001            ResultSpec::value_all(),
2002        ]);
2003
2004        (col_type, result_spec).prop_flat_map(|(col, result_spec)| {
2005            gen_datums_for_type(&col).prop_map(move |datum| {
2006                let result_spec = result_spec.clone().union(ResultSpec::value(datum));
2007                (col.clone(), datum, result_spec)
2008            })
2009        })
2010    }
2011
2012    fn gen_expr_for_relation(
2013        relation: &ReprRelationType,
2014    ) -> BoxedStrategy<(MirScalarExpr, ReprColumnType)> {
2015        let column_gen = {
2016            let column_types = relation.column_types.clone();
2017            any::<Index>()
2018                .prop_map(move |idx| {
2019                    let id = idx.index(column_types.len());
2020                    (MirScalarExpr::column(id), column_types[id].clone())
2021                })
2022                .boxed()
2023        };
2024
2025        let literal_gen = (select(SCALAR_TYPES), any::<bool>())
2026            .prop_map(|(s, b)| s.nullable(b))
2027            .prop_flat_map(|ct| {
2028                let error_gen = any::<EvalError>().prop_map(Err).boxed();
2029                let value_gen = gen_datums_for_type(&ct)
2030                    .prop_map(move |datum| Ok(Row::pack_slice(&[datum])))
2031                    .boxed();
2032                error_gen.prop_union(value_gen).prop_map(move |result| {
2033                    (MirScalarExpr::Literal(result, ct.clone()), ct.clone())
2034                })
2035            })
2036            .boxed();
2037
2038        column_gen
2039            .prop_union(literal_gen)
2040            .prop_recursive(4, 64, 8, |self_gen| {
2041                let unary_gen = (select(interesting_unary_funcs()), self_gen.clone())
2042                    .prop_filter_map("unary func", |(func, (expr_in, type_in))| {
2043                        if !unary_typecheck(&func, &type_in) {
2044                            return None;
2045                        }
2046                        let type_out = func.output_type(type_in);
2047                        let expr_out = MirScalarExpr::CallUnary {
2048                            func,
2049                            expr: Box::new(expr_in),
2050                        };
2051                        Some((expr_out, type_out))
2052                    })
2053                    .boxed();
2054                let binary_gen = (
2055                    select(interesting_binary_funcs()),
2056                    self_gen.clone(),
2057                    self_gen.clone(),
2058                )
2059                    .prop_filter_map(
2060                        "binary func",
2061                        |(func, (expr_left, type_left), (expr_right, type_right))| {
2062                            if !binary_typecheck(&func, &type_left, &type_right) {
2063                                return None;
2064                            }
2065                            let type_out = func.output_type(&[type_left, type_right]);
2066                            let expr_out = MirScalarExpr::CallBinary {
2067                                func,
2068                                expr1: Box::new(expr_left),
2069                                expr2: Box::new(expr_right),
2070                            };
2071                            Some((expr_out, type_out))
2072                        },
2073                    )
2074                    .boxed();
2075                let variadic_gen = (
2076                    select(INTERESTING_VARIADIC_FUNCS),
2077                    prop::collection::vec(self_gen.clone(), 1..4),
2078                )
2079                    .prop_filter_map("variadic func", |(func, exprs)| {
2080                        let (exprs_in, type_in): (_, Vec<_>) = exprs.into_iter().unzip();
2081                        if !variadic_typecheck(&func, &type_in) {
2082                            return None;
2083                        }
2084                        let type_out = func.output_type(type_in);
2085                        let expr_out = MirScalarExpr::CallVariadic {
2086                            func,
2087                            exprs: exprs_in,
2088                        };
2089                        Some((expr_out, type_out))
2090                    })
2091                    .boxed();
2092                // Generate `If` nodes without the heavy rejection that filtering
2093                // three independent subexprs for a bool condition and matching
2094                // branch types would incur. The condition is a boolean literal
2095                // (so it can be `True`, `False`, or `Null` — exercising `cond`'s
2096                // value channel, including the null-takes-`els` path), and `els`
2097                // is a literal of `then`'s type so the branches always unify.
2098                let if_gen = {
2099                    let bool_type = ReprScalarType::Bool.nullable(true);
2100                    let cond_gen = gen_datums_for_type(&bool_type).prop_map(move |datum| {
2101                        MirScalarExpr::Literal(Ok(Row::pack_slice(&[datum])), bool_type.clone())
2102                    });
2103                    (cond_gen, self_gen.clone())
2104                        .prop_flat_map(|(cond_expr, (then_expr, then_type))| {
2105                            let out_type = then_type.clone();
2106                            gen_datums_for_type(&then_type).prop_map(move |datum| {
2107                                let els_expr = MirScalarExpr::Literal(
2108                                    Ok(Row::pack_slice(&[datum])),
2109                                    out_type.clone(),
2110                                );
2111                                let expr_out = MirScalarExpr::If {
2112                                    cond: Box::new(cond_expr.clone()),
2113                                    then: Box::new(then_expr.clone()),
2114                                    els: Box::new(els_expr),
2115                                };
2116                                (expr_out, out_type.clone())
2117                            })
2118                        })
2119                        .boxed()
2120                };
2121
2122                unary_gen
2123                    .prop_union(binary_gen)
2124                    .boxed()
2125                    .prop_union(variadic_gen)
2126                    .boxed()
2127                    .prop_union(if_gen)
2128            })
2129            .boxed()
2130    }
2131
2132    fn gen_expr_data() -> impl Strategy<Value = ExpressionData> {
2133        let columns = prop::collection::vec(gen_column(), 1..10);
2134        columns.prop_flat_map(|data| {
2135            let (columns, datums, specs): (Vec<_>, Vec<_>, Vec<_>) = data.into_iter().multiunzip();
2136            let relation = ReprRelationType::new(columns);
2137            let row = Row::pack_slice(&datums);
2138            gen_expr_for_relation(&relation).prop_map(move |(expr, _)| ExpressionData {
2139                relation_type: relation.clone(),
2140                specs: specs.clone(),
2141                rows: vec![row.clone()],
2142                expr,
2143            })
2144        })
2145    }
2146
2147    #[mz_ore::test]
2148    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2149    fn test_trivial_spec_matches() {
2150        fn check(datum: PropDatum) -> Result<(), TestCaseError> {
2151            let datum: Datum = (&datum).into();
2152            let spec = if datum.is_null() {
2153                ResultSpec::null()
2154            } else {
2155                ResultSpec::value(datum)
2156            };
2157            assert!(spec.may_contain(datum));
2158            Ok(())
2159        }
2160
2161        proptest!(|(datum in mz_repr::arb_datum(true))| {
2162            check(datum)?;
2163        });
2164
2165        assert!(ResultSpec::fails().may_fail());
2166    }
2167
2168    #[mz_ore::test]
2169    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2170    fn test_equivalence() {
2171        fn check(data: ExpressionData) -> Result<(), TestCaseError> {
2172            let ExpressionData {
2173                relation_type,
2174                specs,
2175                rows,
2176                expr,
2177            } = data;
2178
2179            // We want to ensure that the spec we get when evaluating an expression using
2180            // `ColumnSpecs` always contains the _actual_ value of that column when evaluated with
2181            // eval. (This is an important correctness property of abstract interpretation.)
2182            let arena = RowArena::new();
2183            let mut interpreter = ColumnSpecs::new(&relation_type, &arena);
2184            for (id, spec) in specs.into_iter().enumerate() {
2185                interpreter.push_column(id, spec);
2186            }
2187
2188            let spec = interpreter.expr(&expr);
2189
2190            for row in &rows {
2191                let datums: Vec<_> = row.iter().collect();
2192                let eval_result = expr.eval(&datums, &arena);
2193                match eval_result {
2194                    Ok(value) => {
2195                        assert!(spec.range.may_contain(value))
2196                    }
2197                    Err(_) => {
2198                        assert!(spec.range.may_fail());
2199                    }
2200                }
2201            }
2202
2203            Ok(())
2204        }
2205
2206        proptest!(|(data in gen_expr_data())| {
2207            check(data)?;
2208        });
2209    }
2210
2211    /// A column whose spec is a genuine `value_between(lo, hi)` range with
2212    /// `lo < hi`, paired with a concrete row value `mid` drawn from strictly
2213    /// inside `[lo, hi]`. This is the shape persist filter pushdown actually
2214    /// feeds the interpreter: min/max stats become a `Values::Within` range,
2215    /// and the interpreter narrows it through each function (relying on
2216    /// monotonicity) without ever seeing the interior values. `gen_column`
2217    /// only ever produces single-value or `anything` specs, so it never
2218    /// exercises the range-narrowing path.
2219    fn gen_range_column()
2220    -> impl Strategy<Value = (ReprColumnType, Datum<'static>, ResultSpec<'static>)> {
2221        select(SCALAR_TYPES)
2222            .prop_map(|t| t.nullable(false))
2223            .prop_filter("need at least two distinct values for a range", |c| {
2224                let mut datums: Vec<Datum> = SqlScalarType::from_repr(&c.scalar_type)
2225                    .interesting_datums()
2226                    .filter(|d| !d.is_null())
2227                    .collect();
2228                datums.sort();
2229                datums.dedup();
2230                datums.len() >= 2
2231            })
2232            .prop_flat_map(|col| {
2233                let mut datums: Vec<Datum<'static>> = SqlScalarType::from_repr(&col.scalar_type)
2234                    .interesting_datums()
2235                    .filter(|d| !d.is_null())
2236                    .collect();
2237                datums.sort();
2238                datums.dedup();
2239                (
2240                    Just(col),
2241                    Just(datums),
2242                    any::<Index>(),
2243                    any::<Index>(),
2244                    any::<Index>(),
2245                )
2246                    .prop_map(|(col, datums, a, b, c)| {
2247                        let n = datums.len();
2248                        let mut idxs = [a.index(n), b.index(n), c.index(n)];
2249                        idxs.sort();
2250                        let lo = datums[idxs[0]];
2251                        let mid = datums[idxs[1]];
2252                        let hi = datums[idxs[2]];
2253                        let spec = ResultSpec::value_between(lo, hi);
2254                        (col, mid, spec)
2255                    })
2256            })
2257    }
2258
2259    fn gen_range_expr_data() -> impl Strategy<Value = ExpressionData> {
2260        let columns = prop::collection::vec(gen_range_column(), 1..10);
2261        columns.prop_flat_map(|data| {
2262            let (columns, datums, specs): (Vec<_>, Vec<_>, Vec<_>) = data.into_iter().multiunzip();
2263            let relation = ReprRelationType::new(columns);
2264            let row = Row::pack_slice(&datums);
2265            gen_expr_for_relation(&relation).prop_map(move |(expr, _)| ExpressionData {
2266                relation_type: relation.clone(),
2267                specs: specs.clone(),
2268                rows: vec![row.clone()],
2269                expr,
2270            })
2271        })
2272    }
2273
2274    /// Regression test for database-issues#9656 (PER-50).
2275    ///
2276    /// Like [`test_equivalence`], but the column specs are genuine
2277    /// `value_between(lo, hi)` ranges rather than single values. This is the
2278    /// input shape persist filter pushdown produces from min/max stats, and it
2279    /// is the one that drives the interpreter's monotonicity-based range
2280    /// narrowing. If a function narrows a range to a spec that does not contain
2281    /// the value the concrete evaluator produces for an interior input, the
2282    /// interpreter can wrongly rule out a matching row and pushdown discards a
2283    /// part it should have kept, triggering the audit panic.
2284    #[mz_ore::test]
2285    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2286    fn test_equivalence_ranges() {
2287        fn check(data: ExpressionData) -> Result<(), TestCaseError> {
2288            let ExpressionData {
2289                relation_type,
2290                specs,
2291                rows,
2292                expr,
2293            } = data;
2294
2295            let arena = RowArena::new();
2296            let mut interpreter = ColumnSpecs::new(&relation_type, &arena);
2297            for (id, spec) in specs.into_iter().enumerate() {
2298                interpreter.push_column(id, spec);
2299            }
2300
2301            let spec = interpreter.expr(&expr);
2302
2303            for row in &rows {
2304                let datums: Vec<_> = row.iter().collect();
2305                let eval_result = expr.eval(&datums, &arena);
2306                match eval_result {
2307                    Ok(value) => {
2308                        prop_assert!(
2309                            spec.range.may_contain(value),
2310                            "interpreter ruled out a value the evaluator produced \
2311                             for an interior input: expr={expr:?} row={row:?} \
2312                             value={value:?} spec={:?}",
2313                            spec.range,
2314                        );
2315                    }
2316                    Err(_) => {
2317                        prop_assert!(
2318                            spec.range.may_fail(),
2319                            "interpreter ruled out an error the evaluator produced \
2320                             for an interior input: expr={expr:?} row={row:?}",
2321                        );
2322                    }
2323                }
2324            }
2325
2326            Ok(())
2327        }
2328
2329        // The expression generator rejects many function/type combinations
2330        // (see the `prop_filter_map`s in `gen_expr_for_relation`), so the
2331        // per-run local-reject budget has to be raised well above proptest's
2332        // default to let enough cases through.
2333        // An explicit PROPTEST_CASES (already parsed into the default config)
2334        // wins, for long local or nightly runs. The generator rejects at a
2335        // roughly fixed rate per case, so the reject budget scales with the
2336        // case count.
2337        let default = ProptestConfig::default();
2338        let cases = if std::env::var_os("PROPTEST_CASES").is_some() {
2339            default.cases
2340        } else {
2341            2048
2342        };
2343        let config = ProptestConfig {
2344            cases,
2345            max_local_rejects: cases.saturating_mul(512),
2346            ..default
2347        };
2348        proptest!(config, |(data in gen_range_expr_data())| {
2349            check(data)?;
2350        });
2351    }
2352
2353    /// The abstract-domain lattice laws `ColumnSpecs` relies on: `union` must
2354    /// over-approximate (contain everything either operand contains), and
2355    /// `intersect` must contain every value BOTH operands contain. An
2356    /// intersect-law violation is a false negative — a value the interpreter
2357    /// silently drops. The interpreter forms straddling `Within` ranges
2358    /// internally (e.g. `Values::union` of differently-typed endpoints in `cond`
2359    /// branches or `eq`), so this is not purely hypothetical. See
2360    /// database-issues#9656.
2361    #[mz_ore::test]
2362    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2363    fn test_result_spec_lattice_laws() {
2364        // A recipe for a `ResultSpec`, carrying owned `PropDatum`s so the spec
2365        // (which borrows `Datum`s) can be materialized inside the test.
2366        #[derive(Debug, Clone)]
2367        enum Recipe {
2368            Nothing,
2369            Null,
2370            Fails,
2371            Anything,
2372            ValueAll,
2373            Value(PropDatum),
2374            Between(PropDatum, PropDatum),
2375            Map(Vec<(PropDatum, Recipe)>),
2376            Union(Box<Recipe>, Box<Recipe>),
2377        }
2378
2379        fn materialize(recipe: &Recipe) -> ResultSpec<'_> {
2380            match recipe {
2381                Recipe::Nothing => ResultSpec::nothing(),
2382                Recipe::Null => ResultSpec::null(),
2383                Recipe::Fails => ResultSpec::fails(),
2384                Recipe::Anything => ResultSpec::anything(),
2385                Recipe::ValueAll => ResultSpec::value_all(),
2386                Recipe::Value(pd) => ResultSpec::value(pd.into()),
2387                Recipe::Between(a, b) => {
2388                    let (a, b): (Datum, Datum) = (a.into(), b.into());
2389                    if a.is_null() || b.is_null() {
2390                        ResultSpec::nothing()
2391                    } else if a <= b {
2392                        ResultSpec::value_between(a, b)
2393                    } else {
2394                        ResultSpec::value_between(b, a)
2395                    }
2396                }
2397                Recipe::Map(entries) => {
2398                    let mut map = BTreeMap::new();
2399                    for (key, val) in entries {
2400                        let key: Datum = key.into();
2401                        if !key.is_null() {
2402                            map.insert(key, materialize(val));
2403                        }
2404                    }
2405                    ResultSpec::map_spec(map)
2406                }
2407                Recipe::Union(a, b) => materialize(a).union(materialize(b)),
2408            }
2409        }
2410
2411        fn recipe_strategy() -> impl Strategy<Value = Recipe> {
2412            let leaf = proptest::strategy::Union::new(vec![
2413                Just(Recipe::Nothing).boxed(),
2414                Just(Recipe::Null).boxed(),
2415                Just(Recipe::Fails).boxed(),
2416                Just(Recipe::Anything).boxed(),
2417                Just(Recipe::ValueAll).boxed(),
2418                mz_repr::arb_datum(false).prop_map(Recipe::Value).boxed(),
2419                (mz_repr::arb_datum(false), mz_repr::arb_datum(false))
2420                    .prop_map(|(a, b)| Recipe::Between(a, b))
2421                    .boxed(),
2422            ]);
2423            leaf.prop_recursive(3, 24, 4, |inner| {
2424                proptest::strategy::Union::new(vec![
2425                    prop::collection::vec((mz_repr::arb_datum(false), inner.clone()), 0..3)
2426                        .prop_map(Recipe::Map)
2427                        .boxed(),
2428                    (inner.clone(), inner.clone())
2429                        .prop_map(|(a, b)| Recipe::Union(Box::new(a), Box::new(b)))
2430                        .boxed(),
2431                ])
2432            })
2433        }
2434
2435        fn check(a: Recipe, b: Recipe, v: PropDatum) -> Result<(), TestCaseError> {
2436            let a_spec = materialize(&a);
2437            let b_spec = materialize(&b);
2438            let v: Datum = (&v).into();
2439
2440            let in_a = a_spec.may_contain(v);
2441            let in_b = b_spec.may_contain(v);
2442
2443            if in_a || in_b {
2444                prop_assert!(
2445                    a_spec.clone().union(b_spec.clone()).may_contain(v),
2446                    "union dropped a value: a={a:?} b={b:?} v={v:?}",
2447                );
2448            }
2449            if in_a && in_b {
2450                prop_assert!(
2451                    a_spec.intersect(b_spec).may_contain(v),
2452                    "intersect dropped a common value: a={a:?} b={b:?} v={v:?}",
2453                );
2454            }
2455            Ok(())
2456        }
2457
2458        proptest!(
2459            ProptestConfig::with_cases(4096),
2460            |(a in recipe_strategy(), b in recipe_strategy(), v in mz_repr::arb_datum(true))| {
2461                check(a, b, v)?;
2462            }
2463        );
2464    }
2465
2466    /// Deterministic regression test for database-issues#9656 (PER-50), the
2467    /// minimal case [`test_equivalence_ranges`] shrinks to.
2468    ///
2469    /// A numeric column whose stats range spans `[-Infinity, NaN]` (NaN is the
2470    /// maximum of the numeric Datum order) feeds `-column`. `NegNumeric` is
2471    /// declared monotone, so the interpreter would narrow the output to
2472    /// `[neg(-Infinity), neg(NaN)] = [Infinity, NaN]` and wrongly rule out the
2473    /// value `1` that the evaluator produces for the interior input `-1`. That
2474    /// false negative is exactly what makes persist filter pushdown discard a
2475    /// part it should keep, tripping the audit panic.
2476    #[mz_ore::test]
2477    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2478    fn test_neg_numeric_nan_range() {
2479        use mz_repr::adt::numeric::Numeric;
2480
2481        let neg = MirScalarExpr::CallUnary {
2482            func: UnaryFunc::NegNumeric(NegNumeric),
2483            expr: Box::new(MirScalarExpr::column(0)),
2484        };
2485
2486        let relation = ReprRelationType::new(vec![ReprScalarType::Numeric.nullable(false)]);
2487        let arena = RowArena::new();
2488        let mut interpreter = ColumnSpecs::new(&relation, &arena);
2489        interpreter.push_column(
2490            0,
2491            ResultSpec::value_between(
2492                Datum::from(Numeric::from(f64::NEG_INFINITY)),
2493                Datum::from(Numeric::from(f64::NAN)),
2494            ),
2495        );
2496
2497        let spec = interpreter.expr(&neg);
2498
2499        // `-1` is an interior value of the input range, and `-(-1) = 1`.
2500        let actual = neg
2501            .eval(&[Datum::from(Numeric::from(-1.0f64))], &arena)
2502            .expect("eval succeeds");
2503        assert!(
2504            spec.range.may_contain(actual),
2505            "interpreter must not rule out {actual:?}, which the evaluator \
2506             produces for an interior input; got spec {:?}",
2507            spec.range,
2508        );
2509    }
2510
2511    /// Deterministic regression test for database-issues#9656 (PER-50), the
2512    /// fallibility variant [`test_equivalence_ranges`] also surfaces.
2513    ///
2514    /// `cast_numeric_to_mz_timestamp` is declared monotone but errors on
2515    /// fractional inputs, which are dense in the interior of any range. The
2516    /// range `[0, 2]` has integer endpoints that both cast cleanly, so the
2517    /// interpreter's endpoint sampling never observes an error. It must instead
2518    /// surface the function's own `could_error`, otherwise persist filter
2519    /// pushdown discards a part whose interior rows (e.g. `1.5`) produce error
2520    /// rows.
2521    #[mz_ore::test]
2522    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
2523    fn test_fallible_monotone_interior_error() {
2524        use mz_repr::adt::numeric::Numeric;
2525
2526        let cast = MirScalarExpr::CallUnary {
2527            func: UnaryFunc::CastNumericToMzTimestamp(CastNumericToMzTimestamp),
2528            expr: Box::new(MirScalarExpr::column(0)),
2529        };
2530
2531        let relation = ReprRelationType::new(vec![ReprScalarType::Numeric.nullable(false)]);
2532        let arena = RowArena::new();
2533        let mut interpreter = ColumnSpecs::new(&relation, &arena);
2534        interpreter.push_column(
2535            0,
2536            ResultSpec::value_between(
2537                Datum::from(Numeric::from(0.0f64)),
2538                Datum::from(Numeric::from(2.0f64)),
2539            ),
2540        );
2541
2542        let spec = interpreter.expr(&cast);
2543
2544        // `1.5` is an interior value of `[0, 2]`, and casting a fractional
2545        // numeric to mz_timestamp errors.
2546        let interior = Datum::from(Numeric::from(1.5f64));
2547        assert!(
2548            cast.eval(&[interior], &arena).is_err(),
2549            "precondition: a fractional numeric fails to cast to mz_timestamp",
2550        );
2551        assert!(
2552            spec.range.may_fail(),
2553            "interpreter must surface that a monotone-but-fallible function may \
2554             error on an interior value it never sampled; got spec {:?}",
2555            spec.range,
2556        );
2557    }
2558
2559    /// Regression test for database-issues#9656.
2560    ///
2561    /// The interpreter must surface the fallibility of MFP expressions that
2562    /// aren't referenced by any predicate or temporal bound. The runtime MFP
2563    /// evaluator runs every expression once predicates pass, so an expression
2564    /// that errors on the actual data makes the whole row an `Err` — and
2565    /// `filter_result` must keep the part to emit that error.
2566    #[mz_ore::test]
2567    #[cfg_attr(miri, ignore)]
2568    fn test_mfp_unreferenced_fallible_expression() {
2569        use crate::scalar::func::CastStringToUuid;
2570
2571        // MFP: one expression that always errors on the input range, and one
2572        // predicate that always passes. The expression's result column is
2573        // *not* referenced by the predicate, so the default interpreter
2574        // implementation would AND together just `True` and miss the
2575        // fallibility.
2576        let mfp = MapFilterProject {
2577            expressions: vec![MirScalarExpr::CallUnary {
2578                func: UnaryFunc::CastStringToUuid(CastStringToUuid),
2579                expr: Box::new(MirScalarExpr::column(0)),
2580            }],
2581            predicates: vec![(
2582                1,
2583                MirScalarExpr::literal_ok(Datum::True, ReprScalarType::Bool),
2584            )],
2585            projection: vec![0, 1],
2586            input_arity: 1,
2587        };
2588
2589        let relation = ReprRelationType::new(vec![ReprScalarType::String.nullable(false)]);
2590        let arena = RowArena::new();
2591        let mut interpreter = ColumnSpecs::new(&relation, &arena);
2592        // "not-a-uuid" is in the stats range and definitely doesn't parse as a UUID.
2593        interpreter.push_column(
2594            0,
2595            ResultSpec::value_between(Datum::String("not-a-uuid"), Datum::String("not-a-uuid")),
2596        );
2597        let spec = interpreter.mfp_filter(&mfp);
2598        assert!(
2599            spec.range.may_fail(),
2600            "an MFP expression that errors on the stats range must propagate \
2601             fallibility, otherwise persist filter pushdown can wrongly discard \
2602             a part that produces error rows",
2603        );
2604    }
2605
2606    /// Proptest companion to [`test_mfp_unreferenced_fallible_expression`]:
2607    /// directly verifies the fallibility claim of [`ColumnSpecs::mfp_filter`]
2608    /// against the runtime MFP semantics. For a random expression placed in
2609    /// `MapFilterProject::expressions` (i.e. as an unreferenced Map step), if
2610    /// evaluating the expression on a row drawn from the stats range produces
2611    /// an error at runtime, then the interpreter's summary must report
2612    /// `may_fail()`. Without the `expressions.any(|s| s.range.fallible)` patch
2613    /// in `mfp_filter`, the AND over an empty predicate list collapses to
2614    /// `True` and the runtime error is wrongly ruled out.
2615    #[mz_ore::test]
2616    #[cfg_attr(miri, ignore)]
2617    fn test_mfp_filter_fallibility_equivalence() {
2618        fn check(data: ExpressionData) -> Result<(), TestCaseError> {
2619            let ExpressionData {
2620                relation_type,
2621                specs,
2622                rows,
2623                expr,
2624            } = data;
2625
2626            let input_arity = relation_type.column_types.len();
2627            let mfp = MapFilterProject {
2628                expressions: vec![expr.clone()],
2629                predicates: vec![],
2630                projection: (0..input_arity).collect(),
2631                input_arity,
2632            };
2633
2634            let arena = RowArena::new();
2635            let mut interpreter = ColumnSpecs::new(&relation_type, &arena);
2636            for (id, spec) in specs.into_iter().enumerate() {
2637                interpreter.push_column(id, spec);
2638            }
2639            let summary = interpreter.mfp_filter(&mfp);
2640
2641            for row in &rows {
2642                let datums: Vec<_> = row.iter().collect();
2643                if expr.eval(&datums, &arena).is_err() {
2644                    prop_assert!(
2645                        summary.range.may_fail(),
2646                        "mfp_filter must surface the fallibility of an \
2647                         unreferenced MFP expression: row {:?} errored at \
2648                         runtime but the interpreter ruled out errors",
2649                        row,
2650                    );
2651                }
2652            }
2653            Ok(())
2654        }
2655
2656        proptest!(|(data in gen_expr_data())| {
2657            check(data)?;
2658        });
2659    }
2660
2661    #[mz_ore::test]
2662    fn test_mfp() {
2663        // Regression test for https://github.com/MaterializeInc/database-issues/issues/5736
2664        use MirScalarExpr::*;
2665
2666        let mfp = MapFilterProject {
2667            expressions: vec![],
2668            predicates: vec![
2669                // Always fails on the known input range
2670                (
2671                    1,
2672                    CallUnary {
2673                        func: UnaryFunc::IsNull(IsNull),
2674                        expr: Box::new(CallBinary {
2675                            func: MulInt32.into(),
2676                            expr1: Box::new(MirScalarExpr::column(0)),
2677                            expr2: Box::new(MirScalarExpr::column(0)),
2678                        }),
2679                    },
2680                ),
2681                // Always returns false on the known input range
2682                (
2683                    1,
2684                    CallBinary {
2685                        func: Eq.into(),
2686                        expr1: Box::new(MirScalarExpr::column(0)),
2687                        expr2: Box::new(MirScalarExpr::literal_ok(
2688                            Datum::Int32(1727694505),
2689                            ReprScalarType::Int32,
2690                        )),
2691                    },
2692                ),
2693            ],
2694            projection: vec![],
2695            input_arity: 1,
2696        };
2697
2698        let relation = ReprRelationType::new(vec![ReprScalarType::Int32.nullable(true)]);
2699        let arena = RowArena::new();
2700        let mut interpreter = ColumnSpecs::new(&relation, &arena);
2701        interpreter.push_column(0, ResultSpec::value(Datum::Int32(-1294725158)));
2702        let spec = interpreter.mfp_filter(&mfp);
2703        assert!(spec.range.may_fail());
2704    }
2705
2706    #[mz_ore::test]
2707    fn test_concat() {
2708        let expr = MirScalarExpr::call_variadic(
2709            Concat,
2710            vec![
2711                MirScalarExpr::column(0),
2712                MirScalarExpr::literal_ok(Datum::String("a"), ReprScalarType::String),
2713                MirScalarExpr::literal_ok(Datum::String("b"), ReprScalarType::String),
2714            ],
2715        );
2716
2717        let relation = ReprRelationType::new(vec![ReprScalarType::String.nullable(false)]);
2718        let arena = RowArena::new();
2719        let interpreter = ColumnSpecs::new(&relation, &arena);
2720        let spec = interpreter.expr(&expr);
2721        assert!(spec.range.may_contain(Datum::String("blab")));
2722    }
2723
2724    #[mz_ore::test]
2725    fn test_eval_range() {
2726        // Example inspired by the tumbling windows temporal filter in the docs.
2727        //
2728        // NOTE: `may_fail()` is `true` in both cases below. `DivInt64`,
2729        // `MulInt64`, and `CastInt64ToMzTimestamp` can all error, and the
2730        // interpreter no longer infers infallibility from endpoint sampling for
2731        // an erroring function over a multi-valued range (it cannot prove the
2732        // function doesn't error on an interior value). For this data none of
2733        // them actually errors, so this is a conservative over-approximation
2734        // that keeps the part rather than pruning it. The value channel is still
2735        // narrowed precisely (`may_contain` below is exact), so a follow-up that
2736        // makes the fallibility flag argument-aware could recover pruning here.
2737        let period_ms = MirScalarExpr::literal_ok(Datum::Int64(10), ReprScalarType::Int64);
2738        let expr = MirScalarExpr::CallBinary {
2739            func: Gte.into(),
2740            expr1: Box::new(MirScalarExpr::CallUnmaterializable(
2741                UnmaterializableFunc::MzNow,
2742            )),
2743            expr2: Box::new(MirScalarExpr::CallUnary {
2744                func: UnaryFunc::CastInt64ToMzTimestamp(CastInt64ToMzTimestamp),
2745                expr: Box::new(MirScalarExpr::CallBinary {
2746                    func: MulInt64.into(),
2747                    expr1: Box::new(period_ms.clone()),
2748                    expr2: Box::new(MirScalarExpr::CallBinary {
2749                        func: DivInt64.into(),
2750                        expr1: Box::new(MirScalarExpr::column(0)),
2751                        expr2: Box::new(period_ms),
2752                    }),
2753                }),
2754            }),
2755        };
2756        let relation = ReprRelationType::new(vec![ReprScalarType::Int64.nullable(false)]);
2757
2758        {
2759            // Non-overlapping windows
2760            let arena = RowArena::new();
2761            let mut interpreter = ColumnSpecs::new(&relation, &arena);
2762            interpreter.push_unmaterializable(
2763                UnmaterializableFunc::MzNow,
2764                ResultSpec::value_between(
2765                    Datum::MzTimestamp(10.into()),
2766                    Datum::MzTimestamp(20.into()),
2767                ),
2768            );
2769            interpreter.push_column(0, ResultSpec::value_between(30i64.into(), 40i64.into()));
2770
2771            let range_out = interpreter.expr(&expr).range;
2772            assert!(range_out.may_contain(Datum::False));
2773            assert!(!range_out.may_contain(Datum::True));
2774            assert!(!range_out.may_contain(Datum::Null));
2775            assert!(range_out.may_fail());
2776        }
2777
2778        {
2779            // Overlapping windows
2780            let arena = RowArena::new();
2781            let mut interpreter = ColumnSpecs::new(&relation, &arena);
2782            interpreter.push_unmaterializable(
2783                UnmaterializableFunc::MzNow,
2784                ResultSpec::value_between(
2785                    Datum::MzTimestamp(10.into()),
2786                    Datum::MzTimestamp(35.into()),
2787                ),
2788            );
2789            interpreter.push_column(0, ResultSpec::value_between(30i64.into(), 40i64.into()));
2790
2791            let range_out = interpreter.expr(&expr).range;
2792            assert!(range_out.may_contain(Datum::False));
2793            assert!(range_out.may_contain(Datum::True));
2794            assert!(!range_out.may_contain(Datum::Null));
2795            assert!(range_out.may_fail());
2796        }
2797    }
2798
2799    #[mz_ore::test]
2800    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `decNumberFromInt32` on OS `linux`
2801    fn test_jsonb() {
2802        let arena = RowArena::new();
2803
2804        let expr = MirScalarExpr::column(0)
2805            .call_binary(
2806                MirScalarExpr::literal_ok(Datum::from("ts"), ReprScalarType::String),
2807                JsonbGetString,
2808            )
2809            .call_unary(CastJsonbToNumeric(None));
2810
2811        let relation = ReprRelationType::new(vec![ReprScalarType::Jsonb.nullable(true)]);
2812        let mut interpreter = ColumnSpecs::new(&relation, &arena);
2813        interpreter.push_column(
2814            0,
2815            ResultSpec::map_spec(
2816                [(
2817                    "ts".into(),
2818                    ResultSpec::value_between(
2819                        Datum::Numeric(100.into()),
2820                        Datum::Numeric(300.into()),
2821                    ),
2822                )]
2823                .into_iter()
2824                .collect(),
2825            ),
2826        );
2827
2828        let range_out = interpreter.expr(&expr).range;
2829        assert!(!range_out.may_contain(Datum::Numeric(0.into())));
2830        assert!(range_out.may_contain(Datum::Numeric(200.into())));
2831        assert!(!range_out.may_contain(Datum::Numeric(400.into())));
2832    }
2833
2834    #[mz_ore::test]
2835    fn test_unbounded_call_is_opaque() {
2836        let arena = RowArena::new();
2837
2838        // Evaluating the call would give `2`, and rule out every other value.
2839        let expr = MirScalarExpr::literal_ok(Datum::Numeric(1.into()), ReprScalarType::Jsonb)
2840            .call_unary(Jq(JqProgram::new(". + 1").expect("valid program")));
2841
2842        let relation = ReprRelationType::new(vec![]);
2843        let interpreter = ColumnSpecs::new(&relation, &arena);
2844
2845        let range_out = interpreter.expr(&expr).range;
2846        assert!(range_out.may_contain(Datum::Numeric(3.into())));
2847        assert_eq!(super::Trace.expr(&expr), TraceSummary::Unknown);
2848    }
2849
2850    #[mz_ore::test]
2851    fn test_nested_union_partial_overlap() {
2852        // `Nested(map)` constrains a key only when the key is present in `map`; absent
2853        // keys mean "anything". So the union of two Nested specs must drop any key
2854        // that's missing from one side, because `x ∪ anything = anything`. Only keys
2855        // present in *both* sides survive (with their per-key specs unioned).
2856        let a = ResultSpec::map_spec(
2857            [
2858                ("x".into(), ResultSpec::value(Datum::String("a"))),
2859                ("y".into(), ResultSpec::value(Datum::String("b"))),
2860                ("c".into(), ResultSpec::value(Datum::String("c"))),
2861            ]
2862            .into_iter()
2863            .collect(),
2864        );
2865        let b = ResultSpec::map_spec(
2866            [
2867                ("x".into(), ResultSpec::value(Datum::String("a2"))),
2868                ("y".into(), ResultSpec::value(Datum::String("b2"))),
2869                ("z".into(), ResultSpec::value(Datum::String("z"))),
2870            ]
2871            .into_iter()
2872            .collect(),
2873        );
2874
2875        let unioned = a.union(b);
2876
2877        // Push the unioned spec through `->> <key>`: keys only in one side must
2878        // admit NULL (the other side is unconstrained, so the field could be absent
2879        // there); shared keys must include both observed values.
2880        let arena = RowArena::new();
2881        let relation = ReprRelationType::new(vec![ReprScalarType::Jsonb.nullable(false)]);
2882
2883        // Key only in `a`: the union must admit NULL.
2884        {
2885            let mut interpreter = ColumnSpecs::new(&relation, &arena);
2886            interpreter.push_column(0, unioned.clone());
2887            let expr = MirScalarExpr::column(0).call_binary(
2888                MirScalarExpr::literal_ok(Datum::from("c"), ReprScalarType::String),
2889                JsonbGetStringStringify,
2890            );
2891            assert!(interpreter.expr(&expr).range.may_contain(Datum::Null));
2892        }
2893
2894        // Key only in `b`: symmetric.
2895        {
2896            let mut interpreter = ColumnSpecs::new(&relation, &arena);
2897            interpreter.push_column(0, unioned.clone());
2898            let expr = MirScalarExpr::column(0).call_binary(
2899                MirScalarExpr::literal_ok(Datum::from("z"), ReprScalarType::String),
2900                JsonbGetStringStringify,
2901            );
2902            assert!(interpreter.expr(&expr).range.may_contain(Datum::Null));
2903        }
2904
2905        // Key in both: result must include both observed values.
2906        {
2907            let mut interpreter = ColumnSpecs::new(&relation, &arena);
2908            interpreter.push_column(0, unioned);
2909            let expr = MirScalarExpr::column(0).call_binary(
2910                MirScalarExpr::literal_ok(Datum::from("x"), ReprScalarType::String),
2911                JsonbGetStringStringify,
2912            );
2913            let x_range = interpreter.expr(&expr).range;
2914            assert!(x_range.may_contain(Datum::String("a")));
2915            assert!(x_range.may_contain(Datum::String("a2")));
2916        }
2917    }
2918
2919    #[mz_ore::test]
2920    #[cfg_attr(miri, ignore)] // unsupported foreign call in numeric decoding
2921    fn test_case_over_jsonb_columns() {
2922        // Regression test for PER-6: when CASE picks between two JSON columns whose
2923        // observed keys are disjoint, filter pushdown must not prune parts where
2924        // accessing a key only present in one branch might yield NULL in the other.
2925        let arena = RowArena::new();
2926
2927        // `(CASE WHEN col0 THEN col1 ELSE col2 END) ->> 'y' IS NULL`
2928        let expr = MirScalarExpr::If {
2929            cond: Box::new(MirScalarExpr::column(0)),
2930            then: Box::new(MirScalarExpr::column(1)),
2931            els: Box::new(MirScalarExpr::column(2)),
2932        }
2933        .call_binary(
2934            MirScalarExpr::literal_ok(Datum::from("y"), ReprScalarType::String),
2935            JsonbGetStringStringify,
2936        )
2937        .call_unary(UnaryFunc::IsNull(IsNull));
2938
2939        let relation = ReprRelationType::new(vec![
2940            ReprScalarType::Bool.nullable(false),
2941            ReprScalarType::Jsonb.nullable(false),
2942            ReprScalarType::Jsonb.nullable(false),
2943        ]);
2944        let mut interpreter = ColumnSpecs::new(&relation, &arena);
2945        interpreter.push_column(0, ResultSpec::value_between(Datum::False, Datum::True));
2946        interpreter.push_column(
2947            1,
2948            ResultSpec::map_spec(
2949                [("x".into(), ResultSpec::value(Datum::String("a")))]
2950                    .into_iter()
2951                    .collect(),
2952            ),
2953        );
2954        interpreter.push_column(
2955            2,
2956            ResultSpec::map_spec(
2957                [("y".into(), ResultSpec::value(Datum::String("b")))]
2958                    .into_iter()
2959                    .collect(),
2960            ),
2961        );
2962
2963        let range_out = interpreter.expr(&expr).range;
2964        // When the CASE selects column 1, "y" is absent and `->> 'y'` yields NULL, so
2965        // `IS NULL` is True. The filter must not prune a part that could match.
2966        assert!(range_out.may_contain(Datum::True));
2967    }
2968
2969    #[mz_ore::test]
2970    fn test_like() {
2971        let arena = RowArena::new();
2972
2973        let expr = MirScalarExpr::CallUnary {
2974            func: UnaryFunc::IsLikeMatch(IsLikeMatch(
2975                crate::like_pattern::compile("%whatever%", true).unwrap(),
2976            )),
2977            expr: Box::new(MirScalarExpr::column(0)),
2978        };
2979
2980        let relation = ReprRelationType::new(vec![ReprScalarType::String.nullable(true)]);
2981        let mut interpreter = ColumnSpecs::new(&relation, &arena);
2982        interpreter.push_column(
2983            0,
2984            ResultSpec::value_between(Datum::String("aardvark"), Datum::String("zebra")),
2985        );
2986
2987        let range_out = interpreter.expr(&expr).range;
2988        assert!(
2989            !range_out.fallible,
2990            "like function should not error on non-error input"
2991        );
2992        assert!(range_out.may_contain(Datum::True));
2993        assert!(range_out.may_contain(Datum::False));
2994        assert!(range_out.may_contain(Datum::Null));
2995    }
2996
2997    #[mz_ore::test]
2998    fn test_try_parse_monotonic_iso8601_timestamp() {
2999        use chrono::NaiveDateTime;
3000
3001        let arena = RowArena::new();
3002
3003        let expr = MirScalarExpr::CallUnary {
3004            func: UnaryFunc::TryParseMonotonicIso8601Timestamp(TryParseMonotonicIso8601Timestamp),
3005            expr: Box::new(MirScalarExpr::column(0)),
3006        };
3007
3008        let relation = ReprRelationType::new(vec![ReprScalarType::String.nullable(true)]);
3009        // Test the case where we have full timestamps as bounds.
3010        let mut interpreter = ColumnSpecs::new(&relation, &arena);
3011        interpreter.push_column(
3012            0,
3013            ResultSpec::value_between(
3014                Datum::String("2024-01-11T00:00:00.000Z"),
3015                Datum::String("2024-01-11T20:00:00.000Z"),
3016            ),
3017        );
3018
3019        let timestamp = |ts| {
3020            Datum::Timestamp(
3021                NaiveDateTime::parse_from_str(ts, "%Y-%m-%dT%H:%M:%S")
3022                    .unwrap()
3023                    .try_into()
3024                    .unwrap(),
3025            )
3026        };
3027
3028        let range_out = interpreter.expr(&expr).range;
3029        assert!(!range_out.fallible);
3030        assert!(range_out.nullable);
3031        assert!(!range_out.may_contain(timestamp("2024-01-10T10:00:00")));
3032        assert!(range_out.may_contain(timestamp("2024-01-11T10:00:00")));
3033        assert!(!range_out.may_contain(timestamp("2024-01-12T10:00:00")));
3034
3035        // Test the case where we have truncated / useless bounds.
3036        let mut interpreter = ColumnSpecs::new(&relation, &arena);
3037        interpreter.push_column(
3038            0,
3039            ResultSpec::value_between(Datum::String("2024-01-1"), Datum::String("2024-01-2")),
3040        );
3041
3042        let range_out = interpreter.expr(&expr).range;
3043        assert!(!range_out.fallible);
3044        assert!(range_out.nullable);
3045        assert!(range_out.may_contain(timestamp("2024-01-10T10:00:00")));
3046        assert!(range_out.may_contain(timestamp("2024-01-11T10:00:00")));
3047        assert!(range_out.may_contain(timestamp("2024-01-12T10:00:00")));
3048
3049        // Test the case where only one bound is truncated
3050        let mut interpreter = ColumnSpecs::new(&relation, &arena);
3051        interpreter.push_column(
3052            0,
3053            ResultSpec::value_between(
3054                Datum::String("2024-01-1"),
3055                Datum::String("2024-01-12T10:00:00"),
3056            )
3057            .union(ResultSpec::null()),
3058        );
3059
3060        let range_out = interpreter.expr(&expr).range;
3061        assert!(!range_out.fallible);
3062        assert!(range_out.nullable);
3063        assert!(range_out.may_contain(timestamp("2024-01-10T10:00:00")));
3064        assert!(range_out.may_contain(timestamp("2024-01-11T10:00:00")));
3065        assert!(range_out.may_contain(timestamp("2024-01-12T10:00:00")));
3066
3067        // Test the case where the upper and lower bound are identical
3068        let mut interpreter = ColumnSpecs::new(&relation, &arena);
3069        interpreter.push_column(
3070            0,
3071            ResultSpec::value_between(
3072                Datum::String("2024-01-11T10:00:00.000Z"),
3073                Datum::String("2024-01-11T10:00:00.000Z"),
3074            ),
3075        );
3076
3077        let range_out = interpreter.expr(&expr).range;
3078        assert!(!range_out.fallible);
3079        assert!(!range_out.nullable);
3080        assert!(!range_out.may_contain(timestamp("2024-01-10T10:00:00")));
3081        assert!(range_out.may_contain(timestamp("2024-01-11T10:00:00")));
3082        assert!(!range_out.may_contain(timestamp("2024-01-12T10:00:00")));
3083    }
3084
3085    #[mz_ore::test]
3086    fn test_inequality() {
3087        let arena = RowArena::new();
3088
3089        let expr = MirScalarExpr::column(0).call_binary(
3090            MirScalarExpr::CallUnmaterializable(UnmaterializableFunc::MzNow),
3091            Gte,
3092        );
3093
3094        let relation = ReprRelationType::new(vec![ReprScalarType::MzTimestamp.nullable(true)]);
3095        let mut interpreter = ColumnSpecs::new(&relation, &arena);
3096        interpreter.push_column(
3097            0,
3098            ResultSpec::value_between(
3099                Datum::MzTimestamp(1704736444949u64.into()),
3100                Datum::MzTimestamp(1704736444949u64.into()),
3101            )
3102            .union(ResultSpec::null()),
3103        );
3104        interpreter.push_unmaterializable(
3105            UnmaterializableFunc::MzNow,
3106            ResultSpec::value_between(
3107                Datum::MzTimestamp(1704738791000u64.into()),
3108                Datum::MzTimestamp(18446744073709551615u64.into()),
3109            ),
3110        );
3111
3112        let range_out = interpreter.expr(&expr).range;
3113        assert!(
3114            !range_out.fallible,
3115            "<= function should not error on non-error input"
3116        );
3117        assert!(!range_out.may_contain(Datum::True));
3118        assert!(range_out.may_contain(Datum::False));
3119        assert!(range_out.may_contain(Datum::Null));
3120    }
3121
3122    /// Regression test for database-issues#9656.
3123    ///
3124    /// Adding an `Interval` to a `Timestamp` is non-monotone in the interval
3125    /// argument: the lex order of intervals (months, days, micros) does not
3126    /// respect calendar-month arithmetic with day-clamping. The interpreter
3127    /// must therefore not assume monotonicity, otherwise persist filter
3128    /// pushdown can incorrectly conclude that a part has no matching rows.
3129    #[mz_ore::test]
3130    #[cfg_attr(miri, ignore)]
3131    fn test_add_timestamp_interval_non_monotone() {
3132        use chrono::NaiveDateTime;
3133        use mz_repr::adt::interval::Interval;
3134        use mz_repr::adt::timestamp::CheckedTimestamp;
3135        use mz_repr::{Datum, Row};
3136
3137        let arena = RowArena::new();
3138
3139        // The setup: a timestamp literal `t = 2024-01-31 00:00:00`, and an
3140        // interval column whose stats-range spans
3141        // `[{0 months, 31 days, 0 us}, {1 month, 0 days, 0 us}]`. In lex order,
3142        // the 31-day interval is the lower bound and the 1-month interval is
3143        // the upper bound. The function values at the endpoints are:
3144        //   t + {0,31,0} = 2024-03-02
3145        //   t + {1, 0,0} = 2024-02-29
3146        // But an *interior* interval like {0, 60, 0} maps to 2024-03-31, which
3147        // lies far outside `[Feb 29, Mar 2]`. Under the (incorrect) monotone
3148        // assumption, the interpreter would conclude the output is in that
3149        // narrow window, and rule out predicates like `>= 2024-03-15`.
3150        let ts_lit = |s: &str| {
3151            let mut row = Row::default();
3152            row.packer().push(Datum::Timestamp(
3153                CheckedTimestamp::from_timestamplike(
3154                    NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").unwrap(),
3155                )
3156                .unwrap(),
3157            ));
3158            MirScalarExpr::Literal(Ok(row), ReprScalarType::Timestamp.nullable(false))
3159        };
3160        let interval = |months: i32, days: i32, micros: i64| {
3161            Datum::Interval(Interval {
3162                months,
3163                days,
3164                micros,
3165            })
3166        };
3167
3168        // Expression: `(timestamp_lit + interval_col) >= 2024-03-15`.
3169        let expr = ts_lit("2024-01-31T00:00:00")
3170            .call_binary(MirScalarExpr::column(0), AddTimestampInterval)
3171            .call_binary(ts_lit("2024-03-15T00:00:00"), Gte);
3172
3173        let relation = ReprRelationType::new(vec![ReprScalarType::Interval.nullable(false)]);
3174        let mut interpreter = ColumnSpecs::new(&relation, &arena);
3175        interpreter.push_column(
3176            0,
3177            ResultSpec::value_between(interval(0, 31, 0), interval(1, 0, 0)),
3178        );
3179
3180        let range_out = interpreter.expr(&expr).range;
3181        // The actual data may include e.g. `{0, 60, 0}` → 2024-03-31, which
3182        // satisfies `>= 2024-03-15`. The interpreter must admit `True` so that
3183        // filter pushdown does not skip the part. Under the buggy
3184        // `(true, true)` annotation, the output range would be
3185        // `[Feb 29, Mar 2]`, all of which is `< Mar 15`, and the interpreter
3186        // would (wrongly) admit only `False`.
3187        assert!(
3188            range_out.may_contain(Datum::True),
3189            "interpreter incorrectly ruled out matching rows; \
3190             add_timestamp_interval is not monotone in the interval argument",
3191        );
3192    }
3193
3194    /// Companion test to `test_add_timestamp_interval_non_monotone`: when the
3195    /// interval argument is a literal with `months == 0`, the function reduces
3196    /// to a pure linear shift in microseconds and *is* monotone in the
3197    /// timestamp. The dynamic-monotonicity handler in `AbstractFunc` should
3198    /// recover the tight output range in that case, so that filter pushdown
3199    /// can still narrow predicates like `t - INTERVAL '1' day < literal`.
3200    #[mz_ore::test]
3201    #[cfg_attr(miri, ignore)]
3202    fn test_timestamp_plus_interval_dynamic_monotone() {
3203        use chrono::NaiveDateTime;
3204        use mz_repr::adt::interval::Interval;
3205        use mz_repr::adt::timestamp::CheckedTimestamp;
3206        use mz_repr::{Datum, Row};
3207
3208        let arena = RowArena::new();
3209
3210        let ts = |s: &str| {
3211            Datum::Timestamp(
3212                CheckedTimestamp::from_timestamplike(
3213                    NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").unwrap(),
3214                )
3215                .unwrap(),
3216            )
3217        };
3218        let interval_lit = |months: i32, days: i32, micros: i64| {
3219            let mut row = Row::default();
3220            row.packer().push(Datum::Interval(Interval {
3221                months,
3222                days,
3223                micros,
3224            }));
3225            MirScalarExpr::Literal(Ok(row), ReprScalarType::Interval.nullable(false))
3226        };
3227
3228        let relation = ReprRelationType::new(vec![ReprScalarType::Timestamp.nullable(false)]);
3229
3230        // (a) `t_col - INTERVAL '1' day < 2024-01-15`, with `t_col` ranging
3231        // over `[2024-01-15, 2024-01-20]`. With the days-only interval, the
3232        // subtraction is monotone, so endpoints alone determine the output:
3233        // [2024-01-14, 2024-01-19]. Only `2024-01-14` satisfies `< 2024-01-15`,
3234        // so both True and False are reachable.
3235        {
3236            let expr = MirScalarExpr::column(0)
3237                .call_binary(interval_lit(0, 1, 0), SubTimestampInterval)
3238                .call_binary(
3239                    MirScalarExpr::Literal(
3240                        Ok({
3241                            let mut r = Row::default();
3242                            r.packer().push(ts("2024-01-15T00:00:00"));
3243                            r
3244                        }),
3245                        ReprScalarType::Timestamp.nullable(false),
3246                    ),
3247                    Lt,
3248                );
3249            let mut interpreter = ColumnSpecs::new(&relation, &arena);
3250            interpreter.push_column(
3251                0,
3252                ResultSpec::value_between(ts("2024-01-15T00:00:00"), ts("2024-01-20T00:00:00")),
3253            );
3254            let range_out = interpreter.expr(&expr).range;
3255            assert!(
3256                range_out.may_contain(Datum::True),
3257                "day-only interval should preserve tight bounds",
3258            );
3259            assert!(
3260                range_out.may_contain(Datum::False),
3261                "day-only interval should preserve tight bounds",
3262            );
3263        }
3264
3265        // (b) Same predicate, but with `t_col` strictly *after* the literal:
3266        // `[2024-01-17, 2024-01-20]`. Output of `t - 1 day`:
3267        // `[2024-01-16, 2024-01-19]`, none of which is `< 2024-01-15`. The
3268        // interpreter must rule out `True`.
3269        {
3270            let expr = MirScalarExpr::column(0)
3271                .call_binary(interval_lit(0, 1, 0), SubTimestampInterval)
3272                .call_binary(
3273                    MirScalarExpr::Literal(
3274                        Ok({
3275                            let mut r = Row::default();
3276                            r.packer().push(ts("2024-01-15T00:00:00"));
3277                            r
3278                        }),
3279                        ReprScalarType::Timestamp.nullable(false),
3280                    ),
3281                    Lt,
3282                );
3283            let mut interpreter = ColumnSpecs::new(&relation, &arena);
3284            interpreter.push_column(
3285                0,
3286                ResultSpec::value_between(ts("2024-01-17T00:00:00"), ts("2024-01-20T00:00:00")),
3287            );
3288            let range_out = interpreter.expr(&expr).range;
3289            assert!(
3290                !range_out.may_contain(Datum::True),
3291                "day-only interval should narrow out impossible matches",
3292            );
3293        }
3294
3295        // (c) With a *month*-bearing literal interval, the operation is no
3296        // longer monotone (day-clamping), so the dynamic-monotonicity handler
3297        // must fall back to `anything()` — the interpreter cannot rule out
3298        // either outcome even when the column range is narrow.
3299        {
3300            let expr = MirScalarExpr::column(0)
3301                .call_binary(interval_lit(1, 0, 0), SubTimestampInterval)
3302                .call_binary(
3303                    MirScalarExpr::Literal(
3304                        Ok({
3305                            let mut r = Row::default();
3306                            r.packer().push(ts("2024-01-15T00:00:00"));
3307                            r
3308                        }),
3309                        ReprScalarType::Timestamp.nullable(false),
3310                    ),
3311                    Lt,
3312                );
3313            let mut interpreter = ColumnSpecs::new(&relation, &arena);
3314            interpreter.push_column(
3315                0,
3316                ResultSpec::value_between(ts("2024-01-17T00:00:00"), ts("2024-01-20T00:00:00")),
3317            );
3318            let range_out = interpreter.expr(&expr).range;
3319            assert!(
3320                range_out.may_contain(Datum::True),
3321                "month-bearing interval must conservatively admit True",
3322            );
3323            assert!(
3324                range_out.may_contain(Datum::False),
3325                "month-bearing interval must conservatively admit False",
3326            );
3327        }
3328    }
3329
3330    /// Proptest companion to [`test_timestamp_plus_interval_dynamic_monotone`]:
3331    /// the dynamic-monotonicity handler in [`AbstractFunc`] claims that
3332    /// `add_timestamp_interval(t, i)` is monotone in `t` whenever `i.months == 0`
3333    /// (the only case it actually claims monotonicity for at runtime: the
3334    /// matches above require the right argument to be a single value with
3335    /// `months == 0`). This proptest verifies that claim directly against the
3336    /// function impl by sampling random timestamps and zero-month intervals
3337    /// and checking that input ordering is preserved in the output.
3338    #[mz_ore::test]
3339    #[cfg_attr(miri, ignore)]
3340    fn proptest_timestamp_plus_interval_monotone_when_months_zero() {
3341        use mz_repr::adt::interval::Interval;
3342        use mz_repr::{Datum, RowArena, SqlScalarType, arb_datum_for_scalar};
3343        use proptest::prelude::*;
3344
3345        let timestamp_strat = || arb_datum_for_scalar(SqlScalarType::Timestamp { precision: None });
3346        // Lex order on `Interval` does *not* match total-microseconds order when
3347        // both days and micros vary independently (e.g. `{0, 0, 86_400_000_001}`
3348        // is lex-less than `{0, 1, 0}` but evaluates to a strictly larger
3349        // timestamp), so we only claim monotonicity for *fixed* zero-month
3350        // intervals — which is exactly what the DynamicMonotone handler does.
3351        // The proptest accordingly varies `t` with `i` held constant.
3352        let zero_month_interval_strat =
3353            (any::<i32>(), any::<i64>()).prop_map(|(days, micros)| Interval {
3354                months: 0,
3355                days,
3356                micros,
3357            });
3358
3359        let expr = MirScalarExpr::CallBinary {
3360            func: AddTimestampInterval.into(),
3361            expr1: Box::new(MirScalarExpr::column(0)),
3362            expr2: Box::new(MirScalarExpr::column(1)),
3363        };
3364        let arena = RowArena::new();
3365
3366        proptest!(|(
3367            t1 in timestamp_strat(),
3368            t2 in timestamp_strat(),
3369            i in zero_month_interval_strat,
3370        )| {
3371            let t1 = match t1 { PropDatum::Timestamp(t) => t, _ => unreachable!() };
3372            let t2 = match t2 { PropDatum::Timestamp(t) => t, _ => unreachable!() };
3373            let i = Datum::Interval(i);
3374            let r1 = expr.eval(&[Datum::Timestamp(t1), i], &arena);
3375            let r2 = expr.eval(&[Datum::Timestamp(t2), i], &arena);
3376            // Only compare when both calls succeed; the monotonicity claim
3377            // applies only within the success domain.
3378            if let (Ok(Datum::Timestamp(r1)), Ok(Datum::Timestamp(r2))) = (r1, r2) {
3379                prop_assert_eq!(t1.cmp(&t2), r1.cmp(&r2));
3380            }
3381        });
3382    }
3383
3384    /// Regression test for `date_bin_timestamp`, which is non-monotone in the
3385    /// `stride` argument: a larger stride can bin a source timestamp to an
3386    /// *earlier* result than a smaller stride, because the bin alignment to
3387    /// the unix epoch depends on the stride magnitude rather than on lex order.
3388    #[mz_ore::test]
3389    #[cfg_attr(miri, ignore)]
3390    fn test_date_bin_timestamp_non_monotone() {
3391        use chrono::NaiveDateTime;
3392        use mz_repr::adt::interval::Interval;
3393        use mz_repr::adt::timestamp::CheckedTimestamp;
3394        use mz_repr::{Datum, Row};
3395
3396        let arena = RowArena::new();
3397
3398        let ts_lit = |s: &str| {
3399            let mut row = Row::default();
3400            row.packer().push(Datum::Timestamp(
3401                CheckedTimestamp::from_timestamplike(
3402                    NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").unwrap(),
3403                )
3404                .unwrap(),
3405            ));
3406            MirScalarExpr::Literal(Ok(row), ReprScalarType::Timestamp.nullable(false))
3407        };
3408        let interval = |months: i32, days: i32, micros: i64| {
3409            Datum::Interval(Interval {
3410                months,
3411                days,
3412                micros,
3413            })
3414        };
3415
3416        // Expression: `date_bin(stride_col, 2024-01-01 12:00:00) > 2024-01-01 06:00:00`.
3417        // stride_col ranges over `[1 day, 2 days]`.
3418        //
3419        // Endpoint evaluations:
3420        //   1 day stride → bins to 2024-01-01 00:00:00
3421        //   2 day stride → bins to 2023-12-31 00:00:00
3422        //
3423        // Interior strides produce results *outside* that endpoint box. For
3424        // example, a 1.5-day stride (i.e. `{0 months, 1 day, 12 h micros}`,
3425        // which sorts between the two endpoints in lex order) bins
3426        // 2024-01-01 12:00:00 to exactly 2024-01-01 12:00:00 — well above the
3427        // endpoint maximum of 2024-01-01 00:00:00. With the buggy
3428        // `(true, true)` annotation, the interpreter narrows the output to
3429        // `[Dec 31 00:00, Jan 1 00:00]`, both of which are `<= Jan 1 06:00`,
3430        // so the predicate is wrongly proved `False`. With the non-monotone
3431        // fix the output is `anything()`, so `True` is correctly admitted.
3432        let expr = MirScalarExpr::column(0)
3433            .call_binary(ts_lit("2024-01-01T12:00:00"), DateBinTimestamp)
3434            .call_binary(ts_lit("2024-01-01T06:00:00"), Gt);
3435
3436        let relation = ReprRelationType::new(vec![ReprScalarType::Interval.nullable(false)]);
3437        let mut interpreter = ColumnSpecs::new(&relation, &arena);
3438        interpreter.push_column(
3439            0,
3440            ResultSpec::value_between(interval(0, 1, 0), interval(0, 2, 0)),
3441        );
3442
3443        let range_out = interpreter.expr(&expr).range;
3444        assert!(
3445            range_out.may_contain(Datum::True),
3446            "date_bin is not monotone in the stride argument; \
3447             interior strides can produce outputs outside the endpoint-bounded \
3448             box, so the interpreter must admit True for `>`-style predicates",
3449        );
3450    }
3451
3452    /// `round` must not depend on a numeric's exponent: `Row` encoding folds
3453    /// trailing zeroes into it, so the interpreter, which reads its datums back
3454    /// out of a `Row`, would otherwise disagree with the evaluator and pushdown
3455    /// could discard a part it has to keep.
3456    #[mz_ore::test]
3457    #[cfg_attr(miri, ignore)]
3458    fn test_round_numeric_representation_independent() {
3459        use mz_repr::adt::date::Date;
3460
3461        let arena = RowArena::new();
3462        let lit = |d: Datum, ty: ReprScalarType| {
3463            let mut row = Row::default();
3464            row.packer().push(d);
3465            MirScalarExpr::Literal(Ok(row), ty.nullable(false))
3466        };
3467
3468        // `extract` hands `round` a `946684800` whose exponent is zero, where
3469        // the same value read out of a `Row` is `9.466848E+8`.
3470        let expr = lit(
3471            Datum::Date(Date::from_pg_epoch(0).unwrap()),
3472            ReprScalarType::Date,
3473        )
3474        .call_unary(UnaryFunc::ExtractDate(ExtractDate(DateTimeUnits::Epoch)))
3475        .call_binary(
3476            lit(Datum::Int32(i32::MAX), ReprScalarType::Int32),
3477            BinaryFunc::from(RoundNumericBinary),
3478        );
3479
3480        let relation = ReprRelationType::new(vec![]);
3481        let range = ColumnSpecs::new(&relation, &arena).expr(&expr).range;
3482        match expr.eval(&[], &arena) {
3483            Ok(value) => assert!(
3484                range.may_contain(value),
3485                "interpreter ruled out {value:?}, which the evaluator produced: {range:?}",
3486            ),
3487            Err(_) => assert!(
3488                range.may_fail(),
3489                "interpreter ruled out the error the evaluator produced: {range:?}",
3490            ),
3491        }
3492    }
3493
3494    #[mz_ore::test]
3495    fn test_trace() {
3496        use super::Trace;
3497
3498        let expr = MirScalarExpr::column(0).call_binary(
3499            MirScalarExpr::column(1)
3500                .call_binary(MirScalarExpr::column(3).call_unary(NegInt64), AddInt64),
3501            Gte,
3502        );
3503        let summary = Trace.expr(&expr);
3504        assert!(summary.pushdownable());
3505    }
3506}