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
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
// 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

//! Two-pass optimizer pipeline that pushes cheap expressions (like struct field
//! access `user['status']`) closer to data sources, enabling early data reduction
//! and source-level optimizations (e.g., Parquet column pruning). See
//! [`ExtractLeafExpressions`] (pass 1) and [`PushDownLeafProjections`] (pass 2).
//!
//! # Precedence over [`PushDownFilter`]
//!
//! [`PushDownLeafProjections`] and [`PushDownFilter`] both move nodes towards
//! the leaves, and for an adjacent filter and *pure extraction projection* (a
//! projection whose expressions are only `__datafusion_extracted_N` aliases and
//! pass-through columns) they want the opposite order:
//!
//! ```text
//! Filter: t.date = '2025-01-03'                                  <-- (A)
//!   Projection: get_field(t.ids, 'id1') AS __datafusion_extracted_1, t.date   <-- (B)
//!     TableScan: t
//! ```
//!
//! `PushDownFilter` wants (A) below (B). `PushDownLeafProjections` wants (B)
//! below (A). Before <https://github.com/apache/datafusion/issues/14540> was
//! decided the two rules undid each other on every optimizer pass, and the rule
//! that runs later in the list won.
//!
//! **Invariant: pure extraction projections win.** `PushDownFilter` does not
//! move a filter below a pure extraction projection, so the plan above is the
//! final plan. `PushDownLeafProjections` keeps moving such a projection through
//! a filter, which is how the projection reaches the scan.
//!
//! The reason is that the extraction projection is the node a source absorbs.
//! A Parquet scan merges it into the file projection and reads only the struct
//! leaf. With the opposite precedence the scan reads the whole struct whenever
//! `datafusion.execution.parquet.pushdown_filters` is `false`, which is the
//! default. The filter loses nothing by staying one node higher, because
//! `PushDownFilter` records the predicate in
//! [`TableScan::filters`](datafusion_expr::logical_plan::TableScan) in the pass
//! that runs before the extraction projection exists, so row group pruning and
//! source level filtering still happen.
//!
//! # Yields to [`OptimizeProjections`]
//!
//! When the extraction projection cannot move below the input of a projection
//! (for example a `TableScan` or an `Aggregate`), [`PushDownLeafProjections`]
//! leaves the projection unchanged. Splitting it in place would give a
//! recovery projection over an extraction projection on the same input, and
//! `OptimizeProjections` merges those two back into the original projection.
//! The two rules would then undo each other on every optimizer pass. The split
//! has no use there: the source absorbs the leaf expressions of the original
//! projection just as well.
//!
//! [`PushDownFilter`]: crate::push_down_filter::PushDownFilter
//! [`OptimizeProjections`]: crate::optimize_projections::OptimizeProjections

use indexmap::{IndexMap, IndexSet};
use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;

use datafusion_common::alias::AliasGenerator;
use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion_common::{Column, DFSchema, Result, qualified_name};
use datafusion_expr::logical_plan::LogicalPlan;
use datafusion_expr::{Expr, ExpressionPlacement, Projection};

use crate::optimizer::ApplyOrder;
use crate::push_down_filter::replace_cols_by_name;
use crate::utils::{ColumnReference, has_all_column_refs, schema_columns};
use crate::{OptimizerConfig, OptimizerRule};

/// Prefix for aliases generated by the extraction optimizer passes.
///
/// This prefix is **reserved for internal optimizer use**. User-defined aliases
/// starting with this prefix may be misidentified as optimizer-generated
/// extraction aliases, leading to unexpected behavior. Do not use this prefix
/// in user queries.
const EXTRACTED_EXPR_PREFIX: &str = "__datafusion_extracted";

/// Returns `true` if any sub-expression in `exprs` has
/// [`ExpressionPlacement::MoveTowardsLeafNodes`] placement.
///
/// This is a lightweight pre-check that short-circuits as soon as one
/// extractable expression is found, avoiding the expensive allocations
/// (column HashSets, extractors, expression rewrites) that the full
/// extraction pipeline requires.
fn has_extractable_expr(exprs: &[Expr]) -> bool {
    exprs.iter().any(|expr| {
        expr.exists(|e| Ok(e.placement() == ExpressionPlacement::MoveTowardsLeafNodes))
            .unwrap_or(false)
    })
}

/// Returns the flat names of `plan`'s output columns whose defining expression
/// is volatile (e.g. `random()`).
///
/// Only a [`LogicalPlan::Projection`] can define such a column: anywhere else
/// the value has already been materialized by the projection that produced it,
/// so referencing the column again does not re-evaluate anything.
fn volatile_output_columns(plan: &LogicalPlan) -> BTreeSet<String> {
    let LogicalPlan::Projection(projection) = plan else {
        return BTreeSet::new();
    };
    projection
        .schema
        .iter()
        .zip(projection.expr.iter())
        .filter(|(_, expr)| expr.is_volatile())
        .map(|((qualifier, field), _)| Column::from((qualifier, field)).flat_name())
        .collect()
}

/// Returns `true` if building an extraction projection for `exprs` on top of
/// `input` would duplicate a volatile computation.
///
/// When `input` is already a projection, [`build_extraction_projection_impl`]
/// *merges* into it: every column reference in an extracted expression is
/// replaced by that column's defining expression (see
/// [`build_projection_replace_map`]). Inlining a volatile definition makes the
/// merged projection evaluate it a second, independent time, so the extracted
/// value no longer matches the column it was derived from:
///
/// ```text
/// Projection: s, get_field(s, 'a') AS field
///   Projection: named_struct('a', random()) AS s
/// ```
///
/// would merge into a single projection computing `random()` twice, and
/// `field` would then differ from `s['a']` on every row. Callers skip the
/// extraction instead.
fn would_duplicate_volatile<'a>(
    exprs: impl IntoIterator<Item = &'a Expr>,
    input: &LogicalPlan,
) -> bool {
    let volatile = volatile_output_columns(input);
    if volatile.is_empty() {
        return false;
    }
    exprs.into_iter().any(|expr| {
        expr.column_refs()
            .iter()
            .any(|col| volatile.contains(&col.flat_name()))
    })
}

/// Extracts `MoveTowardsLeafNodes` sub-expressions from non-projection nodes
/// into **extraction projections** (pass 1 of 2).
///
/// This handles Filter, Sort, Limit, Aggregate, and Join nodes. For Projection
/// nodes, extraction and pushdown are handled by [`PushDownLeafProjections`].
///
/// # Key Concepts
///
/// **Extraction projection**: a projection inserted *below* a node that
/// pre-computes a cheap expression and exposes it under an alias
/// (`__datafusion_extracted_N`). The parent node then references the alias
/// instead of the original expression.
///
/// **Recovery projection**: a projection inserted *above* a node to restore
/// the original output schema when extraction changes it.
/// Schema-preserving nodes (Filter, Sort, Limit) gain extra columns from
/// the extraction projection that bubble up; the recovery projection selects
/// only the original columns to hide the extras.
///
/// # Example
///
/// Given a filter with a struct field access:
///
/// ```text
/// Filter: user['status'] = 'active'
///   TableScan: t [id, user]
/// ```
///
/// This rule:
/// 1. Inserts an **extraction projection** below the filter:
/// 2. Adds a **recovery projection** above to hide the extra column:
///
/// ```text
/// Projection: id, user                                                        <-- recovery projection
///   Filter: __datafusion_extracted_1 = 'active'
///     Projection: user['status'] AS __datafusion_extracted_1, id, user         <-- extraction projection
///       TableScan: t [id, user]
/// ```
///
/// **Important:** The `PushDownFilter` rule is aware of projections created by this rule
/// and will not push filters through them. It uses `ExpressionPlacement` to detect
/// `MoveTowardsLeafNodes` expressions and skip filter pushdown past them.
#[derive(Default, Debug)]
pub struct ExtractLeafExpressions {}

impl ExtractLeafExpressions {
    /// Create a new [`ExtractLeafExpressions`]
    pub fn new() -> Self {
        Self {}
    }
}

impl OptimizerRule for ExtractLeafExpressions {
    fn name(&self) -> &str {
        "extract_leaf_expressions"
    }

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

        // Advance the alias generator past any user-provided __datafusion_extracted_N
        // aliases to prevent collisions when generating new extraction aliases.
        advance_generator_past_existing(&plan, alias_generator)?;

        plan.transform_down_with_subqueries(|plan| {
            extract_from_plan(plan, alias_generator)
        })
    }
}

/// Scans the plan for pre-existing `__datafusion_extracted_N` aliases and
/// advances the generator counter past them to avoid collisions with
/// user-provided aliases.
///
/// Subquery plans nested inside expressions are scanned as well: extraction
/// rewrites with `transform_down_with_subqueries`, so it can generate aliases
/// *inside* a subquery and would otherwise collide with a user alias there.
fn advance_generator_past_existing(
    plan: &LogicalPlan,
    alias_generator: &AliasGenerator,
) -> Result<()> {
    plan.apply_with_subqueries(|plan| {
        plan.apply_expressions(|expr| {
            expr.apply(|e| {
                if let Expr::Alias(alias) = e
                    && let Some(id) = alias
                        .name
                        .strip_prefix(EXTRACTED_EXPR_PREFIX)
                        .and_then(|s| s.strip_prefix('_'))
                        .and_then(|s| s.parse().ok())
                {
                    alias_generator.update_min_id(id);
                }
                Ok(TreeNodeRecursion::Continue)
            })
        })
    })
    .map(|_| ())
}

/// Extracts `MoveTowardsLeafNodes` sub-expressions from a plan node.
///
/// Works for any number of inputs (0, 1, 2, …N). For multi-input nodes
/// like Join, each extracted sub-expression is routed to the correct input
/// by checking which input's schema contains all of the expression's column
/// references.
fn extract_from_plan(
    plan: LogicalPlan,
    alias_generator: &Arc<AliasGenerator>,
) -> Result<Transformed<LogicalPlan>> {
    // Only extract from plan types whose output schema is predictable after
    // expression rewriting.  Nodes like Window derive column names from
    // their expressions, so rewriting `get_field` inside a window function
    // changes the output schema and breaks the recovery projection.
    if !matches!(
        &plan,
        LogicalPlan::Aggregate(_)
            | LogicalPlan::Filter(_)
            | LogicalPlan::Sort(_)
            | LogicalPlan::Limit(_)
            | LogicalPlan::Join(_)
    ) {
        return Ok(Transformed::no(plan));
    }

    let inputs = plan.inputs();
    if inputs.is_empty() {
        return Ok(Transformed::no(plan));
    }

    // Fast pre-check: skip all allocations if no extractable expressions exist
    let node_exprs = plan.expressions();
    if !has_extractable_expr(&node_exprs) {
        return Ok(Transformed::no(plan));
    }

    // The extraction projection is merged into an input that is already a
    // projection, which inlines the referenced columns' definitions. Skip the
    // extraction when that would duplicate a volatile computation.
    if inputs
        .iter()
        .any(|input| would_duplicate_volatile(node_exprs.iter(), input))
    {
        return Ok(Transformed::no(plan));
    }

    // Save original output schema before any transformation
    let original_schema = Arc::clone(plan.schema());

    // Build per-input schemas from borrowed inputs (before plan is consumed
    // by map_expressions). We only need schemas and column sets for routing;
    // the actual inputs are cloned later only if extraction succeeds.
    let input_schemas: Vec<Arc<DFSchema>> =
        inputs.iter().map(|i| Arc::clone(i.schema())).collect();

    // Build per-input extractors
    let mut extractors: Vec<LeafExpressionExtractor> = input_schemas
        .iter()
        .map(|schema| LeafExpressionExtractor::new(schema.as_ref(), alias_generator))
        .collect();

    // Build per-input column sets for routing expressions to the correct input
    let input_column_sets: Vec<std::collections::HashSet<ColumnReference>> =
        input_schemas
            .iter()
            .map(|schema| schema_columns(schema.as_ref()))
            .collect();

    // Transform expressions via map_expressions with routing
    let transformed = plan.map_expressions(|expr| {
        routing_extract(expr, &mut extractors, &input_column_sets)
    })?;

    // If no expressions were rewritten, nothing was extracted
    if !transformed.transformed {
        return Ok(transformed);
    }

    // Clone inputs now that we know extraction succeeded. Wrap in Arc
    // upfront since build_extraction_projection expects &Arc<LogicalPlan>.
    let owned_inputs: Vec<Arc<LogicalPlan>> = transformed
        .data
        .inputs()
        .into_iter()
        .map(|i| Arc::new(i.clone()))
        .collect();

    // Build per-input extraction projections (None means no extractions for that input)
    let new_inputs: Vec<LogicalPlan> = owned_inputs
        .into_iter()
        .zip(extractors.iter())
        .map(|(input_arc, extractor)| {
            match extractor.build_extraction_projection(&input_arc)? {
                Some(plan) => Ok(plan),
                // No extractions for this input — recover the LogicalPlan
                // without cloning (refcount is 1 since build returned None).
                None => Ok(Arc::unwrap_or_clone(input_arc)),
            }
        })
        .collect::<Result<Vec<_>>>()?;

    // Rebuild the plan keeping its rewritten expressions but replacing
    // inputs with the new extraction projections.
    let new_plan = transformed
        .data
        .with_new_exprs(transformed.data.expressions(), new_inputs)?;

    // Add recovery projection if the output schema changed
    let recovered = build_recovery_projection(original_schema.as_ref(), new_plan)?;

    Ok(Transformed::yes(recovered))
}

/// Given an expression, returns the index of the input whose columns fully
/// cover the expression's column references.
/// Returns `None` if the expression references columns from multiple inputs
/// or if multiple inputs match (ambiguous, e.g. unqualified columns present
/// in both sides of a join).
fn find_owning_input(
    expr: &Expr,
    input_column_sets: &[std::collections::HashSet<ColumnReference>],
) -> Option<usize> {
    let mut found = None;
    for (idx, cols) in input_column_sets.iter().enumerate() {
        if has_all_column_refs(expr, cols) {
            if found.is_some() {
                // Ambiguous — multiple inputs match
                return None;
            }
            found = Some(idx);
        }
    }
    found
}

/// Walks an expression tree top-down, extracting `MoveTowardsLeafNodes`
/// sub-expressions and routing each to the correct per-input extractor.
fn routing_extract(
    expr: Expr,
    extractors: &mut [LeafExpressionExtractor],
    input_column_sets: &[std::collections::HashSet<ColumnReference>],
) -> Result<Transformed<Expr>> {
    expr.transform_down(|e| {
        // Skip expressions already aliased with extracted expression pattern
        if let Expr::Alias(alias) = &e
            && alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
        {
            return Ok(Transformed {
                data: e,
                transformed: false,
                tnr: TreeNodeRecursion::Jump,
            });
        }

        // Don't extract Alias nodes directly — preserve the alias and let
        // transform_down recurse into the inner expression
        if matches!(&e, Expr::Alias(_)) {
            return Ok(Transformed::no(e));
        }

        match e.placement() {
            ExpressionPlacement::MoveTowardsLeafNodes => {
                if let Some(idx) = find_owning_input(&e, input_column_sets) {
                    let col_ref = extractors[idx].add_extracted(e)?;
                    Ok(Transformed::yes(col_ref))
                } else {
                    // References columns from multiple inputs — cannot extract
                    Ok(Transformed::no(e))
                }
            }
            ExpressionPlacement::Column => {
                // Track columns that the parent node references so the
                // extraction projection includes them as pass-through.
                // Without this, the extraction projection would only
                // contain __datafusion_extracted_N aliases, and the parent couldn't
                // resolve its other column references.
                if let Expr::Column(col) = &e
                    && let Some(idx) = find_owning_input(&e, input_column_sets)
                {
                    extractors[idx].columns_needed.insert(col.clone());
                }
                Ok(Transformed::no(e))
            }
            _ => Ok(Transformed::no(e)),
        }
    })
}

