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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
// 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

//! [`PullUpCorrelatedExpr`] converts correlated subqueries to `Joins`

use std::collections::BTreeSet;
use std::sync::Arc;

use crate::push_down_filter::lr_is_preserved;
use crate::simplify_expressions::ExprSimplifier;
use crate::utils::replace_qualified_name;

use datafusion_common::nested_struct::is_injective_cast;
use datafusion_common::tree_node::{
    Transformed, TransformedResult, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
};
use datafusion_common::utils::has_float_leaf;
use datafusion_common::{
    Column, DFSchema, DFSchemaRef, HashMap, Result, ScalarValue, assert_or_internal_err,
    plan_err,
};
use datafusion_expr::expr::{Alias, GroupingSet};
use datafusion_expr::expr_rewriter::strip_outer_reference;
use datafusion_expr::logical_plan::{Join, JoinType};
use datafusion_expr::simplify::SimplifyContext;
use datafusion_expr::utils::{collect_subquery_cols, conjunction, split_conjunction};
use datafusion_expr::{
    Aggregate, BinaryExpr, Cast, Distinct, EmptyRelation, Expr, ExprSchemable, FetchType,
    LogicalPlan, LogicalPlanBuilder, MaterializedCte, MaterializedCtePlan, Operator,
    SkipType, Window, expr, lit,
};

/// This struct rewrite the sub query plan by pull up the correlated
/// expressions(contains outer reference columns) from the inner subquery's
/// 'Filter'. It adds the inner reference columns to the 'Projection' or
/// 'Aggregate' of the subquery if they are missing, so that they can be
/// evaluated by the parent operator as the join condition.
#[derive(Debug)]
pub struct PullUpCorrelatedExpr {
    pub join_filters: Vec<Expr>,
    /// mapping from the plan to its holding correlated columns
    pub correlated_subquery_cols_map: HashMap<LogicalPlan, BTreeSet<Column>>,
    pub in_predicate_opt: Option<Expr>,
    /// Is this an Exists(Not Exists) SubQuery. Defaults to **FALSE**
    pub exists_sub_query: bool,
    /// Can the correlated expressions be pulled up. Defaults to **TRUE**
    pub can_pull_up: bool,
    /// Indicates if we encounter any correlated expression that can not be pulled up
    /// above a aggregation without changing the meaning of the query.
    can_pull_over_aggregation: bool,
    /// Whether every correlated conjunct seen so far passes
    /// [`is_partitionable_equality`], so a Window above them can partition by their
    /// columns.
    can_extend_partition_by: bool,
    /// Do we need to handle [the count bug] during the pull up process.
    ///
    /// The "count bug" was described in [Optimization of Nested SQL
    /// Queries Revisited](https://dl.acm.org/doi/pdf/10.1145/38714.38723). This bug is
    /// not specific to the COUNT function, and it can occur with any aggregate function,
    /// such as SUM, AVG, etc. The anomaly arises because aggregates fail to distinguish
    /// between an empty set and null values when optimizing a correlated query as a join.
    /// Here, we use "the count bug" to refer to all such cases.
    ///
    /// [the count bug]: https://github.com/apache/datafusion/issues/10553
    pub need_handle_count_bug: bool,
    /// mapping from the plan to its expressions' evaluation result on empty batch
    pub collected_count_expr_map: HashMap<LogicalPlan, ExprResultMap>,
    /// pull up having expr, which must be evaluated after the Join
    pub pull_up_having_expr: Option<Expr>,
    /// whether we have converted a scalar aggregation into a group aggregation. When unnesting
    /// lateral joins, we need to produce a left outer join in such cases.
    ///
    /// An `Aggregate` above stops the pull up when this is set. `f_up` visits
    /// the aggregate that sets it before any node above.
    pub pulled_up_scalar_agg: bool,
    /// Every correlated conjunct that a `Filter` of the subquery applies,
    /// before `remove_duplicated_filter` drops the ones that the `IN`
    /// predicate already covers. The outer references are kept, so that a
    /// subquery column and an outer column with the same qualified name stay
    /// apart.
    ///
    /// `join_filters` holds only the conjuncts that the join still needs.
    /// This list is what the subquery enforces on its own rows. The caller
    /// uses it to tell if a join key can be NULL inside the scope of an outer
    /// row: `x IN (SELECT y FROM .. WHERE y = x)` keeps every NULL `y` out of
    /// its result, although `join_filters` no longer says so.
    ///
    /// The list is cleared when the pull up passes a node that can put a NULL
    /// back into such a column: an outer join, a union or a grouping set.
    pub correlated_filters: Vec<Expr>,
    /// Columns each node on the path from the subquery's root to the node
    /// [`Self::f_down`]/[`Self::f_up`] is currently visiting reads in its own
    /// expressions: one entry per node on that path, pushed in `f_down` and
    /// popped in `f_up`. When `f_up` visits an `Aggregate`, this holds every
    /// node strictly above it - its own entry is popped first - so a
    /// grouping set that omits a correlated column can tell whether
    /// something above it reads the column the pull up would fill in.
    column_refs_above: Vec<BTreeSet<Column>>,
    /// For each node on that same path, whether it returns rows based only on
    /// whether its input has rows (see [`depends_only_on_input_having_rows`]). One
    /// entry per node, pushed and popped with [`Self::column_refs_above`].
    /// `f_down`'s `Limit` arm reads it: a `Limit` is only dropped from an
    /// `EXISTS` subquery when this holds for every node above it.
    depends_only_on_input_having_rows_above: Vec<bool>,
}

impl Default for PullUpCorrelatedExpr {
    fn default() -> Self {
        Self::new()
    }
}

impl PullUpCorrelatedExpr {
    pub fn new() -> Self {
        Self {
            join_filters: vec![],
            correlated_subquery_cols_map: HashMap::new(),
            in_predicate_opt: None,
            exists_sub_query: false,
            can_pull_up: true,
            can_pull_over_aggregation: true,
            can_extend_partition_by: true,
            need_handle_count_bug: false,
            collected_count_expr_map: HashMap::new(),
            pull_up_having_expr: None,
            pulled_up_scalar_agg: false,
            correlated_filters: Vec::new(),
            column_refs_above: Vec::new(),
            depends_only_on_input_having_rows_above: Vec::new(),
        }
    }

    /// Set if we need to handle [the count bug] during the pull up process
    ///
    /// [the count bug]: https://github.com/apache/datafusion/issues/10553
    pub fn with_need_handle_count_bug(mut self, need_handle_count_bug: bool) -> Self {
        self.need_handle_count_bug = need_handle_count_bug;
        self
    }

    /// Set the in_predicate_opt
    pub fn with_in_predicate_opt(mut self, in_predicate_opt: Option<Expr>) -> Self {
        self.in_predicate_opt = in_predicate_opt;
        self
    }

    /// Set if this is an Exists(Not Exists) SubQuery
    pub fn with_exists_sub_query(mut self, exists_sub_query: bool) -> Self {
        self.exists_sub_query = exists_sub_query;
        self
    }
}

