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::expressions::Literal;
152use crate::utils::{build_dag, ExprTreeNode};
153use crate::PhysicalExpr;
154
155use arrow::datatypes::{DataType, Schema};
156use datafusion_common::{internal_err, Result};
157use datafusion_expr::interval_arithmetic::{apply_operator, satisfy_greater, Interval};
158use datafusion_expr::Operator;
159
160use petgraph::graph::NodeIndex;
161use petgraph::stable_graph::{DefaultIx, StableGraph};
162use petgraph::visit::{Bfs, Dfs, DfsPostOrder, EdgeRef};
163use petgraph::Outgoing;
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.as_any().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::CERTAINLY_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::CERTAINLY_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::CERTAINLY_TRUE {
522            // First case:
523            Ok(PropagationResult::CannotPropagate)
524        } else if bounds.contains(&given_range)? != Interval::CERTAINLY_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
583    ///     .gather_node_indices(&[Arc::new(Column::new("gnz", 0))]);
584    /// let left_index = node_indices.get(0).unwrap().1;
585    ///
586    /// // Provide intervals for leaf variables (here, there is only one).
587    /// let intervals = vec![(
588    ///     left_index,
589    ///     Interval::make(Some(10), Some(20)).unwrap(),
590    /// )];
591    ///
592    /// // Evaluate bounds for the composite expression:
593    /// graph.assign_intervals(&intervals);
594    /// assert_eq!(
595    ///     graph.evaluate_bounds().unwrap(),
596    ///     &Interval::make(Some(20), Some(30)).unwrap(),
597    /// )
598    /// ```
599    pub fn evaluate_bounds(&mut self) -> Result<&Interval> {
600        let mut dfs = DfsPostOrder::new(&self.graph, self.root);
601        while let Some(node) = dfs.next(&self.graph) {
602            let neighbors = self.graph.neighbors_directed(node, Outgoing);
603            let mut children_intervals = neighbors
604                .map(|child| self.graph[child].interval())
605                .collect::<Vec<_>>();
606            // If the current expression is a leaf, its interval should already
607            // be set externally, just continue with the evaluation procedure:
608            if !children_intervals.is_empty() {
609                // Reverse to align with `PhysicalExpr`'s children:
610                children_intervals.reverse();
611                self.graph[node].interval =
612                    self.graph[node].expr.evaluate_bounds(&children_intervals)?;
613            }
614        }
615        Ok(self.graph[self.root].interval())
616    }
617
618    /// Updates/shrinks bounds for leaf expressions using interval arithmetic
619    /// via a top-down traversal.
620    fn propagate_constraints(
621        &mut self,
622        given_range: Interval,
623    ) -> Result<PropagationResult> {
624        // Adjust the root node with the given range:
625        if let Some(interval) = self.graph[self.root].interval.intersect(given_range)? {
626            self.graph[self.root].interval = interval;
627        } else {
628            return Ok(PropagationResult::Infeasible);
629        }
630
631        let mut bfs = Bfs::new(&self.graph, self.root);
632
633        while let Some(node) = bfs.next(&self.graph) {
634            let neighbors = self.graph.neighbors_directed(node, Outgoing);
635            let mut children = neighbors.collect::<Vec<_>>();
636            // If the current expression is a leaf, its range is now final.
637            // So, just continue with the propagation procedure:
638            if children.is_empty() {
639                continue;
640            }
641            // Reverse to align with `PhysicalExpr`'s children:
642            children.reverse();
643            let children_intervals = children
644                .iter()
645                .map(|child| self.graph[*child].interval())
646                .collect::<Vec<_>>();
647            let node_interval = self.graph[node].interval();
648            let propagated_intervals = self.graph[node]
649                .expr
650                .propagate_constraints(node_interval, &children_intervals)?;
651            if let Some(propagated_intervals) = propagated_intervals {
652                for (child, interval) in children.into_iter().zip(propagated_intervals) {
653                    self.graph[child].interval = interval;
654                }
655            } else {
656                // The constraint is infeasible, report:
657                return Ok(PropagationResult::Infeasible);
658            }
659        }
660        Ok(PropagationResult::Success)
661    }
662
663    /// Returns the interval associated with the node at the given `index`.
664    pub fn get_interval(&self, index: usize) -> Interval {
665        self.graph[NodeIndex::new(index)].interval.clone()
666    }
667}
668
669/// This is a subfunction of the `propagate_arithmetic` function that propagates to the right child.
670fn propagate_right(
671    left: &Interval,
672    parent: &Interval,
673    right: &Interval,
674    op: &Operator,
675    inverse_op: &Operator,
676) -> Result<Option<Interval>> {
677    match op {
678        Operator::Minus => apply_operator(op, left, parent),
679        Operator::Plus => apply_operator(inverse_op, parent, left),
680        Operator::Divide => apply_operator(op, left, parent),
681        Operator::Multiply => apply_operator(inverse_op, parent, left),
682        _ => internal_err!("Interval arithmetic does not support the operator {}", op),
683    }?
684    .intersect(right)
685}
686
687/// During the propagation of [`Interval`] values on an [`ExprIntervalGraph`],
688/// if there exists a `timestamp - timestamp` operation, the result would be
689/// of type `Duration`. However, we may encounter a situation where a time interval
690/// is involved in an arithmetic operation with a `Duration` type. This function
691/// offers special handling for such cases, where the time interval resides on
692/// the left side of the operation.
693fn propagate_time_interval_at_left(
694    left_child: &Interval,
695    right_child: &Interval,
696    parent: &Interval,
697    op: &Operator,
698    inverse_op: &Operator,
699) -> Result<Option<(Interval, Interval)>> {
700    // We check if the child's time interval(s) has a non-zero month or day field(s).
701    // If so, we return it as is without propagating. Otherwise, we first convert
702    // the time intervals to the `Duration` type, then propagate, and then convert
703    // the bounds to time intervals again.
704    let result = if let Some(duration) = convert_interval_type_to_duration(left_child) {
705        match apply_operator(inverse_op, parent, right_child)?.intersect(duration)? {
706            Some(value) => {
707                let left = convert_duration_type_to_interval(&value);
708                let right = propagate_right(&value, parent, right_child, op, inverse_op)?;
709                match (left, right) {
710                    (Some(left), Some(right)) => Some((left, right)),
711                    _ => None,
712                }
713            }
714            None => None,
715        }
716    } else {
717        propagate_right(left_child, parent, right_child, op, inverse_op)?
718            .map(|right| (left_child.clone(), right))
719    };
720    Ok(result)
721}
722
723/// During the propagation of [`Interval`] values on an [`ExprIntervalGraph`],
724/// if there exists a `timestamp - timestamp` operation, the result would be
725/// of type `Duration`. However, we may encounter a situation where a time interval
726/// is involved in an arithmetic operation with a `Duration` type. This function
727/// offers special handling for such cases, where the time interval resides on
728/// the right side of the operation.
729fn propagate_time_interval_at_right(
730    left_child: &Interval,
731    right_child: &Interval,
732    parent: &Interval,
733    op: &Operator,
734    inverse_op: &Operator,
735) -> Result<Option<(Interval, Interval)>> {
736    // We check if the child's time interval(s) has a non-zero month or day field(s).
737    // If so, we return it as is without propagating. Otherwise, we first convert
738    // the time intervals to the `Duration` type, then propagate, and then convert
739    // the bounds to time intervals again.
740    let result = if let Some(duration) = convert_interval_type_to_duration(right_child) {
741        match apply_operator(inverse_op, parent, &duration)?.intersect(left_child)? {
742            Some(value) => {
743                propagate_right(left_child, parent, &duration, op, inverse_op)?
744                    .and_then(|right| convert_duration_type_to_interval(&right))
745                    .map(|right| (value, right))
746            }
747            None => None,
748        }
749    } else {
750        apply_operator(inverse_op, parent, right_child)?
751            .intersect(left_child)?
752            .map(|value| (value, right_child.clone()))
753    };
754    Ok(result)
755}
756
757fn reverse_tuple<T, U>((first, second): (T, U)) -> (U, T) {
758    (second, first)
759}
760
761#[cfg(test)]
762mod tests {
763    use super::*;
764    use crate::expressions::{BinaryExpr, Column};
765    use crate::intervals::test_utils::gen_conjunctive_numerical_expr;
766
767    use arrow::array::types::{IntervalDayTime, IntervalMonthDayNano};
768    use arrow::datatypes::{Field, TimeUnit};
769    use datafusion_common::ScalarValue;
770
771    use itertools::Itertools;
772    use rand::rngs::StdRng;
773    use rand::{Rng, SeedableRng};
774    use rstest::*;
775
776    #[allow(clippy::too_many_arguments)]
777    fn experiment(
778        expr: Arc<dyn PhysicalExpr>,
779        exprs_with_interval: (Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>),
780        left_interval: Interval,
781        right_interval: Interval,
782        left_expected: Interval,
783        right_expected: Interval,
784        result: PropagationResult,
785        schema: &Schema,
786    ) -> Result<()> {
787        let col_stats = vec![
788            (Arc::clone(&exprs_with_interval.0), left_interval),
789            (Arc::clone(&exprs_with_interval.1), right_interval),
790        ];
791        let expected = vec![
792            (Arc::clone(&exprs_with_interval.0), left_expected),
793            (Arc::clone(&exprs_with_interval.1), right_expected),
794        ];
795        let mut graph = ExprIntervalGraph::try_new(expr, schema)?;
796        let expr_indexes = graph.gather_node_indices(
797            &col_stats.iter().map(|(e, _)| Arc::clone(e)).collect_vec(),
798        );
799
800        let mut col_stat_nodes = col_stats
801            .iter()
802            .zip(expr_indexes.iter())
803            .map(|((_, interval), (_, index))| (*index, interval.clone()))
804            .collect_vec();
805        let expected_nodes = expected
806            .iter()
807            .zip(expr_indexes.iter())
808            .map(|((_, interval), (_, index))| (*index, interval.clone()))
809            .collect_vec();
810
811        let exp_result =
812            graph.update_ranges(&mut col_stat_nodes[..], Interval::CERTAINLY_TRUE)?;
813        assert_eq!(exp_result, result);
814        col_stat_nodes.iter().zip(expected_nodes.iter()).for_each(
815            |((_, calculated_interval_node), (_, expected))| {
816                // NOTE: These randomized tests only check for conservative containment,
817                // not openness/closedness of endpoints.
818
819                // Calculated bounds are relaxed by 1 to cover all strict and
820                // and non-strict comparison cases since we have only closed bounds.
821                let one = ScalarValue::new_one(&expected.data_type()).unwrap();
822                assert!(
823                    calculated_interval_node.lower()
824                        <= &expected.lower().add(&one).unwrap(),
825                    "{}",
826                    format!(
827                        "Calculated {} must be less than or equal {}",
828                        calculated_interval_node.lower(),
829                        expected.lower()
830                    )
831                );
832                assert!(
833                    calculated_interval_node.upper()
834                        >= &expected.upper().sub(&one).unwrap(),
835                    "{}",
836                    format!(
837                        "Calculated {} must be greater than or equal {}",
838                        calculated_interval_node.upper(),
839                        expected.upper()
840                    )
841                );
842            },
843        );
844        Ok(())
845    }
846
847    macro_rules! generate_cases {
848        ($FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
849            fn $FUNC_NAME<const ASC: bool>(
850                expr: Arc<dyn PhysicalExpr>,
851                left_col: Arc<dyn PhysicalExpr>,
852                right_col: Arc<dyn PhysicalExpr>,
853                seed: u64,
854                expr_left: $TYPE,
855                expr_right: $TYPE,
856            ) -> Result<()> {
857                let mut r = StdRng::seed_from_u64(seed);
858
859                let (left_given, right_given, left_expected, right_expected) = if ASC {
860                    let left = r.gen_range((0 as $TYPE)..(1000 as $TYPE));
861                    let right = r.gen_range((0 as $TYPE)..(1000 as $TYPE));
862                    (
863                        (Some(left), None),
864                        (Some(right), None),
865                        (Some(<$TYPE>::max(left, right + expr_left)), None),
866                        (Some(<$TYPE>::max(right, left + expr_right)), None),
867                    )
868                } else {
869                    let left = r.gen_range((0 as $TYPE)..(1000 as $TYPE));
870                    let right = r.gen_range((0 as $TYPE)..(1000 as $TYPE));
871                    (
872                        (None, Some(left)),
873                        (None, Some(right)),
874                        (None, Some(<$TYPE>::min(left, right + expr_left))),
875                        (None, Some(<$TYPE>::min(right, left + expr_right))),
876                    )
877                };
878
879                experiment(
880                    expr,
881                    (left_col.clone(), right_col.clone()),
882                    Interval::make(left_given.0, left_given.1).unwrap(),
883                    Interval::make(right_given.0, right_given.1).unwrap(),
884                    Interval::make(left_expected.0, left_expected.1).unwrap(),
885                    Interval::make(right_expected.0, right_expected.1).unwrap(),
886                    PropagationResult::Success,
887                    &Schema::new(vec![
888                        Field::new(
889                            left_col.as_any().downcast_ref::<Column>().unwrap().name(),
890                            DataType::$SCALAR,
891                            true,
892                        ),
893                        Field::new(
894                            right_col.as_any().downcast_ref::<Column>().unwrap().name(),
895                            DataType::$SCALAR,
896                            true,
897                        ),
898                    ]),
899                )
900            }
901        };
902    }
903    generate_cases!(generate_case_i32, i32, Int32);
904    generate_cases!(generate_case_i64, i64, Int64);
905    generate_cases!(generate_case_f32, f32, Float32);
906    generate_cases!(generate_case_f64, f64, Float64);
907
908    #[test]
909    fn testing_not_possible() -> Result<()> {
910        let left_col = Arc::new(Column::new("left_watermark", 0));
911        let right_col = Arc::new(Column::new("right_watermark", 0));
912
913        // left_watermark > right_watermark + 5
914        let left_and_1 = Arc::new(BinaryExpr::new(
915            Arc::clone(&left_col) as Arc<dyn PhysicalExpr>,
916            Operator::Plus,
917            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
918        ));
919        let expr = Arc::new(BinaryExpr::new(
920            left_and_1,
921            Operator::Gt,
922            Arc::clone(&right_col) as Arc<dyn PhysicalExpr>,
923        ));
924        experiment(
925            expr,
926            (
927                Arc::clone(&left_col) as Arc<dyn PhysicalExpr>,
928                Arc::clone(&right_col) as Arc<dyn PhysicalExpr>,
929            ),
930            Interval::make(Some(10_i32), Some(20_i32))?,
931            Interval::make(Some(100), None)?,
932            Interval::make(Some(10), Some(20))?,
933            Interval::make(Some(100), None)?,
934            PropagationResult::Infeasible,
935            &Schema::new(vec![
936                Field::new(
937                    left_col.as_any().downcast_ref::<Column>().unwrap().name(),
938                    DataType::Int32,
939                    true,
940                ),
941                Field::new(
942                    right_col.as_any().downcast_ref::<Column>().unwrap().name(),
943                    DataType::Int32,
944                    true,
945                ),
946            ]),
947        )
948    }
949
950    macro_rules! integer_float_case_1 {
951        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
952            #[rstest]
953            #[test]
954            fn $TEST_FUNC_NAME(
955                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
956                seed: u64,
957                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
958                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
959            ) -> Result<()> {
960                let left_col = Arc::new(Column::new("left_watermark", 0));
961                let right_col = Arc::new(Column::new("right_watermark", 0));
962
963                // left_watermark + 1 > right_watermark + 11 AND left_watermark + 3 < right_watermark + 33
964                let expr = gen_conjunctive_numerical_expr(
965                    left_col.clone(),
966                    right_col.clone(),
967                    (
968                        Operator::Plus,
969                        Operator::Plus,
970                        Operator::Plus,
971                        Operator::Plus,
972                    ),
973                    ScalarValue::$SCALAR(Some(1 as $TYPE)),
974                    ScalarValue::$SCALAR(Some(11 as $TYPE)),
975                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
976                    ScalarValue::$SCALAR(Some(33 as $TYPE)),
977                    (greater_op, less_op),
978                );
979                // l > r + 10 AND r > l - 30
980                let l_gt_r = 10 as $TYPE;
981                let r_gt_l = -30 as $TYPE;
982                $GENERATE_CASE_FUNC_NAME::<true>(
983                    expr.clone(),
984                    left_col.clone(),
985                    right_col.clone(),
986                    seed,
987                    l_gt_r,
988                    r_gt_l,
989                )?;
990                // Descending tests
991                // r < l - 10 AND l < r + 30
992                let r_lt_l = -l_gt_r;
993                let l_lt_r = -r_gt_l;
994                $GENERATE_CASE_FUNC_NAME::<false>(
995                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
996                )
997            }
998        };
999    }
1000
1001    integer_float_case_1!(case_1_i32, generate_case_i32, i32, Int32);
1002    integer_float_case_1!(case_1_i64, generate_case_i64, i64, Int64);
1003    integer_float_case_1!(case_1_f64, generate_case_f64, f64, Float64);
1004    integer_float_case_1!(case_1_f32, generate_case_f32, f32, Float32);
1005
1006    macro_rules! integer_float_case_2 {
1007        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1008            #[rstest]
1009            #[test]
1010            fn $TEST_FUNC_NAME(
1011                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1012                seed: u64,
1013                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1014                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1015            ) -> Result<()> {
1016                let left_col = Arc::new(Column::new("left_watermark", 0));
1017                let right_col = Arc::new(Column::new("right_watermark", 0));
1018
1019                // left_watermark - 1 > right_watermark + 5 AND left_watermark + 3 < right_watermark + 10
1020                let expr = gen_conjunctive_numerical_expr(
1021                    left_col.clone(),
1022                    right_col.clone(),
1023                    (
1024                        Operator::Minus,
1025                        Operator::Plus,
1026                        Operator::Plus,
1027                        Operator::Plus,
1028                    ),
1029                    ScalarValue::$SCALAR(Some(1 as $TYPE)),
1030                    ScalarValue::$SCALAR(Some(5 as $TYPE)),
1031                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1032                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1033                    (greater_op, less_op),
1034                );
1035                // l > r + 6 AND r > l - 7
1036                let l_gt_r = 6 as $TYPE;
1037                let r_gt_l = -7 as $TYPE;
1038                $GENERATE_CASE_FUNC_NAME::<true>(
1039                    expr.clone(),
1040                    left_col.clone(),
1041                    right_col.clone(),
1042                    seed,
1043                    l_gt_r,
1044                    r_gt_l,
1045                )?;
1046                // Descending tests
1047                // r < l - 6 AND l < r + 7
1048                let r_lt_l = -l_gt_r;
1049                let l_lt_r = -r_gt_l;
1050                $GENERATE_CASE_FUNC_NAME::<false>(
1051                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1052                )
1053            }
1054        };
1055    }
1056
1057    integer_float_case_2!(case_2_i32, generate_case_i32, i32, Int32);
1058    integer_float_case_2!(case_2_i64, generate_case_i64, i64, Int64);
1059    integer_float_case_2!(case_2_f64, generate_case_f64, f64, Float64);
1060    integer_float_case_2!(case_2_f32, generate_case_f32, f32, Float32);
1061
1062    macro_rules! integer_float_case_3 {
1063        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1064            #[rstest]
1065            #[test]
1066            fn $TEST_FUNC_NAME(
1067                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1068                seed: u64,
1069                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1070                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1071            ) -> Result<()> {
1072                let left_col = Arc::new(Column::new("left_watermark", 0));
1073                let right_col = Arc::new(Column::new("right_watermark", 0));
1074
1075                // left_watermark - 1 > right_watermark + 5 AND left_watermark - 3 < right_watermark + 10
1076                let expr = gen_conjunctive_numerical_expr(
1077                    left_col.clone(),
1078                    right_col.clone(),
1079                    (
1080                        Operator::Minus,
1081                        Operator::Plus,
1082                        Operator::Minus,
1083                        Operator::Plus,
1084                    ),
1085                    ScalarValue::$SCALAR(Some(1 as $TYPE)),
1086                    ScalarValue::$SCALAR(Some(5 as $TYPE)),
1087                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1088                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1089                    (greater_op, less_op),
1090                );
1091                // l > r + 6 AND r > l - 13
1092                let l_gt_r = 6 as $TYPE;
1093                let r_gt_l = -13 as $TYPE;
1094                $GENERATE_CASE_FUNC_NAME::<true>(
1095                    expr.clone(),
1096                    left_col.clone(),
1097                    right_col.clone(),
1098                    seed,
1099                    l_gt_r,
1100                    r_gt_l,
1101                )?;
1102                // Descending tests
1103                // r < l - 6 AND l < r + 13
1104                let r_lt_l = -l_gt_r;
1105                let l_lt_r = -r_gt_l;
1106                $GENERATE_CASE_FUNC_NAME::<false>(
1107                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1108                )
1109            }
1110        };
1111    }
1112
1113    integer_float_case_3!(case_3_i32, generate_case_i32, i32, Int32);
1114    integer_float_case_3!(case_3_i64, generate_case_i64, i64, Int64);
1115    integer_float_case_3!(case_3_f64, generate_case_f64, f64, Float64);
1116    integer_float_case_3!(case_3_f32, generate_case_f32, f32, Float32);
1117
1118    macro_rules! integer_float_case_4 {
1119        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1120            #[rstest]
1121            #[test]
1122            fn $TEST_FUNC_NAME(
1123                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1124                seed: u64,
1125                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1126                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1127            ) -> Result<()> {
1128                let left_col = Arc::new(Column::new("left_watermark", 0));
1129                let right_col = Arc::new(Column::new("right_watermark", 0));
1130
1131                // left_watermark - 10 > right_watermark - 5 AND left_watermark - 30 < right_watermark - 3
1132                let expr = gen_conjunctive_numerical_expr(
1133                    left_col.clone(),
1134                    right_col.clone(),
1135                    (
1136                        Operator::Minus,
1137                        Operator::Minus,
1138                        Operator::Minus,
1139                        Operator::Plus,
1140                    ),
1141                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1142                    ScalarValue::$SCALAR(Some(5 as $TYPE)),
1143                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1144                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1145                    (greater_op, less_op),
1146                );
1147                // l > r + 5 AND r > l - 13
1148                let l_gt_r = 5 as $TYPE;
1149                let r_gt_l = -13 as $TYPE;
1150                $GENERATE_CASE_FUNC_NAME::<true>(
1151                    expr.clone(),
1152                    left_col.clone(),
1153                    right_col.clone(),
1154                    seed,
1155                    l_gt_r,
1156                    r_gt_l,
1157                )?;
1158                // Descending tests
1159                // r < l - 5 AND l < r + 13
1160                let r_lt_l = -l_gt_r;
1161                let l_lt_r = -r_gt_l;
1162                $GENERATE_CASE_FUNC_NAME::<false>(
1163                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1164                )
1165            }
1166        };
1167    }
1168
1169    integer_float_case_4!(case_4_i32, generate_case_i32, i32, Int32);
1170    integer_float_case_4!(case_4_i64, generate_case_i64, i64, Int64);
1171    integer_float_case_4!(case_4_f64, generate_case_f64, f64, Float64);
1172    integer_float_case_4!(case_4_f32, generate_case_f32, f32, Float32);
1173
1174    macro_rules! integer_float_case_5 {
1175        ($TEST_FUNC_NAME:ident, $GENERATE_CASE_FUNC_NAME:ident, $TYPE:ty, $SCALAR:ident) => {
1176            #[rstest]
1177            #[test]
1178            fn $TEST_FUNC_NAME(
1179                #[values(0, 1, 2, 3, 4, 12, 32, 314, 3124, 123, 125, 211, 215, 4123)]
1180                seed: u64,
1181                #[values(Operator::Gt, Operator::GtEq)] greater_op: Operator,
1182                #[values(Operator::Lt, Operator::LtEq)] less_op: Operator,
1183            ) -> Result<()> {
1184                let left_col = Arc::new(Column::new("left_watermark", 0));
1185                let right_col = Arc::new(Column::new("right_watermark", 0));
1186
1187                // left_watermark - 10 > right_watermark - 5 AND left_watermark - 30 < right_watermark - 3
1188                let expr = gen_conjunctive_numerical_expr(
1189                    left_col.clone(),
1190                    right_col.clone(),
1191                    (
1192                        Operator::Minus,
1193                        Operator::Minus,
1194                        Operator::Minus,
1195                        Operator::Minus,
1196                    ),
1197                    ScalarValue::$SCALAR(Some(10 as $TYPE)),
1198                    ScalarValue::$SCALAR(Some(5 as $TYPE)),
1199                    ScalarValue::$SCALAR(Some(30 as $TYPE)),
1200                    ScalarValue::$SCALAR(Some(3 as $TYPE)),
1201                    (greater_op, less_op),
1202                );
1203                // l > r + 5 AND r > l - 27
1204                let l_gt_r = 5 as $TYPE;
1205                let r_gt_l = -27 as $TYPE;
1206                $GENERATE_CASE_FUNC_NAME::<true>(
1207                    expr.clone(),
1208                    left_col.clone(),
1209                    right_col.clone(),
1210                    seed,
1211                    l_gt_r,
1212                    r_gt_l,
1213                )?;
1214                // Descending tests
1215                // r < l - 5 AND l < r + 27
1216                let r_lt_l = -l_gt_r;
1217                let l_lt_r = -r_gt_l;
1218                $GENERATE_CASE_FUNC_NAME::<false>(
1219                    expr, left_col, right_col, seed, l_lt_r, r_lt_l,
1220                )
1221            }
1222        };
1223    }
1224
1225    integer_float_case_5!(case_5_i32, generate_case_i32, i32, Int32);
1226    integer_float_case_5!(case_5_i64, generate_case_i64, i64, Int64);
1227    integer_float_case_5!(case_5_f64, generate_case_f64, f64, Float64);
1228    integer_float_case_5!(case_5_f32, generate_case_f32, f32, Float32);
1229
1230    #[test]
1231    fn test_gather_node_indices_dont_remove() -> Result<()> {
1232        // Expression: a@0 + b@1 + 1 > a@0 - b@1, given a@0 + b@1.
1233        // Do not remove a@0 or b@1, only remove edges since a@0 - b@1 also
1234        // depends on leaf nodes a@0 and b@1.
1235        let left_expr = Arc::new(BinaryExpr::new(
1236            Arc::new(BinaryExpr::new(
1237                Arc::new(Column::new("a", 0)),
1238                Operator::Plus,
1239                Arc::new(Column::new("b", 1)),
1240            )),
1241            Operator::Plus,
1242            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1243        ));
1244
1245        let right_expr = Arc::new(BinaryExpr::new(
1246            Arc::new(Column::new("a", 0)),
1247            Operator::Minus,
1248            Arc::new(Column::new("b", 1)),
1249        ));
1250        let expr = Arc::new(BinaryExpr::new(left_expr, Operator::Gt, right_expr));
1251        let mut graph = ExprIntervalGraph::try_new(
1252            expr,
1253            &Schema::new(vec![
1254                Field::new("a", DataType::Int32, true),
1255                Field::new("b", DataType::Int32, true),
1256            ]),
1257        )
1258        .unwrap();
1259        // Define a test leaf node.
1260        let leaf_node = Arc::new(BinaryExpr::new(
1261            Arc::new(Column::new("a", 0)),
1262            Operator::Plus,
1263            Arc::new(Column::new("b", 1)),
1264        ));
1265        // Store the current node count.
1266        let prev_node_count = graph.node_count();
1267        // Gather the index of node in the expression graph that match the test leaf node.
1268        graph.gather_node_indices(&[leaf_node]);
1269        // Store the final node count.
1270        let final_node_count = graph.node_count();
1271        // Assert that the final node count is equal the previous node count.
1272        // This means we did not remove any node.
1273        assert_eq!(prev_node_count, final_node_count);
1274        Ok(())
1275    }
1276
1277    #[test]
1278    fn test_gather_node_indices_remove() -> Result<()> {
1279        // Expression: a@0 + b@1 + 1 > y@0 - z@1, given a@0 + b@1.
1280        // We expect to remove two nodes since we do not need a@ and b@.
1281        let left_expr = Arc::new(BinaryExpr::new(
1282            Arc::new(BinaryExpr::new(
1283                Arc::new(Column::new("a", 0)),
1284                Operator::Plus,
1285                Arc::new(Column::new("b", 1)),
1286            )),
1287            Operator::Plus,
1288            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1289        ));
1290
1291        let right_expr = Arc::new(BinaryExpr::new(
1292            Arc::new(Column::new("y", 0)),
1293            Operator::Minus,
1294            Arc::new(Column::new("z", 1)),
1295        ));
1296        let expr = Arc::new(BinaryExpr::new(left_expr, Operator::Gt, right_expr));
1297        let mut graph = ExprIntervalGraph::try_new(
1298            expr,
1299            &Schema::new(vec![
1300                Field::new("a", DataType::Int32, true),
1301                Field::new("b", DataType::Int32, true),
1302                Field::new("y", DataType::Int32, true),
1303                Field::new("z", DataType::Int32, true),
1304            ]),
1305        )
1306        .unwrap();
1307        // Define a test leaf node.
1308        let leaf_node = Arc::new(BinaryExpr::new(
1309            Arc::new(Column::new("a", 0)),
1310            Operator::Plus,
1311            Arc::new(Column::new("b", 1)),
1312        ));
1313        // Store the current node count.
1314        let prev_node_count = graph.node_count();
1315        // Gather the index of node in the expression graph that match the test leaf node.
1316        graph.gather_node_indices(&[leaf_node]);
1317        // Store the final node count.
1318        let final_node_count = graph.node_count();
1319        // Assert that the final node count is two less than the previous node
1320        // count; i.e. that we did remove two nodes.
1321        assert_eq!(prev_node_count, final_node_count + 2);
1322        Ok(())
1323    }
1324
1325    #[test]
1326    fn test_gather_node_indices_remove_one() -> Result<()> {
1327        // Expression: a@0 + b@1 + 1 > a@0 - z@1, given a@0 + b@1.
1328        // We expect to remove one nodesince we still need a@ but not b@.
1329        let left_expr = Arc::new(BinaryExpr::new(
1330            Arc::new(BinaryExpr::new(
1331                Arc::new(Column::new("a", 0)),
1332                Operator::Plus,
1333                Arc::new(Column::new("b", 1)),
1334            )),
1335            Operator::Plus,
1336            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1337        ));
1338
1339        let right_expr = Arc::new(BinaryExpr::new(
1340            Arc::new(Column::new("a", 0)),
1341            Operator::Minus,
1342            Arc::new(Column::new("z", 1)),
1343        ));
1344        let expr = Arc::new(BinaryExpr::new(left_expr, Operator::Gt, right_expr));
1345        let mut graph = ExprIntervalGraph::try_new(
1346            expr,
1347            &Schema::new(vec![
1348                Field::new("a", DataType::Int32, true),
1349                Field::new("b", DataType::Int32, true),
1350                Field::new("z", DataType::Int32, true),
1351            ]),
1352        )
1353        .unwrap();
1354        // Define a test leaf node.
1355        let leaf_node = Arc::new(BinaryExpr::new(
1356            Arc::new(Column::new("a", 0)),
1357            Operator::Plus,
1358            Arc::new(Column::new("b", 1)),
1359        ));
1360        // Store the current node count.
1361        let prev_node_count = graph.node_count();
1362        // Gather the index of node in the expression graph that match the test leaf node.
1363        graph.gather_node_indices(&[leaf_node]);
1364        // Store the final node count.
1365        let final_node_count = graph.node_count();
1366        // Assert that the final node count is one less than the previous node
1367        // count; i.e. that we did remove two nodes.
1368        assert_eq!(prev_node_count, final_node_count + 1);
1369        Ok(())
1370    }
1371
1372    #[test]
1373    fn test_gather_node_indices_cannot_provide() -> Result<()> {
1374        // Expression: a@0 + 1 + b@1 > y@0 - z@1 -> provide a@0 + b@1
1375        // TODO: We expect nodes a@0 and b@1 to be pruned, and intervals to be provided from the a@0 + b@1 node.
1376        // However, we do not have an exact node for a@0 + b@1 due to the binary tree structure of the expressions.
1377        // Pruning and interval providing for BinaryExpr expressions are more challenging without exact matches.
1378        // Currently, we only support exact matches for BinaryExprs, but we plan to extend support beyond exact matches in the future.
1379        let left_expr = Arc::new(BinaryExpr::new(
1380            Arc::new(BinaryExpr::new(
1381                Arc::new(Column::new("a", 0)),
1382                Operator::Plus,
1383                Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
1384            )),
1385            Operator::Plus,
1386            Arc::new(Column::new("b", 1)),
1387        ));
1388
1389        let right_expr = Arc::new(BinaryExpr::new(
1390            Arc::new(Column::new("y", 0)),
1391            Operator::Minus,
1392            Arc::new(Column::new("z", 1)),
1393        ));
1394        let expr = Arc::new(BinaryExpr::new(left_expr, Operator::Gt, right_expr));
1395        let mut graph = ExprIntervalGraph::try_new(
1396            expr,
1397            &Schema::new(vec![
1398                Field::new("a", DataType::Int32, true),
1399                Field::new("b", DataType::Int32, true),
1400                Field::new("y", DataType::Int32, true),
1401                Field::new("z", DataType::Int32, true),
1402            ]),
1403        )
1404        .unwrap();
1405        // Define a test leaf node.
1406        let leaf_node = Arc::new(BinaryExpr::new(
1407            Arc::new(Column::new("a", 0)),
1408            Operator::Plus,
1409            Arc::new(Column::new("b", 1)),
1410        ));
1411        // Store the current node count.
1412        let prev_node_count = graph.node_count();
1413        // Gather the index of node in the expression graph that match the test leaf node.
1414        graph.gather_node_indices(&[leaf_node]);
1415        // Store the final node count.
1416        let final_node_count = graph.node_count();
1417        // Assert that the final node count is equal the previous node count (i.e., no node was pruned).
1418        assert_eq!(prev_node_count, final_node_count);
1419        Ok(())
1420    }
1421
1422    #[test]
1423    fn test_propagate_constraints_singleton_interval_at_right() -> Result<()> {
1424        let expression = BinaryExpr::new(
1425            Arc::new(Column::new("ts_column", 0)),
1426            Operator::Plus,
1427            Arc::new(Literal::new(ScalarValue::new_interval_mdn(0, 1, 321))),
1428        );
1429        let parent = Interval::try_new(
1430            // 15.10.2020 - 10:11:12.000_000_321 AM
1431            ScalarValue::TimestampNanosecond(Some(1_602_756_672_000_000_321), None),
1432            // 16.10.2020 - 10:11:12.000_000_321 AM
1433            ScalarValue::TimestampNanosecond(Some(1_602_843_072_000_000_321), None),
1434        )?;
1435        let left_child = Interval::try_new(
1436            // 10.10.2020 - 10:11:12 AM
1437            ScalarValue::TimestampNanosecond(Some(1_602_324_672_000_000_000), None),
1438            // 20.10.2020 - 10:11:12 AM
1439            ScalarValue::TimestampNanosecond(Some(1_603_188_672_000_000_000), None),
1440        )?;
1441        let right_child = Interval::try_new(
1442            // 1 day 321 ns
1443            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
1444                months: 0,
1445                days: 1,
1446                nanoseconds: 321,
1447            })),
1448            // 1 day 321 ns
1449            ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
1450                months: 0,
1451                days: 1,
1452                nanoseconds: 321,
1453            })),
1454        )?;
1455        let children = vec![&left_child, &right_child];
1456        let result = expression
1457            .propagate_constraints(&parent, &children)?
1458            .unwrap();
1459
1460        assert_eq!(
1461            vec![
1462                Interval::try_new(
1463                    // 14.10.2020 - 10:11:12 AM
1464                    ScalarValue::TimestampNanosecond(
1465                        Some(1_602_670_272_000_000_000),
1466                        None
1467                    ),
1468                    // 15.10.2020 - 10:11:12 AM
1469                    ScalarValue::TimestampNanosecond(
1470                        Some(1_602_756_672_000_000_000),
1471                        None
1472                    ),
1473                )?,
1474                Interval::try_new(
1475                    // 1 day 321 ns in Duration type
1476                    ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
1477                        months: 0,
1478                        days: 1,
1479                        nanoseconds: 321,
1480                    })),
1481                    // 1 day 321 ns in Duration type
1482                    ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano {
1483                        months: 0,
1484                        days: 1,
1485                        nanoseconds: 321,
1486                    })),
1487                )?
1488            ],
1489            result
1490        );
1491
1492        Ok(())
1493    }
1494
1495    #[test]
1496    fn test_propagate_constraints_column_interval_at_left() -> Result<()> {
1497        let expression = BinaryExpr::new(
1498            Arc::new(Column::new("interval_column", 1)),
1499            Operator::Plus,
1500            Arc::new(Column::new("ts_column", 0)),
1501        );
1502        let parent = Interval::try_new(
1503            // 15.10.2020 - 10:11:12 AM
1504            ScalarValue::TimestampMillisecond(Some(1_602_756_672_000), None),
1505            // 16.10.2020 - 10:11:12 AM
1506            ScalarValue::TimestampMillisecond(Some(1_602_843_072_000), None),
1507        )?;
1508        let right_child = Interval::try_new(
1509            // 10.10.2020 - 10:11:12 AM
1510            ScalarValue::TimestampMillisecond(Some(1_602_324_672_000), None),
1511            // 20.10.2020 - 10:11:12 AM
1512            ScalarValue::TimestampMillisecond(Some(1_603_188_672_000), None),
1513        )?;
1514        let left_child = Interval::try_new(
1515            // 2 days in millisecond
1516            ScalarValue::IntervalDayTime(Some(IntervalDayTime {
1517                days: 0,
1518                milliseconds: 172_800_000,
1519            })),
1520            // 10 days in millisecond
1521            ScalarValue::IntervalDayTime(Some(IntervalDayTime {
1522                days: 0,
1523                milliseconds: 864_000_000,
1524            })),
1525        )?;
1526        let children = vec![&left_child, &right_child];
1527        let result = expression
1528            .propagate_constraints(&parent, &children)?
1529            .unwrap();
1530
1531        assert_eq!(
1532            vec![
1533                Interval::try_new(
1534                    // 2 days in millisecond
1535                    ScalarValue::IntervalDayTime(Some(IntervalDayTime {
1536                        days: 0,
1537                        milliseconds: 172_800_000,
1538                    })),
1539                    // 6 days
1540                    ScalarValue::IntervalDayTime(Some(IntervalDayTime {
1541                        days: 0,
1542                        milliseconds: 518_400_000,
1543                    })),
1544                )?,
1545                Interval::try_new(
1546                    // 10.10.2020 - 10:11:12 AM
1547                    ScalarValue::TimestampMillisecond(Some(1_602_324_672_000), None),
1548                    // 14.10.2020 - 10:11:12 AM
1549                    ScalarValue::TimestampMillisecond(Some(1_602_670_272_000), None),
1550                )?
1551            ],
1552            result
1553        );
1554
1555        Ok(())
1556    }
1557
1558    #[test]
1559    fn test_propagate_comparison() -> Result<()> {
1560        // In the examples below:
1561        // `left` is unbounded: [?, ?],
1562        // `right` is known to be [1000,1000]
1563        // so `left` < `right` results in no new knowledge of `right` but knowing that `left` is now < 1000:` [?, 999]
1564        let left = Interval::make_unbounded(&DataType::Int64)?;
1565        let right = Interval::make(Some(1000_i64), Some(1000_i64))?;
1566        assert_eq!(
1567            (Some((
1568                Interval::make(None, Some(999_i64))?,
1569                Interval::make(Some(1000_i64), Some(1000_i64))?,
1570            ))),
1571            propagate_comparison(
1572                &Operator::Lt,
1573                &Interval::CERTAINLY_TRUE,
1574                &left,
1575                &right
1576            )?
1577        );
1578
1579        let left =
1580            Interval::make_unbounded(&DataType::Timestamp(TimeUnit::Nanosecond, None))?;
1581        let right = Interval::try_new(
1582            ScalarValue::TimestampNanosecond(Some(1000), None),
1583            ScalarValue::TimestampNanosecond(Some(1000), None),
1584        )?;
1585        assert_eq!(
1586            (Some((
1587                Interval::try_new(
1588                    ScalarValue::try_from(&DataType::Timestamp(
1589                        TimeUnit::Nanosecond,
1590                        None
1591                    ))
1592                    .unwrap(),
1593                    ScalarValue::TimestampNanosecond(Some(999), None),
1594                )?,
1595                Interval::try_new(
1596                    ScalarValue::TimestampNanosecond(Some(1000), None),
1597                    ScalarValue::TimestampNanosecond(Some(1000), None),
1598                )?
1599            ))),
1600            propagate_comparison(
1601                &Operator::Lt,
1602                &Interval::CERTAINLY_TRUE,
1603                &left,
1604                &right
1605            )?
1606        );
1607
1608        let left = Interval::make_unbounded(&DataType::Timestamp(
1609            TimeUnit::Nanosecond,
1610            Some("+05:00".into()),
1611        ))?;
1612        let right = Interval::try_new(
1613            ScalarValue::TimestampNanosecond(Some(1000), Some("+05:00".into())),
1614            ScalarValue::TimestampNanosecond(Some(1000), Some("+05:00".into())),
1615        )?;
1616        assert_eq!(
1617            (Some((
1618                Interval::try_new(
1619                    ScalarValue::try_from(&DataType::Timestamp(
1620                        TimeUnit::Nanosecond,
1621                        Some("+05:00".into()),
1622                    ))
1623                    .unwrap(),
1624                    ScalarValue::TimestampNanosecond(Some(999), Some("+05:00".into())),
1625                )?,
1626                Interval::try_new(
1627                    ScalarValue::TimestampNanosecond(Some(1000), Some("+05:00".into())),
1628                    ScalarValue::TimestampNanosecond(Some(1000), Some("+05:00".into())),
1629                )?
1630            ))),
1631            propagate_comparison(
1632                &Operator::Lt,
1633                &Interval::CERTAINLY_TRUE,
1634                &left,
1635                &right
1636            )?
1637        );
1638
1639        Ok(())
1640    }
1641
1642    #[test]
1643    fn test_propagate_or() -> Result<()> {
1644        let expr = Arc::new(BinaryExpr::new(
1645            Arc::new(Column::new("a", 0)),
1646            Operator::Or,
1647            Arc::new(Column::new("b", 1)),
1648        ));
1649        let parent = Interval::CERTAINLY_FALSE;
1650        let children_set = vec![
1651            vec![&Interval::CERTAINLY_FALSE, &Interval::UNCERTAIN],
1652            vec![&Interval::UNCERTAIN, &Interval::CERTAINLY_FALSE],
1653            vec![&Interval::CERTAINLY_FALSE, &Interval::CERTAINLY_FALSE],
1654            vec![&Interval::UNCERTAIN, &Interval::UNCERTAIN],
1655        ];
1656        for children in children_set {
1657            assert_eq!(
1658                expr.propagate_constraints(&parent, &children)?.unwrap(),
1659                vec![Interval::CERTAINLY_FALSE, Interval::CERTAINLY_FALSE],
1660            );
1661        }
1662
1663        let parent = Interval::CERTAINLY_FALSE;
1664        let children_set = vec![
1665            vec![&Interval::CERTAINLY_TRUE, &Interval::UNCERTAIN],
1666            vec![&Interval::UNCERTAIN, &Interval::CERTAINLY_TRUE],
1667        ];
1668        for children in children_set {
1669            assert_eq!(expr.propagate_constraints(&parent, &children)?, None,);
1670        }
1671
1672        let parent = Interval::CERTAINLY_TRUE;
1673        let children = vec![&Interval::CERTAINLY_FALSE, &Interval::UNCERTAIN];
1674        assert_eq!(
1675            expr.propagate_constraints(&parent, &children)?.unwrap(),
1676            vec![Interval::CERTAINLY_FALSE, Interval::CERTAINLY_TRUE]
1677        );
1678
1679        let parent = Interval::CERTAINLY_TRUE;
1680        let children = vec![&Interval::UNCERTAIN, &Interval::UNCERTAIN];
1681        assert_eq!(
1682            expr.propagate_constraints(&parent, &children)?.unwrap(),
1683            // Empty means unchanged intervals.
1684            vec![]
1685        );
1686
1687        Ok(())
1688    }
1689
1690    #[test]
1691    fn test_propagate_certainly_false_and() -> Result<()> {
1692        let expr = Arc::new(BinaryExpr::new(
1693            Arc::new(Column::new("a", 0)),
1694            Operator::And,
1695            Arc::new(Column::new("b", 1)),
1696        ));
1697        let parent = Interval::CERTAINLY_FALSE;
1698        let children_and_results_set = vec![
1699            (
1700                vec![&Interval::CERTAINLY_TRUE, &Interval::UNCERTAIN],
1701                vec![Interval::CERTAINLY_TRUE, Interval::CERTAINLY_FALSE],
1702            ),
1703            (
1704                vec![&Interval::UNCERTAIN, &Interval::CERTAINLY_TRUE],
1705                vec![Interval::CERTAINLY_FALSE, Interval::CERTAINLY_TRUE],
1706            ),
1707            (
1708                vec![&Interval::UNCERTAIN, &Interval::UNCERTAIN],
1709                // Empty means unchanged intervals.
1710                vec![],
1711            ),
1712            (
1713                vec![&Interval::CERTAINLY_FALSE, &Interval::UNCERTAIN],
1714                vec![],
1715            ),
1716        ];
1717        for (children, result) in children_and_results_set {
1718            assert_eq!(
1719                expr.propagate_constraints(&parent, &children)?.unwrap(),
1720                result
1721            );
1722        }
1723
1724        Ok(())
1725    }
1726}