/// Rewrites extraction pairs and column references from one qualifier
/// space to another.
///
/// Builds a replacement map by zipping `from_schema` (whose qualifiers
/// currently appear in `pairs` / `columns`) with `to_schema` (the
/// qualifiers we want), then applies `replace_cols_by_name`.
///
/// Used for SubqueryAlias (alias-space -> input-space) and Union
/// (union output-space -> per-branch input-space).
fn remap_pairs_and_columns(
    pairs: &[(Expr, String)],
    columns: &IndexSet<Column>,
    from_schema: &DFSchema,
    to_schema: &DFSchema,
) -> Result<ExtractionTarget> {
    let mut replace_map = HashMap::with_capacity(from_schema.fields().len());
    for ((from_q, from_f), (to_q, to_f)) in from_schema.iter().zip(to_schema.iter()) {
        replace_map.insert(
            qualified_name(from_q, from_f.name()),
            Expr::Column(Column::new(to_q.cloned(), to_f.name())),
        );
    }
    let remapped_pairs: Vec<(Expr, String)> = pairs
        .iter()
        .map(|(expr, alias)| {
            Ok((
                replace_cols_by_name(expr.clone(), &replace_map)?,
                alias.clone(),
            ))
        })
        .collect::<Result<_>>()?;
    let remapped_columns: IndexSet<Column> = columns
        .iter()
        .filter_map(|col| {
            let rewritten =
                replace_cols_by_name(Expr::Column(col.clone()), &replace_map).ok()?;
            if let Expr::Column(c) = rewritten {
                Some(c)
            } else {
                Some(col.clone())
            }
        })
        .collect();
    Ok(ExtractionTarget {
        pairs: remapped_pairs,
        columns: remapped_columns,
    })
}

// =============================================================================
// Helper Types & Functions for Extraction Targeting
// =============================================================================

/// A bundle of extraction pairs (expression + alias) and standalone columns
/// that need to be pushed through a plan node.
struct ExtractionTarget {
    /// Extracted expressions paired with their generated aliases.
    pairs: Vec<(Expr, String)>,
    /// Standalone column references needed by the parent node.
    columns: IndexSet<Column>,
}

/// Build a replacement map from a projection: output_column_name -> underlying_expr.
///
/// This is used to resolve column references through a renaming projection.
/// For example, if a projection has `user AS x`, this maps `x` -> `col("user")`.
fn build_projection_replace_map(projection: &Projection) -> HashMap<String, Expr> {
    projection
        .schema
        .iter()
        .zip(projection.expr.iter())
        .map(|((qualifier, field), expr)| {
            let key = Column::from((qualifier, field)).flat_name();
            (key, expr.clone().unalias())
        })
        .collect()
}

/// Build a recovery projection to restore the original output schema.
///
/// After extraction, a node's output schema may differ from the original:
///
/// - **Schema-preserving nodes** (Filter/Sort/Limit): the extraction projection
///   below adds extra `__datafusion_extracted_N` columns that bubble up through
///   the node. Recovery selects only the original columns to hide the extras.
///   ```text
///   Original schema: [id, user]
///   After extraction: [__datafusion_extracted_1, id, user]   ← extra column leaked through
///   Recovery: SELECT id, user FROM ...                       ← hides __datafusion_extracted_1
///   ```
///
/// - **Schema-defining nodes** (Aggregate): same number of columns but names
///   may differ because extracted aliases replaced the original expressions.
///   Recovery maps positionally, aliasing where names changed.
///   ```text
///   Original: [SUM(user['balance'])]
///   After:    [SUM(__datafusion_extracted_1)]                ← name changed
///   Recovery: SUM(__datafusion_extracted_1) AS "SUM(user['balance'])"
///   ```
///
/// - **Schemas identical** → no recovery projection needed.
fn build_recovery_projection(
    original_schema: &DFSchema,
    input: LogicalPlan,
) -> Result<LogicalPlan> {
    let new_schema = input.schema();
    let orig_len = original_schema.fields().len();
    let new_len = new_schema.fields().len();

    if orig_len == new_len {
        // Same number of fields — check if schemas are identical
        let schemas_match = original_schema.iter().zip(new_schema.iter()).all(
            |((orig_q, orig_f), (new_q, new_f))| {
                orig_f.name() == new_f.name() && orig_q == new_q
            },
        );
        if schemas_match {
            return Ok(input);
        }

        // Schema-defining nodes (Aggregate, Join): names may differ at some
        // positions because extracted aliases replaced the original expressions.
        // Map positionally, aliasing where the name changed.
        //
        // Invariant: `with_new_exprs` on all supported node types (Aggregate,
        // Filter, Sort, Limit, Join) preserves column order, so positional
        // mapping is safe here.
        debug_assert!(
            orig_len == new_len,
            "build_recovery_projection: positional mapping requires same field count, \
             got original={orig_len} vs new={new_len}"
        );
        let mut proj_exprs = Vec::with_capacity(orig_len);
        for (i, (orig_qualifier, orig_field)) in original_schema.iter().enumerate() {
            let (new_qualifier, new_field) = new_schema.qualified_field(i);
            if orig_field.name() == new_field.name() && orig_qualifier == new_qualifier {
                proj_exprs.push(Expr::from((orig_qualifier, orig_field)));
            } else {
                let new_col = Expr::Column(Column::from((new_qualifier, new_field)));
                proj_exprs.push(
                    new_col.alias_qualified(orig_qualifier.cloned(), orig_field.name()),
                );
            }
        }
        let projection = Projection::try_new(proj_exprs, Arc::new(input))?;
        Ok(LogicalPlan::Projection(projection))
    } else {
        // Schema-preserving nodes: new schema has extra extraction columns.
        // Original columns still exist by name; select them to hide extras.
        let col_exprs: Vec<Expr> = original_schema.iter().map(Expr::from).collect();
        let projection = Projection::try_new(col_exprs, Arc::new(input))?;
        Ok(LogicalPlan::Projection(projection))
    }
}

/// Collects `MoveTowardsLeafNodes` sub-expressions found during expression
/// tree traversal and can build an extraction projection from them.
///
/// # Example
///
/// Given `Filter: user['status'] = 'active' AND user['name'] IS NOT NULL`:
/// - `add_extracted(user['status'])` → stores it, returns `col("__datafusion_extracted_1")`
/// - `add_extracted(user['name'])`   → stores it, returns `col("__datafusion_extracted_2")`
/// - `build_extraction_projection()` produces:
///   `Projection: user['status'] AS __datafusion_extracted_1, user['name'] AS __datafusion_extracted_2, <all input columns>`
struct LeafExpressionExtractor<'a> {
    /// Extracted expressions: maps expression -> alias
    extracted: IndexMap<Expr, String>,
    /// Columns referenced by extracted expressions or the parent node,
    /// included as pass-through in the extraction projection.
    columns_needed: IndexSet<Column>,
    /// Input schema
    input_schema: &'a DFSchema,
    /// Alias generator
    alias_generator: &'a Arc<AliasGenerator>,
}

impl<'a> LeafExpressionExtractor<'a> {
    fn new(input_schema: &'a DFSchema, alias_generator: &'a Arc<AliasGenerator>) -> Self {
        Self {
            extracted: IndexMap::new(),
            columns_needed: IndexSet::new(),
            input_schema,
            alias_generator,
        }
    }

    /// Adds an expression to extracted set, returns column reference.
    fn add_extracted(&mut self, expr: Expr) -> Result<Expr> {
        // Deduplication: reuse existing alias if same expression
        if let Some(alias) = self.extracted.get(&expr) {
            return Ok(Expr::Column(Column::new_unqualified(alias)));
        }

        // Track columns referenced by this expression
        for col in expr.column_refs() {
            self.columns_needed.insert(col.clone());
        }

        // Generate unique alias
        let alias = self.alias_generator.next(EXTRACTED_EXPR_PREFIX);
        self.extracted.insert(expr, alias.clone());

        Ok(Expr::Column(Column::new_unqualified(&alias)))
    }

    /// Builds an extraction projection above the given input, or merges into
    /// it if the input is already a projection. Delegates to
    /// [`build_extraction_projection_impl`].
    ///
    /// Returns `None` if there are no extractions.
    fn build_extraction_projection(
        &self,
        input: &Arc<LogicalPlan>,
    ) -> Result<Option<LogicalPlan>> {
        if self.extracted.is_empty() {
            return Ok(None);
        }
        let pairs: Vec<(Expr, String)> = self
            .extracted
            .iter()
            .map(|(e, a)| (e.clone(), a.clone()))
            .collect();
        let proj = build_extraction_projection_impl(
            &pairs,
            &self.columns_needed,
            input,
            self.input_schema,
        )?;
        Ok(Some(LogicalPlan::Projection(proj)))
    }
}

/// Resolves `col` against `schema` and returns it with the qualifier that
/// `schema` gives the field. Returns `None` if `schema` does not hold `col`,
/// or if the name is ambiguous in `schema`.
///
/// Two spellings of the same input column (a bare `c` and a qualified `t.c`)
/// resolve to the same `Column`, so they compare equal. A column pushed into
/// a projection this way uses the name that the input gives it.
fn resolve_against(schema: &DFSchema, col: &Column) -> Option<Column> {
    schema
        .qualified_field_from_column(col)
        .ok()
        .map(Column::from)
}

/// Build an extraction projection above the target node (shared by both passes).
///
/// If the target is an existing projection, merges into it. This requires
/// resolving column references through the projection's rename mapping:
/// if the projection has `user AS u`, and an extracted expression references
/// `u['name']`, we must rewrite it to `user['name']` since the merged
/// projection reads from the same input as the original.
///
/// Deduplicates by resolved expression equality and adds pass-through
/// columns as needed. Otherwise builds a fresh projection with extracted
/// expressions + ALL input schema columns.
fn build_extraction_projection_impl(
    extracted_exprs: &[(Expr, String)],
    columns_needed: &IndexSet<Column>,
    target: &Arc<LogicalPlan>,
    target_schema: &DFSchema,
) -> Result<Projection> {
    if let LogicalPlan::Projection(existing) = target.as_ref() {
        // Merge into existing projection
        let mut proj_exprs = existing.expr.clone();

        // Build a map of existing expressions (by Expr equality) to their aliases
        let existing_extractions: IndexMap<Expr, String> = existing
            .expr
            .iter()
            .filter_map(|e| {
                if let Expr::Alias(alias) = e
                    && alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
                {
                    return Some((*alias.expr.clone(), alias.name.clone()));
                }
                None
            })
            .collect();

        // Resolve column references through the projection's rename mapping
        let replace_map = build_projection_replace_map(existing);

        // Add new extracted expressions, resolving column refs through the projection
        for (expr, alias) in extracted_exprs {
            let resolved = replace_cols_by_name(expr.clone().alias(alias), &replace_map)?;
            let resolved_inner = if let Expr::Alias(a) = &resolved {
                a.expr.as_ref()
            } else {
                &resolved
            };
            if let Some(existing_alias) = existing_extractions.get(resolved_inner) {
                // Same expression already extracted under a different alias —
                // add the expression with the new alias so both names are
                // available in the output. We can't reference the existing alias
                // as a column within the same projection, so we duplicate the
                // computation.
                if existing_alias != alias {
                    proj_exprs.push(resolved);
                }
            } else {
                proj_exprs.push(resolved);
            }
        }

        // Add any new pass-through columns that aren't already in the projection.
        // We check against existing.input.schema() (the projection's source) rather
        // than target_schema (the projection's output) because columns produced
        // by alias expressions (e.g., CSE's __common_expr_N) exist in the output but
        // not the input, and cannot be added as pass-through Column references.
        //
        // Resolve the pass-through columns of `existing` (including same-name
        // aliases such as `t.c AS c`) and the columns in `columns_needed`
        // against the input schema before comparing them. Otherwise a bare `c`
        // and a qualified `t.c` do not match, and the merged projection holds
        // both, which `Projection::try_new` rejects as ambiguous.
        let input_schema = existing.input.schema();
        let existing_cols: IndexSet<Column> = existing
            .expr
            .iter()
            .filter_map(|e| resolve_against(input_schema, passthrough_column(e)?))
            .collect();

        // The names the merged projection already produces. The merge keeps
        // every expression of `existing`, so the parent can still read each of
        // these names, and a pass-through column that carries one of them makes
        // the output schema ambiguous.
        let output_names: std::collections::HashSet<&str> = existing
            .schema
            .fields()
            .iter()
            .map(|f| f.name().as_str())
            .collect();

        for col in columns_needed {
            // The projection produces this name, so the parent reads it from the
            // projection's own output. Do not resolve the name through the rename
            // map: a rename such as `t.a AS b` is a computed output, and its
            // input column `t.a` beside the output field `a` of a second rename
            // gives an ambiguous schema (issue #25446).
            if output_names.contains(col.name.as_str()) {
                continue;
            }
            let col_expr = Expr::Column(col.clone());
            let resolved = replace_cols_by_name(col_expr, &replace_map)?;
            if let Expr::Column(resolved_col) = &resolved
                && let Some(input_col) = resolve_against(input_schema, resolved_col)
                && !existing_cols.contains(&input_col)
                && !output_names.contains(input_col.name.as_str())
            {
                proj_exprs.push(Expr::Column(input_col));
            }
            // Skip a column that resolves to a non-column expr: the existing
            // projection already computes it. Also skip a column that is not in
            // the input or is ambiguous there: no single spelling is correct.
        }

        Projection::try_new(proj_exprs, Arc::clone(&existing.input))
    } else {
        // Build new projection with extracted expressions + all input columns
        let mut proj_exprs =
            Vec::with_capacity(extracted_exprs.len() + target_schema.fields().len());
        for (expr, alias) in extracted_exprs {
            proj_exprs.push(expr.clone().alias(alias));
        }
        for (qualifier, field) in target_schema.iter() {
            proj_exprs.push(Expr::from((qualifier, field)));
        }
        Projection::try_new(proj_exprs, Arc::clone(target))
    }
}

// =============================================================================
// Pass 2: PushDownLeafProjections
// =============================================================================

/// Pushes extraction projections down through schema-preserving nodes towards
/// leaf nodes (pass 2 of 2, after [`ExtractLeafExpressions`]).
///
/// Handles two types of projections:
/// - **Pure extraction projections** (all `__datafusion_extracted` aliases + columns):
///   pushes through Filter/Sort/Limit, merges into existing projections, or routes
///   into multi-input node inputs (Join, SubqueryAlias, etc.)
/// - **Mixed projections** (user projections containing `MoveTowardsLeafNodes`
///   sub-expressions): splits into a recovery projection + extraction projection,
///   then pushes the extraction projection down.
///
/// # Example: Pushing through a Filter
///
/// After pass 1, the extraction projection sits directly below the filter:
/// ```text
/// Projection: id, user                                                              <-- recovery
///   Filter: __datafusion_extracted_1 = 'active'
///     Projection: user['status'] AS __datafusion_extracted_1, id, user               <-- extraction
///       TableScan: t [id, user]
/// ```
///
/// Pass 2 pushes the extraction projection through the recovery and filter,
/// and a subsequent `OptimizeProjections` pass removes the (now-redundant)
/// recovery projection:
/// ```text
/// Filter: __datafusion_extracted_1 = 'active'
///   Projection: user['status'] AS __datafusion_extracted_1, id, user                 <-- extraction (pushed down)
///     TableScan: t [id, user]
/// ```
#[derive(Default, Debug)]
pub struct PushDownLeafProjections {}

impl PushDownLeafProjections {
    pub fn new() -> Self {
        Self {}
    }
}

impl OptimizerRule for PushDownLeafProjections {
    fn name(&self) -> &str {
        "push_down_leaf_projections"
    }

    fn apply_order(&self) -> Option<ApplyOrder> {
        Some(ApplyOrder::TopDown)
    }

    fn rewrite(
        &self,
        plan: LogicalPlan,
        config: &dyn OptimizerConfig,
    ) -> Result<Transformed<LogicalPlan>> {
        if !config.options().optimizer.enable_leaf_expression_pushdown {
            return Ok(Transformed::no(plan));
        }
        let alias_generator = config.alias_generator();
        match try_push_input(&plan, alias_generator)? {
            Some(new_plan) => Ok(Transformed::yes(new_plan)),
            None => Ok(Transformed::no(plan)),
        }
    }
}