/// The outcome of trying to fold the pull up's columns into a grouping set
/// `Aggregate`. See [`PullUpCorrelatedExpr::grouping_sets_pull_up_outcome`].
#[derive(Debug, PartialEq, Eq)]
enum GroupingSetsPullUp {
    /// Every set already groups by the columns; the aggregate's `group_expr`
    /// stays as it is.
    NoColumnsToAdd,
    /// Some set leaves a required column out, but extending every set with it
    /// changes nothing the rest of the query can observe.
    SafeToExtend,
    /// Some set leaves a required column out, and extending every set with it
    /// would change what the query returns.
    Unsafe,
}

/// Used to indicate the unmatched rows from the inner(subquery) table after the left out Join
/// This is used to handle [the Count bug]
///
/// [the Count bug]: https://github.com/apache/datafusion/issues/10553
pub const UN_MATCHED_ROW_INDICATOR: &str = "__always_true";

/// Mapping from expr display name to its evaluation result on empty record
/// batch (for example: 'count(*)' is 'ScalarValue(0)', 'count(*) + 2' is
/// 'ScalarValue(2)')
pub type ExprResultMap = HashMap<String, Expr>;

impl TreeNodeRewriter for PullUpCorrelatedExpr {
    type Node = LogicalPlan;

    fn f_down(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
        // Tracks the columns this node's own expressions read, so a
        // descendant `Aggregate` can later tell what reads above it. Popped
        // by the matching `f_up` call for this same node.
        let mut column_refs = BTreeSet::new();
        for expr in plan.expressions() {
            column_refs.extend(expr.column_refs().into_iter().cloned());
        }
        self.column_refs_above.push(column_refs);
        self.depends_only_on_input_having_rows_above
            .push(depends_only_on_input_having_rows(&plan));

        // This match is exhaustive on purpose. A correlated filter moves above
        // a node only when the node is known to keep the result the same. Add
        // each new `LogicalPlan` variant to one of the groups below.
        match plan {
            LogicalPlan::Filter(_) => Ok(Transformed::no(plan)),
            // Subquery nodes are scope boundaries for correlation. A nested
            // Subquery's outer references belong to a different decorrelation
            // level and must not be pulled up into the current scope.
            LogicalPlan::Subquery(_) => {
                Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump))
            }
            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref cte))
                if !cte.cte.all_out_ref_exprs().is_empty() =>
            {
                // A correlated body would have to run once per outer row.
                Ok(self.stop_pull_up(plan))
            }
            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
                // Only the continuation can hold correlated expressions. Rewrite
                // it alone, so that the body shared by every scan keeps its schema.
                let continuation =
                    Arc::unwrap_or_clone(cte.continuation).rewrite(self)?;
                Ok(Transformed::new(
                    LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
                        MaterializedCte {
                            continuation: Arc::new(continuation.data),
                            ..cte
                        },
                    )),
                    continuation.transformed,
                    TreeNodeRecursion::Jump,
                ))
            }
            // A correlated filter can only move above a join from a side whose
            // rows the join preserves. Below the side an outer join fills with
            // NULLs, the filter decides which rows are unmatched, so pulling it
            // above the join changes the result. The side a semi, anti or mark
            // join does not output cannot give its columns to a pulled up
            // filter either.
            LogicalPlan::Join(ref join) if !correlated_inputs_are_preserved(join) => {
                Ok(self.stop_pull_up(plan))
            }
            // An ASOF join keeps each left row once, so a filter on the left
            // side can move above it. A filter on the right side selects the
            // rows the join can match, so it must stay below the join.
            LogicalPlan::AsOfJoin(ref join) if holds_outer_reference(&join.right) => {
                Ok(self.stop_pull_up(plan))
            }
            // An Unnest replaces the column it unnests with the values of that
            // column, so a filter on it means something else above the
            // Unnest. The output column loses its qualifier, so compare names.
            // The SQL planner unnests a new `__unnest_placeholder` column and
            // passes the original column through, so this only stops plans
            // built with `unnest_column` and similar.
            LogicalPlan::Unnest(ref unnest)
                if correlated_filter_columns(&unnest.input).iter().any(|col| {
                    unnest
                        .exec_columns
                        .iter()
                        .any(|exec_col| exec_col.name == col.name)
                }) =>
            {
                Ok(self.stop_pull_up(plan))
            }
            // A correlated filter cannot move out of one input of a Union, and
            // `f_up` does not add its columns to a Sort or an Extension, so no
            // correlated filter may be below these nodes.
            LogicalPlan::Union(_) | LogicalPlan::Sort(_) | LogicalPlan::Extension(_) => {
                if holds_outer_reference(&plan) {
                    Ok(self.stop_pull_up(plan))
                } else {
                    Ok(Transformed::no(plan))
                }
            }
            // For EXISTS only emptiness matters, so `f_down` removes or
            // replaces a Limit over a correlated filter where it can. Any other
            // Limit keeps the correlated filters below it.
            LogicalPlan::Limit(ref limit) => {
                if !holds_outer_reference(&plan) {
                    return Ok(Transformed::no(plan));
                }
                if !self.exists_sub_query {
                    return Ok(self.stop_pull_up(plan));
                }
                // A `LIMIT 0` always gives an empty input, whatever is
                // above it, so it becomes an empty relation.
                let fetch = limit.get_fetch_type()?;
                if matches!(fetch, FetchType::Literal(Some(0))) {
                    return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
                        EmptyRelation {
                            produce_one_row: false,
                            schema: Arc::clone(limit.input.schema()),
                        },
                    )));
                }
                // `EXISTS` asks whether the whole subquery returns a row, not
                // whether this `Limit` does. If a node above the `Limit` looks
                // at which rows it gets, such as a `Filter` or the `HAVING` in
                // https://github.com/apache/datafusion/issues/26629, removing
                // the `Limit` hands it different rows and can change the
                // answer, so the `Limit` has to stay.
                let (_, above) = self
                    .depends_only_on_input_having_rows_above
                    .split_last()
                    .expect("f_down pushed this Limit's own entry");
                if !above.iter().all(|follows| *follows) {
                    return Ok(self.stop_pull_up(plan));
                }

                match (limit.get_skip_type()?, fetch) {
                    (SkipType::Literal(0), FetchType::Literal(_)) => {
                        // The rewriter does not call `f_down` on the returned
                        // node, so do it here. This call pushes its own
                        // entry onto `column_refs_above`; pop the one this
                        // call pushed for the `Limit` itself first; only one
                        // `f_up` call reaches this tree position once `Limit`
                        // is gone, so only one entry must remain pushed.
                        self.column_refs_above.pop();
                        self.depends_only_on_input_having_rows_above.pop();
                        let mut t = self.f_down((*limit.input).clone())?;
                        t.transformed = true;
                        Ok(t)
                    }
                    _ => Ok(self.stop_pull_up(plan)),
                }
            }
            // A correlated filter below these nodes can move above them. The
            // node itself must not hold an outer reference, because only a
            // Filter gives its outer references to the join.
            // - `f_up` adds the columns the pulled up filter needs to a
            //   Projection or an Aggregate, and checks that the filter can move
            //   above an Aggregate.
            // - A `DISTINCT` shares the exemption of an Aggregate without
            //   aggregate functions: its output takes the columns the node
            //   below it adds, so they become part of its keys. This is only
            //   right when the pulled up filter fixes those columns for each
            //   outer row. A non-equality filter can return duplicates, see
            //   https://github.com/apache/datafusion/issues/25808.
            // - A Window keeps or drops whole partitions when the filter reads
            //   only its `PARTITION BY` columns. For other filters, `f_up` adds
            //   the columns of a column equality to `PARTITION BY` and keeps
            //   the subquery correlated in the remaining cases.
            // - An Unnest maps each input row to its own output rows, so a
            //   filter on a column it passes through keeps the same rows.
            //   The arm above checks that the filter does not read an unnested
            //   column.
            LogicalPlan::Projection(_)
            | LogicalPlan::Aggregate(_)
            | LogicalPlan::Distinct(Distinct::All(_))
            | LogicalPlan::Window(_)
            | LogicalPlan::Unnest(_)
            | LogicalPlan::Join(_)
            | LogicalPlan::AsOfJoin(_)
            | LogicalPlan::Repartition(_)
            | LogicalPlan::SubqueryAlias(_)
            | LogicalPlan::TableScan(_)
            | LogicalPlan::EmptyRelation(_)
            | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_))
            | LogicalPlan::Values(_) => {
                if plan.contains_outer_reference() {
                    // the unsupported cases, the plan expressions contain out
                    // reference columns
                    Ok(self.stop_pull_up(plan))
                } else {
                    Ok(Transformed::no(plan))
                }
            }
            // A correlated filter below these nodes cannot move above them:
            // - `DISTINCT ON` keeps the first row of each group, so the filter
            //   changes which row is first.
            // - A RecursiveQuery repeats its recursive term.
            // - The other nodes are not queries and are not in a subquery.
            LogicalPlan::Distinct(Distinct::On(_))
            | LogicalPlan::RecursiveQuery(_)
            | LogicalPlan::Statement(_)
            | LogicalPlan::Explain(_)
            | LogicalPlan::Analyze(_)
            | LogicalPlan::Dml(_)
            | LogicalPlan::Ddl(_)
            | LogicalPlan::Copy(_)
            | LogicalPlan::Show(_) => {
                if holds_outer_reference(&plan) {
                    Ok(self.stop_pull_up(plan))
                } else {
                    Ok(Transformed::no(plan))
                }
            }
        }
    }

    fn f_up(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
        // Pop this node's own entry, pushed by the matching `f_down` call, so
        // `column_refs_above` holds only the nodes strictly above `plan`.
        self.column_refs_above.pop();
        self.depends_only_on_input_having_rows_above.pop();

        // A node that null-extends or regroups rows can put a NULL back into
        // a column that a correlated filter below it rejected, so the filters
        // recorded so far no longer bound what the subquery returns.
        if !self.correlated_filters.is_empty() && may_reintroduce_nulls(&plan) {
            self.correlated_filters.clear();
        }
        let subquery_schema = plan.schema();
        match &plan {
            LogicalPlan::Filter(plan_filter) => {
                let subquery_filter_exprs = split_conjunction(&plan_filter.predicate);
                for &expr in subquery_filter_exprs.iter().filter(|e| e.contains_outer()) {
                    self.can_pull_over_aggregation &= can_pullup_over_aggregation(expr);
                    self.can_extend_partition_by &=
                        is_partitionable_equality(expr, plan_filter.input.schema());
                }
                for expr in &subquery_filter_exprs {
                    if expr.contains_outer() && !self.correlated_filters.contains(expr) {
                        self.correlated_filters.push((*expr).clone());
                    }
                }
                let (mut join_filters, subquery_filters) =
                    find_join_exprs(subquery_filter_exprs);
                if let Some(in_predicate) = &self.in_predicate_opt {
                    // in_predicate may be already included in the join filters, remove it from the join filters first.
                    join_filters = remove_duplicated_filter(join_filters, in_predicate)?;
                }
                let correlated_subquery_cols =
                    collect_subquery_cols(&join_filters, subquery_schema)?;
                for expr in join_filters {
                    if !self.join_filters.contains(&expr) {
                        self.join_filters.push(expr)
                    }
                }

                let mut expr_result_map_for_count_bug = HashMap::new();
                let pull_up_expr_opt = if let Some(expr_result_map) =
                    self.collected_count_expr_map.get(&*plan_filter.input)
                {
                    if let Some(expr) = conjunction(subquery_filters.clone()) {
                        filter_exprs_evaluation_result_on_empty_batch(
                            &expr,
                            Arc::clone(plan_filter.input.schema()),
                            expr_result_map,
                            &mut expr_result_map_for_count_bug,
                        )?
                    } else {
                        None
                    }
                } else {
                    None
                };

                if self.exists_sub_query
                    && self.pull_up_having_expr.is_some()
                    && let Some(expr) = conjunction(subquery_filters.clone())
                {
                    let unqualified_expr = expr
                        .transform_up(|e| {
                            if let Expr::Column(Column { name, .. }) = &e {
                                Ok(Transformed::yes(Expr::Column(
                                    Column::new_unqualified(name),
                                )))
                            } else {
                                Ok(Transformed::no(e))
                            }
                        })
                        .data()?;
                    let combined = match self.pull_up_having_expr.take() {
                        Some(existing) => existing.and(unqualified_expr),
                        None => unqualified_expr,
                    };
                    self.pull_up_having_expr = Some(combined);
                    let new_plan =
                        LogicalPlanBuilder::from((*plan_filter.input).clone()).build()?;
                    let mut carried_correlated_cols = correlated_subquery_cols;
                    if let Some(existing) =
                        self.correlated_subquery_cols_map.get(&*plan_filter.input)
                    {
                        carried_correlated_cols.extend(existing.iter().cloned());
                    }
                    self.correlated_subquery_cols_map
                        .insert(new_plan.clone(), carried_correlated_cols);
                    if !expr_result_map_for_count_bug.is_empty() {
                        self.collected_count_expr_map
                            .insert(new_plan.clone(), expr_result_map_for_count_bug);
                    } else if let Some(input_map) = self
                        .collected_count_expr_map
                        .get(&*plan_filter.input)
                        .cloned()
                    {
                        self.collected_count_expr_map
                            .insert(new_plan.clone(), input_map);
                    }
                    return Ok(Transformed::yes(new_plan));
                }

                match (&pull_up_expr_opt, &self.pull_up_having_expr) {
                    (Some(_), Some(_)) => {
                        // Error path
                        plan_err!("Unsupported Subquery plan")
                    }
                    (Some(_), None) => {
                        self.pull_up_having_expr = pull_up_expr_opt;
                        let new_plan =
                            LogicalPlanBuilder::from((*plan_filter.input).clone())
                                .build()?;
                        self.correlated_subquery_cols_map
                            .entry(new_plan.clone())
                            .or_default()
                            .extend(correlated_subquery_cols);
                        Ok(Transformed::yes(new_plan))
                    }
                    (None, _) => {
                        // if the subquery still has filter expressions, restore them.
                        let mut plan =
                            LogicalPlanBuilder::from((*plan_filter.input).clone());
                        if let Some(expr) = conjunction(subquery_filters) {
                            plan = plan.filter(expr)?
                        }
                        let new_plan = plan.build()?;
                        self.correlated_subquery_cols_map
                            .entry(new_plan.clone())
                            .or_default()
                            .extend(correlated_subquery_cols);
                        Ok(Transformed::yes(new_plan))
                    }
                }
            }
            LogicalPlan::Projection(projection)
                if self.in_predicate_opt.is_some() || !self.join_filters.is_empty() =>
            {
                let mut local_correlated_cols = BTreeSet::new();
                collect_local_correlated_cols(
                    &plan,
                    &self.correlated_subquery_cols_map,
                    &mut local_correlated_cols,
                );
                // add missing columns to Projection
                let mut missing_exprs = self.collect_missing_exprs(
                    &projection.expr,
                    &local_correlated_cols,
                    projection.input.schema(),
                )?;

                let mut expr_result_map_for_count_bug = HashMap::new();
                if let Some(expr_result_map) =
                    self.collected_count_expr_map.get(&*projection.input)
                {
                    proj_exprs_evaluation_result_on_empty_batch(
                        &missing_exprs,
                        projection.input.schema(),
                        expr_result_map,
                        &mut expr_result_map_for_count_bug,
                    )?;
                    if !expr_result_map_for_count_bug.is_empty() {
                        // has count bug
                        let un_matched_row = Expr::Column(Column::new_unqualified(
                            UN_MATCHED_ROW_INDICATOR.to_string(),
                        ));
                        // add the unmatched rows indicator to the Projection expressions
                        missing_exprs.push(un_matched_row);
                    }
                }

                let new_plan = LogicalPlanBuilder::from((*projection.input).clone())
                    .project(missing_exprs)?
                    .build()?;
                if !expr_result_map_for_count_bug.is_empty() {
                    self.collected_count_expr_map
                        .insert(new_plan.clone(), expr_result_map_for_count_bug);
                }
                Ok(Transformed::yes(new_plan))
            }
            LogicalPlan::Aggregate(aggregate)
                if self.in_predicate_opt.is_some() || !self.join_filters.is_empty() =>
            {
                // A pulled up scalar aggregate below gives no row for unmatched
                // outer rows, so this aggregate would see an empty input. Stop
                // the rewrite here, since rebuilding the nodes above can fail
                // with a schema error. See https://github.com/apache/datafusion/issues/26508
                if self.pulled_up_scalar_agg {
                    self.can_pull_up = false;
                    return Ok(Transformed::new(plan, false, TreeNodeRecursion::Stop));
                }
                // If the aggregation is from a distinct it will not change the result for
                // exists/in subqueries so we can still pull up all predicates.
                let is_distinct = aggregate.aggr_expr.is_empty();
                if !is_distinct {
                    self.can_pull_up = self.can_pull_up && self.can_pull_over_aggregation;
                }
                let mut local_correlated_cols = BTreeSet::new();
                collect_local_correlated_cols(
                    &plan,
                    &self.correlated_subquery_cols_map,
                    &mut local_correlated_cols,
                );
                // A grouping set that omits a column the pull up adds either
                // keeps its sets as they are (every set already groups by the
                // column), or gains the column in every set, `ROLLUP(i.k)`
                // (`GROUPING SETS ((i.k), ())`) becoming
                // `GROUPING SETS ((i.k), (i.k, i.k))`. The latter loses the
                // empty set, and with it the grand total row the subquery
                // returns for every outer row, including the rows whose
                // correlated filter matches nothing, so it is only safe when
                // no set is empty and nothing reads the column the fill
                // changes from `NULL` to the correlated value.
                let mut missing_exprs = if aggregate
                    .group_expr
                    .iter()
                    .any(|expr| matches!(expr, Expr::GroupingSet(_)))
                {
                    match self
                        .grouping_sets_pull_up_outcome(aggregate, &local_correlated_cols)
                    {
                        GroupingSetsPullUp::NoColumnsToAdd => {
                            // Every set already groups by them, so the sets stay as
                            // they are. Adding the columns again would repeat them
                            // inside every set.
                            aggregate.group_expr.to_vec()
                        }
                        GroupingSetsPullUp::SafeToExtend => {
                            // No set is empty and nothing reads the columns the
                            // fill changes from `NULL` to the correlated value,
                            // so extending every set is invisible to the rest of
                            // the query.
                            self.collect_missing_exprs(
                                &aggregate.group_expr,
                                &local_correlated_cols,
                                aggregate.input.schema(),
                            )?
                        }
                        GroupingSetsPullUp::Unsafe => {
                            self.can_pull_up = false;
                            // The rewrite still runs, the same way the
                            // `can_pull_over_aggregation` case above does. The callers
                            // read `can_pull_up` only after the whole rewrite has
                            // finished, and the nodes above this one still expect the
                            // pulled up columns in its output, so leaving them out here
                            // would fail the rewrite with a schema error instead. They
                            // drop this plan and keep the correlated subquery.
                            self.collect_missing_exprs(
                                &aggregate.group_expr,
                                &local_correlated_cols,
                                aggregate.input.schema(),
                            )?
                        }
                    }
                } else {
                    // add missing columns to Aggregation's group expressions
                    self.collect_missing_exprs(
                        &aggregate.group_expr,
                        &local_correlated_cols,
                        aggregate.input.schema(),
                    )?
                };

                // if the original group expressions are empty, need to handle the Count bug
                let mut expr_result_map_for_count_bug = HashMap::new();
                if self.need_handle_count_bug
                    && aggregate.group_expr.is_empty()
                    && !missing_exprs.is_empty()
                {
                    agg_exprs_evaluation_result_on_empty_batch(
                        &aggregate.aggr_expr,
                        aggregate.input.schema(),
                        &mut expr_result_map_for_count_bug,
                    )?;
                    if !expr_result_map_for_count_bug.is_empty() {
                        // has count bug
                        let un_matched_row = lit(true).alias(UN_MATCHED_ROW_INDICATOR);
                        // add the unmatched rows indicator to the Aggregation's group expressions
                        missing_exprs.push(un_matched_row);
                    }
                }
                if aggregate.group_expr.is_empty() {
                    self.pulled_up_scalar_agg = true;
                }
                let new_plan = LogicalPlanBuilder::from((*aggregate.input).clone())
                    .aggregate(missing_exprs, aggregate.aggr_expr.to_vec())?
                    .build()?;
                if !expr_result_map_for_count_bug.is_empty() {
                    self.collected_count_expr_map
                        .insert(new_plan.clone(), expr_result_map_for_count_bug);
                }
                Ok(Transformed::yes(new_plan))
            }
            LogicalPlan::SubqueryAlias(alias) => {
                let mut local_correlated_cols = BTreeSet::new();
                collect_local_correlated_cols(
                    &plan,
                    &self.correlated_subquery_cols_map,
                    &mut local_correlated_cols,
                );
                let mut new_correlated_cols = BTreeSet::new();
                for col in local_correlated_cols.iter() {
                    new_correlated_cols
                        .insert(Column::new(Some(alias.alias.clone()), col.name.clone()));
                }

                let new_plan = if alias.input.schema().fields().len()
                    != alias.schema.fields().len()
                {
                    LogicalPlanBuilder::from((*alias.input).clone())
                        .alias(alias.alias.clone())?
                        .build()?
                } else {
                    plan.clone()
                };

                self.correlated_subquery_cols_map
                    .insert(new_plan.clone(), new_correlated_cols);
                if let Some(input_map) = self.collected_count_expr_map.get(&*alias.input)
                {
                    self.collected_count_expr_map
                        .insert(new_plan.clone(), input_map.clone());
                }

                if new_plan != plan {
                    Ok(Transformed::yes(new_plan))
                } else {
                    Ok(Transformed::no(plan))
                }
            }
            LogicalPlan::Limit(limit) => {
                if let Some(input_map) =
                    self.collected_count_expr_map.get(&*limit.input).cloned()
                {
                    self.collected_count_expr_map
                        .insert(plan.clone(), input_map);
                }
                Ok(Transformed::no(plan))
            }
            LogicalPlan::Window(window) => {
                let mut local_correlated_cols = BTreeSet::new();
                collect_local_correlated_cols(
                    &plan,
                    &self.correlated_subquery_cols_map,
                    &mut local_correlated_cols,
                );
                // A filter that reads only `PARTITION BY` columns keeps or drops
                // whole partitions, so each window function sees the same rows
                // above it or below it. A filter on any other column changes the
                // rows of a partition.
                if !local_correlated_cols.is_empty()
                    && !window
                        .window_expr
                        .iter()
                        .all(|expr| partitions_by_all(expr, &local_correlated_cols))
                {
                    // `inner.y = outer.k` keeps the rows of one `y` value for
                    // each outer row, so partitioning by `y` as well gives each
                    // window function the same rows. An aggregate without
                    // `GROUP BY` below returns a row for an outer row without
                    // a match, which the pulled up filter would drop.
                    if self.can_extend_partition_by && !self.pulled_up_scalar_agg {
                        let extended =
                            partition_window_by(window, &local_correlated_cols)?;
                        return self.pass_through_pulled_up_cols(extended);
                    }
                    self.can_pull_up = false;
                }
                self.pass_through_pulled_up_cols(plan)
            }
            // `f_down` checked that the pulled up filters do not read an
            // unnested column.
            LogicalPlan::Unnest(_) => self.pass_through_pulled_up_cols(plan),
            _ => Ok(Transformed::no(plan)),
        }
    }
}

