datafusion-optimizer 56.0.0

DataFusion Query Optimizer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! Rewrites `UNION DISTINCT` branches that differ only by filter predicates
//! into a single filtered branch plus `DISTINCT`.

use crate::utils::is_repeatable;
use crate::{OptimizerConfig, OptimizerRule};
use datafusion_common::Result;
use datafusion_common::tree_node::{
    Transformed, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
};
use datafusion_expr::expr_rewriter::coerce_plan_expr_for_schema;
use datafusion_expr::logical_plan::builder::LogicalPlanBuilder;
use datafusion_expr::utils::disjunction;
use datafusion_expr::{
    Distinct, Expr, Filter, LogicalPlan, Projection, SubqueryAlias, TableSource, Union,
};
use log::debug;
use std::sync::Arc;

#[derive(Default, Debug)]
pub struct UnionsToFilter;

impl UnionsToFilter {
    #[expect(missing_docs)]
    pub fn new() -> Self {
        Self
    }
}

impl OptimizerRule for UnionsToFilter {
    fn name(&self) -> &str {
        "unions_to_filter"
    }

    fn rewrite(
        &self,
        plan: LogicalPlan,
        config: &dyn OptimizerConfig,
    ) -> Result<Transformed<LogicalPlan>> {
        if !config.options().optimizer.enable_unions_to_filter {
            return Ok(Transformed::no(plan));
        }

        // Fast pre-check: if the plan tree has no Distinct::All node at all we can
        // skip the expensive bottom-up rewrite_with_subqueries traversal entirely.
        // This matters for large UNION ALL plans (e.g. TPC-DS Q4) where the rule
        // can never fire and the traversal overhead is otherwise measurable.
        if !plan.exists(|p| Ok(matches!(p, LogicalPlan::Distinct(Distinct::All(_)))))? {
            return Ok(Transformed::no(plan));
        }

        plan.rewrite_with_subqueries(&mut UnionsToFilterRewriter)
    }
}

struct UnionsToFilterRewriter;

impl TreeNodeRewriter for UnionsToFilterRewriter {
    type Node = LogicalPlan;

    fn f_up(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
        match &plan {
            LogicalPlan::Distinct(Distinct::All(input)) => {
                match try_rewrite_distinct_union(input.as_ref().clone())? {
                    Some(rewritten) => Ok(Transformed::yes(rewritten)),
                    None => Ok(Transformed::no(plan)),
                }
            }
            _ => Ok(Transformed::no(plan)),
        }
    }
}

fn try_rewrite_distinct_union(plan: LogicalPlan) -> Result<Option<LogicalPlan>> {
    let LogicalPlan::Union(Union { inputs, schema }) = plan else {
        debug!("unions_to_filter skipped: input is not a UNION");
        return Ok(None);
    };

    if inputs.len() < 2 {
        debug!(
            "unions_to_filter skipped: UNION has {} input(s), need at least 2",
            inputs.len()
        );
        return Ok(None);
    }

    // Use a Vec instead of HashMap: union branches are typically 2-10 entries,
    // so a linear scan with PartialEq is faster than recursively hashing entire
    // LogicalPlan subtrees (O(N * tree_size) hashing for every insert/lookup).
    let mut grouped: Vec<(GroupKey, Vec<Expr>)> = Vec::with_capacity(inputs.len());
    let mut transformed = false;

    for input in inputs {
        let Some(branch) = extract_branch(Arc::unwrap_or_clone(input))? else {
            return Ok(None);
        };

        let table_sources = collect_table_sources(&branch.source)?;
        let key = GroupKey {
            source: branch.source,
            wrappers: branch.wrappers,
            table_sources,
        };
        if let Some((_, conds)) = grouped.iter_mut().find(|(k, _)| k == &key) {
            conds.push(branch.predicate);
            transformed = true;
        } else {
            grouped.push((key, vec![branch.predicate]));
        }
    }

    if !transformed {
        debug!("unions_to_filter skipped: no branch groups could be merged");
        return Ok(None);
    }

    let mut builder: Option<LogicalPlanBuilder> = None;
    for (key, predicates) in grouped {
        let combined =
            disjunction(predicates).expect("union branches always provide predicates");
        let branch = LogicalPlanBuilder::from(key.source)
            .filter(combined)?
            .build()?;
        let branch = wrap_branch(branch, &key.wrappers)?;
        let branch = coerce_plan_expr_for_schema(branch, &schema)?;
        let branch = align_plan_to_schema(branch, Arc::clone(&schema))?;
        builder = Some(match builder {
            None => LogicalPlanBuilder::from(branch),
            Some(builder) => builder.union(branch)?,
        });
    }

    let union = builder
        .expect("at least one branch after rewrite")
        .build()?;
    Ok(Some(LogicalPlan::Distinct(Distinct::All(Arc::new(union)))))
}