/// Attempts to push a projection's extractable expressions further down.
///
/// Returns `Some(new_subtree)` if the projection was pushed down or merged,
/// `None` if there is nothing to push or the projection sits above a barrier.
fn try_push_input(
    input: &LogicalPlan,
    alias_generator: &Arc<AliasGenerator>,
) -> Result<Option<LogicalPlan>> {
    let LogicalPlan::Projection(proj) = input else {
        return Ok(None);
    };
    split_and_push_projection(proj, alias_generator)
}

/// If this is a passthrough column.  I.e,
///
///  - A bare column expression
///  - A trivial alias rename (i.e, `p.column AS column`)
fn passthrough_column(expr: &Expr) -> Option<&Column> {
    match expr {
        Expr::Column(col) => Some(col),
        Expr::Alias(alias) => match alias.expr.as_ref() {
            Expr::Column(col) if col.name == alias.name => Some(col),
            _ => None,
        },
        _ => None,
    }
}

/// Returns `true` if merging the extracted `pairs` (and the pass-through
/// `columns_needed`) into `child` would inline a `KeepInPlace` definition into
/// more than one reference site — e.g. a struct-returning UDF `f(c)` behind both
/// `f(c)['a']` and `f(c)['b']`, or behind `f(c)['a']` and a bare `f(c)`.
///
/// `CommonSubexprEliminate` hoists such an expression into a shared column so it
/// runs once; [`build_extraction_projection_impl`] then resolves that column
/// back to its definition and re-duplicates it. Mirrors the
/// `optimize_projections` merge guard (#8296): a compute-once expression used
/// more than once stays in place.
fn merge_would_duplicate_kept_expr(
    pairs: &[(Expr, String)],
    columns_needed: &IndexSet<Column>,
    child: &Projection,
) -> bool {
    // Columns whose `KeepInPlace` definition must stay put; inlining one would
    // duplicate a compute-once expression. Plain columns, pushable exprs, and
    // literals are all cheap to duplicate, so only `KeepInPlace` counts.
    let kept_columns: std::collections::HashSet<String> = child
        .schema
        .iter()
        .zip(child.expr.iter())
        .filter_map(|((qualifier, field), expr)| {
            if matches!(expr.placement(), ExpressionPlacement::KeepInPlace) {
                Some(Column::from((qualifier, field)).flat_name())
            } else {
                None
            }
        })
        .collect();
    if kept_columns.is_empty() {
        return false;
    }

    // Count every site that references a kept column. A pair that references the
    // same kept column twice still inlines one copy, so count each pair at most
    // once per column.
    let mut usage: HashMap<String, usize> = HashMap::new();
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    for (expr, _alias) in pairs {
        seen.clear();
        for col in expr.column_refs() {
            let name = col.flat_name();
            if kept_columns.contains(&name) && seen.insert(name.clone()) {
                *usage.entry(name).or_insert(0) += 1;
            }
        }
    }
    // Pass-through / pre-existing-alias inputs are additional reference sites:
    // a bare `f(c)` alongside `f(c)['a']` also pins the compute-once column, so
    // counting only `pairs` under-counted and re-duplicated it (#23655).
    for col in columns_needed {
        let name = col.flat_name();
        if kept_columns.contains(&name) {
            *usage.entry(name).or_insert(0) += 1;
        }
    }
    usage.values().any(|&count| count > 1)
}

/// Splits a projection into extractable pieces, pushes them towards leaf
/// nodes, and adds a recovery projection if needed.
///
/// Handles both:
/// - **Pure extraction projections** (all `__datafusion_extracted` aliases + columns)
/// - **Mixed projections** (containing `MoveTowardsLeafNodes` sub-expressions)
///
/// Returns `Some(new_subtree)` if extractions were pushed down,
/// `None` if there is nothing to extract or push.
///
/// # Example: Mixed Projection
///
/// ```text
/// Input plan:
///   Projection: user['name'] IS NOT NULL AS has_name, id
///     Filter: ...
///       TableScan
///
/// Phase 1 (Split):
///   extraction_pairs: [(user['name'], "__datafusion_extracted_1")]
///   recovery_exprs:   [__datafusion_extracted_1 IS NOT NULL AS has_name, id]
///
/// Phase 2 (Push):
///   Push extraction projection through Filter toward TableScan
///
/// Phase 3 (Recovery):
///   Projection: __datafusion_extracted_1 IS NOT NULL AS has_name, id       <-- recovery
///     Filter: ...
///       Projection: user['name'] AS __datafusion_extracted_1, id           <-- extraction (pushed)
///         TableScan
/// ```
fn split_and_push_projection(
    proj: &Projection,
    alias_generator: &Arc<AliasGenerator>,
) -> Result<Option<LogicalPlan>> {
    // Fast pre-check: skip if there are no pre-existing extracted aliases
    // and no new extractable expressions.
    let has_existing_extracted = proj.expr.iter().any(|e| {
        matches!(e, Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX))
    });
    if !has_existing_extracted && !has_extractable_expr(&proj.expr) {
        return Ok(None);
    }

    let input = &proj.input;
    let input_schema = input.schema();

    // ── Phase 1: Split ──────────────────────────────────────────────────
    // For each projection expression, collect extraction pairs and build
    // recovery expressions.
    //
    // Pre-existing `__datafusion_extracted` aliases are inserted into the
    // extractor's `IndexMap` with the **full** `Expr::Alias(…)` as the key,
    // so the alias name participates in equality. This prevents collisions
    // when CSE rewrites produce the same inner expression under different
    // alias names (e.g. `__common_expr_4 AS __datafusion_extracted_1` and
    // `__common_expr_4 AS __datafusion_extracted_3`). New extractions from
    // `routing_extract` use bare (non-Alias) keys and get normal dedup.
    //
    // When building the final `extraction_pairs`, the Alias wrapper is
    // stripped so consumers see the usual `(inner_expr, alias_name)` tuples.

    let mut extractors = vec![LeafExpressionExtractor::new(
        input_schema.as_ref(),
        alias_generator,
    )];
    let input_column_sets = vec![schema_columns(input_schema.as_ref())];

    let original_schema = proj.schema.as_ref();
    let mut recovery_exprs: Vec<Expr> = Vec::with_capacity(proj.expr.len());
    let mut has_new_extractions = false;
    let mut proj_exprs_captured: usize = 0;

    for (expr, (qualifier, field)) in proj.expr.iter().zip(original_schema.iter()) {
        if let Some(col) = passthrough_column(expr) {
            // Pass-through — the input already produces this column, so
            // there is nothing to extract; just track it in the extractor.
            extractors[0].columns_needed.insert(col.clone());
            recovery_exprs.push(expr.clone());
            proj_exprs_captured += 1;
        } else if let Expr::Alias(alias) = expr
            && alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
        {
            // Insert the full Alias expression as the key so that
            // distinct alias names don't collide in the IndexMap.
            let alias_name = alias.name.clone();

            for col_ref in alias.expr.column_refs() {
                extractors[0].columns_needed.insert(col_ref.clone());
            }

            extractors[0]
                .extracted
                .insert(expr.clone(), alias_name.clone());
            recovery_exprs.push(Expr::Column(Column::new_unqualified(&alias_name)));
            proj_exprs_captured += 1;
        } else {
            // Everything else: run through routing_extract
            let transformed =
                routing_extract(expr.clone(), &mut extractors, &input_column_sets)?;
            if transformed.transformed {
                has_new_extractions = true;
            }
            let transformed_expr = transformed.data;

            // Build recovery expression, aliasing back to original name if needed
            let original_name = field.name();
            let needs_alias = if let Expr::Column(col) = &transformed_expr {
                col.name.as_str() != original_name
            } else {
                let expr_name = transformed_expr.schema_name().to_string();
                original_name != &expr_name
            };
            let recovery_expr = if needs_alias {
                transformed_expr
                    .clone()
                    .alias_qualified(qualifier.cloned(), original_name)
            } else {
                transformed_expr.clone()
            };

            recovery_exprs.push(recovery_expr);
        }
    }

    // Build extraction_pairs, stripping the Alias wrapper from pre-existing
    // entries (they used the full Alias as the map key to avoid dedup).
    let extractor = &extractors[0];
    let extraction_pairs: Vec<(Expr, String)> = extractor
        .extracted
        .iter()
        .map(|(e, a)| match e {
            Expr::Alias(alias) => (*alias.expr.clone(), a.clone()),
            _ => (e.clone(), a.clone()),
        })
        .collect();
    let columns_needed = &extractor.columns_needed;

    // If no extractions found, nothing to do
    if extraction_pairs.is_empty() {
        return Ok(None);
    }

    // Pushing into an input that is already a projection merges into it and
    // inlines the referenced columns' definitions. Leave the projection alone
    // when that would duplicate a volatile computation.
    if would_duplicate_volatile(
        extraction_pairs.iter().map(|(expr, _)| expr),
        input.as_ref(),
    ) {
        return Ok(None);
    }

    // Merging here would re-inline an expression `CommonSubexprEliminate` hoisted
    // to run once, undoing it (issue #23655); leave the projection in place.
    if let LogicalPlan::Projection(child) = input.as_ref()
        && merge_would_duplicate_kept_expr(&extraction_pairs, columns_needed, child)
    {
        return Ok(None);
    }

    // ── Phase 2: Push down ──────────────────────────────────────────────
    let proj_input = Arc::clone(&proj.input);
    let pushed = push_extraction_pairs(
        &extraction_pairs,
        columns_needed,
        proj,
        &proj_input,
        alias_generator,
        proj_exprs_captured,
    )?;

    // ── Phase 3: Recovery ───────────────────────────────────────────────
    // Determine the base plan: either the pushed result or an in-place extraction.
    let base_plan = match pushed {
        Some(plan) => plan,
        None => {
            if !has_new_extractions {
                // Only pre-existing __datafusion_extracted aliases and columns, no new
                // extractions from routing_extract. The original projection is
                // already an extraction projection that couldn't be pushed
                // further. Return None. This return also ends the recursion
                // of the `try_push_input` call below, which comes back here
                // with a pure extraction projection.
                return Ok(None);
            }
            // Build the extraction projection in place, then push it. It is a
            // pure extraction projection, which can go through nodes that the
            // original projection cannot.
            let input_arc = Arc::clone(input);
            let extraction = LogicalPlan::Projection(build_extraction_projection_impl(
                &extraction_pairs,
                columns_needed,
                &input_arc,
                input_schema.as_ref(),
            )?);
            match try_push_input(&extraction, alias_generator)? {
                Some(pushed) => pushed,
                // The extraction projection cannot move below `input`. Leave
                // the original projection unchanged: the split would put the
                // extraction projection on the same input, and
                // `OptimizeProjections` merges the recovery and extraction
                // projections back into the original projection. The rules
                // would then undo each other in every optimizer pass. The
                // source absorbs the leaf expressions of the original
                // projection just as well.
                None => return Ok(None),
            }
        }
    };

    // The recovery projection restores the original projection's output. We need
    // it whenever `base_plan` no longer exposes the same set of output column
    // names, which happens two ways:
    //   * a column is *renamed* — a transformed expression now surfaces as its
    //     internal `__datafusion_extracted_*` alias instead of the original name;
    //   * a column is *leaked* — pushing the projection down widens `base_plan`
    //     with an inner extraction projection's *other* extracted aliases bubbling
    //     up through a Filter. A schema-caching parent like SubqueryAlias then
    //     keeps a stale schema (see `map_children` in `logical_plan/tree_node.rs`)
    //     and the later `optimize_projections` pass fails to resolve columns.
    //
    // Both are captured by comparing the *set of unqualified field names*. We
    // compare by unqualified name rather than the full qualified schema on
    // purpose: extracted aliases are globally unique, so name-only comparison is
    // unambiguous for them, while it ignores the benign column reordering and the
    // `SubqueryAlias` re-qualification (`sub.__datafusion_extracted_1` vs
    // `__datafusion_extracted_1`) that a qualified/ordered comparison would
    // spuriously treat as drift, stacking redundant recovery projections.
    //
    // A name comparison alone is not sufficient. A name says nothing about the
    // *value* behind it. Take the projection
    // `(- t.a) AS a, t.s, get_field(t.s, "b") AS __datafusion_extracted_1`. When
    // the extraction goes below it, the pushed plan keeps every name, but it
    // exposes the table column `t.a` where the projection computed `- t.a`. If
    // the recovery projection goes away, the computed column becomes its own
    // input column and the query gives wrong results. See
    // <https://github.com/apache/datafusion/issues/25414>.
    //
    // So the recovery projection also stays when a recovery expression computes
    // a value, that is, when it is not a pass-through of a column.
    let base_names: BTreeSet<&str> = base_plan
        .schema()
        .fields()
        .iter()
        .map(|f| f.name().as_str())
        .collect();
    let original_names: BTreeSet<&str> = original_schema
        .fields()
        .iter()
        .map(|f| f.name().as_str())
        .collect();
    let computes_a_value = recovery_exprs
        .iter()
        .any(|expr| passthrough_column(expr).is_none());
    let needs_recovery = base_names != original_names || computes_a_value;

    // Wrap with recovery projection if the output schema changed
    if needs_recovery {
        let recovery = LogicalPlan::Projection(Projection::try_new(
            recovery_exprs,
            Arc::new(base_plan),
        )?);
        Ok(Some(recovery))
    } else {
        Ok(Some(base_plan))
    }
}

/// Returns true if `exprs` are the expressions of a *pure extraction
/// projection*: every expression is either `Alias(EXTRACTED_EXPR_PREFIX, ...)`
/// or a bare `Column`, and there is at least one extraction alias.
///
/// Such projections can safely be pushed further without re-extraction.
///
/// [`PushDownFilter`](crate::push_down_filter::PushDownFilter) uses the same
/// predicate to keep a filter above such a projection. See the module
/// documentation for the precedence rule.
pub(crate) fn is_pure_extraction_projection(exprs: &[Expr]) -> bool {
    let mut has_extraction = false;
    for expr in exprs {
        match expr {
            Expr::Alias(alias) if alias.name.starts_with(EXTRACTED_EXPR_PREFIX) => {
                has_extraction = true;
            }
            Expr::Column(_) => {}
            _ => return false,
        }
    }
    has_extraction
}

/// Pushes extraction pairs down through the projection's input node,
/// dispatching to the appropriate handler based on the input node type.
fn push_extraction_pairs(
    pairs: &[(Expr, String)],
    columns_needed: &IndexSet<Column>,
    proj: &Projection,
    proj_input: &Arc<LogicalPlan>,
    alias_generator: &Arc<AliasGenerator>,
    proj_exprs_captured: usize,
) -> Result<Option<LogicalPlan>> {
    match proj_input.as_ref() {
        // Merge into existing projection, then try to push the result further down.
        // Only merge when every expression in the outer projection is fully
        // captured as either an extraction pair (Case A: __datafusion_extracted
        // alias) or a plain column (Case B). Uncaptured expressions (e.g.
        // `col AS __common_expr_1` from CSE, or complex expressions with
        // extracted sub-parts) would be lost during the merge.
        LogicalPlan::Projection(_) if proj_exprs_captured == proj.expr.len() => {
            let target_schema = Arc::clone(proj_input.schema());
            let merged = build_extraction_projection_impl(
                pairs,
                columns_needed,
                proj_input,
                target_schema.as_ref(),
            )?;
            let merged_is_pure = is_pure_extraction_projection(&merged.expr);
            let merged_plan = LogicalPlan::Projection(merged);

            // After merging, try to push the result further down, but ONLY
            // if the merged result is still a pure extraction projection
            // (all __datafusion_extracted aliases + columns). If the merge inherited
            // bare MoveTowardsLeafNodes expressions from the inner projection,
            // pushing would re-extract them into new aliases and fail when
            // the (None, true) fallback can't find the original aliases.
            // This handles: Extraction → Recovery(cols) → Filter → ... → TableScan
            // by pushing through the recovery projection AND the filter in one pass.
            if merged_is_pure
                && let Some(pushed) = try_push_input(&merged_plan, alias_generator)?
            {
                return Ok(Some(pushed));
            }
            Ok(Some(merged_plan))
        }
        // Generic: handles Filter/Sort/Limit (via recursion),
        // SubqueryAlias (with qualifier remap in try_push_into_inputs),
        // Join, and anything else.
        // Safely bails out for nodes that don't pass through extracted
        // columns (Aggregate, Window) via the output schema check.
        _ => try_push_into_inputs(
            pairs,
            columns_needed,
            proj_input.as_ref(),
            alias_generator,
        ),
    }
}