impl PullUpCorrelatedExpr {
    /// Keeps the correlated expressions below `plan` where they are. The caller
    /// then keeps the subquery correlated.
    fn stop_pull_up(&mut self, plan: LogicalPlan) -> Transformed<LogicalPlan> {
        self.can_pull_up = false;
        Transformed::new(plan, false, TreeNodeRecursion::Jump)
    }

    /// Rebuilds a node whose output holds every column of its input, so that
    /// it outputs the columns the pull up added below it.
    ///
    /// The count bug handling of a Projection or a Filter above reads the
    /// values an aggregate below gives on an empty input. Those values do not
    /// hold once a Window or an Unnest runs over the aggregate, so the pull up
    /// stops in that case.
    fn pass_through_pulled_up_cols(
        &mut self,
        plan: LogicalPlan,
    ) -> Result<Transformed<LogicalPlan>> {
        if plan
            .inputs()
            .iter()
            .any(|input| self.collected_count_expr_map.contains_key(*input))
        {
            self.can_pull_up = false;
        }
        Ok(Transformed::yes(plan.recompute_schema()?))
    }

    /// Whether the pull up can add its columns to a grouping set `Aggregate`,
    /// and whether it needs to.
    ///
    /// [`GroupingSetsPullUp::NoColumnsToAdd`] when every set of every grouping
    /// set already groups by each column [`Self::collect_missing_exprs`]
    /// would add: the pull up adds nothing and the aggregate keeps the sets
    /// it has.
    ///
    /// Otherwise some set leaves a required column out, which fills that
    /// column with `NULL` in the set's rows. Adding the column to every set
    /// (`LogicalPlanBuilder::aggregate` cross joins a plain group expression
    /// with the sets that are already there) gives it a value instead. This
    /// is only invisible to the rest of the query when:
    ///  - no set is empty. `ROLLUP(i.k)`, `GROUPING SETS ((i.k), ())`, always
    ///    holds one, and turns into `GROUPING SETS ((i.k), (i.k, i.k))`,
    ///    losing the empty set and the grand total row it yields for every
    ///    outer row, including the rows the correlated filter matches
    ///    nothing for. The join that replaces the filter cannot bring that
    ///    row back.
    ///  - the aggregate does not compute `GROUPING`/`GROUPING_ID`, which
    ///    reads whether a row's set groups by a column.
    ///  - nothing above the aggregate reads the column, which
    ///    `column_refs_above` tracks as `f_down`/`f_up` push and pop a node's
    ///    own columns while they walk down to and back up from it.
    ///
    /// When one of these fails, [`GroupingSetsPullUp::Unsafe`] is returned:
    /// the columns are still added, so the schema the nodes above expect
    /// stays correct, but the caller must give up on decorrelating.
    fn grouping_sets_pull_up_outcome(
        &self,
        aggregate: &Aggregate,
        correlated_subquery_cols: &BTreeSet<Column>,
    ) -> GroupingSetsPullUp {
        let group_expr = &aggregate.group_expr;
        let grouping_sets = group_expr
            .iter()
            .filter_map(|expr| match expr {
                Expr::GroupingSet(grouping_set) => Some(grouping_set),
                _ => None,
            })
            .collect::<Vec<_>>();
        if grouping_sets.is_empty() {
            return GroupingSetsPullUp::NoColumnsToAdd;
        }

        // The same columns `collect_missing_exprs` appends: the correlated columns
        // and the columns of a pulled up HAVING, minus the ones `group_expr`
        // already lists on their own, which it leaves alone.
        let mut required_cols = correlated_subquery_cols.iter().collect::<BTreeSet<_>>();
        if let Some(pull_up_having) = &self.pull_up_having_expr {
            required_cols.extend(pull_up_having.column_refs());
        }
        required_cols.retain(|col| {
            !group_expr
                .iter()
                .any(|expr| matches!(expr, Expr::Column(c) if c == *col))
        });
        if required_cols.is_empty() {
            return GroupingSetsPullUp::NoColumnsToAdd;
        }

        let already_covered =
            grouping_sets.iter().all(|grouping_set| match grouping_set {
                GroupingSet::Rollup(_) | GroupingSet::Cube(_) => false,
                GroupingSet::GroupingSets(sets) => sets.iter().all(|set| {
                    required_cols.iter().all(|col| {
                        set.iter()
                            .any(|expr| matches!(expr, Expr::Column(c) if c == *col))
                    })
                }),
            });
        if already_covered {
            return GroupingSetsPullUp::NoColumnsToAdd;
        }

        let has_empty_set = grouping_sets.iter().any(|grouping_set| match grouping_set {
            GroupingSet::Rollup(_) | GroupingSet::Cube(_) => true,
            GroupingSet::GroupingSets(sets) => sets.iter().any(|set| set.is_empty()),
        });
        // `GROUPING`/`GROUPING_ID` are resolved to bit tests on `__grouping_id`
        // above the aggregate by `ResolveGroupingFunction` before this rule
        // runs, so `aggregate.aggr_expr` never holds a `GROUPING` call by the
        // time this is reached; adding a column shifts those bits instead.
        let unsafe_read = self.column_refs_above.iter().flatten().any(|col| {
            col.name == Aggregate::INTERNAL_GROUPING_ID || required_cols.contains(col)
        });

        if has_empty_set || unsafe_read {
            GroupingSetsPullUp::Unsafe
        } else {
            GroupingSetsPullUp::SafeToExtend
        }
    }