struct UnionBranch {
    source: LogicalPlan,
    predicate: Expr,
    wrappers: Vec<Wrapper>,
}

fn extract_branch(plan: LogicalPlan) -> Result<Option<UnionBranch>> {
    let (wrappers, plan) = peel_wrappers(plan);

    // Volatile or subquery expressions in the projection must not be merged:
    // they are evaluated once per branch in the original plan but would be
    // evaluated once per combined row after the rewrite, which can change the
    // output row set.
    if !wrapper_projections_are_safe(&wrappers) {
        debug!(
            "unions_to_filter skipped: projection wrapper contains volatile expression or subquery"
        );
        return Ok(None);
    }

    let (source, predicate) = match plan {
        LogicalPlan::Filter(Filter {
            predicate, input, ..
        }) => {
            if !is_repeatable(&predicate) {
                debug!(
                    "unions_to_filter skipped: branch predicate contains volatility or a subquery"
                );
                return Ok(None);
            }
            // Keep the input intact: projections compute values and aliases
            // define the qualifiers used by the predicate. GroupKey compares
            // the retained plans before merging their predicates.
            (Arc::unwrap_or_clone(input), predicate)
        }
        // A Limit or Sort node changes the row-set semantics of the branch.
        // Merging two such branches into one would silently drop the per-branch
        // row restriction (LIMIT) or rely on an order guarantee that UNION does
        // not preserve (ORDER BY).  Bail out to leave the UNION unchanged.
        LogicalPlan::Limit(_) => {
            debug!("unions_to_filter skipped: branch contains LIMIT");
            return Ok(None);
        }
        LogicalPlan::Sort(_) => {
            debug!("unions_to_filter skipped: branch contains ORDER BY / SORT");
            return Ok(None);
        }
        other => (
            other,
            Expr::Literal(datafusion_common::ScalarValue::Boolean(Some(true)), None),
        ),
    };

    if !source_is_safe(&source)? {
        debug!(
            "unions_to_filter skipped: source contains volatile expression or subquery"
        );
        return Ok(None);
    }

    Ok(Some(UnionBranch {
        source,
        predicate,
        wrappers,
    }))
}

struct GroupKey {
    source: LogicalPlan,
    wrappers: Vec<Wrapper>,
    // LogicalPlan equality deliberately ignores TableScan::source. Retain the
    // corresponding Arcs so structurally identical scans over different data
    // cannot be grouped together.
    table_sources: Vec<Arc<dyn TableSource>>,
}

impl PartialEq for GroupKey {
    fn eq(&self, other: &Self) -> bool {
        self.source == other.source
            && self.wrappers == other.wrappers
            && self.table_sources.len() == other.table_sources.len()
            && self
                .table_sources
                .iter()
                .zip(&other.table_sources)
                .all(|(left, right)| Arc::ptr_eq(left, right))
    }
}

impl Eq for GroupKey {}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Wrapper {
    Projection {
        expr: Vec<Expr>,
        schema: datafusion_common::DFSchemaRef,
    },
    SubqueryAlias {
        alias: datafusion_common::TableReference,
        schema: datafusion_common::DFSchemaRef,
    },
}

fn peel_wrappers(mut plan: LogicalPlan) -> (Vec<Wrapper>, LogicalPlan) {
    let mut wrappers = vec![];
    loop {
        match plan {
            LogicalPlan::Projection(Projection {
                expr,
                input,
                schema,
                ..
            }) => {
                wrappers.push(Wrapper::Projection { expr, schema });
                plan = Arc::unwrap_or_clone(input);
            }
            LogicalPlan::SubqueryAlias(SubqueryAlias {
                input,
                alias,
                schema,
                ..
            }) => {
                wrappers.push(Wrapper::SubqueryAlias { alias, schema });
                plan = Arc::unwrap_or_clone(input);
            }
            other => return (wrappers, other),
        }
    }
}

