Skip to main content

datafusion_physical_expr/intervals/
cp_solver.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Constraint propagator/solver for custom [`PhysicalExpr`] graphs.
6//!
7//! The constraint propagator/solver in DataFusion uses interval arithmetic to
8//! perform mathematical operations on intervals, which represent a range of
9//! possible values rather than a single point value. This allows for the
10//! propagation of ranges through mathematical operations, and can be used to
11//! compute bounds for a complicated expression. The key idea is that by
12//! breaking down a complicated expression into simpler terms, and then
13//! combining the bounds for those simpler terms, one can obtain bounds for the
14//! overall expression.
15//!
16//! This way of using interval arithmetic to compute bounds for a complex
17//! expression by combining the bounds for the constituent terms within the
18//! original expression allows us to reason about the range of possible values
19//! of the expression. This information later can be used in range pruning of
20//! the provably unnecessary parts of `RecordBatch`es.
21//!
22//! # Example
23//!
24//! For example, consider a mathematical expression such as `x^2 + y = 4` \[1\].
25//! Since this expression would be a binary tree in [`PhysicalExpr`] notation,
26//! this type of an hierarchical computation is well-suited for a graph based
27//! implementation. In such an implementation, an equation system `f(x) = 0` is
28//! represented by a directed acyclic expression graph (DAEG).
29//!
30//! In order to use interval arithmetic to compute bounds for this expression,
31//! one would first determine intervals that represent the possible values of
32//! `x` and `y` Let's say that the interval for `x` is `[1, 2]` and the interval
33//! for `y` is `[-3, 1]`. In the chart below, you can see how the computation
34//! takes place.
35//!
36//! # References
37//!
38//! 1. Kabak, Mehmet Ozan. Analog Circuit Start-Up Behavior Analysis: An Interval
39//!    Arithmetic Based Approach, Chapter 4. Stanford University, 2015.
40//! 2. Moore, Ramon E. Interval analysis. Vol. 4. Englewood Cliffs: Prentice-Hall, 1966.
41//! 3. F. Messine, "Deterministic global optimization using interval constraint
42//!    propagation techniques," RAIRO-Operations Research, vol. 38, no. 04,
43//!    pp. 277-293, 2004.
44//!
45//! # Illustration
46//!
47//! ## Computing bounds for an expression using interval arithmetic
48//!
49//! ```text
50//!             +-----+                         +-----+
51//!        +----|  +  |----+               +----|  +  |----+
52//!        |    |     |    |               |    |     |    |
53//!        |    +-----+    |               |    +-----+    |
54//!        |               |               |               |
55//!    +-----+           +-----+       +-----+           +-----+
56//!    |   2 |           |  y  |       |   2 | [1, 4]    |  y  |
57//!    |[.]  |           |     |       |[.]  |           |     |
58//!    +-----+           +-----+       +-----+           +-----+
59//!       |                               |
60//!       |                               |
61//!     +---+                           +---+
62//!     | x | [1, 2]                    | x | [1, 2]
63//!     +---+                           +---+
64//!
65//!  (a) Bottom-up evaluation: Step 1 (b) Bottom up evaluation: Step 2
66//!
67//!                                      [1 - 3, 4 + 1] = [-2, 5]
68//!             +-----+                         +-----+
69//!        +----|  +  |----+               +----|  +  |----+
70//!        |    |     |    |               |    |     |    |
71//!        |    +-----+    |               |    +-----+    |
72//!        |               |               |               |
73//!    +-----+           +-----+       +-----+           +-----+
74//!    |   2 |[1, 4]     |  y  |       |   2 |[1, 4]     |  y  |
75//!    |[.]  |           |     |       |[.]  |           |     |
76//!    +-----+           +-----+       +-----+           +-----+
77//!       |              [-3, 1]          |              [-3, 1]
78//!       |                               |
79//!     +---+                           +---+
80//!     | x | [1, 2]                    | x | [1, 2]
81//!     +---+                           +---+
82//!
83//!  (c) Bottom-up evaluation: Step 3 (d) Bottom-up evaluation: Step 4
84//! ```
85//!
86//! ## Top-down constraint propagation using inverse semantics
87//!
88//! ```text
89//!    [-2, 5] ∩ [4, 4] = [4, 4]               [4, 4]
90//!            +-----+                         +-----+
91//!       +----|  +  |----+               +----|  +  |----+
92//!       |    |     |    |               |    |     |    |
93//!       |    +-----+    |               |    +-----+    |
94//!       |               |               |               |
95//!    +-----+           +-----+       +-----+           +-----+
96//!    |   2 | [1, 4]    |  y  |       |   2 | [1, 4]    |  y  | [0, 1]*
97//!    |[.]  |           |     |       |[.]  |           |     |
98//!    +-----+           +-----+       +-----+           +-----+
99//!      |              [-3, 1]          |
100//!      |                               |
101//!    +---+                           +---+
102//!    | x | [1, 2]                    | x | [1, 2]
103//!    +---+                           +---+
104//!
105//!  (a) Top-down propagation: Step 1 (b) Top-down propagation: Step 2
106//!
107//!                                     [1 - 3, 4 + 1] = [-2, 5]
108//!            +-----+                         +-----+
109//!       +----|  +  |----+               +----|  +  |----+
110//!       |    |     |    |               |    |     |    |
111//!       |    +-----+    |               |    +-----+    |
112//!       |               |               |               |
113//!    +-----+           +-----+       +-----+           +-----+
114//!    |   2 |[3, 4]**   |  y  |       |   2 |[3, 4]     |  y  |
115//!    |[.]  |           |     |       |[.]  |           |     |
116//!    +-----+           +-----+       +-----+           +-----+
117//!      |              [0, 1]           |              [-3, 1]
118//!      |                               |
119//!    +---+                           +---+
120//!    | x | [1, 2]                    | x | [sqrt(3), 2]***
121//!    +---+                           +---+
122//!
123//!  (c) Top-down propagation: Step 3  (d) Top-down propagation: Step 4
124//!
125//!    * [-3, 1] ∩ ([4, 4] - [1, 4]) = [0, 1]
126//!    ** [1, 4] ∩ ([4, 4] - [0, 1]) = [3, 4]
127//!    *** [1, 2] ∩ [sqrt(3), sqrt(4)] = [sqrt(3), 2]
128//! ```
129
130use std::collections::HashSet;
131use std::fmt::{Display, Formatter};
132use std::mem::{size_of, size_of_val};
133use std::sync::Arc;
134
135use super::utils::{
136    convert_duration_type_to_interval, convert_interval_type_to_duration, get_inverse_op,
137};
138use crate::PhysicalExpr;
139use crate::expressions::{BinaryExpr, Literal};
140use crate::utils::{ExprTreeNode, build_dag};
141
142use arrow::datatypes::{DataType, Schema};
143use datafusion_common::heap_size::{DFHeapSize, DFHeapSizeCtx};
144use datafusion_common::{Result, ScalarValue, internal_err, not_impl_err};
145use datafusion_expr::Operator;
146use datafusion_expr::interval_arithmetic::{Interval, apply_operator, satisfy_greater};
147
148use petgraph::Outgoing;
149use petgraph::graph::NodeIndex;
150use petgraph::stable_graph::{DefaultIx, StableGraph};
151use petgraph::visit::{Bfs, Dfs, DfsPostOrder, EdgeRef};
152
153/// This object implements a directed acyclic expression graph (DAEG) that
154/// is used to compute ranges for expressions through interval arithmetic.
155#[derive(Clone, Debug)]
156pub struct ExprIntervalGraph {
157    graph: StableGraph<ExprIntervalGraphNode, usize>,
158    root: NodeIndex,
159}
160
161/// This object encapsulates all possible constraint propagation results.
162#[derive(PartialEq, Debug)]
163pub enum PropagationResult {
164    CannotPropagate,
165    Infeasible,
166    Success,
167}
168
169/// This is a node in the DAEG; it encapsulates a reference to the actual
170/// [`PhysicalExpr`] as well as an interval containing expression bounds.
171#[derive(Clone, Debug)]
172pub struct ExprIntervalGraphNode {
173    expr: Arc<dyn PhysicalExpr>,
174    interval: Interval,
175}
176
177impl PartialEq for ExprIntervalGraphNode {
178    fn eq(&self, other: &Self) -> bool {
179        self.expr.eq(&other.expr)
180    }
181}
182
183impl Display for ExprIntervalGraphNode {
184    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
185        write!(f, "{}", self.expr)
186    }
187}
188
189impl ExprIntervalGraphNode {
190    /// Constructs a new DAEG node with an `[-∞, ∞]` range.
191    pub fn new_unbounded(expr: Arc<dyn PhysicalExpr>, dt: &DataType) -> Result<Self> {
192        Interval::make_unbounded(dt)
193            .map(|interval| ExprIntervalGraphNode { expr, interval })
194    }
195
196    /// Constructs a new DAEG node with the given range.
197    pub fn new_with_interval(expr: Arc<dyn PhysicalExpr>, interval: Interval) -> Self {
198        ExprIntervalGraphNode { expr, interval }
199    }
200
201    /// Get the interval object representing the range of the expression.
202    pub fn interval(&self) -> &Interval {
203        &self.interval
204    }
205
206    /// This function creates a DAEG node from DataFusion's [`ExprTreeNode`]
207    /// object. Literals are created with definite, singleton intervals while
208    /// any other expression starts with an indefinite interval (`[-∞, ∞]`).
209    pub fn make_node(node: &ExprTreeNode<NodeIndex>, schema: &Schema) -> Result<Self> {
210        let expr = Arc::clone(&node.expr);
211        if let Some(literal) = expr.downcast_ref::<Literal>() {
212            let value = literal.value();
213            Interval::try_new(value.clone(), value.clone())
214                .map(|interval| Self::new_with_interval(expr, interval))
215        } else {
216            expr.data_type(schema)
217                .and_then(|dt| Self::new_unbounded(expr, &dt))
218        }
219    }
220}
221
222/// This function refines intervals `left_child` and `right_child` by applying
223/// constraint propagation through `parent` via operation. The main idea is
224/// that we can shrink ranges of variables x and y using parent interval p.
225///
226/// Assuming that x,y and p has ranges `[xL, xU]`, `[yL, yU]`, and `[pL, pU]`, we
227/// apply the following operations:
228/// - For plus operation, specifically, we would first do
229///     - `[xL, xU]` <- (`[pL, pU]` - `[yL, yU]`) ∩ `[xL, xU]`, and then
230///     - `[yL, yU]` <- (`[pL, pU]` - `[xL, xU]`) ∩ `[yL, yU]`.
231/// - For minus operation, specifically, we would first do
232///     - `[xL, xU]` <- (`[yL, yU]` + `[pL, pU]`) ∩ `[xL, xU]`, and then
233///     - `[yL, yU]` <- (`[xL, xU]` - `[pL, pU]`) ∩ `[yL, yU]`.
234/// - For multiplication operation, specifically, we would first do
235///     - `[xL, xU]` <- (`[pL, pU]` / `[yL, yU]`) ∩ `[xL, xU]`, and then
236///     - `[yL, yU]` <- (`[pL, pU]` / `[xL, xU]`) ∩ `[yL, yU]`.
237/// - For division operation, specifically, we would first do
238///     - `[xL, xU]` <- (`[yL, yU]` * `[pL, pU]`) ∩ `[xL, xU]`, and then
239///     - `[yL, yU]` <- (`[xL, xU]` / `[pL, pU]`) ∩ `[yL, yU]`.
240pub fn propagate_arithmetic(
241    op: &Operator,
242    parent: &Interval,
243    left_child: &Interval,
244    right_child: &Interval,
245) -> Result<Option<(Interval, Interval)>> {
246    let inverse_op = get_inverse_op(*op)?;
247    match (left_child.data_type(), right_child.data_type()) {
248        // If we have a child whose type is a time interval (i.e. DataType::Interval),
249        // we need special handling since timestamp differencing results in a
250        // Duration type.
251        (DataType::Timestamp(..), DataType::Interval(_)) => {
252            propagate_time_interval_at_right(
253                left_child,
254                right_child,
255                parent,
256                op,
257                &inverse_op,
258            )
259        }
260        (DataType::Interval(_), DataType::Timestamp(..)) => {
261            propagate_time_interval_at_left(
262                left_child,
263                right_child,
264                parent,
265                op,
266                &inverse_op,
267            )
268        }
269        _ => {
270            // First, propagate to the left:
271            match apply_operator(&inverse_op, parent, right_child)?
272                .intersect(left_child)?
273            {
274                // Left is feasible:
275                Some(value) => Ok(
276                    // Propagate to the right using the new left.
277                    propagate_right(&value, parent, right_child, op, &inverse_op)?
278                        .map(|right| (value, right)),
279                ),
280                // If the left child is infeasible, short-circuit.
281                None => Ok(None),
282            }
283        }
284    }
285}
286
287/// Compare two scalars the way runtime `Eq` does, instead of with
288/// `ScalarValue`'s bit-wise equality. `ScalarValue::PartialEq` is bit-wise for
289/// floats (`to_bits`), under which `-0.0 != +0.0`; runtime `Eq` normalizes
290/// them via [`ScalarValue::normalize`] (see
291/// `physical-expr-common/src/datum.rs`).
292fn singleton_values_equal(left: &ScalarValue, right: &ScalarValue) -> bool {
293    left.clone().normalize() == right.clone().normalize()
294}
295
296/// This function refines intervals `left_child` and `right_child` by applying
297/// comparison propagation through `parent` via operation. The main idea is
298/// that we can shrink ranges of variables x and y using parent interval p.
299/// Two intervals can be ordered in 6 ways for a Gt `>` operator:
300/// ```text
301///                           (1): Infeasible, short-circuit
302/// left:   |        ================                                               |
303/// right:  |                           ========================                    |
304///
305///                             (2): Update both interval
306/// left:   |              ======================                                   |
307/// right:  |                             ======================                    |
308///                                          |
309///                                          V
310/// left:   |                             =======                                   |
311/// right:  |                             =======                                   |
312///
313///                             (3): Update left interval
314/// left:   |                  ==============================                       |
315/// right:  |                           ==========                                  |
316///                                          |
317///                                          V
318/// left:   |                           =====================                       |
319/// right:  |                           ==========                                  |
320///
321///                             (4): Update right interval
322/// left:   |                           ==========                                  |
323/// right:  |                   ===========================                         |
324///                                          |
325///                                          V
326/// left:   |                           ==========                                  |
327/// right   |                   ==================                                  |
328///
329///                                   (5): No change
330/// left:   |                       ============================                    |
331/// right:  |               ===================                                     |
332///
333///                                   (6): No change
334/// left:   |                                    ====================               |
335/// right:  |                ===============                                        |
336///
337///         -inf --------------------------------------------------------------- +inf
338/// ```
339pub fn propagate_comparison(
340    op: &Operator,
341    parent: &Interval,
342    left_child: &Interval,
343    right_child: &Interval,
344) -> Result<Option<(Interval, Interval)>> {
345    if parent == &Interval::TRUE {
346        match op {
347            Operator::Eq => left_child.intersect(right_child).map(|result| {
348                result.map(|intersection| (intersection.clone(), intersection))
349            }),
350            Operator::Gt => satisfy_greater(left_child, right_child, true),
351            Operator::GtEq => satisfy_greater(left_child, right_child, false),
352            Operator::Lt => satisfy_greater(right_child, left_child, true)
353                .map(|t| t.map(reverse_tuple)),
354            Operator::LtEq => satisfy_greater(right_child, left_child, false)
355                .map(|t| t.map(reverse_tuple)),
356            _ => internal_err!(
357                "The operator must be a comparison operator to propagate intervals"
358            ),
359        }
360    } else if parent == &Interval::FALSE {
361        match op {
362            Operator::Eq => {
363                // `a = b` being certainly false means `a != b`, which excludes
364                // at most a single point from each child. A single interval
365                // cannot represent that excluded point, so returning the
366                // children unchanged is a safe over-approximation. Returning
367                // `None` is not: the caller reads it as infeasible, which
368                // discards satisfiable ranges (see issue #19264).
369                //
370                // The exception is when both children are singletons that are
371                // equal under the `Eq` operator's comparison semantics: then
372                // `a = b` is certainly true, so `NOT(a = b)` is infeasible.
373                // `ScalarValue::PartialEq` is bit-wise for floats, so
374                // `singleton_values_equal` normalizes signed zero to match
375                // runtime `Eq` behavior -- both when deciding whether a child
376                // is a singleton and when comparing the two children.
377                // `Interval::try_new` orders endpoints with `total_cmp`, so
378                // `[-0.0, +0.0]` is a valid interval whose endpoints differ
379                // bit-wise but denote a single `Eq`-comparable value.
380                if !left_child.is_unbounded()
381                    && !right_child.is_unbounded()
382                    && singleton_values_equal(left_child.lower(), left_child.upper())
383                    && singleton_values_equal(right_child.lower(), right_child.upper())
384                    && singleton_values_equal(left_child.lower(), right_child.lower())
385                {
386                    Ok(None)
387                } else {
388                    Ok(Some((left_child.clone(), right_child.clone())))
389                }
390            }
391            Operator::Gt => satisfy_greater(right_child, left_child, false),
392            Operator::GtEq => satisfy_greater(right_child, left_child, true),
393            Operator::Lt => satisfy_greater(left_child, right_child, false)
394                .map(|t| t.map(reverse_tuple)),
395            Operator::LtEq => satisfy_greater(left_child, right_child, true)
396                .map(|t| t.map(reverse_tuple)),
397            _ => internal_err!(
398                "The operator must be a comparison operator to propagate intervals"
399            ),
400        }
401    } else {
402        // Uncertainty cannot change any end-point of the intervals.
403        Ok(Some((left_child.clone(), right_child.clone())))
404    }
405}
406
407impl ExprIntervalGraph {
408    pub fn try_new(expr: Arc<dyn PhysicalExpr>, schema: &Schema) -> Result<Self> {
409        // Build the full graph:
410        let (root, graph) =
411            build_dag(expr, &|node| ExprIntervalGraphNode::make_node(node, schema))?;
412        Ok(Self { graph, root })
413    }
414
415    pub fn node_count(&self) -> usize {
416        self.graph.node_count()
417    }
418
419    /// Returns retained bytes, including `Self`, backing capacity and interval
420    /// heaps, but excluding shared [`PhysicalExpr`] pointees.
421    pub fn size(&self) -> usize {
422        // StableGraph stores a Graph<Option<N>, Option<E>>. Its vacant slots
423        // and spare capacity remain allocated after nodes/edges are removed.
424        let (nodes, edges) = self.graph.capacity();
425        let node_memory_usage =
426            nodes * size_of::<petgraph::graph::Node<Option<ExprIntervalGraphNode>>>();
427        let edge_memory_usage = edges * size_of::<petgraph::graph::Edge<Option<usize>>>();
428        let mut ctx = DFHeapSizeCtx::default();
429        let interval_memory_usage: usize = self
430            .graph
431            .node_weights()
432            .map(|node| {
433                node.interval.lower().heap_size(&mut ctx)
434                    + node.interval.upper().heap_size(&mut ctx)
435            })
436            .sum();
437
438        size_of_val(self) + node_memory_usage + edge_memory_usage + interval_memory_usage
439    }
440
441    // Sometimes, we do not want to calculate and/or propagate intervals all
442    // way down to leaf expressions. For example, assume that we have a
443    // `SymmetricHashJoin` which has a child with an output ordering like:
444    //
445    // ```text
446    // PhysicalSortExpr {
447    //     expr: BinaryExpr('a', +, 'b'),
448    //     sort_option: ..
449    // }
450    // ```
451    //
452    // i.e. its output order comes from a clause like `ORDER BY a + b`. In such
453    // a case, we must calculate the interval for the `BinaryExpr(a, +, b)`
454    // instead of the columns inside this `BinaryExpr`, because this interval
455    // decides whether we prune or not. Therefore, children `PhysicalExpr`s of
456    // this `BinaryExpr` may be pruned for performance. The figure below
457    // explains this example visually.
458    //
459    // Note that we just remove the nodes from the DAEG, do not make any change
460    // to the plan itself.
461    //
462    // ```text
463    //
464    //                                  +-----+                                          +-----+
465    //                                  | GT  |                                          | GT  |
466    //                         +--------|     |-------+                         +--------|     |-------+
467    //                         |        +-----+       |                         |        +-----+       |
468    //                         |                      |                         |                      |
469    //                      +-----+                   |                      +-----+                   |
470    //                      |Cast |                   |                      |Cast |                   |
471    //                      |     |                   |             --\      |     |                   |
472    //                      +-----+                   |       ----------     +-----+                   |
473    //                         |                      |             --/         |                      |
474    //                         |                      |                         |                      |
475    //                      +-----+                +-----+                   +-----+                +-----+
476    //                   +--|Plus |--+          +--|Plus |--+                |Plus |             +--|Plus |--+
477    //                   |  |     |  |          |  |     |  |                |     |             |  |     |  |
478    //  Prune from here  |  +-----+  |          |  +-----+  |                +-----+             |  +-----+  |
479    //  ------------------------------------    |           |                                    |           |
480    //                   |           |          |           |                                    |           |
481    //                +-----+     +-----+    +-----+     +-----+                              +-----+     +-----+
482    //                | a   |     |  b  |    |  c  |     |  2  |                              |  c  |     |  2  |
483    //                |     |     |     |    |     |     |     |                              |     |     |     |
484    //                +-----+     +-----+    +-----+     +-----+                              +-----+     +-----+
485    //
486    // ```
487
488    /// This function associates stable node indices with [`PhysicalExpr`]s so
489    /// that we can match `Arc<dyn PhysicalExpr>` and NodeIndex objects during
490    /// membership tests.
491    pub fn gather_node_indices(
492        &mut self,
493        exprs: &[Arc<dyn PhysicalExpr>],
494    ) -> Vec<(Arc<dyn PhysicalExpr>, usize)> {
495        let graph = &self.graph;
496        let mut bfs = Bfs::new(graph, self.root);
497        // We collect the node indices (usize) of [PhysicalExpr]s in the order
498        // given by argument `exprs`. To preserve this order, we initialize each
499        // expression's node index with usize::MAX, and then find the corresponding
500        // node indices by traversing the graph.
501        let mut removals = vec![];
502        let mut expr_node_indices = exprs
503            .iter()
504            .map(|e| (Arc::clone(e), usize::MAX))
505            .collect::<Vec<_>>();
506        while let Some(node) = bfs.next(graph) {
507            // Get the plan corresponding to this node:
508            let expr = &graph[node].expr;
509            // If the current expression is among `exprs`, slate its children
510            // for removal:
511            if let Some(value) = exprs.iter().position(|e| expr.eq(e)) {
512                // Update the node index of the associated `PhysicalExpr`:
513                expr_node_indices[value].1 = node.index();
514                for edge in graph.edges_directed(node, Outgoing) {
515                    // Slate the child for removal, do not remove immediately.
516                    removals.push(edge.id());
517                }
518            }
519        }
520        for edge_idx in removals {
521            self.graph.remove_edge(edge_idx);
522        }
523        // Get the set of node indices reachable from the root node:
524        let connected_nodes = self.connected_nodes();
525        // Remove nodes not connected to the root node:
526        self.graph
527            .retain_nodes(|_, index| connected_nodes.contains(&index));
528        expr_node_indices
529    }
530
531    /// Returns the set of node indices reachable from the root node via a
532    /// simple depth-first search.
533    fn connected_nodes(&self) -> HashSet<NodeIndex> {
534        let mut nodes = HashSet::with_capacity(self.graph.node_count());
535        let mut dfs = Dfs::new(&self.graph, self.root);
536        while let Some(node) = dfs.next(&self.graph) {
537            nodes.insert(node);
538        }
539        nodes
540    }
541
542    /// Updates intervals for all expressions in the DAEG by successive
543    /// bottom-up and top-down traversals.
544    pub fn update_ranges(
545        &mut self,
546        leaf_bounds: &mut [(usize, Interval)],
547        given_range: Interval,
548    ) -> Result<PropagationResult> {
549        self.assign_intervals(leaf_bounds);
550        let bounds = self.evaluate_bounds()?;
551        // There are three possible cases to consider:
552        // (1) given_range ⊇ bounds => Nothing to propagate
553        // (2) ∅ ⊂ (given_range ∩ bounds) ⊂ bounds => Can propagate
554        // (3) Disjoint sets => Infeasible
555        if given_range.contains(bounds)? == Interval::TRUE {
556            // First case:
557            Ok(PropagationResult::CannotPropagate)
558        } else if bounds.contains(&given_range)? != Interval::FALSE {
559            // Second case:
560            let result = self.propagate_constraints(given_range);
561            self.update_intervals(leaf_bounds);
562            result
563        } else {
564            // Third case:
565            Ok(PropagationResult::Infeasible)
566        }
567    }
568
569    /// This function assigns given ranges to expressions in the DAEG.
570    /// The argument `assignments` associates indices of sought expressions
571    /// with their corresponding new ranges.
572    pub fn assign_intervals(&mut self, assignments: &[(usize, Interval)]) {
573        for (index, interval) in assignments {
574            let node_index = NodeIndex::from(*index as DefaultIx);
575            self.graph[node_index].interval = interval.clone();
576        }
577    }
578
579    /// This function fetches ranges of expressions from the DAEG. The argument
580    /// `assignments` associates indices of sought expressions with their ranges,
581    /// which this function modifies to reflect the intervals in the DAEG.
582    pub fn update_intervals(&self, assignments: &mut [(usize, Interval)]) {
583        for (index, interval) in assignments.iter_mut() {
584            let node_index = NodeIndex::from(*index as DefaultIx);
585            *interval = self.graph[node_index].interval.clone();
586        }
587    }
588
589    /// Computes bounds for an expression using interval arithmetic via a
590    /// bottom-up traversal.
591    ///
592    /// # Examples
593    ///
594    /// ```
595    /// use arrow::datatypes::DataType;
596    /// use arrow::datatypes::Field;
597    /// use arrow::datatypes::Schema;
598    /// use datafusion_common::ScalarValue;
599    /// use datafusion_expr::interval_arithmetic::Interval;
600    /// use datafusion_expr::Operator;
601    /// use datafusion_physical_expr::expressions::{BinaryExpr, Column, Literal};
602    /// use datafusion_physical_expr::intervals::cp_solver::ExprIntervalGraph;
603    /// use datafusion_physical_expr::PhysicalExpr;
604    /// use std::sync::Arc;
605    ///
606    /// let expr = Arc::new(BinaryExpr::new(
607    ///     Arc::new(Column::new("gnz", 0)),
608    ///     Operator::Plus,
609    ///     Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
610    /// ));
611    ///
612    /// let schema = Schema::new(vec![Field::new("gnz".to_string(), DataType::Int32, true)]);
613    ///
614    /// let mut graph = ExprIntervalGraph::try_new(expr, &schema).unwrap();
615    /// // Do it once, while constructing.
616    /// let node_indices = graph.gather_node_indices(&[Arc::new(Column::new("gnz", 0))]);
617    /// let left_index = node_indices.get(0).unwrap().1;
618    ///
619    /// // Provide intervals for leaf variables (here, there is only one).
620    /// let intervals = vec![(left_index, Interval::make(Some(10), Some(20)).unwrap())];
621    ///
622    /// // Evaluate bounds for the composite expression:
623    /// graph.assign_intervals(&intervals);
624    /// assert_eq!(
625    ///     graph.evaluate_bounds().unwrap(),
626    ///     &Interval::make(Some(20), Some(30)).unwrap(),
627    /// )
628    /// ```
629    pub fn evaluate_bounds(&mut self) -> Result<&Interval> {
630        let mut dfs = DfsPostOrder::new(&self.graph, self.root);
631        while let Some(node) = dfs.next(&self.graph) {
632            let neighbors = self.graph.neighbors_directed(node, Outgoing);
633            let mut children_intervals = neighbors
634                .map(|child| self.graph[child].interval())
635                .collect::<Vec<_>>();
636            // If the current expression is a leaf, its interval should already
637            // be set externally, just continue with the evaluation procedure:
638            if !children_intervals.is_empty() {
639                // Reverse to align with `PhysicalExpr`'s children:
640                children_intervals.reverse();
641                self.graph[node].interval =
642                    self.graph[node].expr.evaluate_bounds(&children_intervals)?;
643            }
644        }
645        Ok(self.graph[self.root].interval())
646    }
647
648    /// Updates/shrinks bounds for leaf expressions using interval arithmetic
649    /// via a top-down traversal.
650    fn propagate_constraints(
651        &mut self,
652        given_range: Interval,
653    ) -> Result<PropagationResult> {
654        // Adjust the root node with the given range:
655        if let Some(interval) = self.graph[self.root].interval.intersect(given_range)? {
656            self.graph[self.root].interval = interval;
657        } else {
658            return Ok(PropagationResult::Infeasible);
659        }
660
661        let mut bfs = Bfs::new(&self.graph, self.root);
662        let mut children = Vec::new();
663
664        while let Some(node) = bfs.next(&self.graph) {
665            let neighbors = self.graph.neighbors_directed(node, Outgoing);
666            children.clear();
667            children.extend(neighbors);
668            // If the current expression is a leaf, its range is now final.
669            // So, just continue with the propagation procedure:
670            if children.is_empty() {
671                continue;
672            }
673            // Reverse to align with `PhysicalExpr`'s children:
674            children.reverse();
675            let children_intervals = children
676                .iter()
677                .map(|child| self.graph[*child].interval())
678                .collect::<Vec<_>>();
679            let node_interval = self.graph[node].interval();
680            // Special case: true OR could in principle be propagated by 3 interval sets,
681            // (i.e. left true, or right true, or both true) however we do not support this yet.
682            if node_interval == &Interval::TRUE
683                && self.graph[node]
684                    .expr
685                    .downcast_ref::<BinaryExpr>()
686                    .is_some_and(|expr| expr.op() == &Operator::Or)
687            {
688                return not_impl_err!("OR operator cannot yet propagate true intervals");
689            }
690            let propagated_intervals = self.graph[node]
691                .expr
692                .propagate_constraints(node_interval, &children_intervals)?;
693            if let Some(propagated_intervals) = propagated_intervals {
694                for (child, interval) in children.iter().zip(propagated_intervals) {
695                    self.graph[*child].interval = interval;
696                }
697            } else {
698                // The constraint is infeasible, report:
699                return Ok(PropagationResult::Infeasible);
700            }
701        }
702        Ok(PropagationResult::Success)
703    }
704
705    /// Returns the interval associated with the node at the given `index`.
706    pub fn get_interval(&self, index: usize) -> Interval {
707        self.graph[NodeIndex::new(index)].interval.clone()
708    }
709}
710
711/// This is a subfunction of the `propagate_arithmetic` function that propagates to the right child.
712fn propagate_right(
713    left: &Interval,
714    parent: &Interval,
715    right: &Interval,
716    op: &Operator,
717    inverse_op: &Operator,
718) -> Result<Option<Interval>> {
719    match op {
720        Operator::Minus => apply_operator(op, left, parent),
721        Operator::Plus => apply_operator(inverse_op, parent, left),
722        Operator::Divide => apply_operator(op, left, parent),
723        Operator::Multiply => apply_operator(inverse_op, parent, left),
724        _ => internal_err!("Interval arithmetic does not support the operator {}", op),
725    }?
726    .intersect(right)
727}
728
729/// During the propagation of [`Interval`] values on an [`ExprIntervalGraph`],
730/// if there exists a `timestamp - timestamp` operation, the result would be
731/// of type `Duration`. However, we may encounter a situation where a time interval
732/// is involved in an arithmetic operation with a `Duration` type. This function
733/// offers special handling for such cases, where the time interval resides on
734/// the left side of the operation.
735fn propagate_time_interval_at_left(
736    left_child: &Interval,
737    right_child: &Interval,
738    parent: &Interval,
739    op: &Operator,
740    inverse_op: &Operator,
741) -> Result<Option<(Interval, Interval)>> {
742    // We check if the child's time interval(s) has a non-zero month or day field(s).
743    // If so, we return it as is without propagating. Otherwise, we first convert
744    // the time intervals to the `Duration` type, then propagate, and then convert
745    // the bounds to time intervals again.
746    let result = if let Some(duration) = convert_interval_type_to_duration(left_child) {
747        match apply_operator(inverse_op, parent, right_child)?.intersect(duration)? {
748            Some(value) => {
749                let left = convert_duration_type_to_interval(&value);
750                let right = propagate_right(&value, parent, right_child, op, inverse_op)?;
751                match (left, right) {
752                    (Some(left), Some(right)) => Some((left, right)),
753                    _ => None,
754                }
755            }
756            None => None,
757        }
758    } else {
759        propagate_right(left_child, parent, right_child, op, inverse_op)?
760            .map(|right| (left_child.clone(), right))
761    };
762    Ok(result)
763}
764
765/// During the propagation of [`Interval`] values on an [`ExprIntervalGraph`],
766/// if there exists a `timestamp - timestamp` operation, the result would be
767/// of type `Duration`. However, we may encounter a situation where a time interval
768/// is involved in an arithmetic operation with a `Duration` type. This function
769/// offers special handling for such cases, where the time interval resides on
770/// the right side of the operation.
771fn propagate_time_interval_at_right(
772    left_child: &Interval,
773    right_child: &Interval,
774    parent: &Interval,
775    op: &Operator,
776    inverse_op: &Operator,
777) -> Result<Option<(Interval, Interval)>> {
778    // We check if the child's time interval(s) has a non-zero month or day field(s).
779    // If so, we return it as is without propagating. Otherwise, we first convert
780    // the time intervals to the `Duration` type, then propagate, and then convert
781    // the bounds to time intervals again.
782    let result = if let Some(duration) = convert_interval_type_to_duration(right_child) {
783        match apply_operator(inverse_op, parent, &duration)?.intersect(left_child)? {
784            Some(value) => {
785                propagate_right(left_child, parent, &duration, op, inverse_op)?
786                    .and_then(|right| convert_duration_type_to_interval(&right))
787                    .map(|right| (value, right))
788            }
789            None => None,
790        }
791    } else {
792        apply_operator(inverse_op, parent, right_child)?
793            .intersect(left_child)?
794            .map(|value| (value, right_child.clone()))
795    };
796    Ok(result)
797}
798
799fn reverse_tuple<T, U>((first, second): (T, U)) -> (U, T) {
800    (second, first)
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806    use crate::expressions::Column;
807    use crate::intervals::test_utils::gen_conjunctive_numerical_expr;
808
809    use arrow::array::types::{IntervalDayTime, IntervalMonthDayNano};
810    use arrow::datatypes::{Field, TimeUnit};
811    use datafusion_common::ScalarValue;
812
813    use itertools::Itertools;
814    use rand::rngs::StdRng;
815    use rand::{Rng, SeedableRng};
816    use rstest::*;
817
818    fn expected_graph_backing_size(graph: &ExprIntervalGraph) -> usize {
819        let (nodes, edges) = graph.graph.capacity();
820        size_of_val(graph)
821            + nodes * size_of::<petgraph::graph::Node<Option<ExprIntervalGraphNode>>>()
822            + edges * size_of::<petgraph::graph::Edge<Option<usize>>>()
823    }
824
825    fn graph_with_capacity(nodes: usize, edges: usize) -> ExprIntervalGraph {
826        ExprIntervalGraph {
827            graph: StableGraph::with_capacity(nodes, edges),
828            root: NodeIndex::new(0),
829        }
830    }
831
832    fn add_interval_node(
833        graph: &mut ExprIntervalGraph,
834        expr: Arc<dyn PhysicalExpr>,
835        lower: ScalarValue,
836        upper: ScalarValue,
837    ) -> Result<NodeIndex> {
838        let node = ExprIntervalGraphNode::new_with_interval(
839            expr,
840            Interval::try_new(lower, upper)?,
841        );
842        Ok(graph.graph.add_node(node))
843    }
844
845    #[test]
846    fn graph_size_counts_retained_capacity() -> Result<()> {
847        let mut graph = graph_with_capacity(0, 0);
848        assert_eq!(graph.size(), size_of_val(&graph));
849
850        let expr: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 0));
851        let node = ExprIntervalGraphNode::new_unbounded(expr, &DataType::Int32)?;
852        for _ in 0..17 {
853            let index = graph.graph.add_node(node.clone());
854            if index.index() > 0 {
855                graph.graph.add_edge(graph.root, index, 0);
856            }
857        }
858        assert_eq!(graph.size(), expected_graph_backing_size(&graph));
859
860        let grown_size = graph.size();
861        graph.graph.remove_node(NodeIndex::new(1));
862        assert_eq!(graph.size(), grown_size);
863        graph.graph.clear();
864        assert_eq!(graph.size(), grown_size);
865        Ok(())
866    }
867
868    #[test]
869    fn graph_size_counts_interval_heaps_not_expression_pointees() -> Result<()> {
870        let mut lower = String::with_capacity(73);
871        lower.push('a');
872        let mut upper = String::with_capacity(91);
873        upper.push('z');
874        let string_bytes = lower.capacity() + upper.capacity();
875        // A large expression allocation is shared, not owned by the graph.
876        let expr: Arc<dyn PhysicalExpr> =
877            Arc::new(Literal::new(ScalarValue::Utf8(Some("x".repeat(4096)))));
878        let mut graph = graph_with_capacity(8, 8);
879        add_interval_node(
880            &mut graph,
881            Arc::clone(&expr),
882            ScalarValue::Utf8(Some(lower)),
883            ScalarValue::Utf8(Some(upper)),
884        )?;
885        assert_eq!(
886            graph.size(),
887            expected_graph_backing_size(&graph) + string_bytes
888        );
889
890        // All timestamp endpoints share one timezone allocation, including
891        // across nodes. Charge the Arc allocation only once.
892        let timezone: Arc<str> = Arc::from("UTC");
893        let timezone_bytes = 2 * size_of::<usize>() + timezone.len();
894        let mut timezone_nodes = Vec::with_capacity(2);
895        for _ in 0..2 {
896            timezone_nodes.push(add_interval_node(
897                &mut graph,
898                Arc::clone(&expr),
899                ScalarValue::TimestampNanosecond(Some(0), Some(Arc::clone(&timezone))),
900                ScalarValue::TimestampNanosecond(Some(1), Some(Arc::clone(&timezone))),
901            )?);
902        }
903        assert_eq!(
904            graph.size(),
905            expected_graph_backing_size(&graph) + string_bytes + timezone_bytes
906        );
907        graph.graph.remove_node(graph.root);
908        assert_eq!(
909            graph.size(),
910            expected_graph_backing_size(&graph) + timezone_bytes
911        );
912        graph.graph.remove_node(timezone_nodes[0]);
913        assert_eq!(
914            graph.size(),
915            expected_graph_backing_size(&graph) + timezone_bytes
916        );
917        graph.graph.remove_node(timezone_nodes[1]);
918        assert_eq!(graph.size(), expected_graph_backing_size(&graph));
919        Ok(())
920    }
921
922    #[expect(clippy::too_many_arguments)]
923    fn experiment(
924        expr: Arc<dyn PhysicalExpr>,
925        exprs_with_interval: (Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>),
926        left_interval: Interval,
927        right_interval: Interval,
928        left_expected: Interval,
929        right_expected: Interval,
930        result: PropagationResult,
931        schema: &Schema,
932    ) -> Result<()> {
933        let col_stats = [
934            (Arc::clone(&exprs_with_interval.0), left_interval),
935            (Arc::clone(&exprs_with_interval.1), right_interval),
936        ];
937        let expected = [
938            (Arc::clone(&exprs_with_interval.0), left_expected),
939            (Arc::clone(&exprs_with_interval.1), right_expected),
940        ];
941        let mut graph = ExprIntervalGraph::try_new(expr, schema)?;
942        let expr_indexes = graph.gather_node_indices(
943            &col_stats.iter().map(|(e, _)| Arc::clone(e)).collect_vec(),
944        );
945
946        let mut col_stat_nodes = col_stats
947            .iter()
948            .zip(expr_indexes.iter())
949            .map(|((_, interval), (_, index))| (*index, interval.clone()))
950            .collect_vec();
951        let expected_nodes = expected
952            .iter()
953            .zip(expr_indexes.iter())
954            .map(|((_, interval), (_, index))| (*index, interval.clone()))
955            .collect_vec();
956
957        let exp_result = graph.update_ranges(&mut col_stat_nodes[..], Interval::TRUE)?;
958        assert_eq!(exp_result, result);
959        col_stat_nodes.iter().zip(expected_nodes.iter()).for_each(
960            |((_, calculated_interval_node), (_, expected))| {
961                // NOTE: These randomized tests only check for conservative containment,
962                // not openness/closedness of endpoints.
963
964                // Calculated bounds are relaxed by 1 to cover all strict and
965                // and non-strict comparison cases since we have only closed bounds.
966                let one = ScalarValue::new_one(&expected.data_type()).unwrap();
967                assert!(
968                    calculated_interval_node.lower()
969                        <= &expected.lower().add(&one).unwrap(),
970                    "{}",
971                    format!(
972                        "Calculated {} must be less than or equal {}",
973                        calculated_interval_node.lower(),
974                        expected.lower()
975                    )
976                );
977                assert!(
978                    calculated_interval_node.upper()
979                        >= &expected.upper().sub(&one).unwrap(),
980                    "{}",
981                    format!(
982                        "Calculated {} must be greater than or equal {}",
983                        calculated_interval_node.upper(),
984                        expected.upper()
985                    )
986                );
987            },
988        );
989        Ok(())
990    }
991
992    macro_rules! generate_cases {
993        ($FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
994            fn $FUNC_NAME<const ASC: bool>(
995                expr: Arc<dyn PhysicalExpr>,
996                left_col: Arc<dyn PhysicalExpr>,
997                right_col: Arc<dyn PhysicalExpr>,
998                seed: u64,
999                expr_left: $TYPE,
1000                expr_right: $TYPE,
1001            ) -> Result<()> {
1002                let mut r = StdRng::seed_from_u64(seed);
1003
1004                let (left_given, right_given, left_expected, right_expected) = if ASC {
1005                    let left = r.random_range((0 as $TYPE)..(1000 as $TYPE));
1006                    let right = r.random_range((0 as $TYPE)..(1000 as $TYPE));
1007                    (
1008                        (Some(left), None),
1009                        (Some(right), None),
1010                        (Some(<$TYPE>::max(left, right + expr_left)), None),
1011                        (Some(<$TYPE>::max(right, left + expr_right)), None),
1012                    )
1013                } else {
1014                    let left = r.random_range((0 as $TYPE)..(1000 as $TYPE));
1015                    let right = r.random_range((0 as $TYPE)..(1000 as $TYPE));
1016                    (
1017                        (None, Some(left)),
1018                        (None, Some(right)),
1019                        (None, Some(<$TYPE>::min(left, right + expr_left))),
1020                        (None, Some(<$TYPE>::min(right, left + expr_right))),
1021                    )
1022                };
1023
1024                experiment(
1025                    expr,
1026                    (left_col.clone(), right_col.clone()),
1027                    Interval::make(left_given.0, left_given.1).unwrap(),
1028                    Interval::make(right_given.0, right_given.1).unwrap(),
1029                    Interval::make(left_expected.0, left_expected.1).unwrap(),
1030                    Interval::make(right_expected.0, right_expected.1).unwrap(),
1031                    PropagationResult::Success,
1032                    &Schema::new(vec![
1033                        Field::new(
1034                            left_col.downcast_ref::<Column>().unwrap().name(),
1035                            DataType::$SCALAR,
1036                            true,
1037                        ),
1038                        Field::new(
1039                            right_col.downcast_ref::<Column>().unwrap().name(),
1040                            DataType::$SCALAR,
1041                            true,
1042                        ),
1043                    ]),
1044                )
1045            }
1046        };
1047    }
1048    generate_cases!(generate_case_i32, i32, Int32);
1049    generate_cases!(generate_case_i64, i64, Int64);
1050    generate_cases!(generate_case_f32, f32, Float32);
1051    generate_cases!(generate_case_f64, f64, Float64);
1052
1053    #[test]
1054    fn testing_not_possible() -> Result<()> {
1055        let left_col = Arc::new(Column::new("left_watermark", 0));
1056        let right_col = Arc::new(Column::new("right_watermark", 0));
1057
1058        // left_watermark > right_watermark + 5
1059        let left_and_1 = Arc::new(BinaryExpr::new(
1060            Arc::clone(&left_col) as Arc<dyn PhysicalExpr>,
1061            Operator::Plus,
1062            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
1063        ));
1064        let expr = Arc::new(BinaryExpr::new(
1065            left_and_1,
1066            Operator::Gt,
1067            Arc::clone(&right_col) as Arc<dyn PhysicalExpr>,
1068        ));
1069        experiment(
1070            expr,
1071            (
1072                Arc::clone(&left_col) as Arc<dyn PhysicalExpr>,
1073                Arc::clone(&right_col) as Arc<dyn PhysicalExpr>,
1074            ),
1075            Interval::make(Some(10_i32), Some(20_i32))?,
1076            Interval::make(Some(100), None)?,
1077            Interval::make(Some(10), Some(20))?,
1078            Interval::make(Some(100), None)?,
1079            PropagationResult::Infeasible,
1080            &Schema::new(vec![
1081                Field::new(left_col.name(), DataType::Int32, true),
1082                Field::new(right_col.name(), DataType::Int32, true),
1083            ]),
1084        )
1085    }
1086
1087    macro_rules! integer_float_case_1 {
1088        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1089            #[rstest]
1090            #[test]
1091            fn $TEST_FUNC_NAME(
1092                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1093                seed: u64,
1094                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1095                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1096            ) -> Result<()> {
1097                let left_col = Arc::new(Column::new("left_watermark", 0));
1098                let right_col = Arc::new(Column::new("right_watermark", 0));
1099
1100                // left_watermark + 1 > right_watermark + 11 AND left_watermark + 3 < right_watermark + 33
1101                let expr = gen_conjunctive_numerical_expr(
1102                    left_col.clone(),
1103                    right_col.clone(),
1104                    (
1105                        Operator::Plus,
1106                        Operator::Plus,
1107                        Operator::Plus,
1108                        Operator::Plus,
1109                    ),
1110                    ScalarValue::$SCALAR(Some(1 as $TYPE)),
1111                    ScalarValue::$SCALAR(Some(11 as $TYPE)),
1112                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1113                    ScalarValue::$SCALAR(Some(33 as $TYPE)),
1114                    (greater_op, less_op),
1115                );
1116                // l > r + 10 AND r > l - 30
1117                let l_gt_r = 10 as $TYPE;
1118                let r_gt_l = -30 as $TYPE;
1119                $GENERATE_CASE_FUNC_NAME::<true>(
1120                    expr.clone(),
1121                    left_col.clone(),
1122                    right_col.clone(),
1123                    seed,
1124                    l_gt_r,
1125                    r_gt_l,
1126                )?;
1127                // Descending tests
1128                // r < l - 10 AND l < r + 30
1129                let r_lt_l = -l_gt_r;
1130                let l_lt_r = -r_gt_l;
1131                $GENERATE_CASE_FUNC_NAME::<false>(
1132                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1133                )
1134            }
1135        };
1136    }
1137
1138    integer_float_case_1!(case_1_i32, generate_case_i32, i32, Int32);
1139    integer_float_case_1!(case_1_i64, generate_case_i64, i64, Int64);
1140    integer_float_case_1!(case_1_f64, generate_case_f64, f64, Float64);
1141    integer_float_case_1!(case_1_f32, generate_case_f32, f32, Float32);
1142
1143    macro_rules! integer_float_case_2 {
1144        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1145            #[rstest]
1146            #[test]
1147            fn $TEST_FUNC_NAME(
1148                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1149                seed: u64,
1150                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1151                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1152            ) -> Result<()> {
1153                let left_col = Arc::new(Column::new("left_watermark", 0));
1154                let right_col = Arc::new(Column::new("right_watermark", 0));
1155
1156                // left_watermark - 1 > right_watermark + 5 AND left_watermark + 3 < right_watermark + 10
1157                let expr = gen_conjunctive_numerical_expr(
1158                    left_col.clone(),
1159                    right_col.clone(),
1160                    (
1161                        Operator::Minus,
1162                        Operator::Plus,
1163                        Operator::Plus,
1164                        Operator::Plus,
1165                    ),
1166                    ScalarValue::$SCALAR(Some(1 as $TYPE)),
1167                    ScalarValue::$SCALAR(Some(5 as $TYPE)),
1168                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1169                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1170                    (greater_op, less_op),
1171                );
1172                // l > r + 6 AND r > l - 7
1173                let l_gt_r = 6 as $TYPE;
1174                let r_gt_l = -7 as $TYPE;
1175                $GENERATE_CASE_FUNC_NAME::<true>(
1176                    expr.clone(),
1177                    left_col.clone(),
1178                    right_col.clone(),
1179                    seed,
1180                    l_gt_r,
1181                    r_gt_l,
1182                )?;
1183                // Descending tests
1184                // r < l - 6 AND l < r + 7
1185                let r_lt_l = -l_gt_r;
1186                let l_lt_r = -r_gt_l;
1187                $GENERATE_CASE_FUNC_NAME::<false>(
1188                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1189                )
1190            }
1191        };
1192    }
1193
1194    integer_float_case_2!(case_2_i32, generate_case_i32, i32, Int32);
1195    integer_float_case_2!(case_2_i64, generate_case_i64, i64, Int64);
1196    integer_float_case_2!(case_2_f64, generate_case_f64, f64, Float64);
1197    integer_float_case_2!(case_2_f32, generate_case_f32, f32, Float32);
1198
1199    macro_rules! integer_float_case_3 {
1200        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1201            #[rstest]
1202            #[test]
1203            fn $TEST_FUNC_NAME(
1204                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1205                seed: u64,
1206                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1207                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1208            ) -> Result<()> {
1209                let left_col = Arc::new(Column::new("left_watermark", 0));
1210                let right_col = Arc::new(Column::new("right_watermark", 0));
1211
1212                // left_watermark - 1 > right_watermark + 5 AND left_watermark - 3 < right_watermark + 10
1213                let expr = gen_conjunctive_numerical_expr(
1214                    left_col.clone(),
1215                    right_col.clone(),
1216                    (
1217                        Operator::Minus,
1218                        Operator::Plus,
1219                        Operator::Minus,
1220                        Operator::Plus,
1221                    ),
1222                    ScalarValue::$SCALAR(Some(1 as $TYPE)),
1223                    ScalarValue::$SCALAR(Some(5 as $TYPE)),
1224                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1225                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1226                    (greater_op, less_op),
1227                );
1228                // l > r + 6 AND r > l - 13
1229                let l_gt_r = 6 as $TYPE;
1230                let r_gt_l = -13 as $TYPE;
1231                $GENERATE_CASE_FUNC_NAME::<true>(
1232                    expr.clone(),
1233                    left_col.clone(),
1234                    right_col.clone(),
1235                    seed,
1236                    l_gt_r,
1237                    r_gt_l,
1238                )?;
1239                // Descending tests
1240                // r < l - 6 AND l < r + 13
1241                let r_lt_l = -l_gt_r;
1242                let l_lt_r = -r_gt_l;
1243                $GENERATE_CASE_FUNC_NAME::<false>(
1244                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1245                )
1246            }
1247        };
1248    }
1249
1250    integer_float_case_3!(case_3_i32, generate_case_i32, i32, Int32);
1251    integer_float_case_3!(case_3_i64, generate_case_i64, i64, Int64);
1252    integer_float_case_3!(case_3_f64, generate_case_f64, f64, Float64);
1253    integer_float_case_3!(case_3_f32, generate_case_f32, f32, Float32);
1254
1255    macro_rules! integer_float_case_4 {
1256        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1257            #[rstest]
1258            #[test]
1259            fn $TEST_FUNC_NAME(
1260                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1261                seed: u64,
1262                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1263                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1264            ) -> Result<()> {
1265                let left_col = Arc::new(Column::new("left_watermark", 0));
1266                let right_col = Arc::new(Column::new("right_watermark", 0));
1267
1268                // left_watermark - 10 > right_watermark - 5 AND left_watermark - 30 < right_watermark - 3
1269                let expr = gen_conjunctive_numerical_expr(
1270                    left_col.clone(),
1271                    right_col.clone(),
1272                    (
1273                        Operator::Minus,
1274                        Operator::Minus,
1275                        Operator::Minus,
1276                        Operator::Plus,
1277                    ),
1278                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1279                    ScalarValue::$SCALAR(Some(5 as $TYPE)),
1280                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1281                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1282                    (greater_op, less_op),
1283                );
1284                // l > r + 5 AND r > l - 13
1285                let l_gt_r = 5 as $TYPE;
1286                let r_gt_l = -13 as $TYPE;
1287                $GENERATE_CASE_FUNC_NAME::<true>(
1288                    expr.clone(),
1289                    left_col.clone(),
1290                    right_col.clone(),
1291                    seed,
1292                    l_gt_r,
1293                    r_gt_l,
1294                )?;
1295                // Descending tests
1296                // r < l - 5 AND l < r + 13
1297                let r_lt_l = -l_gt_r;
1298                let l_lt_r = -r_gt_l;
1299                $GENERATE_CASE_FUNC_NAME::<false>(
1300                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1301                )
1302            }
1303        };
1304    }
1305
1306    integer_float_case_4!(case_4_i32, generate_case_i32, i32, Int32);
1307    integer_float_case_4!(case_4_i64, generate_case_i64, i64, Int64);
1308    integer_float_case_4!(case_4_f64, generate_case_f64, f64, Float64);
1309    integer_float_case_4!(case_4_f32, generate_case_f32, f32, Float32);
1310
1311    macro_rules! integer_float_case_5 {
1312        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1313            #[rstest]
1314            #[test]
1315            fn $TEST_FUNC_NAME(
1316                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1317                seed: u64,
1318                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1319                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1320            ) -> Result<()> {
1321                let left_col = Arc::new(Column::new("left_watermark", 0));
1322                let right_col = Arc::new(Column::new("right_watermark", 0));
1323
1324                // left_watermark - 10 > right_watermark - 5 AND left_watermark - 30 < right_watermark - 3
1325                let expr = gen_conjunctive_numerical_expr(
1326                    left_col.clone(),
1327                    right_col.clone(),
1328                    (
1329                        Operator::Minus,
1330                        Operator::Minus,
1331                        Operator::Minus,
1332                        Operator::Minus,
1333                    ),
1334                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1335                    ScalarValue::$SCALAR(Some(5 as $TYPE)),
1336                    ScalarValue::$SCALAR(Some(30 as $TYPE)),
1337                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1338                    (greater_op, less_op),
1339                );
1340                // l > r + 5 AND r > l - 27
1341                let l_gt_r = 5 as $TYPE;
1342                let r_gt_l = -27 as $TYPE;
1343                $GENERATE_CASE_FUNC_NAME::<true>(
1344                    expr.clone(),
1345                    left_col.clone(),
1346                    right_col.clone(),
1347                    seed,
1348                    l_gt_r,
1349                    r_gt_l,
1350                )?;
1351                // Descending tests
1352                // r < l - 5 AND l < r + 27
1353                let r_lt_l = -l_gt_r;
1354                let l_lt_r = -r_gt_l;
1355                $GENERATE_CASE_FUNC_NAME::<false>(
1356                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1357                )
1358            }
1359        };
1360    }
1361
1362    integer_float_case_5!(case_5_i32, generate_case_i32, i32, Int32);
1363    integer_float_case_5!(case_5_i64, generate_case_i64, i64, Int64);
1364    integer_float_case_5!(case_5_f64, generate_case_f64, f64, Float64);
1365    integer_float_case_5!(case_5_f32, generate_case_f32, f32, Float32);
1366
1367    #[test]
1368    fn test_gather_node_indices_dont_remove() -> Result<()> {
1369        // Expression: a@0 + b@1 + 1 > a@0 - b@1, given a@0 + b@1.
1370        // Do not remove a@0 or b@1, only remove edges since a@0 - b@1 also
1371        // depends on leaf nodes a@0 and b@1.
1372        let left_expr = Arc::new(BinaryExpr::new(
1373            Arc::new(BinaryExpr::new(
1374                Arc::new(Column::new("a", 0)),
1375                Operator::Plus,
1376                Arc::new(Column::new("b", 1)),
1377            )),
1378            Operator::Plus,
1379            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1380        ));
1381
1382        let right_expr = Arc::new(BinaryExpr::new(
1383            Arc::new(Column::new("a", 0)),
1384            Operator::Minus,
1385            Arc::new(Column::new("b", 1)),
1386        ));
1387        let expr = Arc::new(BinaryExpr::new(left_expr, Operator::Gt, right_expr));
1388        let mut graph = ExprIntervalGraph::try_new(
1389            expr,
1390            &Schema::new(vec![
1391                Field::new("a", DataType::Int32, true),
1392                Field::new("b", DataType::Int32, true),
1393            ]),
1394        )
1395        .unwrap();
1396        // Define a test leaf node.
1397        let leaf_node = Arc::new(BinaryExpr::new(
1398            Arc::new(Column::new("a", 0)),
1399            Operator::Plus,
1400            Arc::new(Column::new("b", 1)),
1401        ));
1402        // Store the current node count.
1403        let prev_node_count = graph.node_count();
1404        // Gather the index of node in the expression graph that match the test leaf node.
1405        graph.gather_node_indices(&[leaf_node]);
1406        // Store the final node count.
1407        let final_node_count = graph.node_count();
1408        // Assert that the final node count is equal the previous node count.
1409        // This means we did not remove any node.
1410        assert_eq!(prev_node_count, final_node_count);
1411        Ok(())
1412    }
1413
1414    #[test]
1415    fn test_gather_node_indices_remove() -> Result<()> {
1416        // Expression: a@0 + b@1 + 1 > y@0 - z@1, given a@0 + b@1.
1417        // We expect to remove two nodes since we do not need a@ and b@.
1418        let left_expr = Arc::new(BinaryExpr::new(
1419            Arc::new(BinaryExpr::new(
1420                Arc::new(Column::new("a", 0)),
1421                Operator::Plus,
1422                Arc::new(Column::new("b", 1)),
1423            )),
1424            Operator::Plus,
1425            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1426        ));
1427
1428        let right_expr = Arc::new(BinaryExpr::new(
1429            Arc::new(Column::new("y", 0)),
1430            Operator::Minus,
1431            Arc::new(Column::new("z", 1)),
1432        ));
1433        let expr = Arc::new(BinaryExpr::new(left_expr, Operator::Gt, right_expr));
1434        let mut graph = ExprIntervalGraph::try_new(
1435            expr,
1436            &Schema::new(vec![
1437                Field::new("a", DataType::Int32, true),
1438                Field::new("b", DataType::Int32, true),
1439                Field::new("y", DataType::Int32, true),
1440                Field::new("z", DataType::Int32, true),
1441            ]),
1442        )
1443        .unwrap();
1444        // Define a test leaf node.
1445        let leaf_node = Arc::new(BinaryExpr::new(
1446            Arc::new(Column::new("a", 0)),
1447            Operator::Plus,
1448            Arc::new(Column::new("b", 1)),
1449        ));
1450        // Store the current node count.
1451        let prev_node_count = graph.node_count();
1452        // Gather the index of node in the expression graph that match the test leaf node.
1453        graph.gather_node_indices(&[leaf_node]);
1454        // Store the final node count.
1455        let final_node_count = graph.node_count();
1456        // Assert that the final node count is two less than the previous node
1457        // count; i.e. that we did remove two nodes.
1458        assert_eq!(prev_node_count, final_node_count + 2);
1459        Ok(())
1460    }
1461
1462    #[test]
1463    fn test_gather_node_indices_remove_one() -> Result<()> {
1464        // Expression: a@0 + b@1 + 1 > a@0 - z@1, given a@0 + b@1.
1465        // We expect to remove one nodesince we still need a@ but not b@.
1466        let left_expr = Arc::new(BinaryExpr::new(
1467            Arc::new(BinaryExpr::new(
1468                Arc::new(Column::new("a", 0)),
1469                Operator::Plus,
1470                Arc::new(Column::new("b", 1)),
1471            )),
1472            Operator::Plus,
1473            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1474        ));
1475
1476        let right_expr = Arc::new(BinaryExpr::new(
1477            Arc::new(Column::new("a", 0)),
1478            Operator::Minus,
1479            Arc::new(Column::new("z", 1)),
1480        ));
1481        let expr = Arc::new(BinaryExpr::new(left_expr, Operator::Gt, right_expr));
1482        let mut graph = ExprIntervalGraph::try_new(
1483            expr,
1484            &Schema::new(vec![
1485                Field::new("a", DataType::Int32, true),
1486                Field::new("b", DataType::Int32, true),
1487                Field::new("z", DataType::Int32, true),
1488            ]),
1489        )
1490        .unwrap();
1491        // Define a test leaf node.
1492        let leaf_node = Arc::new(BinaryExpr::new(
1493            Arc::new(Column::new("a", 0)),
1494            Operator::Plus,
1495            Arc::new(Column::new("b", 1)),
1496        ));
1497        // Store the current node count.
1498        let prev_node_count = graph.node_count();
1499        // Gather the index of node in the expression graph that match the test leaf node.
1500        graph.gather_node_indices(&[leaf_node]);
1501        // Store the final node count.
1502        let final_node_count = graph.node_count();
1503        // Assert that the final node count is one less than the previous node
1504        // count; i.e. that we did remove two nodes.
1505        assert_eq!(prev_node_count, final_node_count + 1);
1506        Ok(())
1507    }
1508
1509    #[test]
1510    fn test_gather_node_indices_cannot_provide() -> Result<()> {
1511        // Expression: a@0 + 1 + b@1 > y@0 - z@1 -> provide a@0 + b@1
1512        // TODO: We expect nodes a@0 and b@1 to be pruned, and intervals to be provided from the a@0 + b@1 node.
1513        // However, we do not have an exact node for a@0 + b@1 due to the binary tree structure of the expressions.
1514        // Pruning and interval providing for BinaryExpr expressions are more challenging without exact matches.
1515        // Currently, we only support exact matches for BinaryExprs, but we plan to extend support beyond exact matches in the future.
1516        let left_expr = Arc::new(BinaryExpr::new(
1517            Arc::new(BinaryExpr::new(
1518                Arc::new(Column::new("a", 0)),
1519                Operator::Plus,
1520                Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1521            )),
1522            Operator::Plus,
1523            Arc::new(Column::new("b", 1)),
1524        ));
1525
1526        let right_expr = Arc::new(BinaryExpr::new(
1527            Arc::new(Column::new("y", 0)),
1528            Operator::Minus,
1529            Arc::new(Column::new("z", 1)),
1530        ));
1531        let expr = Arc::new(BinaryExpr::new(left_expr, Operator::Gt, right_expr));
1532        let mut graph = ExprIntervalGraph::try_new(
1533            expr,
1534            &Schema::new(vec![
1535                Field::new("a", DataType::Int32, true),
1536                Field::new("b", DataType::Int32, true),
1537                Field::new("y", DataType::Int32, true),
1538                Field::new("z", DataType::Int32, true),
1539            ]),
1540        )
1541        .unwrap();
1542        // Define a test leaf node.
1543        let leaf_node = Arc::new(BinaryExpr::new(
1544            Arc::new(Column::new("a", 0)),
1545            Operator::Plus,
1546            Arc::new(Column::new("b", 1)),
1547        ));
1548        // Store the current node count.
1549        let prev_node_count = graph.node_count();
1550        // Gather the index of node in the expression graph that match the test leaf node.
1551        graph.gather_node_indices(&[leaf_node]);
1552        // Store the final node count.
1553        let final_node_count = graph.node_count();
1554        // Assert that the final node count is equal the previous node count (i.e., no node was pruned).
1555        assert_eq!(prev_node_count, final_node_count);
1556        Ok(())
1557    }
1558
1559    #[test]
1560    fn test_propagate_constraints_singleton_interval_at_right() -> Result<()> {
1561        let expression = BinaryExpr::new(
1562            Arc::new(Column::new("ts_column", 0)),
1563            Operator::Plus,
1564            Arc::new(Literal::new(ScalarValue::new_interval_mdn(0, 1, 321))),
1565        );
1566        let parent = Interval::try_new(
1567            // 15.10.2020 - 10:11:12.000_000_321 AM
1568            ScalarValue::TimestampNanosecond(Some(1_602_756_672_000_000_321), None),
1569            // 16.10.2020 - 10:11:12.000_000_321 AM
1570            ScalarValue::TimestampNanosecond(Some(1_602_843_072_000_000_321), None),
1571        )?;
1572        let left_child = Interval::try_new(
1573            // 10.10.2020 - 10:11:12 AM
1574            ScalarValue::TimestampNanosecond(Some(1_602_324_672_000_000_000), None),
1575            // 20.10.2020 - 10:11:12 AM
1576            ScalarValue::TimestampNanosecond(Some(1_603_188_672_000_000_000), None),
1577        )?;
1578        let right_child = Interval::try_new(
1579            // 1 day 321 ns
1580            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
1581                months: 0,
1582                days: 1,
1583                nanoseconds: 321,
1584            })),
1585            // 1 day 321 ns
1586            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
1587                months: 0,
1588                days: 1,
1589                nanoseconds: 321,
1590            })),
1591        )?;
1592        let children = vec![&left_child, &right_child];
1593        let result = expression
1594            .propagate_constraints(&parent, &children)?
1595            .unwrap();
1596
1597        assert_eq!(
1598            vec![
1599                Interval::try_new(
1600                    // 14.10.2020 - 10:11:12 AM
1601                    ScalarValue::TimestampNanosecond(
1602                        Some(1_602_670_272_000_000_000),
1603                        None
1604                    ),
1605                    // 15.10.2020 - 10:11:12 AM
1606                    ScalarValue::TimestampNanosecond(
1607                        Some(1_602_756_672_000_000_000),
1608                        None
1609                    ),
1610                )?,
1611                Interval::try_new(
1612                    // 1 day 321 ns in Duration type
1613                    ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
1614                        months: 0,
1615                        days: 1,
1616                        nanoseconds: 321,
1617                    })),
1618                    // 1 day 321 ns in Duration type
1619                    ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
1620                        months: 0,
1621                        days: 1,
1622                        nanoseconds: 321,
1623                    })),
1624                )?
1625            ],
1626            result
1627        );
1628
1629        Ok(())
1630    }
1631
1632    #[test]
1633    fn test_propagate_constraints_column_interval_at_left() -> Result<()> {
1634        let expression = BinaryExpr::new(
1635            Arc::new(Column::new("interval_column", 1)),
1636            Operator::Plus,
1637            Arc::new(Column::new("ts_column", 0)),
1638        );
1639        let parent = Interval::try_new(
1640            // 15.10.2020 - 10:11:12 AM
1641            ScalarValue::TimestampMillisecond(Some(1_602_756_672_000), None),
1642            // 16.10.2020 - 10:11:12 AM
1643            ScalarValue::TimestampMillisecond(Some(1_602_843_072_000), None),
1644        )?;
1645        let right_child = Interval::try_new(
1646            // 10.10.2020 - 10:11:12 AM
1647            ScalarValue::TimestampMillisecond(Some(1_602_324_672_000), None),
1648            // 20.10.2020 - 10:11:12 AM
1649            ScalarValue::TimestampMillisecond(Some(1_603_188_672_000), None),
1650        )?;
1651        let left_child = Interval::try_new(
1652            // 2 days in millisecond
1653            ScalarValue::IntervalDayTime(Some(IntervalDayTime {
1654                days: 0,
1655                milliseconds: 172_800_000,
1656            })),
1657            // 10 days in millisecond
1658            ScalarValue::IntervalDayTime(Some(IntervalDayTime {
1659                days: 0,
1660                milliseconds: 864_000_000,
1661            })),
1662        )?;
1663        let children = vec![&left_child, &right_child];
1664        let result = expression
1665            .propagate_constraints(&parent, &children)?
1666            .unwrap();
1667
1668        assert_eq!(
1669            vec![
1670                Interval::try_new(
1671                    // 2 days in millisecond
1672                    ScalarValue::IntervalDayTime(Some(IntervalDayTime {
1673                        days: 0,
1674                        milliseconds: 172_800_000,
1675                    })),
1676                    // 6 days
1677                    ScalarValue::IntervalDayTime(Some(IntervalDayTime {
1678                        days: 0,
1679                        milliseconds: 518_400_000,
1680                    })),
1681                )?,
1682                Interval::try_new(
1683                    // 10.10.2020 - 10:11:12 AM
1684                    ScalarValue::TimestampMillisecond(Some(1_602_324_672_000), None),
1685                    // 14.10.2020 - 10:11:12 AM
1686                    ScalarValue::TimestampMillisecond(Some(1_602_670_272_000), None),
1687                )?
1688            ],
1689            result
1690        );
1691
1692        Ok(())
1693    }
1694
1695    #[test]
1696    fn test_propagate_comparison() -> Result<()> {
1697        // In the examples below:
1698        // `left` is unbounded: [?, ?],
1699        // `right` is known to be [1000,1000]
1700        // so `left` < `right` results in no new knowledge of `right` but knowing that `left` is now < 1000:` [?, 999]
1701        let left = Interval::make_unbounded(&DataType::Int64)?;
1702        let right = Interval::make(Some(1000_i64), Some(1000_i64))?;
1703        assert_eq!(
1704            (Some((
1705                Interval::make(None, Some(999_i64))?,
1706                Interval::make(Some(1000_i64), Some(1000_i64))?,
1707            ))),
1708            propagate_comparison(&Operator::Lt, &Interval::TRUE, &left, &right)?
1709        );
1710
1711        let left =
1712            Interval::make_unbounded(&DataType::Timestamp(TimeUnit::Nanosecond, None))?;
1713        let right = Interval::try_new(
1714            ScalarValue::TimestampNanosecond(Some(1000), None),
1715            ScalarValue::TimestampNanosecond(Some(1000), None),
1716        )?;
1717        assert_eq!(
1718            (Some((
1719                Interval::try_new(
1720                    ScalarValue::try_from(&DataType::Timestamp(
1721                        TimeUnit::Nanosecond,
1722                        None
1723                    ))
1724                    .unwrap(),
1725                    ScalarValue::TimestampNanosecond(Some(999), None),
1726                )?,
1727                Interval::try_new(
1728                    ScalarValue::TimestampNanosecond(Some(1000), None),
1729                    ScalarValue::TimestampNanosecond(Some(1000), None),
1730                )?
1731            ))),
1732            propagate_comparison(&Operator::Lt, &Interval::TRUE, &left, &right)?
1733        );
1734
1735        let left = Interval::make_unbounded(&DataType::Timestamp(
1736            TimeUnit::Nanosecond,
1737            Some("+05:00".into()),
1738        ))?;
1739        let right = Interval::try_new(
1740            ScalarValue::TimestampNanosecond(Some(1000), Some("+05:00".into())),
1741            ScalarValue::TimestampNanosecond(Some(1000), Some("+05:00".into())),
1742        )?;
1743        assert_eq!(
1744            (Some((
1745                Interval::try_new(
1746                    ScalarValue::try_from(&DataType::Timestamp(
1747                        TimeUnit::Nanosecond,
1748                        Some("+05:00".into()),
1749                    ))
1750                    .unwrap(),
1751                    ScalarValue::TimestampNanosecond(Some(999), Some("+05:00".into())),
1752                )?,
1753                Interval::try_new(
1754                    ScalarValue::TimestampNanosecond(Some(1000), Some("+05:00".into())),
1755                    ScalarValue::TimestampNanosecond(Some(1000), Some("+05:00".into())),
1756                )?
1757            ))),
1758            propagate_comparison(&Operator::Lt, &Interval::TRUE, &left, &right)?
1759        );
1760
1761        Ok(())
1762    }
1763
1764    #[test]
1765    fn test_propagate_eq_false_identical_singletons() -> Result<()> {
1766        // When both children are the same single-point interval, `a = b` is
1767        // certainly true, so `NOT(a = b)` (parent = FALSE) is infeasible.
1768        // This is the only case the `Eq + FALSE` arm reports as infeasible;
1769        // see issue #19264 and PR #20138.
1770        let left = Interval::make(Some(0_i64), Some(0_i64))?;
1771        let right = Interval::make(Some(0_i64), Some(0_i64))?;
1772        assert_eq!(
1773            None,
1774            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1775        );
1776
1777        Ok(())
1778    }
1779
1780    #[test]
1781    fn test_propagate_eq_false_signed_zero_singletons() -> Result<()> {
1782        // `-0.0` and `+0.0` are equal under SQL/IEEE-754 comparison
1783        // semantics, even though `ScalarValue::PartialEq` is bit-wise and
1784        // treats them as distinct. When both children are singletons that
1785        // are equal under comparison semantics, `a = b` is certainly true
1786        // and `NOT(a = b)` is infeasible.
1787        //
1788        // This case is reachable in nested boolean contexts (e.g.
1789        // `NOT(a = +0.0) AND b`) where the bottom-up pass does not
1790        // short-circuit before reaching `propagate_comparison`.
1791        let left = Interval::try_new(
1792            ScalarValue::Float32(Some(-0.0f32)),
1793            ScalarValue::Float32(Some(-0.0f32)),
1794        )?;
1795        let right = Interval::try_new(
1796            ScalarValue::Float32(Some(0.0f32)),
1797            ScalarValue::Float32(Some(0.0f32)),
1798        )?;
1799        assert_eq!(
1800            None,
1801            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1802        );
1803
1804        // Float64 variant.
1805        let left = Interval::try_new(
1806            ScalarValue::Float64(Some(-0.0f64)),
1807            ScalarValue::Float64(Some(-0.0f64)),
1808        )?;
1809        let right = Interval::try_new(
1810            ScalarValue::Float64(Some(0.0f64)),
1811            ScalarValue::Float64(Some(0.0f64)),
1812        )?;
1813        assert_eq!(
1814            None,
1815            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1816        );
1817
1818        Ok(())
1819    }
1820
1821    #[test]
1822    fn test_propagate_eq_false_distinct_singletons() -> Result<()> {
1823        // Different single points: `a = b` is certainly false, so `NOT(a = b)`
1824        // is feasible. The children admit no further refinement, but must be
1825        // preserved rather than reported as infeasible.
1826        let left = Interval::make(Some(0_i64), Some(0_i64))?;
1827        let right = Interval::make(Some(1_i64), Some(1_i64))?;
1828        assert_eq!(
1829            Some((left.clone(), right.clone())),
1830            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1831        );
1832
1833        Ok(())
1834    }
1835
1836    #[test]
1837    fn test_propagate_eq_false_overlapping_intervals() -> Result<()> {
1838        // The case from issue #19264: `a ∈ [-1, 1]`, `b = 0`. `a = b` is
1839        // possibly true (at a = 0) and possibly false, so `NOT(a = b)` is
1840        // feasible. Interval arithmetic cannot exclude the single point 0,
1841        // so the children are returned unchanged rather than as infeasible.
1842        let left = Interval::make(Some(-1_i64), Some(1_i64))?;
1843        let right = Interval::make(Some(0_i64), Some(0_i64))?;
1844        assert_eq!(
1845            Some((left.clone(), right.clone())),
1846            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1847        );
1848
1849        // Overlapping non-singleton intervals: same reasoning, feasible but
1850        // not refinable.
1851        let left = Interval::make(Some(-1_i64), Some(1_i64))?;
1852        let right = Interval::make(Some(0_i64), Some(2_i64))?;
1853        assert_eq!(
1854            Some((left.clone(), right.clone())),
1855            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1856        );
1857
1858        // A structurally singleton-looking `[NULL, NULL]` interval is
1859        // unbounded, not a known value, and must not be treated as equal to a
1860        // bounded singleton.
1861        let left = Interval::make(Some(0_i64), Some(0_i64))?;
1862        let right = Interval::make::<i64>(None, None)?;
1863        assert_eq!(
1864            Some((left.clone(), right.clone())),
1865            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1866        );
1867
1868        // Two fully unbounded intervals likewise provide no proof that the
1869        // operands are equal singletons.
1870        let left = Interval::make::<i64>(None, None)?;
1871        let right = Interval::make::<i64>(None, None)?;
1872        assert_eq!(
1873            Some((left.clone(), right.clone())),
1874            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1875        );
1876
1877        Ok(())
1878    }
1879
1880    #[test]
1881    fn test_propagate_eq_false_signed_zero_interval_singleton() -> Result<()> {
1882        // `Interval::try_new` orders endpoints with `total_cmp`, so
1883        // `[-0.0, +0.0]` is a valid interval. Its endpoints differ bit-wise
1884        // but denote a single value under `Eq` comparison semantics, so
1885        // `a = 0.0` is certainly true over it and `NOT(a = 0.0)` is
1886        // infeasible. A bit-wise `lower() == upper()` singleton check would
1887        // miss this and report the input intervals as feasible.
1888        let left = Interval::try_new(
1889            ScalarValue::Float32(Some(-0.0f32)),
1890            ScalarValue::Float32(Some(0.0f32)),
1891        )?;
1892        let right = Interval::try_new(
1893            ScalarValue::Float32(Some(0.0f32)),
1894            ScalarValue::Float32(Some(0.0f32)),
1895        )?;
1896        assert_eq!(
1897            None,
1898            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1899        );
1900
1901        // The signed-zero span may sit on either side.
1902        assert_eq!(
1903            None,
1904            propagate_comparison(&Operator::Eq, &Interval::FALSE, &right, &left)?
1905        );
1906
1907        // Float64 variant.
1908        let left = Interval::try_new(
1909            ScalarValue::Float64(Some(-0.0f64)),
1910            ScalarValue::Float64(Some(0.0f64)),
1911        )?;
1912        let right = Interval::try_new(
1913            ScalarValue::Float64(Some(-0.0f64)),
1914            ScalarValue::Float64(Some(0.0f64)),
1915        )?;
1916        assert_eq!(
1917            None,
1918            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1919        );
1920
1921        // A genuinely wider float interval is still not a singleton.
1922        let left = Interval::try_new(
1923            ScalarValue::Float64(Some(-0.0f64)),
1924            ScalarValue::Float64(Some(1.0f64)),
1925        )?;
1926        let right = Interval::try_new(
1927            ScalarValue::Float64(Some(0.0f64)),
1928            ScalarValue::Float64(Some(0.0f64)),
1929        )?;
1930        assert_eq!(
1931            Some((left.clone(), right.clone())),
1932            propagate_comparison(&Operator::Eq, &Interval::FALSE, &left, &right)?
1933        );
1934
1935        Ok(())
1936    }
1937
1938    #[test]
1939    fn test_propagate_comparison_uncertain_parent_preserves_operands() -> Result<()> {
1940        // A `TRUE_OR_FALSE` parent proves nothing about either operand, so the
1941        // shared catch-all arm must return both children unchanged for every
1942        // comparison operator. Returning `None` here would be read as
1943        // infeasible and would discard satisfiable ranges (issue #19264).
1944        let left = Interval::make(Some(-1_i64), Some(5_i64))?;
1945        let right = Interval::make(Some(0_i64), Some(2_i64))?;
1946        for op in [
1947            Operator::Eq,
1948            Operator::Gt,
1949            Operator::GtEq,
1950            Operator::Lt,
1951            Operator::LtEq,
1952        ] {
1953            assert_eq!(
1954                Some((left.clone(), right.clone())),
1955                propagate_comparison(&op, &Interval::TRUE_OR_FALSE, &left, &right)?,
1956                "operands must be preserved for {op} under an uncertain parent"
1957            );
1958        }
1959
1960        // Also holds for singleton and unbounded operands.
1961        let left = Interval::make(Some(0_i64), Some(0_i64))?;
1962        let right = Interval::make::<i64>(None, None)?;
1963        for op in [
1964            Operator::Eq,
1965            Operator::Gt,
1966            Operator::GtEq,
1967            Operator::Lt,
1968            Operator::LtEq,
1969        ] {
1970            assert_eq!(
1971                Some((left.clone(), right.clone())),
1972                propagate_comparison(&op, &Interval::TRUE_OR_FALSE, &left, &right)?,
1973                "operands must be preserved for {op} under an uncertain parent"
1974            );
1975        }
1976
1977        Ok(())
1978    }
1979
1980    #[test]
1981    fn test_propagate_or() -> Result<()> {
1982        let expr = Arc::new(BinaryExpr::new(
1983            Arc::new(Column::new("a", 0)),
1984            Operator::Or,
1985            Arc::new(Column::new("b", 1)),
1986        ));
1987        let parent = Interval::FALSE;
1988        let children_set = vec![
1989            vec![&Interval::FALSE, &Interval::TRUE_OR_FALSE],
1990            vec![&Interval::TRUE_OR_FALSE, &Interval::FALSE],
1991            vec![&Interval::FALSE, &Interval::FALSE],
1992            vec![&Interval::TRUE_OR_FALSE, &Interval::TRUE_OR_FALSE],
1993        ];
1994        for children in children_set {
1995            assert_eq!(
1996                expr.propagate_constraints(&parent, &children)?.unwrap(),
1997                vec![Interval::FALSE, Interval::FALSE],
1998            );
1999        }
2000
2001        let parent = Interval::FALSE;
2002        let children_set = vec![
2003            vec![&Interval::TRUE, &Interval::TRUE_OR_FALSE],
2004            vec![&Interval::TRUE_OR_FALSE, &Interval::TRUE],
2005        ];
2006        for children in children_set {
2007            assert_eq!(expr.propagate_constraints(&parent, &children)?, None,);
2008        }
2009
2010        let parent = Interval::TRUE;
2011        let children = vec![&Interval::FALSE, &Interval::TRUE_OR_FALSE];
2012        assert_eq!(
2013            expr.propagate_constraints(&parent, &children)?.unwrap(),
2014            vec![Interval::FALSE, Interval::TRUE]
2015        );
2016
2017        let parent = Interval::TRUE;
2018        let children = vec![&Interval::TRUE_OR_FALSE, &Interval::TRUE_OR_FALSE];
2019        assert_eq!(
2020            expr.propagate_constraints(&parent, &children)?.unwrap(),
2021            // Empty means unchanged intervals.
2022            vec![]
2023        );
2024
2025        Ok(())
2026    }
2027
2028    #[test]
2029    fn test_propagate_certainly_false_and() -> Result<()> {
2030        let expr = Arc::new(BinaryExpr::new(
2031            Arc::new(Column::new("a", 0)),
2032            Operator::And,
2033            Arc::new(Column::new("b", 1)),
2034        ));
2035        let parent = Interval::FALSE;
2036        let children_and_results_set = vec![
2037            (
2038                vec![&Interval::TRUE, &Interval::TRUE_OR_FALSE],
2039                vec![Interval::TRUE, Interval::FALSE],
2040            ),
2041            (
2042                vec![&Interval::TRUE_OR_FALSE, &Interval::TRUE],
2043                vec![Interval::FALSE, Interval::TRUE],
2044            ),
2045            (
2046                vec![&Interval::TRUE_OR_FALSE, &Interval::TRUE_OR_FALSE],
2047                // Empty means unchanged intervals.
2048                vec![],
2049            ),
2050            (vec![&Interval::FALSE, &Interval::TRUE_OR_FALSE], vec![]),
2051        ];
2052        for (children, result) in children_and_results_set {
2053            assert_eq!(
2054                expr.propagate_constraints(&parent, &children)?.unwrap(),
2055                result
2056            );
2057        }
2058
2059        Ok(())
2060    }
2061}