    fn collect_missing_exprs(
        &mut self,
        exprs: &[Expr],
        correlated_subquery_cols: &BTreeSet<Column>,
        _subquery_schema: &DFSchemaRef,
    ) -> Result<Vec<Expr>> {
        let mut missing_exprs =
            Vec::with_capacity(exprs.len() + correlated_subquery_cols.len());
        for expr in exprs {
            if !missing_exprs.contains(expr) {
                missing_exprs.push(expr.clone())
            }
        }
        for col in correlated_subquery_cols.iter() {
            let col_expr = Expr::Column(col.clone());
            if !collides_with_existing(&missing_exprs, &col_expr) {
                missing_exprs.push(col_expr)
            }
        }
        if let Some(pull_up_having) = &self.pull_up_having_expr {
            for col in pull_up_having.column_refs() {
                let col_expr = Expr::Column(col.clone());
                // `col` is unqualified but the projection may already have
                // it as `agg.c`. Check by bare name so that doesn't get
                // added twice.
                let already_present = missing_exprs
                    .iter()
                    .any(|expr| matches!(expr, Expr::Column(c) if c.name == col.name))
                    || collides_with_existing(&missing_exprs, &col_expr);
                if !already_present {
                    missing_exprs.push(col_expr)
                }
            }
        }
        Ok(missing_exprs)
    }
}

