Skip to main content

datafusion_physical_expr/equivalence/
class.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::any::Any;
6use std::fmt::Display;
7use std::ops::Deref;
8use std::sync::Arc;
9use std::vec::IntoIter;
10
11use super::ProjectionMapping;
12use crate::expressions::{Column, Literal};
13use crate::physical_expr::add_offset_to_expr;
14use crate::projection::ProjectionTargets;
15use crate::scalar_subquery::ScalarSubqueryExpr;
16use crate::{PhysicalExpr, PhysicalExprRef, PhysicalSortExpr, PhysicalSortRequirement};
17
18use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
19use datafusion_common::{JoinType, Result, ScalarValue};
20use datafusion_expr::sort_properties::SortProperties;
21use datafusion_physical_expr_common::physical_expr::{
22    format_physical_expr_list, is_volatile,
23};
24
25use indexmap::{IndexMap, IndexSet};
26
27/// Represents whether a constant expression's value is uniform or varies across
28/// partitions. Has two variants:
29/// - `Heterogeneous`: The constant expression may have different values for
30///   different partitions.
31/// - `Uniform(Option<ScalarValue>)`: The constant expression has the same value
32///   across all partitions, or is `None` if the value is unknown.
33#[derive(Clone, Debug, Default, Eq, PartialEq)]
34pub enum AcrossPartitions {
35    #[default]
36    Heterogeneous,
37    Uniform(Option<ScalarValue>),
38}
39
40impl Display for AcrossPartitions {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            AcrossPartitions::Heterogeneous => write!(f, "(heterogeneous)"),
44            AcrossPartitions::Uniform(value) => {
45                if let Some(val) = value {
46                    write!(f, "(uniform: {val})")
47                } else {
48                    write!(f, "(uniform: unknown)")
49                }
50            }
51        }
52    }
53}
54
55/// A structure representing a expression known to be constant in a physical
56/// execution plan.
57///
58/// The `ConstExpr` struct encapsulates an expression that is constant during
59/// the execution of a query. For example if a filter like `A = 5` appears
60/// earlier in the plan, `A` would become a constant in subsequent operations.
61///
62/// # Fields
63///
64/// - `expr`: Constant expression for a node in the physical plan.
65/// - `across_partitions`: A boolean flag indicating whether the constant
66///   expression is the same across partitions. If set to `true`, the constant
67///   expression has same value for all partitions. If set to `false`, the
68///   constant expression may have different values for different partitions.
69///
70/// # Example
71///
72/// ```rust
73/// # use datafusion_physical_expr::ConstExpr;
74/// # use datafusion_physical_expr::expressions::lit;
75/// let col = lit(5);
76/// // Create a constant expression from a physical expression:
77/// let const_expr = ConstExpr::from(col);
78/// ```
79#[derive(Clone, Debug)]
80pub struct ConstExpr {
81    /// The expression that is known to be constant (e.g. a `Column`).
82    pub expr: Arc<dyn PhysicalExpr>,
83    /// Indicates whether the constant have the same value across all partitions.
84    pub across_partitions: AcrossPartitions,
85}
86// TODO: The `ConstExpr` definition above can be in an inconsistent state where
87//       `expr` is a literal but `across_partitions` is not `Uniform`. Consider
88//       a refactor to ensure that `ConstExpr` is always in a consistent state
89//       (either by changing type definition, or by API constraints).
90
91impl ConstExpr {
92    /// Create a new constant expression from a physical expression, specifying
93    /// whether the constant expression is the same across partitions.
94    ///
95    /// Note that you can also use `ConstExpr::from` to create a constant
96    /// expression from just a physical expression, with the *safe* assumption
97    /// of heterogenous values across partitions unless the expression is a
98    /// literal.
99    pub fn new(expr: Arc<dyn PhysicalExpr>, across_partitions: AcrossPartitions) -> Self {
100        let mut result = ConstExpr::from(expr);
101        // Override the across partitions specification if the expression is not
102        // a literal.
103        if result.across_partitions == AcrossPartitions::Heterogeneous {
104            result.across_partitions = across_partitions;
105        }
106        result
107    }
108
109    /// Returns a [`Display`]able list of `ConstExpr`.
110    pub fn format_list(input: &[ConstExpr]) -> impl Display + '_ {
111        struct DisplayableList<'a>(&'a [ConstExpr]);
112        impl Display for DisplayableList<'_> {
113            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
114                let mut first = true;
115                for const_expr in self.0 {
116                    if first {
117                        first = false;
118                    } else {
119                        write!(f, ",")?;
120                    }
121                    write!(f, "{const_expr}")?;
122                }
123                Ok(())
124            }
125        }
126        DisplayableList(input)
127    }
128}
129
130impl PartialEq for ConstExpr {
131    fn eq(&self, other: &Self) -> bool {
132        self.across_partitions == other.across_partitions && self.expr.eq(&other.expr)
133    }
134}
135
136impl Display for ConstExpr {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        write!(f, "{}", self.expr)?;
139        write!(f, "{}", self.across_partitions)
140    }
141}
142
143impl From<Arc<dyn PhysicalExpr>> for ConstExpr {
144    fn from(expr: Arc<dyn PhysicalExpr>) -> Self {
145        // By default, assume constant expressions are not same across partitions.
146        // However, if we have a literal, it will have a single value that is the
147        // same across all partitions.
148        let across = if let Some(lit) = expr.downcast_ref::<Literal>() {
149            AcrossPartitions::Uniform(Some(lit.value().clone()))
150        } else {
151            AcrossPartitions::Heterogeneous
152        };
153        Self {
154            expr,
155            across_partitions: across,
156        }
157    }
158}
159
160/// An `EquivalenceClass` is a set of [`Arc<dyn PhysicalExpr>`]s that are known
161/// to have the same value for all tuples in a relation. These are generated by
162/// equality predicates (e.g. `a = b`), typically equi-join conditions and
163/// equality conditions in filters.
164///
165/// Two `EquivalenceClass`es are equal if they contains the same expressions in
166/// without any ordering.
167#[derive(Clone, Debug, Default, Eq, PartialEq)]
168pub struct EquivalenceClass {
169    /// The expressions in this equivalence class. The order doesn't matter for
170    /// equivalence purposes.
171    pub(crate) exprs: IndexSet<Arc<dyn PhysicalExpr>>,
172    /// Indicates whether the expressions in this equivalence class have a
173    /// constant value. A `Some` value indicates constant-ness.
174    pub(crate) constant: Option<AcrossPartitions>,
175}
176
177impl EquivalenceClass {
178    /// Keeps what still holds on a join side whose unmatched rows are padded
179    /// with NULLs: padded columns stay equal to each other, but constants and
180    /// computed members do not (`coalesce(a, 0)` is 0 where `a` is NULL).
181    fn null_pad(&mut self) {
182        self.constant = None;
183        self.exprs.retain(|expr| expr.is::<Column>());
184    }
185
186    // Create a new equivalence class from a pre-existing collection.
187    pub fn new(exprs: impl IntoIterator<Item = Arc<dyn PhysicalExpr>>) -> Self {
188        let mut class = Self::default();
189        for expr in exprs {
190            class.push(expr);
191        }
192        class
193    }
194
195    /// Return the "canonical" expression for this class (the first element)
196    /// if non-empty.
197    pub fn canonical_expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {
198        self.exprs.iter().next()
199    }
200
201    /// Insert the expression into this class, meaning it is known to be equal to
202    /// all other expressions in this class.
203    pub fn push(&mut self, expr: Arc<dyn PhysicalExpr>) {
204        if let Some(lit) = expr.downcast_ref::<Literal>() {
205            let expr_across = AcrossPartitions::Uniform(Some(lit.value().clone()));
206            if let Some(across) = self.constant.as_mut() {
207                // TODO: Return an error if constant values do not agree.
208                if *across == AcrossPartitions::Heterogeneous {
209                    *across = expr_across;
210                }
211            } else {
212                self.constant = Some(expr_across);
213            }
214        }
215        self.exprs.insert(expr);
216    }
217
218    /// Inserts all the expressions from other into this class.
219    pub fn extend(&mut self, other: Self) {
220        self.exprs.extend(other.exprs);
221        match (&self.constant, &other.constant) {
222            (Some(across), Some(_)) => {
223                // TODO: Return an error if constant values do not agree.
224                if across == &AcrossPartitions::Heterogeneous {
225                    self.constant = other.constant;
226                }
227            }
228            (None, Some(_)) => self.constant = other.constant,
229            (_, None) => {}
230        }
231    }
232
233    /// Returns whether this equivalence class has any entries in common with
234    /// `other`.
235    pub fn contains_any(&self, other: &Self) -> bool {
236        self.exprs.intersection(&other.exprs).next().is_some()
237    }
238
239    /// Returns whether this equivalence class is trivial, meaning that it is
240    /// either empty, or contains a single expression that is not a constant.
241    /// Such classes are not useful, and can be removed from equivalence groups.
242    pub fn is_trivial(&self) -> bool {
243        self.exprs.is_empty() || (self.exprs.len() == 1 && self.constant.is_none())
244    }
245
246    /// Adds the given offset to all columns in the expressions inside this
247    /// class, keeping its constant value. This is used when schemas are
248    /// appended, e.g. in joins.
249    pub fn try_with_offset(&self, offset: isize) -> Result<Self> {
250        let mut cls = Self::default();
251        for expr_result in self
252            .exprs
253            .iter()
254            .cloned()
255            .map(|e| add_offset_to_expr(e, offset))
256        {
257            cls.push(expr_result?);
258        }
259        cls.constant.clone_from(&self.constant);
260        Ok(cls)
261    }
262}
263
264impl Deref for EquivalenceClass {
265    type Target = IndexSet<Arc<dyn PhysicalExpr>>;
266
267    fn deref(&self) -> &Self::Target {
268        &self.exprs
269    }
270}
271
272impl IntoIterator for EquivalenceClass {
273    type Item = Arc<dyn PhysicalExpr>;
274    type IntoIter = <IndexSet<Self::Item> as IntoIterator>::IntoIter;
275
276    fn into_iter(self) -> Self::IntoIter {
277        self.exprs.into_iter()
278    }
279}
280
281impl Display for EquivalenceClass {
282    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
283        write!(f, "{{")?;
284        write!(f, "members: {}", format_physical_expr_list(&self.exprs))?;
285        if let Some(across) = &self.constant {
286            write!(f, ", constant: {across}")?;
287        }
288        write!(f, "}}")
289    }
290}
291
292impl From<EquivalenceClass> for Vec<Arc<dyn PhysicalExpr>> {
293    fn from(cls: EquivalenceClass) -> Self {
294        cls.exprs.into_iter().collect()
295    }
296}
297
298type AugmentedMapping<'a> = IndexMap<
299    &'a Arc<dyn PhysicalExpr>,
300    (&'a ProjectionTargets, Option<&'a EquivalenceClass>),
301>;
302
303/// A collection of distinct `EquivalenceClass`es. This object supports fast
304/// lookups of expressions and their equivalence classes.
305#[derive(Clone, Debug, Default)]
306pub struct EquivalenceGroup {
307    /// A mapping from expressions to their equivalence class key.
308    map: IndexMap<Arc<dyn PhysicalExpr>, usize>,
309    /// The equivalence classes in this group.
310    classes: Vec<EquivalenceClass>,
311}
312
313impl EquivalenceGroup {
314    /// A cheap, deliberately conservative check that two groups hold the same
315    /// equivalence classes.
316    ///
317    /// This is not `PartialEq`, and the distinction is the point. `classes` is a
318    /// `Vec` whose order carries no meaning -- `remove_class_at_idx` uses
319    /// `swap_remove` -- so two groups describing exactly the same equalities can
320    /// hold their classes in different orders and this returns `false` for them.
321    /// Naming it `PartialEq` would invite callers to read it as semantic equality,
322    /// which it is not.
323    ///
324    /// The comparison is positional because it runs on a hot path:
325    /// `ProjectionExec` consults it every time a rule replaces its child. Set
326    /// semantics would mean scanning the other group once per class, and that
327    /// quadratic term costs more than the recomputation the caller is trying to
328    /// skip, by a margin that widens with the number of classes.
329    ///
330    /// Only the false direction is reachable: a group can be reported different
331    /// when it is not, never the same when it is not. Callers using this to skip
332    /// work must be built so that a `false` merely costs them that work, which is
333    /// exactly how the projection fast path uses it.
334    ///
335    /// `map` is an index into `classes` and carries no information the classes do
336    /// not already have, so it takes no part in the comparison.
337    pub fn has_same_classes(&self, other: &Self) -> bool {
338        self.classes == other.classes
339    }
340
341    /// Creates an equivalence group from the given equivalence classes.
342    pub fn new(classes: impl IntoIterator<Item = EquivalenceClass>) -> Self {
343        classes.into_iter().collect::<Vec<_>>().into()
344    }
345
346    /// Adds `expr` as a constant expression to this equivalence group.
347    pub fn add_constant(&mut self, const_expr: ConstExpr) {
348        // If the expression is already in an equivalence class, we should
349        // adjust the constant-ness of the class if necessary:
350        if let Some(idx) = self.map.get(&const_expr.expr) {
351            let cls = &mut self.classes[*idx];
352            if let Some(across) = cls.constant.as_mut() {
353                // TODO: Return an error if constant values do not agree.
354                if *across == AcrossPartitions::Heterogeneous {
355                    *across = const_expr.across_partitions;
356                }
357            } else {
358                cls.constant = Some(const_expr.across_partitions);
359            }
360            return;
361        }
362        // If the expression is not in any equivalence class, but has the same
363        // constant value with some class, add it to that class. An unknown
364        // value is never known to match, so it gets a class of its own:
365        if let AcrossPartitions::Uniform(Some(_)) = &const_expr.across_partitions {
366            for (idx, cls) in self.classes.iter_mut().enumerate() {
367                if cls
368                    .constant
369                    .as_ref()
370                    .is_some_and(|across| const_expr.across_partitions.eq(across))
371                {
372                    self.map.insert(Arc::clone(&const_expr.expr), idx);
373                    cls.push(const_expr.expr);
374                    return;
375                }
376            }
377        }
378        // Otherwise, create a new class with the expression as the only member:
379        let mut new_class = EquivalenceClass::new(std::iter::once(const_expr.expr));
380        if new_class.constant.is_none() {
381            new_class.constant = Some(const_expr.across_partitions);
382        }
383        Self::update_lookup_table(&mut self.map, &new_class, self.classes.len());
384        self.classes.push(new_class);
385    }
386
387    /// Removes constant expressions that may change across partitions.
388    /// This method should be used when merging data from different partitions.
389    /// Returns whether any change was made to the equivalence group.
390    pub fn clear_per_partition_constants(&mut self) -> bool {
391        let (mut idx, mut change) = (0, false);
392        while idx < self.classes.len() {
393            let cls = &mut self.classes[idx];
394            if cls.constant == Some(AcrossPartitions::Heterogeneous) {
395                change = true;
396                if cls.len() == 1 {
397                    // If this class becomes trivial, remove it entirely:
398                    self.remove_class_at_idx(idx);
399                    continue;
400                } else {
401                    cls.constant = None;
402                }
403            }
404            idx += 1;
405        }
406        change
407    }
408
409    /// Adds the equality `left` = `right` to this equivalence group. New
410    /// equality conditions often arise after steps like `Filter(a = b)`,
411    /// `Alias(a, a as b)` etc. Returns whether the given equality defines
412    /// a new equivalence class.
413    pub fn add_equal_conditions(
414        &mut self,
415        left: Arc<dyn PhysicalExpr>,
416        right: Arc<dyn PhysicalExpr>,
417    ) -> bool {
418        let first_class = self.map.get(&left).copied();
419        let second_class = self.map.get(&right).copied();
420        match (first_class, second_class) {
421            (Some(mut first_idx), Some(mut second_idx)) => {
422                // If the given left and right sides belong to different classes,
423                // we should unify/bridge these classes.
424                match first_idx.cmp(&second_idx) {
425                    // The equality is already known, return and signal this:
426                    std::cmp::Ordering::Equal => return false,
427                    // Swap indices to ensure `first_idx` is the lesser index.
428                    std::cmp::Ordering::Greater => {
429                        std::mem::swap(&mut first_idx, &mut second_idx);
430                    }
431                    _ => {}
432                }
433                // Remove the class at `second_idx` and merge its values with
434                // the class at `first_idx`. The convention above makes sure
435                // that `first_idx` is still valid after removing `second_idx`.
436                let other_class = self.remove_class_at_idx(second_idx);
437                // Update the lookup table for the second class:
438                Self::update_lookup_table(&mut self.map, &other_class, first_idx);
439                self.classes[first_idx].extend(other_class);
440            }
441            (Some(group_idx), None) => {
442                // Right side is new, extend left side's class:
443                self.map.insert(Arc::clone(&right), group_idx);
444                self.classes[group_idx].push(right);
445            }
446            (None, Some(group_idx)) => {
447                // Left side is new, extend right side's class:
448                self.map.insert(Arc::clone(&left), group_idx);
449                self.classes[group_idx].push(left);
450            }
451            (None, None) => {
452                // None of the expressions is among existing classes.
453                // Create a new equivalence class and extend the group.
454                let class = EquivalenceClass::new([left, right]);
455                Self::update_lookup_table(&mut self.map, &class, self.classes.len());
456                self.classes.push(class);
457                return true;
458            }
459        }
460        false
461    }
462
463    /// Removes the equivalence class at the given index from this group.
464    fn remove_class_at_idx(&mut self, idx: usize) -> EquivalenceClass {
465        // Remove the class at the given index:
466        let cls = self.classes.swap_remove(idx);
467        // Remove its entries from the lookup table:
468        for expr in cls.iter() {
469            self.map.swap_remove(expr);
470        }
471        // Update the lookup table for the moved class:
472        if idx < self.classes.len() {
473            Self::update_lookup_table(&mut self.map, &self.classes[idx], idx);
474        }
475        cls
476    }
477
478    /// Updates the entry in lookup table for the given equivalence class with
479    /// the given index.
480    fn update_lookup_table(
481        map: &mut IndexMap<Arc<dyn PhysicalExpr>, usize>,
482        cls: &EquivalenceClass,
483        idx: usize,
484    ) {
485        for expr in cls.iter() {
486            map.insert(Arc::clone(expr), idx);
487        }
488    }
489
490    /// Removes redundant entries from this group. Returns whether any change
491    /// was made to the equivalence group.
492    fn remove_redundant_entries(&mut self) -> bool {
493        // First, remove trivial equivalence classes:
494        let mut change = false;
495        for idx in (0..self.classes.len()).rev() {
496            if self.classes[idx].is_trivial() {
497                self.remove_class_at_idx(idx);
498                change = true;
499            }
500        }
501        // Then, unify/bridge groups that have common expressions:
502        self.bridge_classes() || change
503    }
504
505    /// This utility function unifies/bridges classes that have common expressions.
506    /// For example, assume that we have [`EquivalenceClass`]es `[a, b]` and `[b, c]`.
507    /// Since both classes contain `b`, columns `a`, `b` and `c` are actually all
508    /// equal and belong to one class. This utility converts merges such classes.
509    /// Returns whether any change was made to the equivalence group.
510    fn bridge_classes(&mut self) -> bool {
511        let (mut idx, mut change) = (0, false);
512        'scan: while idx < self.classes.len() {
513            for other_idx in (idx + 1..self.classes.len()).rev() {
514                if self.classes[idx].contains_any(&self.classes[other_idx]) {
515                    let extension = self.remove_class_at_idx(other_idx);
516                    Self::update_lookup_table(&mut self.map, &extension, idx);
517                    self.classes[idx].extend(extension);
518                    change = true;
519                    continue 'scan;
520                }
521            }
522            idx += 1;
523        }
524        change
525    }
526
527    /// Extends this equivalence group with the `other` equivalence group.
528    /// Returns whether any equivalence classes were unified/bridged as a
529    /// result of the extension process.
530    pub fn extend(&mut self, other: Self) -> bool {
531        for (idx, cls) in other.classes.iter().enumerate() {
532            // Update the lookup table for the new class:
533            Self::update_lookup_table(&mut self.map, cls, idx);
534        }
535        self.classes.extend(other.classes);
536        self.bridge_classes()
537    }
538
539    /// Normalizes the given physical expression according to this group. The
540    /// expression is replaced with the first (canonical) expression in the
541    /// equivalence class it matches with (if any).
542    pub fn normalize_expr(&self, expr: Arc<dyn PhysicalExpr>) -> Arc<dyn PhysicalExpr> {
543        expr.transform(|expr| {
544            let cls = self.get_equivalence_class(&expr);
545            let Some(canonical) = cls.and_then(|cls| cls.canonical_expr()) else {
546                return Ok(Transformed::no(expr));
547            };
548            Ok(Transformed::yes(Arc::clone(canonical)))
549        })
550        .data()
551        .unwrap()
552        // The unwrap above is safe because the closure always returns `Ok`.
553    }
554
555    /// Normalizes the given sort expression according to this group. The
556    /// underlying physical expression is replaced with the first expression in
557    /// the equivalence class it matches with (if any). If the underlying
558    /// expression does not belong to any equivalence class in this group,
559    /// returns the sort expression as is.
560    pub fn normalize_sort_expr(
561        &self,
562        mut sort_expr: PhysicalSortExpr,
563    ) -> PhysicalSortExpr {
564        sort_expr.expr = self.normalize_expr(sort_expr.expr);
565        sort_expr
566    }
567
568    /// Normalizes the given sort expressions (i.e. `sort_exprs`) by:
569    /// - Replacing sections that belong to some equivalence class in the
570    ///   with the first entry in the matching equivalence class.
571    /// - Removing expressions that have a constant value.
572    ///
573    /// If columns `a` and `b` are known to be equal, `d` is known to be a
574    /// constant, and `sort_exprs` is `[b ASC, d DESC, c ASC, a ASC]`, this
575    /// function would return `[a ASC, c ASC, a ASC]`.
576    pub fn normalize_sort_exprs<'a>(
577        &'a self,
578        sort_exprs: impl IntoIterator<Item = PhysicalSortExpr> + 'a,
579    ) -> impl Iterator<Item = PhysicalSortExpr> + 'a {
580        sort_exprs
581            .into_iter()
582            .map(|sort_expr| self.normalize_sort_expr(sort_expr))
583            .filter(|sort_expr| !self.is_uniform_constant(&sort_expr.expr))
584    }
585
586    /// Returns `true` when `expr` is a *globally* constant column, safe to drop
587    /// from a required ordering. Only [`AcrossPartitions::Uniform`] qualifies; a
588    /// [`AcrossPartitions::Heterogeneous`] value is constant within a partition
589    /// but varies across partitions, so it still discriminates the order once
590    /// partitions are merged and must be kept.
591    fn is_uniform_constant(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {
592        matches!(
593            self.is_expr_constant(expr),
594            Some(AcrossPartitions::Uniform(_))
595        )
596    }
597
598    /// Normalizes the given sort requirement according to this group. The
599    /// underlying physical expression is replaced with the first expression in
600    /// the equivalence class it matches with (if any). If the underlying
601    /// expression does not belong to any equivalence class in this group,
602    /// returns the given sort requirement as is.
603    pub fn normalize_sort_requirement(
604        &self,
605        mut sort_requirement: PhysicalSortRequirement,
606    ) -> PhysicalSortRequirement {
607        sort_requirement.expr = self.normalize_expr(sort_requirement.expr);
608        sort_requirement
609    }
610
611    /// Normalizes the given sort requirements (i.e. `sort_reqs`) by:
612    /// - Replacing sections that belong to some equivalence class in the
613    ///   with the first entry in the matching equivalence class.
614    /// - Removing expressions that have a constant value.
615    ///
616    /// If columns `a` and `b` are known to be equal, `d` is known to be a
617    /// constant, and `sort_reqs` is `[b ASC, d DESC, c ASC, a ASC]`, this
618    /// function would return `[a ASC, c ASC, a ASC]`.
619    pub fn normalize_sort_requirements<'a>(
620        &'a self,
621        sort_reqs: impl IntoIterator<Item = PhysicalSortRequirement> + 'a,
622    ) -> impl Iterator<Item = PhysicalSortRequirement> + 'a {
623        sort_reqs
624            .into_iter()
625            .map(|req| self.normalize_sort_requirement(req))
626            .filter(|req| !self.is_uniform_constant(&req.expr))
627    }
628
629    /// Projects `expr` through its children or an equivalent expression in the
630    /// mapping, preferring to preserve its structure.
631    fn project_expr_indirect(
632        aug_mapping: &AugmentedMapping,
633        expr: &Arc<dyn PhysicalExpr>,
634    ) -> Option<Arc<dyn PhysicalExpr>> {
635        // These leaves do not read columns from the projected input schema.
636        if expr.is::<Literal>() || expr.is::<ScalarSubqueryExpr>() {
637            return Some(Arc::clone(expr));
638        }
639
640        // Preserve expression structure when its children can be projected.
641        // Otherwise, projecting a class such as a + 1 = b can collapse it to
642        // b = b, losing the equivalence even when a survives the projection.
643        let children = expr.children();
644        if !children.is_empty() {
645            let projected_children = children
646                .into_iter()
647                .map(|child| {
648                    // First, we try to project children with an exact match. If
649                    // we are unable to do this, we consult equivalence classes.
650                    if let Some((targets, _)) = aug_mapping.get(child) {
651                        // If we match the source, we can project directly:
652                        let (target, _) = targets.first();
653                        Some(Arc::clone(target))
654                    } else {
655                        Self::project_expr_indirect(aug_mapping, child)
656                    }
657                })
658                .collect::<Option<Vec<_>>>();
659            if let Some(children) = projected_children {
660                return Some(Arc::clone(expr).with_new_children(children).unwrap());
661            }
662        }
663
664        // Project expressions whose children could not be projected by consulting
665        // equivalence classes.
666        for (targets, eq_class) in aug_mapping.values() {
667            // If we match an equivalent expression to a source expression in
668            // the mapping, then we can project. For example, if we have the
669            // mapping `(a as a1, a + c)` and the equivalence `a == b`,
670            // expression `b` projects to `a1`.
671            if eq_class.as_ref().is_some_and(|cls| cls.contains(expr)) {
672                let (target, _) = targets.first();
673                return Some(Arc::clone(target));
674            }
675        }
676        None
677    }
678
679    fn augment_projection_mapping<'a>(
680        &'a self,
681        mapping: &'a ProjectionMapping,
682    ) -> AugmentedMapping<'a> {
683        mapping
684            .iter()
685            .map(|(k, v)| {
686                // A source expression may only be in a class in its normalized
687                // form. For example, if `a == b`, `a + c` is in a class, and
688                // the mapping has `b + c`, then the class of `b + c` is found
689                // only through `a + c`. A leaf that is in no class normalizes
690                // to itself, so only expressions with children are normalized.
691                let eq_class = self.get_equivalence_class(k).or_else(|| {
692                    if k.children().is_empty() {
693                        return None;
694                    }
695                    self.get_equivalence_class(&self.normalize_expr(Arc::clone(k)))
696                });
697                (k, (v, eq_class))
698            })
699            .collect()
700    }
701
702    /// Projects `expr` according to the given projection mapping.
703    /// If the resulting expression is invalid after projection, returns `None`.
704    pub fn project_expr(
705        &self,
706        mapping: &ProjectionMapping,
707        expr: &Arc<dyn PhysicalExpr>,
708    ) -> Option<Arc<dyn PhysicalExpr>> {
709        if let Some(targets) = mapping.get(expr) {
710            // If we match the source, we can project directly:
711            let (target, _) = targets.first();
712            Some(Arc::clone(target))
713        } else {
714            let aug_mapping = self.augment_projection_mapping(mapping);
715            Self::project_expr_indirect(&aug_mapping, expr)
716        }
717    }
718
719    /// Projects `expressions` according to the given projection mapping.
720    /// This function is similar to [`Self::project_expr`], but projects multiple
721    /// expressions at once more efficiently than calling `project_expr` for each
722    /// expression.
723    pub fn project_expressions<'a>(
724        &'a self,
725        mapping: &'a ProjectionMapping,
726        expressions: impl IntoIterator<Item = &'a Arc<dyn PhysicalExpr>> + 'a,
727    ) -> impl Iterator<Item = Option<Arc<dyn PhysicalExpr>>> + 'a {
728        let mut aug_mapping = None;
729        expressions.into_iter().map(move |expr| {
730            if let Some(targets) = mapping.get(expr) {
731                // If we match the source, we can project directly:
732                let (target, _) = targets.first();
733                Some(Arc::clone(target))
734            } else {
735                let aug_mapping = aug_mapping
736                    .get_or_insert_with(|| self.augment_projection_mapping(mapping));
737                Self::project_expr_indirect(aug_mapping, expr)
738            }
739        })
740    }
741
742    /// Projects this equivalence group according to the given projection mapping.
743    pub fn project(&self, mapping: &ProjectionMapping) -> Self {
744        let projected_classes = self.iter().map(|cls| {
745            let new_exprs = self.project_expressions(mapping, cls.iter());
746            let mut projected = EquivalenceClass::new(new_exprs.flatten());
747            // Projection changes column references, not constant values or how
748            // they are distributed across partitions.
749            projected.constant = projected.constant.or_else(|| cls.constant.clone());
750            projected
751        });
752
753        // The key is the source expression, and the value is the equivalence
754        // class that contains the corresponding target expression.
755        let mut new_constants = vec![];
756        let mut new_classes =
757            IndexMap::<_, EquivalenceClass>::with_capacity(mapping.len());
758        let mut augmented = None;
759        for (source, targets) in mapping.iter() {
760            // We need to find equivalent projected expressions. For example,
761            // consider a table with columns `[a, b, c]` with `a` == `b`, and
762            // projection `[a + c, b + c]`. To conclude that `a + c == b + c`,
763            // we first normalize all source expressions in the mapping, then
764            // merge all equivalent expressions into the classes.
765            let normalized_expr = self.normalize_expr(Arc::clone(source));
766            let cls = new_classes.entry(normalized_expr).or_default();
767            for (target, _) in targets.iter() {
768                cls.push(Arc::clone(target));
769            }
770            // Retain deterministic expressions as equalities so orderings derived
771            // through strict functions can be inferred after a merge clears orderings.
772            if !source.children().is_empty() && !is_volatile(source) {
773                let augmented = augmented
774                    .get_or_insert_with(|| self.augment_projection_mapping(mapping));
775                if let Some(projected) = Self::project_expr_indirect(augmented, source) {
776                    cls.push(projected);
777                }
778            }
779            // Save new constants arising from the projection:
780            if let Some(across) = self.is_expr_constant(source) {
781                for (target, _) in targets.iter() {
782                    let const_expr = ConstExpr::new(Arc::clone(target), across.clone());
783                    new_constants.push(const_expr);
784                }
785            }
786        }
787
788        // Union projected classes with new classes to make up the result:
789        let classes = projected_classes
790            .chain(new_classes.into_values())
791            .filter(|cls| !cls.is_trivial());
792        let mut result = Self::new(classes);
793        // Add new constants arising from the projection to the equivalence group:
794        for constant in new_constants {
795            result.add_constant(constant);
796        }
797        result
798    }
799
800    /// Returns a `Some` value if the expression is constant according to
801    /// equivalence group, and `None` otherwise. The `Some` variant contains
802    /// an `AcrossPartitions` value indicating whether the expression is
803    /// constant across partitions, and its actual value (if available).
804    pub fn is_expr_constant(
805        &self,
806        expr: &Arc<dyn PhysicalExpr>,
807    ) -> Option<AcrossPartitions> {
808        if let Some(lit) = expr.downcast_ref::<Literal>() {
809            return Some(AcrossPartitions::Uniform(Some(lit.value().clone())));
810        }
811        if let Some(cls) = self.get_equivalence_class(expr)
812            && cls.constant.is_some()
813        {
814            return cls.constant.clone();
815        }
816        // TODO: This function should be able to return values of non-literal
817        //       complex constants as well; e.g. it should return `8` for the
818        //       expression `3 + 5`, not an unknown `heterogenous` value.
819        // A volatile expression can change from row to row, even when all of
820        // its inputs are constant
821        if expr.is_volatile_node() {
822            return None;
823        }
824        let children = expr.children();
825        if children.is_empty() {
826            // A leaf that reads no column can still be constant, e.g. an
827            // uncorrelated scalar subquery, which reports itself as a
828            // singleton. It does not depend on the row or the partition, so
829            // its value is the same everywhere, even if it is not known yet.
830            let singleton = expr
831                .get_properties(&[])
832                .is_ok_and(|props| props.sort_properties == SortProperties::Singleton);
833            return singleton.then_some(AcrossPartitions::Uniform(None));
834        }
835        for child in children {
836            self.is_expr_constant(child)?;
837        }
838        Some(AcrossPartitions::Heterogeneous)
839    }
840
841    /// Returns the equivalence class containing `expr`. If no equivalence class
842    /// contains `expr`, returns `None`.
843    pub fn get_equivalence_class(
844        &self,
845        expr: &Arc<dyn PhysicalExpr>,
846    ) -> Option<&EquivalenceClass> {
847        self.map.get(expr).map(|idx| &self.classes[*idx])
848    }
849
850    /// Combine equivalence groups of the given join children.
851    pub fn join(
852        &self,
853        right_equivalences: &Self,
854        join_type: &JoinType,
855        left_size: usize,
856        on: &[(PhysicalExprRef, PhysicalExprRef)],
857    ) -> Result<Self> {
858        let group = match join_type {
859            JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right => {
860                let mut result = Self::new(
861                    self.iter()
862                        .cloned()
863                        .map(|mut cls| {
864                            // Rows without a match on the left side are
865                            // padded with NULLs, so its constants and computed
866                            // equalities no longer hold.
867                            if matches!(join_type, JoinType::Right | JoinType::Full) {
868                                cls.null_pad();
869                            }
870                            cls
871                        })
872                        .chain(
873                            right_equivalences
874                                .iter()
875                                .map(|cls| {
876                                    let mut cls = cls.try_with_offset(left_size as _)?;
877                                    // Rows without a match on the right side are
878                                    // padded with NULLs, so its constants and computed
879                                    // equalities no longer hold.
880                                    if matches!(
881                                        join_type,
882                                        JoinType::Left | JoinType::Full
883                                    ) {
884                                        cls.null_pad();
885                                    }
886                                    Ok(cls)
887                                })
888                                .collect::<Result<Vec<_>>>()?,
889                        ),
890                );
891                // In we have an inner join, expressions in the "on" condition
892                // are equal in the resulting table.
893                if join_type == &JoinType::Inner {
894                    for (lhs, rhs) in on.iter() {
895                        let new_lhs = Arc::clone(lhs);
896                        // Rewrite rhs to point to the right side of the join:
897                        let new_rhs =
898                            add_offset_to_expr(Arc::clone(rhs), left_size as _)?;
899                        result.add_equal_conditions(new_lhs, new_rhs);
900                    }
901                }
902                result
903            }
904            JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => self.clone(),
905            JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
906                right_equivalences.clone()
907            }
908        };
909        Ok(group)
910    }
911
912    /// Checks if two expressions are equal directly or through equivalence
913    /// classes. For complex expressions (e.g. `a + b`), checks that the
914    /// expression trees are structurally identical and their leaf nodes are
915    /// equivalent either directly or through equivalence classes.
916    pub fn exprs_equal(
917        &self,
918        left: &Arc<dyn PhysicalExpr>,
919        right: &Arc<dyn PhysicalExpr>,
920    ) -> bool {
921        // Direct equality check
922        if left.eq(right) {
923            return true;
924        }
925
926        // Check if expressions are equivalent through equivalence classes
927        // We need to check both directions since expressions might be in different classes
928        if let Some(left_class) = self.get_equivalence_class(left)
929            && left_class.contains(right)
930        {
931            return true;
932        }
933        if let Some(right_class) = self.get_equivalence_class(right)
934            && right_class.contains(left)
935        {
936            return true;
937        }
938
939        // For non-leaf nodes, check structural equality
940        let left_children = left.children();
941        let right_children = right.children();
942
943        // If either expression is a leaf node and we haven't found equality yet,
944        // they must be different
945        if left_children.is_empty() || right_children.is_empty() {
946            return false;
947        }
948
949        // Type equality check through reflection
950        if (left as &dyn Any).type_id() != (right as &dyn Any).type_id() {
951            return false;
952        }
953
954        // Check if the number of children is the same
955        if left_children.len() != right_children.len() {
956            return false;
957        }
958
959        // Check if all children are equal
960        left_children
961            .into_iter()
962            .zip(right_children)
963            .all(|(left_child, right_child)| self.exprs_equal(left_child, right_child))
964    }
965}
966
967impl Deref for EquivalenceGroup {
968    type Target = [EquivalenceClass];
969
970    fn deref(&self) -> &Self::Target {
971        &self.classes
972    }
973}
974
975impl IntoIterator for EquivalenceGroup {
976    type Item = EquivalenceClass;
977    type IntoIter = IntoIter<Self::Item>;
978
979    fn into_iter(self) -> Self::IntoIter {
980        self.classes.into_iter()
981    }
982}
983
984impl Display for EquivalenceGroup {
985    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
986        write!(f, "[")?;
987        let mut iter = self.iter();
988        if let Some(cls) = iter.next() {
989            write!(f, "{cls}")?;
990        }
991        for cls in iter {
992            write!(f, ", {cls}")?;
993        }
994        write!(f, "]")
995    }
996}
997
998impl From<Vec<EquivalenceClass>> for EquivalenceGroup {
999    fn from(classes: Vec<EquivalenceClass>) -> Self {
1000        let mut result = Self {
1001            map: classes
1002                .iter()
1003                .enumerate()
1004                .flat_map(|(idx, cls)| {
1005                    cls.iter().map(move |expr| (Arc::clone(expr), idx))
1006                })
1007                .collect(),
1008            classes,
1009        };
1010        result.remove_redundant_entries();
1011        result
1012    }
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use super::*;
1018    use crate::equivalence::tests::create_test_params;
1019    use crate::expressions::{BinaryExpr, Column, binary, col, lit};
1020    use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
1021
1022    use datafusion_expr::Operator;
1023
1024    #[test]
1025    fn test_bridge_groups() -> Result<()> {
1026        // First entry in the tuple is argument, second entry is the bridged result
1027        let test_cases = vec![
1028            // ------- TEST CASE 1 -----------//
1029            (
1030                vec![vec![1, 2, 3], vec![2, 4, 5], vec![11, 12, 9], vec![7, 6, 5]],
1031                // Expected is compared with set equality. Order of the specific results may change.
1032                vec![vec![1, 2, 3, 4, 5, 6, 7], vec![9, 11, 12]],
1033            ),
1034            // ------- TEST CASE 2 -----------//
1035            (
1036                vec![vec![1, 2, 3], vec![3, 4, 5], vec![9, 8, 7], vec![7, 6, 5]],
1037                // Expected
1038                vec![vec![1, 2, 3, 4, 5, 6, 7, 8, 9]],
1039            ),
1040        ];
1041        for (entries, expected) in test_cases {
1042            let entries = entries
1043                .into_iter()
1044                .map(|entry| {
1045                    entry.into_iter().map(|idx| {
1046                        let c = Column::new(format!("col_{idx}").as_str(), idx);
1047                        Arc::new(c) as _
1048                    })
1049                })
1050                .map(EquivalenceClass::new)
1051                .collect::<Vec<_>>();
1052            let expected = expected
1053                .into_iter()
1054                .map(|entry| {
1055                    entry.into_iter().map(|idx| {
1056                        let c = Column::new(format!("col_{idx}").as_str(), idx);
1057                        Arc::new(c) as _
1058                    })
1059                })
1060                .map(EquivalenceClass::new)
1061                .collect::<Vec<_>>();
1062            let eq_groups: EquivalenceGroup = entries.clone().into();
1063            let eq_groups = eq_groups.classes;
1064            let err_msg = format!(
1065                "error in test entries: {entries:?}, expected: {expected:?}, actual:{eq_groups:?}"
1066            );
1067            assert_eq!(eq_groups.len(), expected.len(), "{err_msg}");
1068            for idx in 0..eq_groups.len() {
1069                assert_eq!(&eq_groups[idx], &expected[idx], "{err_msg}");
1070            }
1071        }
1072        Ok(())
1073    }
1074
1075    #[test]
1076    fn test_remove_redundant_entries_eq_group() -> Result<()> {
1077        let c = |idx| Arc::new(Column::new(format!("col_{idx}").as_str(), idx)) as _;
1078        let entries = [
1079            EquivalenceClass::new([c(1), c(1), lit(20)]),
1080            EquivalenceClass::new([lit(30), lit(30)]),
1081            EquivalenceClass::new([c(2), c(3), c(4)]),
1082        ];
1083        // Given equivalences classes are not in succinct form.
1084        // Expected form is the most plain representation that is functionally same.
1085        let expected = [
1086            EquivalenceClass::new([c(1), lit(20)]),
1087            EquivalenceClass::new([lit(30)]),
1088            EquivalenceClass::new([c(2), c(3), c(4)]),
1089        ];
1090        let eq_groups = EquivalenceGroup::new(entries);
1091        assert_eq!(eq_groups.classes, expected);
1092        Ok(())
1093    }
1094
1095    #[test]
1096    fn test_schema_normalize_expr_with_equivalence() -> Result<()> {
1097        let col_a = Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>;
1098        let col_b = Arc::new(Column::new("b", 1)) as _;
1099        let col_c = Arc::new(Column::new("c", 2)) as _;
1100        // Assume that column a and c are aliases.
1101        let (_, eq_properties) = create_test_params()?;
1102        // Test cases for equivalence normalization. First entry in the tuple is
1103        // the argument, second entry is expected result after normalization.
1104        let expressions = vec![
1105            // Normalized version of the column a and c should go to a
1106            // (by convention all the expressions inside equivalence class are mapped to the first entry
1107            // in this case a is the first entry in the equivalence class.)
1108            (Arc::clone(&col_a), Arc::clone(&col_a)),
1109            (col_c, col_a),
1110            // Cannot normalize column b
1111            (Arc::clone(&col_b), Arc::clone(&col_b)),
1112        ];
1113        let eq_group = eq_properties.eq_group();
1114        for (expr, expected_eq) in expressions {
1115            assert!(expected_eq.eq(&eq_group.normalize_expr(expr)));
1116        }
1117
1118        Ok(())
1119    }
1120
1121    #[test]
1122    fn test_contains_any() {
1123        let lit_true = Arc::new(Literal::new(ScalarValue::from(true))) as _;
1124        let lit_false = Arc::new(Literal::new(ScalarValue::from(false))) as _;
1125        let col_a_expr = Arc::new(Column::new("a", 0)) as _;
1126        let col_b_expr = Arc::new(Column::new("b", 1)) as _;
1127        let col_c_expr = Arc::new(Column::new("c", 2)) as _;
1128
1129        let cls1 = EquivalenceClass::new([Arc::clone(&lit_true), col_a_expr]);
1130        let cls2 = EquivalenceClass::new([lit_true, col_b_expr]);
1131        let cls3 = EquivalenceClass::new([col_c_expr, lit_false]);
1132
1133        // lit_true is common
1134        assert!(cls1.contains_any(&cls2));
1135        // there is no common entry
1136        assert!(!cls1.contains_any(&cls3));
1137        assert!(!cls2.contains_any(&cls3));
1138    }
1139
1140    #[test]
1141    fn test_exprs_equal() -> Result<()> {
1142        struct TestCase {
1143            left: Arc<dyn PhysicalExpr>,
1144            right: Arc<dyn PhysicalExpr>,
1145            expected: bool,
1146            description: &'static str,
1147        }
1148
1149        // Create test columns
1150        let col_a = Arc::new(Column::new("a", 0)) as _;
1151        let col_b = Arc::new(Column::new("b", 1)) as _;
1152        let col_x = Arc::new(Column::new("x", 2)) as _;
1153        let col_y = Arc::new(Column::new("y", 3)) as _;
1154
1155        // Create test literals
1156        let lit_1 = Arc::new(Literal::new(ScalarValue::from(1))) as _;
1157        let lit_2 = Arc::new(Literal::new(ScalarValue::from(2))) as _;
1158
1159        // Create equivalence group with classes (a = x) and (b = y)
1160        let eq_group = EquivalenceGroup::new([
1161            EquivalenceClass::new([Arc::clone(&col_a), Arc::clone(&col_x)]),
1162            EquivalenceClass::new([Arc::clone(&col_b), Arc::clone(&col_y)]),
1163        ]);
1164
1165        let test_cases = vec![
1166            // Basic equality tests
1167            TestCase {
1168                left: Arc::clone(&col_a),
1169                right: Arc::clone(&col_a),
1170                expected: true,
1171                description: "Same column should be equal",
1172            },
1173            // Equivalence class tests
1174            TestCase {
1175                left: Arc::clone(&col_a),
1176                right: Arc::clone(&col_x),
1177                expected: true,
1178                description: "Columns in same equivalence class should be equal",
1179            },
1180            TestCase {
1181                left: Arc::clone(&col_b),
1182                right: Arc::clone(&col_y),
1183                expected: true,
1184                description: "Columns in same equivalence class should be equal",
1185            },
1186            TestCase {
1187                left: Arc::clone(&col_a),
1188                right: Arc::clone(&col_b),
1189                expected: false,
1190                description: "Columns in different equivalence classes should not be equal",
1191            },
1192            // Literal tests
1193            TestCase {
1194                left: Arc::clone(&lit_1),
1195                right: Arc::clone(&lit_1),
1196                expected: true,
1197                description: "Same literal should be equal",
1198            },
1199            TestCase {
1200                left: Arc::clone(&lit_1),
1201                right: Arc::clone(&lit_2),
1202                expected: false,
1203                description: "Different literals should not be equal",
1204            },
1205            // Complex expression tests
1206            TestCase {
1207                left: Arc::new(BinaryExpr::new(
1208                    Arc::clone(&col_a),
1209                    Operator::Plus,
1210                    Arc::clone(&col_b),
1211                )) as _,
1212                right: Arc::new(BinaryExpr::new(
1213                    Arc::clone(&col_x),
1214                    Operator::Plus,
1215                    Arc::clone(&col_y),
1216                )) as _,
1217                expected: true,
1218                description: "Binary expressions with equivalent operands should be equal",
1219            },
1220            TestCase {
1221                left: Arc::new(BinaryExpr::new(
1222                    Arc::clone(&col_a),
1223                    Operator::Plus,
1224                    Arc::clone(&col_b),
1225                )) as _,
1226                right: Arc::new(BinaryExpr::new(
1227                    Arc::clone(&col_x),
1228                    Operator::Plus,
1229                    Arc::clone(&col_a),
1230                )) as _,
1231                expected: false,
1232                description: "Binary expressions with non-equivalent operands should not be equal",
1233            },
1234            TestCase {
1235                left: Arc::new(BinaryExpr::new(
1236                    Arc::clone(&col_a),
1237                    Operator::Plus,
1238                    Arc::clone(&lit_1),
1239                )) as _,
1240                right: Arc::new(BinaryExpr::new(
1241                    Arc::clone(&col_x),
1242                    Operator::Plus,
1243                    Arc::clone(&lit_1),
1244                )) as _,
1245                expected: true,
1246                description: "Binary expressions with equivalent column and same literal should be equal",
1247            },
1248            TestCase {
1249                left: Arc::new(BinaryExpr::new(
1250                    Arc::new(BinaryExpr::new(
1251                        Arc::clone(&col_a),
1252                        Operator::Plus,
1253                        Arc::clone(&col_b),
1254                    )),
1255                    Operator::Multiply,
1256                    Arc::clone(&lit_1),
1257                )) as _,
1258                right: Arc::new(BinaryExpr::new(
1259                    Arc::new(BinaryExpr::new(
1260                        Arc::clone(&col_x),
1261                        Operator::Plus,
1262                        Arc::clone(&col_y),
1263                    )),
1264                    Operator::Multiply,
1265                    Arc::clone(&lit_1),
1266                )) as _,
1267                expected: true,
1268                description: "Nested binary expressions with equivalent operands should be equal",
1269            },
1270        ];
1271
1272        for TestCase {
1273            left,
1274            right,
1275            expected,
1276            description,
1277        } in test_cases
1278        {
1279            let actual = eq_group.exprs_equal(&left, &right);
1280            assert_eq!(
1281                actual, expected,
1282                "{description}: Failed comparing {left:?} and {right:?}, expected {expected}, got {actual}"
1283            );
1284        }
1285
1286        Ok(())
1287    }
1288
1289    #[test]
1290    fn test_project_classes() -> Result<()> {
1291        // - columns: [a, b, c].
1292        // - "a" and "b" in the same equivalence class.
1293        // - then after a+c, b+c projection col(0) and col(1) must be
1294        // in the same class too.
1295        let schema = Arc::new(Schema::new(vec![
1296            Field::new("a", DataType::Int32, false),
1297            Field::new("b", DataType::Int32, false),
1298            Field::new("c", DataType::Int32, false),
1299        ]));
1300        let mut group = EquivalenceGroup::default();
1301        group.add_equal_conditions(col("a", &schema)?, col("b", &schema)?);
1302
1303        let projected_schema = Arc::new(Schema::new(vec![
1304            Field::new("a+c", DataType::Int32, false),
1305            Field::new("b+c", DataType::Int32, false),
1306        ]));
1307
1308        let mapping = [
1309            (
1310                binary(
1311                    col("a", &schema)?,
1312                    Operator::Plus,
1313                    col("c", &schema)?,
1314                    &schema,
1315                )?,
1316                vec![(col("a+c", &projected_schema)?, 0)].into(),
1317            ),
1318            (
1319                binary(
1320                    col("b", &schema)?,
1321                    Operator::Plus,
1322                    col("c", &schema)?,
1323                    &schema,
1324                )?,
1325                vec![(col("b+c", &projected_schema)?, 1)].into(),
1326            ),
1327        ]
1328        .into_iter()
1329        .collect::<ProjectionMapping>();
1330
1331        let projected = group.project(&mapping);
1332
1333        assert!(!projected.is_empty());
1334        let first_normalized = projected.normalize_expr(col("a+c", &projected_schema)?);
1335        let second_normalized = projected.normalize_expr(col("b+c", &projected_schema)?);
1336
1337        assert!(first_normalized.eq(&second_normalized));
1338
1339        Ok(())
1340    }
1341
1342    #[test]
1343    fn test_project_preserves_constant_metadata() -> Result<()> {
1344        let schema = abc_schema();
1345        let expr = binary(col("b", &schema)?, Operator::Divide, lit(2i32), &schema)?;
1346        let mapping = ProjectionMapping::from_indices(&[1], &schema)?;
1347        let dropped_mapping = ProjectionMapping::from_indices(&[0], &schema)?;
1348        let projected_b: Arc<dyn PhysicalExpr> = Arc::new(Column::new("b", 0));
1349        let projected_expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
1350            Arc::clone(&projected_b),
1351            Operator::Divide,
1352            lit(2i32),
1353        ));
1354
1355        for across in [
1356            AcrossPartitions::Uniform(Some(ScalarValue::Int32(Some(2)))),
1357            AcrossPartitions::Uniform(None),
1358            AcrossPartitions::Heterogeneous,
1359        ] {
1360            let mut group = EquivalenceGroup::default();
1361            // The class has no literal member, so `EquivalenceClass::new` cannot
1362            // restore the constant.
1363            group.add_constant(ConstExpr::new(Arc::clone(&expr), across.clone()));
1364
1365            let mut projected = group.project(&mapping);
1366            assert_eq!(
1367                projected.is_expr_constant(&projected_expr),
1368                Some(across.clone())
1369            );
1370            // A constant expression does not imply that its argument is constant.
1371            assert_eq!(projected.is_expr_constant(&projected_b), None);
1372            assert!(group.project(&dropped_mapping).is_empty());
1373
1374            let heterogeneous = across == AcrossPartitions::Heterogeneous;
1375            assert_eq!(projected.clear_per_partition_constants(), heterogeneous);
1376            assert_eq!(
1377                projected.is_expr_constant(&projected_expr),
1378                (!heterogeneous).then_some(across)
1379            );
1380        }
1381
1382        Ok(())
1383    }
1384
1385    #[test]
1386    fn test_project_constant_of_equivalent_source() -> Result<()> {
1387        // - columns: [a, b, c].
1388        // - "a" and "b" in the same equivalence class, and a + c = 7.
1389        // - then after a b + c projection, col(0) must be the constant 7.
1390        let schema = Arc::new(Schema::new(vec![
1391            Field::new("a", DataType::Int32, false),
1392            Field::new("b", DataType::Int32, false),
1393            Field::new("c", DataType::Int32, false),
1394        ]));
1395        let mut group = EquivalenceGroup::default();
1396        group.add_equal_conditions(col("a", &schema)?, col("b", &schema)?);
1397        group.add_equal_conditions(
1398            binary(
1399                col("a", &schema)?,
1400                Operator::Plus,
1401                col("c", &schema)?,
1402                &schema,
1403            )?,
1404            lit(7),
1405        );
1406
1407        let projected_schema =
1408            Arc::new(Schema::new(vec![Field::new("b+c", DataType::Int32, false)]));
1409        let mapping = std::iter::once((
1410            binary(
1411                col("b", &schema)?,
1412                Operator::Plus,
1413                col("c", &schema)?,
1414                &schema,
1415            )?,
1416            vec![(col("b+c", &projected_schema)?, 0)].into(),
1417        ))
1418        .collect::<ProjectionMapping>();
1419
1420        let projected = group.project(&mapping);
1421
1422        assert_eq!(
1423            projected.is_expr_constant(&col("b+c", &projected_schema)?),
1424            Some(AcrossPartitions::Uniform(Some(ScalarValue::Int32(Some(7)))))
1425        );
1426
1427        Ok(())
1428    }
1429
1430    #[test]
1431    fn test_project_class_of_equivalent_source() -> Result<()> {
1432        // - columns: [a, b, c, d].
1433        // - "a" and "b" in the same equivalence class, and a + c = d * 2.
1434        // - then after a b + c, d projection, col(0) and col(1) * 2 must be
1435        // in the same class.
1436        let schema = abc_schema();
1437        let mut group = EquivalenceGroup::default();
1438        group.add_equal_conditions(col("a", &schema)?, col("b", &schema)?);
1439        group.add_equal_conditions(
1440            binary(
1441                col("a", &schema)?,
1442                Operator::Plus,
1443                col("c", &schema)?,
1444                &schema,
1445            )?,
1446            binary(col("d", &schema)?, Operator::Multiply, lit(2), &schema)?,
1447        );
1448
1449        let projected_schema = Arc::new(Schema::new(vec![
1450            Field::new("b+c", DataType::Int32, false),
1451            Field::new("d", DataType::Int32, false),
1452        ]));
1453        let mapping = [
1454            (
1455                binary(
1456                    col("b", &schema)?,
1457                    Operator::Plus,
1458                    col("c", &schema)?,
1459                    &schema,
1460                )?,
1461                vec![(col("b+c", &projected_schema)?, 0)].into(),
1462            ),
1463            (
1464                col("d", &schema)?,
1465                vec![(col("d", &projected_schema)?, 1)].into(),
1466            ),
1467        ]
1468        .into_iter()
1469        .collect::<ProjectionMapping>();
1470
1471        let projected = group.project(&mapping);
1472
1473        let first_normalized = projected.normalize_expr(col("b+c", &projected_schema)?);
1474        let second_normalized = projected.normalize_expr(binary(
1475            col("d", &projected_schema)?,
1476            Operator::Multiply,
1477            lit(2),
1478            &projected_schema,
1479        )?);
1480        assert!(first_normalized.eq(&second_normalized));
1481
1482        Ok(())
1483    }
1484
1485    /// Builds a group from a list of equated column pairs.
1486    fn group_of(schema: &SchemaRef, pairs: &[(&str, &str)]) -> Result<EquivalenceGroup> {
1487        let mut group = EquivalenceGroup::default();
1488        for (lhs, rhs) in pairs {
1489            group.add_equal_conditions(col(lhs, schema)?, col(rhs, schema)?);
1490        }
1491        Ok(group)
1492    }
1493
1494    fn abc_schema() -> SchemaRef {
1495        Arc::new(Schema::new(vec![
1496            Field::new("a", DataType::Int32, false),
1497            Field::new("b", DataType::Int32, false),
1498            Field::new("c", DataType::Int32, false),
1499            Field::new("d", DataType::Int32, false),
1500        ]))
1501    }
1502
1503    #[test]
1504    fn test_has_same_classes_is_conservative_about_class_order() -> Result<()> {
1505        // `classes` is a `Vec` and `remove_class_at_idx` uses `swap_remove`, so
1506        // the order two groups hold their classes in depends on how they were
1507        // built. This check is positional and reports such a pair as different.
1508        //
1509        // That is deliberate, and it is why this is not `PartialEq`: set
1510        // semantics would mean scanning the other group per class, and the
1511        // quadratic cost dwarfs the recomputation the caller is trying to skip.
1512        // The error can only go this way -- different when they match, never the
1513        // reverse -- so a caller only forfeits an optimization.
1514        let schema = abc_schema();
1515        let ab_then_cd = group_of(&schema, &[("a", "b"), ("c", "d")])?;
1516        let cd_then_ab = group_of(&schema, &[("c", "d"), ("a", "b")])?;
1517
1518        assert_eq!(ab_then_cd.len(), 2, "expected two disjoint classes");
1519        assert!(!ab_then_cd.has_same_classes(&cd_then_ab));
1520
1521        Ok(())
1522    }
1523
1524    #[test]
1525    fn test_has_same_classes_compares_classes() -> Result<()> {
1526        let schema = abc_schema();
1527
1528        // Two empty groups agree.
1529        assert!(group_of(&schema, &[])?.has_same_classes(&group_of(&schema, &[])?));
1530        // The same class, built the same way.
1531        assert!(
1532            group_of(&schema, &[("a", "b")])?
1533                .has_same_classes(&group_of(&schema, &[("a", "b")])?)
1534        );
1535        // A class is a set, so the order within a pair is immaterial.
1536        assert!(
1537            group_of(&schema, &[("a", "b")])?
1538                .has_same_classes(&group_of(&schema, &[("b", "a")])?)
1539        );
1540        // A populated group is not an empty one.
1541        assert!(
1542            !group_of(&schema, &[("a", "b")])?.has_same_classes(&group_of(&schema, &[])?)
1543        );
1544        // Equating a different pair yields a different group.
1545        assert!(
1546            !group_of(&schema, &[("a", "b")])?
1547                .has_same_classes(&group_of(&schema, &[("a", "c")])?)
1548        );
1549        // Widening a class yields a different group.
1550        assert!(
1551            !group_of(&schema, &[("a", "b")])?
1552                .has_same_classes(&group_of(&schema, &[("a", "b"), ("b", "c")])?)
1553        );
1554
1555        Ok(())
1556    }
1557
1558    /// An uncorrelated scalar subquery is a leaf with no columns, so the only
1559    /// way to know it is constant is to ask the expression itself.
1560    /// <https://github.com/apache/datafusion/issues/26572>
1561    #[test]
1562    fn test_scalar_subquery_is_uniform_constant() -> Result<()> {
1563        use crate::scalar_subquery::ScalarSubqueryExpr;
1564        use datafusion_expr::physical_planning_context::{
1565            ScalarSubqueryResults, SubqueryIndex,
1566        };
1567
1568        let subquery: Arc<dyn PhysicalExpr> = Arc::new(ScalarSubqueryExpr::new(
1569            DataType::Int32,
1570            true,
1571            SubqueryIndex::new(0),
1572            ScalarSubqueryResults::new(1),
1573        ));
1574        let group = EquivalenceGroup::default();
1575        assert_eq!(
1576            group.is_expr_constant(&subquery),
1577            Some(AcrossPartitions::Uniform(None))
1578        );
1579        // A column is a leaf too, but it is not constant
1580        let schema = abc_schema();
1581        assert_eq!(group.is_expr_constant(&col("a", &schema)?), None);
1582
1583        Ok(())
1584    }
1585
1586    #[test]
1587    fn test_volatile_function_of_constants_is_not_constant() -> Result<()> {
1588        use crate::ScalarFunctionExpr;
1589        use crate::scalar_subquery::ScalarSubqueryExpr;
1590        use datafusion_common::config::ConfigOptions;
1591        use datafusion_expr::physical_planning_context::{
1592            ScalarSubqueryResults, SubqueryIndex,
1593        };
1594        use datafusion_expr::{ColumnarValue, Volatility, create_udf};
1595
1596        let schema = abc_schema();
1597        let group = EquivalenceGroup::default();
1598        let subquery: Arc<dyn PhysicalExpr> = Arc::new(ScalarSubqueryExpr::new(
1599            DataType::Int32,
1600            true,
1601            SubqueryIndex::new(0),
1602            ScalarSubqueryResults::new(1),
1603        ));
1604        let call = |volatility, arg: Arc<dyn PhysicalExpr>| -> Result<_> {
1605            let udf = Arc::new(create_udf(
1606                "f",
1607                vec![DataType::Int32],
1608                DataType::Int32,
1609                volatility,
1610                Arc::new(|args: &[ColumnarValue]| Ok(args[0].clone())),
1611            ));
1612            let expr = ScalarFunctionExpr::try_new(
1613                udf,
1614                vec![arg],
1615                &schema,
1616                Arc::new(ConfigOptions::new()),
1617            )?;
1618            Ok(Arc::new(expr) as Arc<dyn PhysicalExpr>)
1619        };
1620
1621        // A volatile function can return a new value for every row, even
1622        // when its argument is constant
1623        for arg in [lit(1i32), Arc::clone(&subquery)] {
1624            let volatile = call(Volatility::Volatile, arg)?;
1625            assert_eq!(group.is_expr_constant(&volatile), None);
1626        }
1627        // A stable function of a constant is constant
1628        let stable = call(Volatility::Stable, subquery)?;
1629        assert_eq!(
1630            group.is_expr_constant(&stable),
1631            Some(AcrossPartitions::Heterogeneous)
1632        );
1633
1634        Ok(())
1635    }
1636
1637    #[test]
1638    fn test_unknown_constants_stay_apart() -> Result<()> {
1639        // Two constants whose values are unknown are not known to be equal,
1640        // so they must not be merged into one class
1641        let schema = abc_schema();
1642        let mut group = EquivalenceGroup::default();
1643        group.add_constant(ConstExpr::new(
1644            col("a", &schema)?,
1645            AcrossPartitions::Uniform(None),
1646        ));
1647        group.add_constant(ConstExpr::new(
1648            col("b", &schema)?,
1649            AcrossPartitions::Uniform(None),
1650        ));
1651        assert_eq!(group.len(), 2);
1652
1653        // Two constants with the same known value are merged
1654        let mut group = EquivalenceGroup::default();
1655        let one = Some(ScalarValue::Int32(Some(1)));
1656        group.add_constant(ConstExpr::new(
1657            col("a", &schema)?,
1658            AcrossPartitions::Uniform(one.clone()),
1659        ));
1660        group.add_constant(ConstExpr::new(
1661            col("b", &schema)?,
1662            AcrossPartitions::Uniform(one),
1663        ));
1664        assert_eq!(group.len(), 1);
1665
1666        Ok(())
1667    }
1668
1669    /// A constant on the right side of a join stays constant in the join
1670    /// output, unless unmatched rows pad the right side with NULLs.
1671    /// <https://github.com/apache/datafusion/issues/26283>
1672    #[test]
1673    fn test_join_keeps_right_constants() -> Result<()> {
1674        let schema = abc_schema();
1675        let mut right = EquivalenceGroup::default();
1676        right.add_constant(ConstExpr::from(col("a", &schema)?));
1677        // `a` of the right side is column 4 of the join output
1678        let right_a: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 4));
1679
1680        for (join_type, expected) in [
1681            (JoinType::Inner, true),
1682            (JoinType::Right, true),
1683            (JoinType::Left, false),
1684            (JoinType::Full, false),
1685        ] {
1686            let joined = EquivalenceGroup::default().join(&right, &join_type, 4, &[])?;
1687            assert_eq!(
1688                joined.is_expr_constant(&right_a).is_some(),
1689                expected,
1690                "{join_type}"
1691            );
1692        }
1693
1694        Ok(())
1695    }
1696
1697    /// The same for a constant on the left side, whose rows are padded with
1698    /// NULLs by a right or full join.
1699    #[test]
1700    fn test_join_keeps_left_constants() -> Result<()> {
1701        let schema = abc_schema();
1702        let mut left = EquivalenceGroup::default();
1703        left.add_constant(ConstExpr::from(col("a", &schema)?));
1704        let left_a = col("a", &schema)?;
1705        for (join_type, expected) in [
1706            (JoinType::Inner, true),
1707            (JoinType::Left, true),
1708            (JoinType::Right, false),
1709            (JoinType::Full, false),
1710        ] {
1711            let joined = left.join(&EquivalenceGroup::default(), &join_type, 4, &[])?;
1712            assert_eq!(
1713                joined.is_expr_constant(&left_a).is_some(),
1714                expected,
1715                "{join_type}"
1716            );
1717        }
1718
1719        Ok(())
1720    }
1721
1722    #[test]
1723    fn test_has_same_classes_ignores_the_map() -> Result<()> {
1724        // `map` indexes into `classes`, so equal classes must imply equal
1725        // groups no matter how the classes were arrived at. Bridging `a = b`
1726        // and `b = c` into one class must match stating `a = c` and `a = b`.
1727        let schema = abc_schema();
1728        let bridged = group_of(&schema, &[("a", "b"), ("b", "c")])?;
1729        let direct = group_of(&schema, &[("a", "c"), ("a", "b")])?;
1730
1731        assert_eq!(bridged.len(), 1, "expected a single bridged class");
1732        assert!(bridged.has_same_classes(&direct));
1733
1734        Ok(())
1735    }
1736}