Skip to main content

datafusion_optimizer/
common_subexpr_eliminate.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
5//! [`CommonSubexprEliminate`] to avoid redundant computation of common sub-expressions
6
7use std::collections::BTreeSet;
8use std::fmt::Debug;
9use std::sync::Arc;
10
11use crate::{OptimizerConfig, OptimizerRule};
12
13use crate::optimizer::ApplyOrder;
14use crate::utils::NamePreserver;
15use datafusion_common::alias::AliasGenerator;
16
17use datafusion_common::cse::{CSE, CSEController, FoundCommonNodes};
18use datafusion_common::tree_node::{Transformed, TreeNode};
19use datafusion_common::{Column, DFSchema, DFSchemaRef, Result, qualified_name};
20use datafusion_expr::expr::{
21    AggregateFunction, AggregateFunctionParams, Alias, HigherOrderFunction,
22    ScalarFunction, WindowFunction, WindowFunctionParams,
23};
24use datafusion_expr::logical_plan::{
25    Aggregate, Filter, LogicalPlan, Projection, Sort, Window,
26};
27use datafusion_expr::{
28    BinaryExpr, Case, Expr, ExpressionPlacement, Operator, SortExpr, col,
29};
30
31const CSE_PREFIX: &str = "__common_expr";
32
33/// Performs Common Sub-expression Elimination optimization.
34///
35/// This optimization improves query performance by computing expressions that
36/// appear more than once and reusing those results rather than re-computing the
37/// same value
38///
39/// Currently only common sub-expressions within a single `LogicalPlan` are
40/// eliminated.
41///
42/// # Example
43///
44/// Given a projection that computes the same expensive expression
45/// multiple times such as parsing as string as a date with `to_date` twice:
46///
47/// ```text
48/// ProjectionExec(expr=[extract (day from to_date(c1)), extract (year from to_date(c1))])
49/// ```
50///
51/// This optimization will rewrite the plan to compute the common expression once
52/// using a new `ProjectionExec` and then rewrite the original expressions to
53/// refer to that new column.
54///
55/// ```text
56/// ProjectionExec(exprs=[extract (day from new_col), extract (year from new_col)]) <-- reuse here
57///   ProjectionExec(exprs=[to_date(c1) as new_col]) <-- compute to_date once
58/// ```
59#[derive(Debug)]
60pub struct CommonSubexprEliminate {}
61
62impl CommonSubexprEliminate {
63    pub fn new() -> Self {
64        Self {}
65    }
66
67    fn try_optimize_proj(
68        &self,
69        projection: Projection,
70        config: &dyn OptimizerConfig,
71    ) -> Result<Transformed<LogicalPlan>> {
72        let Projection {
73            expr,
74            input,
75            schema,
76            ..
77        } = projection;
78        let input = Arc::unwrap_or_clone(input);
79        let rewritten = self.try_unary_plan(expr, input, config)?;
80        let transformed = rewritten.transformed;
81        rewritten.map_data(|(new_expr, new_input)| {
82            let new_input = Arc::new(new_input);
83            // The rewritten expressions keep their names, but their fields can
84            // differ: a CASE whose `WHEN x IS NOT NULL THEN x` guard is split
85            // into two common subexpressions can no longer be proven non-null.
86            // Derive the schema from the new expressions so it matches what
87            // the physical planner will compute from them.
88            if transformed {
89                Projection::try_new(new_expr, new_input)
90            } else {
91                Projection::try_new_with_schema(new_expr, new_input, schema)
92            }
93            .map(LogicalPlan::Projection)
94        })
95    }
96
97    fn try_optimize_sort(
98        &self,
99        sort: Sort,
100        config: &dyn OptimizerConfig,
101    ) -> Result<Transformed<LogicalPlan>> {
102        let Sort { expr, input, fetch } = sort;
103        let input = Arc::unwrap_or_clone(input);
104        let (sort_expressions, sort_params): (Vec<_>, Vec<(_, _)>) = expr
105            .into_iter()
106            .map(|sort| (sort.expr, (sort.asc, sort.nulls_first)))
107            .unzip();
108        let new_sort = self
109            .try_unary_plan(sort_expressions, input, config)?
110            .update_data(|(new_expr, new_input)| {
111                LogicalPlan::Sort(Sort {
112                    expr: new_expr
113                        .into_iter()
114                        .zip(sort_params)
115                        .map(|(expr, (asc, nulls_first))| SortExpr {
116                            expr,
117                            asc,
118                            nulls_first,
119                        })
120                        .collect(),
121                    input: Arc::new(new_input),
122                    fetch,
123                })
124            });
125        Ok(new_sort)
126    }
127
128    fn try_optimize_filter(
129        &self,
130        filter: Filter,
131        config: &dyn OptimizerConfig,
132    ) -> Result<Transformed<LogicalPlan>> {
133        let Filter {
134            predicate, input, ..
135        } = filter;
136        let input = Arc::unwrap_or_clone(input);
137        let expr = vec![predicate];
138        self.try_unary_plan(expr, input, config)?
139            .map_data(|(mut new_expr, new_input)| {
140                assert_eq!(new_expr.len(), 1); // passed in vec![predicate]
141                let new_predicate = new_expr.pop().unwrap();
142                Filter::try_new(new_predicate, Arc::new(new_input))
143                    .map(LogicalPlan::Filter)
144            })
145    }
146
147    fn try_optimize_window(
148        &self,
149        window: Window,
150        config: &dyn OptimizerConfig,
151    ) -> Result<Transformed<LogicalPlan>> {
152        // Collects window expressions from consecutive `LogicalPlan::Window` nodes into
153        // a list.
154        let (window_expr_list, window_schemas, input) =
155            get_consecutive_window_exprs(window);
156
157        // Extract common sub-expressions from the list.
158
159        match CSE::new(ExprCSEController::new(
160            config.alias_generator().as_ref(),
161            ExprMask::Normal,
162        ))
163        .extract_common_nodes(window_expr_list)?
164        {
165            // If there are common sub-expressions, then the insert a projection node
166            // with the common expressions between the new window nodes and the
167            // original input.
168            FoundCommonNodes::Yes {
169                common_nodes: common_exprs,
170                new_nodes_list: new_exprs_list,
171                original_nodes_list: original_exprs_list,
172            } => build_common_expr_project_plan(input, common_exprs).map(|new_input| {
173                Transformed::yes((new_exprs_list, new_input, Some(original_exprs_list)))
174            }),
175            FoundCommonNodes::No {
176                original_nodes_list: original_exprs_list,
177            } => Ok(Transformed::no((original_exprs_list, input, None))),
178        }?
179        // Recurse into the new input.
180        // (This is similar to what a `ApplyOrder::TopDown` optimizer rule would do.)
181        .transform_data(|(new_window_expr_list, new_input, window_expr_list)| {
182            self.rewrite(new_input, config)?.map_data(|new_input| {
183                Ok((new_window_expr_list, new_input, window_expr_list))
184            })
185        })?
186        // Rebuild the consecutive window nodes.
187        .map_data(|(new_window_expr_list, new_input, window_expr_list)| {
188            // If there were common expressions extracted, then we need to make sure
189            // we restore the original column names.
190            // TODO: Although `find_common_exprs()` inserts aliases around extracted
191            //  common expressions this doesn't mean that the original column names
192            //  (schema) are preserved due to the inserted aliases are not always at
193            //  the top of the expression.
194            //  Let's consider improving `find_common_exprs()` to always keep column
195            //  names and get rid of additional name preserving logic here.
196            if let Some(window_expr_list) = window_expr_list {
197                let name_preserver = NamePreserver::new_for_projection();
198                let saved_names = window_expr_list
199                    .iter()
200                    .map(|exprs| {
201                        exprs
202                            .iter()
203                            .map(|expr| name_preserver.save(expr))
204                            .collect::<Vec<_>>()
205                    })
206                    .collect::<Vec<_>>();
207                new_window_expr_list.into_iter().zip(saved_names).try_rfold(
208                    new_input,
209                    |plan, (new_window_expr, saved_names)| {
210                        let new_window_expr = new_window_expr
211                            .into_iter()
212                            .zip(saved_names)
213                            .map(|(new_window_expr, saved_name)| {
214                                saved_name.restore(new_window_expr)
215                            })
216                            .collect::<Vec<_>>();
217                        Window::try_new(new_window_expr, Arc::new(plan))
218                            .map(LogicalPlan::Window)
219                    },
220                )
221            } else {
222                new_window_expr_list
223                    .into_iter()
224                    .zip(window_schemas)
225                    .try_rfold(new_input, |plan, (new_window_expr, schema)| {
226                        Window::try_new_with_schema(
227                            new_window_expr,
228                            Arc::new(plan),
229                            schema,
230                        )
231                        .map(LogicalPlan::Window)
232                    })
233            }
234        })
235    }
236
237    fn try_optimize_aggregate(
238        &self,
239        aggregate: Aggregate,
240        config: &dyn OptimizerConfig,
241    ) -> Result<Transformed<LogicalPlan>> {
242        let Aggregate {
243            group_expr,
244            aggr_expr,
245            input,
246            schema,
247            ..
248        } = aggregate;
249        let input = Arc::unwrap_or_clone(input);
250        // Extract common sub-expressions from the aggregate and grouping expressions.
251        match CSE::new(ExprCSEController::new(
252            config.alias_generator().as_ref(),
253            ExprMask::Normal,
254        ))
255        .extract_common_nodes(vec![group_expr, aggr_expr])?
256        {
257            // If there are common sub-expressions, then insert a projection node
258            // with the common expressions between the new aggregate node and the
259            // original input.
260            FoundCommonNodes::Yes {
261                common_nodes: common_exprs,
262                new_nodes_list: mut new_exprs_list,
263                original_nodes_list: mut original_exprs_list,
264            } => {
265                let new_aggr_expr = new_exprs_list.pop().unwrap();
266                let new_group_expr = new_exprs_list.pop().unwrap();
267
268                build_common_expr_project_plan(input, common_exprs).map(|new_input| {
269                    let aggr_expr = original_exprs_list.pop().unwrap();
270                    Transformed::yes((
271                        new_aggr_expr,
272                        new_group_expr,
273                        new_input,
274                        Some(aggr_expr),
275                    ))
276                })
277            }
278
279            FoundCommonNodes::No {
280                original_nodes_list: mut original_exprs_list,
281            } => {
282                let new_aggr_expr = original_exprs_list.pop().unwrap();
283                let new_group_expr = original_exprs_list.pop().unwrap();
284
285                Ok(Transformed::no((
286                    new_aggr_expr,
287                    new_group_expr,
288                    input,
289                    None,
290                )))
291            }
292        }?
293        // Recurse into the new input.
294        // (This is similar to what a `ApplyOrder::TopDown` optimizer rule would do.)
295        .transform_data(|(new_aggr_expr, new_group_expr, new_input, aggr_expr)| {
296            self.rewrite(new_input, config)?.map_data(|new_input| {
297                Ok((
298                    new_aggr_expr,
299                    new_group_expr,
300                    aggr_expr,
301                    Arc::new(new_input),
302                ))
303            })
304        })?
305        // Try extracting common aggregate expressions and rebuild the aggregate node.
306        .transform_data(
307            |(new_aggr_expr, new_group_expr, aggr_expr, new_input)| {
308                // Extract common aggregate sub-expressions from the aggregate expressions.
309                match CSE::new(ExprCSEController::new(
310                    config.alias_generator().as_ref(),
311                    ExprMask::NormalAndAggregates,
312                ))
313                .extract_common_nodes(vec![new_aggr_expr])?
314                {
315                    FoundCommonNodes::Yes {
316                        common_nodes: common_exprs,
317                        new_nodes_list: mut new_exprs_list,
318                        original_nodes_list: mut original_exprs_list,
319                    } => {
320                        let rewritten_aggr_expr = new_exprs_list.pop().unwrap();
321                        let new_aggr_expr = original_exprs_list.pop().unwrap();
322                        let saved_names = if let Some(aggr_expr) = aggr_expr {
323                            let name_preserver = NamePreserver::new_for_projection();
324                            aggr_expr
325                                .iter()
326                                .map(|expr| Some(name_preserver.save(expr)))
327                                .collect::<Vec<_>>()
328                        } else {
329                            (0..new_aggr_expr.len()).map(|_| None).collect()
330                        };
331
332                        let mut agg_exprs = common_exprs
333                            .into_iter()
334                            .map(|(expr, expr_alias)| expr.alias(expr_alias))
335                            .collect::<Vec<_>>();
336
337                        let mut proj_exprs = Vec::with_capacity(
338                            new_group_expr.len() + rewritten_aggr_expr.len(),
339                        );
340                        for expr in &new_group_expr {
341                            extract_expressions(expr, &mut proj_exprs)
342                        }
343                        for ((expr_rewritten, expr_orig), saved_name) in
344                            rewritten_aggr_expr
345                                .into_iter()
346                                .zip(new_aggr_expr)
347                                .zip(saved_names)
348                        {
349                            if expr_rewritten == expr_orig {
350                                let expr_rewritten = if let Some(saved_name) = saved_name
351                                {
352                                    saved_name.restore(expr_rewritten)
353                                } else {
354                                    expr_rewritten
355                                };
356                                if let Expr::Alias(Alias { expr, name, .. }) =
357                                    expr_rewritten
358                                {
359                                    agg_exprs.push(expr.alias(&name));
360                                    proj_exprs
361                                        .push(Expr::Column(Column::from_name(name)));
362                                } else {
363                                    let expr_alias =
364                                        config.alias_generator().next(CSE_PREFIX);
365                                    let (qualifier, field_name) =
366                                        expr_rewritten.qualified_name();
367                                    let out_name =
368                                        qualified_name(qualifier.as_ref(), &field_name);
369
370                                    agg_exprs.push(expr_rewritten.alias(&expr_alias));
371                                    proj_exprs.push(
372                                        Expr::Column(Column::from_name(expr_alias))
373                                            .alias(out_name),
374                                    );
375                                }
376                            } else {
377                                proj_exprs.push(expr_rewritten);
378                            }
379                        }
380
381                        let agg = LogicalPlan::Aggregate(Aggregate::try_new(
382                            new_input,
383                            new_group_expr,
384                            agg_exprs,
385                        )?);
386                        Projection::try_new(proj_exprs, Arc::new(agg))
387                            .map(|p| Transformed::yes(LogicalPlan::Projection(p)))
388                    }
389
390                    // If there aren't any common aggregate sub-expressions, then just
391                    // rebuild the aggregate node.
392                    FoundCommonNodes::No {
393                        original_nodes_list: mut original_exprs_list,
394                    } => {
395                        let rewritten_aggr_expr = original_exprs_list.pop().unwrap();
396
397                        // If there were common expressions extracted, then we need to
398                        // make sure we restore the original column names.
399                        // TODO: Although `find_common_exprs()` inserts aliases around
400                        //  extracted common expressions this doesn't mean that the
401                        //  original column names (schema) are preserved due to the
402                        //  inserted aliases are not always at the top of the
403                        //  expression.
404                        //  Let's consider improving `find_common_exprs()` to always
405                        //  keep column names and get rid of additional name
406                        //  preserving logic here.
407                        if let Some(aggr_expr) = aggr_expr {
408                            let name_preserver = NamePreserver::new_for_projection();
409                            let saved_names = aggr_expr
410                                .iter()
411                                .map(|expr| name_preserver.save(expr))
412                                .collect::<Vec<_>>();
413                            let new_aggr_expr = rewritten_aggr_expr
414                                .into_iter()
415                                .zip(saved_names)
416                                .map(|(new_expr, saved_name)| {
417                                    saved_name.restore(new_expr)
418                                })
419                                .collect::<Vec<Expr>>();
420
421                            // Since `group_expr` may have changed, schema may also.
422                            // Use `try_new()` method.
423                            Aggregate::try_new(new_input, new_group_expr, new_aggr_expr)
424                                .map(LogicalPlan::Aggregate)
425                                .map(Transformed::no)
426                        } else {
427                            Aggregate::try_new_with_schema(
428                                new_input,
429                                new_group_expr,
430                                rewritten_aggr_expr,
431                                schema,
432                            )
433                            .map(LogicalPlan::Aggregate)
434                            .map(Transformed::no)
435                        }
436                    }
437                }
438            },
439        )
440    }
441
442    /// Rewrites the expr list and input to remove common subexpressions
443    ///
444    /// # Parameters
445    ///
446    /// * `exprs`: List of expressions in the node
447    /// * `input`: input plan (that produces the columns referred to in `exprs`)
448    ///
449    /// # Return value
450    ///
451    ///  Returns `(rewritten_exprs, new_input)`. `new_input` is either:
452    ///
453    /// 1. The original `input` of no common subexpressions were extracted
454    /// 2. A newly added projection on top of the original input
455    ///    that computes the common subexpressions
456    fn try_unary_plan(
457        &self,
458        exprs: Vec<Expr>,
459        input: LogicalPlan,
460        config: &dyn OptimizerConfig,
461    ) -> Result<Transformed<(Vec<Expr>, LogicalPlan)>> {
462        // Extract common sub-expressions from the expressions.
463        match CSE::new(ExprCSEController::new(
464            config.alias_generator().as_ref(),
465            ExprMask::Normal,
466        ))
467        .extract_common_nodes(vec![exprs])?
468        {
469            FoundCommonNodes::Yes {
470                common_nodes: common_exprs,
471                new_nodes_list: mut new_exprs_list,
472                original_nodes_list: _,
473            } => {
474                let new_exprs = new_exprs_list.pop().unwrap();
475                build_common_expr_project_plan(input, common_exprs)
476                    .map(|new_input| Transformed::yes((new_exprs, new_input)))
477            }
478            FoundCommonNodes::No {
479                original_nodes_list: mut original_exprs_list,
480            } => {
481                let new_exprs = original_exprs_list.pop().unwrap();
482                Ok(Transformed::no((new_exprs, input)))
483            }
484        }?
485        // Recurse into the new input.
486        // (This is similar to what a `ApplyOrder::TopDown` optimizer rule would do.)
487        .transform_data(|(new_exprs, new_input)| {
488            self.rewrite(new_input, config)?
489                .map_data(|new_input| Ok((new_exprs, new_input)))
490        })
491    }
492}
493
494/// Get all window expressions inside the consecutive window operators.
495///
496/// Returns the window expressions, and the input to the deepest child
497/// LogicalPlan.
498///
499/// For example, if the input window looks like
500///
501/// ```text
502///   LogicalPlan::Window(exprs=[a, b, c])
503///     LogicalPlan::Window(exprs=[d])
504///       InputPlan
505/// ```
506///
507/// Returns:
508/// *  `window_exprs`: `[[a, b, c], [d]]`
509/// * InputPlan
510///
511/// Consecutive window expressions may refer to same complex expression.
512///
513/// If same complex expression is referred more than once by subsequent
514/// `WindowAggr`s, we can cache complex expression by evaluating it with a
515/// projection before the first WindowAggr.
516///
517/// This enables us to cache complex expression "c3+c4" for following plan:
518///
519/// ```text
520/// WindowAggr: windowExpr=[[sum(c9) ORDER BY [c3 + c4] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
521/// --WindowAggr: windowExpr=[[sum(c9) ORDER BY [c3 + c4] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
522/// ```
523///
524/// where, it is referred once by each `WindowAggr` (total of 2) in the plan.
525fn get_consecutive_window_exprs(
526    window: Window,
527) -> (Vec<Vec<Expr>>, Vec<DFSchemaRef>, LogicalPlan) {
528    let mut window_expr_list = vec![];
529    let mut window_schemas = vec![];
530    let mut plan = LogicalPlan::Window(window);
531    while let LogicalPlan::Window(Window {
532        input,
533        window_expr,
534        schema,
535    }) = plan
536    {
537        window_expr_list.push(window_expr);
538        window_schemas.push(schema);
539
540        plan = Arc::unwrap_or_clone(input);
541    }
542    (window_expr_list, window_schemas, plan)
543}
544
545impl OptimizerRule for CommonSubexprEliminate {
546    fn apply_order(&self) -> Option<ApplyOrder> {
547        // This rule handles recursion itself in a `ApplyOrder::TopDown` like manner.
548        // This is because in some cases adjacent nodes are collected (e.g. `Window`) and
549        // CSEd as a group, which can't be done in a simple `ApplyOrder::TopDown` rule.
550        None
551    }
552
553    #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
554    fn rewrite(
555        &self,
556        plan: LogicalPlan,
557        config: &dyn OptimizerConfig,
558    ) -> Result<Transformed<LogicalPlan>> {
559        let original_schema = Arc::clone(plan.schema());
560
561        let optimized_plan = match plan {
562            LogicalPlan::Projection(proj) => self.try_optimize_proj(proj, config)?,
563            LogicalPlan::Sort(sort) => self.try_optimize_sort(sort, config)?,
564            LogicalPlan::Filter(filter) => self.try_optimize_filter(filter, config)?,
565            LogicalPlan::Window(window) => self.try_optimize_window(window, config)?,
566            LogicalPlan::Aggregate(agg) => self.try_optimize_aggregate(agg, config)?,
567            LogicalPlan::Join(_)
568            | LogicalPlan::AsOfJoin(_)
569            | LogicalPlan::Repartition(_)
570            | LogicalPlan::Union(_)
571            | LogicalPlan::TableScan(_)
572            | LogicalPlan::Values(_)
573            | LogicalPlan::EmptyRelation(_)
574            | LogicalPlan::Subquery(_)
575            | LogicalPlan::SubqueryAlias(_)
576            | LogicalPlan::Limit(_)
577            | LogicalPlan::Ddl(_)
578            | LogicalPlan::Explain(_)
579            | LogicalPlan::Analyze(_)
580            | LogicalPlan::Statement(_)
581            | LogicalPlan::Show(_)
582            | LogicalPlan::Distinct(_)
583            | LogicalPlan::Extension(_)
584            | LogicalPlan::Dml(_)
585            | LogicalPlan::Copy(_)
586            | LogicalPlan::Unnest(_)
587            | LogicalPlan::RecursiveQuery(_)
588            | LogicalPlan::MaterializedCte(_) => {
589                // This rule handles recursion itself in a `ApplyOrder::TopDown` like
590                // manner. Process uncorrelated subqueries in expressions
591                // (e.g., Expr::ScalarSubquery), then direct children.
592                plan.map_uncorrelated_subqueries(|c| self.rewrite(c, config))?
593                    .transform_sibling(|plan| {
594                        plan.map_children(|c| self.rewrite(c, config))
595                    })?
596            }
597        };
598
599        // If we rewrote the plan, ensure the schema stays the same
600        if optimized_plan.transformed && optimized_plan.data.schema() != &original_schema
601        {
602            optimized_plan.map_data(|optimized_plan| {
603                build_recover_project_plan(&original_schema, optimized_plan)
604            })
605        } else {
606            Ok(optimized_plan)
607        }
608    }
609
610    fn name(&self) -> &str {
611        "common_sub_expression_eliminate"
612    }
613}
614
615/// Which type of [expressions](Expr) should be considered for rewriting?
616#[derive(Debug, Clone, Copy)]
617enum ExprMask {
618    /// Ignores:
619    ///
620    /// - [`Literal`](Expr::Literal)
621    /// - [`Columns`](Expr::Column)
622    /// - [`ScalarVariable`](Expr::ScalarVariable)
623    /// - [`Alias`](Expr::Alias)
624    /// - [`Wildcard`](Expr::Wildcard)
625    /// - [`AggregateFunction`](Expr::AggregateFunction)
626    Normal,
627
628    /// Like [`Normal`](Self::Normal), but includes [`AggregateFunction`](Expr::AggregateFunction).
629    NormalAndAggregates,
630}
631
632struct ExprCSEController<'a> {
633    alias_generator: &'a AliasGenerator,
634    mask: ExprMask,
635
636    // how many aliases have we seen so far
637    alias_counter: usize,
638}
639
640impl<'a> ExprCSEController<'a> {
641    fn new(alias_generator: &'a AliasGenerator, mask: ExprMask) -> Self {
642        Self {
643            alias_generator,
644            mask,
645            alias_counter: 0,
646        }
647    }
648}
649
650impl CSEController for ExprCSEController<'_> {
651    type Node = Expr;
652
653    fn conditional_children(node: &Expr) -> Option<(Vec<&Expr>, Vec<&Expr>)> {
654        match node {
655            // In case of `ScalarFunction`s and `HigherOrderFunction`s we don't know which children are surely
656            // executed so start visiting all children conditionally and stop the
657            // recursion with `TreeNodeRecursion::Jump`.
658            Expr::ScalarFunction(ScalarFunction { func, args }) => {
659                func.conditional_arguments(args)
660            }
661            Expr::HigherOrderFunction(HigherOrderFunction { func, args }) => {
662                func.conditional_arguments(args)
663            }
664
665            // In case of `And` and `Or` the first child is surely executed, but we
666            // account subexpressions as conditional in the second.
667            Expr::BinaryExpr(BinaryExpr {
668                left,
669                op: Operator::And | Operator::Or,
670                right,
671            }) => Some((vec![left.as_ref()], vec![right.as_ref()])),
672
673            // In case of `Case` the optional base expression and the first when
674            // expressions are surely executed, but we account subexpressions as
675            // conditional in the others.
676            Expr::Case(Case {
677                expr,
678                when_then_expr,
679                else_expr,
680            }) => Some((
681                expr.iter()
682                    .map(|e| e.as_ref())
683                    .chain(when_then_expr.iter().take(1).map(|(when, _)| when.as_ref()))
684                    .collect(),
685                when_then_expr
686                    .iter()
687                    .take(1)
688                    .map(|(_, then)| then.as_ref())
689                    .chain(
690                        when_then_expr
691                            .iter()
692                            .skip(1)
693                            .flat_map(|(when, then)| [when.as_ref(), then.as_ref()]),
694                    )
695                    .chain(else_expr.iter().map(|e| e.as_ref()))
696                    .collect(),
697            )),
698
699            // An aggregate function with a `FILTER` clause evaluates the filter for
700            // every input row, but it evaluates its arguments only for the rows that
701            // pass the filter. Extracting an argument subexpression into a projection
702            // below the aggregate would evaluate it for the rejected rows too, which
703            // can raise an error (for example a failed cast or a division by zero)
704            // that the filter must prevent. The `ORDER BY` expressions of the
705            // aggregate are conservatively handled like the arguments.
706            Expr::AggregateFunction(AggregateFunction {
707                params:
708                    AggregateFunctionParams {
709                        args,
710                        filter: Some(filter),
711                        order_by,
712                        ..
713                    },
714                ..
715            }) => Some((
716                vec![filter.as_ref()],
717                args.iter()
718                    .chain(order_by.iter().map(|sort| &sort.expr))
719                    .collect(),
720            )),
721
722            // The arguments of a window function with a `FILTER` clause are
723            // conservatively handled like the arguments of a filtered aggregate.
724            // The window executor does not guarantee the same today:
725            // `AggregateWindowExpr::get_result_column` evaluates the arguments
726            // before it applies the filter. This rule must not rely on that order,
727            // so it does not extract a subexpression that occurs only in such
728            // arguments. The `PARTITION BY` and `ORDER BY` expressions of the
729            // window are evaluated for every input row.
730            Expr::WindowFunction(window_function) => {
731                let WindowFunction {
732                    params:
733                        WindowFunctionParams {
734                            args,
735                            partition_by,
736                            order_by,
737                            filter: Some(filter),
738                            ..
739                        },
740                    ..
741                } = window_function.as_ref()
742                else {
743                    return None;
744                };
745                Some((
746                    partition_by
747                        .iter()
748                        .chain(order_by.iter().map(|sort| &sort.expr))
749                        .chain([filter.as_ref()])
750                        .collect(),
751                    args.iter().collect(),
752                ))
753            }
754            _ => None,
755        }
756    }
757
758    fn is_valid(node: &Expr) -> bool {
759        !node.is_volatile_node()
760            && !matches!(node, Expr::Lambda(_) | Expr::LambdaVariable(_))
761    }
762
763    fn is_ignored(&self, node: &Expr) -> bool {
764        // MoveTowardsLeafNodes expressions (e.g. get_field) are cheap struct
765        // field accesses that the ExtractLeafExpressions / PushDownLeafProjections
766        // rules deliberately duplicate when needed (one copy for a filter
767        // predicate, another for an output column). CSE deduplicating them
768        // creates intermediate projections that fight with those rules,
769        // causing optimizer instability — ExtractLeafExpressions will undo
770        // the dedup, creating an infinite loop that runs until the iteration
771        // limit is hit. Skip them.
772        if node.placement() == ExpressionPlacement::MoveTowardsLeafNodes {
773            return true;
774        }
775
776        // TODO: remove the next line after `Expr::Wildcard` is removed
777        #[expect(deprecated)]
778        let is_normal_minus_aggregates = matches!(
779            node,
780            // TODO: there's an argument for removing `Literal` from here,
781            // maybe using `Expr::placemement().should_push_to_leaves()` instead
782            // so that we extract common literals and don't broadcast them to num_batch_rows multiple times.
783            // However that currently breaks things like `percentile_cont()` which expect literal arguments
784            // (and would instead be getting `col(__common_expr_n)`).
785            Expr::Literal(..)
786                | Expr::Column(..)
787                | Expr::ScalarVariable(..)
788                | Expr::Alias(..)
789                | Expr::Wildcard { .. }
790                | Expr::Lambda(_)
791                | Expr::LambdaVariable(_)
792                | Expr::WindowFunction(..)
793        );
794
795        let is_aggr = matches!(node, Expr::AggregateFunction(..));
796
797        match self.mask {
798            ExprMask::Normal => is_normal_minus_aggregates || is_aggr,
799            ExprMask::NormalAndAggregates => is_normal_minus_aggregates,
800        }
801    }
802
803    fn generate_alias(&self) -> String {
804        self.alias_generator.next(CSE_PREFIX)
805    }
806
807    fn rewrite(&mut self, node: &Self::Node, alias: &str) -> Self::Node {
808        // alias the expressions without an `Alias` ancestor node
809        if self.alias_counter > 0 {
810            col(alias)
811        } else {
812            self.alias_counter += 1;
813            col(alias).alias(node.schema_name().to_string())
814        }
815    }
816
817    fn rewrite_f_down(&mut self, node: &Expr) {
818        if matches!(node, Expr::Alias(_)) {
819            self.alias_counter += 1;
820        }
821    }
822    fn rewrite_f_up(&mut self, node: &Expr) {
823        if matches!(node, Expr::Alias(_)) {
824            self.alias_counter -= 1
825        }
826    }
827}
828
829impl Default for CommonSubexprEliminate {
830    fn default() -> Self {
831        Self::new()
832    }
833}
834
835/// Build the "intermediate" projection plan that evaluates the extracted common
836/// expressions.
837///
838/// # Arguments
839/// input: the input plan
840///
841/// common_exprs: which common subexpressions were used (and thus are added to
842/// intermediate projection)
843///
844/// expr_stats: the set of common subexpressions
845fn build_common_expr_project_plan(
846    input: LogicalPlan,
847    common_exprs: Vec<(Expr, String)>,
848) -> Result<LogicalPlan> {
849    let mut fields_set = BTreeSet::new();
850    let mut project_exprs = common_exprs
851        .into_iter()
852        .map(|(expr, expr_alias)| {
853            fields_set.insert(expr_alias.clone());
854            Ok(expr.alias(expr_alias))
855        })
856        .collect::<Result<Vec<_>>>()?;
857
858    for (qualifier, field) in input.schema().iter() {
859        if fields_set.insert(qualified_name(qualifier, field.name())) {
860            project_exprs.push(Expr::from((qualifier, field)));
861        }
862    }
863
864    Projection::try_new(project_exprs, Arc::new(input)).map(LogicalPlan::Projection)
865}
866
867/// Build the projection plan to eliminate unnecessary columns produced by
868/// the "intermediate" projection plan built in [build_common_expr_project_plan].
869///
870/// This is required to keep the schema the same for plans that pass the input
871/// on to the output, such as `Filter` or `Sort`.
872fn build_recover_project_plan(
873    schema: &DFSchema,
874    input: LogicalPlan,
875) -> Result<LogicalPlan> {
876    let col_exprs = schema.iter().map(Expr::from).collect();
877    Projection::try_new(col_exprs, Arc::new(input)).map(LogicalPlan::Projection)
878}
879
880fn extract_expressions(expr: &Expr, result: &mut Vec<Expr>) {
881    if let Expr::GroupingSet(groupings) = expr {
882        for e in groupings.distinct_expr() {
883            let (qualifier, field_name) = e.qualified_name();
884            let col = Column::new(qualifier, field_name);
885            result.push(Expr::Column(col))
886        }
887        result.push(Expr::Column(Column::from_name(
888            Aggregate::INTERNAL_GROUPING_ID,
889        )));
890    } else {
891        let (qualifier, field_name) = expr.qualified_name();
892        let col = Column::new(qualifier, field_name);
893        result.push(Expr::Column(col));
894    }
895}
896
897#[cfg(test)]
898mod test {
899
900    use std::iter;
901
902    use arrow::datatypes::{DataType, Field, Schema};
903    use datafusion_expr::logical_plan::{JoinType, projection_schema, table_scan};
904    use datafusion_expr::{
905        AccumulatorFactoryFunction, AggregateUDF, ColumnarValue, ExprFunctionExt,
906        ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, SimpleAggregateUDF,
907        Volatility, WindowFunctionDefinition, grouping_set, is_null, not, when,
908    };
909    use datafusion_expr::{lit, logical_plan::builder::LogicalPlanBuilder};
910
911    use super::*;
912    use crate::assert_optimized_plan_eq_snapshot;
913    use crate::optimizer::OptimizerContext;
914    use crate::test::udfs::leaf_udf_expr;
915    use crate::test::*;
916    use datafusion_expr::test::function_stub::{avg, count, sum, sum_udaf};
917    use datafusion_functions_window::row_number::row_number_udwf;
918
919    macro_rules! assert_optimized_plan_equal {
920        (
921            $config:expr,
922            $plan:expr,
923            @ $expected:literal $(,)?
924        ) => {{
925            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(CommonSubexprEliminate::new())];
926            assert_optimized_plan_eq_snapshot!(
927                $config,
928                rules,
929                $plan,
930                @ $expected,
931            )
932        }};
933
934        (
935            $plan:expr,
936            @ $expected:literal $(,)?
937        ) => {{
938            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(CommonSubexprEliminate::new())];
939            let optimizer_ctx = OptimizerContext::new();
940            assert_optimized_plan_eq_snapshot!(
941                optimizer_ctx,
942                rules,
943                $plan,
944                @ $expected,
945            )
946        }};
947    }
948
949    #[test]
950    fn tpch_q1_simplified() -> Result<()> {
951        // SQL:
952        //  select
953        //      sum(a * (1 - b)),
954        //      sum(a * (1 - b) * (1 + c))
955        //  from T;
956        //
957        // The manual assembled logical plan don't contains the outermost `Projection`.
958
959        let table_scan = test_table_scan()?;
960
961        let plan = LogicalPlanBuilder::from(table_scan)
962            .aggregate(
963                iter::empty::<Expr>(),
964                vec![
965                    sum(col("a") * (lit(1) - col("b"))),
966                    sum((col("a") * (lit(1) - col("b"))) * (lit(1) + col("c"))),
967                ],
968            )?
969            .build()?;
970
971        assert_optimized_plan_equal!(
972            plan,
973            @ r"
974        Aggregate: groupBy=[[]], aggr=[[sum(__common_expr_1 AS test.a * Int32(1) - test.b), sum(__common_expr_1 AS test.a * Int32(1) - test.b * (Int32(1) + test.c))]]
975          Projection: test.a * (Int32(1) - test.b) AS __common_expr_1, test.a, test.b, test.c
976            TableScan: test
977        "
978        )
979    }
980
981    #[test]
982    fn nested_aliases() -> Result<()> {
983        let table_scan = test_table_scan()?;
984
985        let plan = LogicalPlanBuilder::from(table_scan)
986            .project(vec![
987                (col("a") + col("b") - col("c")).alias("alias1") * (col("a") + col("b")),
988                col("a") + col("b"),
989            ])?
990            .build()?;
991
992        assert_optimized_plan_equal!(
993            plan,
994            @ r"
995        Projection: __common_expr_1 - test.c AS alias1 * __common_expr_1 AS test.a + test.b, __common_expr_1 AS test.a + test.b
996          Projection: test.a + test.b AS __common_expr_1, test.a, test.b, test.c
997            TableScan: test
998        "
999        )
1000    }
1001
1002    #[test]
1003    fn aggregate() -> Result<()> {
1004        let table_scan = test_table_scan()?;
1005
1006        let return_type = DataType::UInt32;
1007        let accumulator: AccumulatorFactoryFunction = Arc::new(|_| unimplemented!());
1008        let udf_agg = |inner: Expr| {
1009            Expr::AggregateFunction(AggregateFunction::new_udf(
1010                Arc::new(AggregateUDF::from(SimpleAggregateUDF::new_with_signature(
1011                    "my_agg",
1012                    Signature::exact(vec![DataType::UInt32], Volatility::Stable),
1013                    return_type.clone(),
1014                    Arc::clone(&accumulator),
1015                    vec![Field::new("value", DataType::UInt32, true).into()],
1016                ))),
1017                vec![inner],
1018                false,
1019                None,
1020                vec![],
1021                None,
1022            ))
1023        };
1024
1025        // test: common aggregates
1026        let plan = LogicalPlanBuilder::from(table_scan.clone())
1027            .aggregate(
1028                iter::empty::<Expr>(),
1029                vec![
1030                    // common: avg(col("a"))
1031                    avg(col("a")).alias("col1"),
1032                    avg(col("a")).alias("col2"),
1033                    // no common
1034                    avg(col("b")).alias("col3"),
1035                    avg(col("c")),
1036                    // common: udf_agg(col("a"))
1037                    udf_agg(col("a")).alias("col4"),
1038                    udf_agg(col("a")).alias("col5"),
1039                    // no common
1040                    udf_agg(col("b")).alias("col6"),
1041                    udf_agg(col("c")),
1042                ],
1043            )?
1044            .build()?;
1045
1046        assert_optimized_plan_equal!(
1047            plan,
1048            @ r"
1049        Projection: __common_expr_1 AS col1, __common_expr_1 AS col2, col3, __common_expr_3 AS avg(test.c), __common_expr_2 AS col4, __common_expr_2 AS col5, col6, __common_expr_4 AS my_agg(test.c)
1050          Aggregate: groupBy=[[]], aggr=[[avg(test.a) AS __common_expr_1, my_agg(test.a) AS __common_expr_2, avg(test.b) AS col3, avg(test.c) AS __common_expr_3, my_agg(test.b) AS col6, my_agg(test.c) AS __common_expr_4]]
1051            TableScan: test
1052        "
1053        )?;
1054
1055        // test: trafo after aggregate
1056        let plan = LogicalPlanBuilder::from(table_scan.clone())
1057            .aggregate(
1058                iter::empty::<Expr>(),
1059                vec![
1060                    lit(1) + avg(col("a")),
1061                    lit(1) - avg(col("a")),
1062                    lit(1) + udf_agg(col("a")),
1063                    lit(1) - udf_agg(col("a")),
1064                ],
1065            )?
1066            .build()?;
1067
1068        assert_optimized_plan_equal!(
1069            plan,
1070            @ r"
1071        Projection: Int32(1) + __common_expr_1 AS avg(test.a), Int32(1) - __common_expr_1 AS avg(test.a), Int32(1) + __common_expr_2 AS my_agg(test.a), Int32(1) - __common_expr_2 AS my_agg(test.a)
1072          Aggregate: groupBy=[[]], aggr=[[avg(test.a) AS __common_expr_1, my_agg(test.a) AS __common_expr_2]]
1073            TableScan: test
1074        "
1075        )?;
1076
1077        // test: transformation before aggregate
1078        let plan = LogicalPlanBuilder::from(table_scan.clone())
1079            .aggregate(
1080                iter::empty::<Expr>(),
1081                vec![
1082                    avg(lit(1u32) + col("a")).alias("col1"),
1083                    udf_agg(lit(1u32) + col("a")).alias("col2"),
1084                ],
1085            )?
1086            .build()?;
1087
1088        assert_optimized_plan_equal!(
1089            plan,
1090            @ r"
1091        Aggregate: groupBy=[[]], aggr=[[avg(__common_expr_1) AS col1, my_agg(__common_expr_1) AS col2]]
1092          Projection: UInt32(1) + test.a AS __common_expr_1, test.a, test.b, test.c
1093            TableScan: test
1094        "
1095        )?;
1096
1097        // test: common between agg and group
1098        let plan = LogicalPlanBuilder::from(table_scan.clone())
1099            .aggregate(
1100                vec![lit(1u32) + col("a")],
1101                vec![
1102                    avg(lit(1u32) + col("a")).alias("col1"),
1103                    udf_agg(lit(1u32) + col("a")).alias("col2"),
1104                ],
1105            )?
1106            .build()?;
1107
1108        assert_optimized_plan_equal!(
1109            plan,
1110            @ r"
1111        Aggregate: groupBy=[[__common_expr_1 AS UInt32(1) + test.a]], aggr=[[avg(__common_expr_1) AS col1, my_agg(__common_expr_1) AS col2]]
1112          Projection: UInt32(1) + test.a AS __common_expr_1, test.a, test.b, test.c
1113            TableScan: test
1114        "
1115        )?;
1116
1117        // test: all mixed
1118        let plan = LogicalPlanBuilder::from(table_scan)
1119            .aggregate(
1120                vec![lit(1u32) + col("a")],
1121                vec![
1122                    (lit(1u32) + avg(lit(1u32) + col("a"))).alias("col1"),
1123                    (lit(1u32) - avg(lit(1u32) + col("a"))).alias("col2"),
1124                    avg(lit(1u32) + col("a")),
1125                    (lit(1u32) + udf_agg(lit(1u32) + col("a"))).alias("col3"),
1126                    (lit(1u32) - udf_agg(lit(1u32) + col("a"))).alias("col4"),
1127                    udf_agg(lit(1u32) + col("a")),
1128                ],
1129            )?
1130            .build()?;
1131
1132        assert_optimized_plan_equal!(
1133            plan,
1134            @ r"
1135        Projection: UInt32(1) + test.a, UInt32(1) + __common_expr_2 AS col1, UInt32(1) - __common_expr_2 AS col2, __common_expr_4 AS avg(UInt32(1) + test.a), UInt32(1) + __common_expr_3 AS col3, UInt32(1) - __common_expr_3 AS col4, __common_expr_5 AS my_agg(UInt32(1) + test.a)
1136          Aggregate: groupBy=[[__common_expr_1 AS UInt32(1) + test.a]], aggr=[[avg(__common_expr_1) AS __common_expr_2, my_agg(__common_expr_1) AS __common_expr_3, avg(__common_expr_1 AS UInt32(1) + test.a) AS __common_expr_4, my_agg(__common_expr_1 AS UInt32(1) + test.a) AS __common_expr_5]]
1137            Projection: UInt32(1) + test.a AS __common_expr_1, test.a, test.b, test.c
1138              TableScan: test
1139        "
1140        )
1141    }
1142
1143    #[test]
1144    fn aggregate_with_relations_and_dots() -> Result<()> {
1145        let schema = Schema::new(vec![Field::new("col.a", DataType::UInt32, false)]);
1146        let table_scan = table_scan(Some("table.test"), &schema, None)?.build()?;
1147
1148        let col_a = Expr::Column(Column::new(Some("table.test"), "col.a"));
1149
1150        let plan = LogicalPlanBuilder::from(table_scan)
1151            .aggregate(
1152                vec![col_a.clone()],
1153                vec![
1154                    (lit(1u32) + avg(lit(1u32) + col_a.clone())),
1155                    avg(lit(1u32) + col_a),
1156                ],
1157            )?
1158            .build()?;
1159
1160        assert_optimized_plan_equal!(
1161            plan,
1162            @ r"
1163        Projection: table.test.col.a, UInt32(1) + __common_expr_2 AS avg(UInt32(1) + table.test.col.a), __common_expr_2 AS avg(UInt32(1) + table.test.col.a)
1164          Aggregate: groupBy=[[table.test.col.a]], aggr=[[avg(__common_expr_1 AS UInt32(1) + table.test.col.a) AS __common_expr_2]]
1165            Projection: UInt32(1) + table.test.col.a AS __common_expr_1, table.test.col.a
1166              TableScan: table.test
1167        "
1168        )
1169    }
1170
1171    #[test]
1172    fn common_aggregate_grouping_set_preserves_internal_id() -> Result<()> {
1173        let plan = LogicalPlanBuilder::from(test_table_scan()?)
1174            .aggregate(
1175                vec![grouping_set(vec![vec![col("a")]])],
1176                vec![avg(col("b")).alias("first"), avg(col("b")).alias("second")],
1177            )?
1178            .filter(col(Aggregate::INTERNAL_GROUPING_ID).eq(lit(0_u8)))?
1179            .build()?;
1180
1181        assert_optimized_plan_equal!(
1182            plan,
1183            @ r"
1184        Filter: __grouping_id = UInt8(0)
1185          Projection: test.a, __grouping_id, __common_expr_1 AS first, __common_expr_1 AS second
1186            Aggregate: groupBy=[[GROUPING SETS ((test.a))]], aggr=[[avg(test.b) AS __common_expr_1]]
1187              TableScan: test
1188        "
1189        )
1190    }
1191
1192    #[test]
1193    fn subexpr_in_same_order() -> Result<()> {
1194        let table_scan = test_table_scan()?;
1195
1196        let plan = LogicalPlanBuilder::from(table_scan)
1197            .project(vec![
1198                (lit(1) + col("a")).alias("first"),
1199                (lit(1) + col("a")).alias("second"),
1200            ])?
1201            .build()?;
1202
1203        assert_optimized_plan_equal!(
1204            plan,
1205            @ r"
1206        Projection: __common_expr_1 AS first, __common_expr_1 AS second
1207          Projection: Int32(1) + test.a AS __common_expr_1, test.a, test.b, test.c
1208            TableScan: test
1209        "
1210        )
1211    }
1212
1213    #[test]
1214    fn subexpr_in_different_order() -> Result<()> {
1215        let table_scan = test_table_scan()?;
1216
1217        let plan = LogicalPlanBuilder::from(table_scan)
1218            .project(vec![lit(1) + col("a"), col("a") + lit(1)])?
1219            .build()?;
1220
1221        assert_optimized_plan_equal!(
1222            plan,
1223            @ r"
1224        Projection: __common_expr_1 AS Int32(1) + test.a, __common_expr_1 AS test.a + Int32(1)
1225          Projection: Int32(1) + test.a AS __common_expr_1, test.a, test.b, test.c
1226            TableScan: test
1227        "
1228        )
1229    }
1230
1231    #[test]
1232    fn cross_plans_subexpr() -> Result<()> {
1233        let table_scan = test_table_scan()?;
1234
1235        let plan = LogicalPlanBuilder::from(table_scan)
1236            .project(vec![lit(1) + col("a"), col("a")])?
1237            .project(vec![lit(1) + col("a")])?
1238            .build()?;
1239
1240        assert_optimized_plan_equal!(
1241            plan,
1242            @ r"
1243        Projection: Int32(1) + test.a
1244          Projection: Int32(1) + test.a, test.a
1245            TableScan: test
1246        "
1247        )
1248    }
1249
1250    #[test]
1251    fn redundant_project_fields() {
1252        let table_scan = test_table_scan().unwrap();
1253        let c_plus_a = col("c") + col("a");
1254        let b_plus_a = col("b") + col("a");
1255        let common_exprs_1 = vec![
1256            (c_plus_a, format!("{CSE_PREFIX}_1")),
1257            (b_plus_a, format!("{CSE_PREFIX}_2")),
1258        ];
1259        let c_plus_a_2 = col(format!("{CSE_PREFIX}_1"));
1260        let b_plus_a_2 = col(format!("{CSE_PREFIX}_2"));
1261        let common_exprs_2 = vec![
1262            (c_plus_a_2, format!("{CSE_PREFIX}_3")),
1263            (b_plus_a_2, format!("{CSE_PREFIX}_4")),
1264        ];
1265        let project = build_common_expr_project_plan(table_scan, common_exprs_1).unwrap();
1266        let project_2 = build_common_expr_project_plan(project, common_exprs_2).unwrap();
1267
1268        let mut field_set = BTreeSet::new();
1269        for name in project_2.schema().field_names() {
1270            assert!(field_set.insert(name));
1271        }
1272    }
1273
1274    #[test]
1275    fn redundant_project_fields_join_input() {
1276        let table_scan_1 = test_table_scan_with_name("test1").unwrap();
1277        let table_scan_2 = test_table_scan_with_name("test2").unwrap();
1278        let join = LogicalPlanBuilder::from(table_scan_1)
1279            .join(table_scan_2, JoinType::Inner, (vec!["a"], vec!["a"]), None)
1280            .unwrap()
1281            .build()
1282            .unwrap();
1283        let c_plus_a = col("test1.c") + col("test1.a");
1284        let b_plus_a = col("test1.b") + col("test1.a");
1285        let common_exprs_1 = vec![
1286            (c_plus_a, format!("{CSE_PREFIX}_1")),
1287            (b_plus_a, format!("{CSE_PREFIX}_2")),
1288        ];
1289        let c_plus_a_2 = col(format!("{CSE_PREFIX}_1"));
1290        let b_plus_a_2 = col(format!("{CSE_PREFIX}_2"));
1291        let common_exprs_2 = vec![
1292            (c_plus_a_2, format!("{CSE_PREFIX}_3")),
1293            (b_plus_a_2, format!("{CSE_PREFIX}_4")),
1294        ];
1295        let project = build_common_expr_project_plan(join, common_exprs_1).unwrap();
1296        let project_2 = build_common_expr_project_plan(project, common_exprs_2).unwrap();
1297
1298        let mut field_set = BTreeSet::new();
1299        for name in project_2.schema().field_names() {
1300            assert!(field_set.insert(name));
1301        }
1302    }
1303
1304    #[test]
1305    fn eliminated_subexpr_datatype() {
1306        use datafusion_expr::cast;
1307
1308        let schema = Schema::new(vec![
1309            Field::new("a", DataType::UInt64, false),
1310            Field::new("b", DataType::UInt64, false),
1311            Field::new("c", DataType::UInt64, false),
1312        ]);
1313
1314        let plan = table_scan(Some("table"), &schema, None)
1315            .unwrap()
1316            .filter(
1317                cast(col("a"), DataType::Int64)
1318                    .lt(lit(1_i64))
1319                    .and(cast(col("a"), DataType::Int64).not_eq(lit(1_i64))),
1320            )
1321            .unwrap()
1322            .build()
1323            .unwrap();
1324        let rule = CommonSubexprEliminate::new();
1325        let optimized_plan = rule.rewrite(plan, &OptimizerContext::new()).unwrap();
1326        assert!(optimized_plan.transformed);
1327        let optimized_plan = optimized_plan.data;
1328
1329        let schema = optimized_plan.schema();
1330        let fields_with_datatypes: Vec<_> = schema
1331            .fields()
1332            .iter()
1333            .map(|field| (field.name(), field.data_type()))
1334            .collect();
1335        let formatted_fields_with_datatype = format!("{fields_with_datatypes:#?}");
1336        let expected = r#"[
1337    (
1338        "a",
1339        UInt64,
1340    ),
1341    (
1342        "b",
1343        UInt64,
1344    ),
1345    (
1346        "c",
1347        UInt64,
1348    ),
1349]"#;
1350        assert_eq!(expected, formatted_fields_with_datatype);
1351    }
1352
1353    #[test]
1354    fn filter_schema_changed() -> Result<()> {
1355        let table_scan = test_table_scan()?;
1356
1357        let plan = LogicalPlanBuilder::from(table_scan)
1358            .filter((lit(1) + col("a") - lit(10)).gt(lit(1) + col("a")))?
1359            .build()?;
1360
1361        assert_optimized_plan_equal!(
1362            plan,
1363            @ r"
1364        Projection: test.a, test.b, test.c
1365          Filter: __common_expr_1 - Int32(10) > __common_expr_1
1366            Projection: Int32(1) + test.a AS __common_expr_1, test.a, test.b, test.c
1367              TableScan: test
1368        "
1369        )
1370    }
1371
1372    #[test]
1373    fn test_extract_expressions_from_grouping_set() -> Result<()> {
1374        let mut result = Vec::with_capacity(4);
1375        let grouping = grouping_set(vec![vec![col("a"), col("b")], vec![col("c")]]);
1376        extract_expressions(&grouping, &mut result);
1377
1378        assert_eq!(
1379            result,
1380            vec![
1381                col("a"),
1382                col("b"),
1383                col("c"),
1384                col(Aggregate::INTERNAL_GROUPING_ID),
1385            ]
1386        );
1387        Ok(())
1388    }
1389
1390    #[test]
1391    fn test_extract_expressions_from_grouping_set_with_identical_expr() -> Result<()> {
1392        let mut result = Vec::with_capacity(3);
1393        let grouping = grouping_set(vec![vec![col("a"), col("b")], vec![col("a")]]);
1394        extract_expressions(&grouping, &mut result);
1395        assert_eq!(
1396            result,
1397            vec![col("a"), col("b"), col(Aggregate::INTERNAL_GROUPING_ID),]
1398        );
1399        Ok(())
1400    }
1401
1402    #[test]
1403    fn test_alias_collision() -> Result<()> {
1404        let table_scan = test_table_scan()?;
1405
1406        let config = OptimizerContext::new();
1407        let common_expr_1 = config.alias_generator().next(CSE_PREFIX);
1408        let plan = LogicalPlanBuilder::from(table_scan.clone())
1409            .project(vec![
1410                (col("a") + col("b")).alias(common_expr_1.clone()),
1411                col("c"),
1412            ])?
1413            .project(vec![
1414                col(common_expr_1.clone()).alias("c1"),
1415                col(common_expr_1).alias("c2"),
1416                (col("c") + lit(2)).alias("c3"),
1417                (col("c") + lit(2)).alias("c4"),
1418            ])?
1419            .build()?;
1420
1421        assert_optimized_plan_equal!(
1422            config,
1423            plan,
1424            @ r"
1425        Projection: __common_expr_1 AS c1, __common_expr_1 AS c2, __common_expr_2 AS c3, __common_expr_2 AS c4
1426          Projection: test.c + Int32(2) AS __common_expr_2, __common_expr_1, test.c
1427            Projection: test.a + test.b AS __common_expr_1, test.c
1428              TableScan: test
1429        "
1430        )?;
1431
1432        let config = OptimizerContext::new();
1433        let _common_expr_1 = config.alias_generator().next(CSE_PREFIX);
1434        let common_expr_2 = config.alias_generator().next(CSE_PREFIX);
1435        let plan = LogicalPlanBuilder::from(table_scan)
1436            .project(vec![
1437                (col("a") + col("b")).alias(common_expr_2.clone()),
1438                col("c"),
1439            ])?
1440            .project(vec![
1441                col(common_expr_2.clone()).alias("c1"),
1442                col(common_expr_2).alias("c2"),
1443                (col("c") + lit(2)).alias("c3"),
1444                (col("c") + lit(2)).alias("c4"),
1445            ])?
1446            .build()?;
1447
1448        assert_optimized_plan_equal!(
1449            config,
1450            plan,
1451            @ r"
1452        Projection: __common_expr_2 AS c1, __common_expr_2 AS c2, __common_expr_3 AS c3, __common_expr_3 AS c4
1453          Projection: test.c + Int32(2) AS __common_expr_3, __common_expr_2, test.c
1454            Projection: test.a + test.b AS __common_expr_2, test.c
1455              TableScan: test
1456        "
1457        )?;
1458
1459        Ok(())
1460    }
1461
1462    #[test]
1463    fn test_extract_expressions_from_col() -> Result<()> {
1464        let mut result = Vec::with_capacity(1);
1465        extract_expressions(&col("a"), &mut result);
1466        assert_eq!(result.len(), 1);
1467        Ok(())
1468    }
1469
1470    #[test]
1471    fn test_short_circuits() -> Result<()> {
1472        let table_scan = test_table_scan()?;
1473
1474        let extracted_short_circuit = col("a").eq(lit(0)).or(col("b").eq(lit(0)));
1475        let extracted_short_circuit_leg_1 = (col("a") + col("b")).eq(lit(0));
1476        let not_extracted_short_circuit_leg_2 = (col("a") - col("b")).eq(lit(0));
1477        let extracted_short_circuit_leg_3 = (col("a") * col("b")).eq(lit(0));
1478        let plan = LogicalPlanBuilder::from(table_scan)
1479            .project(vec![
1480                extracted_short_circuit.clone().alias("c1"),
1481                extracted_short_circuit.alias("c2"),
1482                extracted_short_circuit_leg_1
1483                    .clone()
1484                    .or(not_extracted_short_circuit_leg_2.clone())
1485                    .alias("c3"),
1486                extracted_short_circuit_leg_1
1487                    .and(not_extracted_short_circuit_leg_2)
1488                    .alias("c4"),
1489                extracted_short_circuit_leg_3
1490                    .clone()
1491                    .or(extracted_short_circuit_leg_3)
1492                    .alias("c5"),
1493            ])?
1494            .build()?;
1495
1496        assert_optimized_plan_equal!(
1497            plan,
1498            @ r"
1499        Projection: __common_expr_1 AS c1, __common_expr_1 AS c2, __common_expr_2 OR test.a - test.b = Int32(0) AS c3, __common_expr_2 AND test.a - test.b = Int32(0) AS c4, __common_expr_3 OR __common_expr_3 AS c5
1500          Projection: test.a = Int32(0) OR test.b = Int32(0) AS __common_expr_1, test.a + test.b = Int32(0) AS __common_expr_2, test.a * test.b = Int32(0) AS __common_expr_3, test.a, test.b, test.c
1501            TableScan: test
1502        "
1503        )
1504    }
1505
1506    #[test]
1507    fn test_volatile() -> Result<()> {
1508        let table_scan = test_table_scan()?;
1509
1510        let extracted_child = col("a") + col("b");
1511        let rand = rand_func().call(vec![]);
1512        let not_extracted_volatile = extracted_child + rand;
1513        let plan = LogicalPlanBuilder::from(table_scan)
1514            .project(vec![
1515                not_extracted_volatile.clone().alias("c1"),
1516                not_extracted_volatile.alias("c2"),
1517            ])?
1518            .build()?;
1519
1520        assert_optimized_plan_equal!(
1521            plan,
1522            @ r"
1523        Projection: __common_expr_1 + random() AS c1, __common_expr_1 + random() AS c2
1524          Projection: test.a + test.b AS __common_expr_1, test.a, test.b, test.c
1525            TableScan: test
1526        "
1527        )
1528    }
1529
1530    #[test]
1531    fn test_volatile_short_circuits() -> Result<()> {
1532        let table_scan = test_table_scan()?;
1533
1534        let rand = rand_func().call(vec![]);
1535        let extracted_short_circuit_leg_1 = col("a").eq(lit(0));
1536        let not_extracted_volatile_short_circuit_1 =
1537            extracted_short_circuit_leg_1.or(rand.clone().eq(lit(0)));
1538        let not_extracted_short_circuit_leg_2 = col("b").eq(lit(0));
1539        let not_extracted_volatile_short_circuit_2 =
1540            rand.eq(lit(0)).or(not_extracted_short_circuit_leg_2);
1541        let plan = LogicalPlanBuilder::from(table_scan)
1542            .project(vec![
1543                not_extracted_volatile_short_circuit_1.clone().alias("c1"),
1544                not_extracted_volatile_short_circuit_1.alias("c2"),
1545                not_extracted_volatile_short_circuit_2.clone().alias("c3"),
1546                not_extracted_volatile_short_circuit_2.alias("c4"),
1547            ])?
1548            .build()?;
1549
1550        assert_optimized_plan_equal!(
1551            plan,
1552            @ r"
1553        Projection: __common_expr_1 OR random() = Int32(0) AS c1, __common_expr_1 OR random() = Int32(0) AS c2, random() = Int32(0) OR test.b = Int32(0) AS c3, random() = Int32(0) OR test.b = Int32(0) AS c4
1554          Projection: test.a = Int32(0) AS __common_expr_1, test.a, test.b, test.c
1555            TableScan: test
1556        "
1557        )
1558    }
1559
1560    #[test]
1561    fn test_non_top_level_common_expression() -> Result<()> {
1562        let table_scan = test_table_scan()?;
1563
1564        let common_expr = col("a") + col("b");
1565        let plan = LogicalPlanBuilder::from(table_scan)
1566            .project(vec![
1567                common_expr.clone().alias("c1"),
1568                common_expr.alias("c2"),
1569            ])?
1570            .project(vec![col("c1"), col("c2")])?
1571            .build()?;
1572
1573        assert_optimized_plan_equal!(
1574            plan,
1575            @ r"
1576        Projection: c1, c2
1577          Projection: __common_expr_1 AS c1, __common_expr_1 AS c2
1578            Projection: test.a + test.b AS __common_expr_1, test.a, test.b, test.c
1579              TableScan: test
1580        "
1581        )
1582    }
1583
1584    #[test]
1585    fn test_nested_common_expression() -> Result<()> {
1586        let table_scan = test_table_scan()?;
1587
1588        let nested_common_expr = col("a") + col("b");
1589        let common_expr = nested_common_expr.clone() * nested_common_expr;
1590        let plan = LogicalPlanBuilder::from(table_scan)
1591            .project(vec![
1592                common_expr.clone().alias("c1"),
1593                common_expr.alias("c2"),
1594            ])?
1595            .build()?;
1596
1597        assert_optimized_plan_equal!(
1598            plan,
1599            @ r"
1600        Projection: __common_expr_1 AS c1, __common_expr_1 AS c2
1601          Projection: __common_expr_2 * __common_expr_2 AS __common_expr_1, test.a, test.b, test.c
1602            Projection: test.a + test.b AS __common_expr_2, test.a, test.b, test.c
1603              TableScan: test
1604        "
1605        )
1606    }
1607
1608    #[test]
1609    fn test_normalize_add_expression() -> Result<()> {
1610        // a + b <=> b + a
1611        let table_scan = test_table_scan()?;
1612        let expr = ((col("a") + col("b")) * (col("b") + col("a"))).eq(lit(30));
1613        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1614
1615        assert_optimized_plan_equal!(
1616            plan,
1617            @ r"
1618        Projection: test.a, test.b, test.c
1619          Filter: __common_expr_1 * __common_expr_1 = Int32(30)
1620            Projection: test.a + test.b AS __common_expr_1, test.a, test.b, test.c
1621              TableScan: test
1622        "
1623        )
1624    }
1625
1626    #[test]
1627    fn test_normalize_multi_expression() -> Result<()> {
1628        // a * b <=> b * a
1629        let table_scan = test_table_scan()?;
1630        let expr = ((col("a") * col("b")) + (col("b") * col("a"))).eq(lit(30));
1631        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1632
1633        assert_optimized_plan_equal!(
1634            plan,
1635            @ r"
1636        Projection: test.a, test.b, test.c
1637          Filter: __common_expr_1 + __common_expr_1 = Int32(30)
1638            Projection: test.a * test.b AS __common_expr_1, test.a, test.b, test.c
1639              TableScan: test
1640        "
1641        )
1642    }
1643
1644    #[test]
1645    fn test_normalize_bitset_and_expression() -> Result<()> {
1646        // a & b <=> b & a
1647        let table_scan = test_table_scan()?;
1648        let expr = ((col("a") & col("b")) + (col("b") & col("a"))).eq(lit(30));
1649        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1650
1651        assert_optimized_plan_equal!(
1652            plan,
1653            @ r"
1654        Projection: test.a, test.b, test.c
1655          Filter: __common_expr_1 + __common_expr_1 = Int32(30)
1656            Projection: test.a & test.b AS __common_expr_1, test.a, test.b, test.c
1657              TableScan: test
1658        "
1659        )
1660    }
1661
1662    #[test]
1663    fn test_normalize_bitset_or_expression() -> Result<()> {
1664        // a | b <=> b | a
1665        let table_scan = test_table_scan()?;
1666        let expr = ((col("a") | col("b")) + (col("b") | col("a"))).eq(lit(30));
1667        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1668
1669        assert_optimized_plan_equal!(
1670            plan,
1671            @ r"
1672        Projection: test.a, test.b, test.c
1673          Filter: __common_expr_1 + __common_expr_1 = Int32(30)
1674            Projection: test.a | test.b AS __common_expr_1, test.a, test.b, test.c
1675              TableScan: test
1676        "
1677        )
1678    }
1679
1680    #[test]
1681    fn test_normalize_bitset_xor_expression() -> Result<()> {
1682        // a # b <=> b # a
1683        let table_scan = test_table_scan()?;
1684        let expr = ((col("a") ^ col("b")) + (col("b") ^ col("a"))).eq(lit(30));
1685        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1686
1687        assert_optimized_plan_equal!(
1688            plan,
1689            @ r"
1690        Projection: test.a, test.b, test.c
1691          Filter: __common_expr_1 + __common_expr_1 = Int32(30)
1692            Projection: test.a BIT_XOR test.b AS __common_expr_1, test.a, test.b, test.c
1693              TableScan: test
1694        "
1695        )
1696    }
1697
1698    #[test]
1699    fn test_normalize_eq_expression() -> Result<()> {
1700        // a = b <=> b = a
1701        let table_scan = test_table_scan()?;
1702        let expr = (col("a").eq(col("b"))).and(col("b").eq(col("a")));
1703        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1704
1705        assert_optimized_plan_equal!(
1706            plan,
1707            @ r"
1708        Projection: test.a, test.b, test.c
1709          Filter: __common_expr_1 AND __common_expr_1
1710            Projection: test.a = test.b AS __common_expr_1, test.a, test.b, test.c
1711              TableScan: test
1712        "
1713        )
1714    }
1715
1716    #[test]
1717    fn test_normalize_ne_expression() -> Result<()> {
1718        // a != b <=> b != a
1719        let table_scan = test_table_scan()?;
1720        let expr = (col("a").not_eq(col("b"))).and(col("b").not_eq(col("a")));
1721        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1722
1723        assert_optimized_plan_equal!(
1724            plan,
1725            @ r"
1726        Projection: test.a, test.b, test.c
1727          Filter: __common_expr_1 AND __common_expr_1
1728            Projection: test.a != test.b AS __common_expr_1, test.a, test.b, test.c
1729              TableScan: test
1730        "
1731        )
1732    }
1733
1734    #[test]
1735    fn test_normalize_complex_expression() -> Result<()> {
1736        // case1: a + b * c <=> b * c + a
1737        let table_scan = test_table_scan()?;
1738        let expr = ((col("a") + col("b") * col("c")) - (col("b") * col("c") + col("a")))
1739            .eq(lit(30));
1740        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1741
1742        assert_optimized_plan_equal!(
1743            plan,
1744            @ r"
1745        Projection: test.a, test.b, test.c
1746          Filter: __common_expr_1 - __common_expr_1 = Int32(30)
1747            Projection: test.a + test.b * test.c AS __common_expr_1, test.a, test.b, test.c
1748              TableScan: test
1749        "
1750        )?;
1751
1752        // ((c1 + c2 / c3) * c3 <=> c3 * (c2 / c3 + c1))
1753        let table_scan = test_table_scan()?;
1754        let expr = (((col("a") + col("b") / col("c")) * col("c"))
1755            / (col("c") * (col("b") / col("c") + col("a")))
1756            + col("a"))
1757        .eq(lit(30));
1758        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1759
1760        assert_optimized_plan_equal!(
1761            plan,
1762            @ r"
1763        Projection: test.a, test.b, test.c
1764          Filter: __common_expr_1 / __common_expr_1 + test.a = Int32(30)
1765            Projection: (test.a + test.b / test.c) * test.c AS __common_expr_1, test.a, test.b, test.c
1766              TableScan: test
1767        "
1768        )?;
1769
1770        // c2 / (c1 + c3) <=> c2 / (c3 + c1)
1771        let table_scan = test_table_scan()?;
1772        let expr = ((col("b") / (col("a") + col("c")))
1773            * (col("b") / (col("c") + col("a"))))
1774        .eq(lit(30));
1775        let plan = LogicalPlanBuilder::from(table_scan).filter(expr)?.build()?;
1776        assert_optimized_plan_equal!(
1777            plan,
1778            @ r"
1779        Projection: test.a, test.b, test.c
1780          Filter: __common_expr_1 * __common_expr_1 = Int32(30)
1781            Projection: test.b / (test.a + test.c) AS __common_expr_1, test.a, test.b, test.c
1782              TableScan: test
1783        "
1784        )?;
1785
1786        Ok(())
1787    }
1788
1789    #[derive(Debug, PartialEq, Eq, Hash)]
1790    pub struct TestUdf {
1791        signature: Signature,
1792    }
1793
1794    impl TestUdf {
1795        pub fn new() -> Self {
1796            Self {
1797                signature: Signature::numeric(1, Volatility::Immutable),
1798            }
1799        }
1800    }
1801
1802    impl ScalarUDFImpl for TestUdf {
1803        fn name(&self) -> &str {
1804            "my_udf"
1805        }
1806
1807        fn signature(&self) -> &Signature {
1808            &self.signature
1809        }
1810
1811        fn return_type(&self, _: &[DataType]) -> Result<DataType> {
1812            Ok(DataType::Int32)
1813        }
1814
1815        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
1816            panic!("not implemented")
1817        }
1818    }
1819
1820    #[test]
1821    fn test_normalize_inner_binary_expression() -> Result<()> {
1822        // Not(a == b) <=> Not(b == a)
1823        let table_scan = test_table_scan()?;
1824        let expr1 = not(col("a").eq(col("b")));
1825        let expr2 = not(col("b").eq(col("a")));
1826        let plan = LogicalPlanBuilder::from(table_scan)
1827            .project(vec![expr1, expr2])?
1828            .build()?;
1829        assert_optimized_plan_equal!(
1830            plan,
1831            @ r"
1832        Projection: __common_expr_1 AS NOT test.a = test.b, __common_expr_1 AS NOT test.b = test.a
1833          Projection: NOT test.a = test.b AS __common_expr_1, test.a, test.b, test.c
1834            TableScan: test
1835        "
1836        )?;
1837
1838        // is_null(a == b) <=> is_null(b == a)
1839        let table_scan = test_table_scan()?;
1840        let expr1 = is_null(col("a").eq(col("b")));
1841        let expr2 = is_null(col("b").eq(col("a")));
1842        let plan = LogicalPlanBuilder::from(table_scan)
1843            .project(vec![expr1, expr2])?
1844            .build()?;
1845        assert_optimized_plan_equal!(
1846            plan,
1847            @ r"
1848        Projection: __common_expr_1 AS test.a = test.b IS NULL, __common_expr_1 AS test.b = test.a IS NULL
1849          Projection: test.a = test.b IS NULL AS __common_expr_1, test.a, test.b, test.c
1850            TableScan: test
1851        "
1852        )?;
1853
1854        // a + b between 0 and 10 <=> b + a between 0 and 10
1855        let table_scan = test_table_scan()?;
1856        let expr1 = (col("a") + col("b")).between(lit(0), lit(10));
1857        let expr2 = (col("b") + col("a")).between(lit(0), lit(10));
1858        let plan = LogicalPlanBuilder::from(table_scan)
1859            .project(vec![expr1, expr2])?
1860            .build()?;
1861        assert_optimized_plan_equal!(
1862            plan,
1863            @ r"
1864        Projection: __common_expr_1 AS test.a + test.b BETWEEN Int32(0) AND Int32(10), __common_expr_1 AS test.b + test.a BETWEEN Int32(0) AND Int32(10)
1865          Projection: test.a + test.b BETWEEN Int32(0) AND Int32(10) AS __common_expr_1, test.a, test.b, test.c
1866            TableScan: test
1867        "
1868        )?;
1869
1870        // c between a + b and 10 <=> c between b + a and 10
1871        let table_scan = test_table_scan()?;
1872        let expr1 = col("c").between(col("a") + col("b"), lit(10));
1873        let expr2 = col("c").between(col("b") + col("a"), lit(10));
1874        let plan = LogicalPlanBuilder::from(table_scan)
1875            .project(vec![expr1, expr2])?
1876            .build()?;
1877        assert_optimized_plan_equal!(
1878            plan,
1879            @ r"
1880        Projection: __common_expr_1 AS test.c BETWEEN test.a + test.b AND Int32(10), __common_expr_1 AS test.c BETWEEN test.b + test.a AND Int32(10)
1881          Projection: test.c BETWEEN test.a + test.b AND Int32(10) AS __common_expr_1, test.a, test.b, test.c
1882            TableScan: test
1883        "
1884        )?;
1885
1886        // function call with argument <=> function call with argument
1887        let udf = ScalarUDF::from(TestUdf::new());
1888        let table_scan = test_table_scan()?;
1889        let expr1 = udf.call(vec![col("a") + col("b")]);
1890        let expr2 = udf.call(vec![col("b") + col("a")]);
1891        let plan = LogicalPlanBuilder::from(table_scan)
1892            .project(vec![expr1, expr2])?
1893            .build()?;
1894        assert_optimized_plan_equal!(
1895            plan,
1896            @ r"
1897        Projection: __common_expr_1 AS my_udf(test.a + test.b), __common_expr_1 AS my_udf(test.b + test.a)
1898          Projection: my_udf(test.a + test.b) AS __common_expr_1, test.a, test.b, test.c
1899            TableScan: test
1900        "
1901        )
1902    }
1903
1904    /// returns a "random" function that is marked volatile (aka each invocation
1905    /// returns a different value)
1906    ///
1907    /// Does not use datafusion_functions::rand to avoid introducing a
1908    /// dependency on that crate.
1909    fn rand_func() -> ScalarUDF {
1910        ScalarUDF::new_from_impl(RandomStub::new())
1911    }
1912
1913    #[derive(Debug, PartialEq, Eq, Hash)]
1914    struct RandomStub {
1915        signature: Signature,
1916    }
1917
1918    impl RandomStub {
1919        fn new() -> Self {
1920            Self {
1921                signature: Signature::exact(vec![], Volatility::Volatile),
1922            }
1923        }
1924    }
1925    impl ScalarUDFImpl for RandomStub {
1926        fn name(&self) -> &str {
1927            "random"
1928        }
1929
1930        fn signature(&self) -> &Signature {
1931            &self.signature
1932        }
1933
1934        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
1935            Ok(DataType::Float64)
1936        }
1937
1938        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
1939            panic!("dummy - not implemented")
1940        }
1941    }
1942
1943    /// Identical MoveTowardsLeafNodes expressions should NOT be deduplicated
1944    /// by CSE — they are cheap (e.g. struct field access) and the extraction
1945    /// rules deliberately duplicate them. Deduplicating causes optimizer
1946    /// instability where one optimizer rule will undo the work of another,
1947    /// resulting in an infinite optimization loop until the
1948    /// we hit the max iteration limit and then give up.
1949    #[test]
1950    fn test_leaf_expression_not_extracted() -> Result<()> {
1951        let table_scan = test_table_scan()?;
1952
1953        let leaf = leaf_udf_expr(col("a"));
1954        let plan = LogicalPlanBuilder::from(table_scan)
1955            .project(vec![leaf.clone().alias("c1"), leaf.alias("c2")])?
1956            .build()?;
1957
1958        // Plan should be unchanged — no __common_expr introduced
1959        assert_optimized_plan_equal!(
1960            plan,
1961            @r"
1962        Projection: leaf_udf(test.a) AS c1, leaf_udf(test.a) AS c2
1963          TableScan: test
1964        "
1965        )
1966    }
1967
1968    /// When a MoveTowardsLeafNodes expression appears as a sub-expression of
1969    /// a larger expression that IS duplicated, only the outer expression gets
1970    /// deduplicated; the leaf sub-expression stays inline.
1971    #[test]
1972    fn test_leaf_subexpression_not_extracted() -> Result<()> {
1973        let table_scan = test_table_scan()?;
1974
1975        // leaf_udf(a) + b appears twice — the outer `+` is a common
1976        // sub-expression, but leaf_udf(a) by itself is MoveTowardsLeafNodes
1977        // and should not be extracted separately.
1978        let common = leaf_udf_expr(col("a")) + col("b");
1979        let plan = LogicalPlanBuilder::from(table_scan)
1980            .project(vec![common.clone().alias("c1"), common.alias("c2")])?
1981            .build()?;
1982
1983        // The whole `leaf_udf(a) + b` gets deduplicated as __common_expr_1,
1984        // but leaf_udf(a) alone is NOT pulled out.
1985        assert_optimized_plan_equal!(
1986            plan,
1987            @r"
1988        Projection: __common_expr_1 AS c1, __common_expr_1 AS c2
1989          Projection: leaf_udf(test.a) + test.b AS __common_expr_1, test.a, test.b, test.c
1990            TableScan: test
1991        "
1992        )
1993    }
1994
1995    #[test]
1996    fn test_window_function_is_not_extracted() -> Result<()> {
1997        let wexpr = row_number_udwf().call(vec![]);
1998
1999        let plan = LogicalPlanBuilder::empty(true)
2000            .window(vec![wexpr.clone(), wexpr.alias("aliased")])?
2001            .build()?;
2002
2003        assert_optimized_plan_equal!(
2004            plan,
2005            @r"
2006        WindowAggr: windowExpr=[[row_number() ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, row_number() ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING AS aliased]]
2007          EmptyRelation: rows=1
2008        "
2009        )
2010    }
2011
2012    #[test]
2013    fn test_aggregate_filter_arguments() -> Result<()> {
2014        let table_scan = test_table_scan()?;
2015
2016        // An aggregate evaluates its arguments only for the rows that pass its
2017        // `FILTER`. Thus `a + b` must stay in the aggregates. The filter `c > 0` is
2018        // evaluated for every row and is extracted.
2019        let filter = col("c").gt(lit(0));
2020        let plan = LogicalPlanBuilder::from(table_scan.clone())
2021            .aggregate(
2022                iter::empty::<Expr>(),
2023                vec![
2024                    sum(col("a") + col("b")).filter(filter.clone()).build()?,
2025                    count(col("a") + col("b")).filter(filter.clone()).build()?,
2026                ],
2027            )?
2028            .build()?;
2029
2030        assert_optimized_plan_equal!(
2031            plan,
2032            @ "
2033        Aggregate: groupBy=[[]], aggr=[[sum(test.a + test.b) FILTER (WHERE __common_expr_1 AS test.c > Int32(0)) AS sum(test.a + test.b) FILTER (WHERE test.c > Int32(0)), COUNT(test.a + test.b) FILTER (WHERE __common_expr_1 AS test.c > Int32(0)) AS COUNT(test.a + test.b) FILTER (WHERE test.c > Int32(0))]]
2034          Projection: test.c > Int32(0) AS __common_expr_1, test.a, test.b, test.c
2035            TableScan: test
2036        "
2037        )?;
2038
2039        // `a + b` is surely evaluated by the aggregate without a `FILTER`, so it is
2040        // extracted.
2041        let plan = LogicalPlanBuilder::from(table_scan.clone())
2042            .aggregate(
2043                iter::empty::<Expr>(),
2044                vec![
2045                    sum(col("a") + col("b")).filter(filter.clone()).build()?,
2046                    count(col("a") + col("b")),
2047                ],
2048            )?
2049            .build()?;
2050
2051        assert_optimized_plan_equal!(
2052            plan,
2053            @ "
2054        Aggregate: groupBy=[[]], aggr=[[sum(__common_expr_1 AS test.a + test.b) FILTER (WHERE test.c > Int32(0)), COUNT(__common_expr_1 AS test.a + test.b)]]
2055          Projection: test.a + test.b AS __common_expr_1, test.a, test.b, test.c
2056            TableScan: test
2057        "
2058        )?;
2059
2060        // `a + b` is surely evaluated by the filter, so it is extracted.
2061        let plan = LogicalPlanBuilder::from(table_scan.clone())
2062            .aggregate(
2063                iter::empty::<Expr>(),
2064                vec![
2065                    sum(col("a") + col("b"))
2066                        .filter((col("a") + col("b")).gt(lit(0)))
2067                        .build()?,
2068                ],
2069            )?
2070            .build()?;
2071
2072        assert_optimized_plan_equal!(
2073            plan,
2074            @ "
2075        Aggregate: groupBy=[[]], aggr=[[sum(__common_expr_1 AS test.a + test.b) FILTER (WHERE __common_expr_1 AS test.a + test.b > Int32(0)) AS sum(test.a + test.b) FILTER (WHERE test.a + test.b > Int32(0))]]
2076          Projection: test.a + test.b AS __common_expr_1, test.a, test.b, test.c
2077            TableScan: test
2078        "
2079        )?;
2080
2081        // Identical aggregates with a `FILTER` are still deduplicated.
2082        let plan = LogicalPlanBuilder::from(table_scan)
2083            .aggregate(
2084                iter::empty::<Expr>(),
2085                vec![
2086                    sum(col("a") + col("b"))
2087                        .filter(filter.clone())
2088                        .build()?
2089                        .alias("s1"),
2090                    sum(col("a") + col("b")).filter(filter).build()?.alias("s2"),
2091                ],
2092            )?
2093            .build()?;
2094
2095        assert_optimized_plan_equal!(
2096            plan,
2097            @ "
2098        Projection: __common_expr_2 AS s1, __common_expr_2 AS s2
2099          Aggregate: groupBy=[[]], aggr=[[sum(test.a + test.b) FILTER (WHERE __common_expr_1) AS __common_expr_2]]
2100            Projection: test.c > Int32(0) AS __common_expr_1, test.a, test.b, test.c
2101              TableScan: test
2102        "
2103        )
2104    }
2105
2106    #[test]
2107    fn test_aggregate_filter_order_by() -> Result<()> {
2108        let table_scan = test_table_scan()?;
2109
2110        // The `ORDER BY` expressions of an aggregate with a `FILTER` are handled
2111        // like its arguments, so `a + b` is not extracted.
2112        let filter = col("c").gt(lit(0));
2113        let order_by = vec![(col("a") + col("b")).sort(true, false)];
2114        let plan = LogicalPlanBuilder::from(table_scan)
2115            .aggregate(
2116                iter::empty::<Expr>(),
2117                vec![
2118                    sum(col("a"))
2119                        .order_by(order_by.clone())
2120                        .filter(filter.clone())
2121                        .build()?,
2122                    sum(col("b")).order_by(order_by).filter(filter).build()?,
2123                ],
2124            )?
2125            .build()?;
2126
2127        assert_optimized_plan_equal!(
2128            plan,
2129            @ "
2130        Aggregate: groupBy=[[]], aggr=[[sum(test.a) FILTER (WHERE __common_expr_1 AS test.c > Int32(0)) ORDER BY [test.a + test.b ASC NULLS LAST] AS sum(test.a) FILTER (WHERE test.c > Int32(0)) ORDER BY [test.a + test.b ASC NULLS LAST], sum(test.b) FILTER (WHERE __common_expr_1 AS test.c > Int32(0)) ORDER BY [test.a + test.b ASC NULLS LAST] AS sum(test.b) FILTER (WHERE test.c > Int32(0)) ORDER BY [test.a + test.b ASC NULLS LAST]]]
2131          Projection: test.c > Int32(0) AS __common_expr_1, test.a, test.b, test.c
2132            TableScan: test
2133        "
2134        )
2135    }
2136
2137    #[test]
2138    fn test_window_filter_arguments() -> Result<()> {
2139        let table_scan = test_table_scan()?;
2140
2141        // CSE conservatively treats the arguments of a window function with a
2142        // `FILTER` as conditionally evaluated, although the window executor
2143        // evaluates them before it applies the filter today. The `PARTITION BY`
2144        // expressions and the filter are evaluated for every input row.
2145        let window_sum = |arg: Expr| {
2146            Expr::from(WindowFunction::new(
2147                WindowFunctionDefinition::AggregateUDF(sum_udaf()),
2148                vec![arg],
2149            ))
2150            .partition_by(vec![col("a") * col("b")])
2151            .filter(col("c").gt(lit(0)))
2152            .build()
2153        };
2154        let plan = LogicalPlanBuilder::from(table_scan)
2155            .window(vec![
2156                window_sum(col("a") + col("b"))?,
2157                window_sum((col("a") + col("b")) * lit(2))?,
2158            ])?
2159            .build()?;
2160
2161        assert_optimized_plan_equal!(
2162            plan,
2163            @ "
2164        Projection: test.a, test.b, test.c, sum(test.a + test.b) FILTER (WHERE test.c > Int32(0)) PARTITION BY [test.a * test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, sum(test.a + test.b * Int32(2)) FILTER (WHERE test.c > Int32(0)) PARTITION BY [test.a * test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
2165          WindowAggr: windowExpr=[[sum(test.a + test.b) FILTER (WHERE __common_expr_2 AS test.c > Int32(0)) PARTITION BY [__common_expr_1 AS test.a * test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING AS sum(test.a + test.b) FILTER (WHERE test.c > Int32(0)) PARTITION BY [test.a * test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, sum((test.a + test.b) * Int32(2)) FILTER (WHERE __common_expr_2 AS test.c > Int32(0)) PARTITION BY [__common_expr_1 AS test.a * test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING AS sum(test.a + test.b * Int32(2)) FILTER (WHERE test.c > Int32(0)) PARTITION BY [test.a * test.b] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING]]
2166            Projection: test.a * test.b AS __common_expr_1, test.c > Int32(0) AS __common_expr_2, test.a, test.b, test.c
2167              TableScan: test
2168        "
2169        )
2170    }
2171
2172    /// A projection rewritten by CSE carries the schema its new expressions
2173    /// derive, not the one derived before the rewrite.
2174    #[test]
2175    fn projection_schema_follows_rewritten_exprs() -> Result<()> {
2176        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
2177        let table_scan = table_scan(Some("t"), &schema, None)?.build()?;
2178        let a = || col("a") + lit(1);
2179        let expr = when(a().is_not_null(), a())
2180            .when(a().is_not_null(), a())
2181            .otherwise(lit(0))?;
2182        let plan = LogicalPlanBuilder::from(table_scan)
2183            .project(vec![expr])?
2184            .build()?;
2185        // Before the rewrite the guard proves the CASE non-null.
2186        assert!(!plan.schema().field(0).is_nullable());
2187
2188        let optimized = CommonSubexprEliminate::new()
2189            .rewrite(plan, &OptimizerContext::new())?
2190            .data;
2191        let LogicalPlan::Projection(projection) = &optimized else {
2192            panic!("expected a projection, got {optimized}");
2193        };
2194        let derived = projection_schema(&projection.input, &projection.expr)?;
2195        assert_eq!(projection.schema.as_ref(), derived.as_ref());
2196        Ok(())
2197    }
2198}