/// Routes extraction pairs and columns to the appropriate inputs.
///
/// - **Union**: broadcasts to every input via [`remap_pairs_and_columns`].
/// - **Other nodes**: routes each expression to the one input that owns
///   all of its column references (via [`find_owning_input`]).
///
/// Returns `None` if any expression can't be routed or no input has pairs.
fn route_to_inputs(
    pairs: &[(Expr, String)],
    columns: &IndexSet<Column>,
    node: &LogicalPlan,
    input_column_sets: &[std::collections::HashSet<ColumnReference>],
    input_schemas: &[Arc<DFSchema>],
) -> Result<Option<Vec<ExtractionTarget>>> {
    let num_inputs = input_schemas.len();
    let mut per_input: Vec<ExtractionTarget> = (0..num_inputs)
        .map(|_| ExtractionTarget {
            pairs: vec![],
            columns: IndexSet::new(),
        })
        .collect();

    if matches!(node, LogicalPlan::Union(_)) {
        // Union output schema and each input schema have the same fields by
        // index but may differ in qualifiers (e.g. output `s` vs input
        // `simple_struct.s`). Remap pairs/columns to each input's space.
        let union_schema = node.schema();
        for (idx, input_schema) in input_schemas.iter().enumerate() {
            per_input[idx] =
                remap_pairs_and_columns(pairs, columns, union_schema, input_schema)?;
        }
    } else {
        for (expr, alias) in pairs {
            match find_owning_input(expr, input_column_sets) {
                Some(idx) => per_input[idx].pairs.push((expr.clone(), alias.clone())),
                None => return Ok(None), // Cross-input expression — bail out
            }
        }
        for col in columns {
            let col_expr = Expr::Column(col.clone());
            match find_owning_input(&col_expr, input_column_sets) {
                Some(idx) => {
                    per_input[idx].columns.insert(col.clone());
                }
                None => return Ok(None), // Ambiguous column — bail out
            }
        }
    }

    // Check at least one input has extractions to push
    if per_input.iter().all(|t| t.pairs.is_empty()) {
        return Ok(None);
    }

    Ok(Some(per_input))
}

/// Pushes extraction expressions into a node's inputs by routing each
/// expression to the input that owns all of its column references.
///
/// Works for any number of inputs (1, 2, …N). For single-input nodes,
/// all expressions trivially route to that input. For multi-input nodes
/// (Join, etc.), each expression is routed to the side that owns its columns.
///
/// Returns `Some(new_node)` if all expressions could be routed AND the
/// rebuilt node's output schema contains all extracted aliases.
/// Returns `None` if any expression references columns from multiple inputs
/// or the node doesn't pass through the extracted columns.
///
/// # Example: Join with expressions from both sides
///
/// ```text
/// Extraction projection above a Join:
///   Projection: left.user['name'] AS __datafusion_extracted_1, right.order['total'] AS __datafusion_extracted_2, ...
///     Join: left.id = right.user_id
///       TableScan: left [id, user]
///       TableScan: right [user_id, order]
///
/// After routing each expression to its owning input:
///   Join: left.id = right.user_id
///     Projection: user['name'] AS __datafusion_extracted_1, id, user              <-- left-side extraction
///       TableScan: left [id, user]
///     Projection: order['total'] AS __datafusion_extracted_2, user_id, order      <-- right-side extraction
///       TableScan: right [user_id, order]
/// ```
fn try_push_into_inputs(
    pairs: &[(Expr, String)],
    columns_needed: &IndexSet<Column>,
    node: &LogicalPlan,
    alias_generator: &Arc<AliasGenerator>,
) -> Result<Option<LogicalPlan>> {
    let inputs = node.inputs();
    if inputs.is_empty() {
        return Ok(None);
    }

    // Unnest may output a column with the same name but different value/type
    // than its input column. Name-based routing cannot distinguish those.
    if matches!(node, LogicalPlan::Unnest(_)) {
        return Ok(None);
    }

    // SubqueryAlias remaps qualifiers between input and output.
    // Rewrite pairs/columns from alias-space to input-space before routing.
    let remapped = if let LogicalPlan::SubqueryAlias(sa) = node {
        remap_pairs_and_columns(pairs, columns_needed, &sa.schema, sa.input.schema())?
    } else {
        ExtractionTarget {
            pairs: pairs.to_vec(),
            columns: columns_needed.clone(),
        }
    };
    let pairs = &remapped.pairs[..];
    let columns_needed = &remapped.columns;

    // Build per-input schemas and column sets for routing
    let input_schemas: Vec<Arc<DFSchema>> =
        inputs.iter().map(|i| Arc::clone(i.schema())).collect();
    let input_column_sets: Vec<std::collections::HashSet<ColumnReference>> =
        input_schemas.iter().map(|s| schema_columns(s)).collect();

    // Route pairs and columns to the appropriate inputs
    let Some(per_input) = route_to_inputs(
        pairs,
        columns_needed,
        node,
        &input_column_sets,
        &input_schemas,
    )?
    else {
        return Ok(None);
    };

    let num_inputs = inputs.len();

    // Build per-input extraction projections and push them as far as possible
    // immediately. This is critical because map_children preserves cached schemas,
    // so if the TopDown pass later pushes a child further (changing its output
    // schema), the parent node's schema becomes stale.
    let mut new_inputs: Vec<LogicalPlan> = Vec::with_capacity(num_inputs);
    let is_union = matches!(node, LogicalPlan::Union(_));
    for (idx, input) in inputs.into_iter().enumerate() {
        if per_input[idx].pairs.is_empty() {
            new_inputs.push(input.clone());
        } else {
            // Merging into an input projection inlines the referenced columns'
            // definitions; bail out when that would duplicate a volatile
            // computation.
            if would_duplicate_volatile(
                per_input[idx].pairs.iter().map(|(expr, _)| expr),
                input,
            ) {
                return Ok(None);
            }
            let input_arc = Arc::new(input.clone());
            let target_schema = Arc::clone(input.schema());
            let proj = build_extraction_projection_impl(
                &per_input[idx].pairs,
                &per_input[idx].columns,
                &input_arc,
                target_schema.as_ref(),
            )?;
            // Verify all requested aliases appear in the projection's output.
            // A merge may deduplicate if the same expression already exists
            // under a different alias, leaving the requested alias missing.
            let proj_schema = proj.schema.as_ref();
            for (_expr, alias) in &per_input[idx].pairs {
                if !proj_schema.fields().iter().any(|f| f.name() == alias) {
                    return Ok(None);
                }
            }
            let proj_plan = LogicalPlan::Projection(proj);
            // Try to push the extraction projection further down within
            // this input (e.g., through Filter → existing extraction projection).
            // This ensures the input's output schema is stable and won't change
            // when the TopDown pass later visits children.
            let pushed = match try_push_input(&proj_plan, alias_generator)? {
                Some(pushed) => pushed,
                None => proj_plan,
            };
            if is_union {
                new_inputs.push(align_union_input(pushed, &per_input[idx])?);
            } else {
                new_inputs.push(pushed);
            }
        }
    }

    // Rebuild the node with new inputs
    let new_node = node.with_new_exprs(node.expressions(), new_inputs)?;

    // Safety check: verify all extracted aliases appear in the rebuilt
    // node's output schema. Nodes like Aggregate define their own output
    // and won't pass through extracted columns — bail out for those.
    let output_schema = new_node.schema();
    for (_expr, alias) in pairs {
        if !output_schema.fields().iter().any(|f| f.name() == alias) {
            return Ok(None);
        }
    }

    Ok(Some(new_node))
}

