datafusion-physical-plan 56.0.0

Physical (ExecutionPlan) implementations for DataFusion query engine
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
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
// 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

use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, ready};

use datafusion_physical_expr::projection::{ProjectionRef, combine_projections};
use itertools::Itertools;

use super::{
    ColumnStatistics, DisplayAs, ExecutionPlanProperties, PlanProperties,
    RecordBatchStream, SendableRecordBatchStream, Statistics,
};
use crate::coalesce::{LimitedBatchCoalescer, PushBatchStatus};
use crate::common::can_project;
use crate::execution_plan::CardinalityEffect;
use crate::filter_pushdown::{
    ChildFilterDescription, ChildPushdownResult, FilterDescription, FilterPushdownPhase,
    FilterPushdownPropagation, FilterRemapper, PushedDown,
};
use crate::limit::LocalLimitExec;
use crate::metrics::{MetricBuilder, MetricType};
use crate::projection::{
    EmbeddedProjection, ProjectionExec, ProjectionExpr, make_with_child,
    try_embed_projection, update_expr,
};
use crate::statistics::{ChildStats, StatisticsArgs, StatisticsContext};
use crate::stream::EmptyRecordBatchStream;
use crate::{ChildrenPropertiesMode, ReplaceChildrenOptions, validate_child_count};
use crate::{
    DisplayFormatType, ExecutionPlan,
    metrics::{BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet, RatioMetrics},
};

use arrow::compute::filter_record_batch;
use arrow::datatypes::{DataType, SchemaRef};
use arrow::record_batch::RecordBatch;
use datafusion_common::cast::as_boolean_array;
use datafusion_common::config::ConfigOptions;
use datafusion_common::stats::Precision;
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::{
    DataFusionError, Result, ScalarValue, internal_datafusion_err, internal_err,
    plan_err, project_schema,
};
use datafusion_execution::TaskContext;
use datafusion_expr::Operator;
use datafusion_physical_expr::equivalence::ProjectionMapping;
use datafusion_physical_expr::expressions::{
    BinaryExpr, Column, InListExpr, IsNotNullExpr, IsNullExpr, LikeExpr, Literal, lit,
};
use datafusion_physical_expr::intervals::utils::check_support;
use datafusion_physical_expr::utils::collect_columns;
use datafusion_physical_expr::{
    AcrossPartitions, AnalysisContext, ConstExpr, ExprBoundaries, PhysicalExpr, analyze,
    conjunction, split_conjunction,
};

use datafusion_physical_expr_common::physical_expr::fmt_sql;
use futures::stream::{Stream, StreamExt};
use log::trace;

const FILTER_EXEC_DEFAULT_SELECTIVITY: u8 = 20;
const FILTER_EXEC_DEFAULT_BATCH_SIZE: usize = 8192;

/// FilterExec evaluates a boolean predicate against all input batches to determine which rows to
/// include in its output batches.
#[derive(Debug, Clone)]
pub struct FilterExec {
    /// The expression to filter on. This expression must evaluate to a boolean value.
    predicate: Arc<dyn PhysicalExpr>,
    /// The input plan
    input: Arc<dyn ExecutionPlan>,
    /// Execution metrics
    metrics: ExecutionPlanMetricsSet,
    /// Selectivity for statistics. 0 = no rows, 100 = all rows
    default_selectivity: u8,
    /// Properties equivalence properties, partitioning, etc.
    cache: Arc<PlanProperties>,
    /// The projection indices of the columns in the output schema of join
    projection: Option<ProjectionRef>,
    /// Target batch size for output batches
    batch_size: usize,
    /// Number of rows to fetch
    fetch: Option<usize>,
}

/// Builder for [`FilterExec`] to set optional parameters
pub struct FilterExecBuilder {
    predicate: Arc<dyn PhysicalExpr>,
    input: Arc<dyn ExecutionPlan>,
    projection: Option<ProjectionRef>,
    default_selectivity: u8,
    batch_size: usize,
    fetch: Option<usize>,
}

impl FilterExecBuilder {
    /// Create a new builder with required parameters (predicate and input)
    pub fn new(predicate: Arc<dyn PhysicalExpr>, input: Arc<dyn ExecutionPlan>) -> Self {
        Self {
            predicate,
            input,
            projection: None,
            default_selectivity: FILTER_EXEC_DEFAULT_SELECTIVITY,
            batch_size: FILTER_EXEC_DEFAULT_BATCH_SIZE,
            fetch: None,
        }
    }

    /// Set the input execution plan
    pub fn with_input(mut self, input: Arc<dyn ExecutionPlan>) -> Self {
        self.input = input;
        self
    }

    /// Set the predicate expression
    pub fn with_predicate(mut self, predicate: Arc<dyn PhysicalExpr>) -> Self {
        self.predicate = predicate;
        self
    }

    /// Set the projection, composing with any existing projection.
    ///
    /// If a projection is already set, the new projection indices are mapped
    /// through the existing projection. For example, if the current projection
    /// is `[0, 2, 3]` and `apply_projection(Some(vec![0, 2]))` is called, the
    /// resulting projection will be `[0, 3]` (indices 0 and 2 of `[0, 2, 3]`).
    ///
    /// If no projection is currently set, the new projection is used directly.
    /// If `None` is passed, the projection is cleared.
    pub fn apply_projection(self, projection: Option<Vec<usize>>) -> Result<Self> {
        let projection = projection.map(Into::into);
        self.apply_projection_by_ref(projection.as_ref())
    }

    /// The same as [`Self::apply_projection`] but takes projection shared reference.
    pub fn apply_projection_by_ref(
        mut self,
        projection: Option<&ProjectionRef>,
    ) -> Result<Self> {
        // Check if the projection is valid against current output schema
        can_project(&self.input.schema(), projection.map(AsRef::as_ref))?;
        self.projection = combine_projections(projection, self.projection.as_ref())?;
        Ok(self)
    }

    /// Set the default selectivity
    pub fn with_default_selectivity(mut self, default_selectivity: u8) -> Self {
        self.default_selectivity = default_selectivity;
        self
    }

    /// Set the batch size
    pub fn with_batch_size(mut self, batch_size: usize) -> Self {
        self.batch_size = batch_size;
        self
    }

    /// Set the fetch limit
    pub fn with_fetch(mut self, fetch: Option<usize>) -> Self {
        self.fetch = fetch;
        self
    }

    /// Build the FilterExec, computing properties once with all configured parameters
    pub fn build(self) -> Result<FilterExec> {
        if self.batch_size == 0 {
            return plan_err!("FilterExec: batch_size must be greater than 0");
        }

        // Validate predicate type
        match self.predicate.data_type(self.input.schema().as_ref())? {
            DataType::Boolean => {}
            other => {
                return plan_err!(
                    "Filter predicate must return BOOLEAN values, got {other:?}"
                );
            }
        }

        // Validate selectivity
        if self.default_selectivity > 100 {
            return plan_err!(
                "Default filter selectivity value needs to be less than or equal to 100"
            );
        }

        // Validate projection if provided
        can_project(&self.input.schema(), self.projection.as_deref())?;

        // Compute properties once with all parameters
        let cache = FilterExec::compute_properties(
            &self.input,
            &self.predicate,
            self.default_selectivity,
            self.projection.as_deref(),
        )?;

        Ok(FilterExec {
            predicate: self.predicate,
            input: self.input,
            metrics: ExecutionPlanMetricsSet::new(),
            default_selectivity: self.default_selectivity,
            cache: Arc::new(cache),
            projection: self.projection,
            batch_size: self.batch_size,
            fetch: self.fetch,
        })
    }
}

impl From<&FilterExec> for FilterExecBuilder {
    fn from(exec: &FilterExec) -> Self {
        Self {
            predicate: Arc::clone(&exec.predicate),
            input: Arc::clone(&exec.input),
            projection: exec.projection.clone(),
            default_selectivity: exec.default_selectivity,
            batch_size: exec.batch_size,
            fetch: exec.fetch,
            // We could cache / copy over PlanProperties
            // here but that would require invalidating them in FilterExecBuilder::apply_projection, etc.
            // and currently every call to this method ends up invalidating them anyway.
            // If useful this can be added in the future as a non-breaking change.
        }
    }
}

impl FilterExec {
    /// Create a FilterExec on an input using the builder pattern
    pub fn try_new(
        predicate: Arc<dyn PhysicalExpr>,
        input: Arc<dyn ExecutionPlan>,
    ) -> Result<Self> {
        FilterExecBuilder::new(predicate, input).build()
    }

    /// Get a batch size
    pub fn batch_size(&self) -> usize {
        self.batch_size
    }

    /// Set the default selectivity
    pub fn with_default_selectivity(
        mut self,
        default_selectivity: u8,
    ) -> Result<Self, DataFusionError> {
        if default_selectivity > 100 {
            return plan_err!(
                "Default filter selectivity value needs to be less than or equal to 100"
            );
        }
        self.default_selectivity = default_selectivity;
        Ok(self)
    }

    /// Return new instance of [FilterExec] with the given projection.
    ///
    /// # Deprecated
    /// Use [`FilterExecBuilder::apply_projection`] instead
    #[deprecated(
        since = "52.0.0",
        note = "Use FilterExecBuilder::apply_projection instead"
    )]
    pub fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
        let builder = FilterExecBuilder::from(self);
        builder.apply_projection(projection)?.build()
    }

    /// Set the batch size
    pub fn with_batch_size(&self, batch_size: usize) -> Result<Self> {
        if batch_size == 0 {
            return plan_err!("FilterExec: batch_size must be greater than 0");
        }
        Ok(Self {
            predicate: Arc::clone(&self.predicate),
            input: Arc::clone(&self.input),
            metrics: self.metrics.clone(),
            default_selectivity: self.default_selectivity,
            cache: Arc::clone(&self.cache),
            projection: self.projection.clone(),
            batch_size,
            fetch: self.fetch,
        })
    }

    /// The expression to filter on. This expression must evaluate to a boolean value.
    pub fn predicate(&self) -> &Arc<dyn PhysicalExpr> {
        &self.predicate
    }

    /// The input plan
    pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
        &self.input
    }

    /// The default selectivity
    pub fn default_selectivity(&self) -> u8 {
        self.default_selectivity
    }

    /// Describe which parent filters (in this node's output coordinates) can
    /// be forwarded to the input, remapped into input coordinates.
    ///
    /// With an embedded projection the output position `i` reads input column
    /// `projection[i]`; without one the positions are identical. Mapping by
    /// position keeps same-named input columns distinct.
    fn parent_filters_for_input(
        &self,
        parent_filters: &[Arc<dyn PhysicalExpr>],
    ) -> Result<ChildFilterDescription> {
        if parent_filters.is_empty() {
            return Ok(ChildFilterDescription::empty());
        }
        match self.projection.as_ref() {
            Some(projection) => ChildFilterDescription::from_child_with_column_mapping(
                parent_filters,
                projection.iter().copied().enumerate().collect(),
                self.input(),
            ),
            None => ChildFilterDescription::from_child(parent_filters, self.input()),
        }
    }

    /// Projection
    pub fn projection(&self) -> &Option<ProjectionRef> {
        &self.projection
    }

    /// Calculates `Statistics` for `FilterExec` by applying the filter's
    /// selectivity (estimated from interval analysis or string statistics, with
    /// a configurable fallback) to the input statistics.
    ///
    /// The estimated output row count is used to keep the per-column statistics
    /// consistent with it:
    /// - null and distinct counts are capped at the estimated row count;
    /// - byte sizes (per column and total) are scaled by the selectivity, and
    ///   are an exact zero when the row count is an exact zero;
    /// - a column constrained to a single value (`col = literal`, or an
    ///   interval that collapses to one point) gets a distinct count of 1;
    /// - a column in a null-rejecting conjunct gets a null count of 0.
    ///
    /// When interval analysis applies, min/max are also tightened to the
    /// surviving value range.
    ///
    /// A contradictory predicate (e.g. `a = 1 AND a = 2`) yields zero rows and
    /// empty-column statistics.
    pub(crate) fn statistics_helper(
        schema: &SchemaRef,
        input_stats: Statistics,
        predicate: &Arc<dyn PhysicalExpr>,
        default_selectivity: u8,
    ) -> Result<Statistics> {
        let (eq_columns, is_infeasible) = collect_equality_columns(predicate);

        let input_num_rows = input_stats.num_rows;
        let input_total_byte_size = input_stats.total_byte_size;

        // A column holding each of its values once, as a primary key or unique
        // constraint says, matches one row per value asked for. No selectivity
        // expresses that.
        let match_limit = unique_match_limit(predicate, &input_stats);

        let (selectivity, num_rows, column_statistics) = if is_infeasible {
            // Contradictory predicate: no rows survive.
            let cs = vec![empty_column_statistics(); input_stats.column_statistics.len()];
            (0.0, Precision::Exact(0), cs)
        } else {
            let null_rejecting_columns = collect_null_rejecting_columns(predicate);

            if check_support(predicate, schema) {
                let input_analysis_ctx = AnalysisContext::try_from_statistics(
                    schema,
                    &input_stats.column_statistics,
                )?;
                let analysis_ctx = analyze(predicate, input_analysis_ctx, schema)?;
                let selectivity = analysis_ctx.selectivity.unwrap_or(1.0);
                let filtered_num_rows =
                    input_num_rows.with_estimated_selectivity(selectivity);
                let cs = collect_new_statistics(
                    schema,
                    &input_stats.column_statistics,
                    analysis_ctx.boundaries,
                    selectivity,
                    &null_rejecting_columns,
                    filtered_num_rows,
                );
                (selectivity, filtered_num_rows, cs)
            } else {
                // String predicates cannot use interval analysis. Estimate them
                // from distinct counts and pattern form when possible, then
                // apply the row-count constraints implied by the predicate.
                //
                // Without interval boundaries, attempt a heuristic fallback for selectivities.
                // For instance, an equality filter against an unresolved scalar subquery will
                // fail `check_support`, but we can still estimate selectivity as `1.0 / NDV`.
                let default_selectivity_f64 = default_selectivity as f64 / 100.0;
                let selectivity = string_selectivity(
                    predicate,
                    schema,
                    &input_stats,
                    default_selectivity_f64,
                )
                .unwrap_or_else(|| {
                    compute_fallback_selectivity(
                        predicate,
                        &input_stats.column_statistics,
                        default_selectivity,
                    )
                });
                let filtered_num_rows =
                    input_num_rows.with_estimated_selectivity(selectivity);
                let mut cs = input_stats.to_inexact().column_statistics;
                for (idx, col_stat) in cs.iter_mut().enumerate() {
                    col_stat.byte_size = scale_byte_size_at_rows(
                        col_stat.byte_size,
                        selectivity,
                        filtered_num_rows,
                    );
                    col_stat.null_count = if null_rejecting_columns.contains(&idx) {
                        Precision::Exact(0)
                    } else {
                        cap_at_rows(col_stat.null_count, filtered_num_rows)
                    };
                    col_stat.distinct_count = if eq_columns.contains(&idx) {
                        distinct_count_for_singleton_domain(filtered_num_rows)
                    } else {
                        cap_at_rows(col_stat.distinct_count, filtered_num_rows)
                    };
                }
                (selectivity, filtered_num_rows, cs)
            }
        };

        let num_rows = match (match_limit, num_rows.get_value()) {
            (Some(limit), Some(rows)) if *rows > limit => Precision::Inexact(limit),
            _ => num_rows,
        };
        let total_byte_size =
            scale_byte_size_at_rows(input_total_byte_size, selectivity, num_rows);

        Ok(Statistics {
            num_rows,
            total_byte_size,
            column_statistics,
        })
    }

    /// Applies the filter's `fetch` to its output statistics for `partition`,
    /// or for all partitions when `partition` is `None`. The fetch stops each
    /// partition separately.
    #[inline]
    pub(crate) fn statistics_with_fetch(
        &self,
        stats: Statistics,
        partition: Option<usize>,
    ) -> Result<Statistics> {
        match self.fetch {
            Some(fetch) => self.statistics_under_fetch(stats, fetch, partition),
            None => Ok(stats),
        }
    }

    fn statistics_under_fetch(
        &self,
        stats: Statistics,
        fetch: usize,
        partition: Option<usize>,
    ) -> Result<Statistics> {
        if stats
            .num_rows
            .get_value()
            .is_some_and(|rows| *rows <= fetch)
        {
            // No partition reaches the fetch, so no rows are dropped.
            return Ok(stats);
        }
        let partitions = self.properties().partitioning.partition_count();
        let single = partition.is_some() || partitions <= 1;
        let bound = if single {
            fetch
        } else {
            fetch.saturating_mul(partitions)
        };
        let input_columns = stats.column_statistics.clone();
        let stats = if single {
            stats
        } else {
            // Any partition can hold more than `fetch` rows, so the total
            // under the fetch is only an estimate.
            stats.to_inexact()
        };

        let mut stats = stats.with_fetch(Some(bound), 0, 1)?;
        if stats.num_rows == Precision::Exact(0) {
            stats.total_byte_size = Precision::Exact(0);
            stats.column_statistics.fill(empty_column_statistics());
            return Ok(stats);
        }
        // A fetch only drops rows. A count that is exactly zero stays exact, and
        // so does a column with one value in every row while rows remain.
        for (column_stats, input) in stats.column_statistics.iter_mut().zip(input_columns)
        {
            if input.null_count == Precision::Exact(0) {
                if fetch > 0 && input.is_singleton() {
                    column_stats.min_value = input.min_value;
                    column_stats.max_value = input.max_value;
                    if input.distinct_count == Precision::Exact(1) {
                        column_stats.distinct_count = input.distinct_count;
                    }
                }
                column_stats.null_count = input.null_count;
            } else {
                column_stats.null_count =
                    cap_at_rows(column_stats.null_count, stats.num_rows);
            }
            if input.distinct_count == Precision::Exact(0) {
                column_stats.distinct_count = input.distinct_count;
            }
        }
        if let Some((column, true)) = null_check_column(self.predicate())
            && let Some(column_stats) = stats.column_statistics.get_mut(column)
        {
            // Every surviving row is still null after the fetch.
            column_stats.null_count = stats.num_rows;
        }
        Ok(stats)
    }

    /// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
    fn compute_properties(
        input: &Arc<dyn ExecutionPlan>,
        predicate: &Arc<dyn PhysicalExpr>,
        default_selectivity: u8,
        projection: Option<&[usize]>,
    ) -> Result<PlanProperties> {
        // Combine the equal predicates with the input equivalence properties
        // to construct the equivalence properties:
        let schema = input.schema();
        let stats = Self::statistics_helper(
            &schema,
            Arc::unwrap_or_clone(
                StatisticsContext::new()
                    .compute(input.as_ref(), &StatisticsArgs::new())?,
            ),
            predicate,
            default_selectivity,
        )?;
        let mut eq_properties = input.equivalence_properties().clone();
        let (equal_pairs, _) = collect_columns_from_predicate_inner(predicate);
        for (lhs, rhs) in equal_pairs {
            eq_properties.add_equal_conditions(Arc::clone(lhs), Arc::clone(rhs))?
        }
        // Add the columns that have only one viable value (singleton) after
        // filtering to constants.
        let constants = collect_columns(predicate)
            .into_iter()
            .filter(|column| stats.column_statistics[column.index()].is_singleton())
            .map(|column| {
                let value = stats.column_statistics[column.index()]
                    .min_value
                    .get_value();
                let expr = Arc::new(column) as _;
                ConstExpr::new(expr, AcrossPartitions::Uniform(value.cloned()))
            });
        // This is for statistics
        eq_properties.add_constants(constants)?;
        // This is for logical constant (for example: a = '1', then a could be marked as a constant)
        // to do: how to deal with multiple situation to represent = (for example c1 between 0 and 0)
        eq_properties.add_constants(ConstExpr::collect_predicate_constants(
            input.equivalence_properties(),
            predicate,
        ))?;

        let mut output_partitioning = input.output_partitioning().clone();
        // If contains projection, update the PlanProperties.
        if let Some(projection) = projection {
            let schema = eq_properties.schema();
            let projection_mapping = ProjectionMapping::from_indices(projection, schema)?;
            let out_schema = project_schema(schema, Some(&projection))?;
            output_partitioning =
                output_partitioning.project(&projection_mapping, &eq_properties);
            eq_properties = eq_properties.project(&projection_mapping, out_schema);
        }

        Ok(PlanProperties::new(
            eq_properties,
            output_partitioning,
            input.pipeline_behavior(),
            input.boundedness(),
        ))
    }
}

