Skip to main content

datafusion_optimizer/
eliminate_aggregate_distinct.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//! [`EliminateAggregateDistinct`] drops the `DISTINCT` modifier from aggregate
6//! functions that report [`DistinctHandling::Insensitive`]
7
8use crate::optimizer::ApplyOrder;
9use crate::{OptimizerConfig, OptimizerRule};
10
11use datafusion_common::Result;
12use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
13use datafusion_expr::expr::AggregateFunction;
14use datafusion_expr::expr_rewriter::NamePreserver;
15use datafusion_expr::{DistinctHandling, Expr, LogicalPlan};
16
17/// Optimizer rule that removes a `DISTINCT` modifier that cannot change the
18/// result of the aggregate it is attached to.
19///
20/// `min`, `max`, `bool_and`, `bit_or` and friends have an idempotent merge, so
21/// `min(DISTINCT x)` and `min(x)` return the same value. Removing the flag here
22/// keeps [`crate::single_distinct_to_groupby::SingleDistinctToGroupBy`] from
23/// rewriting the plan into an inner group by that only exists to deduplicate.
24///
25/// An aggregate states how it treats duplicates through
26/// [`datafusion_expr::AggregateUDFImpl::distinct_handling`].
27///
28/// ```text
29/// Aggregate: groupBy=[[g]], aggr=[[min(DISTINCT x)]]
30/// ```
31///
32/// becomes
33///
34/// ```text
35/// Aggregate: groupBy=[[g]], aggr=[[min(x) AS "min(DISTINCT x)"]]
36/// ```
37///
38/// The alias keeps the output schema unchanged so the parent projection still
39/// resolves.
40#[derive(Default, Debug)]
41pub struct EliminateAggregateDistinct {}
42
43impl EliminateAggregateDistinct {
44    pub fn new() -> Self {
45        Self {}
46    }
47}
48
49impl OptimizerRule for EliminateAggregateDistinct {
50    fn name(&self) -> &str {
51        "eliminate_aggregate_distinct"
52    }
53
54    fn apply_order(&self) -> Option<ApplyOrder> {
55        Some(ApplyOrder::BottomUp)
56    }
57
58    fn rewrite(
59        &self,
60        plan: LogicalPlan,
61        _config: &dyn OptimizerConfig,
62    ) -> Result<Transformed<LogicalPlan>> {
63        // Aggregate expressions only appear on Aggregate nodes, so every other
64        // node is a cheap no-op. Window functions carry their own `distinct`
65        // flag and are out of scope.
66        let LogicalPlan::Aggregate(aggregate) = &plan else {
67            return Ok(Transformed::no(plan));
68        };
69        if !can_strip_every_distinct(&aggregate.aggr_expr)? {
70            return Ok(Transformed::no(plan));
71        }
72
73        // Dropping `DISTINCT` changes `Expr::schema_name`, and with it the
74        // output schema of the Aggregate, so restore the original name. The
75        // aggregate may sit under an alias that type coercion added, so walk
76        // the expression rather than matching only its root.
77        let name_preserver = NamePreserver::new(&plan);
78        plan.map_expressions(|expr| {
79            let saved_name = name_preserver.save(&expr);
80            expr.transform_down(strip_insensitive_distinct)
81                .map(|t| t.update_data(|e| saved_name.restore(e)))
82        })
83    }
84}
85
86/// Whether the node has at least one `DISTINCT` and every one is
87/// `Insensitive`.
88///
89/// If only some of them were stripped, a `Sensitive` `DISTINCT` could stay
90/// beside a stripped aggregate. A stripped aggregate carries an alias, and
91/// [`crate::single_distinct_to_groupby::SingleDistinctToGroupBy`] does not
92/// rewrite a node whose `aggr_expr` contains an alias. So `min(DISTINCT x),
93/// count(DISTINCT x)` would lose the rewrite that `count` needs. When every
94/// `DISTINCT` is `Insensitive`, none is left after stripping, so that rule has
95/// nothing to rewrite. This is conservative: `min(DISTINCT x),
96/// count(DISTINCT y)` keeps the `min` flag. That flag costs nothing at run
97/// time, because `min` ignores `is_distinct` when it selects its accumulator.
98fn can_strip_every_distinct(aggr_expr: &[Expr]) -> Result<bool> {
99    let mut found_distinct = false;
100    let mut all_insensitive = true;
101    for expr in aggr_expr {
102        expr.apply(|e| {
103            if let Expr::AggregateFunction(AggregateFunction { func, params }) = e
104                && params.distinct
105            {
106                found_distinct = true;
107                if func.distinct_handling() != DistinctHandling::Insensitive {
108                    all_insensitive = false;
109                    return Ok(TreeNodeRecursion::Stop);
110                }
111            }
112            Ok(TreeNodeRecursion::Continue)
113        })?;
114        if !all_insensitive {
115            break;
116        }
117    }
118    Ok(found_distinct && all_insensitive)
119}
120
121/// Drops `DISTINCT` from `expr` if it is an aggregate that ignores duplicates.
122///
123/// The handling is checked again here rather than trusted to
124/// [`can_strip_every_distinct`], which only inspects `aggr_expr`, while
125/// `map_expressions` also visits the group expressions.
126///
127/// An idempotent merge is not always commutative: `first_value` is
128/// idempotent but order-sensitive. The rule does not need commutativity.
129/// `Insensitive` means that the result does not change when duplicates are
130/// removed, and stripping `DISTINCT` only stops that removal. `order_by` and
131/// `filter` are carried over untouched, so the function sees the same rows in
132/// the same order, plus the duplicates that it ignores.
133fn strip_insensitive_distinct(expr: Expr) -> Result<Transformed<Expr>> {
134    Ok(match expr {
135        Expr::AggregateFunction(mut agg)
136            if agg.params.distinct
137                && agg.func.distinct_handling() == DistinctHandling::Insensitive =>
138        {
139            agg.params.distinct = false;
140            Transformed::yes(Expr::AggregateFunction(agg))
141        }
142        _ => Transformed::no(expr),
143    })
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149    use crate::OptimizerContext;
150    use crate::assert_optimized_plan_eq_snapshot;
151    use crate::test::udfs::DistinctHandlingTestUDAF;
152    use crate::test::*;
153
154    use crate::single_distinct_to_groupby::SingleDistinctToGroupBy;
155    use datafusion_expr::{AggregateUDF, ExprFunctionExt, LogicalPlanBuilder, col, lit};
156    use datafusion_functions_aggregate::expr_fn::{bit_xor, max, min, sum};
157
158    use std::sync::Arc;
159
160    macro_rules! assert_optimized_plan_equal {
161        (
162            $plan:expr,
163            @ $expected:literal $(,)?
164        ) => {{
165            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
166            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> =
167                vec![Arc::new(EliminateAggregateDistinct::new())];
168            assert_optimized_plan_eq_snapshot!(
169                optimizer_ctx,
170                rules,
171                $plan,
172                @ $expected,
173            )
174        }};
175    }
176
177    /// A user defined aggregate that reports the given [`DistinctHandling`].
178    ///
179    /// The tests above read the tag off built-in functions, which only covers
180    /// the variants those functions happen to carry.
181    fn tagged(name: &'static str, handling: DistinctHandling) -> AggregateUDF {
182        AggregateUDF::from(DistinctHandlingTestUDAF::new(name, handling))
183    }
184
185    /// `min(DISTINCT b)` loses the flag but keeps its column name.
186    #[test]
187    fn eliminate_distinct_from_min() -> Result<()> {
188        let table_scan = test_table_scan()?;
189        let plan = LogicalPlanBuilder::from(table_scan)
190            .aggregate(vec![col("a")], vec![min(col("b")).distinct().build()?])?
191            .build()?;
192
193        assert_optimized_plan_equal!(plan, @r"
194        Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b)]]
195          TableScan: test
196        ")
197    }
198
199    /// `sum` deduplicates for real, so the flag stays.
200    #[test]
201    fn keep_distinct_on_sum() -> Result<()> {
202        let table_scan = test_table_scan()?;
203        let plan = LogicalPlanBuilder::from(table_scan)
204            .aggregate(vec![col("a")], vec![sum(col("b")).distinct().build()?])?
205            .build()?;
206
207        assert_optimized_plan_equal!(plan, @r"
208        Aggregate: groupBy=[[test.a]], aggr=[[sum(DISTINCT test.b)]]
209          TableScan: test
210        ")
211    }
212
213    /// XOR cancels duplicate pairs, unlike its `bit_and`/`bit_or` siblings.
214    #[test]
215    fn keep_distinct_on_bit_xor() -> Result<()> {
216        let table_scan = test_table_scan()?;
217        let plan = LogicalPlanBuilder::from(table_scan)
218            .aggregate(vec![col("a")], vec![bit_xor(col("b")).distinct().build()?])?
219            .build()?;
220
221        assert_optimized_plan_equal!(plan, @r"
222        Aggregate: groupBy=[[test.a]], aggr=[[bit_xor(DISTINCT test.b)]]
223          TableScan: test
224        ")
225    }
226
227    /// A node keeps every flag when one of them has to stay, so that this rule
228    /// cannot change which plans `SingleDistinctToGroupBy` rewrites.
229    #[test]
230    fn mixed_node_is_left_alone() -> Result<()> {
231        let table_scan = test_table_scan()?;
232        let plan = LogicalPlanBuilder::from(table_scan)
233            .aggregate(
234                vec![col("a")],
235                vec![
236                    min(col("b")).distinct().build()?,
237                    sum(col("c")).distinct().build()?,
238                ],
239            )?
240            .build()?;
241
242        assert_optimized_plan_equal!(plan, @r"
243        Aggregate: groupBy=[[test.a]], aggr=[[min(DISTINCT test.b), sum(DISTINCT test.c)]]
244          TableScan: test
245        ")
246    }
247
248    /// Several duplicate-insensitive aggregates all lose the flag together.
249    #[test]
250    fn eliminate_distinct_from_every_insensitive_aggregate() -> Result<()> {
251        let table_scan = test_table_scan()?;
252        let plan = LogicalPlanBuilder::from(table_scan)
253            .aggregate(
254                vec![col("a")],
255                vec![
256                    min(col("b")).distinct().build()?,
257                    max(col("c")).distinct().build()?,
258                ],
259            )?
260            .build()?;
261
262        assert_optimized_plan_equal!(plan, @r"
263        Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b), max(test.c) AS max(DISTINCT test.c)]]
264          TableScan: test
265        ")
266    }
267
268    /// A non-distinct aggregate alongside is no obstacle.
269    #[test]
270    fn eliminate_distinct_beside_non_distinct_aggregate() -> Result<()> {
271        let table_scan = test_table_scan()?;
272        let plan = LogicalPlanBuilder::from(table_scan)
273            .aggregate(
274                vec![col("a")],
275                vec![min(col("b")).distinct().build()?, sum(col("c"))],
276            )?
277            .build()?;
278
279        assert_optimized_plan_equal!(plan, @r"
280        Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b), sum(test.c)]]
281          TableScan: test
282        ")
283    }
284
285    /// The gate only inspects `aggr_expr`, so a `Sensitive` distinct aggregate
286    /// in the group expressions must keep its flag.
287    #[test]
288    fn keep_sensitive_distinct_in_group_expr() -> Result<()> {
289        let table_scan = test_table_scan()?;
290        let plan = LogicalPlanBuilder::from(table_scan)
291            .aggregate(
292                vec![sum(col("c")).distinct().build()?],
293                vec![min(col("b")).distinct().build()?],
294            )?
295            .build()?;
296
297        assert_optimized_plan_equal!(plan, @r"
298        Aggregate: groupBy=[[sum(DISTINCT test.c)]], aggr=[[min(test.b) AS min(DISTINCT test.b)]]
299          TableScan: test
300        ")
301    }
302
303    /// `FILTER` is applied before deduplication, so it rides along untouched.
304    #[test]
305    fn eliminate_distinct_keeps_filter() -> Result<()> {
306        let table_scan = test_table_scan()?;
307        let plan = LogicalPlanBuilder::from(table_scan)
308            .aggregate(
309                vec![col("a")],
310                vec![
311                    min(col("b"))
312                        .distinct()
313                        .filter(col("c").gt(lit(0u32)))
314                        .build()?,
315                ],
316            )?
317            .build()?;
318
319        assert_optimized_plan_equal!(plan, @r"
320        Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) FILTER (WHERE test.c > UInt32(0)) AS min(DISTINCT test.b) FILTER (WHERE test.c > UInt32(0))]]
321          TableScan: test
322        ")
323    }
324
325    /// The conservative gate exists so `SingleDistinctToGroupBy` still sees the
326    /// plan exactly as it did before this rule was added.
327    #[test]
328    fn mixed_node_still_reaches_single_distinct_to_groupby() -> Result<()> {
329        let table_scan = test_table_scan()?;
330        let plan = LogicalPlanBuilder::from(table_scan)
331            .aggregate(
332                vec![col("a")],
333                vec![
334                    min(col("b")).distinct().build()?,
335                    sum(col("b")).distinct().build()?,
336                ],
337            )?
338            .build()?;
339
340        let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
341        let rules: Vec<Arc<dyn OptimizerRule + Send + Sync>> = vec![
342            Arc::new(EliminateAggregateDistinct::new()),
343            Arc::new(SingleDistinctToGroupBy::new()),
344        ];
345        assert_optimized_plan_eq_snapshot!(
346            optimizer_ctx,
347            rules,
348            plan,
349            @r"
350        Projection: test.a, min(alias1) AS min(DISTINCT test.b), sum(alias1) AS sum(DISTINCT test.b)
351          Aggregate: groupBy=[[test.a]], aggr=[[min(alias1), sum(alias1)]]
352            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[]]
353              TableScan: test
354        ",
355        )
356    }
357
358    /// A user defined `Insensitive` aggregate loses the flag, keeps its output
359    /// name, and carries `FILTER` and `ORDER BY` over untouched.
360    #[test]
361    fn eliminate_distinct_from_insensitive_udaf() -> Result<()> {
362        let table_scan = test_table_scan()?;
363        let plan = LogicalPlanBuilder::from(table_scan)
364            .aggregate(
365                vec![col("a")],
366                vec![
367                    tagged("first_seen", DistinctHandling::Insensitive)
368                        .call(vec![col("b")])
369                        .distinct()
370                        .filter(col("c").gt(lit(0u32)))
371                        .order_by(vec![col("b").sort(true, false)])
372                        .build()?,
373                ],
374            )?
375            .build()?;
376
377        assert_optimized_plan_equal!(plan, @r"
378        Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) FILTER (WHERE test.c > UInt32(0)) ORDER BY [test.b ASC NULLS LAST] AS first_seen(DISTINCT test.b) FILTER (WHERE test.c > UInt32(0)) ORDER BY [test.b ASC NULLS LAST]]]
379          TableScan: test
380        ")
381    }
382
383    /// A user defined aggregate that deduplicates for real keeps the flag.
384    #[test]
385    fn keep_distinct_on_sensitive_udaf() -> Result<()> {
386        let table_scan = test_table_scan()?;
387        let plan = LogicalPlanBuilder::from(table_scan)
388            .aggregate(
389                vec![col("a")],
390                vec![
391                    tagged("counts_uniques", DistinctHandling::Sensitive)
392                        .call(vec![col("b")])
393                        .distinct()
394                        .build()?,
395                ],
396            )?
397            .build()?;
398
399        assert_optimized_plan_equal!(plan, @r"
400        Aggregate: groupBy=[[test.a]], aggr=[[counts_uniques(DISTINCT test.b)]]
401          TableScan: test
402        ")
403    }
404
405    /// An aggregate that does not implement `DISTINCT` keeps the flag too: the
406    /// planner still has to deduplicate the input for it.
407    #[test]
408    fn keep_distinct_on_unsupported_udaf() -> Result<()> {
409        let table_scan = test_table_scan()?;
410        let plan = LogicalPlanBuilder::from(table_scan)
411            .aggregate(
412                vec![col("a")],
413                vec![
414                    tagged("needs_dedup", DistinctHandling::Unsupported)
415                        .call(vec![col("b")])
416                        .distinct()
417                        .build()?,
418                ],
419            )?
420            .build()?;
421
422        assert_optimized_plan_equal!(plan, @r"
423        Aggregate: groupBy=[[test.a]], aggr=[[needs_dedup(DISTINCT test.b)]]
424          TableScan: test
425        ")
426    }
427
428    /// The conservative gate covers user defined functions as well: an
429    /// `Insensitive` one beside a `Sensitive` one keeps both flags.
430    #[test]
431    fn mixed_udaf_node_is_left_alone() -> Result<()> {
432        let table_scan = test_table_scan()?;
433        let plan = LogicalPlanBuilder::from(table_scan)
434            .aggregate(
435                vec![col("a")],
436                vec![
437                    tagged("first_seen", DistinctHandling::Insensitive)
438                        .call(vec![col("b")])
439                        .distinct()
440                        .build()?,
441                    tagged("counts_uniques", DistinctHandling::Sensitive)
442                        .call(vec![col("c")])
443                        .distinct()
444                        .build()?,
445                ],
446            )?
447            .build()?;
448
449        assert_optimized_plan_equal!(plan, @r"
450        Aggregate: groupBy=[[test.a]], aggr=[[first_seen(DISTINCT test.b), counts_uniques(DISTINCT test.c)]]
451          TableScan: test
452        ")
453    }
454
455    /// An aggregate that already carries an alias keeps that one name: the
456    /// rule restores the name it found, so no second alias is stacked on top.
457    #[test]
458    fn already_aliased_aggregate_gets_no_second_alias() -> Result<()> {
459        let table_scan = test_table_scan()?;
460        let plan = LogicalPlanBuilder::from(table_scan)
461            .aggregate(
462                vec![col("a")],
463                vec![
464                    tagged("first_seen", DistinctHandling::Insensitive)
465                        .call(vec![col("b")])
466                        .distinct()
467                        .build()?
468                        .alias("m"),
469                ],
470            )?
471            .build()?;
472
473        assert_optimized_plan_equal!(plan, @r"
474        Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) AS m]]
475          TableScan: test
476        ")
477    }
478
479    /// `AggregateUDF::with_aliases` wraps the function in another
480    /// `AggregateUDFImpl`, which has to pass the tag through.
481    #[test]
482    fn with_aliases_delegates_distinct_handling() -> Result<()> {
483        let aliased = tagged("first_seen", DistinctHandling::Insensitive)
484            .with_aliases(["first_hit"]);
485        assert_eq!(aliased.distinct_handling(), DistinctHandling::Insensitive);
486
487        let table_scan = test_table_scan()?;
488        let plan = LogicalPlanBuilder::from(table_scan)
489            .aggregate(
490                vec![col("a")],
491                vec![aliased.call(vec![col("b")]).distinct().build()?],
492            )?
493            .build()?;
494
495        assert_optimized_plan_equal!(plan, @r"
496        Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) AS first_seen(DISTINCT test.b)]]
497          TableScan: test
498        ")
499    }
500
501    /// A plan with no Aggregate takes the no-op path.
502    #[test]
503    fn non_aggregate_plan_is_unchanged() -> Result<()> {
504        let table_scan = test_table_scan()?;
505        let plan = LogicalPlanBuilder::from(table_scan)
506            .filter(col("b").gt(lit(1u32)))?
507            .project(vec![col("a")])?
508            .build()?;
509
510        assert_optimized_plan_equal!(plan, @r"
511        Projection: test.a
512          Filter: test.b > UInt32(1)
513            TableScan: test
514        ")
515    }
516}