/// Whether `plan` returns rows based only on whether its input has rows, and
/// not on which rows those are.
///
/// This is what lets `EXISTS` drop a `Limit` with no skip and a non-zero
/// fetch. Such a `Limit` returns rows exactly when its input has rows. If
/// every node above it also only depends on whether it gets rows, the whole
/// subquery returns rows exactly when the `Limit`'s input has rows, with or
/// without the `Limit`, so removing it cannot change the `EXISTS` result.
///
/// It holds for:
/// - `Projection`, `SubqueryAlias`, `Sort`, `Window` and `Repartition`, which
///   return rows whenever their input has rows (a `Sort` with a fetch of 0
///   returns none either way)
/// - `DISTINCT` and a grouped `Aggregate`, which return at least one row for a
///   non-empty input and none for an empty one
/// - an `Aggregate` without grouping, which always returns one row
/// - a materialized CTE, which returns its continuation's rows
///
/// It does not hold for a `Filter`, which keeps or removes rows by their
/// values, so the rows the `Limit` kept decide whether any survive. A `Join`
/// and an `Unnest` can also turn rows into none. Every other plan, including a
/// user-defined `Extension`, is treated as not holding: the `Limit` stays and
/// the subquery is not decorrelated.
fn depends_only_on_input_having_rows(plan: &LogicalPlan) -> bool {
    matches!(
        plan,
        LogicalPlan::Projection(_)
            | LogicalPlan::SubqueryAlias(_)
            | LogicalPlan::Sort(_)
            | LogicalPlan::Window(_)
            | LogicalPlan::Repartition(_)
            | LogicalPlan::Distinct(Distinct::All(_))
            | LogicalPlan::Aggregate(_)
            | LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_))
    )
}