impl DisplayAs for FilterExec {
    fn fmt_as(
        &self,
        t: DisplayFormatType,
        f: &mut std::fmt::Formatter,
    ) -> std::fmt::Result {
        match t {
            DisplayFormatType::Default | DisplayFormatType::Verbose => {
                let display_projections = if let Some(projection) =
                    self.projection.as_ref()
                {
                    format!(
                        ", projection=[{}]",
                        projection
                            .iter()
                            .map(|index| format!(
                                "{}@{}",
                                self.input.schema().fields().get(*index).unwrap().name(),
                                index
                            ))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                } else {
                    "".to_string()
                };
                let fetch = self
                    .fetch
                    .map_or_else(|| "".to_string(), |f| format!(", fetch={f}"));
                write!(
                    f,
                    "FilterExec: {}{}{}",
                    self.predicate, display_projections, fetch
                )
            }
            DisplayFormatType::TreeRender => {
                if let Some(fetch) = self.fetch {
                    writeln!(f, "fetch={fetch}")?;
                }
                write!(f, "predicate={}", fmt_sql(self.predicate.as_ref()))
            }
        }
    }
}

impl ExecutionPlan for FilterExec {
    fn name(&self) -> &'static str {
        "FilterExec"
    }

    /// Return a reference to Any that can be used for downcasting
    fn properties(&self) -> &Arc<PlanProperties> {
        &self.cache
    }

    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
        vec![&self.input]
    }

    fn apply_expressions(
        &self,
        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
    ) -> Result<TreeNodeRecursion> {
        crate::apply_expression_roots([&self.predicate], f)
    }

    fn maintains_input_order(&self) -> Vec<bool> {
        // Tell optimizer this operator doesn't reorder its input
        vec![true]
    }

    fn replace_children(
        self: Arc<Self>,
        mut children: Vec<Arc<dyn ExecutionPlan>>,
        options: ReplaceChildrenOptions,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        validate_child_count!(self, children);
        match options.children_properties {
            ChildrenPropertiesMode::Keep => Ok(Arc::new(Self {
                input: children.swap_remove(0),
                metrics: ExecutionPlanMetricsSet::new(),
                ..Self::clone(&*self)
            })),
            ChildrenPropertiesMode::Recompute => {
                let new_input = children.swap_remove(0);
                FilterExecBuilder::from(&*self)
                    .with_input(new_input)
                    .build()
                    .map(|e| Arc::new(e) as _)
            }
        }
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        self.replace_children(
            children,
            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
        )
    }

    fn with_new_children_and_same_properties(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        self.replace_children(
            children,
            ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
        )
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        trace!(
            "Start FilterExec::execute for partition {} of context session_id {} and task_id {:?}",
            partition,
            context.session_id(),
            context.task_id()
        );
        let metrics = FilterExecMetrics::new(&self.metrics, partition);
        Ok(Box::pin(FilterExecStream {
            schema: self.schema(),
            predicate: Arc::clone(&self.predicate),
            input: self.input.execute(partition, context)?,
            metrics,
            projection: self.projection.clone(),
            batch_coalescer: LimitedBatchCoalescer::new(
                self.schema(),
                self.batch_size,
                self.fetch,
            ),
        }))
    }

    fn metrics(&self) -> Option<MetricsSet> {
        Some(self.metrics.clone_inner())
    }

    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
        vec![ChildStats::At(partition)]
    }

    /// The output statistics of a filtering operation can be estimated if the
    /// predicate's selectivity value can be determined for the incoming data.
    fn statistics_from_inputs(
        &self,
        input_stats: &[Arc<Statistics>],
        args: &StatisticsArgs,
    ) -> Result<Arc<Statistics>> {
        let input_stats = input_stats[0].as_ref().clone();
        let stats = Self::statistics_helper(
            &self.input.schema(),
            input_stats,
            self.predicate(),
            self.default_selectivity,
        )?;
        let stats = self.statistics_with_fetch(stats, args.partition())?;
        Ok(Arc::new(stats.project(self.projection.as_ref())))
    }

    fn cardinality_effect(&self) -> CardinalityEffect {
        CardinalityEffect::LowerEqual
    }

    /// Tries to swap `projection` with its input (`filter`). If possible, performs
    /// the swap and returns [`FilterExec`] as the top plan. Otherwise, returns `None`.
    fn try_swapping_with_projection(
        &self,
        projection: &ProjectionExec,
    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
        // If the projection does not narrow the schema, we should not try to push it down:
        if projection.expr().len() < projection.input().schema().fields().len() {
            // Each column in the predicate expression must exist after the projection.
            if let Some(new_predicate) =
                update_expr(self.predicate(), projection.expr(), false)?
            {
                return FilterExecBuilder::from(self)
                    .with_input(make_with_child(projection, self.input())?)
                    .with_predicate(new_predicate)
                    // The original FilterExec projection referenced columns from its old
                    // input. After the swap the new input is the ProjectionExec which
                    // already handles column selection, so clear the projection here.
                    .apply_projection(None)?
                    .build()
                    .map(|e| Some(Arc::new(e) as _));
            }
        }
        try_embed_projection(projection, self)
    }

    fn gather_filters_for_pushdown(
        &self,
        phase: FilterPushdownPhase,
        parent_filters: Vec<Arc<dyn PhysicalExpr>>,
        _config: &ConfigOptions,
    ) -> Result<FilterDescription> {
        let mut child = self.parent_filters_for_input(&parent_filters);
        if phase == FilterPushdownPhase::Pre {
            child = child.map(|child| {
                child.with_self_filters(
                    split_conjunction(&self.predicate)
                        .into_iter()
                        .cloned()
                        .collect(),
                )
            });
        }
        child.map(|child| FilterDescription::new().with_child(child))
    }

    fn handle_child_pushdown_result(
        &self,
        phase: FilterPushdownPhase,
        child_pushdown_result: ChildPushdownResult,
        _config: &ConfigOptions,
    ) -> Result<FilterPushdownPropagation<Arc<dyn ExecutionPlan>>> {
        if phase != FilterPushdownPhase::Pre {
            return Ok(FilterPushdownPropagation::if_all(child_pushdown_result));
        }
        // We absorb any parent filters that were not handled by our children
        let mut unsupported_parent_filters: Vec<Arc<dyn PhysicalExpr>> =
            child_pushdown_result
                .parent_filters
                .iter()
                .filter_map(|f| {
                    matches!(f.all(), PushedDown::No).then_some(Arc::clone(&f.filter))
                })
                .collect();

        // If this FilterExec has a projection, the unsupported parent filters
        // are in the output schema (after projection) coordinates. We need to
        // remap them to the input schema coordinates before combining with self
        // filters. Map by position through the projection: the input may
        // contain several columns with the same name.
        if let Some(projection) = self.projection.as_ref()
            && !unsupported_parent_filters.is_empty()
        {
            let remapper = FilterRemapper::with_column_mapping(
                self.input().schema(),
                projection.iter().copied().enumerate().collect(),
            );
            unsupported_parent_filters = unsupported_parent_filters
                .into_iter()
                .map(|expr| {
                    remapper.try_remap(&expr)?.ok_or_else(|| {
                        internal_datafusion_err!(
                            "Parent filter {expr} references a column that is not in the FilterExec projection {projection:?}"
                        )
                    })
                })
                .collect::<Result<Vec<_>>>()?;
        }

        let unsupported_self_filters = child_pushdown_result
            .self_filters
            .first()
            .expect("we have exactly one child")
            .iter()
            .filter_map(|f| match f.discriminant {
                PushedDown::Yes => None,
                PushedDown::No => Some(&f.predicate),
            })
            .cloned();

        let unhandled_filters = unsupported_parent_filters
            .into_iter()
            .chain(unsupported_self_filters)
            .collect_vec();

        // If we have unhandled filters, we need to create a new FilterExec
        let filter_input = Arc::clone(self.input());
        let new_predicate = conjunction(unhandled_filters);
        let updated_node = if new_predicate.eq(&lit(true)) {
            // FilterExec is no longer needed, but we may need to leave a projection in place.
            // If this FilterExec had a fetch limit, propagate it to the child.
            // When the child also has a fetch, use the minimum of both to preserve
            // the tighter constraint.
            let filter_input = if let Some(outer_fetch) = self.fetch {
                let effective_fetch = match filter_input.fetch() {
                    Some(inner_fetch) => outer_fetch.min(inner_fetch),
                    None => outer_fetch,
                };
                match filter_input.with_fetch(Some(effective_fetch)) {
                    Some(node) => node,
                    None => Arc::new(LocalLimitExec::new(filter_input, effective_fetch)),
                }
            } else {
                filter_input
            };
            match self.projection().as_ref() {
                Some(projection_indices) => {
                    let filter_child_schema = filter_input.schema();
                    let proj_exprs = projection_indices
                        .iter()
                        .map(|p| {
                            let field = filter_child_schema.field(*p).clone();
                            ProjectionExpr {
                                expr: Arc::new(Column::new(field.name(), *p))
                                    as Arc<dyn PhysicalExpr>,
                                alias: field.name().to_string(),
                            }
                        })
                        .collect::<Vec<_>>();
                    Some(Arc::new(ProjectionExec::try_new(proj_exprs, filter_input)?)
                        as Arc<dyn ExecutionPlan>)
                }
                None => {
                    // No projection needed, just return the input
                    Some(filter_input)
                }
            }
        } else if new_predicate.eq(&self.predicate) {
            // The new predicate is the same as our current predicate
            None
        } else {
            // Create a new FilterExec with the new predicate, preserving the projection
            let new = FilterExec {
                predicate: Arc::clone(&new_predicate),
                input: Arc::clone(&filter_input),
                metrics: self.metrics.clone(),
                default_selectivity: self.default_selectivity,
                cache: Arc::new(Self::compute_properties(
                    &filter_input,
                    &new_predicate,
                    self.default_selectivity,
                    self.projection.as_deref(),
                )?),
                projection: self.projection.clone(),
                batch_size: self.batch_size,
                fetch: self.fetch,
            };
            Some(Arc::new(new) as _)
        };

        Ok(FilterPushdownPropagation {
            filters: vec![PushedDown::Yes; child_pushdown_result.parent_filters.len()],
            updated_node,
        })
    }

    fn fetch(&self) -> Option<usize> {
        self.fetch
    }

    fn with_fetch(&self, fetch: Option<usize>) -> Option<Arc<dyn ExecutionPlan>> {
        Some(Arc::new(Self {
            predicate: Arc::clone(&self.predicate),
            input: Arc::clone(&self.input),
            metrics: self.metrics.clone(),
            default_selectivity: self.default_selectivity,
            cache: Arc::clone(&self.cache),
            projection: self.projection.clone(),
            batch_size: self.batch_size,
            fetch,
        }))
    }

    #[cfg(feature = "proto")]
    fn try_to_proto(
        &self,
        ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
        use datafusion_common::utils::usize_to_wire;
        use datafusion_proto_models::protobuf;
        // Destructure exhaustively (no `..`) so that adding a field to
        // `FilterExec` is a compile error here until it is either serialized or
        // explicitly documented as not needing to be.
        let Self {
            predicate,
            input,
            // Runtime metrics, not part of the plan shape.
            metrics: _,
            default_selectivity,
            // Derived plan properties, recomputed on decode.
            cache: _,
            projection,
            batch_size,
            fetch,
        } = self;
        let input_node = ctx.encode_child(input)?;
        let expr = ctx.encode_expr(predicate)?;
        if *batch_size == 0 {
            return plan_err!("FilterExec: batch_size must be greater than 0");
        }
        let batch_size = usize_to_wire(*batch_size, "FilterExec", "batch_size")?;
        let fetch = fetch
            .map(|fetch| usize_to_wire(fetch, "FilterExec", "fetch"))
            .transpose()?;
        // The identity projection `[0, 1, ..., num_fields - 1]` is the
        // canonical wire representation of a full projection, so `None` is
        // encoded that way (and decodes back to `None`).
        let projection = if let Some(v) = projection {
            v.iter().map(|x| *x as u32).collect()
        } else {
            (0..input.schema().fields().len())
                .map(|i| i as u32)
                .collect()
        };
        Ok(Some(protobuf::PhysicalPlanNode {
            physical_plan_type: Some(
                protobuf::physical_plan_node::PhysicalPlanType::Filter(Box::new(
                    protobuf::FilterExecNode {
                        input: Some(Box::new(input_node)),
                        expr: Some(expr),
                        default_filter_selectivity: *default_selectivity as u32,
                        projection,
                        batch_size,
                        fetch,
                    },
                )),
            ),
        }))
    }
}

#[cfg(feature = "proto")]
impl FilterExec {
    /// Reconstruct a [`FilterExec`] from its protobuf representation.
    ///
    /// The exact inverse of [`ExecutionPlan::try_to_proto`]: it takes the whole
    /// [`PhysicalPlanNode`] so every plan's `try_from_proto` shares one signature.
    ///
    /// [`PhysicalPlanNode`]: datafusion_proto_models::protobuf::PhysicalPlanNode
    /// [`ExecutionPlan::try_to_proto`]: crate::ExecutionPlan::try_to_proto
    pub fn try_from_proto(
        node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
        ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        use datafusion_common::utils::usize_from_wire;
        use datafusion_proto_models::protobuf;
        let filter_node = crate::expect_plan_variant!(
            node,
            protobuf::physical_plan_node::PhysicalPlanType::Filter,
            "FilterExec",
        );
        // Destructure exhaustively so that a new field on `FilterExecNode` is a
        // compile error here rather than a silently dropped field.
        let protobuf::FilterExecNode {
            input,
            expr,
            default_filter_selectivity,
            projection,
            batch_size,
            fetch,
        } = &**filter_node;
        let input = ctx.decode_required_child(input.as_deref(), "FilterExec", "input")?;
        let predicate = ctx.decode_required_expr(
            expr.as_ref(),
            input.schema().as_ref(),
            "FilterExec",
            "expr",
        )?;
        let filter_selectivity = (*default_filter_selectivity).try_into();

        // `None` is encoded as the full identity projection. Reconstruct it only
        // when all input columns are present in order, leaving an empty list as
        // `Some(vec![])`.
        let num_fields = input.schema().fields().len();
        let mut is_full_projection = projection.len() == num_fields;
        let mut projection_vec: Vec<usize> = Vec::with_capacity(projection.len());
        for (i, idx) in projection.iter().enumerate() {
            let idx = *idx as usize;
            is_full_projection &= idx == i;
            projection_vec.push(idx);
        }
        let projection = if is_full_projection {
            None
        } else {
            Some(projection_vec)
        };
        // Proto3's zero default means "use the builder default."
        let batch_size = match *batch_size {
            0 => FILTER_EXEC_DEFAULT_BATCH_SIZE,
            batch_size => usize_from_wire(batch_size, "FilterExec", "batch_size")?,
        };
        let fetch = fetch
            .map(|f| usize_from_wire(f, "FilterExec", "fetch"))
            .transpose()?;
        let filter = FilterExecBuilder::new(predicate, input)
            .apply_projection(projection)?
            .with_batch_size(batch_size)
            .with_fetch(fetch)
            .build()?;
        match filter_selectivity {
            Ok(filter_selectivity) => Ok(Arc::new(
                filter.with_default_selectivity(filter_selectivity)?,
            )),
            Err(_) => Err(datafusion_common::internal_datafusion_err!(
                "filter_selectivity in PhysicalPlanNode is invalid"
            )),
        }
    }
}

impl EmbeddedProjection for FilterExec {
    fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
        FilterExecBuilder::from(self)
            .apply_projection(projection)?
            .build()
    }
}

