Skip to main content

datafusion_physical_expr/intervals/
cp_solver.rs

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