Skip to main content

vortex_functions/between/
find.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Rewrites `x >= a AND x < b` into `x BETWEEN a AND b`.
5
6use std::ptr;
7
8use vortex_array::scalar_fn::builtin::boolean::Boolean;
9use vortex_array::scalar_fn::builtin::compare::Compare;
10use vortex_array::scalar_fn::builtin::get_item::GetItem;
11use vortex_array::scalar_fn::builtin::literal::Literal;
12use vortex_array::scalar_fn::builtin::operators::BooleanOperator;
13use vortex_array::scalar_fn::builtin::operators::CompareOperator;
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_expr::BoundExpression;
17use vortex_expr::ScalarFnExprExt;
18
19use crate::between::Between;
20use crate::between::BetweenOptions;
21use crate::between::StrictComparison;
22
23/// Merge pairs of range comparisons on the same column within any conjunction of `expr` into a
24/// single [`Between`].
25///
26/// This is not an optimizer rule because it is worth running only once, on a scan's filter.
27/// Subtrees without a match keep their identity, so an expression without any match is returned
28/// unchanged.
29pub fn find_between(expr: BoundExpression) -> VortexResult<BoundExpression> {
30    Ok(try_find_between(&expr)?.unwrap_or(expr))
31}
32
33fn try_find_between(expr: &BoundExpression) -> VortexResult<Option<BoundExpression>> {
34    let children = expr.children();
35    let mut new_children: Option<Vec<BoundExpression>> = None;
36    for (idx, child) in children.iter().enumerate() {
37        if let Some(rewritten) = try_find_between(child)? {
38            new_children
39                .get_or_insert_with(|| children[..idx].to_vec())
40                .push(rewritten);
41        } else if let Some(new_children) = new_children.as_mut() {
42            new_children.push(child.clone());
43        }
44    }
45    let rewritten = new_children
46        .map(|children| expr.clone().with_children(children))
47        .transpose()?;
48
49    let current = rewritten.as_ref().unwrap_or(expr);
50    if is_and(current)
51        && let Some(merged) = merge_straddling_pairs(current)?
52    {
53        return Ok(Some(merged));
54    }
55    Ok(rewritten)
56}
57
58/// Merge pairs of range comparisons that sit on opposite sides of the `AND` node `expr`.
59///
60/// Children are rewritten before their parents, so a pair within one side was already merged at
61/// the `AND` node joining it. Only considering straddling pairs keeps the pass linear in the size
62/// of the conjunction instead of re-pairing every conjunct at every level. The rest of the tree
63/// keeps its shape: the lhs conjunct becomes the between and the rhs conjunct is removed.
64fn merge_straddling_pairs(expr: &BoundExpression) -> VortexResult<Option<BoundExpression>> {
65    let mut current: Option<BoundExpression> = None;
66
67    loop {
68        let expr = current.as_ref().unwrap_or(expr);
69        if !is_and(expr) {
70            break;
71        }
72        let lhs = expr.child(0);
73        let rhs = expr.child(1);
74
75        let Some((lower, upper, between)) = find_conjunct(rhs, &mut |rhs_conjunct| {
76            let rhs_cmp = RangeComparison::try_new(rhs_conjunct)?;
77            find_conjunct(lhs, &mut |lhs_conjunct| {
78                let lhs_cmp = RangeComparison::try_new(lhs_conjunct)?;
79                let between = lhs_cmp.between(&rhs_cmp)?;
80                Some((lhs_conjunct, rhs_conjunct, between))
81            })
82        }) else {
83            break;
84        };
85
86        tracing::debug!(%lower, %upper, "merged range comparisons into {between}");
87
88        let new_lhs = rewrite_conjunct(lhs, lower, Some(&between))?
89            .vortex_expect("matched conjunct is part of the lhs")
90            .vortex_expect("replaced conjunct is never removed");
91        let new_rhs = rewrite_conjunct(rhs, upper, None)?
92            .vortex_expect("matched conjunct is part of the rhs");
93
94        current = Some(match new_rhs {
95            Some(new_rhs) => expr.clone().with_children([new_lhs, new_rhs])?,
96            None => new_lhs,
97        });
98    }
99
100    Ok(current)
101}
102
103fn is_and(expr: &BoundExpression) -> bool {
104    expr.as_opt::<Boolean>() == Some(&BooleanOperator::And)
105}
106
107/// Return the first `Some` produced by `f` over the conjuncts of the `AND` tree rooted at `expr`.
108fn find_conjunct<'a, T>(
109    expr: &'a BoundExpression,
110    f: &mut impl FnMut(&'a BoundExpression) -> Option<T>,
111) -> Option<T> {
112    if is_and(expr) {
113        find_conjunct(expr.child(0), f).or_else(|| find_conjunct(expr.child(1), f))
114    } else {
115        f(expr)
116    }
117}
118
119/// Replace the conjunct `target`, identified by address, in the `AND` tree rooted at `expr`, or
120/// remove it when `replacement` is `None`.
121///
122/// Returns `None` when `target` is not a conjunct of `expr`, otherwise the rewritten tree, which
123/// is itself `None` when removing `target` leaves nothing behind.
124fn rewrite_conjunct(
125    expr: &BoundExpression,
126    target: &BoundExpression,
127    replacement: Option<&BoundExpression>,
128) -> VortexResult<Option<Option<BoundExpression>>> {
129    if ptr::eq(expr, target) {
130        return Ok(Some(replacement.cloned()));
131    }
132    if !is_and(expr) {
133        return Ok(None);
134    }
135
136    for idx in 0..2 {
137        let Some(new_child) = rewrite_conjunct(expr.child(idx), target, replacement)? else {
138            continue;
139        };
140        let sibling = expr.child(1 - idx).clone();
141        let rewritten = match new_child {
142            Some(new_child) if idx == 0 => expr.clone().with_children([new_child, sibling])?,
143            Some(new_child) => expr.clone().with_children([sibling, new_child])?,
144            None => sibling,
145        };
146        return Ok(Some(Some(rewritten)));
147    }
148
149    Ok(None)
150}
151
152/// A conjunct `column op literal` (in either order) that bounds `column` from one side.
153struct RangeComparison<'a> {
154    column: &'a BoundExpression,
155    literal: &'a BoundExpression,
156    is_lower: bool,
157    strict: StrictComparison,
158}
159
160impl<'a> RangeComparison<'a> {
161    fn try_new(expr: &'a BoundExpression) -> Option<Self> {
162        let operator = *expr.as_opt::<Compare>()?;
163        let lhs = expr.child(0);
164        let rhs = expr.child(1);
165
166        // Normalize the column to the left of the operator.
167        let (column, literal, operator) = if lhs.is::<GetItem>() && rhs.is::<Literal>() {
168            (lhs, rhs, operator)
169        } else if rhs.is::<GetItem>() && lhs.is::<Literal>() {
170            (rhs, lhs, operator.swap())
171        } else {
172            return None;
173        };
174
175        let (is_lower, strict) = match operator {
176            CompareOperator::Gt => (true, StrictComparison::Strict),
177            CompareOperator::Gte => (true, StrictComparison::NonStrict),
178            CompareOperator::Lt => (false, StrictComparison::Strict),
179            CompareOperator::Lte => (false, StrictComparison::NonStrict),
180            _ => return None,
181        };
182
183        Some(Self {
184            column,
185            literal,
186            is_lower,
187            strict,
188        })
189    }
190
191    /// Combine two comparisons bounding the same column from opposite sides.
192    fn between(&self, other: &Self) -> Option<BoundExpression> {
193        if self.is_lower == other.is_lower || self.column != other.column {
194            return None;
195        }
196        let (lower, upper) = if self.is_lower {
197            (self, other)
198        } else {
199            (other, self)
200        };
201
202        // A between that fails to type-check leaves the comparisons in place.
203        Between
204            .try_new_bound_expr(
205                BetweenOptions {
206                    lower_strict: lower.strict,
207                    upper_strict: upper.strict,
208                },
209                [
210                    self.column.clone(),
211                    lower.literal.clone(),
212                    upper.literal.clone(),
213                ],
214            )
215            .ok()
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use std::sync::LazyLock;
222
223    use rstest::rstest;
224    use vortex_array::IntoArray;
225    use vortex_array::VortexSessionExecute;
226    use vortex_array::arrays::BoolArray;
227    use vortex_array::arrays::StructArray;
228    use vortex_array::dtype::DType;
229    use vortex_array::dtype::Nullability;
230    use vortex_array::dtype::PType;
231    use vortex_array::dtype::StructFields;
232    use vortex_array::scalar::Scalar;
233    use vortex_buffer::buffer;
234    use vortex_error::VortexResult;
235    use vortex_expr::ArrayExprExt;
236    use vortex_expr::Expression;
237    use vortex_expr::and;
238    use vortex_expr::col;
239    use vortex_expr::gt;
240    use vortex_expr::gt_eq;
241    use vortex_expr::lit;
242    use vortex_expr::lt;
243    use vortex_expr::lt_eq;
244    use vortex_expr::or;
245    use vortex_session::VortexSession;
246
247    use super::find_between;
248    use crate::between::BetweenOptions;
249    use crate::between::StrictComparison;
250    use crate::expr::between;
251
252    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
253
254    fn scope() -> DType {
255        let i32_dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
256        DType::Struct(
257            StructFields::new(
258                ["x", "y", "z"].into(),
259                vec![i32_dtype.clone(), i32_dtype.clone(), i32_dtype],
260            ),
261            Nullability::NonNullable,
262        )
263    }
264
265    fn between_x(lower: i32, upper: i32, lower_strict: bool, upper_strict: bool) -> Expression {
266        let strictness = |strict| {
267            if strict {
268                StrictComparison::Strict
269            } else {
270                StrictComparison::NonStrict
271            }
272        };
273        between(
274            col("x"),
275            lit(lower),
276            lit(upper),
277            BetweenOptions {
278                lower_strict: strictness(lower_strict),
279                upper_strict: strictness(upper_strict),
280            },
281        )
282    }
283
284    #[rstest]
285    // An impossible range is still a between.
286    #[case::bad_match(
287        and(lt_eq(lit(100), col("x")), gt(lit(-100), col("x"))),
288        between_x(100, -100, false, true)
289    )]
290    #[case::literals_on_left(
291        and(lt(lit(2), col("x")), gt_eq(lit(5), col("x"))),
292        between_x(2, 5, true, false)
293    )]
294    #[case::columns_on_left(
295        and(gt_eq(col("x"), lit(2)), lt(col("x"), lit(5))),
296        between_x(2, 5, false, true)
297    )]
298    #[case::mixed_sides(
299        and(gt_eq(col("x"), lit(2)), gt_eq(lit(5), col("x"))),
300        between_x(2, 5, false, false)
301    )]
302    #[case::upper_first(
303        and(gt_eq(lit(5), col("x")), lt(lit(2), col("x"))),
304        between_x(2, 5, true, false)
305    )]
306    #[case::other_conjunct_first(
307        and(
308            and(gt_eq(col("y"), lit(10)), gt_eq(lit(5), col("x"))),
309            lt(lit(2), col("x")),
310        ),
311        and(gt_eq(col("y"), lit(10)), between_x(2, 5, true, false))
312    )]
313    #[case::other_conjunct_last(
314        and(
315            and(gt_eq(lit(5), col("x")), gt_eq(col("y"), lit(10))),
316            lt(lit(2), col("x")),
317        ),
318        and(between_x(2, 5, true, false), gt_eq(col("y"), lit(10)))
319    )]
320    #[case::skips_non_leaf_conjuncts(
321        and(
322            and(gt_eq(col("x"), lit(2)), gt(col("y"), col("z"))),
323            lt(col("x"), lit(5))
324        ),
325        and(between_x(2, 5, false, true), gt(col("y"), col("z")))
326    )]
327    #[case::pair_within_one_side(
328        and(
329            and(gt_eq(col("x"), lit(2)), lt(col("x"), lit(5))),
330            gt(col("y"), col("z"))
331        ),
332        and(between_x(2, 5, false, true), gt(col("y"), col("z")))
333    )]
334    #[case::under_or(
335        or(
336            and(gt_eq(col("x"), lit(2)), lt(col("x"), lit(5))),
337            gt(col("y"), col("z"))
338        ),
339        or(between_x(2, 5, false, true), gt(col("y"), col("z")))
340    )]
341    #[case::no_pair(
342        and(gt_eq(col("x"), lit(2)), lt(col("y"), lit(5))),
343        and(gt_eq(col("x"), lit(2)), lt(col("y"), lit(5)))
344    )]
345    #[case::same_direction(
346        and(gt_eq(col("x"), lit(2)), gt(col("x"), lit(5))),
347        and(gt_eq(col("x"), lit(2)), gt(col("x"), lit(5)))
348    )]
349    fn finds_between(#[case] expr: Expression, #[case] expected: Expression) -> VortexResult<()> {
350        let scope = scope();
351        assert_eq!(find_between(expr.bind(&scope)?)?, expected.bind(&scope)?);
352        Ok(())
353    }
354
355    /// Every pair straddling a single `AND` node is merged.
356    #[test]
357    fn merges_many_pairs() -> VortexResult<()> {
358        let scope = scope();
359        let lowers = ["x", "y", "z"].map(|name| gt_eq(col(name), lit(0)));
360        let uppers = ["x", "y", "z"].map(|name| lt(col(name), lit(10)));
361        let [lx, ly, lz] = lowers;
362        let [ux, uy, uz] = uppers;
363        let expr = and(and(and(lx, ly), lz), and(and(uz, uy), ux));
364
365        let range = |name| {
366            between(
367                col(name),
368                lit(0),
369                lit(10),
370                BetweenOptions {
371                    lower_strict: StrictComparison::NonStrict,
372                    upper_strict: StrictComparison::Strict,
373                },
374            )
375        };
376        let expected = and(and(range("x"), range("y")), range("z"));
377
378        assert_eq!(find_between(expr.bind(&scope)?)?, expected.bind(&scope)?);
379        Ok(())
380    }
381
382    /// A null literal bound must not change the values of the rewritten expression. Kleene `AND`
383    /// keeps a row false when the surviving comparison is false, so the rewrite cannot null it.
384    #[test]
385    fn null_literal_bound_is_value_preserving() -> VortexResult<()> {
386        let ctx = &mut SESSION.create_execution_ctx();
387        let data = StructArray::from_fields(&[("x", buffer![10, 1].into_array())])?.into_array();
388
389        let null_lit = lit(Scalar::null(DType::Primitive(
390            PType::I32,
391            Nullability::Nullable,
392        )));
393        let expr = and(gt_eq(col("x"), null_lit), lt_eq(col("x"), lit(5i32)));
394
395        let before = data
396            .clone()
397            .apply(&expr)?
398            .execute::<BoolArray>(ctx)?
399            .opt_bool_vec(ctx);
400
401        let rewritten = find_between(expr.bind(data.dtype())?)?;
402        let after = data
403            .apply_bound(&rewritten)?
404            .execute::<BoolArray>(ctx)?
405            .opt_bool_vec(ctx);
406
407        // Row 0 is false rather than null because `$.x <= 5` falsifies it on its own.
408        assert_eq!(before, [Some(false), None]);
409        assert_eq!(before, after);
410
411        Ok(())
412    }
413}