/// Whether `plan` can output a NULL in a column that a filter below it keeps
/// free of NULLs: an outer join fills the columns of its unmatched side with
/// NULL, a union adds the rows of its other inputs, and a grouping set fills
/// the columns it leaves out with NULL, such as the grand total row of `ROLLUP`.
fn may_reintroduce_nulls(plan: &LogicalPlan) -> bool {
    match plan {
        LogicalPlan::Join(join) => {
            matches!(
                join.join_type,
                JoinType::Left | JoinType::Right | JoinType::Full
            )
        }
        LogicalPlan::Union(_) => true,
        LogicalPlan::Aggregate(aggregate) => aggregate
            .group_expr
            .iter()
            .any(|expr| matches!(expr, Expr::GroupingSet(_))),
        _ => false,
    }
}

/// Whether every input of `join` that holds outer references is a side whose
/// rows the join preserves, so a correlated filter below it can be pulled above
/// the join without changing the result.
fn correlated_inputs_are_preserved(join: &Join) -> bool {
    let (left_preserved, right_preserved) = lr_is_preserved(join.join_type);
    (left_preserved || !holds_outer_reference(&join.left))
        && (right_preserved || !holds_outer_reference(&join.right))
}

/// Whether `plan` or any of its inputs holds an outer reference of the scope
/// being decorrelated. Like [`PullUpCorrelatedExpr`], this does not descend into
/// a [`LogicalPlan::Subquery`], whose outer references belong to a nested
/// scope, such as the right side of a `LATERAL` join that is not decorrelated
/// yet.
fn holds_outer_reference(plan: &LogicalPlan) -> bool {
    let mut found = false;
    plan.apply(|node| {
        Ok(match node {
            LogicalPlan::Subquery(_) => TreeNodeRecursion::Jump,
            _ if node.contains_outer_reference() => {
                found = true;
                TreeNodeRecursion::Stop
            }
            _ => TreeNodeRecursion::Continue,
        })
    })
    .expect("apply closure is infallible");
    found
}

/// The columns that the correlated conjuncts of the Filters in `plan` read,
/// in the scope being decorrelated. Like [`holds_outer_reference`], this does
/// not descend into a [`LogicalPlan::Subquery`].
fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
    let mut cols = vec![];
    plan.apply(|node| {
        Ok(match node {
            LogicalPlan::Subquery(_) => TreeNodeRecursion::Jump,
            LogicalPlan::Filter(filter) => {
                for expr in split_conjunction(&filter.predicate) {
                    if expr.contains_outer() {
                        cols.extend(expr.column_refs().into_iter().cloned());
                    }
                }
                TreeNodeRecursion::Continue
            }
            _ => TreeNodeRecursion::Continue,
        })
    })
    .expect("apply closure is infallible");
    cols
}