fn wrap_branch(mut plan: LogicalPlan, wrappers: &[Wrapper]) -> Result<LogicalPlan> {
    for wrapper in wrappers.iter().rev() {
        plan = match wrapper {
            Wrapper::Projection { expr, schema } => {
                LogicalPlan::Projection(Projection::try_new_with_schema(
                    expr.clone(),
                    Arc::new(plan),
                    Arc::clone(schema),
                )?)
            }
            // SubqueryAlias::try_new recomputes the schema from the new input.
            // This is safe because the source table is unchanged; only the
            // filter predicate differs, so the recomputed schema matches the
            // original one stored in peel_wrappers.
            Wrapper::SubqueryAlias { alias, .. } => LogicalPlan::SubqueryAlias(
                SubqueryAlias::try_new(Arc::new(plan), alias.clone())?,
            ),
        };
    }
    Ok(plan)
}

fn align_plan_to_schema(
    plan: LogicalPlan,
    schema: datafusion_common::DFSchemaRef,
) -> Result<LogicalPlan> {
    if plan.schema() == &schema {
        return Ok(plan);
    }

    let expr = plan
        .schema()
        .iter()
        .enumerate()
        .map(|(i, _)| {
            Expr::Column(datafusion_common::Column::from(
                plan.schema().qualified_field(i),
            ))
        })
        .collect::<Vec<_>>();

    Ok(LogicalPlan::Projection(Projection::try_new_with_schema(
        expr,
        Arc::new(plan),
        schema,
    )?))
}

/// Check every expression in the retained source, including its descendants.
/// Merging branches also merges their source evaluations, so the same
/// restrictions as for projection wrappers apply throughout the source.
fn source_is_safe(source: &LogicalPlan) -> Result<bool> {
    let mut safe = true;
    source.apply(|node| {
        node.apply_expressions(|expr| {
            if is_repeatable(expr) {
                Ok(TreeNodeRecursion::Continue)
            } else {
                safe = false;
                Ok(TreeNodeRecursion::Stop)
            }
        })
    })?;
    Ok(safe)
}

fn collect_table_sources(source: &LogicalPlan) -> Result<Vec<Arc<dyn TableSource>>> {
    let mut table_sources = vec![];
    source.apply(|node| {
        if let LogicalPlan::TableScan(scan) = node {
            table_sources.push(Arc::clone(&scan.source));
        }
        Ok(TreeNodeRecursion::Continue)
    })?;
    Ok(table_sources)
}