/// The most rows a filter can match, when it restricts a column holding each value
/// once to a fixed set of values: one row per value.
fn unique_match_limit(
    predicate: &Arc<dyn PhysicalExpr>,
    statistics: &Statistics,
) -> Option<usize> {
    let mut limit: Option<usize> = None;
    for expr in split_conjunction(predicate) {
        let Some((index, values)) = restricted_column(expr) else {
            continue;
        };
        let holds_once = statistics
            .column_statistics
            .get(index)
            .is_some_and(|column| holds_each_value_once(column, &statistics.num_rows));
        if !holds_once {
            continue;
        }
        limit = Some(limit.map_or(values, |limit: usize| limit.min(values)));
    }
    limit
}

/// The column an expression restricts to a fixed set of values, and how many values
/// that is. NULL is never one of them: it matches nothing.
fn restricted_column(expr: &Arc<dyn PhysicalExpr>) -> Option<(usize, usize)> {
    if let Some(in_list) = expr.downcast_ref::<InListExpr>() {
        if in_list.negated() {
            return None;
        }
        let column = in_list.expr().downcast_ref::<Column>()?;
        let mut values: Vec<&ScalarValue> = Vec::with_capacity(in_list.list().len());
        for expr in in_list.list() {
            let value = expr.downcast_ref::<Literal>()?.value();
            if !value.is_null() && !values.contains(&value) {
                values.push(value);
            }
        }
        return Some((column.index(), values.len()));
    }

    let binary = expr.downcast_ref::<BinaryExpr>()?;
    if *binary.op() != Operator::Eq {
        return None;
    }
    let (column, literal) = match (
        binary.left().downcast_ref::<Column>(),
        binary.right().downcast_ref::<Column>(),
    ) {
        (Some(column), None) => (column, binary.right()),
        (None, Some(column)) => (column, binary.left()),
        _ => return None,
    };
    let value = literal.downcast_ref::<Literal>()?.value();
    (!value.is_null()).then_some((column.index(), 1))
}

/// Whether the column has as many distinct values as it has non-null rows, so each
/// value appears once.
fn holds_each_value_once(column: &ColumnStatistics, num_rows: &Precision<usize>) -> bool {
    let (Some(rows), Some(distinct), Some(nulls)) = (
        num_rows.get_value(),
        column.distinct_count.get_value(),
        column.null_count.get_value(),
    ) else {
        return false;
    };
    distinct.saturating_add(*nulls) >= *rows
}

/// Heuristic selectivity for predicates that fail interval analysis.
///
/// Splits the predicate into AND conjuncts. For each equality (`col = expr`)
/// where at least one side is a [`Column`] with a known NDV, the selectivity
/// contribution is `1 / NDV`. When both sides are columns with known NDV,
/// `1 / max(left_NDV, right_NDV)` is used. All remaining conjuncts that
/// cannot be estimated are covered by a single application of
/// `default_selectivity`, preserving the pre-existing estimate for predicates
/// that contain no recognizable equality.
fn compute_fallback_selectivity(
    predicate: &Arc<dyn PhysicalExpr>,
    column_statistics: &[ColumnStatistics],
    default_selectivity: u8,
) -> f64 {
    let conjuncts = split_conjunction(predicate);
    let mut selectivity = 1.0;
    let mut has_unhandled = false;

    for expr in conjuncts {
        let mut handled = false;

        if let Some(binary) = expr.downcast_ref::<BinaryExpr>()
            && *binary.op() == Operator::Eq
        {
            let left_ndv = column_ndv(binary.left(), column_statistics);
            let right_ndv = column_ndv(binary.right(), column_statistics);

            let ndv = match (left_ndv, right_ndv) {
                (Some(l), Some(r)) => Some(l.max(r)),
                (Some(n), None) | (None, Some(n)) => Some(n),
                (None, None) => None,
            };

            if let Some(n) = ndv {
                selectivity *= 1.0 / (n as f64);
                handled = true;
            }
        }

        if !handled {
            has_unhandled = true;
        }
    }

    // Apply the default selectivity at most once for all unhandled conjuncts,
    // so that a predicate with no handled equalities returns the default estimate.
    if has_unhandled {
        selectivity *= default_selectivity as f64 / 100.0;
    }

    selectivity
}

/// Extracts the NDV from a [`Column`] reference, if the expression is a bare
/// column and its statistics carry a positive distinct count.
fn column_ndv(
    expr: &Arc<dyn PhysicalExpr>,
    column_statistics: &[ColumnStatistics],
) -> Option<usize> {
    let col = expr.downcast_ref::<Column>()?;
    let stat = column_statistics.get(col.index())?;
    match stat.distinct_count {
        Precision::Exact(ndv) | Precision::Inexact(ndv) if ndv > 0 => Some(ndv),
        _ => None,
    }
}

/// Collects column equality information from `col = literal` predicates in a
/// conjunction.
///
/// Returns `(eq_columns, is_infeasible)`:
/// - `eq_columns`: set of column indices constrained to a single literal value.
/// - `is_infeasible`: `true` when the same column is equated to two different
///   non-null literals (e.g. `name = 'alice' AND name = 'bob'`), which is
///   always unsatisfiable.
///
/// Only AND conjunctions are traversed; OR is intentionally skipped
/// since `a = 1 OR a = 2` does not pin NDV to 1.
fn collect_equality_columns(predicate: &Arc<dyn PhysicalExpr>) -> (HashSet<usize>, bool) {
    let mut eq_values: HashMap<usize, ScalarValue> = HashMap::new();
    let mut infeasible = false;

    for expr in split_conjunction(predicate) {
        let Some(binary) = expr.downcast_ref::<BinaryExpr>() else {
            continue;
        };
        if *binary.op() != Operator::Eq {
            continue;
        }
        let left = binary.left();
        let right = binary.right();
        let pair = if let Some(col) = left.downcast_ref::<Column>()
            && let Some(lit) = right.downcast_ref::<Literal>()
            && !lit.value().is_null()
        {
            Some((col.index(), lit.value().clone()))
        } else if let Some(col) = right.downcast_ref::<Column>()
            && let Some(lit) = left.downcast_ref::<Literal>()
            && !lit.value().is_null()
        {
            Some((col.index(), lit.value().clone()))
        } else {
            None
        };

        if let Some((idx, value)) = pair {
            match eq_values.entry(idx) {
                Entry::Occupied(prev) => {
                    if *prev.get() != value {
                        infeasible = true;
                        break;
                    }
                }
                Entry::Vacant(slot) => {
                    slot.insert(value);
                }
            }
        }
    }

    (eq_values.into_keys().collect(), infeasible)
}

/// Collects columns that cannot be NULL in any surviving row.
///
/// A filter keeps only rows where the predicate is TRUE, so a column is
/// null-rejecting if some top-level AND conjunct evaluates to NULL or FALSE
/// whenever that column is NULL. Two such conjuncts are recognized:
///
/// - a binary operator that returns NULL on NULL input, applied directly to the
///   column (e.g. `a = 10`, `a < b`);
/// - an `IS NOT NULL` check on the column (e.g. `a IS NOT NULL`).
///
/// This analysis is conservative; for example, OR clauses are not considered
/// null-rejecting, and neither are indirect operands like `a + 1 < 10`.
fn collect_null_rejecting_columns(predicate: &Arc<dyn PhysicalExpr>) -> HashSet<usize> {
    let mut columns = HashSet::new();

    for expr in split_conjunction(predicate) {
        // LIKE (including ILIKE and their negations) returns NULL if either
        // operand is NULL.
        if let Some(like) = expr.downcast_ref::<LikeExpr>() {
            for operand in [like.expr(), like.pattern()] {
                if let Some(col) = operand.downcast_ref::<Column>() {
                    columns.insert(col.index());
                }
            }
            continue;
        }

        // `col IS NOT NULL` keeps only rows where `col` is non-null.
        if let Some(is_not_null) = expr.downcast_ref::<IsNotNullExpr>() {
            if let Some(col) = is_not_null.arg().downcast_ref::<Column>() {
                columns.insert(col.index());
            }
            continue;
        }

        // A binary operator that returns NULL on NULL input rejects rows where
        // a direct column operand is NULL.
        if let Some(binary) = expr.downcast_ref::<BinaryExpr>() {
            if !binary.op().returns_null_on_null() {
                continue;
            }
            if let Some(col) = binary.left().downcast_ref::<Column>() {
                columns.insert(col.index());
            }
            if let Some(col) = binary.right().downcast_ref::<Column>() {
                columns.insert(col.index());
            }
        }
    }

    columns
}

/// Estimates a single string comparison against a literal. Compound predicates
/// retain the fallback: multiplying estimates for predicates on the same column
/// would count null rejection (and possibly the same restriction) repeatedly.
fn string_selectivity(
    predicate: &Arc<dyn PhysicalExpr>,
    schema: &SchemaRef,
    input_stats: &Statistics,
    default_selectivity: f64,
) -> Option<f64> {
    let (column, literal, negated, like) =
        if let Some(binary) = predicate.downcast_ref::<BinaryExpr>() {
            if !matches!(binary.op(), Operator::Eq | Operator::NotEq) {
                return None;
            }
            let operands = [
                (binary.left(), binary.right()),
                (binary.right(), binary.left()),
            ];
            let (column, literal) = operands.into_iter().find_map(|(left, right)| {
                Some((
                    left.downcast_ref::<Column>()?,
                    right.downcast_ref::<Literal>()?,
                ))
            })?;
            (column, literal, *binary.op() == Operator::NotEq, None)
        } else {
            let like = predicate.downcast_ref::<LikeExpr>()?;
            (
                like.expr().downcast_ref::<Column>()?,
                like.pattern().downcast_ref::<Literal>()?,
                like.negated(),
                Some(like),
            )
        };

    if !matches!(
        schema.field(column.index()).data_type(),
        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
    ) {
        return None;
    }
    let Some(value) = literal.value().try_as_str()? else {
        // Both a comparison and its negation evaluate to NULL here.
        return Some(0.0);
    };
    let column_stats = &input_stats.column_statistics[column.index()];
    let equality_selectivity = column_stats
        .distinct_count
        .get_value()
        .filter(|&&ndv| ndv > 0)
        .map_or(default_selectivity, |&ndv| 1.0 / ndv as f64);
    let positive_selectivity = match like {
        Some(like) => like_selectivity(
            value,
            like.case_insensitive(),
            equality_selectivity,
            default_selectivity,
        ),
        None => equality_selectivity,
    };
    let selectivity = if negated {
        1.0 - positive_selectivity
    } else {
        positive_selectivity
    };

    // Apply the complement within the non-null rows, not across all input
    // rows. Unknown null counts use the usual assumption of no nulls.
    match (
        input_stats.num_rows.get_value(),
        column_stats.null_count.get_value(),
    ) {
        (Some(&rows), Some(&nulls)) if rows > 0 => {
            Some(rows.saturating_sub(nulls) as f64 * selectivity / rows as f64)
        }
        (Some(0), _) => Some(0.0),
        _ => Some(selectivity),
    }
}

/// Classifies a LIKE pattern without treating escaped wildcards as operators.
/// In the absence of string histograms, wildcard patterns use the configured
/// fallback, halved for each anchored end. Thus prefix/suffix patterns are
/// estimated to match fewer rows than an unanchored contains pattern. These are
/// heuristics, not bounds on the number of matches.
fn like_selectivity(
    pattern: &str,
    case_insensitive: bool,
    equality_selectivity: f64,
    default_selectivity: f64,
) -> f64 {
    let mut chars = pattern.chars();
    let mut has_wildcard = false;
    let mut all_percent = !pattern.is_empty();
    let mut starts_with_percent = false;
    let mut ends_with_percent = false;
    let mut first = true;
    while let Some(ch) = chars.next() {
        let percent = ch == '%';
        if ch == '\\' {
            // Arrow treats a trailing backslash as a literal backslash too.
            chars.next();
        } else if matches!(ch, '%' | '_') {
            has_wildcard = true;
        }
        all_percent &= percent;
        if first {
            starts_with_percent = percent;
            first = false;
        }
        ends_with_percent = percent;
    }
    if all_percent {
        1.0
    } else if !has_wildcard {
        // Case folding may merge several distinct input values, so the raw
        // NDV does not give the selectivity of a literal ILIKE pattern.
        if case_insensitive {
            default_selectivity
        } else {
            equality_selectivity
        }
    } else {
        let start_factor = if starts_with_percent { 1.0 } else { 0.5 };
        let end_factor = if ends_with_percent { 1.0 } else { 0.5 };
        default_selectivity * start_factor * end_factor
    }
}

/// Returns the checked column index, and whether the check is `IS NULL`, when
/// `predicate` is a bare `IS NULL` or `IS NOT NULL` check on a column.
pub(crate) fn null_check_column(
    predicate: &Arc<dyn PhysicalExpr>,
) -> Option<(usize, bool)> {
    let (arg, is_null) = if let Some(expr) = predicate.downcast_ref::<IsNullExpr>() {
        (expr.arg(), true)
    } else {
        let expr = predicate.downcast_ref::<IsNotNullExpr>()?;
        (expr.arg(), false)
    };
    Some((arg.downcast_ref::<Column>()?.index(), is_null))
}

/// Column statistics of an exactly empty output: no nulls, distinct values or
/// bytes, and no value bounds.
fn empty_column_statistics() -> ColumnStatistics {
    ColumnStatistics {
        null_count: Precision::Exact(0),
        distinct_count: Precision::Exact(0),
        byte_size: Precision::Exact(0),
        ..ColumnStatistics::new_unknown()
    }
}

/// Converts an interval bound to a [`Precision`] value. NULL bounds (which
/// represent "unbounded" in the interval type) map to [`Precision::Absent`].
fn interval_bound_to_precision(
    bound: ScalarValue,
    is_exact: bool,
) -> Precision<ScalarValue> {
    if bound.is_null() {
        Precision::Absent
    } else if is_exact {
        Precision::Exact(bound)
    } else {
        Precision::Inexact(bound)
    }
}

/// Caps a row-bounded column statistic (a null count or distinct count) at the
/// filtered row count, since a column cannot have more nulls or distinct values
/// than it has rows. Known counts are demoted to inexact because a
/// filter-derived row bound is normally an estimate, the exception being an
/// exact zero, which proves the column is empty.
fn cap_at_rows(
    value: Precision<usize>,
    filtered_num_rows: Precision<usize>,
) -> Precision<usize> {
    match filtered_num_rows {
        Precision::Absent => value.to_inexact(),
        Precision::Exact(0) => Precision::Exact(0),
        rows => value.to_inexact().min(&rows),
    }
}

/// Scales a byte size by the filter selectivity. An exact zero row count means
/// the output is exactly empty, so the byte size is an exact zero too.
fn scale_byte_size_at_rows(
    byte_size: Precision<usize>,
    selectivity: f64,
    filtered_num_rows: Precision<usize>,
) -> Precision<usize> {
    if filtered_num_rows == Precision::Exact(0) {
        Precision::Exact(0)
    } else {
        byte_size.with_estimated_selectivity(selectivity)
    }
}

/// Returns the NDV for a column constrained to one non-null value (e.g.
/// `column = literal` or a singleton interval), derived from the filtered row
/// estimate: zero rows means zero distinct values, an exact positive row count
/// means exactly one, and an estimated or unknown row count means an inexact
/// one (the column could still be empty).
///
/// The caller is responsible for proving the singleton domain.
fn distinct_count_for_singleton_domain(
    filtered_num_rows: Precision<usize>,
) -> Precision<usize> {
    match filtered_num_rows {
        Precision::Exact(0) | Precision::Inexact(0) => filtered_num_rows,
        Precision::Exact(_) => Precision::Exact(1),
        // The row count is not known exactly, so the column could still be
        // empty (zero distinct values); report an inexact one.
        Precision::Inexact(_) | Precision::Absent => Precision::Inexact(1),
    }
}

/// Builds output column statistics from interval-analysis boundaries.
///
/// The interval bounds become min/max values, singleton intervals become
/// singleton NDV, and row-bounded counts are kept consistent with the filtered
/// row estimate.
fn collect_new_statistics(
    schema: &SchemaRef,
    input_column_stats: &[ColumnStatistics],
    analysis_boundaries: Vec<ExprBoundaries>,
    selectivity: f64,
    null_rejecting_columns: &HashSet<usize>,
    filtered_num_rows: Precision<usize>,
) -> Vec<ColumnStatistics> {
    analysis_boundaries
        .into_iter()
        .enumerate()
        .map(
            |(
                idx,
                ExprBoundaries {
                    interval,
                    distinct_count,
                    ..
                },
            )| {
                let Some(interval) = interval else {
                    // If the interval is `None`, we can say that there are no rows.
                    // Use a typed null to preserve the column's data type, so that
                    // downstream interval analysis can still intersect intervals
                    // of the same type.
                    let typed_null = ScalarValue::try_from(schema.field(idx).data_type())
                        .unwrap_or(ScalarValue::Null);
                    return ColumnStatistics {
                        null_count: Precision::Exact(0),
                        max_value: Precision::Exact(typed_null.clone()),
                        min_value: Precision::Exact(typed_null.clone()),
                        sum_value: Precision::Exact(typed_null),
                        distinct_count: Precision::Exact(0),
                        byte_size: Precision::Exact(0),
                    };
                };
                let (lower, upper) = interval.into_bounds();
                let is_single_value =
                    !lower.is_null() && !upper.is_null() && lower == upper;
                let min_value = interval_bound_to_precision(lower, is_single_value);
                let max_value = interval_bound_to_precision(upper, is_single_value);

                // Distinct and null counts cannot exceed the number of rows
                // that survive the filter. Singleton intervals and
                // null-rejecting predicates provide tighter bounds.
                let capped_distinct_count = if is_single_value {
                    distinct_count_for_singleton_domain(filtered_num_rows)
                } else {
                    cap_at_rows(distinct_count, filtered_num_rows)
                };
                let capped_null_count = if null_rejecting_columns.contains(&idx) {
                    Precision::Exact(0)
                } else {
                    cap_at_rows(input_column_stats[idx].null_count, filtered_num_rows)
                };
                let byte_size = scale_byte_size_at_rows(
                    input_column_stats[idx].byte_size,
                    selectivity,
                    filtered_num_rows,
                );
                ColumnStatistics {
                    null_count: capped_null_count,
                    max_value,
                    min_value,
                    sum_value: Precision::Absent,
                    distinct_count: capped_distinct_count,
                    byte_size,
                }
            },
        )
        .collect()
}