/// Adds `cols` to the `PARTITION BY` of every window function of `window`. Each
/// window expression keeps its old output name, so nothing above sees a change.
fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
    let window_expr = window
        .window_expr
        .iter()
        .map(|expr| {
            add_partition_by(expr, cols).alias_if_changed(expr.schema_name().to_string())
        })
        .collect::<Result<Vec<_>>>()?;
    Window::try_new(window_expr, Arc::clone(&window.input)).map(LogicalPlan::Window)
}

fn add_partition_by(expr: &Expr, cols: &BTreeSet<Column>) -> Expr {
    match expr {
        Expr::Alias(alias) => Expr::Alias(Alias {
            expr: Box::new(add_partition_by(&alias.expr, cols)),
            ..alias.clone()
        }),
        Expr::WindowFunction(window_fun) => {
            let mut window_fun = window_fun.clone();
            for col in cols {
                let partitioned = window_fun
                    .params
                    .partition_by
                    .iter()
                    .any(|expr| matches!(expr, Expr::Column(c) if c == col));
                if !partitioned {
                    window_fun
                        .params
                        .partition_by
                        .push(Expr::Column(col.clone()));
                }
            }
            Expr::WindowFunction(window_fun)
        }
        _ => expr.clone(),
    }
}

/// Whether the window function `expr` lists each of `cols` as a plain
/// `PARTITION BY` column.
fn partitions_by_all(expr: &Expr, cols: &BTreeSet<Column>) -> bool {
    let mut expr = expr;
    while let Expr::Alias(Alias { expr: inner, .. }) = expr {
        expr = inner;
    }
    let Expr::WindowFunction(window_fun) = expr else {
        return false;
    };
    let partition_by = &window_fun.params.partition_by;
    cols.iter().all(|col| {
        partition_by
            .iter()
            .any(|expr| matches!(expr, Expr::Column(c) if c == col))
    })
}

/// True if `candidate` collides with an existing entry's schema name,
/// e.g. a bare column already wrapped in an equally-named `CAST`.
/// Colliding means `LogicalPlanBuilder::project` would reject it as a duplicate.
fn collides_with_existing(exprs: &[Expr], candidate: &Expr) -> bool {
    let candidate_name = candidate.schema_name().to_string();
    exprs
        .iter()
        .any(|expr| expr.schema_name().to_string() == candidate_name)
}

fn can_pullup_over_aggregation(expr: &Expr) -> bool {
    split_column_equality(expr).is_some()
}

/// Whether partitioning by the columns of `expr` keeps the rows `expr` matches
/// for one outer row in one partition. That holds for `col = <expr>` or
/// `<expr> = col`, where:
/// - `<expr>` reads no subquery column and is not volatile.
/// - `col` has no float leaf, because `-0.0 = 0.0` holds but a partition
///   keeps the two apart.
/// - `col` is cast only by a cast that keeps distinct values distinct. A lossy
///   cast lets several `col` values match one outer row, see #26014.
fn is_partitionable_equality(expr: &Expr, schema: &DFSchema) -> bool {
    let Some((col_side, other)) = split_column_equality(expr) else {
        return false;
    };
    let (col, cast_to) = match col_side {
        Expr::Cast(Cast { expr, field }) => (&**expr, Some(field.data_type())),
        _ => (col_side, None),
    };
    let Ok(col_type) = col.get_type(schema) else {
        return false;
    };
    !other.is_volatile()
        && !has_float_leaf(&col_type)
        && cast_to.is_none_or(|to| is_injective_cast(&col_type, to))
}

/// Splits `col = <expr>` or `<expr> = col` into the subquery column side, a
/// column or a cast of one, and the other side, which reads no subquery column.
fn split_column_equality(expr: &Expr) -> Option<(&Expr, &Expr)> {
    let Expr::BinaryExpr(BinaryExpr {
        left,
        op: Operator::Eq,
        right,
    }) = expr
    else {
        return None;
    };
    [(&**left, &**right), (&**right, &**left)]
        .into_iter()
        .find(|(col_side, other)| {
            let is_col = match col_side {
                Expr::Column(_) => true,
                Expr::Cast(Cast { expr, .. }) => matches!(&**expr, Expr::Column(_)),
                _ => false,
            };
            is_col && !other.any_column_refs()
        })
}

fn collect_local_correlated_cols(
    plan: &LogicalPlan,
    all_cols_map: &HashMap<LogicalPlan, BTreeSet<Column>>,
    local_cols: &mut BTreeSet<Column>,
) {
    for child in plan.inputs() {
        if let Some(cols) = all_cols_map.get(child) {
            local_cols.extend(cols.iter().cloned());
        }
        // SubqueryAlias is treated as the leaf node
        if !matches!(child, LogicalPlan::SubqueryAlias(_)) {
            collect_local_correlated_cols(child, all_cols_map, local_cols);
        }
    }
}

/// Extracts correlated predicates, such as a comparison between a column from the
/// subquery and a column from the outer scope.
///
/// Preserves [`Expr::OuterReferenceColumn`] markers so callers can distinguish
/// inner and outer columns when qualifying join filters (see [`build_join_filter`]).
///
/// # Arguments
///
/// * `exprs` - Subquery filter predicates to classify.
///
/// # Return value
///
/// Tuple of (correlated join filters, remaining subquery filters). Correlated
/// self-equalities are discarded from both lists.
pub(crate) fn find_join_exprs(exprs: Vec<&Expr>) -> (Vec<Expr>, Vec<Expr>) {
    let mut joins = vec![];
    let mut others = vec![];
    for filter in exprs {
        // Predicates containing outer references become join filters.
        if filter.contains_outer() {
            // Compare with the outer-reference markers intact: inner and outer
            // columns with the same qualified name belong to different scopes.
            if !matches!(filter, Expr::BinaryExpr(BinaryExpr { left, op: Operator::Eq, right }) if left.eq(right))
            {
                joins.push(filter.clone());
            }
        } else {
            others.push(filter.clone());
        }
    }
    (joins, others)
}

/// Combines join filters and qualifies their inner columns with the subquery alias.
///
/// Aliasing must precede stripping outer references so inner and outer columns
/// with the same qualified name remain distinguishable.
pub(crate) fn build_join_filter<'a>(
    join_filters: Vec<Expr>,
    correlated_cols: impl IntoIterator<Item = &'a Column>,
    subquery_alias: &str,
) -> Result<Option<Expr>> {
    let correlated_cols = correlated_cols
        .into_iter()
        .cloned()
        .collect::<BTreeSet<_>>();
    conjunction(join_filters)
        .map(|filter| {
            replace_qualified_name(filter, &correlated_cols, subquery_alias)
                .map(strip_outer_reference)
        })
        .transpose()
}