/// Returns `true` when every projection expression in `wrappers` is both
/// non-volatile and subquery-free.
///
/// Volatile expressions (e.g. `random()`) or correlated subqueries
/// in the SELECT list cannot be safely merged: the original plan evaluates
/// them once per branch execution, while the rewritten plan evaluates them
/// once per combined row, which can change the set of output rows.
fn wrapper_projections_are_safe(wrappers: &[Wrapper]) -> bool {
    wrappers.iter().all(|w| match w {
        Wrapper::Projection { expr, .. } => expr.iter().all(is_repeatable),
        Wrapper::SubqueryAlias { .. } => true,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::OptimizerContext;
    use crate::assert_optimized_plan_eq_snapshot;
    use crate::test::test_table_scan_with_name;
    use arrow::datatypes::DataType;
    use datafusion_common::Result;
    use datafusion_expr::{
        ColumnarValue, Expr, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature,
        Volatility, col, lit,
    };

    macro_rules! assert_optimized_plan_equal {
        (
            $plan:expr,
            @ $expected:literal $(,)?
        ) => {{
            let mut options = datafusion_common::config::ConfigOptions::default();
            options.optimizer.enable_unions_to_filter = true;
            let optimizer_ctx = OptimizerContext::new_with_config_options(Arc::new(options))
                .with_max_passes(1);
            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> =
                vec![Arc::new(UnionsToFilter::new())];
            assert_optimized_plan_eq_snapshot!(
                optimizer_ctx,
                rules,
                $plan,
                @ $expected,
            )
        }};
    }

    #[derive(Debug, PartialEq, Eq, Hash)]
    struct VolatileTestUdf;

    impl ScalarUDFImpl for VolatileTestUdf {
        fn name(&self) -> &str {
            "volatile_test"
        }

        fn signature(&self) -> &Signature {
            static SIGNATURE: std::sync::LazyLock<Signature> =
                std::sync::LazyLock::new(|| Signature::nullary(Volatility::Volatile));
            &SIGNATURE
        }

        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
            Ok(DataType::Float64)
        }

        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
            panic!("VolatileTestUdf is not intended for execution")
        }
    }

    fn volatile_expr() -> Expr {
        ScalarUDF::new_from_impl(VolatileTestUdf).call(vec![])
    }

    fn assert_not_rewritten(plan: LogicalPlan) {
        let mut options = datafusion_common::config::ConfigOptions::default();
        options.optimizer.enable_unions_to_filter = true;
        let optimizer_ctx = OptimizerContext::new_with_config_options(Arc::new(options));
        let result = UnionsToFilter::new()
            .rewrite(plan.clone(), &optimizer_ctx)
            .unwrap();
        assert!(!result.transformed);
        assert_eq!(result.data, plan);
    }

    #[test]
    fn rewrite_union_distinct_preserves_alias_below_filter() -> Result<()> {
        let scan = test_table_scan_with_name("t").unwrap();
        let left_source = LogicalPlanBuilder::from(scan.clone())
            .alias("x")
            .unwrap()
            .build()
            .unwrap();
        let right_source = LogicalPlanBuilder::from(scan)
            .alias("x")
            .unwrap()
            .build()
            .unwrap();
        let left = LogicalPlanBuilder::from(left_source)
            .filter(col("x.a").eq(lit(1)))
            .unwrap()
            .project(vec![col("x.a")])
            .unwrap()
            .build()
            .unwrap();
        let right = LogicalPlanBuilder::from(right_source)
            .filter(col("x.a").eq(lit(2)))
            .unwrap()
            .project(vec![col("x.a")])
            .unwrap()
            .build()
            .unwrap();
        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)
            .unwrap()
            .build()
            .unwrap();

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Projection: x.a
            Projection: x.a
              Filter: x.a = Int32(1) OR x.a = Int32(2)
                SubqueryAlias: x
                  TableScan: t
        ")
        .unwrap();
        Ok(())
    }

    #[test]
    fn rewrite_union_distinct_matching_computed_projection_below_filter() -> Result<()> {
        let scan = test_table_scan_with_name("prices").unwrap();
        let left_source = LogicalPlanBuilder::from(scan.clone())
            .project(vec![(col("a") + lit(100)).alias("amount")])
            .unwrap()
            .alias("prices")
            .unwrap()
            .build()
            .unwrap();
        let right_source = LogicalPlanBuilder::from(scan)
            .project(vec![(col("a") + lit(100)).alias("amount")])
            .unwrap()
            .alias("prices")
            .unwrap()
            .build()
            .unwrap();
        let left = LogicalPlanBuilder::from(left_source)
            .filter(col("amount").gt(lit(0)))
            .unwrap()
            .project(vec![col("amount")])
            .unwrap()
            .build()
            .unwrap();
        let right = LogicalPlanBuilder::from(right_source)
            .filter(col("amount").gt(lit(1)))
            .unwrap()
            .project(vec![col("amount")])
            .unwrap()
            .build()
            .unwrap();
        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)
            .unwrap()
            .build()
            .unwrap();

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Projection: prices.amount
            Projection: prices.amount
              Filter: prices.amount > Int32(0) OR prices.amount > Int32(1)
                SubqueryAlias: prices
                  Projection: prices.a + Int32(100) AS amount
                    TableScan: prices
        ")
        .unwrap();
        Ok(())
    }

    #[test]
    fn keep_union_distinct_with_volatile_source_projection() {
        for nested in [false, true] {
            let mut source =
                LogicalPlanBuilder::from(test_table_scan_with_name("t").unwrap())
                    .project(vec![(volatile_expr() + lit(1.0_f64)).alias("v"), col("a")])
                    .unwrap()
                    .alias("x")
                    .unwrap();
            if nested {
                // The volatile projection is below another Filter, so checking
                // just the source node's expressions would miss it.
                source = source.filter(col("x.v").gt(lit(0.5_f64))).unwrap();
            }
            let source = source.build().unwrap();
            let left = LogicalPlanBuilder::from(source.clone())
                .filter(col("x.a").eq(lit(1)))
                .unwrap()
                .build()
                .unwrap();
            let right = LogicalPlanBuilder::from(source)
                .filter(col("x.a").eq(lit(2)))
                .unwrap()
                .build()
                .unwrap();
            let plan = LogicalPlanBuilder::from(left)
                .union_distinct(right)
                .unwrap()
                .build()
                .unwrap();
            assert_not_rewritten(plan);
        }
    }

    #[test]
    fn keep_union_distinct_with_volatile_source_without_filter() {
        let source = LogicalPlanBuilder::from(test_table_scan_with_name("t").unwrap())
            .project(vec![volatile_expr().alias("v"), col("a")])
            .unwrap()
            // Keep the volatile projection inside the retained source rather
            // than letting peel_wrappers classify it as an outer wrapper.
            .distinct()
            .unwrap()
            .build()
            .unwrap();
        let left = LogicalPlanBuilder::from(source.clone())
            .project(vec![col("a")])
            .unwrap()
            .build()
            .unwrap();
        let right = LogicalPlanBuilder::from(source)
            .filter(col("a").eq(lit(2)))
            .unwrap()
            .project(vec![col("a")])
            .unwrap()
            .build()
            .unwrap();
        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)
            .unwrap()
            .build()
            .unwrap();
        assert_not_rewritten(plan);
    }

    #[test]
    fn keep_union_distinct_with_subquery_in_source() {
        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("t2").unwrap())
            .project(vec![col("b")])
            .unwrap()
            .build()
            .unwrap();
        let source = LogicalPlanBuilder::from(test_table_scan_with_name("t").unwrap())
            .project(vec![
                datafusion_expr::scalar_subquery(Arc::new(subquery)).alias("v"),
                col("a"),
            ])
            .unwrap()
            .build()
            .unwrap();
        let left = LogicalPlanBuilder::from(source.clone())
            .filter(col("a").eq(lit(1)))
            .unwrap()
            .build()
            .unwrap();
        let right = LogicalPlanBuilder::from(source)
            .filter(col("a").eq(lit(2)))
            .unwrap()
            .build()
            .unwrap();
        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)
            .unwrap()
            .build()
            .unwrap();
        assert_not_rewritten(plan);
    }

    #[test]
    fn rewrite_union_distinct_same_source_filters() -> Result<()> {
        let scan = test_table_scan_with_name("t")?;
        let left = LogicalPlanBuilder::from(scan.clone())
            .filter(col("a").eq(lit(1)))?
            .build()?;
        let right = LogicalPlanBuilder::from(scan)
            .filter(col("a").eq(lit(2)))?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Projection: t.a, t.b, t.c
            Filter: t.a = Int32(1) OR t.a = Int32(2)
              TableScan: t
        ")?;
        Ok(())
    }

    #[test]
    fn keep_union_distinct_same_metadata_different_root_sources() -> Result<()> {
        let left_scan_plan = test_table_scan_with_name("t")?;
        let right_scan_plan = test_table_scan_with_name("t")?;

        // TableScan equality compares metadata but deliberately ignores its provider.
        assert_eq!(left_scan_plan, right_scan_plan);
        let (LogicalPlan::TableScan(left_scan), LogicalPlan::TableScan(right_scan)) =
            (&left_scan_plan, &right_scan_plan)
        else {
            panic!("test helper must return TableScan plans");
        };
        assert!(!Arc::ptr_eq(&left_scan.source, &right_scan.source));

        let left = LogicalPlanBuilder::from(left_scan_plan)
            .filter(col("a").eq(lit(1)))?
            .build()?;
        let right = LogicalPlanBuilder::from(right_scan_plan)
            .filter(col("a").eq(lit(2)))?
            .build()?;
        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_not_rewritten(plan);
        Ok(())
    }

    #[test]
    fn keep_union_distinct_same_metadata_different_nested_sources() {
        let left_scan_plan = test_table_scan_with_name("t").unwrap();
        let right_scan_plan = test_table_scan_with_name("t").unwrap();
        assert_eq!(left_scan_plan, right_scan_plan);
        let left_sources = collect_table_sources(&left_scan_plan).unwrap();
        let right_sources = collect_table_sources(&right_scan_plan).unwrap();
        assert_eq!(left_sources.len(), 1);
        assert_eq!(right_sources.len(), 1);
        assert!(!Arc::ptr_eq(&left_sources[0], &right_sources[0]));

        // Verify collection through the Projection/SubqueryAlias source shape
        // retained below a branch Filter.
        let left_source = LogicalPlanBuilder::from(left_scan_plan)
            .project(vec![col("a")])
            .unwrap()
            .alias("x")
            .unwrap()
            .build()
            .unwrap();
        let right_source = LogicalPlanBuilder::from(right_scan_plan)
            .project(vec![col("a")])
            .unwrap()
            .alias("x")
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(left_source, right_source);

        let left = LogicalPlanBuilder::from(left_source)
            .filter(col("x.a").eq(lit(1)))
            .unwrap()
            .build()
            .unwrap();
        let right = LogicalPlanBuilder::from(right_source)
            .filter(col("x.a").eq(lit(2)))
            .unwrap()
            .build()
            .unwrap();
        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)
            .unwrap()
            .build()
            .unwrap();

        assert_not_rewritten(plan);
    }

    #[test]
    fn keep_union_distinct_different_sources() -> Result<()> {
        let left = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
            .filter(col("a").eq(lit(1)))?
            .build()?;
        let right = LogicalPlanBuilder::from(test_table_scan_with_name("t2")?)
            .filter(col("a").eq(lit(2)))?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Union
            Filter: t1.a = Int32(1)
              TableScan: t1
            Filter: t2.a = Int32(2)
              TableScan: t2
        ")?;
        Ok(())
    }

    #[test]
    fn keep_union_distinct_with_volatile_predicate() -> Result<()> {
        let scan = test_table_scan_with_name("t")?;
        let left = LogicalPlanBuilder::from(scan.clone())
            .filter(volatile_expr().gt(lit(0.5_f64)))?
            .build()?;
        let right = LogicalPlanBuilder::from(scan)
            .filter(col("a").eq(lit(2)))?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Union
            Filter: volatile_test() > Float64(0.5)
              TableScan: t
            Filter: t.a = Int32(2)
              TableScan: t
        ")?;
        Ok(())
    }

    #[test]
    fn rewrite_union_distinct_with_matching_projection_prefix() -> Result<()> {
        let scan = test_table_scan_with_name("emp")?;
        let left = LogicalPlanBuilder::from(scan.clone())
            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
            .build()?;
        let right = LogicalPlanBuilder::from(scan)
            .filter(col("b").eq(lit(5)))?
            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Projection: emp.a AS mgr, emp.b AS comm
            Filter: Boolean(true) OR emp.b = Int32(5)
              TableScan: emp
        ")?;
        Ok(())
    }

    #[test]
    fn keep_union_distinct_with_computed_projection_below_filter() -> Result<()> {
        let scan = test_table_scan_with_name("prices")?;
        let left = LogicalPlanBuilder::from(scan.clone())
            .project(vec![(col("a") + lit(100)).alias("amount")])?
            .alias("prices")?
            .filter(col("amount").gt(lit(0)))?
            .project(vec![col("amount")])?
            .build()?;
        let right = LogicalPlanBuilder::from(scan)
            .project(vec![(col("a") + lit(200)).alias("amount")])?
            .alias("prices")?
            .filter(col("amount").gt(lit(1)))?
            .project(vec![col("amount")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Union
            Projection: prices.amount
              Filter: prices.amount > Int32(0)
                SubqueryAlias: prices
                  Projection: prices.a + Int32(100) AS amount
                    TableScan: prices
            Projection: prices.amount
              Filter: prices.amount > Int32(1)
                SubqueryAlias: prices
                  Projection: prices.a + Int32(200) AS amount
                    TableScan: prices
        ")?;
        Ok(())
    }

    /// A volatile expression in the **projection** (SELECT list) must block the
    /// rewrite.  Each original branch evaluates it independently; merging them
    /// would evaluate it once per combined row, changing the row set.
    #[test]
    fn keep_union_distinct_with_volatile_projection() -> Result<()> {
        // Both branches project volatile_test() AS v over the same source.
        let scan = test_table_scan_with_name("t")?;
        let left = LogicalPlanBuilder::from(scan.clone())
            .filter(col("a").eq(lit(1)))?
            .project(vec![volatile_expr().alias("v"), col("a")])?
            .build()?;
        let right = LogicalPlanBuilder::from(scan)
            .filter(col("a").eq(lit(2)))?
            .project(vec![volatile_expr().alias("v"), col("a")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Union
            Projection: volatile_test() AS v, t.a
              Filter: t.a = Int32(1)
                TableScan: t
            Projection: volatile_test() AS v, t.a
              Filter: t.a = Int32(2)
                TableScan: t
        ")?;
        Ok(())
    }

    /// A scalar subquery in the **projection** must also block the rewrite.
    #[test]
    fn keep_union_distinct_with_subquery_in_projection() -> Result<()> {
        use datafusion_expr::scalar_subquery;

        // Build a simple scalar subquery: (SELECT t2.b FROM t2 WHERE t2.a = t.a)
        let t2 = test_table_scan_with_name("t2")?;
        let subquery_plan = Arc::new(
            LogicalPlanBuilder::from(t2)
                .filter(col("t2.a").eq(col("t.a")))?
                .project(vec![col("t2.b")])?
                .build()?,
        );
        let sq = scalar_subquery(subquery_plan);

        let scan = test_table_scan_with_name("t")?;
        let left = LogicalPlanBuilder::from(scan.clone())
            .filter(col("a").eq(lit(1)))?
            .project(vec![sq.clone().alias("sub"), col("a")])?
            .build()?;
        let right = LogicalPlanBuilder::from(scan)
            .filter(col("a").eq(lit(2)))?
            .project(vec![sq.alias("sub"), col("a")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        // Plan should be left untouched because the projection contains a subquery.
        let optimized = {
            let mut options = datafusion_common::config::ConfigOptions::default();
            options.optimizer.enable_unions_to_filter = true;
            let optimizer_ctx =
                OptimizerContext::new_with_config_options(Arc::new(options))
                    .with_max_passes(1);
            let rules: Vec<Arc<dyn OptimizerRule + Send + Sync>> =
                vec![Arc::new(UnionsToFilter::new())];
            crate::Optimizer::with_rules(rules).optimize(
                plan.clone(),
                &optimizer_ctx,
                |_, _| {},
            )?
        };
        // The Distinct(Union(...)) structure must be preserved.
        assert!(
            matches!(
                &optimized,
                LogicalPlan::Distinct(Distinct::All(inner))
                if matches!(inner.as_ref(), LogicalPlan::Union(_))
            ),
            "expected Distinct(Union(...)) to be preserved, got:\n{optimized:?}"
        );
        Ok(())
    }

    /// A UNION where both branches have a LIMIT must **not** be rewritten.
    /// Each branch independently restricts the row-set; collapsing them into a
    /// single branch would lose the per-branch LIMIT semantics.
    #[test]
    fn keep_union_distinct_with_limit_branches() -> Result<()> {
        let scan = test_table_scan_with_name("emp")?;
        let left = LogicalPlanBuilder::from(scan.clone())
            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
            .limit(0, Some(2))?
            .build()?;
        let right = LogicalPlanBuilder::from(scan)
            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
            .limit(0, Some(2))?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Union
            Limit: skip=0, fetch=2
              Projection: emp.a AS mgr, emp.b AS comm
                TableScan: emp
            Limit: skip=0, fetch=2
              Projection: emp.a AS mgr, emp.b AS comm
                TableScan: emp
        ")?;
        Ok(())
    }

    /// A UNION where both branches have an ORDER BY (Sort) must **not** be
    /// rewritten.  ORDER BY inside a UNION subquery does not guarantee ordering
    /// in the result; merging the branches would silently discard the Sort.
    #[test]
    fn keep_union_distinct_with_sort_branches() -> Result<()> {
        let scan = test_table_scan_with_name("emp")?;
        let left = LogicalPlanBuilder::from(scan.clone())
            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
            .sort(vec![col("a").sort(true, true)])?
            .build()?;
        let right = LogicalPlanBuilder::from(scan)
            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
            .sort(vec![col("a").sort(true, true)])?
            .build()?;

        let plan = LogicalPlanBuilder::from(left)
            .union_distinct(right)?
            .build()?;

        assert_optimized_plan_equal!(plan, @r"
        Distinct:
          Union
            Projection: mgr, comm
              Sort: emp.a ASC NULLS FIRST
                Projection: emp.a AS mgr, emp.b AS comm, emp.a
                  TableScan: emp
            Projection: mgr, comm
              Sort: emp.a ASC NULLS FIRST
                Projection: emp.a AS mgr, emp.b AS comm, emp.a
                  TableScan: emp
        ")?;
        Ok(())
    }
}