/// The FilterExec streams wraps the input iterator and applies the predicate expression to
/// determine which rows to include in its output batches
struct FilterExecStream {
    /// Output schema after the projection
    schema: SchemaRef,
    /// The expression to filter on. This expression must evaluate to a boolean value.
    predicate: Arc<dyn PhysicalExpr>,
    /// The input partition to filter.
    input: SendableRecordBatchStream,
    /// Runtime metrics recording
    metrics: FilterExecMetrics,
    /// The projection indices of the columns in the input schema
    projection: Option<ProjectionRef>,
    /// Batch coalescer to combine small batches
    batch_coalescer: LimitedBatchCoalescer,
}

/// The metrics for `FilterExec`
struct FilterExecMetrics {
    /// Common metrics for most operators
    baseline_metrics: BaselineMetrics,
    /// Selectivity of the filter, calculated as output_rows / input_rows
    selectivity: RatioMetrics,
    // Remember to update `docs/source/user-guide/metrics.md` when adding new metrics,
    // or modifying metrics comments
}

impl FilterExecMetrics {
    pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
        Self {
            baseline_metrics: BaselineMetrics::new(metrics, partition),
            selectivity: MetricBuilder::new(metrics)
                .with_type(MetricType::Summary)
                .ratio_metrics("selectivity", partition),
        }
    }
}

pub fn batch_filter(
    batch: &RecordBatch,
    predicate: &Arc<dyn PhysicalExpr>,
) -> Result<RecordBatch> {
    filter_and_project(batch, predicate, None)
}

fn filter_and_project(
    batch: &RecordBatch,
    predicate: &Arc<dyn PhysicalExpr>,
    projection: Option<&[usize]>,
) -> Result<RecordBatch> {
    predicate
        .evaluate(batch)
        .and_then(|v| v.into_array(batch.num_rows()))
        .and_then(|array| {
            Ok(match (as_boolean_array(&array), projection) {
                // Apply filter array to record batch
                (Ok(filter_array), None) => filter_record_batch(batch, filter_array)?,
                (Ok(filter_array), Some(projection)) => {
                    let projected_batch = batch.project(projection)?;
                    filter_record_batch(&projected_batch, filter_array)?
                }
                (Err(_), _) => {
                    return internal_err!(
                        "Cannot create filter_array from non-boolean predicates"
                    );
                }
            })
        })
}

impl Stream for FilterExecStream {
    type Item = Result<RecordBatch>;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        let elapsed_compute = self.metrics.baseline_metrics.elapsed_compute().clone();
        loop {
            // If there is a completed batch ready, return it
            if let Some(batch) = self.batch_coalescer.next_completed_batch() {
                self.metrics.selectivity.add_part(batch.num_rows());
                let poll = Poll::Ready(Some(Ok(batch)));
                return self.metrics.baseline_metrics.record_poll(poll);
            }

            if self.batch_coalescer.is_finished() {
                // If input is done and no batches are ready, return None to signal end of stream.
                return Poll::Ready(None);
            }

            // Attempt to pull the next batch from the input stream.
            match ready!(self.input.poll_next_unpin(cx)) {
                None => {
                    self.batch_coalescer.finish()?;
                    // Release the input pipeline's resources.
                    let input_schema = self.input.schema();
                    self.input = Box::pin(EmptyRecordBatchStream::new(input_schema));
                    // continue draining the coalescer
                }
                Some(Ok(batch)) => {
                    let timer = elapsed_compute.timer();
                    let status = self.predicate.as_ref()
                        .evaluate(&batch)
                        .and_then(|v| v.into_array(batch.num_rows()))
                        .and_then(|array| {
                            Ok(match self.projection.as_ref()  {
                                Some(projection) => {
                                    let projected_batch = batch.project(projection)?;
                                    (array, projected_batch)
                                },
                                None => (array, batch)
                            })
                        }).and_then(|(array, batch)| {
                            match as_boolean_array(&array) {
                                Ok(filter_array) => {
                                    self.metrics.selectivity.add_total(batch.num_rows());
                                    let state = self.batch_coalescer.push_batch_with_filter(batch, filter_array)?;
                                    Ok(state)
                                }
                                Err(_) => {
                                    internal_err!(
                                        "Cannot create filter_array from non-boolean predicates"
                                    )
                                }
                            }
                        })?;
                    timer.done();

                    match status {
                        PushBatchStatus::Continue => {
                            // Keep pushing more batches
                        }
                        PushBatchStatus::LimitReached => {
                            // limit was reached, so stop early
                            self.batch_coalescer.finish()?;
                            // Release the input pipeline's resources.
                            let input_schema = self.input.schema();
                            self.input =
                                Box::pin(EmptyRecordBatchStream::new(input_schema));
                            // continue draining the coalescer
                        }
                    }
                }

                // Error case
                other => return Poll::Ready(other),
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        // Same number of record batches
        self.input.size_hint()
    }
}
impl RecordBatchStream for FilterExecStream {
    fn schema(&self) -> SchemaRef {
        Arc::clone(&self.schema)
    }
}

/// Return the equals Column-Pairs and Non-equals Column-Pairs
#[deprecated(
    since = "51.0.0",
    note = "This function will be internal in the future"
)]
pub fn collect_columns_from_predicate(
    predicate: &'_ Arc<dyn PhysicalExpr>,
) -> EqualAndNonEqual<'_> {
    collect_columns_from_predicate_inner(predicate)
}

fn collect_columns_from_predicate_inner(
    predicate: &'_ Arc<dyn PhysicalExpr>,
) -> EqualAndNonEqual<'_> {
    let mut eq_predicate_columns = Vec::<PhysicalExprPairRef>::new();
    let mut ne_predicate_columns = Vec::<PhysicalExprPairRef>::new();

    let predicates = split_conjunction(predicate);
    for p in predicates {
        if let Some(binary) = p.downcast_ref::<BinaryExpr>() {
            // Only extract pairs where at least one side is a Column reference.
            // Pairs like `complex_expr = literal` should not create equivalence
            // classes — the literal could appear in many unrelated expressions
            // (e.g. sort keys), and normalize_expr's deep traversal would
            // replace those occurrences with the complex expression, corrupting
            // sort orderings. Constant propagation for such pairs is handled
            // separately by `extend_constants`.
            let has_direct_column_operand =
                binary.left().downcast_ref::<Column>().is_some()
                    || binary.right().downcast_ref::<Column>().is_some();
            if !has_direct_column_operand {
                continue;
            }
            match binary.op() {
                Operator::Eq => {
                    eq_predicate_columns.push((binary.left(), binary.right()))
                }
                Operator::NotEq => {
                    ne_predicate_columns.push((binary.left(), binary.right()))
                }
                _ => {}
            }
        }
    }

    (eq_predicate_columns, ne_predicate_columns)
}

/// Pair of `Arc<dyn PhysicalExpr>`s
pub type PhysicalExprPairRef<'a> = (&'a Arc<dyn PhysicalExpr>, &'a Arc<dyn PhysicalExpr>);