fn remove_duplicated_filter(
    filters: Vec<Expr>,
    in_predicate: &Expr,
) -> Result<Vec<Expr>> {
    // We assume below that swapping the order of operands to an operator does
    // not change behavior, which is only true if the operator is commutative.
    assert_or_internal_err!(
        match in_predicate {
            Expr::BinaryExpr(b) => b.op.swap() == Some(b.op),
            _ => true,
        },
        "in_predicate must use a commutative operator"
    );

    Ok(filters
        .into_iter()
        .filter(|filter| {
            let filter = &strip_outer_reference(filter.clone());
            if filter == in_predicate {
                return false;
            }

            // Treat swapped operand order to a binary operator as equivalent
            !match (filter, in_predicate) {
                (Expr::BinaryExpr(a_expr), Expr::BinaryExpr(b_expr)) => {
                    a_expr.op == b_expr.op
                        && ((a_expr.left == b_expr.left && a_expr.right == b_expr.right)
                            || (a_expr.left == b_expr.right
                                && a_expr.right == b_expr.left))
                }
                _ => false,
            }
        })
        .collect::<Vec<_>>())
}

fn agg_exprs_evaluation_result_on_empty_batch(
    agg_expr: &[Expr],
    schema: &DFSchemaRef,
    expr_result_map_for_count_bug: &mut ExprResultMap,
) -> Result<()> {
    let info = SimplifyContext::builder()
        .with_schema(Arc::clone(schema))
        .build();
    let simplifier = ExprSimplifier::new(info);
    for e in agg_expr.iter() {
        let result_expr = e
            .clone()
            .transform_up(|expr| {
                let new_expr = if let Expr::AggregateFunction(agg) = &expr {
                    let return_type = expr.get_type(schema.as_ref())?;
                    let default_value = agg.func.default_value(&return_type)?;
                    Transformed::yes(Expr::Literal(default_value, None))
                } else {
                    Transformed::no(expr)
                };
                Ok(new_expr)
            })
            .data()?;

        let result_expr = result_expr.unalias();
        let result_expr = simplifier.simplify(result_expr)?;
        expr_result_map_for_count_bug.insert(e.schema_name().to_string(), result_expr);
    }
    Ok(())
}

fn proj_exprs_evaluation_result_on_empty_batch(
    proj_expr: &[Expr],
    schema: &DFSchemaRef,
    input_expr_result_map_for_count_bug: &ExprResultMap,
    expr_result_map_for_count_bug: &mut ExprResultMap,
) -> Result<()> {
    for expr in proj_expr.iter() {
        let result_expr = expr
            .clone()
            .transform_up(|expr| {
                if let Expr::Column(Column { name, .. }) = &expr {
                    if let Some(result_expr) =
                        input_expr_result_map_for_count_bug.get(name)
                    {
                        Ok(Transformed::yes(result_expr.clone()))
                    } else {
                        Ok(Transformed::no(expr))
                    }
                } else {
                    Ok(Transformed::no(expr))
                }
            })
            .data()?;

        // An expression that reads no column, like `1 AS x`, keeps its value
        // on an empty input, while the join that replaces the subquery gives
        // it NULL for an outer row without a match.
        let is_constant = !expr.any_column_refs() && !expr.contains_outer();
        if result_expr.ne(expr) || is_constant {
            let info = SimplifyContext::builder()
                .with_schema(Arc::clone(schema))
                .build();
            let simplifier = ExprSimplifier::new(info);
            let result_expr = simplifier.simplify(result_expr)?;
            let expr_name = match expr {
                Expr::Alias(Alias { name, .. }) => name.to_string(),
                Expr::Column(Column {
                    relation: _,
                    name,
                    spans: _,
                }) => name.to_string(),
                _ => expr.schema_name().to_string(),
            };
            expr_result_map_for_count_bug.insert(expr_name, result_expr);
        }
    }
    Ok(())
}

fn filter_exprs_evaluation_result_on_empty_batch(
    filter_expr: &Expr,
    schema: DFSchemaRef,
    input_expr_result_map_for_count_bug: &ExprResultMap,
    expr_result_map_for_count_bug: &mut ExprResultMap,
) -> Result<Option<Expr>> {
    let result_expr = filter_expr
        .clone()
        .transform_up(|expr| {
            if let Expr::Column(Column { name, .. }) = &expr {
                if let Some(result_expr) = input_expr_result_map_for_count_bug.get(name) {
                    Ok(Transformed::yes(result_expr.clone()))
                } else {
                    Ok(Transformed::no(expr))
                }
            } else {
                Ok(Transformed::no(expr))
            }
        })
        .data()?;

    let pull_up_expr = if result_expr.ne(filter_expr) {
        let info = SimplifyContext::builder().with_schema(schema).build();
        let simplifier = ExprSimplifier::new(info);
        let result_expr = simplifier.simplify(result_expr)?;
        match &result_expr {
            Expr::Literal(ScalarValue::Null, _)
            | Expr::Literal(ScalarValue::Boolean(None), _)
            | Expr::Literal(ScalarValue::Boolean(Some(false)), _) => {
                for (name, exprs) in input_expr_result_map_for_count_bug {
                    expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
                }
                None
            }
            // evaluate to true on empty batch, need to pull up the expr
            Expr::Literal(ScalarValue::Boolean(Some(true)), _) => {
                for (name, exprs) in input_expr_result_map_for_count_bug {
                    expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
                }
                Some(filter_expr.clone())
            }
            // can not evaluate statically
            _ => {
                for input_expr in input_expr_result_map_for_count_bug.values() {
                    let new_expr = Expr::Case(expr::Case {
                        expr: None,
                        when_then_expr: vec![(
                            Box::new(result_expr.clone()),
                            Box::new(input_expr.clone()),
                        )],
                        else_expr: Some(Box::new(Expr::Literal(ScalarValue::Null, None))),
                    });
                    let expr_key = new_expr.schema_name().to_string();
                    expr_result_map_for_count_bug.insert(expr_key, new_expr);
                }
                None
            }
        }
    } else {
        for (name, exprs) in input_expr_result_map_for_count_bug {
            expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
        }
        None
    };
    Ok(pull_up_expr)
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::datatypes::DataType;
    use datafusion_expr::{col, out_ref_col};

    #[test]
    fn test_find_join_exprs_preserves_outer_references() {
        let outer = out_ref_col(DataType::Int32, "t.a");
        let correlated = col("t.a").eq(outer.clone());
        let self_equality = outer.clone().eq(outer);
        let local = col("t.b").gt(lit(2));

        assert_eq!(
            find_join_exprs(vec![&correlated, &self_equality, &local]),
            (vec![correlated], vec![local])
        );
    }

    #[test]
    fn test_build_join_filter() -> Result<()> {
        assert_eq!(build_join_filter(vec![], [], "sq")?, None);

        let column = Column::from("t.a");
        let outer = out_ref_col(DataType::Int32, "t.a");
        let filters = vec![col("t.a").eq(outer.clone()), outer.gt(lit(1))];

        assert_eq!(
            build_join_filter(filters, [&column, &column], "sq")?,
            Some(col("sq.a").eq(col("t.a")).and(col("t.a").gt(lit(1))))
        );
        Ok(())
    }
}