Skip to main content

datafusion_expr_common/
sort_properties.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::ops::Neg;
6
7use crate::interval_arithmetic::Interval;
8
9use arrow::compute::SortOptions;
10use arrow::datatypes::DataType;
11
12/// To propagate [`SortOptions`] across the `PhysicalExpr`, it is insufficient
13/// to simply use `Option<SortOptions>`: There must be a differentiation between
14/// unordered columns and literal values, since literals may not break the ordering
15/// when they are used as a child of some binary expression when the other child has
16/// some ordering. On the other hand, unordered columns cannot maintain ordering when
17/// they take part in such operations.
18///
19/// Example: ((a_ordered + b_unordered) + c_ordered) expression cannot end up with
20/// sorted data; however the ((a_ordered + 999) + c_ordered) expression can. Therefore,
21/// we need two different variants for literals and unordered columns as literals are
22/// often more ordering-friendly under most mathematical operations.
23#[derive(PartialEq, Debug, Clone, Copy, Default)]
24pub enum SortProperties {
25    /// Use the ordinary [`SortOptions`] struct to represent ordered data:
26    Ordered(SortOptions),
27    // This alternative represents unordered data:
28    #[default]
29    Unordered,
30    // Singleton is used for single-valued literal numbers:
31    Singleton,
32}
33
34impl SortProperties {
35    pub fn add(&self, rhs: &Self) -> Self {
36        match (self, rhs) {
37            (Self::Singleton, _) => *rhs,
38            (_, Self::Singleton) => *self,
39            (Self::Ordered(lhs), Self::Ordered(rhs))
40                if lhs.descending == rhs.descending
41                    && lhs.nulls_first == rhs.nulls_first =>
42            {
43                Self::Ordered(SortOptions {
44                    descending: lhs.descending,
45                    nulls_first: lhs.nulls_first,
46                })
47            }
48            _ => Self::Unordered,
49        }
50    }
51
52    pub fn sub(&self, rhs: &Self) -> Self {
53        match (self, rhs) {
54            (Self::Singleton, Self::Singleton) => Self::Singleton,
55            (Self::Singleton, Self::Ordered(rhs)) => Self::Ordered(SortOptions {
56                descending: !rhs.descending,
57                nulls_first: rhs.nulls_first,
58            }),
59            (_, Self::Singleton) => *self,
60            (Self::Ordered(lhs), Self::Ordered(rhs))
61                if lhs.descending != rhs.descending
62                    && lhs.nulls_first == rhs.nulls_first =>
63            {
64                Self::Ordered(SortOptions {
65                    descending: lhs.descending,
66                    nulls_first: lhs.nulls_first,
67                })
68            }
69            _ => Self::Unordered,
70        }
71    }
72
73    pub fn gt_or_gteq(&self, rhs: &Self) -> Self {
74        match (self, rhs) {
75            (Self::Singleton, Self::Ordered(rhs)) => Self::Ordered(SortOptions {
76                descending: !rhs.descending,
77                nulls_first: rhs.nulls_first,
78            }),
79            (_, Self::Singleton) => *self,
80            (Self::Ordered(lhs), Self::Ordered(rhs))
81                if lhs.descending != rhs.descending
82                    && lhs.nulls_first == rhs.nulls_first =>
83            {
84                *self
85            }
86            _ => Self::Unordered,
87        }
88    }
89
90    /// `AND` keeps an ordering only when nulls sort after `true`
91    /// (`ASC NULLS LAST`, `DESC NULLS FIRST`).
92    pub fn and(&self, rhs: &Self) -> Self {
93        self.kleene(rhs, |opt| opt.descending == opt.nulls_first)
94    }
95
96    /// `OR` keeps an ordering only when nulls sort before `false`
97    /// (`ASC NULLS FIRST`, `DESC NULLS LAST`).
98    pub fn or(&self, rhs: &Self) -> Self {
99        self.kleene(rhs, |opt| opt.descending != opt.nulls_first)
100    }
101
102    /// `preserves` reports whether the operator keeps data in that ordering.
103    /// A `Singleton` may be a literal NULL, so it carries the same guard.
104    fn kleene(&self, rhs: &Self, preserves: fn(&SortOptions) -> bool) -> Self {
105        match (self, rhs) {
106            (Self::Singleton, Self::Singleton) => Self::Singleton,
107            (Self::Ordered(opt), Self::Singleton)
108            | (Self::Singleton, Self::Ordered(opt))
109                if preserves(opt) =>
110            {
111                Self::Ordered(*opt)
112            }
113            (Self::Ordered(lhs), Self::Ordered(rhs)) if lhs == rhs && preserves(lhs) => {
114                Self::Ordered(*lhs)
115            }
116            _ => Self::Unordered,
117        }
118    }
119}
120
121#[cfg(test)]
122mod sort_properties_test {
123    use super::{SortOptions, SortProperties};
124    use rstest::rstest;
125
126    const fn ordered(descending: bool, nulls_first: bool) -> SortProperties {
127        SortProperties::Ordered(SortOptions {
128            descending,
129            nulls_first,
130        })
131    }
132
133    const ASC_NF: SortProperties = ordered(false, true);
134    const ASC_NL: SortProperties = ordered(false, false);
135    const DESC_NF: SortProperties = ordered(true, true);
136    const DESC_NL: SortProperties = ordered(true, false);
137    const UNORDERED: SortProperties = SortProperties::Unordered;
138    const SINGLETON: SortProperties = SortProperties::Singleton;
139
140    type BinOp = fn(&SortProperties, &SortProperties) -> SortProperties;
141
142    /// Each method's direction rule and its `Singleton` arms.
143    ///
144    /// Operands that *disagree* on null placement are deliberately absent:
145    /// that half is covered exhaustively by
146    /// [`conflicting_null_placement_is_never_ordered`].
147    #[test]
148    fn ordering_propagation() {
149        let cases: &[(&str, BinOp, SortProperties, SortProperties, SortProperties)] = &[
150            // `add` preserves ordering when both operands run in the same
151            // direction. It is commutative, so one argument order suffices.
152            (
153                "add: same direction is preserved",
154                SortProperties::add,
155                ASC_NF,
156                ASC_NF,
157                ASC_NF,
158            ),
159            (
160                "add: nulls_last placement is preserved",
161                SortProperties::add,
162                ASC_NL,
163                ASC_NL,
164                ASC_NL,
165            ),
166            (
167                "add: opposing directions are unordered",
168                SortProperties::add,
169                ASC_NF,
170                DESC_NF,
171                UNORDERED,
172            ),
173            (
174                "add: literal with ordered",
175                SortProperties::add,
176                SINGLETON,
177                ASC_NF,
178                ASC_NF,
179            ),
180            (
181                "add: two literals stay a literal",
182                SortProperties::add,
183                SINGLETON,
184                SINGLETON,
185                SINGLETON,
186            ),
187            // `and` keeps ASC NULLS LAST / DESC NULLS FIRST, `or` keeps ASC
188            // NULLS FIRST / DESC NULLS LAST. Both are commutative.
189            (
190                "and: ASC NULLS LAST is preserved",
191                SortProperties::and,
192                ASC_NL,
193                ASC_NL,
194                ASC_NL,
195            ),
196            (
197                "and: DESC NULLS FIRST is preserved",
198                SortProperties::and,
199                DESC_NF,
200                DESC_NF,
201                DESC_NF,
202            ),
203            (
204                "and: ASC NULLS FIRST is unordered",
205                SortProperties::and,
206                ASC_NF,
207                ASC_NF,
208                UNORDERED,
209            ),
210            (
211                "and: DESC NULLS LAST is unordered",
212                SortProperties::and,
213                DESC_NL,
214                DESC_NL,
215                UNORDERED,
216            ),
217            (
218                "and: mixed directions are unordered",
219                SortProperties::and,
220                ASC_NL,
221                DESC_NF,
222                UNORDERED,
223            ),
224            (
225                "and: literal with ASC NULLS LAST",
226                SortProperties::and,
227                SINGLETON,
228                ASC_NL,
229                ASC_NL,
230            ),
231            (
232                "and: literal with ASC NULLS FIRST is unordered",
233                SortProperties::and,
234                SINGLETON,
235                ASC_NF,
236                UNORDERED,
237            ),
238            (
239                "and: two literals stay a literal",
240                SortProperties::and,
241                SINGLETON,
242                SINGLETON,
243                SINGLETON,
244            ),
245            (
246                "or: ASC NULLS FIRST is preserved",
247                SortProperties::or,
248                ASC_NF,
249                ASC_NF,
250                ASC_NF,
251            ),
252            (
253                "or: DESC NULLS LAST is preserved",
254                SortProperties::or,
255                DESC_NL,
256                DESC_NL,
257                DESC_NL,
258            ),
259            (
260                "or: ASC NULLS LAST is unordered",
261                SortProperties::or,
262                ASC_NL,
263                ASC_NL,
264                UNORDERED,
265            ),
266            (
267                "or: DESC NULLS FIRST is unordered",
268                SortProperties::or,
269                DESC_NF,
270                DESC_NF,
271                UNORDERED,
272            ),
273            (
274                "or: mixed directions are unordered",
275                SortProperties::or,
276                ASC_NF,
277                DESC_NL,
278                UNORDERED,
279            ),
280            (
281                "or: literal with ASC NULLS FIRST",
282                SortProperties::or,
283                SINGLETON,
284                ASC_NF,
285                ASC_NF,
286            ),
287            (
288                "or: literal with ASC NULLS LAST is unordered",
289                SortProperties::or,
290                SINGLETON,
291                ASC_NL,
292                UNORDERED,
293            ),
294            (
295                "or: two literals stay a literal",
296                SortProperties::or,
297                SINGLETON,
298                SINGLETON,
299                SINGLETON,
300            ),
301            // `sub` needs the *opposite* rule: an ascending column minus a
302            // descending one still ascends. It is not commutative
303            (
304                "sub: opposing directions are preserved",
305                SortProperties::sub,
306                ASC_NF,
307                DESC_NF,
308                ASC_NF,
309            ),
310            (
311                "sub: result follows the left operand",
312                SortProperties::sub,
313                DESC_NF,
314                ASC_NF,
315                DESC_NF,
316            ),
317            (
318                "sub: nulls_last placement is preserved",
319                SortProperties::sub,
320                ASC_NL,
321                DESC_NL,
322                ASC_NL,
323            ),
324            (
325                "sub: same direction is unordered",
326                SortProperties::sub,
327                ASC_NF,
328                ASC_NF,
329                UNORDERED,
330            ),
331            (
332                "sub: literal minus ordered flips the direction",
333                SortProperties::sub,
334                SINGLETON,
335                ASC_NF,
336                DESC_NF,
337            ),
338            (
339                "sub: ordered minus literal keeps the direction",
340                SortProperties::sub,
341                ASC_NF,
342                SINGLETON,
343                ASC_NF,
344            ),
345            (
346                "sub: two literals stay a literal",
347                SortProperties::sub,
348                SINGLETON,
349                SINGLETON,
350                SINGLETON,
351            ),
352            // `gt_or_gteq` compares into a boolean column, which is ordered by
353            // `false < true`. Same direction rule as `sub`, also asymmetric.
354            (
355                "gt_or_gteq: opposing directions are preserved",
356                SortProperties::gt_or_gteq,
357                ASC_NF,
358                DESC_NF,
359                ASC_NF,
360            ),
361            (
362                "gt_or_gteq: result follows the left operand",
363                SortProperties::gt_or_gteq,
364                DESC_NF,
365                ASC_NF,
366                DESC_NF,
367            ),
368            (
369                "gt_or_gteq: nulls_last placement is preserved",
370                SortProperties::gt_or_gteq,
371                DESC_NL,
372                ASC_NL,
373                DESC_NL,
374            ),
375            (
376                "gt_or_gteq: same direction is unordered",
377                SortProperties::gt_or_gteq,
378                ASC_NF,
379                ASC_NF,
380                UNORDERED,
381            ),
382            (
383                "gt_or_gteq: literal on the left flips the direction",
384                SortProperties::gt_or_gteq,
385                SINGLETON,
386                ASC_NF,
387                DESC_NF,
388            ),
389            (
390                "gt_or_gteq: literal on the right keeps the direction",
391                SortProperties::gt_or_gteq,
392                ASC_NF,
393                SINGLETON,
394                ASC_NF,
395            ),
396            (
397                "gt_or_gteq: two literals stay a literal",
398                SortProperties::gt_or_gteq,
399                SINGLETON,
400                SINGLETON,
401                SINGLETON,
402            ),
403        ];
404
405        for &(name, op, lhs, rhs, expected) in cases {
406            assert_eq!(op(&lhs, &rhs), expected, "case: {name}");
407        }
408
409        // `add`, `and` and `or` are commutative, so the table above covers
410        // only one argument order.
411        for (lhs, rhs) in [
412            (ASC_NF, DESC_NL),
413            (ASC_NF, SINGLETON),
414            (ASC_NL, SINGLETON),
415            (ASC_NL, DESC_NF),
416        ] {
417            assert_eq!(lhs.add(&rhs), rhs.add(&lhs), "add is commutative");
418            assert_eq!(lhs.and(&rhs), rhs.and(&lhs), "and is commutative");
419            assert_eq!(lhs.or(&rhs), rhs.or(&lhs), "or is commutative");
420        }
421    }
422
423    /// If two ordered operands disagree on null placement, the result is
424    /// always Unordered, no matter which operator or direction is used.
425    /// Checked below for every combination.
426    ///
427    /// Nulls propagate through the arithmetic and comparison operators: the
428    /// result is null wherever either operand is null. `nulls_first` treats
429    /// those rows as a prefix, `nulls_last` as a suffix. A set that's both
430    /// can't be described by any `SortOptions`. `and`/`or` keep an ordering
431    /// only when both operands already share it.
432    ///
433    /// The assertion only checks "not Ordered", not which ordering
434    /// results. That keeps the test from just repeating the logic it's
435    /// checking.
436    #[rstest]
437    #[case::add("add", SortProperties::add)]
438    #[case::sub("sub", SortProperties::sub)]
439    #[case::gt_or_gteq("gt_or_gteq", SortProperties::gt_or_gteq)]
440    #[case::and("and", SortProperties::and)]
441    #[case::or("or", SortProperties::or)]
442    fn conflicting_null_placement_is_never_ordered(
443        #[values(false, true)] l_descending: bool,
444        #[values(false, true)] r_descending: bool,
445        #[values(false, true)] l_nulls_first: bool,
446        #[case] op_name: &str,
447        #[case] op: BinOp,
448    ) {
449        // Negating `l_nulls_first` makes the operands disagree by construction.
450        let lhs = ordered(l_descending, l_nulls_first);
451        let rhs = ordered(r_descending, !l_nulls_first);
452        assert_eq!(op(&lhs, &rhs), UNORDERED, "{op_name}: {lhs:?} and {rhs:?}");
453    }
454}
455
456impl Neg for SortProperties {
457    type Output = Self;
458
459    fn neg(mut self) -> Self::Output {
460        if let SortProperties::Ordered(SortOptions { descending, .. }) = &mut self {
461            *descending = !*descending;
462        }
463        self
464    }
465}
466
467/// Represents the properties of a `PhysicalExpr`, including its sorting,
468/// range, and whether it preserves lexicographical ordering.
469#[derive(Debug, Clone)]
470pub struct ExprProperties {
471    /// Properties that describe the sorting behavior of the expression,
472    /// such as whether it is ordered, unordered, or a singleton value.
473    pub sort_properties: SortProperties,
474    /// A closed interval representing the range of possible values for
475    /// the expression. Used to compute reliable bounds.
476    pub range: Interval,
477    /// Indicates whether the expression preserves lexicographical ordering
478    /// of its inputs.
479    ///
480    /// This is a *non-strict* (monotone) property: inputs advancing in
481    /// lexicographical order never make the output decrease, but distinct
482    /// inputs may map to equal outputs (ties). See
483    /// [`Self::strictly_order_preserving`] for the strict variant and an
484    /// explanation of the difference.
485    pub preserves_lex_ordering: bool,
486    /// Indicates whether the expression is strictly order-preserving with
487    /// respect to its inputs that are `Ordered`: the output is ordered in the
488    /// same direction, equal outputs can only result from equal values of
489    /// those inputs (i.e. the mapping is one-to-one), and nulls map to nulls.
490    ///
491    /// i.e. setting this to true means that `a.cmp(b) == f(a).cmp(f(b))`
492    ///
493    /// # Difference from [`Self::preserves_lex_ordering`]
494    ///
495    /// The two properties differ in both their premise and their strictness:
496    ///
497    /// - `preserves_lex_ordering` assumes the inputs advance in
498    ///   *lexicographical* order (a later input may decrease whenever an
499    ///   earlier one increases), and only promises a non-decreasing output,
500    ///   allowing distinct inputs to collapse into equal outputs; `floor`,
501    ///   `date_trunc` and narrowing casts do exactly that.
502    /// - `strictly_order_preserving` assumes every `Ordered` input advances
503    ///   *simultaneously* (component-wise, which is what actually holds when
504    ///   all of them are sorted in the data), and promises a strict output:
505    ///   equal outputs only from equal inputs.
506    ///
507    /// For an expression with a single ordered input the premises coincide,
508    /// and this field is simply the stronger claim: it implies
509    /// `preserves_lex_ordering`. With multiple ordered inputs, neither
510    /// implies the other: a lexicographical-ordering-preserving expression
511    /// need not be strict (distinct inputs may still produce equal outputs),
512    /// while `a + b` over two ordered, overflow-free inputs is strict but not
513    /// lexicographical (under the lexicographical premise `b` may decrease
514    /// while `a` increases, making the sum decrease).
515    ///
516    /// The distinction matters for suffix sort keys. Optimizers use this
517    /// field to substitute a sort key with an expression computed from it:
518    /// if data is sorted by `[x, y]`, it is also sorted by `[expr(x), y]`.
519    /// That claim requires `y` to be sorted within each run of equal
520    /// `expr(x)` values, which only holds if equal outputs imply equal `x`
521    /// values. With a merely monotone expression such as `floor`, one output
522    /// run can span several `x` groups, and `y` restarts at each group:
523    ///
524    /// ```text
525    /// sorted by [x, y]:  (1.2, 5), (1.8, 1), (2.5, 3)
526    /// [floor(x), y]:     (1, 5),   (1, 1),   (2, 3)   <-- y not sorted within
527    ///                                                     the "1" run
528    /// ```
529    ///
530    /// Hence a monotone expression only justifies the length-1 ordering
531    /// `[expr(x)]`, while a strictly order-preserving one keeps the entire
532    /// suffix valid. When in doubt, set to `false`.
533    pub strictly_order_preserving: bool,
534}
535
536impl ExprProperties {
537    /// Creates a new `ExprProperties` instance with unknown sort properties,
538    /// unknown range, and unknown lexicographical ordering preservation.
539    pub fn new_unknown() -> Self {
540        Self {
541            sort_properties: SortProperties::default(),
542            range: Interval::make_unbounded(&DataType::Null).unwrap(),
543            preserves_lex_ordering: false,
544            strictly_order_preserving: false,
545        }
546    }
547
548    /// Sets the sorting properties of the expression and returns the modified instance.
549    pub fn with_order(mut self, order: SortProperties) -> Self {
550        self.sort_properties = order;
551        self
552    }
553
554    /// Sets the range of the expression and returns the modified instance.
555    pub fn with_range(mut self, range: Interval) -> Self {
556        self.range = range;
557        self
558    }
559
560    /// Sets whether the expression maintains lexicographical ordering and returns the modified instance.
561    pub fn with_preserves_lex_ordering(mut self, preserves_lex_ordering: bool) -> Self {
562        self.preserves_lex_ordering = preserves_lex_ordering;
563        self
564    }
565
566    /// Sets whether the expression is strictly order-preserving and returns
567    /// the modified instance.
568    pub fn with_strictly_order_preserving(
569        mut self,
570        strictly_order_preserving: bool,
571    ) -> Self {
572        self.strictly_order_preserving = strictly_order_preserving;
573        self
574    }
575}