/// The equals Column-Pairs and Non-equals Column-Pairs in the Predicates
pub type EqualAndNonEqual<'a> =
    (Vec<PhysicalExprPairRef<'a>>, Vec<PhysicalExprPairRef<'a>>);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::collect;
    use crate::empty::EmptyExec;
    use crate::expressions::*;
    use crate::statistics::{StatisticsArgs, StatisticsContext};
    use crate::test;
    use crate::test::exec::StatisticsExec;
    use arrow::array::Int32Array;
    use arrow::datatypes::{Field, Schema, UnionFields, UnionMode};

    #[tokio::test]
    async fn test_filter_exec_fetch_truncates_within_selected_rows() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int32Array::from_iter_values(0..10))],
        )?;
        let input = test::TestMemoryExec::try_new_exec(
            &[vec![batch]],
            Arc::clone(&schema),
            None,
        )?;
        let predicate = binary(col("i", &schema)?, Operator::GtEq, lit(2i32), &schema)?;
        let filter = Arc::new(
            FilterExecBuilder::new(predicate, input)
                .with_fetch(Some(3))
                .build()?,
        );

        let task_ctx = Arc::new(TaskContext::default());
        let batches = collect(filter.execute(0, task_ctx)?).await?;
        let values: Vec<i32> = batches
            .iter()
            .flat_map(|b| {
                b.column(0)
                    .as_any()
                    .downcast_ref::<Int32Array>()
                    .unwrap()
                    .values()
                    .to_vec()
            })
            .collect();
        assert_eq!(values, vec![2, 3, 4]);
        Ok(())
    }

    #[test]
    fn filter_rejects_zero_batch_size() -> Result<()> {
        let input: Arc<dyn ExecutionPlan> =
            Arc::new(EmptyExec::new(Arc::new(Schema::empty())));
        assert!(
            FilterExecBuilder::new(lit(true), Arc::clone(&input))
                .with_batch_size(0)
                .build()
                .is_err()
        );

        let filter = FilterExec::try_new(lit(true), input)?;
        assert!(filter.with_batch_size(0).is_err());
        Ok(())
    }

    #[tokio::test]
    async fn collect_columns_predicates() -> Result<()> {
        let schema = test::aggr_test_schema();
        let predicate: Arc<dyn PhysicalExpr> = binary(
            binary(
                binary(col("c2", &schema)?, Operator::GtEq, lit(1u32), &schema)?,
                Operator::And,
                binary(col("c2", &schema)?, Operator::Eq, lit(4u32), &schema)?,
                &schema,
            )?,
            Operator::And,
            binary(
                binary(
                    col("c2", &schema)?,
                    Operator::Eq,
                    col("c9", &schema)?,
                    &schema,
                )?,
                Operator::And,
                binary(
                    col("c1", &schema)?,
                    Operator::NotEq,
                    col("c13", &schema)?,
                    &schema,
                )?,
                &schema,
            )?,
            &schema,
        )?;

        let (equal_pairs, ne_pairs) = collect_columns_from_predicate_inner(&predicate);
        assert_eq!(2, equal_pairs.len());
        assert!(equal_pairs[0].0.eq(&col("c2", &schema)?));
        assert!(equal_pairs[0].1.eq(&lit(4u32)));

        assert!(equal_pairs[1].0.eq(&col("c2", &schema)?));
        assert!(equal_pairs[1].1.eq(&col("c9", &schema)?));

        assert_eq!(1, ne_pairs.len());
        assert!(ne_pairs[0].0.eq(&col("c1", &schema)?));
        assert!(ne_pairs[0].1.eq(&col("c13", &schema)?));

        Ok(())
    }

    /// An equality on a column that holds each value once matches one row at most,
    /// including on a type interval analysis cannot read, where the default
    /// selectivity would otherwise apply.
    #[tokio::test]
    async fn test_filter_statistics_equality_on_a_unique_column() -> Result<()> {
        let schema = Schema::new(vec![Field::new("id", DataType::Utf8, true)]);
        let unique = ColumnStatistics {
            null_count: Precision::Exact(0),
            distinct_count: Precision::Exact(100),
            ..Default::default()
        };
        let rows = |column: ColumnStatistics| -> Result<Precision<usize>> {
            let input = Arc::new(StatisticsExec::new(
                Statistics {
                    num_rows: Precision::Exact(100),
                    total_byte_size: Precision::Exact(800),
                    column_statistics: vec![column],
                },
                schema.clone(),
            ));
            let predicate =
                binary(col("id", &schema)?, Operator::Eq, lit("seven"), &schema)?;
            let filter: Arc<dyn ExecutionPlan> =
                Arc::new(FilterExec::try_new(predicate, input)?);
            Ok(StatisticsContext::new()
                .compute(filter.as_ref(), &StatisticsArgs::new())?
                .num_rows)
        };

        assert_eq!(rows(unique.clone())?, Precision::Inexact(1));

        // The nulls a unique column may repeat do not make it hold a value twice.
        assert_eq!(
            rows(ColumnStatistics {
                null_count: Precision::Exact(10),
                distinct_count: Precision::Exact(90),
                ..unique.clone()
            })?,
            Precision::Inexact(1)
        );

        // Without a distinct count, the default selectivity applies as before.
        assert_eq!(
            rows(ColumnStatistics {
                distinct_count: Precision::Absent,
                ..unique
            })?,
            Precision::Inexact(20)
        );

        Ok(())
    }

    /// Asking a unique column for three values matches three rows at most.
    #[tokio::test]
    async fn test_filter_statistics_in_list_on_a_unique_column() -> Result<()> {
        use datafusion_physical_expr::expressions::in_list;

        let schema = Schema::new(vec![Field::new("id", DataType::Utf8, true)]);
        let rows = |list: Vec<&str>, negated: bool| -> Result<Precision<usize>> {
            let input = Arc::new(StatisticsExec::new(
                Statistics {
                    num_rows: Precision::Exact(100),
                    total_byte_size: Precision::Exact(800),
                    column_statistics: vec![ColumnStatistics {
                        null_count: Precision::Exact(0),
                        distinct_count: Precision::Exact(100),
                        ..Default::default()
                    }],
                },
                schema.clone(),
            ));
            let predicate = in_list(
                col("id", &schema)?,
                list.into_iter().map(|value| lit(value) as _).collect(),
                &negated,
                &schema,
            )?;
            let filter: Arc<dyn ExecutionPlan> =
                Arc::new(FilterExec::try_new(predicate, input)?);
            Ok(StatisticsContext::new()
                .compute(filter.as_ref(), &StatisticsArgs::new())?
                .num_rows)
        };

        assert_eq!(rows(vec!["a", "b", "c"], false)?, Precision::Inexact(3));
        // Repeats ask for the same row twice.
        assert_eq!(rows(vec!["a", "b", "a"], false)?, Precision::Inexact(2));
        // `NOT IN` selects nearly everything, so the default applies.
        assert_eq!(rows(vec!["a", "b", "c"], true)?, Precision::Inexact(20));

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_basic_expr() -> Result<()> {
        // Table:
        //      a: min=1, max=100
        let bytes_per_row = 4;
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(100 * bytes_per_row),
                column_statistics: vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        // a <= 25
        let predicate: Arc<dyn PhysicalExpr> =
            binary(col("a", &schema)?, Operator::LtEq, lit(25i32), &schema)?;

        // WHERE a <= 25
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);

        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Inexact(25));
        assert_eq!(
            statistics.total_byte_size,
            Precision::Inexact(25 * bytes_per_row)
        );
        assert_eq!(
            statistics.column_statistics,
            vec![ColumnStatistics {
                // `a <= 25` rejects nulls, so the column has no surviving nulls.
                null_count: Precision::Exact(0),
                min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                max_value: Precision::Inexact(ScalarValue::Int32(Some(25))),
                ..Default::default()
            }]
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_column_level_nested() -> Result<()> {
        // Table:
        //      a: min=1, max=100
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                column_statistics: vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                    ..Default::default()
                }],
                total_byte_size: Precision::Absent,
            },
            schema.clone(),
        ));

        // WHERE a <= 25
        let sub_filter: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(
            binary(col("a", &schema)?, Operator::LtEq, lit(25i32), &schema)?,
            input,
        )?);

        // Nested filters (two separate physical plans, instead of AND chain in the expr)
        // WHERE a >= 10
        // WHERE a <= 25
        let filter: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(
            binary(col("a", &schema)?, Operator::GtEq, lit(10i32), &schema)?,
            sub_filter,
        )?);

        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Inexact(16));
        assert_eq!(
            statistics.column_statistics,
            vec![ColumnStatistics {
                // `a <= 25 AND a >= 10` rejects nulls in `a`.
                null_count: Precision::Exact(0),
                min_value: Precision::Inexact(ScalarValue::Int32(Some(10))),
                max_value: Precision::Inexact(ScalarValue::Int32(Some(25))),
                ..Default::default()
            }]
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_column_level_nested_multiple() -> Result<()> {
        // Table:
        //      a: min=1, max=100
        //      b: min=1, max=50
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(50))),
                        ..Default::default()
                    },
                ],
                total_byte_size: Precision::Absent,
            },
            schema.clone(),
        ));

        // WHERE a <= 25
        let a_lte_25: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(
            binary(col("a", &schema)?, Operator::LtEq, lit(25i32), &schema)?,
            input,
        )?);

        // WHERE b > 45
        let b_gt_5: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(
            binary(col("b", &schema)?, Operator::Gt, lit(45i32), &schema)?,
            a_lte_25,
        )?);

        // WHERE a >= 10
        let filter: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(
            binary(col("a", &schema)?, Operator::GtEq, lit(10i32), &schema)?,
            b_gt_5,
        )?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        // On a uniform distribution, only fifteen rows will satisfy the
        // filter that 'a' proposed (a >= 10 AND a <= 25) (15/100) and only
        // 5 rows will satisfy the filter that 'b' proposed (b > 45) (5/50).
        //
        // Which would result with a selectivity of  '15/100 * 5/50' or 0.015
        // and that means about %1.5 of the all rows (rounded up to 2 rows).
        assert_eq!(statistics.num_rows, Precision::Inexact(2));
        assert_eq!(
            statistics.column_statistics,
            vec![
                ColumnStatistics {
                    // `a <= 25 AND a >= 10` rejects nulls in `a`.
                    null_count: Precision::Exact(0),
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(10))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(25))),
                    ..Default::default()
                },
                ColumnStatistics {
                    // `b > 45` in the upstream filter zeroes b's nulls; the outer
                    // filter then caps the (already zero) count, demoting to inexact.
                    null_count: Precision::Inexact(0),
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(46))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(50))),
                    ..Default::default()
                }
            ]
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_when_input_stats_missing() -> Result<()> {
        // Table:
        //      a: min=???, max=??? (missing)
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics::new_unknown(&schema),
            schema.clone(),
        ));

        // a <= 25
        let predicate: Arc<dyn PhysicalExpr> =
            binary(col("a", &schema)?, Operator::LtEq, lit(25i32), &schema)?;

        // WHERE a <= 25
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);

        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Absent);

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_multiple_columns() -> Result<()> {
        // Table:
        //      a: min=1, max=100
        //      b: min=1, max=3
        //      c: min=1000.0  max=1100.0
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Float32, false),
        ]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(4000),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(3))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Float32(Some(1000.0))),
                        max_value: Precision::Inexact(ScalarValue::Float32(Some(1100.0))),
                        ..Default::default()
                    },
                ],
            },
            schema,
        ));
        // WHERE a<=53 AND (b=3 AND (c<=1075.0 AND a>b))
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(BinaryExpr::new(
                Arc::new(Column::new("a", 0)),
                Operator::LtEq,
                Arc::new(Literal::new(ScalarValue::Int32(Some(53)))),
            )),
            Operator::And,
            Arc::new(BinaryExpr::new(
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("b", 1)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(3)))),
                )),
                Operator::And,
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("c", 2)),
                        Operator::LtEq,
                        Arc::new(Literal::new(ScalarValue::Float32(Some(1075.0)))),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Gt,
                        Arc::new(Column::new("b", 1)),
                    )),
                )),
            )),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        // 0.5 (from a) * 0.333333... (from b) * 0.798387... (from c) ≈ 0.1330...
        // num_rows after ceil => 133.0... => 134
        // total_byte_size after ceil => 532.0... => 533
        assert_eq!(statistics.num_rows, Precision::Inexact(134));
        assert_eq!(statistics.total_byte_size, Precision::Inexact(533));
        let exp_col_stats = vec![
            ColumnStatistics {
                min_value: Precision::Inexact(ScalarValue::Int32(Some(4))),
                max_value: Precision::Inexact(ScalarValue::Int32(Some(53))),
                ..Default::default()
            },
            ColumnStatistics {
                min_value: Precision::Inexact(ScalarValue::Int32(Some(3))),
                max_value: Precision::Inexact(ScalarValue::Int32(Some(3))),
                ..Default::default()
            },
            ColumnStatistics {
                min_value: Precision::Inexact(ScalarValue::Float32(Some(1000.0))),
                max_value: Precision::Inexact(ScalarValue::Float32(Some(1075.0))),
                ..Default::default()
            },
        ];
        let _ = exp_col_stats
            .into_iter()
            .zip(statistics.column_statistics.clone())
            .map(|(expected, actual)| {
                if let Some(val) = actual.min_value.get_value() {
                    if val.data_type().is_floating() {
                        // Windows rounds arithmetic operation results differently for floating point numbers.
                        // Therefore, we check if the actual values are in an epsilon range.
                        let actual_min = actual.min_value.get_value().unwrap();
                        let actual_max = actual.max_value.get_value().unwrap();
                        let expected_min = expected.min_value.get_value().unwrap();
                        let expected_max = expected.max_value.get_value().unwrap();
                        let eps = ScalarValue::Float32(Some(1e-6));

                        assert!(actual_min.sub(expected_min).unwrap() < eps);
                        assert!(actual_min.sub(expected_min).unwrap() < eps);

                        assert!(actual_max.sub(expected_max).unwrap() < eps);
                        assert!(actual_max.sub(expected_max).unwrap() < eps);
                    } else {
                        assert_eq!(actual, expected);
                    }
                } else {
                    assert_eq!(actual, expected);
                }
            });

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_full_selective() -> Result<()> {
        // Table:
        //      a: min=1, max=100
        //      b: min=1, max=3
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(4000),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(3))),
                        ..Default::default()
                    },
                ],
            },
            schema,
        ));
        // WHERE a<200 AND 1<=b
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(BinaryExpr::new(
                Arc::new(Column::new("a", 0)),
                Operator::Lt,
                Arc::new(Literal::new(ScalarValue::Int32(Some(200)))),
            )),
            Operator::And,
            Arc::new(BinaryExpr::new(
                Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
                Operator::LtEq,
                Arc::new(Column::new("b", 1)),
            )),
        ));
        // The filter predicate passes all (non-null) entries, so min/max/NDV
        // are unchanged. `a < 200` and `1 <= b` are null-rejecting, though, so
        // both columns lose any nulls regardless of selectivity.
        let mut expected = StatisticsContext::new()
            .compute(input.as_ref(), &StatisticsArgs::new())?
            .column_statistics
            .clone();
        for col in &mut expected {
            col.null_count = Precision::Exact(0);
        }
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;

        assert_eq!(statistics.num_rows, Precision::Inexact(1000));
        assert_eq!(statistics.total_byte_size, Precision::Inexact(4000));
        assert_eq!(statistics.column_statistics, expected);

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_zero_selective() -> Result<()> {
        // Table:
        //      a: min=1, max=100
        //      b: min=1, max=3
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(4000),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(3))),
                        ..Default::default()
                    },
                ],
            },
            schema,
        ));
        // WHERE a>200 AND 1<=b
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(BinaryExpr::new(
                Arc::new(Column::new("a", 0)),
                Operator::Gt,
                Arc::new(Literal::new(ScalarValue::Int32(Some(200)))),
            )),
            Operator::And,
            Arc::new(BinaryExpr::new(
                Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
                Operator::LtEq,
                Arc::new(Column::new("b", 1)),
            )),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;

        assert_eq!(statistics.num_rows, Precision::Inexact(0));
        assert_eq!(statistics.total_byte_size, Precision::Inexact(0));
        assert_eq!(
            statistics.column_statistics,
            vec![
                ColumnStatistics {
                    min_value: Precision::Exact(ScalarValue::Int32(None)),
                    max_value: Precision::Exact(ScalarValue::Int32(None)),
                    sum_value: Precision::Exact(ScalarValue::Int32(None)),
                    distinct_count: Precision::Exact(0),
                    null_count: Precision::Exact(0),
                    byte_size: Precision::Exact(0),
                },
                ColumnStatistics {
                    min_value: Precision::Exact(ScalarValue::Int32(None)),
                    max_value: Precision::Exact(ScalarValue::Int32(None)),
                    sum_value: Precision::Exact(ScalarValue::Int32(None)),
                    distinct_count: Precision::Exact(0),
                    null_count: Precision::Exact(0),
                    byte_size: Precision::Exact(0),
                },
            ]
        );

        Ok(())
    }

    /// Regression test: stacking two FilterExecs where the inner filter
    /// proves zero selectivity should not panic with a type mismatch
    /// during interval intersection.
    ///
    /// Previously, when a filter proved no rows could match, the column
    /// statistics used untyped `ScalarValue::Null` (data type `Null`).
    /// If an outer FilterExec then tried to analyze its own predicate
    /// against those statistics, `Interval::intersect` would fail with:
    ///   "Only intervals with the same data type are intersectable, lhs:Null, rhs:Int32"
    #[tokio::test]
    async fn test_nested_filter_with_zero_selectivity_inner() -> Result<()> {
        // Inner table: a: [1, 100], b: [1, 3]
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(4000),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(3))),
                        ..Default::default()
                    },
                ],
            },
            schema,
        ));

        // Inner filter: a > 200 (impossible given a max=100 → zero selectivity)
        let inner_predicate: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(200)))),
        ));
        let inner_filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(inner_predicate, input)?);

        // Outer filter: a = 50
        // Before the fix, this would panic because the inner filter's
        // zero-selectivity statistics produced Null-typed intervals for
        // column `a`, which couldn't intersect with the Int32 literal.
        let outer_predicate: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(50)))),
        ));
        let outer_filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(outer_predicate, inner_filter)?);

        // Should succeed without error
        let statistics = StatisticsContext::new()
            .compute(outer_filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Inexact(0));

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_more_inputs() -> Result<()> {
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(4000),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                ],
            },
            schema,
        ));
        // WHERE a<50
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Lt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(50)))),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;

        assert_eq!(statistics.num_rows, Precision::Inexact(490));
        assert_eq!(statistics.total_byte_size, Precision::Inexact(1960));
        assert_eq!(
            statistics.column_statistics,
            vec![
                ColumnStatistics {
                    // `a < 50` rejects nulls in `a`.
                    null_count: Precision::Exact(0),
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(49))),
                    ..Default::default()
                },
                // `b` is not referenced by the predicate, so its stats are
                // unchanged (null count stays unknown).
                ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                    ..Default::default()
                },
            ]
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_empty_input_statistics() -> Result<()> {
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics::new_unknown(&schema),
            schema,
        ));
        // WHERE a <= 10 AND 0 <= a - 5
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(BinaryExpr::new(
                Arc::new(Column::new("a", 0)),
                Operator::LtEq,
                Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
            )),
            Operator::And,
            Arc::new(BinaryExpr::new(
                Arc::new(Literal::new(ScalarValue::Int32(Some(0)))),
                Operator::LtEq,
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("a", 0)),
                    Operator::Minus,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
                )),
            )),
        ));
        // i32::MIN also satisfies this predicate because subtracting 5 wraps.
        // A mathematical lower bound of 5 would exclude a valid input value.
        let batch = RecordBatch::try_new(
            input.schema(),
            vec![Arc::new(Int32Array::from(vec![i32::MIN]))],
        )
        .unwrap();
        let result = predicate.evaluate(&batch).unwrap().into_array(1).unwrap();
        assert_eq!(
            result.as_ref(),
            &arrow::array::BooleanArray::from(vec![true])
        );
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let filter_statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;

        let expected_filter_statistics = Statistics {
            num_rows: Precision::Absent,
            total_byte_size: Precision::Absent,
            column_statistics: vec![ColumnStatistics {
                // `a <= 10` rejects nulls, so `a` has no surviving nulls even
                // though the input statistics are entirely unknown.
                null_count: Precision::Exact(0),
                min_value: Precision::Absent,
                max_value: Precision::Inexact(ScalarValue::Int32(Some(10))),
                sum_value: Precision::Absent,
                distinct_count: Precision::Absent,
                byte_size: Precision::Absent,
            }],
        };

        assert_eq!(*filter_statistics, expected_filter_statistics);

        Ok(())
    }

    #[tokio::test]
    async fn test_statistics_with_constant_column() -> Result<()> {
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics::new_unknown(&schema),
            schema,
        ));
        // WHERE a = 10
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let filter_statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        // First column is "a", and it is a column with only one value after the filter.
        assert!(filter_statistics.column_statistics[0].is_singleton());

        Ok(())
    }

    #[tokio::test]
    async fn test_validation_filter_selectivity() -> Result<()> {
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics::new_unknown(&schema),
            schema,
        ));
        // WHERE a = 10
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        ));
        let filter = FilterExec::try_new(predicate, input)?;
        assert!(filter.with_default_selectivity(120).is_err());
        Ok(())
    }

    #[tokio::test]
    async fn test_custom_filter_selectivity() -> Result<()> {
        // Need a decimal to trigger inexact selectivity
        let schema =
            Schema::new(vec![Field::new("a", DataType::Decimal128(2, 3), false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(4000),
                column_statistics: vec![ColumnStatistics::default()],
            },
            schema,
        ));
        // WHERE a = 10
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Decimal128(Some(10), 10, 10))),
        ));
        let filter = FilterExec::try_new(predicate, input)?;
        let statistics =
            StatisticsContext::new().compute(&filter, &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Inexact(200));
        assert_eq!(statistics.total_byte_size, Precision::Inexact(800));
        let filter = filter.with_default_selectivity(40)?;
        let statistics =
            StatisticsContext::new().compute(&filter, &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Inexact(400));
        assert_eq!(statistics.total_byte_size, Precision::Inexact(1600));
        Ok(())
    }

    #[test]
    fn test_equivalence_properties_union_type() -> Result<()> {
        let union_type = DataType::Union(
            UnionFields::try_new(
                vec![0, 1],
                vec![
                    Field::new("f1", DataType::Int32, true),
                    Field::new("f2", DataType::Utf8, true),
                ],
            )
            .unwrap(),
            UnionMode::Sparse,
        );

        let schema = Arc::new(Schema::new(vec![
            Field::new("c1", DataType::Int32, true),
            Field::new("c2", union_type, true),
        ]));

        let exec = FilterExec::try_new(
            binary(
                binary(col("c1", &schema)?, Operator::GtEq, lit(1i32), &schema)?,
                Operator::And,
                binary(col("c1", &schema)?, Operator::LtEq, lit(4i32), &schema)?,
                &schema,
            )?,
            Arc::new(EmptyExec::new(Arc::clone(&schema))),
        )?;

        StatisticsContext::new()
            .compute(&exec, &StatisticsArgs::new())
            .unwrap();

        Ok(())
    }

    #[tokio::test]
    async fn test_builder_with_projection() -> Result<()> {
        // Create a schema with multiple columns
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Int32, false),
        ]));

        let input = Arc::new(EmptyExec::new(Arc::clone(&schema)));

        // Create a filter predicate: a > 10
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        ));

        // Create filter with projection [0, 2] (columns a and c) using builder
        let projection = Some(vec![0, 2]);
        let filter = FilterExecBuilder::new(predicate, input)
            .apply_projection(projection.clone())
            .unwrap()
            .build()?;

        // Verify projection is set correctly
        assert_eq!(filter.projection(), &Some([0, 2].into()));

        // Verify schema contains only projected columns
        let output_schema = filter.schema();
        assert_eq!(output_schema.fields().len(), 2);
        assert_eq!(output_schema.field(0).name(), "a");
        assert_eq!(output_schema.field(1).name(), "c");

        Ok(())
    }

    #[tokio::test]
    async fn test_builder_without_projection() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]));

        let input = Arc::new(EmptyExec::new(Arc::clone(&schema)));

        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
        ));

        // Create filter without projection using builder
        let filter = FilterExecBuilder::new(predicate, input).build()?;

        // Verify no projection is set
        assert!(filter.projection().is_none());

        // Verify schema contains all columns
        let output_schema = filter.schema();
        assert_eq!(output_schema.fields().len(), 2);

        Ok(())
    }

    #[tokio::test]
    async fn test_builder_invalid_projection() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]));

        let input = Arc::new(EmptyExec::new(Arc::clone(&schema)));

        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
        ));

        // Try to create filter with invalid projection (index out of bounds) using builder
        let result =
            FilterExecBuilder::new(predicate, input).apply_projection(Some(vec![0, 5])); // 5 is out of bounds

        // Should return an error
        assert!(result.is_err());

        Ok(())
    }

    #[tokio::test]
    async fn test_builder_vs_with_projection() -> Result<()> {
        // This test verifies that the builder with projection produces the same result
        // as try_new().with_projection(), but more efficiently (one compute_properties call)
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Int32, false),
            Field::new("d", DataType::Int32, false),
        ]);

        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(4000),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                    ColumnStatistics::default(),
                    ColumnStatistics::default(),
                    ColumnStatistics::default(),
                ],
            },
            schema,
        ));
        let input: Arc<dyn ExecutionPlan> = input;

        let predicate: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Lt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(50)))),
        ));

        let projection = Some(vec![0, 2]);

        // Method 1: Builder with projection (one call to compute_properties)
        let filter1 = FilterExecBuilder::new(Arc::clone(&predicate), Arc::clone(&input))
            .apply_projection(projection.clone())
            .unwrap()
            .build()?;

        // Method 2: Also using builder for comparison (deprecated try_new().with_projection() removed)
        let filter2 = FilterExecBuilder::new(predicate, input)
            .apply_projection(projection)
            .unwrap()
            .build()?;

        // Both methods should produce equivalent results
        assert_eq!(filter1.schema(), filter2.schema());
        assert_eq!(filter1.projection(), filter2.projection());

        // Verify statistics are the same
        let stats1 =
            StatisticsContext::new().compute(&filter1, &StatisticsArgs::new())?;
        let stats2 =
            StatisticsContext::new().compute(&filter2, &StatisticsArgs::new())?;
        assert_eq!(stats1.num_rows, stats2.num_rows);
        assert_eq!(stats1.total_byte_size, stats2.total_byte_size);

        Ok(())
    }

    #[tokio::test]
    async fn test_builder_statistics_with_projection() -> Result<()> {
        // Test that statistics are correctly computed when using builder with projection
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Int32, false),
        ]);

        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(12000),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(10))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(200))),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(5))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(50))),
                        ..Default::default()
                    },
                ],
            },
            schema,
        ));

        // Filter: a < 50, Project: [0, 2]
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Lt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(50)))),
        ));

        let filter = FilterExecBuilder::new(predicate, input)
            .apply_projection(Some(vec![0, 2]))
            .unwrap()
            .build()?;

        let statistics =
            StatisticsContext::new().compute(&filter, &StatisticsArgs::new())?;

        // Verify statistics reflect both filtering and projection
        assert!(matches!(statistics.num_rows, Precision::Inexact(_)));

        // Schema should only have 2 columns after projection
        assert_eq!(filter.schema().fields().len(), 2);

        Ok(())
    }

    #[test]
    fn test_builder_predicate_validation() -> Result<()> {
        // Test that builder validates predicate type correctly
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]));

        let input = Arc::new(EmptyExec::new(Arc::clone(&schema)));

        // Create a predicate that doesn't return boolean (returns Int32)
        let invalid_predicate = Arc::new(Column::new("a", 0));

        // Should fail because predicate doesn't return boolean
        let result = FilterExecBuilder::new(invalid_predicate, input)
            .apply_projection(Some(vec![0]))
            .unwrap()
            .build();

        assert!(result.is_err());

        Ok(())
    }

    #[tokio::test]
    async fn test_builder_projection_composition() -> Result<()> {
        // Test that calling apply_projection multiple times composes projections
        // If initial projection is [0, 2, 3] and we call apply_projection([0, 2]),
        // the result should be [0, 3] (indices 0 and 2 of [0, 2, 3])
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Int32, false),
            Field::new("d", DataType::Int32, false),
        ]));

        let input = Arc::new(EmptyExec::new(Arc::clone(&schema)));

        // Create a filter predicate: a > 10
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        ));

        // First projection: [0, 2, 3] -> select columns a, c, d
        // Second projection: [0, 2] -> select indices 0 and 2 of [0, 2, 3] -> [0, 3]
        // Final result: columns a and d
        let filter = FilterExecBuilder::new(predicate, input)
            .apply_projection(Some(vec![0, 2, 3]))?
            .apply_projection(Some(vec![0, 2]))?
            .build()?;

        // Verify composed projection is [0, 3]
        assert_eq!(filter.projection(), &Some([0, 3].into()));

        // Verify schema contains only columns a and d
        let output_schema = filter.schema();
        assert_eq!(output_schema.fields().len(), 2);
        assert_eq!(output_schema.field(0).name(), "a");
        assert_eq!(output_schema.field(1).name(), "d");

        Ok(())
    }

    #[tokio::test]
    async fn test_builder_projection_composition_none_clears() -> Result<()> {
        // Test that passing None clears the projection
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]));

        let input = Arc::new(EmptyExec::new(Arc::clone(&schema)));

        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        ));

        // Set a projection then clear it with None
        let filter = FilterExecBuilder::new(predicate, input)
            .apply_projection(Some(vec![0]))?
            .apply_projection(None)?
            .build()?;

        // Projection should be cleared
        assert_eq!(filter.projection(), &None);

        // Schema should have all columns
        let output_schema = filter.schema();
        assert_eq!(output_schema.fields().len(), 2);

        Ok(())
    }

    #[test]
    fn test_filter_with_projection_remaps_post_phase_parent_filters() -> Result<()> {
        // Test that FilterExec with a projection must remap parent dynamic
        // filter column indices from its output schema to the input schema
        // before passing them to the child.
        let input_schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Utf8, false),
            Field::new("c", DataType::Float64, false),
        ]));
        let input = Arc::new(EmptyExec::new(Arc::clone(&input_schema)));

        // FilterExec: a > 0, projection=[c@2]
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(0)))),
        ));
        let filter = FilterExecBuilder::new(predicate, input)
            .apply_projection(Some(vec![2]))?
            .build()?;

        // Output schema should be [c:Float64]
        let output_schema = filter.schema();
        assert_eq!(output_schema.fields().len(), 1);
        assert_eq!(output_schema.field(0).name(), "c");

        // Simulate a parent dynamic filter referencing output column c@0
        let parent_filter: Arc<dyn PhysicalExpr> = Arc::new(Column::new("c", 0));

        let config = ConfigOptions::new();
        let desc = filter.gather_filters_for_pushdown(
            FilterPushdownPhase::Post,
            vec![parent_filter],
            &config,
        )?;

        // The filter pushed to the child must reference c@2 (input schema),
        // not c@0 (output schema).
        let parent_filters = desc.parent_filters();
        assert_eq!(parent_filters.len(), 1); // one child
        assert_eq!(parent_filters[0].len(), 1); // one filter
        let remapped = &parent_filters[0][0].predicate;
        let display = format!("{remapped}");
        assert_eq!(
            display, "c@2",
            "Post-phase parent filter column index must be remapped \
             from output schema (c@0) to input schema (c@2)"
        );

        Ok(())
    }

    /// Regression test for https://github.com/apache/datafusion/issues/20194
    ///
    /// `collect_columns_from_predicate_inner` should only extract equality
    /// pairs where at least one side is a Column. Pairs like
    /// `complex_expr = literal` must not create equivalence classes because
    /// `normalize_expr`'s deep traversal would replace the literal inside
    /// unrelated expressions (e.g. sort keys) with the complex expression.
    #[test]
    fn test_collect_columns_skips_non_column_pairs() -> Result<()> {
        let schema = test::aggr_test_schema();

        // Simulate: nvl(c2, 0) = 0  →  (c2 IS DISTINCT FROM 0) = 0
        // Neither side is a Column, so this should NOT be extracted.
        let complex_expr: Arc<dyn PhysicalExpr> = binary(
            col("c2", &schema)?,
            Operator::IsDistinctFrom,
            lit(0u32),
            &schema,
        )?;
        let predicate: Arc<dyn PhysicalExpr> =
            binary(complex_expr, Operator::Eq, lit(0u32), &schema)?;

        let (equal_pairs, _) = collect_columns_from_predicate_inner(&predicate);
        assert_eq!(
            0,
            equal_pairs.len(),
            "Should not extract equality pairs where neither side is a Column"
        );

        // But col = literal should still be extracted
        let predicate: Arc<dyn PhysicalExpr> =
            binary(col("c2", &schema)?, Operator::Eq, lit(0u32), &schema)?;
        let (equal_pairs, _) = collect_columns_from_predicate_inner(&predicate);
        assert_eq!(
            1,
            equal_pairs.len(),
            "Should extract equality pairs where one side is a Column"
        );

        Ok(())
    }

    /// Columns with Absent min/max statistics should remain Absent after
    /// FilterExec.
    #[tokio::test]
    async fn test_filter_statistics_absent_columns_stay_absent() -> Result<()> {
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Absent,
                column_statistics: vec![
                    ColumnStatistics::default(),
                    ColumnStatistics::default(),
                ],
            },
            schema.clone(),
        ));

        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);

        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        let col_b_stats = &statistics.column_statistics[1];
        assert_eq!(col_b_stats.min_value, Precision::Absent);
        assert_eq!(col_b_stats.max_value, Precision::Absent);

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_equality_ndv() -> Result<()> {
        #[expect(clippy::type_complexity)]
        let cases: Vec<(
            &str,
            Vec<Field>,
            Vec<ColumnStatistics>,
            Arc<dyn PhysicalExpr>,
            Vec<Precision<usize>>,
        )> = vec![
            (
                "utf8 equality",
                vec![Field::new("name", DataType::Utf8, false)],
                vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(50),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("name", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Utf8(Some("hello".to_string())))),
                )),
                vec![Precision::Inexact(1)],
            ),
            (
                "utf8view equality",
                vec![Field::new("name", DataType::Utf8View, false)],
                vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(50),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("name", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Utf8View(Some(
                        "hello".to_string(),
                    )))),
                )),
                vec![Precision::Inexact(1)],
            ),
            (
                "largeutf8 equality",
                vec![Field::new("name", DataType::LargeUtf8, false)],
                vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(50),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("name", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::LargeUtf8(Some(
                        "hello".to_string(),
                    )))),
                )),
                vec![Precision::Inexact(1)],
            ),
            (
                "utf8 reversed (literal = column)",
                vec![Field::new("name", DataType::Utf8, false)],
                vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(50),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(Literal::new(ScalarValue::Utf8(Some("hello".to_string())))),
                    Operator::Eq,
                    Arc::new(Column::new("name", 0)),
                )),
                vec![Precision::Inexact(1)],
            ),
            (
                "OR is not collapsed to NDV=1, but NDV is capped at filtered rows",
                vec![Field::new("name", DataType::Utf8, false)],
                vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(50),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("name", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Utf8(Some("a".to_string())))),
                    )),
                    Operator::Or,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("name", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Utf8(Some("b".to_string())))),
                    )),
                )),
                // Input NDV is 50, but the 20% default selectivity on 100 rows
                // estimates 20 output rows, so NDV is capped at 20.
                vec![Precision::Inexact(20)],
            ),
            (
                "AND with mixed types (Utf8 + Int32)",
                vec![
                    Field::new("name", DataType::Utf8, false),
                    Field::new("age", DataType::Int32, false),
                ],
                vec![
                    ColumnStatistics {
                        distinct_count: Precision::Inexact(50),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        distinct_count: Precision::Inexact(80),
                        ..Default::default()
                    },
                ],
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("name", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Utf8(Some(
                            "hello".to_string(),
                        )))),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("age", 1)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                    )),
                )),
                vec![Precision::Inexact(1), Precision::Inexact(1)],
            ),
            (
                "numeric equality with min/max bounds (interval analysis path)",
                vec![Field::new("a", DataType::Int32, false)],
                vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                    distinct_count: Precision::Inexact(80),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("a", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                )),
                vec![Precision::Inexact(1)],
            ),
            (
                "timestamp equality",
                vec![Field::new(
                    "ts",
                    DataType::Timestamp(arrow::datatypes::TimeUnit::Nanosecond, None),
                    false,
                )],
                vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(500),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("ts", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::TimestampNanosecond(
                        Some(1_609_459_200_000_000_000),
                        None,
                    ))),
                )),
                vec![Precision::Inexact(1)],
            ),
            (
                "contradictory numeric equality (infeasible)",
                vec![Field::new("a", DataType::Int32, false)],
                vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(50),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(99)))),
                    )),
                )),
                vec![Precision::Exact(0)],
            ),
            (
                "utf8 equality with absent input NDV",
                vec![Field::new("name", DataType::Utf8, false)],
                vec![ColumnStatistics {
                    distinct_count: Precision::Absent,
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("name", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Utf8(Some("hello".to_string())))),
                )),
                vec![Precision::Inexact(1)],
            ),
            (
                "contradictory utf8 equality (infeasible)",
                vec![Field::new("name", DataType::Utf8, false)],
                vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(100),
                    ..Default::default()
                }],
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("name", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Utf8(Some(
                            "alice".to_string(),
                        )))),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("name", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Utf8(Some(
                            "bob".to_string(),
                        )))),
                    )),
                )),
                vec![Precision::Exact(0)],
            ),
            (
                "redundant same-value equality combined with another column",
                vec![
                    Field::new("a", DataType::Int32, false),
                    Field::new("b", DataType::Int32, false),
                ],
                vec![
                    ColumnStatistics {
                        distinct_count: Precision::Inexact(80),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        distinct_count: Precision::Inexact(40),
                        ..Default::default()
                    },
                ],
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(BinaryExpr::new(
                            Arc::new(Column::new("a", 0)),
                            Operator::Eq,
                            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
                        )),
                        Operator::And,
                        Arc::new(BinaryExpr::new(
                            Arc::new(Column::new("a", 0)),
                            Operator::Eq,
                            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
                        )),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("b", 1)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(2)))),
                    )),
                )),
                vec![Precision::Inexact(1), Precision::Inexact(1)],
            ),
        ];

        for (desc, fields, col_stats, predicate, expected_ndvs) in cases {
            let schema = Schema::new(fields);
            let input = Arc::new(StatisticsExec::new(
                Statistics {
                    num_rows: Precision::Inexact(100),
                    total_byte_size: Precision::Inexact(1000),
                    column_statistics: col_stats,
                },
                schema.clone(),
            ));
            let filter: Arc<dyn ExecutionPlan> =
                Arc::new(FilterExec::try_new(predicate, input)?);
            let statistics = StatisticsContext::new()
                .compute(filter.as_ref(), &StatisticsArgs::new())?;

            for (i, expected) in expected_ndvs.iter().enumerate() {
                assert_eq!(
                    statistics.column_statistics[i].distinct_count, *expected,
                    "case '{desc}': column {i} NDV mismatch"
                );
            }
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_preserves_exactly_empty_input() -> Result<()> {
        // A satisfiable predicate over an exactly empty input: the filter cannot
        // produce rows, so the whole estimate stays exact. Column `b` is not
        // mentioned by the predicate, so its null and distinct counts go through
        // the generic row cap.
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, true),
            Field::new("b", DataType::Int32, true),
        ]);
        let input_stats = Statistics {
            num_rows: Precision::Exact(0),
            total_byte_size: Precision::Exact(0),
            column_statistics: vec![
                ColumnStatistics {
                    null_count: Precision::Exact(0),
                    byte_size: Precision::Exact(0),
                    ..Default::default()
                },
                ColumnStatistics {
                    null_count: Precision::Exact(3),
                    distinct_count: Precision::Exact(7),
                    byte_size: Precision::Exact(0),
                    ..Default::default()
                },
            ],
        };
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
        ));

        let input = Arc::new(StatisticsExec::new(input_stats, schema.clone()));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;

        assert_eq!(statistics.num_rows, Precision::Exact(0));
        assert_eq!(statistics.total_byte_size, Precision::Exact(0));
        assert_eq!(
            statistics.column_statistics[0].byte_size,
            Precision::Exact(0)
        );
        assert_eq!(
            statistics.column_statistics[1].null_count,
            Precision::Exact(0)
        );
        assert_eq!(
            statistics.column_statistics[1].distinct_count,
            Precision::Exact(0)
        );

        // A contradictory predicate (`a = 1 AND a = 2`) discards all rows, the
        // output is empty independently of the input.
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(8000),
                column_statistics: vec![ColumnStatistics::new_unknown(); 2],
            },
            schema,
        ));
        let contradiction = Arc::new(BinaryExpr::new(
            Arc::new(BinaryExpr::new(
                Arc::new(Column::new("a", 0)),
                Operator::Eq,
                Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
            )),
            Operator::And,
            Arc::new(BinaryExpr::new(
                Arc::new(Column::new("a", 0)),
                Operator::Eq,
                Arc::new(Literal::new(ScalarValue::Int32(Some(2)))),
            )),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(contradiction, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;

        assert_eq!(statistics.num_rows, Precision::Exact(0));
        assert_eq!(statistics.total_byte_size, Precision::Exact(0));

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_exact_empty_input_zeroes_byte_size() -> Result<()> {
        let cases = [
            ("absent", Precision::Absent, Precision::Absent),
            ("inexact", Precision::Inexact(8000), Precision::Inexact(400)),
        ];

        for (desc, input_total_byte_size, input_byte_size) in cases {
            let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
            let input_stats = Statistics {
                num_rows: Precision::Exact(0),
                total_byte_size: input_total_byte_size,
                column_statistics: vec![ColumnStatistics {
                    byte_size: input_byte_size,
                    ..Default::default()
                }],
            };
            let predicate = Arc::new(BinaryExpr::new(
                Arc::new(Column::new("a", 0)),
                Operator::Gt,
                Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
            ));

            let input = Arc::new(StatisticsExec::new(input_stats, schema));
            let filter: Arc<dyn ExecutionPlan> =
                Arc::new(FilterExec::try_new(predicate, input)?);
            let statistics = StatisticsContext::new()
                .compute(filter.as_ref(), &StatisticsArgs::new())?;

            assert_eq!(
                statistics.num_rows,
                Precision::Exact(0),
                "case '{desc}': num_rows mismatch"
            );
            assert_eq!(
                statistics.total_byte_size,
                Precision::Exact(0),
                "case '{desc}': total_byte_size mismatch"
            );
            assert_eq!(
                statistics.column_statistics[0].byte_size,
                Precision::Exact(0),
                "case '{desc}': byte_size mismatch"
            );
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_empty_input_equality_ndv_zero() -> Result<()> {
        let cases: Vec<(&str, Schema, Statistics, Arc<dyn PhysicalExpr>)> = vec![
            (
                "fallback string equality",
                Schema::new(vec![Field::new("name", DataType::Utf8, true)]),
                Statistics {
                    num_rows: Precision::Exact(0),
                    total_byte_size: Precision::Exact(0),
                    column_statistics: vec![ColumnStatistics {
                        distinct_count: Precision::Exact(0),
                        null_count: Precision::Exact(0),
                        byte_size: Precision::Exact(0),
                        ..Default::default()
                    }],
                },
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("name", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Utf8(Some("x".to_string())))),
                )),
            ),
            (
                "interval numeric equality",
                Schema::new(vec![Field::new("a", DataType::Int32, true)]),
                Statistics {
                    num_rows: Precision::Exact(0),
                    total_byte_size: Precision::Exact(0),
                    column_statistics: vec![ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(10))),
                        distinct_count: Precision::Exact(0),
                        null_count: Precision::Exact(0),
                        byte_size: Precision::Exact(0),
                        ..Default::default()
                    }],
                },
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("a", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
                )),
            ),
        ];

        for (desc, schema, input_stats, predicate) in cases {
            let input = Arc::new(StatisticsExec::new(input_stats, schema));
            let filter: Arc<dyn ExecutionPlan> =
                Arc::new(FilterExec::try_new(predicate, input)?);
            let statistics = StatisticsContext::new()
                .compute(filter.as_ref(), &StatisticsArgs::new())?;

            assert_eq!(
                statistics.num_rows,
                Precision::Exact(0),
                "case '{desc}': row count mismatch"
            );
            assert_eq!(
                statistics.column_statistics[0].distinct_count,
                Precision::Exact(0),
                "case '{desc}': NDV should be capped at zero rows"
            );
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_and_equality_ndv() -> Result<()> {
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Int32, false),
        ]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(1200),
                column_statistics: vec![
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                        null_count: Precision::Inexact(80),
                        distinct_count: Precision::Inexact(80),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(50))),
                        distinct_count: Precision::Inexact(40),
                        ..Default::default()
                    },
                    ColumnStatistics {
                        min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                        max_value: Precision::Inexact(ScalarValue::Int32(Some(200))),
                        null_count: Precision::Inexact(90),
                        distinct_count: Precision::Inexact(150),
                        ..Default::default()
                    },
                ],
            },
            schema.clone(),
        ));

        // a = 42 AND b > 10 AND c = 7
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(BinaryExpr::new(
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("a", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                )),
                Operator::And,
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("b", 1)),
                    Operator::Gt,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
                )),
            )),
            Operator::And,
            Arc::new(BinaryExpr::new(
                Arc::new(Column::new("c", 2)),
                Operator::Eq,
                Arc::new(Literal::new(ScalarValue::Int32(Some(7)))),
            )),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        // Equality predicates collapse NDV and reject nulls for their columns.
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(1)
        );
        assert_eq!(
            statistics.column_statistics[0].null_count,
            Precision::Exact(0)
        );
        // b > 10 narrows to [11, 50] but doesn't collapse to a single value.
        // The combined selectivity of a=42 (1/80) and c=7 (1/150) on 100 rows
        // computes num_rows = 1, so NDV is capped at the row count: min(40, 1) = 1.
        assert_eq!(
            statistics.column_statistics[1].distinct_count,
            Precision::Inexact(1)
        );
        assert_eq!(
            statistics.column_statistics[2].distinct_count,
            Precision::Inexact(1)
        );
        assert_eq!(
            statistics.column_statistics[2].null_count,
            Precision::Exact(0)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_equality_absent_bounds_ndv() -> Result<()> {
        // a: ndv=80, no min/max
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(400),
                column_statistics: vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(80),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        // Even without input bounds, interval analysis can derive singleton
        // bounds from the equality itself.
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(1)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_equality_int8_ndv() -> Result<()> {
        // a: min=-100, max=100, ndv=50
        let schema = Schema::new(vec![Field::new("a", DataType::Int8, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(100),
                column_statistics: vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Int8(Some(-100))),
                    max_value: Precision::Inexact(ScalarValue::Int8(Some(100))),
                    distinct_count: Precision::Inexact(50),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Int8(Some(42)))),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(1)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_equality_int64_ndv() -> Result<()> {
        // a: min=0, max=1_000_000, ndv=100_000
        let schema = Schema::new(vec![Field::new("a", DataType::Int64, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100_000),
                total_byte_size: Precision::Inexact(800_000),
                column_statistics: vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Int64(Some(0))),
                    max_value: Precision::Inexact(ScalarValue::Int64(Some(1_000_000))),
                    distinct_count: Precision::Inexact(100_000),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Int64(Some(42)))),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(1)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_equality_float32_ndv() -> Result<()> {
        // a: min=0.0, max=100.0, ndv=50
        let schema = Schema::new(vec![Field::new("a", DataType::Float32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(400),
                column_statistics: vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Float32(Some(0.0))),
                    max_value: Precision::Inexact(ScalarValue::Float32(Some(100.0))),
                    distinct_count: Precision::Inexact(50),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("a", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::Float32(Some(42.5)))),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(1)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_equality_reversed_ndv() -> Result<()> {
        // a: min=1, max=100, ndv=80
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(400),
                column_statistics: vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                    distinct_count: Precision::Inexact(80),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        // 42 = a (literal on the left)
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
            Operator::Eq,
            Arc::new(Column::new("a", 0)),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(1)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_equality_timestamp_ndv() -> Result<()> {
        // ts: min=1_000_000_000, max=2_000_000_000, ndv=500
        let schema = Schema::new(vec![Field::new(
            "ts",
            DataType::Timestamp(arrow::datatypes::TimeUnit::Nanosecond, None),
            false,
        )]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Inexact(8000),
                column_statistics: vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::TimestampNanosecond(
                        Some(1_000_000_000),
                        None,
                    )),
                    max_value: Precision::Inexact(ScalarValue::TimestampNanosecond(
                        Some(2_000_000_000),
                        None,
                    )),
                    distinct_count: Precision::Inexact(500),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("ts", 0)),
            Operator::Eq,
            Arc::new(Literal::new(ScalarValue::TimestampNanosecond(
                Some(1_500_000_000),
                None,
            ))),
        ));
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);
        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(1)
        );
        Ok(())
    }

    #[test]
    fn test_collect_equality_columns() {
        use std::collections::HashSet;
        // (description, predicate, expected_column_indices, expected_infeasible)
        #[expect(clippy::type_complexity)]
        let cases: Vec<(&str, Arc<dyn PhysicalExpr>, Vec<usize>, bool)> = vec![
            (
                "simple col = literal",
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("a", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                )),
                vec![0],
                false,
            ),
            (
                "reversed literal = col",
                Arc::new(BinaryExpr::new(
                    Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                    Operator::Eq,
                    Arc::new(Column::new("a", 0)),
                )),
                vec![0],
                false,
            ),
            (
                "AND with two equalities",
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("b", 1)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Utf8(Some(
                            "hello".to_string(),
                        )))),
                    )),
                )),
                vec![0, 1],
                false,
            ),
            (
                "OR produces empty set",
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                    )),
                    Operator::Or,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(99)))),
                    )),
                )),
                vec![],
                false,
            ),
            (
                "greater-than produces empty set",
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("a", 0)),
                    Operator::Gt,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                )),
                vec![],
                false,
            ),
            (
                "col = col produces empty set",
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("a", 0)),
                    Operator::Eq,
                    Arc::new(Column::new("b", 1)),
                )),
                vec![],
                false,
            ),
            (
                "nested AND with three equalities",
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(BinaryExpr::new(
                            Arc::new(Column::new("a", 0)),
                            Operator::Eq,
                            Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
                        )),
                        Operator::And,
                        Arc::new(BinaryExpr::new(
                            Arc::new(Column::new("b", 1)),
                            Operator::Eq,
                            Arc::new(Literal::new(ScalarValue::Int32(Some(2)))),
                        )),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("c", 2)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(3)))),
                    )),
                )),
                vec![0, 1, 2],
                false,
            ),
            (
                "AND with mixed equality and non-equality",
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("b", 1)),
                        Operator::Gt,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
                    )),
                )),
                vec![0],
                false,
            ),
            (
                "col = NULL is excluded",
                Arc::new(BinaryExpr::new(
                    Arc::new(Column::new("a", 0)),
                    Operator::Eq,
                    Arc::new(Literal::new(ScalarValue::Int32(None))),
                )),
                vec![],
                false,
            ),
            (
                "NULL = col is excluded",
                Arc::new(BinaryExpr::new(
                    Arc::new(Literal::new(ScalarValue::Utf8(None))),
                    Operator::Eq,
                    Arc::new(Column::new("a", 0)),
                )),
                vec![],
                false,
            ),
            (
                "contradictory: same col, different literals",
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Utf8(Some(
                            "alice".to_string(),
                        )))),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Utf8(Some(
                            "bob".to_string(),
                        )))),
                    )),
                )),
                vec![0],
                true,
            ),
            (
                "same col, same literal is not contradictory",
                Arc::new(BinaryExpr::new(
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                    )),
                    Operator::And,
                    Arc::new(BinaryExpr::new(
                        Arc::new(Column::new("a", 0)),
                        Operator::Eq,
                        Arc::new(Literal::new(ScalarValue::Int32(Some(42)))),
                    )),
                )),
                vec![0],
                false,
            ),
        ];

        for (desc, expr, expected_cols, expected_infeasible) in cases {
            let (result, infeasible) = collect_equality_columns(&expr);
            let expected: HashSet<usize> = expected_cols.into_iter().collect();
            if expected_infeasible {
                // When infeasible, the scan is short-circuited, so we only
                // assert the infeasibility flag — the partial column set
                // contents are an implementation detail.
                assert!(infeasible, "case '{desc}': expected infeasible");
            } else {
                assert_eq!(result, expected, "case '{desc}': columns mismatch");
                assert!(!infeasible, "case '{desc}': expected feasible");
            }
        }
    }

    /// Regression test: ProjectionExec on top of a FilterExec that already has
    /// an explicit projection must not panic when `try_swapping_with_projection`
    /// attempts to swap the two nodes.
    ///
    /// Before the fix, `FilterExecBuilder::from(self)` copied the old projection
    /// (e.g. `[0, 1, 2]`) from the FilterExec. After `.with_input` replaced the
    /// input with the narrower ProjectionExec (2 columns), `.build()` tried to
    /// validate the stale `[0, 1, 2]` projection against the 2-column schema and
    /// panicked with "project index 2 out of bounds, max field 2".
    #[test]
    fn test_filter_with_projection_swap_does_not_panic() -> Result<()> {
        use crate::projection::ProjectionExpr;
        use datafusion_physical_expr::expressions::col;

        // Schema: [ts: Int64, tokens: Int64, svc: Utf8]
        let schema = Arc::new(Schema::new(vec![
            Field::new("ts", DataType::Int64, false),
            Field::new("tokens", DataType::Int64, false),
            Field::new("svc", DataType::Utf8, false),
        ]));
        let input = Arc::new(EmptyExec::new(Arc::clone(&schema)));

        // FilterExec: ts > 0, projection=[ts@0, tokens@1, svc@2] (all 3 cols)
        let predicate = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("ts", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int64(Some(0)))),
        ));
        let filter = Arc::new(
            FilterExecBuilder::new(predicate, input)
                .apply_projection(Some(vec![0, 1, 2]))?
                .build()?,
        );

        // ProjectionExec: narrows to [ts, tokens] (drops svc)
        let proj_exprs = vec![
            ProjectionExpr {
                expr: col("ts", &filter.schema())?,
                alias: "ts".to_string(),
            },
            ProjectionExpr {
                expr: col("tokens", &filter.schema())?,
                alias: "tokens".to_string(),
            },
        ];
        let projection = Arc::new(ProjectionExec::try_new(
            proj_exprs,
            Arc::clone(&filter) as _,
        )?);

        // This must not panic
        let result = filter.try_swapping_with_projection(&projection)?;
        assert!(result.is_some(), "swap should succeed");

        let new_plan = result.unwrap();
        // Output schema must still be [ts, tokens]
        let out_schema = new_plan.schema();
        assert_eq!(out_schema.fields().len(), 2);
        assert_eq!(out_schema.field(0).name(), "ts");
        assert_eq!(out_schema.field(1).name(), "tokens");
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_ndv_capped_at_row_count() -> Result<()> {
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(1000),
                column_statistics: vec![ColumnStatistics {
                    min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
                    max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
                    null_count: Precision::Inexact(80),
                    distinct_count: Precision::Inexact(80),
                    byte_size: Precision::Exact(1000),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        // a <= 10 => ~10 rows out of 100
        let predicate: Arc<dyn PhysicalExpr> =
            binary(col("a", &schema)?, Operator::LtEq, lit(10i32), &schema)?;

        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);

        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        // Filter estimates ~10 rows (selectivity = 10/100)
        assert_eq!(statistics.num_rows, Precision::Inexact(10));
        let ndv = &statistics.column_statistics[0].distinct_count;
        assert!(
            ndv.get_value().copied() <= Some(10),
            "Expected NDV <= 10 (filtered row count), got {ndv:?}"
        );
        // `a <= 10` rejects nulls, so the 80 input nulls drop to exactly zero.
        assert_eq!(
            statistics.column_statistics[0].null_count,
            Precision::Exact(0)
        );
        // byte_size follows the same 10% selectivity estimate.
        assert_eq!(
            statistics.column_statistics[0].byte_size,
            Precision::Inexact(100)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_default_selectivity_column_stats() -> Result<()> {
        let schema = Schema::new(vec![Field::new("name", DataType::Utf8, true)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(1000),
                column_statistics: vec![ColumnStatistics {
                    null_count: Precision::Inexact(80),
                    distinct_count: Precision::Inexact(60),
                    byte_size: Precision::Exact(1000),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        // Utf8 interval analysis is unsupported, so this exercises the default
        // selectivity path. The predicate rejects nulls but does not constrain
        // the column to one value.
        let predicate: Arc<dyn PhysicalExpr> =
            binary(col("name", &schema)?, Operator::Gt, lit("m"), &schema)?;
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);

        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Inexact(20));
        assert_eq!(
            statistics.column_statistics[0].null_count,
            Precision::Exact(0)
        );
        assert_eq!(
            statistics.column_statistics[0].byte_size,
            Precision::Inexact(200)
        );
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(20)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_or_does_not_reject_nulls() -> Result<()> {
        let schema = Schema::new(vec![Field::new("name", DataType::Utf8, true)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(1000),
                column_statistics: vec![ColumnStatistics {
                    null_count: Precision::Inexact(80),
                    distinct_count: Precision::Inexact(60),
                    byte_size: Precision::Exact(1000),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        let predicate: Arc<dyn PhysicalExpr> = binary(
            binary(col("name", &schema)?, Operator::Gt, lit("m"), &schema)?,
            Operator::Or,
            is_null(col("name", &schema)?)?,
            &schema,
        )?;
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);

        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Inexact(20));
        assert_eq!(
            statistics.column_statistics[0].null_count,
            Precision::Inexact(20)
        );
        assert_eq!(
            statistics.column_statistics[0].byte_size,
            Precision::Inexact(200)
        );
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(20)
        );
        Ok(())
    }

    #[test]
    fn test_string_selectivity_non_string_literal() {
        let schema =
            Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, true)]));
        let predicate: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("name", 0)),
            Operator::Eq,
            lit(42_i32),
        ));
        let statistics = Statistics::new_unknown(&schema);

        // SQL coerces comparison operands, so exercise this defensive fallback directly.
        assert_eq!(
            string_selectivity(&predicate, &schema, &statistics, 0.2),
            None
        );
    }

    fn like_filter_statistics(
        num_rows: Precision<usize>,
        column: ColumnStatistics,
        pattern: Option<&str>,
        negated: bool,
    ) -> Arc<Statistics> {
        let schema = Schema::new(vec![Field::new("name", DataType::Utf8, true)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows,
                total_byte_size: Precision::Absent,
                column_statistics: vec![column],
            },
            schema.clone(),
        ));
        let predicate = Arc::new(LikeExpr::new(
            negated,
            false,
            col("name", &schema).expect("name column exists"),
            lit(ScalarValue::Utf8(pattern.map(str::to_owned))),
        ));
        let filter = FilterExec::try_new(predicate, input).expect("valid LIKE filter");
        StatisticsContext::new()
            .compute(&filter, &StatisticsArgs::new())
            .expect("LIKE filter statistics")
    }

    #[test]
    fn test_filter_statistics_like_literal_patterns() {
        // SQL simplification rewrites these patterns before FilterExec sees
        // them. Construct LIKE directly to exercise physical-plan callers too.
        for (pattern, positive_rows, negative_rows) in [
            (Some("%"), 800, 0),
            (Some("%%%"), 800, 0),
            (Some(""), 40, 760),
            (Some(r"\%"), 40, 760),
            (Some(r"\_"), 40, 760),
            (Some(r"\%%"), 80, 720),
            (Some(r"%\%"), 80, 720),
            (None, 0, 0),
        ] {
            for (negated, expected_rows) in
                [(false, positive_rows), (true, negative_rows)]
            {
                let statistics = like_filter_statistics(
                    Precision::Exact(1000),
                    ColumnStatistics {
                        null_count: Precision::Exact(200),
                        distinct_count: Precision::Exact(20),
                        ..Default::default()
                    },
                    pattern,
                    negated,
                );
                assert_eq!(
                    statistics.num_rows,
                    Precision::Inexact(expected_rows),
                    "pattern={pattern:?}, negated={negated}"
                );
                assert_eq!(
                    statistics.column_statistics[0].null_count,
                    Precision::Exact(0)
                );
            }
        }
    }

    #[test]
    fn test_filter_statistics_like_missing_or_zero_counts() {
        use Precision::{Absent, Exact, Inexact};

        for (rows, nulls, distinct, positive_rows, negative_rows) in [
            (Exact(1000), Absent, Exact(20), Inexact(50), Inexact(950)),
            (
                Exact(1000),
                Exact(200),
                Exact(0),
                Inexact(160),
                Inexact(640),
            ),
            (Exact(1000), Exact(1000), Exact(0), Inexact(0), Inexact(0)),
            (Exact(0), Exact(0), Exact(0), Exact(0), Exact(0)),
            (Inexact(0), Absent, Absent, Inexact(0), Inexact(0)),
            (Absent, Absent, Exact(20), Absent, Absent),
        ] {
            for (negated, expected_rows) in
                [(false, positive_rows), (true, negative_rows)]
            {
                let statistics = like_filter_statistics(
                    rows,
                    ColumnStatistics {
                        null_count: nulls,
                        distinct_count: distinct,
                        ..Default::default()
                    },
                    Some(""),
                    negated,
                );
                assert_eq!(
                    statistics.num_rows, expected_rows,
                    "rows={rows:?}, nulls={nulls:?}, distinct={distinct:?}, negated={negated}"
                );
                assert_eq!(statistics.column_statistics[0].null_count, Exact(0));
            }
        }
    }

    #[test]
    fn test_filter_statistics_like_column_pattern_rejects_nulls() {
        let schema = Schema::new(vec![
            Field::new("name", DataType::Utf8, true),
            Field::new("pattern", DataType::Utf8, true),
        ]);
        for negated in [false, true] {
            let input = Arc::new(StatisticsExec::new(
                Statistics {
                    num_rows: Precision::Exact(1000),
                    total_byte_size: Precision::Absent,
                    column_statistics: [200, 300]
                        .into_iter()
                        .map(|nulls| ColumnStatistics {
                            null_count: Precision::Exact(nulls),
                            distinct_count: Precision::Exact(20),
                            ..Default::default()
                        })
                        .collect(),
                },
                schema.clone(),
            ));
            let predicate = Arc::new(LikeExpr::new(
                negated,
                false,
                col("name", &schema).expect("name column exists"),
                col("pattern", &schema).expect("pattern column exists"),
            ));
            let filter =
                FilterExec::try_new(predicate, input).expect("valid LIKE filter");
            let statistics = StatisticsContext::new()
                .compute(&filter, &StatisticsArgs::new())
                .expect("LIKE filter statistics");
            // A varying pattern retains the fallback estimate, but neither
            // operand can be NULL in any surviving row.
            assert_eq!(statistics.num_rows, Precision::Inexact(200));
            for column in &statistics.column_statistics {
                assert_eq!(column.null_count, Precision::Exact(0));
            }
        }
    }

    #[test]
    fn test_filter_statistics_fetch_preserves_singleton() -> Result<()> {
        use Precision::{Absent, Exact, Inexact};

        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics::new_unknown(&schema),
            schema,
        ));
        let filter = FilterExecBuilder::new(lit(true), input)
            .with_fetch(Some(3))
            .build()?;
        // A positive fetch keeps the singleton that its input reports, for
        // both overall and partition stats.
        for num_rows in [Exact(100), Inexact(100), Absent] {
            for partition in [None, Some(0)] {
                let stats = filter.statistics_with_fetch(
                    Statistics {
                        num_rows,
                        total_byte_size: Absent,
                        column_statistics: vec![ColumnStatistics {
                            null_count: Exact(0),
                            distinct_count: Exact(1),
                            min_value: Exact(ScalarValue::Int32(Some(5))),
                            max_value: Exact(ScalarValue::Int32(Some(5))),
                            ..Default::default()
                        }],
                    },
                    partition,
                )?;
                let column = &stats.column_statistics[0];
                assert_eq!(column.null_count, Exact(0));
                assert!(column.is_singleton());
                assert_eq!(column.distinct_count, Exact(1));
            }
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_fetch_statistics_match_execution() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int32Array::from_iter_values(0..100))],
        )?;
        for partitions in [1, 2] {
            let input: Arc<dyn ExecutionPlan> = test::TestMemoryExec::try_new_exec(
                &vec![vec![batch.clone()]; partitions],
                Arc::clone(&schema),
                None,
            )?;
            for fetch in [0, 3] {
                let filter: Arc<dyn ExecutionPlan> = Arc::new(
                    FilterExecBuilder::new(lit(true), Arc::clone(&input))
                        .with_fetch(Some(fetch))
                        .build()?,
                );
                let stats = StatisticsContext::new()
                    .compute(filter.as_ref(), &StatisticsArgs::new())?;
                let partition_stats = StatisticsContext::new().compute(
                    filter.as_ref(),
                    &StatisticsArgs::new().with_partition(Some(0)),
                )?;
                assert_eq!(stats.num_rows.get_value(), Some(&(fetch * partitions)));
                assert_eq!(partition_stats.num_rows.get_value(), Some(&fetch));
                let batches = crate::execution_plan::collect(
                    filter,
                    Arc::new(TaskContext::default()),
                )
                .await?;
                assert_eq!(
                    batches.iter().map(RecordBatch::num_rows).sum::<usize>(),
                    fetch * partitions
                );
            }
        }
        Ok(())
    }

    #[test]
    fn test_filter_fetch_null_column_statistics() -> Result<()> {
        use Precision::{Exact, Inexact};

        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
        let stats = Statistics {
            num_rows: Exact(100),
            total_byte_size: Exact(400),
            column_statistics: vec![ColumnStatistics {
                null_count: Exact(100),
                distinct_count: Exact(0),
                byte_size: Exact(400),
                ..Default::default()
            }],
        };
        let input: Arc<dyn ExecutionPlan> = Arc::new(
            StatisticsExec::new(stats.clone(), schema.clone())
                .with_partition_statistics(vec![stats.clone()]),
        );
        for fetch in [0, 3, 200] {
            let filter =
                FilterExecBuilder::new(is_null(col("a", &schema)?)?, Arc::clone(&input))
                    .with_fetch(Some(fetch))
                    .build()?;
            let output = filter.statistics_with_fetch(stats.clone(), None)?;
            assert_eq!(output.num_rows, Exact(fetch.min(100)));
            assert_eq!(output.column_statistics[0].null_count, output.num_rows);
            assert_eq!(output.column_statistics[0].distinct_count, Exact(0));
            let expected_bytes = match fetch {
                0 => Exact(0),
                3 => Inexact(12),
                _ => Exact(400),
            };
            assert_eq!(output.total_byte_size, expected_bytes);
            assert_eq!(output.column_statistics[0].byte_size, expected_bytes);
        }
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_singleton_precision() -> Result<()> {
        use Precision::{Exact, Inexact};

        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)]));
        // The bounds include 5, but no row contains it.
        let values = Int32Array::from_iter_values(
            (0..1000).map(|i| if i % 2 == 0 { 1 } else { 100 }),
        );
        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(values)])?;
        let input = test::TestMemoryExec::try_new_exec(
            &[vec![batch]],
            Arc::clone(&schema),
            None,
        )?;
        let mut input_stats = StatisticsContext::new()
            .compute(input.as_ref(), &StatisticsArgs::new())?
            .as_ref()
            .clone();
        // Supply the bounds a file scan could report for these rows.
        input_stats.column_statistics[0].min_value = Exact(ScalarValue::Int32(Some(1)));
        input_stats.column_statistics[0].max_value = Exact(ScalarValue::Int32(Some(100)));
        let predicate = binary(col("a", &schema)?, Operator::Eq, lit(5i32), &schema)?;
        let filter = FilterExecBuilder::new(predicate, input).build()?;
        let stats = filter
            .statistics_from_inputs(&[Arc::new(input_stats)], &StatisticsArgs::new())?;
        let batches =
            collect(filter.execute(0, Arc::new(TaskContext::default()))?).await?;
        assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 0);
        assert_eq!(stats.column_statistics[0].distinct_count, Inexact(1));
        Ok(())
    }

    #[tokio::test]
    async fn test_filter_statistics_is_not_null_rejects_nulls() -> Result<()> {
        let schema = Schema::new(vec![Field::new("name", DataType::Utf8, true)]);
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(100),
                total_byte_size: Precision::Inexact(1000),
                column_statistics: vec![ColumnStatistics {
                    null_count: Precision::Inexact(80),
                    distinct_count: Precision::Inexact(60),
                    byte_size: Precision::Exact(1000),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        // `name IS NOT NULL` keeps only non-null rows, so the surviving null
        // count is exactly zero. Utf8 interval analysis is unsupported, so this
        // also exercises the default-selectivity path.
        let predicate: Arc<dyn PhysicalExpr> = is_not_null(col("name", &schema)?)?;
        let filter: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExec::try_new(predicate, input)?);

        let statistics =
            StatisticsContext::new().compute(filter.as_ref(), &StatisticsArgs::new())?;
        assert_eq!(statistics.num_rows, Precision::Inexact(20));
        assert_eq!(
            statistics.column_statistics[0].null_count,
            Precision::Exact(0)
        );
        assert_eq!(
            statistics.column_statistics[0].byte_size,
            Precision::Inexact(200)
        );
        assert_eq!(
            statistics.column_statistics[0].distinct_count,
            Precision::Inexact(20)
        );
        Ok(())
    }

    // ---------------------------------------------------------------
    // Unit tests for compute_fallback_selectivity
    // ---------------------------------------------------------------

    #[test]
    fn test_fallback_selectivity_single_handled_equality() {
        // col_0 = <expr>, NDV(col_0) = 100 → selectivity = 1/100
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let predicate: Arc<dyn PhysicalExpr> = binary(
            col("a", &schema).unwrap(),
            Operator::Eq,
            lit(42i32),
            &schema,
        )
        .unwrap();
        let col_stats = vec![ColumnStatistics {
            distinct_count: Precision::Inexact(100),
            ..Default::default()
        }];
        let result = compute_fallback_selectivity(&predicate, &col_stats, 20);
        assert!(
            (result - 0.01).abs() < 1e-12,
            "expected 1/100 = 0.01, got {result}"
        );
    }

    #[test]
    fn test_fallback_selectivity_missing_column_statistics() {
        // col_0 = <expr>, but col_stats is empty. -> NDV is unknown, default selectivity is applied.
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let predicate: Arc<dyn PhysicalExpr> = binary(
            col("a", &schema).unwrap(),
            Operator::Eq,
            lit(42i32),
            &schema,
        )
        .unwrap();
        // Empty column statistics, so getting index 0 will return None
        let col_stats = vec![];
        let result = compute_fallback_selectivity(&predicate, &col_stats, 20);
        assert!(
            (result - 0.2).abs() < 1e-12,
            "expected default selectivity 0.2, got {result}"
        );
    }

    #[test]
    fn test_fallback_selectivity_multiple_unhandled_conjuncts() {
        // s <> 'abc' AND t <> 'x' AND u <> 'p'
        // None are handled equalities → selectivity = default once = 0.2
        let schema = Schema::new(vec![
            Field::new("s", DataType::Utf8, false),
            Field::new("t", DataType::Utf8, false),
            Field::new("u", DataType::Utf8, false),
        ]);
        // Simulate three non-equality conjuncts via NotEq operators
        let pred1 = binary(
            col("s", &schema).unwrap(),
            Operator::NotEq,
            lit("abc"),
            &schema,
        )
        .unwrap();
        let pred2 = binary(
            col("t", &schema).unwrap(),
            Operator::NotEq,
            lit("x"),
            &schema,
        )
        .unwrap();
        let pred3 = binary(
            col("u", &schema).unwrap(),
            Operator::NotEq,
            lit("p"),
            &schema,
        )
        .unwrap();
        let combined: Arc<dyn PhysicalExpr> = conjunction(vec![pred1, pred2, pred3]);
        let col_stats = vec![
            ColumnStatistics::new_unknown(),
            ColumnStatistics::new_unknown(),
            ColumnStatistics::new_unknown(),
        ];
        let result = compute_fallback_selectivity(&combined, &col_stats, 20);
        // default_selectivity applied exactly once: 0.2
        assert!((result - 0.2).abs() < 1e-12, "expected 0.2, got {result}");
    }

    #[test]
    fn test_fallback_selectivity_mixed_handled_and_unhandled() {
        // col_a = 42 AND col_b <> 'x'
        // col_a has NDV=50, col_b is unhandled
        // selectivity = (1/50) * 0.2 = 0.004
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Utf8, false),
        ]);
        let eq_pred = binary(
            col("a", &schema).unwrap(),
            Operator::Eq,
            lit(42i32),
            &schema,
        )
        .unwrap();
        let neq_pred = binary(
            col("b", &schema).unwrap(),
            Operator::NotEq,
            lit("x"),
            &schema,
        )
        .unwrap();
        let combined: Arc<dyn PhysicalExpr> = conjunction(vec![eq_pred, neq_pred]);
        let col_stats = vec![
            ColumnStatistics {
                distinct_count: Precision::Inexact(50),
                ..Default::default()
            },
            ColumnStatistics::new_unknown(),
        ];
        let result = compute_fallback_selectivity(&combined, &col_stats, 20);
        let expected = (1.0 / 50.0) * 0.2;
        assert!(
            (result - expected).abs() < 1e-12,
            "expected {expected}, got {result}"
        );
    }

    #[test]
    fn test_fallback_selectivity_col_eq_col_uses_max_ndv() {
        // col_a = col_b uses 1 / max(NDV_left, NDV_right). We verify both column
        // orderings to ensure the max is taken symmetrically.
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]);

        // (a=100, b=200) → right NDV dominates → 1/200
        let pred_ab: Arc<dyn PhysicalExpr> = binary(
            col("a", &schema).unwrap(),
            Operator::Eq,
            col("b", &schema).unwrap(),
            &schema,
        )
        .unwrap();
        let stats_ab = vec![
            ColumnStatistics {
                distinct_count: Precision::Inexact(100),
                ..Default::default()
            },
            ColumnStatistics {
                distinct_count: Precision::Inexact(200),
                ..Default::default()
            },
        ];
        let result_ab = compute_fallback_selectivity(&pred_ab, &stats_ab, 20);
        assert!(
            (result_ab - 1.0 / 200.0).abs() < 1e-12,
            "expected 1/200 (right NDV dominates), got {result_ab}"
        );

        // (a=500, b=100) → left NDV dominates → 1/500
        let pred_ba: Arc<dyn PhysicalExpr> = binary(
            col("a", &schema).unwrap(),
            Operator::Eq,
            col("b", &schema).unwrap(),
            &schema,
        )
        .unwrap();
        let stats_ba = vec![
            ColumnStatistics {
                distinct_count: Precision::Exact(500),
                ..Default::default()
            },
            ColumnStatistics {
                distinct_count: Precision::Exact(100),
                ..Default::default()
            },
        ];
        let result_ba = compute_fallback_selectivity(&pred_ba, &stats_ba, 20);
        assert!(
            (result_ba - 1.0 / 500.0).abs() < 1e-12,
            "expected 1/500 (left NDV dominates), got {result_ba}"
        );
    }

    /// Verify that `FilterExec` uses NDV-based fallback selectivity for predicates
    /// that `check_support` cannot handle. A Utf8 equality `name = 'alice'` fails
    /// interval analysis, so the filter falls back to `1 / NDV` instead of the
    /// flat 20% default.
    #[tokio::test]
    async fn test_filter_statistics_fallback_uses_ndv_for_unsupported_predicate() {
        let schema = Schema::new(vec![Field::new("name", DataType::Utf8, false)]);
        // 1000 rows, NDV = 200 for the `name` column.
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Absent,
                column_statistics: vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(200),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        // Utf8 equality fails `check_support`, triggering the NDV fallback.
        // Expected selectivity = 1 / 200 = 0.005 → num_rows = 1000 * 0.005 = 5.
        let predicate: Arc<dyn PhysicalExpr> = binary(
            col("name", &schema).unwrap(),
            Operator::Eq,
            lit("alice"),
            &schema,
        )
        .unwrap();
        let filter = Arc::new(FilterExec::try_new(predicate, input).unwrap());
        let stats = StatisticsContext::new()
            .compute(filter.as_ref(), &StatisticsArgs::new())
            .unwrap();
        assert_eq!(stats.num_rows, Precision::Inexact(5));
    }

    /// Verify that `FilterExec` uses NDV-based fallback selectivity for a scalar
    /// subquery equality predicate `a = <ScalarSubqueryExpr>`.
    ///
    /// The scalar subquery is unresolved during planning and fails interval
    /// analysis (`check_support`), but the fallback heuristic estimates
    /// selectivity as `1.0 / NDV` rather than the flat 20% default.
    #[tokio::test]
    async fn test_filter_statistics_fallback_scalar_subquery_uses_ndv() {
        use datafusion_expr::physical_planning_context::{
            ScalarSubqueryResults, SubqueryIndex,
        };
        use datafusion_physical_expr::scalar_subquery::ScalarSubqueryExpr;

        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        // 1000 rows, NDV = 200 for column `a`.
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Absent,
                column_statistics: vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(200),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        let subquery_expr = Arc::new(ScalarSubqueryExpr::new(
            DataType::Int32,
            false,
            SubqueryIndex::new(0),
            ScalarSubqueryResults::new(1),
        ));

        // a = <ScalarSubqueryExpr>
        let predicate: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
            col("a", &schema).unwrap(),
            Operator::Eq,
            subquery_expr,
        ));

        let filter = Arc::new(FilterExec::try_new(predicate, input).unwrap());
        let stats = StatisticsContext::new()
            .compute(filter.as_ref(), &StatisticsArgs::new())
            .unwrap();

        // Expected selectivity = 1 / 200 = 0.005 -> 1000 * 0.005 = 5 rows
        // (rather than 20% default = 200 rows).
        assert_eq!(stats.num_rows, Precision::Inexact(5));
    }

    /// Verify that a `CAST(a AS Int64) = <ScalarSubqueryExpr>` predicate — where
    /// the column is wrapped in a `CastExpr` and the subquery is unresolved —
    /// falls back to the default selectivity (20%) because `column_ndv` does
    /// not unwrap casts.
    #[tokio::test]
    async fn test_filter_statistics_fallback_cast_scalar_subquery_uses_default() {
        use datafusion_expr::physical_planning_context::{
            ScalarSubqueryResults, SubqueryIndex,
        };
        use datafusion_physical_expr::scalar_subquery::ScalarSubqueryExpr;

        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        // 1000 rows, NDV = 200 for column `a`.
        let input = Arc::new(StatisticsExec::new(
            Statistics {
                num_rows: Precision::Inexact(1000),
                total_byte_size: Precision::Absent,
                column_statistics: vec![ColumnStatistics {
                    distinct_count: Precision::Inexact(200),
                    ..Default::default()
                }],
            },
            schema.clone(),
        ));

        let subquery_expr = Arc::new(ScalarSubqueryExpr::new(
            DataType::Int64,
            false,
            SubqueryIndex::new(0),
            ScalarSubqueryResults::new(1),
        ));

        // CAST(a AS Int64) = <ScalarSubqueryExpr>
        let cast_col: Arc<dyn PhysicalExpr> = Arc::new(CastExpr::new(
            col("a", &schema).unwrap(),
            DataType::Int64,
            None,
        ));
        let predicate: Arc<dyn PhysicalExpr> =
            Arc::new(BinaryExpr::new(cast_col, Operator::Eq, subquery_expr));

        let filter = Arc::new(
            FilterExec::try_new(predicate, input)
                .unwrap()
                .with_default_selectivity(20)
                .unwrap(),
        );
        let stats = StatisticsContext::new()
            .compute(filter.as_ref(), &StatisticsArgs::new())
            .unwrap();

        // CAST wraps the column, so column_ndv returns None.
        // Falls back to default selectivity 20% -> 1000 * 0.20 = 200 rows.
        assert_eq!(stats.num_rows, Precision::Inexact(200));
    }

    #[test]
    fn test_fallback_selectivity_right_col_uses_ndv() {
        // <scalar_expr> = col_a: column is on the right-hand side of the equality.
        // Verifies that column_ndv identifies the NDV regardless of operand order,
        // yielding 1 / NDV(col_a) rather than falling back to default selectivity.
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let predicate: Arc<dyn PhysicalExpr> = binary(
            lit(42i32),
            Operator::Eq,
            col("a", &schema).unwrap(),
            &schema,
        )
        .unwrap();
        let col_stats = vec![ColumnStatistics {
            distinct_count: Precision::Inexact(80),
            ..Default::default()
        }];
        let result = compute_fallback_selectivity(&predicate, &col_stats, 20);
        let expected = 1.0 / 80.0;
        assert!(
            (result - expected).abs() < 1e-12,
            "expected 1/80 = {expected} when column is on the right side, got {result}"
        );
    }

    #[test]
    fn test_fallback_selectivity_ndv_zero_falls_back_to_default() {
        // col = lit where the column statistics report NDV = 0 (empty table or
        // unknown). `column_ndv` returns None for ndv == 0, so the conjunct is
        // unhandled and the default selectivity is applied.
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let predicate: Arc<dyn PhysicalExpr> =
            binary(col("a", &schema).unwrap(), Operator::Eq, lit(1i32), &schema).unwrap();
        let col_stats = vec![ColumnStatistics {
            distinct_count: Precision::Exact(0), // ndv == 0 → column_ndv returns None
            ..Default::default()
        }];
        let result = compute_fallback_selectivity(&predicate, &col_stats, 20);
        assert!(
            (result - 0.2).abs() < 1e-12,
            "expected default 0.2 when ndv=0, got {result}"
        );
    }

    #[test]
    fn test_fallback_selectivity_col_eq_col_no_ndv_falls_back_to_default() {
        // col_a = col_b where neither column has NDV statistics.
        // Both sides return None from column_ndv, so (None, None) matches and
        // the conjunct is unhandled → default selectivity applied once.
        let schema = Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Int32, false),
        ]);
        let predicate: Arc<dyn PhysicalExpr> = binary(
            col("a", &schema).unwrap(),
            Operator::Eq,
            col("b", &schema).unwrap(),
            &schema,
        )
        .unwrap();
        let col_stats = vec![
            ColumnStatistics::new_unknown(), // no NDV
            ColumnStatistics::new_unknown(), // no NDV
        ];
        let result = compute_fallback_selectivity(&predicate, &col_stats, 20);
        assert!(
            (result - 0.2).abs() < 1e-12,
            "expected default 0.2 when both columns lack NDV, got {result}"
        );
    }
}