/// Projects one input of a `Union` to the extracted aliases, in pair order,
/// followed by the needed columns, in column order.
///
/// `Union` matches its inputs by position, not by name. A merge into an
/// existing projection appends the aliases after the existing expressions,
/// while a new projection puts them first. Without this, two inputs that take
/// different paths disagree on the position of each column, and the union
/// reads the alias of one input from an unrelated column of another input.
fn align_union_input(
    input: LogicalPlan,
    target: &ExtractionTarget,
) -> Result<LogicalPlan> {
    let exprs: Vec<Expr> = target
        .pairs
        .iter()
        .map(|(_, alias)| Expr::Column(Column::new_unqualified(alias)))
        .chain(target.columns.iter().map(|col| Expr::Column(col.clone())))
        .collect();
    // Skip the extra projection when the input already has this exact layout.
    let fields = input.schema().fields();
    let already_aligned = fields.len() == exprs.len()
        && target
            .pairs
            .iter()
            .map(|(_, alias)| alias.as_str())
            .chain(target.columns.iter().map(|col| col.name.as_str()))
            .zip(fields.iter())
            .all(|(name, field)| field.name() == name);
    if already_aligned {
        return Ok(input);
    }
    Projection::try_new(exprs, Arc::new(input)).map(LogicalPlan::Projection)
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::common_subexpr_eliminate::CommonSubexprEliminate;
    use crate::optimize_projections::OptimizeProjections;
    use crate::test::udfs::{PlacementTestUDF, get_field_like};
    use crate::test::*;
    use crate::{Optimizer, OptimizerContext};
    use datafusion_expr::expr::ScalarFunction;
    use datafusion_expr::{
        ScalarUDF, Volatility, col, lit, logical_plan::builder::LogicalPlanBuilder,
    };

    fn leaf_udf(expr: Expr, name: &str) -> Expr {
        Expr::ScalarFunction(ScalarFunction::new_udf(
            Arc::new(ScalarUDF::new_from_impl(
                PlacementTestUDF::new()
                    .with_placement(ExpressionPlacement::MoveTowardsLeafNodes),
            )),
            vec![expr, lit(name)],
        ))
    }

    /// A stand-in for `random()`: a volatile expression that must be evaluated
    /// exactly once per row.
    fn volatile_udf(expr: Expr) -> Expr {
        Expr::ScalarFunction(ScalarFunction::new_udf(
            Arc::new(ScalarUDF::new_from_impl(
                PlacementTestUDF::new()
                    .with_placement(ExpressionPlacement::KeepInPlace)
                    .with_volatility(Volatility::Volatile),
            )),
            vec![expr],
        ))
    }

    // =========================================================================
    // Combined optimization stage formatter
    // =========================================================================

    /// Runs all 4 optimization stages and returns a single formatted string.
    /// Stages that produce the same plan as the previous stage show
    /// "(same as <previous>)" to reduce noise.
    ///
    /// Stages:
    /// 1. **Original** - OptimizeProjections only (baseline)
    /// 2. **After Extraction** - + ExtractLeafExpressions
    /// 3. **After Pushdown** - + PushDownLeafProjections
    /// 4. **Optimized** - + final OptimizeProjections
    fn format_optimization_stages(plan: &LogicalPlan) -> Result<String> {
        let run = |rules: Vec<Arc<dyn OptimizerRule + Send + Sync>>| -> Result<String> {
            let ctx = OptimizerContext::new().with_max_passes(1);
            let optimizer = Optimizer::with_rules(rules);
            let optimized = optimizer.optimize(plan.clone(), &ctx, |_, _| {})?;
            Ok(format!("{optimized}"))
        };

        let original = run(vec![Arc::new(OptimizeProjections::new())])?;

        let after_extract = run(vec![
            Arc::new(OptimizeProjections::new()),
            Arc::new(ExtractLeafExpressions::new()),
        ])?;

        let after_pushdown = run(vec![
            Arc::new(OptimizeProjections::new()),
            Arc::new(ExtractLeafExpressions::new()),
            Arc::new(PushDownLeafProjections::new()),
        ])?;

        let optimized = run(vec![
            Arc::new(OptimizeProjections::new()),
            Arc::new(ExtractLeafExpressions::new()),
            Arc::new(PushDownLeafProjections::new()),
            Arc::new(OptimizeProjections::new()),
        ])?;

        let mut out = format!("## Original Plan\n{original}");

        out.push_str("\n\n## After Extraction\n");
        if after_extract == original {
            out.push_str("(same as original)");
        } else {
            out.push_str(&after_extract);
        }

        out.push_str("\n\n## After Pushdown\n");
        if after_pushdown == after_extract {
            out.push_str("(same as after extraction)");
        } else {
            out.push_str(&after_pushdown);
        }

        out.push_str("\n\n## Optimized\n");
        if optimized == after_pushdown {
            out.push_str("(same as after pushdown)");
        } else {
            out.push_str(&optimized);
        }

        Ok(out)
    }

    /// Assert all optimization stages for a plan in a single insta snapshot.
    macro_rules! assert_stages {
        ($plan:expr, @ $expected:literal $(,)?) => {{
            let result = format_optimization_stages(&$plan)?;
            insta::assert_snapshot!(result, @ $expected);
            Ok::<(), datafusion_common::DataFusionError>(())
        }};
    }

    #[test]
    fn test_extract_from_filter() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan.clone())
            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
            .select(vec![
                table_scan
                    .schema()
                    .index_of_column_by_name(None, "id")
                    .unwrap(),
            ])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: test.id
          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
            TableScan: test projection=[id, user]

        ## After Extraction
        Projection: test.id
          Projection: test.id, test.user
            Filter: __datafusion_extracted_1 = Utf8("active")
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
                TableScan: test projection=[id, user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        Projection: test.id
          Filter: __datafusion_extracted_1 = Utf8("active")
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id
              TableScan: test projection=[id, user]
        "#)
    }

    #[test]
    fn test_no_extraction_for_column() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(col("a").eq(lit(1)))?
            .build()?;

        assert_stages!(plan, @"
        ## Original Plan
        Filter: test.a = Int32(1)
          TableScan: test projection=[a, b, c]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        ")
    }

    #[test]
    fn test_extract_from_projection() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![leaf_udf(col("user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name"))
          TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    #[test]
    fn test_extract_from_projection_with_subexpression() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![
                leaf_udf(col("user"), "name")
                    .is_not_null()
                    .alias("has_name"),
            ])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name")) IS NOT NULL AS has_name
          TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    #[test]
    fn test_projection_no_extraction_for_column() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![col("a"), col("b")])?
            .build()?;

        assert_stages!(plan, @"
        ## Original Plan
        TableScan: test projection=[a, b]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        ")
    }

    #[test]
    fn test_filter_with_deduplication() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let field_access = leaf_udf(col("user"), "name");
        // Filter with the same expression used twice
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(
                field_access
                    .clone()
                    .is_not_null()
                    .and(field_access.is_null()),
            )?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(test.user, Utf8("name")) IS NOT NULL AND leaf_udf(test.user, Utf8("name")) IS NULL
          TableScan: test projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user
          Filter: __datafusion_extracted_1 IS NOT NULL AND __datafusion_extracted_1 IS NULL
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
              TableScan: test projection=[id, user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    #[test]
    fn test_already_leaf_expression_in_filter() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("user"), "name").eq(lit("test")))?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(test.user, Utf8("name")) = Utf8("test")
          TableScan: test projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user
          Filter: __datafusion_extracted_1 = Utf8("test")
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
              TableScan: test projection=[id, user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    #[test]
    fn test_extract_from_aggregate_group_by() -> Result<()> {
        use datafusion_expr::test::function_stub::count;

        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .aggregate(vec![leaf_udf(col("user"), "status")], vec![count(lit(1))])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Aggregate: groupBy=[[leaf_udf(test.user, Utf8("status"))]], aggr=[[COUNT(Int32(1))]]
          TableScan: test projection=[user]

        ## After Extraction
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("status")), COUNT(Int32(1))
          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.user
              TableScan: test projection=[user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("status")), COUNT(Int32(1))
          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1
              TableScan: test projection=[user]
        "#)
    }

    #[test]
    fn test_extract_from_aggregate_args() -> Result<()> {
        use datafusion_expr::test::function_stub::count;

        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .aggregate(
                vec![col("user")],
                vec![count(leaf_udf(col("user"), "value"))],
            )?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Aggregate: groupBy=[[test.user]], aggr=[[COUNT(leaf_udf(test.user, Utf8("value")))]]
          TableScan: test projection=[user]

        ## After Extraction
        Projection: test.user, COUNT(__datafusion_extracted_1) AS COUNT(leaf_udf(test.user,Utf8("value")))
          Aggregate: groupBy=[[test.user]], aggr=[[COUNT(__datafusion_extracted_1)]]
            Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user
              TableScan: test projection=[user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    #[test]
    fn test_projection_with_filter_combined() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
            .project(vec![leaf_udf(col("user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name"))
          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
            TableScan: test projection=[user]

        ## After Extraction
        Projection: leaf_udf(test.user, Utf8("name"))
          Projection: test.user
            Filter: __datafusion_extracted_1 = Utf8("active")
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.user
                TableScan: test projection=[user]

        ## After Pushdown
        Projection: __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))
          Projection: test.user, __datafusion_extracted_2
            Filter: __datafusion_extracted_1 = Utf8("active")
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
                TableScan: test projection=[user]

        ## Optimized
        Projection: __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))
          Filter: __datafusion_extracted_1 = Utf8("active")
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
              TableScan: test projection=[user]
        "#)
    }

    #[test]
    fn test_projection_preserves_alias() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![leaf_udf(col("user"), "name").alias("username")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name")) AS username
          TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Test: Projection with different field than Filter
    /// `SELECT id, s['label'] FROM t WHERE s['value'] > 150`
    /// Both `s['label']` and `s['value']` should be in a single extraction projection.
    #[test]
    fn test_projection_different_field_from_filter() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("user"), "value").gt(lit(150)))?
            .project(vec![col("user"), leaf_udf(col("user"), "label")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: test.user, leaf_udf(test.user, Utf8("label"))
          Filter: leaf_udf(test.user, Utf8("value")) > Int32(150)
            TableScan: test projection=[user]

        ## After Extraction
        Projection: test.user, leaf_udf(test.user, Utf8("label"))
          Projection: test.user
            Filter: __datafusion_extracted_1 > Int32(150)
              Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user
                TableScan: test projection=[user]

        ## After Pushdown
        Projection: test.user, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("label"))
          Projection: test.user, __datafusion_extracted_2
            Filter: __datafusion_extracted_1 > Int32(150)
              Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("label")) AS __datafusion_extracted_2
                TableScan: test projection=[user]

        ## Optimized
        Projection: test.user, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("label"))
          Filter: __datafusion_extracted_1 > Int32(150)
            Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user, leaf_udf(test.user, Utf8("label")) AS __datafusion_extracted_2
              TableScan: test projection=[user]
        "#)
    }

    #[test]
    fn test_projection_deduplication() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let field = leaf_udf(col("user"), "name");
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![field.clone(), field.clone().alias("name2")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name")), leaf_udf(test.user, Utf8("name")) AS name2
          TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    // =========================================================================
    // Additional tests for code coverage
    // =========================================================================

    /// Extractions push through Sort nodes to reach the TableScan.
    #[test]
    fn test_extract_through_sort() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .sort(vec![col("user").sort(true, true)])?
            .project(vec![leaf_udf(col("user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name"))
          Sort: test.user ASC NULLS FIRST
            TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name"))
          Sort: test.user ASC NULLS FIRST
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
              TableScan: test projection=[user]

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Extractions push through Limit nodes to reach the TableScan.
    #[test]
    fn test_extract_through_limit() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .limit(0, Some(10))?
            .project(vec![leaf_udf(col("user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name"))
          Limit: skip=0, fetch=10
            TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name"))
          Limit: skip=0, fetch=10
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
              TableScan: test projection=[user]

        ## Optimized
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name"))
          Limit: skip=0, fetch=10
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
              TableScan: test projection=[user]
        "#)
    }

    /// Aliased aggregate functions like count(...).alias("cnt") are handled.
    #[test]
    fn test_extract_from_aliased_aggregate() -> Result<()> {
        use datafusion_expr::test::function_stub::count;

        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .aggregate(
                vec![col("user")],
                vec![count(leaf_udf(col("user"), "value")).alias("cnt")],
            )?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Aggregate: groupBy=[[test.user]], aggr=[[COUNT(leaf_udf(test.user, Utf8("value"))) AS cnt]]
          TableScan: test projection=[user]

        ## After Extraction
        Aggregate: groupBy=[[test.user]], aggr=[[COUNT(__datafusion_extracted_1) AS cnt]]
          Projection: leaf_udf(test.user, Utf8("value")) AS __datafusion_extracted_1, test.user
            TableScan: test projection=[user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Aggregates with no MoveTowardsLeafNodes expressions return unchanged.
    #[test]
    fn test_aggregate_no_extraction() -> Result<()> {
        use datafusion_expr::test::function_stub::count;

        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .aggregate(vec![col("a")], vec![count(col("b"))])?
            .build()?;

        assert_stages!(plan, @"
        ## Original Plan
        Aggregate: groupBy=[[test.a]], aggr=[[COUNT(test.b)]]
          TableScan: test projection=[a, b]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        ")
    }

    /// Projections containing extracted expression aliases are skipped (already extracted).
    #[test]
    fn test_skip_extracted_projection() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![
                leaf_udf(col("user"), "name").alias("__datafusion_extracted_manual"),
                col("user"),
            ])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_manual, test.user
          TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Multiple extractions merge into a single extracted expression projection.
    #[test]
    fn test_merge_into_existing_extracted_projection() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
            .filter(leaf_udf(col("user"), "name").is_not_null())?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(test.user, Utf8("name")) IS NOT NULL
          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
            TableScan: test projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user
          Filter: __datafusion_extracted_1 IS NOT NULL
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
              Projection: test.id, test.user
                Filter: __datafusion_extracted_2 = Utf8("active")
                  Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.id, test.user
                    TableScan: test projection=[id, user]

        ## After Pushdown
        Projection: test.id, test.user
          Filter: __datafusion_extracted_1 IS NOT NULL
            Projection: test.id, test.user, __datafusion_extracted_1
              Filter: __datafusion_extracted_2 = Utf8("active")
                Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
                  TableScan: test projection=[id, user]

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Extractions push through passthrough projections (columns only).
    #[test]
    fn test_extract_through_passthrough_projection() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![col("user")])?
            .project(vec![leaf_udf(col("user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name"))
          TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Merging an extraction into an input projection inlines the definition of
    /// every column the extraction references. When that definition is volatile
    /// the inlined copy is an independent evaluation, so the extraction must be
    /// skipped and the plan left alone.
    #[test]
    fn test_no_merge_into_volatile_projection() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![volatile_udf(col("a")).alias("v")])?
            .project(vec![col("v"), leaf_udf(col("v"), "x")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: v, leaf_udf(v, Utf8("x"))
          Projection: keep_in_place_udf(test.a) AS v
            TableScan: test projection=[a]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Same guard for pass 1: extracting out of a `Filter` whose input
    /// projection defines the referenced column volatilely would make the
    /// predicate test a second, independent evaluation.
    #[test]
    fn test_no_extraction_from_filter_over_volatile_projection() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![volatile_udf(col("a")).alias("v")])?
            .filter(leaf_udf(col("v"), "x").eq(lit(1u32)))?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(v, Utf8("x")) = UInt32(1)
          Projection: keep_in_place_udf(test.a) AS v
            TableScan: test projection=[a]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Projections with aliased columns (nothing to extract) return unchanged.
    #[test]
    fn test_projection_early_return_no_extraction() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![col("a").alias("x"), col("b")])?
            .build()?;

        assert_stages!(plan, @"
        ## Original Plan
        Projection: test.a AS x, test.b
          TableScan: test projection=[a, b]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        ")
    }

    /// Projections with arithmetic expressions but no MoveTowardsLeafNodes return unchanged.
    #[test]
    fn test_projection_with_arithmetic_no_extraction() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![(col("a") + col("b")).alias("sum")])?
            .build()?;

        assert_stages!(plan, @"
        ## Original Plan
        Projection: test.a + test.b AS sum
          TableScan: test projection=[a, b]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        ")
    }

    /// Aggregate extractions merge into existing extracted projection created by Filter.
    #[test]
    fn test_aggregate_merge_into_extracted_projection() -> Result<()> {
        use datafusion_expr::test::function_stub::count;

        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
            .aggregate(vec![leaf_udf(col("user"), "name")], vec![count(lit(1))])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Aggregate: groupBy=[[leaf_udf(test.user, Utf8("name"))]], aggr=[[COUNT(Int32(1))]]
          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
            TableScan: test projection=[user]

        ## After Extraction
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name")), COUNT(Int32(1))
          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
              Projection: test.user
                Filter: __datafusion_extracted_2 = Utf8("active")
                  Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.user
                    TableScan: test projection=[user]

        ## After Pushdown
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name")), COUNT(Int32(1))
          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
            Projection: test.user, __datafusion_extracted_1
              Filter: __datafusion_extracted_2 = Utf8("active")
                Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
                  TableScan: test projection=[user]

        ## Optimized
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name")), COUNT(Int32(1))
          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
            Projection: __datafusion_extracted_1
              Filter: __datafusion_extracted_2 = Utf8("active")
                Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
                  TableScan: test projection=[user]
        "#)
    }

    /// Projection containing a MoveTowardsLeafNodes sub-expression above an
    /// Aggregate. The Aggregate blocks pushdown, so the extraction cannot move
    /// and the original projection is kept unchanged.
    #[test]
    fn test_projection_with_leaf_expr_above_aggregate() -> Result<()> {
        use datafusion_expr::test::function_stub::count;

        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .aggregate(vec![col("user")], vec![count(lit(1))])?
            .project(vec![
                leaf_udf(col("user"), "name")
                    .is_not_null()
                    .alias("has_name"),
                col("COUNT(Int32(1))"),
            ])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("name")) IS NOT NULL AS has_name, COUNT(Int32(1))
          Aggregate: groupBy=[[test.user]], aggr=[[COUNT(Int32(1))]]
            TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Merging adds new pass-through columns not in the existing extracted projection.
    #[test]
    fn test_merge_with_new_columns() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("a"), "x").eq(lit(1)))?
            .filter(leaf_udf(col("b"), "y").eq(lit(2)))?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(test.b, Utf8("y")) = Int32(2)
          Filter: leaf_udf(test.a, Utf8("x")) = Int32(1)
            TableScan: test projection=[a, b, c]

        ## After Extraction
        Projection: test.a, test.b, test.c
          Filter: __datafusion_extracted_1 = Int32(2)
            Projection: leaf_udf(test.b, Utf8("y")) AS __datafusion_extracted_1, test.a, test.b, test.c
              Projection: test.a, test.b, test.c
                Filter: __datafusion_extracted_2 = Int32(1)
                  Projection: leaf_udf(test.a, Utf8("x")) AS __datafusion_extracted_2, test.a, test.b, test.c
                    TableScan: test projection=[a, b, c]

        ## After Pushdown
        Projection: test.a, test.b, test.c
          Filter: __datafusion_extracted_1 = Int32(2)
            Projection: test.a, test.b, test.c, __datafusion_extracted_1
              Filter: __datafusion_extracted_2 = Int32(1)
                Projection: leaf_udf(test.a, Utf8("x")) AS __datafusion_extracted_2, test.a, test.b, test.c, leaf_udf(test.b, Utf8("y")) AS __datafusion_extracted_1
                  TableScan: test projection=[a, b, c]

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// A filter can name a column bare (`a`) while the projection below it
    /// outputs the qualified `test.a`. The optimizer leaves this shape when it
    /// removes the empty input of a `UNION ALL` (for example
    /// `... UNION ALL SELECT ... WHERE 1 = 2`). The merge must match the two, and not add a bare `a`
    /// beside `test.a`, which is an ambiguous schema.
    #[test]
    fn test_merge_bare_column_into_qualified_projection() -> Result<()> {
        let table_scan = test_table_scan()?;
        let projection = LogicalPlanBuilder::from(table_scan)
            .project(vec![
                col("test.a"),
                col("test.b"),
                (col("test.c") + lit(1)).alias("d"),
            ])?
            .build()?;
        let predicate =
            leaf_udf(Expr::Column(Column::new_unqualified("a")), "x").eq(lit(1));
        let plan = LogicalPlan::Filter(datafusion_expr::Filter::try_new(
            predicate,
            Arc::new(projection),
        )?);

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(a, Utf8("x")) = Int32(1)
          Projection: test.a, test.b, test.c + Int32(1) AS d
            TableScan: test projection=[a, b, c]

        ## After Extraction
        Projection: test.a, test.b, d
          Filter: __datafusion_extracted_1 = Int32(1)
            Projection: test.a, test.b, test.c + Int32(1) AS d, leaf_udf(a, Utf8("x")) AS __datafusion_extracted_1
              TableScan: test projection=[a, b, c]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// When the merge appends a needed column that the projection does not
    /// keep, it must append the input's qualified column (`test.b`), not the
    /// bare `b` that the caller asked for.
    #[test]
    fn test_merge_appends_qualified_column_for_bare_request() -> Result<()> {
        let projection = LogicalPlanBuilder::from(test_table_scan()?)
            .project(vec![col("test.a")])?
            .build()?;
        let target_schema = Arc::clone(projection.schema());
        let columns_needed: IndexSet<Column> =
            IndexSet::from([Column::new_unqualified("b")]);

        let merged = build_extraction_projection_impl(
            &[],
            &columns_needed,
            &Arc::new(projection),
            &target_schema,
        )?;

        assert_eq!(
            merged.expr,
            vec![
                Expr::Column(Column::new(Some("test"), "a")),
                Expr::Column(Column::new(Some("test"), "b")),
            ]
        );
        Ok(())
    }

    /// A projection can spell a pass-through column as a same-name alias
    /// (`test.a AS a`). Merging an extraction into it must treat that alias as
    /// the pass-through it is, and not add `test.a` beside the `a` it outputs,
    /// which is an ambiguous schema.
    #[test]
    fn test_merge_into_projection_with_same_name_alias() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![
                col("test.a").alias("a"),
                col("test.b").alias("b"),
                col("test.c").alias("c"),
            ])?
            .filter(leaf_udf(col("a"), "x").eq(lit(1)))?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(a, Utf8("x")) = Int32(1)
          Projection: test.a AS a, test.b AS b, test.c AS c
            TableScan: test projection=[a, b, c]

        ## After Extraction
        Projection: a, b, c
          Filter: __datafusion_extracted_1 = Int32(1)
            Projection: test.a AS a, test.b AS b, test.c AS c, leaf_udf(test.a, Utf8("x")) AS __datafusion_extracted_1
              TableScan: test projection=[a, b, c]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    // =========================================================================
    // Join extraction tests
    // =========================================================================

    /// Create a second table scan with struct field for join tests
    fn test_table_scan_with_struct_named(name: &str) -> Result<LogicalPlan> {
        use arrow::datatypes::Schema;
        let schema = Schema::new(test_table_scan_with_struct_fields());
        datafusion_expr::logical_plan::table_scan(Some(name), &schema, None)?.build()
    }

    /// Extraction from equijoin keys (`on` expressions).
    #[test]
    fn test_extract_from_join_on() -> Result<()> {
        use datafusion_expr::JoinType;

        let left = test_table_scan_with_struct()?;
        let right = test_table_scan_with_struct_named("right")?;

        let plan = LogicalPlanBuilder::from(left)
            .join_with_expr_keys(
                right,
                JoinType::Inner,
                (
                    vec![leaf_udf(col("user"), "id")],
                    vec![leaf_udf(col("user"), "id")],
                ),
                None,
            )?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Inner Join: leaf_udf(test.user, Utf8("id")) = leaf_udf(right.user, Utf8("id"))
          TableScan: test projection=[id, user]
          TableScan: right projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user, right.id, right.user
          Inner Join: __datafusion_extracted_1 = __datafusion_extracted_2
            Projection: leaf_udf(test.user, Utf8("id")) AS __datafusion_extracted_1, test.id, test.user
              TableScan: test projection=[id, user]
            Projection: leaf_udf(right.user, Utf8("id")) AS __datafusion_extracted_2, right.id, right.user
              TableScan: right projection=[id, user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Extraction from non-equi join filter.
    #[test]
    fn test_extract_from_join_filter() -> Result<()> {
        use datafusion_expr::JoinType;

        let left = test_table_scan_with_struct()?;
        let right = test_table_scan_with_struct_named("right")?;

        let plan = LogicalPlanBuilder::from(left)
            .join_on(
                right,
                JoinType::Inner,
                vec![
                    col("test.user").eq(col("right.user")),
                    leaf_udf(col("test.user"), "status").eq(lit("active")),
                ],
            )?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Inner Join:  Filter: test.user = right.user AND leaf_udf(test.user, Utf8("status")) = Utf8("active")
          TableScan: test projection=[id, user]
          TableScan: right projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user, right.id, right.user
          Inner Join:  Filter: test.user = right.user AND __datafusion_extracted_1 = Utf8("active")
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
              TableScan: test projection=[id, user]
            TableScan: right projection=[id, user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Extraction from both left and right sides of a join.
    #[test]
    fn test_extract_from_join_both_sides() -> Result<()> {
        use datafusion_expr::JoinType;

        let left = test_table_scan_with_struct()?;
        let right = test_table_scan_with_struct_named("right")?;

        let plan = LogicalPlanBuilder::from(left)
            .join_on(
                right,
                JoinType::Inner,
                vec![
                    col("test.user").eq(col("right.user")),
                    leaf_udf(col("test.user"), "status").eq(lit("active")),
                    leaf_udf(col("right.user"), "role").eq(lit("admin")),
                ],
            )?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Inner Join:  Filter: test.user = right.user AND leaf_udf(test.user, Utf8("status")) = Utf8("active") AND leaf_udf(right.user, Utf8("role")) = Utf8("admin")
          TableScan: test projection=[id, user]
          TableScan: right projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user, right.id, right.user
          Inner Join:  Filter: test.user = right.user AND __datafusion_extracted_1 = Utf8("active") AND __datafusion_extracted_2 = Utf8("admin")
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
              TableScan: test projection=[id, user]
            Projection: leaf_udf(right.user, Utf8("role")) AS __datafusion_extracted_2, right.id, right.user
              TableScan: right projection=[id, user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Join with no MoveTowardsLeafNodes expressions returns unchanged.
    #[test]
    fn test_extract_from_join_no_extraction() -> Result<()> {
        use datafusion_expr::JoinType;

        let left = test_table_scan()?;
        let right = test_table_scan_with_name("right")?;

        let plan = LogicalPlanBuilder::from(left)
            .join(right, JoinType::Inner, (vec!["a"], vec!["a"]), None)?
            .build()?;

        assert_stages!(plan, @"
        ## Original Plan
        Inner Join: test.a = right.a
          TableScan: test projection=[a, b, c]
          TableScan: right projection=[a, b, c]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        ")
    }

    /// Join followed by filter with extraction.
    #[test]
    fn test_extract_from_filter_above_join() -> Result<()> {
        use datafusion_expr::JoinType;

        let left = test_table_scan_with_struct()?;
        let right = test_table_scan_with_struct_named("right")?;

        let plan = LogicalPlanBuilder::from(left)
            .join_with_expr_keys(
                right,
                JoinType::Inner,
                (
                    vec![leaf_udf(col("user"), "id")],
                    vec![leaf_udf(col("user"), "id")],
                ),
                None,
            )?
            .filter(leaf_udf(col("test.user"), "status").eq(lit("active")))?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
          Inner Join: leaf_udf(test.user, Utf8("id")) = leaf_udf(right.user, Utf8("id"))
            TableScan: test projection=[id, user]
            TableScan: right projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user, right.id, right.user
          Filter: __datafusion_extracted_1 = Utf8("active")
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, right.id, right.user
              Projection: test.id, test.user, right.id, right.user
                Inner Join: __datafusion_extracted_2 = __datafusion_extracted_3
                  Projection: leaf_udf(test.user, Utf8("id")) AS __datafusion_extracted_2, test.id, test.user
                    TableScan: test projection=[id, user]
                  Projection: leaf_udf(right.user, Utf8("id")) AS __datafusion_extracted_3, right.id, right.user
                    TableScan: right projection=[id, user]

        ## After Pushdown
        Projection: test.id, test.user, right.id, right.user
          Filter: __datafusion_extracted_1 = Utf8("active")
            Projection: test.id, test.user, right.id, right.user, __datafusion_extracted_1
              Inner Join: __datafusion_extracted_2 = __datafusion_extracted_3
                Projection: leaf_udf(test.user, Utf8("id")) AS __datafusion_extracted_2, test.id, test.user, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1
                  TableScan: test projection=[id, user]
                Projection: leaf_udf(right.user, Utf8("id")) AS __datafusion_extracted_3, right.id, right.user
                  TableScan: right projection=[id, user]

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Extraction projection (get_field in SELECT) above a Join pushes into
    /// the correct input side.
    #[test]
    fn test_extract_projection_above_join() -> Result<()> {
        use datafusion_expr::JoinType;

        let left = test_table_scan_with_struct()?;
        let right = test_table_scan_with_struct_named("right")?;

        let plan = LogicalPlanBuilder::from(left)
            .join(right, JoinType::Inner, (vec!["id"], vec!["id"]), None)?
            .project(vec![
                leaf_udf(col("test.user"), "status"),
                leaf_udf(col("right.user"), "role"),
            ])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(test.user, Utf8("status")), leaf_udf(right.user, Utf8("role"))
          Inner Join: test.id = right.id
            TableScan: test projection=[id, user]
            TableScan: right projection=[id, user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("status")), __datafusion_extracted_2 AS leaf_udf(right.user,Utf8("role"))
          Inner Join: test.id = right.id
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
              TableScan: test projection=[id, user]
            Projection: leaf_udf(right.user, Utf8("role")) AS __datafusion_extracted_2, right.id, right.user
              TableScan: right projection=[id, user]

        ## Optimized
        Projection: __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("status")), __datafusion_extracted_2 AS leaf_udf(right.user,Utf8("role"))
          Inner Join: test.id = right.id
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id
              TableScan: test projection=[id, user]
            Projection: leaf_udf(right.user, Utf8("role")) AS __datafusion_extracted_2, right.id
              TableScan: right projection=[id, user]
        "#)
    }

    /// Join where both sides have same-named columns: a qualified reference
    /// to the right side must be routed to the right input, not the left.
    #[test]
    fn test_extract_from_join_qualified_right_side() -> Result<()> {
        use datafusion_expr::JoinType;

        let left = test_table_scan_with_struct()?;
        let right = test_table_scan_with_struct_named("right")?;

        // Filter references right.user explicitly — must route to right side
        let plan = LogicalPlanBuilder::from(left)
            .join_on(
                right,
                JoinType::Inner,
                vec![
                    col("test.id").eq(col("right.id")),
                    leaf_udf(col("right.user"), "status").eq(lit("active")),
                ],
            )?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Inner Join:  Filter: test.id = right.id AND leaf_udf(right.user, Utf8("status")) = Utf8("active")
          TableScan: test projection=[id, user]
          TableScan: right projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user, right.id, right.user
          Inner Join:  Filter: test.id = right.id AND __datafusion_extracted_1 = Utf8("active")
            TableScan: test projection=[id, user]
            Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, right.user
              TableScan: right projection=[id, user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// When both inputs contain the same unqualified column, an unqualified
    /// column reference is ambiguous and `find_owning_input` must return
    /// `None` rather than always returning 0 (the left side).
    #[test]
    fn test_find_owning_input_ambiguous_unqualified_column() {
        use std::collections::HashSet;

        // Simulate schema_columns output for two sides of a join where both
        // have a "user" column — each set contains the qualified and
        // unqualified form.
        let relation = "test".into();
        let left_cols: HashSet<ColumnReference> = [
            ColumnReference::new(Some(&relation), "user"),
            ColumnReference::new_unqualified("user"),
        ]
        .into_iter()
        .collect();

        let relation = "right".into();
        let right_cols: HashSet<ColumnReference> = [
            ColumnReference::new(Some(&relation), "user"),
            ColumnReference::new_unqualified("user"),
        ]
        .into_iter()
        .collect();

        let input_column_sets = vec![left_cols, right_cols];

        // Unqualified "user" matches both sets — must return None (ambiguous)
        let unqualified = Expr::Column(Column::new_unqualified("user"));
        assert_eq!(find_owning_input(&unqualified, &input_column_sets), None);

        // Qualified "right.user" matches only the right set — must return Some(1)
        let qualified_right = Expr::Column(Column::new(Some("right"), "user"));
        assert_eq!(
            find_owning_input(&qualified_right, &input_column_sets),
            Some(1)
        );

        // Qualified "test.user" matches only the left set — must return Some(0)
        let qualified_left = Expr::Column(Column::new(Some("test"), "user"));
        assert_eq!(
            find_owning_input(&qualified_left, &input_column_sets),
            Some(0)
        );
    }

    /// Two leaf_udf expressions from different sides of a Join in a Filter.
    /// Each is routed to its respective input side independently.
    #[test]
    fn test_extract_from_join_cross_input_expression() -> Result<()> {
        let left = test_table_scan_with_struct()?;
        let right = test_table_scan_with_struct_named("right")?;

        let plan = LogicalPlanBuilder::from(left)
            .join_on(
                right,
                datafusion_expr::JoinType::Inner,
                vec![col("test.id").eq(col("right.id"))],
            )?
            .filter(
                leaf_udf(col("test.user"), "status")
                    .eq(leaf_udf(col("right.user"), "status")),
            )?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(test.user, Utf8("status")) = leaf_udf(right.user, Utf8("status"))
          Inner Join:  Filter: test.id = right.id
            TableScan: test projection=[id, user]
            TableScan: right projection=[id, user]

        ## After Extraction
        Projection: test.id, test.user, right.id, right.user
          Filter: __datafusion_extracted_1 = __datafusion_extracted_2
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_2, test.id, test.user, right.id, right.user
              Inner Join:  Filter: test.id = right.id
                TableScan: test projection=[id, user]
                TableScan: right projection=[id, user]

        ## After Pushdown
        Projection: test.id, test.user, right.id, right.user
          Filter: __datafusion_extracted_1 = __datafusion_extracted_2
            Inner Join:  Filter: test.id = right.id
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
                TableScan: test projection=[id, user]
              Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_2, right.id, right.user
                TableScan: right projection=[id, user]

        ## Optimized
        (same as after pushdown)
        "#)
    }

    // =========================================================================
    // Column-rename through intermediate node tests
    // =========================================================================

    /// Projection with leaf expr above Filter above renaming Projection.
    #[test]
    fn test_extract_through_filter_with_column_rename() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![col("user").alias("x")])?
            .filter(col("x").is_not_null())?
            .project(vec![leaf_udf(col("x"), "a")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(x, Utf8("a"))
          Filter: x IS NOT NULL
            Projection: test.user AS x
              TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: __datafusion_extracted_1 AS leaf_udf(x,Utf8("a"))
          Filter: x IS NOT NULL
            Projection: test.user AS x, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
              TableScan: test projection=[user]

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Same as above but with a partial extraction (leaf + arithmetic).
    #[test]
    fn test_extract_partial_through_filter_with_column_rename() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![col("user").alias("x")])?
            .filter(col("x").is_not_null())?
            .project(vec![leaf_udf(col("x"), "a").is_not_null()])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(x, Utf8("a")) IS NOT NULL
          Filter: x IS NOT NULL
            Projection: test.user AS x
              TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: __datafusion_extracted_1 IS NOT NULL AS leaf_udf(x,Utf8("a")) IS NOT NULL
          Filter: x IS NOT NULL
            Projection: test.user AS x, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
              TableScan: test projection=[user]

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// Tests merge_into_extracted_projection path through a renaming projection.
    #[test]
    fn test_extract_from_filter_above_renaming_projection() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![col("user").alias("x")])?
            .filter(leaf_udf(col("x"), "a").eq(lit("active")))?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Filter: leaf_udf(x, Utf8("a")) = Utf8("active")
          Projection: test.user AS x
            TableScan: test projection=[user]

        ## After Extraction
        Projection: x
          Filter: __datafusion_extracted_1 = Utf8("active")
            Projection: test.user AS x, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
              TableScan: test projection=[user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// A projection that swaps two column names, below a filter and a struct
    /// field read. The merge must not resolve the parent's column references
    /// through the rename map: the input column `test.user` beside the output
    /// field `user` of the other rename gives an ambiguous schema (#25446).
    #[test]
    fn test_extract_above_projection_that_swaps_column_names() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .project(vec![col("user").alias("id"), col("id").alias("user")])?
            .filter(col("user").gt(lit(0u32)))?
            .project(vec![col("id"), col("user"), leaf_udf(col("id"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: id, user, leaf_udf(id, Utf8("name"))
          Filter: user > UInt32(0)
            Projection: test.user AS id, test.id AS user
              TableScan: test projection=[id, user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: id, user, __datafusion_extracted_1 AS leaf_udf(id,Utf8("name"))
          Filter: user > UInt32(0)
            Projection: test.user AS id, test.id AS user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
              TableScan: test projection=[id, user]

        ## Optimized
        (same as after pushdown)
        "#)
    }

    /// A projection that gives a computed column the name of its own input
    /// column. The extraction projection goes below the filter, which puts a
    /// column named `id` under the rename, so the two plans have the same set
    /// of field names. The recovery projection must stay, or the rename is lost
    /// and the query gives wrong results.
    #[test]
    fn test_extract_above_projection_that_redefines_column_name() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(col("id").gt(lit(0u32)))?
            .project(vec![(col("id") * lit(10u32)).alias("id"), col("user")])?
            .alias("sub")?
            .project(vec![col("sub.id"), leaf_udf(col("sub.user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: sub.id, leaf_udf(sub.user, Utf8("name"))
          SubqueryAlias: sub
            Projection: test.id * UInt32(10) AS id, test.user
              Filter: test.id > UInt32(0)
                TableScan: test projection=[id, user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: sub.id, __datafusion_extracted_1 AS leaf_udf(sub.user,Utf8("name"))
          SubqueryAlias: sub
            Projection: test.id * UInt32(10) AS id, test.user, __datafusion_extracted_1
              Filter: test.id > UInt32(0)
                Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
                  TableScan: test projection=[id, user]

        ## Optimized
        Projection: sub.id, __datafusion_extracted_1 AS leaf_udf(sub.user,Utf8("name"))
          SubqueryAlias: sub
            Projection: test.id * UInt32(10) AS id, __datafusion_extracted_1
              Filter: test.id > UInt32(0)
                Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id
                  TableScan: test projection=[id, user]
        "#)
    }

    // =========================================================================
    // SubqueryAlias extraction tests
    // =========================================================================

    /// Extraction projection pushes through SubqueryAlias.
    #[test]
    fn test_extract_through_subquery_alias() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .alias("sub")?
            .project(vec![leaf_udf(col("sub.user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(sub.user, Utf8("name"))
          SubqueryAlias: sub
            TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: __datafusion_extracted_1 AS leaf_udf(sub.user,Utf8("name"))
          SubqueryAlias: sub
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
              TableScan: test projection=[user]

        ## Optimized
        Projection: __datafusion_extracted_1 AS leaf_udf(sub.user,Utf8("name"))
          SubqueryAlias: sub
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
              TableScan: test projection=[user]
        "#)
    }

    /// Extraction projection pushes through SubqueryAlias + Filter.
    #[test]
    fn test_extract_through_subquery_alias_with_filter() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .alias("sub")?
            .filter(leaf_udf(col("sub.user"), "status").eq(lit("active")))?
            .project(vec![leaf_udf(col("sub.user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(sub.user, Utf8("name"))
          Filter: leaf_udf(sub.user, Utf8("status")) = Utf8("active")
            SubqueryAlias: sub
              TableScan: test projection=[user]

        ## After Extraction
        Projection: leaf_udf(sub.user, Utf8("name"))
          Projection: sub.user
            Filter: __datafusion_extracted_1 = Utf8("active")
              Projection: leaf_udf(sub.user, Utf8("status")) AS __datafusion_extracted_1, sub.user
                SubqueryAlias: sub
                  TableScan: test projection=[user]

        ## After Pushdown
        Projection: __datafusion_extracted_2 AS leaf_udf(sub.user,Utf8("name"))
          Projection: sub.user, __datafusion_extracted_2
            Filter: __datafusion_extracted_1 = Utf8("active")
              SubqueryAlias: sub
                Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.user
                  TableScan: test projection=[user]

        ## Optimized
        Projection: __datafusion_extracted_2 AS leaf_udf(sub.user,Utf8("name"))
          Filter: __datafusion_extracted_1 = Utf8("active")
            SubqueryAlias: sub
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
                TableScan: test projection=[user]
        "#)
    }

    /// Two layers of SubqueryAlias: extraction pushes through both.
    #[test]
    fn test_extract_through_nested_subquery_alias() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .alias("inner_sub")?
            .alias("outer_sub")?
            .project(vec![leaf_udf(col("outer_sub.user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: leaf_udf(outer_sub.user, Utf8("name"))
          SubqueryAlias: outer_sub
            SubqueryAlias: inner_sub
              TableScan: test projection=[user]

        ## After Extraction
        (same as original)

        ## After Pushdown
        Projection: __datafusion_extracted_1 AS leaf_udf(outer_sub.user,Utf8("name"))
          SubqueryAlias: outer_sub
            SubqueryAlias: inner_sub
              Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.user
                TableScan: test projection=[user]

        ## Optimized
        Projection: __datafusion_extracted_1 AS leaf_udf(outer_sub.user,Utf8("name"))
          SubqueryAlias: outer_sub
            SubqueryAlias: inner_sub
              Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1
                TableScan: test projection=[user]
        "#)
    }

    /// Plain columns through SubqueryAlias -- no extraction needed.
    #[test]
    fn test_subquery_alias_no_extraction() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .alias("sub")?
            .project(vec![col("sub.a"), col("sub.b")])?
            .build()?;

        assert_stages!(plan, @"
        ## Original Plan
        SubqueryAlias: sub
          TableScan: test projection=[a, b]

        ## After Extraction
        (same as original)

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        (same as after pushdown)
        ")
    }

    /// Two UDFs with the same `name()` but different concrete types should NOT be
    /// deduplicated -- they are semantically different expressions that happen to
    /// collide on `schema_name()`.
    #[test]
    fn test_different_udfs_same_schema_name_not_deduplicated() -> Result<()> {
        let udf_a = Arc::new(ScalarUDF::new_from_impl(
            PlacementTestUDF::new()
                .with_placement(ExpressionPlacement::MoveTowardsLeafNodes)
                .with_id(1),
        ));
        let udf_b = Arc::new(ScalarUDF::new_from_impl(
            PlacementTestUDF::new()
                .with_placement(ExpressionPlacement::MoveTowardsLeafNodes)
                .with_id(2),
        ));

        let expr_a = Expr::ScalarFunction(ScalarFunction::new_udf(
            udf_a,
            vec![col("user"), lit("field")],
        ));
        let expr_b = Expr::ScalarFunction(ScalarFunction::new_udf(
            udf_b,
            vec![col("user"), lit("field")],
        ));

        // Verify preconditions: same schema_name but different Expr
        assert_eq!(
            expr_a.schema_name().to_string(),
            expr_b.schema_name().to_string(),
            "Both expressions should have the same schema_name"
        );
        assert_ne!(
            expr_a, expr_b,
            "Expressions should NOT be equal (different UDF instances)"
        );

        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan.clone())
            .filter(expr_a.clone().eq(lit("a")).and(expr_b.clone().eq(lit("b"))))?
            .select(vec![
                table_scan
                    .schema()
                    .index_of_column_by_name(None, "id")
                    .unwrap(),
            ])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: test.id
          Filter: leaf_udf(test.user, Utf8("field")) = Utf8("a") AND leaf_udf(test.user, Utf8("field")) = Utf8("b")
            TableScan: test projection=[id, user]

        ## After Extraction
        Projection: test.id
          Projection: test.id, test.user
            Filter: __datafusion_extracted_1 = Utf8("a") AND __datafusion_extracted_2 = Utf8("b")
              Projection: leaf_udf(test.user, Utf8("field")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("field")) AS __datafusion_extracted_2, test.id, test.user
                TableScan: test projection=[id, user]

        ## After Pushdown
        (same as after extraction)

        ## Optimized
        Projection: test.id
          Filter: __datafusion_extracted_1 = Utf8("a") AND __datafusion_extracted_2 = Utf8("b")
            Projection: leaf_udf(test.user, Utf8("field")) AS __datafusion_extracted_1, leaf_udf(test.user, Utf8("field")) AS __datafusion_extracted_2, test.id
              TableScan: test projection=[id, user]
        "#)
    }

    // =========================================================================
    // Filter pushdown interaction tests
    // =========================================================================

    /// Extraction pushdown through a filter that already had its own
    /// `leaf_udf` extracted.
    #[test]
    fn test_extraction_pushdown_through_filter_with_extracted_predicate() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("user"), "status").eq(lit("active")))?
            .project(vec![col("id"), leaf_udf(col("user"), "name")])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: test.id, leaf_udf(test.user, Utf8("name"))
          Filter: leaf_udf(test.user, Utf8("status")) = Utf8("active")
            TableScan: test projection=[id, user]

        ## After Extraction
        Projection: test.id, leaf_udf(test.user, Utf8("name"))
          Projection: test.id, test.user
            Filter: __datafusion_extracted_1 = Utf8("active")
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
                TableScan: test projection=[id, user]

        ## After Pushdown
        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))
          Projection: test.id, test.user, __datafusion_extracted_2
            Filter: __datafusion_extracted_1 = Utf8("active")
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
                TableScan: test projection=[id, user]

        ## Optimized
        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name"))
          Filter: __datafusion_extracted_1 = Utf8("active")
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2
              TableScan: test projection=[id, user]
        "#)
    }

    /// Same expression in filter predicate and projection output.
    #[test]
    fn test_extraction_pushdown_same_expr_in_filter_and_projection() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let field_expr = leaf_udf(col("user"), "status");
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(field_expr.clone().gt(lit(5)))?
            .project(vec![col("id"), field_expr])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: test.id, leaf_udf(test.user, Utf8("status"))
          Filter: leaf_udf(test.user, Utf8("status")) > Int32(5)
            TableScan: test projection=[id, user]

        ## After Extraction
        Projection: test.id, leaf_udf(test.user, Utf8("status"))
          Projection: test.id, test.user
            Filter: __datafusion_extracted_1 > Int32(5)
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
                TableScan: test projection=[id, user]

        ## After Pushdown
        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("status"))
          Projection: test.id, test.user, __datafusion_extracted_2
            Filter: __datafusion_extracted_1 > Int32(5)
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2
                TableScan: test projection=[id, user]

        ## Optimized
        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("status"))
          Filter: __datafusion_extracted_1 > Int32(5)
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2
              TableScan: test projection=[id, user]
        "#)
    }

    /// Left join with a `leaf_udf` filter on the right side AND
    /// the projection also selects `leaf_udf` from the right side.
    #[test]
    fn test_left_join_with_filter_and_projection_extraction() -> Result<()> {
        use datafusion_expr::JoinType;

        let left = test_table_scan_with_struct()?;
        let right = test_table_scan_with_struct_named("right")?;

        let plan = LogicalPlanBuilder::from(left)
            .join_on(
                right,
                JoinType::Left,
                vec![
                    col("test.id").eq(col("right.id")),
                    leaf_udf(col("right.user"), "status").gt(lit(5)),
                ],
            )?
            .project(vec![
                col("test.id"),
                leaf_udf(col("test.user"), "name"),
                leaf_udf(col("right.user"), "status"),
            ])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: test.id, leaf_udf(test.user, Utf8("name")), leaf_udf(right.user, Utf8("status"))
          Left Join:  Filter: test.id = right.id AND leaf_udf(right.user, Utf8("status")) > Int32(5)
            TableScan: test projection=[id, user]
            TableScan: right projection=[id, user]

        ## After Extraction
        Projection: test.id, leaf_udf(test.user, Utf8("name")), leaf_udf(right.user, Utf8("status"))
          Projection: test.id, test.user, right.id, right.user
            Left Join:  Filter: test.id = right.id AND __datafusion_extracted_1 > Int32(5)
              TableScan: test projection=[id, user]
              Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, right.user
                TableScan: right projection=[id, user]

        ## After Pushdown
        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(right.user,Utf8("status"))
          Projection: test.id, test.user, right.id, right.user, __datafusion_extracted_2, __datafusion_extracted_3
            Left Join:  Filter: test.id = right.id AND __datafusion_extracted_1 > Int32(5)
              Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.id, test.user
                TableScan: test projection=[id, user]
              Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, right.user, leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_3
                TableScan: right projection=[id, user]

        ## Optimized
        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(right.user,Utf8("status"))
          Left Join:  Filter: test.id = right.id AND __datafusion_extracted_1 > Int32(5)
            Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, test.id
              TableScan: test projection=[id, user]
            Projection: leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_1, right.id, leaf_udf(right.user, Utf8("status")) AS __datafusion_extracted_3
              TableScan: right projection=[id, user]
        "#)
    }

    /// Extraction projection pushed through a filter whose predicate
    /// references a different extracted expression.
    #[test]
    fn test_pure_extraction_proj_push_through_filter() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("user"), "status").gt(lit(5)))?
            .project(vec![
                col("id"),
                leaf_udf(col("user"), "name"),
                leaf_udf(col("user"), "status"),
            ])?
            .build()?;

        assert_stages!(plan, @r#"
        ## Original Plan
        Projection: test.id, leaf_udf(test.user, Utf8("name")), leaf_udf(test.user, Utf8("status"))
          Filter: leaf_udf(test.user, Utf8("status")) > Int32(5)
            TableScan: test projection=[id, user]

        ## After Extraction
        Projection: test.id, leaf_udf(test.user, Utf8("name")), leaf_udf(test.user, Utf8("status"))
          Projection: test.id, test.user
            Filter: __datafusion_extracted_1 > Int32(5)
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user
                TableScan: test projection=[id, user]

        ## After Pushdown
        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(test.user,Utf8("status"))
          Projection: test.id, test.user, __datafusion_extracted_2, __datafusion_extracted_3
            Filter: __datafusion_extracted_1 > Int32(5)
              Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_3
                TableScan: test projection=[id, user]

        ## Optimized
        Projection: test.id, __datafusion_extracted_2 AS leaf_udf(test.user,Utf8("name")), __datafusion_extracted_3 AS leaf_udf(test.user,Utf8("status"))
          Filter: __datafusion_extracted_1 > Int32(5)
            Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_2, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_3
              TableScan: test projection=[id, user]
        "#)
    }

    /// When an extraction projection's __extracted alias references a column
    /// (e.g. `user`) that is NOT a standalone expression in the projection,
    /// the merge into the inner projection should still succeed.
    #[test]
    fn test_merge_extraction_into_projection_with_column_ref_inflation() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;

        // Inner projection (simulates a trimmed projection)
        let inner = LogicalPlanBuilder::from(table_scan)
            .project(vec![col("user"), col("id")])?
            .build()?;

        // Outer projection: __extracted alias + id (but NOT user as standalone).
        // The alias references `user` internally, inflating columns_needed.
        let plan = LogicalPlanBuilder::from(inner)
            .project(vec![
                leaf_udf(col("user"), "status")
                    .alias(format!("{EXTRACTED_EXPR_PREFIX}_1")),
                col("id"),
            ])?
            .build()?;

        // Run only PushDownLeafProjections
        let ctx = OptimizerContext::new().with_max_passes(1);
        let optimizer =
            Optimizer::with_rules(vec![Arc::new(PushDownLeafProjections::new())]);
        let result = optimizer.optimize(plan, &ctx, |_, _| {})?;

        // With the fix: merge succeeds → extraction merged into inner projection.
        // Without the fix: merge rejected → two separate projections remain.
        insta::assert_snapshot!(format!("{result}"), @r#"
        Projection: __datafusion_extracted_1, test.id
          Projection: test.user, test.id, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1
            TableScan: test
        "#);

        Ok(())
    }

    /// Regression test: the optimizer must not push extractions through
    /// `Unnest`.
    ///
    /// `try_push_into_inputs` routes extracted pairs to inputs by column name.
    /// `Unnest` can emit an output column with the same name as its input
    /// column but a different value/type (the unnested element), so name-based
    /// routing cannot tell the two apart. `try_push_into_inputs` therefore
    /// treats `Unnest` as a barrier and bails instead of pushing through it
    /// (see the `matches!(node, LogicalPlan::Unnest(_))` guard there).
    #[test]
    fn test_no_push_through_unnest() -> Result<()> {
        use arrow::datatypes::{DataType, Field, Schema};

        let schema = Schema::new(vec![
            Field::new("list_col", DataType::new_list(DataType::Int32, true), true),
            Field::new("other_col", DataType::Int32, true),
        ]);
        let table_scan =
            datafusion_expr::logical_plan::table_scan(Some("t"), &schema, None)?
                .build()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .unnest_column("list_col")?
            .filter(leaf_udf(col("list_col"), "x").eq(lit(1i32)))?
            .build()?;

        let ctx = OptimizerContext::new().with_max_passes(1);
        let optimizer = Optimizer::with_rules(vec![
            Arc::new(ExtractLeafExpressions::new()),
            Arc::new(PushDownLeafProjections::new()),
        ]);
        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;

        insta::assert_snapshot!(format!("{optimized}"), @r#"
        Projection: list_col, t.other_col
          Filter: __datafusion_extracted_1 = Int32(1)
            Projection: leaf_udf(list_col, Utf8("x")) AS __datafusion_extracted_1, list_col, t.other_col
              Unnest: lists[t.list_col|depth=1] structs[]
                TableScan: t
        "#);

        Ok(())
    }

    /// Regression test: a leaf expression used in **both** the filter and the
    /// projection, with the **bare base column** also projected, over a
    /// `SubqueryAlias` whose projection emits an **extra column the outer query
    /// never consumes** (`synth`).
    ///
    /// This reproduces a production failure where the leaf-pushdown passes drop
    /// the bare passthrough column from an intermediate schema, causing the
    /// subsequent `optimize_projections` run to fail with:
    /// `Schema error: No field named __datafusion_extracted_N`.
    ///
    /// Equivalent SQL:
    /// ```sql
    /// CREATE VIEW v AS SELECT user, id, id + 1 AS synth FROM test;
    /// SELECT user['status'], user, id FROM v WHERE user['status'] IS NOT NULL;
    /// ```
    #[test]
    fn test_subquery_alias_with_unconsumed_column() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;

        // This is the plan shape *after* `push_down_filter` has run: it pushes
        // the `leaf_udf(...)` filter down through the `SubqueryAlias` and below
        // the view's inner projection. The filter and the outer projection now
        // each contain the same leaf expression but are separated by the
        // `SubqueryAlias`, so they extract into two *independent* aliases
        // (`__datafusion_extracted_1` from the filter, `__datafusion_extracted_2`
        // from the projection) instead of deduplicating into one.
        //
        // The view projects an extra `synth` column the outer query never
        // consumes — without it the bug does not manifest.
        let inner = LogicalPlanBuilder::from(table_scan)
            .filter(leaf_udf(col("user"), "status").is_not_null())?
            .project(vec![
                col("user"),
                col("id"),
                (col("id") + lit(1u32)).alias("synth"),
            ])?
            .alias("v")?
            .build()?;

        // Outer projection: leaf expr + the bare base column + id.
        let plan = LogicalPlanBuilder::from(inner)
            .project(vec![
                leaf_udf(col("v.user"), "status"),
                col("v.user"),
                col("v.id"),
            ])?
            .build()?;

        // Run the leaf-pushdown passes followed by `optimize_projections`,
        // exactly as the default optimizer schedules them. `optimize_projections`
        // is what prunes the unused `synth` column and validates the plan; if the
        // leaf passes drop the bare `v.user` passthrough column it fails with
        // `Schema error: No field named __datafusion_extracted_N`.
        let ctx = OptimizerContext::new();
        let optimizer = Optimizer::with_rules(vec![
            Arc::new(ExtractLeafExpressions::new()),
            Arc::new(PushDownLeafProjections::new()),
            Arc::new(OptimizeProjections::new()),
        ]);
        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;

        // The bare `test.user` passthrough column is preserved and the view's
        // output schema (`user`, `id`, `__datafusion_extracted_2`) is restored
        // by a recovery projection, so `optimize_projections` succeeds.
        insta::assert_snapshot!(format!("{optimized}"), @r#"
        Projection: __datafusion_extracted_2 AS leaf_udf(v.user,Utf8("status")), v.user, v.id
          SubqueryAlias: v
            Projection: test.user, test.id, __datafusion_extracted_2
              Filter: __datafusion_extracted_1 IS NOT NULL
                Projection: leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_1, test.id, test.user, leaf_udf(test.user, Utf8("status")) AS __datafusion_extracted_2
                  TableScan: test projection=[id, user]
        "#);

        Ok(())
    }

    /// Reproduces a schema-ambiguity failure in `PushDownLeafProjections`.
    ///
    /// ```text
    /// Optimizer rule 'push_down_leaf_projections' failed
    /// caused by
    /// Schema error: Schema contains qualified field name p.__datafusion_extracted_1
    /// and unqualified field name __datafusion_extracted_1 which would be ambiguous
    /// ```
    ///
    /// Four ingredients, each necessary:
    ///
    /// 1. a `SubqueryAlias` over each join input (bare aliased table scans pass),
    /// 2. a **left** join (an inner join passes),
    /// 3. a leaf expression on *each* side, so extraction pushes into both inputs,
    /// 4. an aggregate above the join (a projection passes).
    ///
    /// With extraction pushed inside both aliases, the left input re-exposes its
    /// alias qualified as `p.__datafusion_extracted_1`, while the recovery
    /// projection above the join rebuilds the same reference unqualified via
    /// `Column::new_unqualified`, so one schema ends up holding both spellings.
    ///
    /// Equivalent SQL:
    /// ```sql
    /// CREATE VIEW p AS SELECT user, id FROM test;
    /// CREATE VIEW c AS SELECT user, id FROM other;
    /// SELECT p.user['a'], count(1)
    /// FROM p LEFT JOIN c ON p.id = c.id
    /// WHERE c.user['t'] IS NOT NULL
    /// GROUP BY 1;
    /// ```
    #[test]
    fn test_leaf_expr_on_both_sides_of_left_join_under_aggregate() -> Result<()> {
        use datafusion_expr::JoinType;
        use datafusion_expr::test::function_stub::count;

        fn view(name: &str, table: LogicalPlan) -> Result<LogicalPlan> {
            LogicalPlanBuilder::from(table)
                .project(vec![col("user"), col("id")])?
                .alias(name)?
                .build()
        }

        let left = view("p", test_table_scan_with_struct()?)?;
        let right = view("c", test_table_scan_with_struct_named("right")?)?;

        let plan = LogicalPlanBuilder::from(left)
            .join(right, JoinType::Left, (vec!["id"], vec!["id"]), None)?
            .filter(leaf_udf(col("c.user"), "t").is_not_null())?
            .aggregate(vec![leaf_udf(col("p.user"), "a")], vec![count(lit(1))])?
            .build()?;

        // The full optimizer, not `format_optimization_stages`: the triggering
        // shape (`p.__datafusion_extracted_1 AS __datafusion_extracted_1`) only
        // appears once projection merging has collapsed the recovery projection
        // over the `SubqueryAlias`.
        let ctx = OptimizerContext::new();
        let optimized = Optimizer::new().optimize(plan, &ctx, |_, _| {})?;
        insta::assert_snapshot!(format!("{optimized}"), @r#"
        Projection: __datafusion_extracted_1 AS leaf_udf(p.user,Utf8("a")), COUNT(Int32(1))
          Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
            Projection: p.__datafusion_extracted_1 AS __datafusion_extracted_1
              Inner Join: p.id = c.id
                SubqueryAlias: p
                  Projection: test.id, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
                    TableScan: test projection=[id, user]
                SubqueryAlias: c
                  Projection: right.id
                    Filter: __datafusion_extracted_2 IS NOT NULL
                      Projection: right.id, leaf_udf(right.user, Utf8("t")) AS __datafusion_extracted_2
                        TableScan: right projection=[id, user]
        "#);
        Ok(())
    }

    /// Pre-existing `__datafusion_extracted_N` aliases must advance the alias
    /// generator even when they live inside a subquery plan, since extraction
    /// descends into subqueries and would otherwise reuse the same alias.
    #[test]
    fn test_advance_generator_past_alias_in_subquery() -> Result<()> {
        use datafusion_expr::in_subquery;

        let subquery = LogicalPlanBuilder::from(test_table_scan_with_struct()?)
            .project(vec![
                leaf_udf(col("user"), "name").alias("__datafusion_extracted_7"),
            ])?
            .build()?;
        let plan = LogicalPlanBuilder::from(test_table_scan_with_struct_named("outer")?)
            .filter(in_subquery(col("id"), Arc::new(subquery)))?
            .build()?;

        let alias_generator = AliasGenerator::new();
        advance_generator_past_existing(&plan, &alias_generator)?;

        assert_eq!(
            alias_generator.next(EXTRACTED_EXPR_PREFIX),
            "__datafusion_extracted_8"
        );

        Ok(())
    }

    /// Regression test for issue #23655: `f(c)['a'], f(c)['b']` on a
    /// struct-returning UDF must evaluate `f(c)` once, not once per field access.
    ///
    /// `keep_in_place_udf` / `get_field_like` model `f(c)` and `f(c)[key]` — the
    /// crate can't depend on the real `get_field` (see [`get_field_like`]).
    /// Without the guard, `PushDownLeafProjections` re-inlines the shared UDF that
    /// `CommonSubexprEliminate` hoisted and the passes oscillate to a double
    /// evaluation.
    #[test]
    fn test_struct_returning_udf_evaluated_once() -> Result<()> {
        let udf = ScalarUDF::new_from_impl(
            PlacementTestUDF::new().with_placement(ExpressionPlacement::KeepInPlace),
        );
        let f_c = udf.call(vec![col("c")]);
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .project(vec![
                get_field_like(f_c.clone(), "a"),
                get_field_like(f_c, "b"),
            ])?
            .build()?;

        // The full four-rule interaction, default pass budget so any oscillation
        // would surface here as a double evaluation.
        let ctx = OptimizerContext::new();
        let optimizer = Optimizer::with_rules(vec![
            Arc::new(CommonSubexprEliminate::new()),
            Arc::new(ExtractLeafExpressions::new()),
            Arc::new(PushDownLeafProjections::new()),
            Arc::new(OptimizeProjections::new()),
        ]);
        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;

        // Every field access reads the UDF back through `__common_expr_1`; none
        // wraps a fresh `keep_in_place_udf(...)` call. Asserted explicitly so a
        // careless snapshot re-accept can't quietly restore the double evaluation.
        let formatted = format!("{optimized}");
        assert_eq!(
            formatted
                .matches("get_field_like(keep_in_place_udf")
                .count(),
            0,
            "struct-returning UDF must not be re-evaluated inside a field access; got:\n{formatted}"
        );

        insta::assert_snapshot!(formatted, @r#"
        Projection: get_field_like(__common_expr_1 AS keep_in_place_udf(test.c), Utf8("a")), get_field_like(__common_expr_1 AS keep_in_place_udf(test.c), Utf8("b"))
          Projection: keep_in_place_udf(test.c) AS __common_expr_1
            TableScan: test projection=[c]
        "#);

        Ok(())
    }

    #[test]
    fn test_struct_returning_udf_evaluated_once_with_bare_reference() -> Result<()> {
        // Regression for the `SELECT f(c)['a'], f(c)` shape: the struct UDF is
        // referenced once through a field access and once as a bare value. The
        // bare reference is tracked in `columns_needed`, not `extraction_pairs`,
        // so a guard that counted only pairs would re-inline `f(c)` and evaluate
        // it twice (#23655).
        let udf = ScalarUDF::new_from_impl(
            PlacementTestUDF::new().with_placement(ExpressionPlacement::KeepInPlace),
        );
        let f_c = udf.call(vec![col("c")]);
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .project(vec![get_field_like(f_c.clone(), "a"), f_c])?
            .build()?;

        let ctx = OptimizerContext::new();
        let optimizer = Optimizer::with_rules(vec![
            Arc::new(CommonSubexprEliminate::new()),
            Arc::new(ExtractLeafExpressions::new()),
            Arc::new(PushDownLeafProjections::new()),
            Arc::new(OptimizeProjections::new()),
        ]);
        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;

        // The field access must read the UDF back through `__common_expr_1`, not
        // wrap a fresh `keep_in_place_udf(...)` call. Asserted explicitly so a
        // careless snapshot re-accept can't quietly restore the double evaluation.
        let formatted = format!("{optimized}");
        assert_eq!(
            formatted
                .matches("get_field_like(keep_in_place_udf")
                .count(),
            0,
            "struct-returning UDF must not be re-evaluated inside a field access; got:\n{formatted}"
        );

        insta::assert_snapshot!(formatted, @r#"
        Projection: get_field_like(__common_expr_1 AS keep_in_place_udf(test.c), Utf8("a")), __common_expr_1 AS keep_in_place_udf(test.c)
          Projection: keep_in_place_udf(test.c) AS __common_expr_1
            TableScan: test projection=[c]
        "#);

        Ok(())
    }

    /// `passthrough_column` tells `split_and_push_projection` which projection
    /// expressions the input already produces. A renaming alias (`test.a AS b`)
    /// does not qualify: it is a new output column. If the function accepted
    /// it, the rename would count as captured, and the recovery projection
    /// that restores the name would be dropped.
    #[test]
    fn test_passthrough_column_rejects_renaming_alias() {
        // A bare column is a pass-through.
        let bare = Expr::Column(Column::new(Some("test"), "a"));
        assert_eq!(
            passthrough_column(&bare).map(|c| c.flat_name()),
            Some("test.a".to_string())
        );

        // `test.a AS a` keeps the name, so it is a pass-through.
        let trivial_rename = Expr::Column(Column::new(Some("test"), "a")).alias("a");
        assert_eq!(
            passthrough_column(&trivial_rename).map(|c| c.flat_name()),
            Some("test.a".to_string())
        );

        // `test.a AS b` changes the name, so it is not a pass-through.
        let renaming = Expr::Column(Column::new(Some("test"), "a")).alias("b");
        assert_eq!(passthrough_column(&renaming), None);

        // An alias over anything other than a column is not a pass-through.
        let not_a_column = lit(1).alias("a");
        assert_eq!(passthrough_column(&not_a_column), None);
    }

    /// `is_pure_extraction_projection` decides if a merged projection can go
    /// down one more level. It must accept only `__datafusion_extracted`
    /// aliases and plain columns, and only with at least one extraction. An
    /// alias with a different prefix must not count: a second push would
    /// re-extract the expression under a new alias that the parent cannot
    /// resolve.
    #[test]
    fn test_is_pure_extraction_projection() -> Result<()> {
        let scan = test_table_scan_with_struct()?;

        // Columns only: nothing was extracted.
        let columns_only = LogicalPlanBuilder::from(scan.clone())
            .project(vec![col("id"), col("user")])?
            .build()?;
        assert!(!is_pure_extraction_projection(&columns_only.expressions()));

        // One extraction alias and one pass-through column.
        let pure = LogicalPlanBuilder::from(scan.clone())
            .project(vec![
                leaf_udf(col("user"), "status").alias("__datafusion_extracted_1"),
                col("id"),
            ])?
            .build()?;
        assert!(is_pure_extraction_projection(&pure.expressions()));

        // The same shape under a `CommonSubexprEliminate` alias is not an
        // extraction projection.
        let common_expr = LogicalPlanBuilder::from(scan.clone())
            .project(vec![
                leaf_udf(col("user"), "status").alias("__common_expr_1"),
                col("id"),
            ])?
            .build()?;
        assert!(!is_pure_extraction_projection(&common_expr.expressions()));

        // A bare expression is never allowed.
        let bare_expr = LogicalPlanBuilder::from(scan)
            .project(vec![leaf_udf(col("user"), "status"), col("id")])?
            .build()?;
        assert!(!is_pure_extraction_projection(&bare_expr.expressions()));

        Ok(())
    }

    /// A non-volatile `KeepInPlace` expression: the kind that
    /// `CommonSubexprEliminate` hoists into a column so it runs one time.
    fn keep_in_place_udf(expr: Expr) -> Expr {
        Expr::ScalarFunction(ScalarFunction::new_udf(
            Arc::new(ScalarUDF::new_from_impl(
                PlacementTestUDF::new().with_placement(ExpressionPlacement::KeepInPlace),
            )),
            vec![expr],
        ))
    }

    /// `merge_would_duplicate_kept_expr` must block a merge only when it would
    /// inline one `KeepInPlace` definition into more than one reference site.
    /// It must count reference sites for `KeepInPlace` columns alone: a plain
    /// column is cheap to duplicate, and a merge that touches only plain
    /// columns must still go ahead.
    #[test]
    fn test_merge_would_duplicate_kept_expr_counts_only_kept_columns() -> Result<()> {
        let scan = test_table_scan_with_struct()?;
        // `k` holds a `KeepInPlace` definition. `id` is a plain column.
        let child = Projection::try_new(
            vec![keep_in_place_udf(col("user")).alias("k"), col("id")],
            Arc::new(scan),
        )?;
        let no_columns = IndexSet::new();

        // One reference site: the merge inlines one copy, so it is free.
        let one_site = vec![(
            get_field_like(col("k"), "a"),
            "__datafusion_extracted_1".to_string(),
        )];
        assert!(!merge_would_duplicate_kept_expr(
            &one_site,
            &no_columns,
            &child
        ));

        // Two reference sites: the merge would evaluate `k` two times.
        let two_sites = vec![
            (
                get_field_like(col("k"), "a"),
                "__datafusion_extracted_1".to_string(),
            ),
            (
                get_field_like(col("k"), "b"),
                "__datafusion_extracted_2".to_string(),
            ),
        ];
        assert!(merge_would_duplicate_kept_expr(
            &two_sites,
            &no_columns,
            &child
        ));

        // A pass-through reference to `k` is a second site too (#23655).
        let kept_column: IndexSet<Column> =
            std::iter::once(Column::new_unqualified("k")).collect();
        assert!(merge_would_duplicate_kept_expr(
            &one_site,
            &kept_column,
            &child
        ));

        // Two sites that reference the plain column `id` are cheap to
        // duplicate, so the merge must still go ahead.
        let plain_column_sites = vec![
            (
                get_field_like(col("id"), "a"),
                "__datafusion_extracted_1".to_string(),
            ),
            (
                get_field_like(col("id"), "b"),
                "__datafusion_extracted_2".to_string(),
            ),
        ];
        assert!(!merge_would_duplicate_kept_expr(
            &plain_column_sites,
            &no_columns,
            &child
        ));
        Ok(())
    }

    /// Regression test for <https://github.com/apache/datafusion/issues/25414>.
    ///
    /// `(- test.id) AS id` computes a new value under the same name as its input
    /// column `test.id`. Pushing the extraction below that projection makes
    /// `test.id` visible again under the name `id`. The recovery projection must
    /// stay, or the computed column is silently replaced by the table column.
    ///
    /// The two leaf rules run alone here, in their production order.
    /// `optimize_projections` merges the two projections into one and hides the
    /// shape, and it only runs after both leaf rules.
    #[test]
    fn test_recovery_kept_for_same_name_computed_column() -> Result<()> {
        let table_scan = test_table_scan_with_struct()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(col("id").gt(lit(0u32)))?
            .project(vec![
                Expr::Negative(Box::new(col("id"))).alias("id"),
                col("user"),
            ])?
            .project(vec![col("id"), leaf_udf(col("user"), "name")])?
            .build()?;

        let ctx = OptimizerContext::new().with_max_passes(1);
        let optimizer = Optimizer::with_rules(vec![
            Arc::new(ExtractLeafExpressions::new()),
            Arc::new(PushDownLeafProjections::new()),
        ]);
        let optimized = optimizer.optimize(plan, &ctx, |_, _| {})?;

        insta::assert_snapshot!(format!("{optimized}"), @r#"
        Projection: id, __datafusion_extracted_1 AS leaf_udf(test.user,Utf8("name"))
          Projection: (- test.id) AS id, test.user, __datafusion_extracted_1
            Filter: test.id > UInt32(0)
              Projection: leaf_udf(test.user, Utf8("name")) AS __datafusion_extracted_1, test.id, test.user
                TableScan: test
        "#);
        Ok(())
    }
}