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
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
// 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::HashMap;
use std::fmt;
use std::mem::size_of;
use std::sync::{Arc, OnceLock};
use std::vec;

use crate::execution_plan::{
    EmissionType, boundedness_from_children, has_same_children_properties,
    plan_contains_expression_id, stub_properties,
};
use crate::filter_pushdown::{
    ChildFilterDescription, ChildPushdownResult, FilterDescription, FilterPushdownPhase,
    FilterPushdownPropagation, PushedDownPredicate,
};
use crate::joins::Map;
use crate::joins::array_map::ArrayMap;
use crate::joins::hash_join::inlist_builder::build_struct_inlist_values;
use crate::joins::hash_join::not_in::{NotIn, NotInBuild};
use crate::joins::hash_join::shared_bounds::{
    ColumnBounds, PartitionBounds, PushdownStrategy, SharedBuildAccumulator,
};
use crate::joins::hash_join::stream::{
    BuildSide, BuildSideInitialState, HashJoinStream, HashJoinStreamState,
};
use crate::joins::join_hash_map::{JoinHashMapU32, JoinHashMapU64};
use crate::joins::key_range_bitmap::KeyRangeBitmap;
use crate::joins::probe_completion::{Completion, ProbeCompletion};
use crate::joins::utils::{
    OnceAsync, OnceFut, asymmetric_join_output_partitioning, emits_unmatched_left_rows,
    is_existence_join, reorder_output_after_swap, swap_join_projection, update_hash,
};
use crate::joins::{JoinOn, JoinOnRef, PartitionMode, SharedBitmapBuilder};
use crate::metrics::{Count, MetricBuilder, MetricCategory};
use crate::projection::{
    EmbeddedProjection, JoinData, ProjectionExec, try_embed_projection,
    try_pushdown_through_join_with_column_indices,
};
use crate::repartition::REPARTITION_RANDOM_STATE;
use crate::statistics::{ChildStats, StatisticsArgs, with_per_partition_fetch};
use crate::{
    ChildrenPropertiesMode, ExecutionPlanProperties, ReplaceChildrenOptions,
    validate_child_count,
};
use crate::{
    DisplayAs, DisplayFormatType, Distribution, ExecutionPlan,
    InputDistributionRequirements, Partitioning, PlanProperties,
    SendableRecordBatchStream, Statistics,
    common::can_project,
    joins::utils::{
        BuildProbeJoinMetrics, ColumnIndex, JoinFilter, JoinHashMapType,
        build_join_schema, check_join_is_valid, estimate_join_statistics,
        need_produce_result_in_final, symmetric_join_output_partitioning,
    },
    metrics::{ExecutionPlanMetricsSet, MetricsSet},
};

use arrow::array::{Array, ArrayRef, BooleanBufferBuilder};
use arrow::compute::concat_batches;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use arrow::util::bit_util;
use arrow_schema::{DataType, Schema};
use datafusion_common::config::ConfigOptions;
use datafusion_common::float_semantics::normalize_floats;
use datafusion_common::stats::Precision;
use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion_common::utils::memory::{
    RecordBatchMemoryCounter, estimate_memory_size, get_record_batch_memory_size,
};
use datafusion_common::{
    JoinSide, JoinType, NullEquality, Result, assert_or_internal_err, internal_err,
    plan_err, project_schema,
};
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_expr::Accumulator;
use datafusion_functions_aggregate_common::min_max::{MaxAccumulator, MinAccumulator};
use datafusion_physical_expr::equivalence::{
    ProjectionMapping, join_equivalence_properties,
};
use datafusion_physical_expr::expressions::{Column, DynamicFilterPhysicalExpr, lit};
use datafusion_physical_expr::projection::{ProjectionRef, combine_projections};
use datafusion_physical_expr::{PhysicalExpr, PhysicalExprRef};

use datafusion_common::hash_utils::RandomState;
use datafusion_physical_expr_common::physical_expr::fmt_sql;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::TryStreamExt;
use parking_lot::Mutex;

use super::partitioned_hash_eval::SeededRandomState;

mod prepared;
pub use prepared::PreparedHashJoinBuild;

/// Hard-coded seed to ensure hash values from the hash join differ from `RepartitionExec`, avoiding collisions.
pub(crate) const HASH_JOIN_SEED: SeededRandomState =
    SeededRandomState::with_seed(12210250226015887276);

const ARRAY_MAP_CREATED_COUNT_METRIC_NAME: &str = "array_map_created_count";

/// Decides whether the build side should be joined with an [`ArrayMap`]
/// (perfect hash join), returning the `(min, max)` key range to build it over.
///
/// On `Some`, the memory of the [`ArrayMap`] has already been added to
/// `reservation`; the caller concatenates the build batches and creates the map
/// with [`ArrayMap::try_new`].
#[expect(clippy::too_many_arguments)]
fn array_map_key_range(
    bounds: Option<&PartitionBounds>,
    schema: &SchemaRef,
    batches: &[RecordBatch],
    on_left: &[PhysicalExprRef],
    reservation: &mut MemoryReservation,
    perfect_hash_join_small_build_threshold: usize,
    perfect_hash_join_min_key_density: f64,
    null_equality: NullEquality,
) -> Result<Option<(u64, u64)>> {
    // `bounds` are also collected for dynamic filters, on any key type, so the
    // key type cannot be inferred from their presence.
    if !is_perfect_hash_join_candidate(on_left, schema)? {
        return Ok(None);
    }

    if null_equality == NullEquality::NullEqualsNull {
        for batch in batches.iter() {
            let arrays = evaluate_expressions_to_arrays(on_left, batch)?;
            if arrays[0].null_count() > 0 {
                return Ok(None);
            }
        }
    }

    let (min_val, max_val) = if let Some(bounds) = bounds {
        let (min_val, max_val) = if let Some(cb) = bounds.get_column_bounds(0) {
            (cb.min.clone(), cb.max.clone())
        } else {
            return Ok(None);
        };

        if min_val.is_null() || max_val.is_null() {
            return Ok(None);
        }

        if min_val > max_val {
            return internal_err!("min_val>max_val");
        }

        if let Some((mi, ma)) =
            ArrayMap::key_to_u64(&min_val).zip(ArrayMap::key_to_u64(&max_val))
        {
            (mi, ma)
        } else {
            return Ok(None);
        }
    } else {
        return Ok(None);
    };

    let range = ArrayMap::calculate_range(min_val, max_val);
    let num_row: usize = batches.iter().map(|x| x.num_rows()).sum();

    // TODO: support create ArrayMap<u64>
    if num_row >= u32::MAX as usize {
        return Ok(None);
    }

    // When the key range spans the full integer domain (e.g. i64::MIN to i64::MAX),
    // range is u64::MAX and `range + 1` below would overflow.
    if range == usize::MAX as u64 {
        return Ok(None);
    }

    let dense_ratio = (num_row as f64) / ((range + 1) as f64);

    if range >= perfect_hash_join_small_build_threshold as u64
        && dense_ratio <= perfect_hash_join_min_key_density
    {
        return Ok(None);
    }

    let mem_size = ArrayMap::estimate_memory_size(min_val, max_val, num_row);
    reservation.try_grow(mem_size)?;

    Ok(Some((min_val, max_val)))
}

/// Immutable build buffers and their durable reservation.
struct JoinBuildData {
    /// Hash table with row indices into `batch`, also shared with dynamic filters.
    map: Arc<Map>,
    /// The input rows for the build side.
    batch: RecordBatch,
    /// Evaluated build-side key expressions, with float `-0.0` rewritten to
    /// `+0.0` so probe batches can compare against them without scanning the
    /// build side again. The dynamic filters (`bounds`, `membership`) and
    /// the `NOT IN` NULL masks were computed from the original keys in
    /// `collect_left_input`.
    values: Vec<ArrayRef>,
    /// Bounds computed from the build side; absent for an empty partition.
    bounds: Option<PartitionBounds>,
    /// IN-list values or a hash-table reference used for filter pushdown.
    membership: PushdownStrategy,
    // Keep the reservation after the allocations it accounts for.
    reservation: MemoryReservation,
}

/// A build lease and mutable bookkeeping for one join execution.
pub(super) struct JoinLeftData {
    /// The `NOT IN` state of a null-aware join, see [`NotInBuild`].
    not_in: Option<NotInBuild>,
    /// Shared bitmap for visited left indices within this consuming join.
    visited_indices_bitmap: SharedBitmapBuilder,
    /// Tracks the final probe partition and what every partition observed.
    /// See [`ProbeCompletion`] for the completion invariant.
    probe_completion: ProbeCompletion,
    // Drop the reservation after the mutable state it also accounts for.
    build: Arc<JoinBuildData>,
}

impl JoinLeftData {
    /// return a reference to the map
    pub(super) fn map(&self) -> &Map {
        &self.build.map
    }

    /// This build's `NOT IN` state, for a null-aware join.
    pub(super) fn not_in(&self) -> Option<&NotInBuild> {
        self.not_in.as_ref()
    }

    /// returns a reference to the build side batch
    pub(super) fn batch(&self) -> &RecordBatch {
        &self.build.batch
    }

    /// Returns `true` if the build side physically contains rows.
    ///
    /// This is distinct from [`Self::has_matchable_build_rows`]: a build side
    /// can hold rows while its hash map is empty (see that method).
    pub(super) fn has_build_rows(&self) -> bool {
        self.batch().num_rows() > 0
    }

    /// Returns `true` if the build-side hash map has any matchable entries.
    ///
    /// Under [`NullEquality::NullEqualsNothing`] build rows whose join key is
    /// NULL are omitted from the map, so this can be `false` even when
    /// [`Self::has_build_rows`] is `true`.
    pub(super) fn has_matchable_build_rows(&self) -> bool {
        !self.map().is_empty()
    }

    /// Returns the build side key values, with float `-0.0` already rewritten
    /// to `+0.0` for key comparison. The dynamic filters and the `NOT IN`
    /// NULL masks were derived from the original keys instead.
    pub(super) fn values(&self) -> &[ArrayRef] {
        &self.build.values
    }

    /// returns a reference to the visited indices bitmap
    pub(super) fn visited_indices_bitmap(&self) -> &SharedBitmapBuilder {
        &self.visited_indices_bitmap
    }

    /// returns a reference to the InList values for filter pushdown
    pub(super) fn membership(&self) -> &PushdownStrategy {
        &self.build.membership
    }

    /// Borrow bounds without sharing a consuming join's dynamic-filter state.
    pub(super) fn bounds(&self) -> Option<&PartitionBounds> {
        self.build.bounds.as_ref()
    }

    /// Records what a probe partition saw in one batch, for the null-aware
    /// rules evaluated in the final stage.
    pub(super) fn record_probe_batch(&self, non_empty: bool, has_null: bool) {
        self.probe_completion.record_batch(non_empty, has_null);
    }

    /// Whether some probe partition has already recorded a NULL join key.
    ///
    /// Only an early-exit hint for the probe phase: it may lag behind sibling
    /// partitions. Final-stage decisions must use the
    /// [`ProbeSideSummary`](crate::joins::probe_completion::ProbeSideSummary)
    /// returned by [`Self::report_probe_completed`] instead.
    pub(super) fn probe_side_has_null_hint(&self) -> bool {
        self.probe_completion.saw_null_key_hint()
    }

    /// Marks this probe partition as finished, returning
    /// [`Completion::Emit`] for the last one together with what every
    /// partition saw.
    ///
    /// The summary is reachable only through this call, which is what stops
    /// the final stage from reading the shared flags before its own
    /// decrement. See [`ProbeCompletion`] for why that ordering matters.
    pub(super) fn report_probe_completed(&self) -> Completion {
        self.probe_completion.report_completed()
    }
}

/// Helps to build [`HashJoinExec`].
///
/// Builder can be created from an existing [`HashJoinExec`] using [`From::from`].
/// In this case, all its fields are inherited. If a field that affects the node's
/// properties is modified, they will be automatically recomputed during the build.
///
/// # Adding setters
///
/// When adding a new setter, it is necessary to ensure that the `preserve_properties`
/// flag is set to false if modifying the field requires a recomputation of the plan's
/// properties.
///
pub struct HashJoinExecBuilder {
    exec: HashJoinExec,
    preserve_properties: bool,
}

impl HashJoinExecBuilder {
    /// Make a new [`HashJoinExecBuilder`].
    pub fn new(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: Vec<(PhysicalExprRef, PhysicalExprRef)>,
        join_type: JoinType,
    ) -> Self {
        Self {
            exec: HashJoinExec {
                left,
                right,
                on,
                filter: None,
                join_type,
                left_fut: Default::default(),
                prepared_build: None,
                random_state: HASH_JOIN_SEED,
                mode: PartitionMode::Auto,
                fetch: None,
                metrics: ExecutionPlanMetricsSet::new(),
                projection: None,
                column_indices: vec![],
                null_equality: NullEquality::NullEqualsNothing,
                null_aware: false,
                null_aware_value_keys: 0,
                dynamic_filter: None,
                // Will be computed at when plan will be built.
                cache: stub_properties(),
                join_schema: Arc::new(Schema::empty()),
            },
            // As `exec` is initialized with stub properties,
            // they will be properly computed when plan will be built.
            preserve_properties: false,
        }
    }

    /// Set join type.
    pub fn with_type(mut self, join_type: JoinType) -> Self {
        self.exec.join_type = join_type;
        self.preserve_properties = false;
        self
    }

    /// Set projection from the vector.
    pub fn with_projection(self, projection: Option<Vec<usize>>) -> Self {
        self.with_projection_ref(projection.map(Into::into))
    }

    /// Set projection from the shared reference.
    pub fn with_projection_ref(mut self, projection: Option<ProjectionRef>) -> Self {
        self.exec.projection = projection;
        self.preserve_properties = false;
        self
    }

    /// Set optional filter.
    pub fn with_filter(mut self, filter: Option<JoinFilter>) -> Self {
        self.exec.filter = filter;
        self
    }

    /// Set expressions to join on.
    pub fn with_on(mut self, on: Vec<(PhysicalExprRef, PhysicalExprRef)>) -> Self {
        self.exec.on = on;
        self.preserve_properties = false;
        self
    }

    /// Set partition mode.
    pub fn with_partition_mode(mut self, mode: PartitionMode) -> Self {
        self.exec.mode = mode;
        self.preserve_properties = false;
        self
    }

    /// Set null equality property.
    pub fn with_null_equality(mut self, null_equality: NullEquality) -> Self {
        self.exec.null_equality = null_equality;
        self
    }

    /// Set null aware property.
    pub fn with_null_aware(mut self, null_aware: bool) -> Self {
        self.exec.null_aware = null_aware;
        self
    }

    /// Set the number of `NOT IN` value keys of a null-aware join, see
    /// [`HashJoinExec::null_aware_value_keys`].
    pub fn with_null_aware_value_keys(mut self, null_aware_value_keys: usize) -> Self {
        self.exec.null_aware_value_keys = null_aware_value_keys;
        self
    }

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

    /// Require to recompute plan properties.
    pub fn recompute_properties(mut self) -> Self {
        self.preserve_properties = false;
        self
    }

    /// Replace children.
    pub fn with_new_children(
        mut self,
        mut children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Result<Self> {
        assert_or_internal_err!(
            children.len() == 2,
            "wrong number of children passed into `HashJoinExecBuilder`"
        );
        if self.exec.prepared_build.is_some()
            && !Arc::ptr_eq(&self.exec.left, &children[0])
        {
            return plan_err!(
                "Cannot replace the build child after attaching a prepared hash-join build"
            );
        }
        self.preserve_properties &= has_same_children_properties(&self.exec, &children)?;
        self.exec.right = children.swap_remove(1);
        self.exec.left = children.swap_remove(0);
        Ok(self)
    }

    /// Reset task-local runtime state while retaining the immutable prepared build.
    pub fn reset_state(mut self) -> Self {
        self.exec.left_fut = Default::default();

        if let Some(dynamic_filter) = &mut self.exec.dynamic_filter {
            dynamic_filter.filter.reset();
            dynamic_filter.build_accumulator = OnceLock::new();
        }

        self.exec.metrics = ExecutionPlanMetricsSet::new();

        self
    }

    /// Build result as a dyn execution plan.
    pub fn build_exec(self) -> Result<Arc<dyn ExecutionPlan>> {
        self.build().map(|p| Arc::new(p) as _)
    }

    /// Build resulting execution plan.
    pub fn build(self) -> Result<HashJoinExec> {
        let Self {
            mut exec,
            preserve_properties,
        } = self;

        if let Some(prepared) = &exec.prepared_build {
            prepared.validate(&exec)?;
            exec.left_fut = Default::default();
            exec.metrics = ExecutionPlanMetricsSet::new();
            if let Some(filter) = &mut exec.dynamic_filter {
                filter.build_accumulator = OnceLock::new();
            }
        }
        // Before `not_in`, whose value key checks assume some keys.
        if exec.on.is_empty() {
            return plan_err!("On constraints in HashJoinExec should be non-empty");
        }
        // Validate null_aware flag
        exec.not_in()?;

        if preserve_properties {
            return Ok(exec);
        }

        let HashJoinExec {
            left,
            right,
            on,
            filter,
            join_type,
            left_fut,
            prepared_build,
            random_state,
            mode,
            metrics,
            projection,
            null_equality,
            null_aware,
            null_aware_value_keys,
            dynamic_filter,
            fetch,
            // Recomputed.
            join_schema: _,
            column_indices: _,
            cache: _,
        } = exec;

        let left_schema = left.schema();
        let right_schema = right.schema();

        check_join_is_valid(&left_schema, &right_schema, &on)?;
        let (join_schema, column_indices) =
            build_join_schema(&left_schema, &right_schema, &join_type);

        let join_schema = Arc::new(join_schema);

        // Check if the projection is valid.
        can_project(&join_schema, projection.as_deref())?;

        let cache = HashJoinExec::compute_properties(
            &left,
            &right,
            &join_schema,
            join_type,
            &on,
            mode,
            projection.as_deref(),
        )?;

        Ok(HashJoinExec {
            left,
            right,
            on,
            filter,
            join_type,
            join_schema,
            left_fut,
            prepared_build,
            random_state,
            mode,
            metrics,
            projection,
            column_indices,
            null_equality,
            null_aware,
            null_aware_value_keys,
            cache: Arc::new(cache),
            dynamic_filter,
            fetch,
        })
    }

    fn with_dynamic_filter(mut self, filter: Option<HashJoinExecDynamicFilter>) -> Self {
        self.exec.dynamic_filter = filter;
        self
    }
}

impl From<&HashJoinExec> for HashJoinExecBuilder {
    fn from(exec: &HashJoinExec) -> Self {
        Self {
            exec: HashJoinExec {
                left: Arc::clone(exec.left()),
                right: Arc::clone(exec.right()),
                on: exec.on.clone(),
                filter: exec.filter.clone(),
                join_type: exec.join_type,
                join_schema: Arc::clone(&exec.join_schema),
                left_fut: Arc::clone(&exec.left_fut),
                prepared_build: exec.prepared_build.clone(),
                random_state: exec.random_state.clone(),
                mode: exec.mode,
                metrics: exec.metrics.clone(),
                projection: exec.projection.clone(),
                column_indices: exec.column_indices.clone(),
                null_equality: exec.null_equality,
                null_aware: exec.null_aware,
                null_aware_value_keys: exec.null_aware_value_keys,
                cache: Arc::clone(&exec.cache),
                dynamic_filter: exec.dynamic_filter.clone(),
                fetch: exec.fetch,
            },
            preserve_properties: true,
        }
    }
}

#[expect(rustdoc::private_intra_doc_links)]
/// Join execution plan: Evaluates equijoin predicates in parallel on multiple
/// partitions using a hash table and an optional filter list to apply post
/// join.
///
/// # Join Expressions
///
/// This implementation is optimized for evaluating equijoin predicates  (
/// `<col1> = <col2>`) expressions, which are represented as a list of `Columns`
/// in [`Self::on`].
///
/// Non-equality predicates, which can not pushed down to a join inputs (e.g.
/// `<col1> != <col2>`) are known as "filter expressions" and are evaluated
/// after the equijoin predicates.
///
/// # ArrayMap Optimization
///
/// For joins with a single integer-based join key, `HashJoinExec` may use an [`ArrayMap`]
/// (also known as a "perfect hash join") instead of a general-purpose hash map.
/// This optimization is used when:
/// 1. There is exactly one join key.
/// 2. The join key is an integer type up to 64 bits wide that can be losslessly converted
///    to `u64` (128-bit integer types such as `i128` and `u128` are not supported).
/// 3. The range of keys is small enough (controlled by `perfect_hash_join_small_build_threshold`)
///    OR the keys are sufficiently dense (controlled by `perfect_hash_join_min_key_density`).
/// 4. build_side.num_rows() < u32::MAX
/// 5. NullEqualsNothing || (NullEqualsNull && build side doesn't contain null)
///
/// See [`array_map_key_range`] for more details.
///
/// Note that when using [`PartitionMode::Partitioned`], the build side is split into multiple
/// partitions. This can cause a dense build side to become sparse within each partition,
/// potentially disabling this optimization.
///
/// For example, consider:
/// ```sql
/// SELECT t1.value, t2.value
/// FROM range(10000) AS t1
/// JOIN range(10000) AS t2
///   ON t1.value = t2.value;
/// ```
/// With 24 partitions, each partition will only receive a subset of the 10,000 rows.
/// The first partition might contain values like `3, 10, 18, 39, 43`, which are sparse
/// relative to the original range, even though the overall data set is dense.
///
/// # "Build Side" vs "Probe Side"
///
/// HashJoin takes two inputs, which are referred to as the "build" and the
/// "probe". The build side is the first child, and the probe side is the second
/// child.
///
/// The two inputs are treated differently and it is VERY important that the
/// *smaller* input is placed on the build side to minimize the work of creating
/// the hash table.
///
/// ```text
///          ┌───────────┐
///          │ HashJoin  │
///          │           │
///          └───────────┘
///              │   │
///        ┌─────┘   └─────┐
///        ▼               ▼
/// ┌────────────┐  ┌─────────────┐
/// │   Input    │  │    Input    │
/// │    [0]     │  │     [1]     │
/// └────────────┘  └─────────────┘
///
///  "build side"    "probe side"
/// ```
///
/// Execution proceeds in 2 stages:
///
/// 1. the **build phase** creates a hash table from the tuples of the build side,
///    and single concatenated batch containing data from all fetched record batches.
///    Resulting hash table stores hashed join-key fields for each row as a key, and
///    indices of corresponding rows in concatenated batch.
///
/// When using the standard `JoinHashMap`, hash join uses LIFO data structure as a hash table,
/// and in order to retain original build-side input order while obtaining data during probe phase,
/// hash table is updated by iterating batch sequence in reverse order, which keeps rows
/// with smaller indices "on the top" of hash table. The concatenated build-side batch keeps
/// the build side's input order, so each batch is inserted with the offset of its first row
/// in that concatenated batch.
///
/// Example of build phase for 3 record batches:
///
///
/// ```text
///
///  Original build-side data   Inserting build-side values into hashmap    Concatenated build-side batch
///                                                                         ┌───────────────────────────┐
///                             hashmap.insert(row-hash, row-idx + offset)  │                      idx  │
///            ┌───────┐                                                    │          ┌───────┐        │
///            │ Row 1 │        1) update_hash for batch 3 with offset 5    │          │ Row 1 │    0   │
///   Batch 1  │       │           - hashmap.insert(Row 7, idx 6)           │ Batch 1  │       │        │
///            │ Row 2 │           - hashmap.insert(Row 6, idx 5)           │          │ Row 2 │    1   │
///            └───────┘                                                    │          └───────┘        │
///                                                                         │                           │
///            ┌───────┐                                                    │          ┌───────┐        │
///            │ Row 3 │        2) update_hash for batch 2 with offset 2    │          │ Row 3 │    2   │
///            │       │           - hashmap.insert(Row 5, idx 4)           │          │       │        │
///   Batch 2  │ Row 4 │           - hashmap.insert(Row 4, idx 3)           │ Batch 2  │ Row 4 │    3   │
///            │       │           - hashmap.insert(Row 3, idx 2)           │          │       │        │
///            │ Row 5 │                                                    │          │ Row 5 │    4   │
///            └───────┘                                                    │          └───────┘        │
///                                                                         │                           │
///            ┌───────┐                                                    │          ┌───────┐        │
///            │ Row 6 │        3) update_hash for batch 1 with offset 0    │          │ Row 6 │    5   │
///   Batch 3  │       │           - hashmap.insert(Row 2, idx 1)           │ Batch 3  │       │        │
///            │ Row 7 │           - hashmap.insert(Row 1, idx 0)           │          │ Row 7 │    6   │
///            └───────┘                                                    │          └───────┘        │
///                                                                         │                           │
///                                                                         └───────────────────────────┘
/// ```
///
/// 2. the **probe phase** where the tuples of the probe side are streamed
///    through, checking for matches of the join keys in the hash table.
///
/// ```text
///                 ┌────────────────┐          ┌────────────────┐
///                 │ ┌─────────┐    │          │ ┌─────────┐    │
///                 │ │  Hash   │    │          │ │  Hash   │    │
///                 │ │  Table  │    │          │ │  Table  │    │
///                 │ │(keys are│    │          │ │(keys are│    │
///                 │ │equi join│    │          │ │equi join│    │  Stage 2: batches from
///  Stage 1: the   │ │columns) │    │          │ │columns) │    │    the probe side are
/// *entire* build  │ │         │    │          │ │         │    │  streamed through, and
///  side is read   │ └─────────┘    │          │ └─────────┘    │   checked against the
/// into the hash   │      ▲         │          │          ▲     │   contents of the hash
///     table       │       HashJoin │          │  HashJoin      │          table
///                 └──────┼─────────┘          └──────────┼─────┘
///             ─ ─ ─ ─ ─ ─                                 ─ ─ ─ ─ ─ ─ ─
///            │                                                         │
///
///            │                                                         │
///     ┌────────────┐                                            ┌────────────┐
///     │RecordBatch │                                            │RecordBatch │
///     └────────────┘                                            └────────────┘
///     ┌────────────┐                                            ┌────────────┐
///     │RecordBatch │                                            │RecordBatch │
///     └────────────┘                                            └────────────┘
///           ...                                                       ...
///     ┌────────────┐                                            ┌────────────┐
///     │RecordBatch │                                            │RecordBatch │
///     └────────────┘                                            └────────────┘
///
///        build side                                                probe side
/// ```
///
/// # Example "Optimal" Plans
///
/// The differences in the inputs means that for classic "Star Schema Query",
/// the optimal plan will be a **"Right Deep Tree"** . A Star Schema Query is
/// one where there is one large table and several smaller "dimension" tables,
/// joined on `Foreign Key = Primary Key` predicates.
///
/// A "Right Deep Tree" looks like this large table as the probe side on the
/// lowest join:
///
/// ```text
///             ┌───────────┐
///             │ HashJoin  │
///             │           │
///             └───────────┘
///                 │   │
///         ┌───────┘   └──────────┐
///         ▼                      ▼
/// ┌───────────────┐        ┌───────────┐
/// │ small table 1 │        │ HashJoin  │
/// │  "dimension"  │        │           │
/// └───────────────┘        └───┬───┬───┘
///                   ┌──────────┘   └───────┐
///                   │                      │
///                   ▼                      ▼
///           ┌───────────────┐        ┌───────────┐
///           │ small table 2 │        │ HashJoin  │
///           │  "dimension"  │        │           │
///           └───────────────┘        └───┬───┬───┘
///                               ┌────────┘   └────────┐
///                               │                     │
///                               ▼                     ▼
///                       ┌───────────────┐     ┌───────────────┐
///                       │ small table 3 │     │  large table  │
///                       │  "dimension"  │     │    "fact"     │
///                       └───────────────┘     └───────────────┘
/// ```
///
/// # Clone / Shared State
///
/// Note this structure includes a [`OnceAsync`] that is used to coordinate the
/// loading of the left side with the processing in each output stream.
/// Therefore it can not be [`Clone`]
pub struct HashJoinExec {
    /// left (build) side which gets hashed
    pub left: Arc<dyn ExecutionPlan>,
    /// right (probe) side which are filtered by the hash table
    pub right: Arc<dyn ExecutionPlan>,
    /// Set of equijoin columns from the relations: `(left_col, right_col)`
    pub on: Vec<(PhysicalExprRef, PhysicalExprRef)>,
    /// Filters which are applied while finding matching rows
    pub filter: Option<JoinFilter>,
    /// How the join is performed (`OUTER`, `INNER`, etc)
    pub join_type: JoinType,
    /// The schema after join. Please be careful when using this schema,
    /// if there is a projection, the schema isn't the same as the output schema.
    join_schema: SchemaRef,
    /// Future that consumes left input and builds the hash table
    ///
    /// For CollectLeft partition mode, this structure is *shared* across all output streams.
    ///
    /// Each output stream waits on the `OnceAsync` to signal the completion of
    /// the hash table creation.
    left_fut: Arc<OnceAsync<JoinLeftData>>,
    /// Immutable build attached by an embedding executor.
    prepared_build: Option<Arc<PreparedHashJoinBuild>>,
    /// Shared the `SeededRandomState` for the hashing algorithm (seeds preserved for serialization)
    random_state: SeededRandomState,
    /// Partitioning mode to use
    pub mode: PartitionMode,
    /// Execution metrics
    metrics: ExecutionPlanMetricsSet,
    /// The projection indices of the columns in the output schema of join
    pub projection: Option<ProjectionRef>,
    /// Information of index and left / right placement of columns
    column_indices: Vec<ColumnIndex>,
    /// The equality null-handling behavior of the join algorithm.
    pub null_equality: NullEquality,
    /// Flag to indicate if this join uses null-aware equality semantics.
    ///
    /// Set for the physical lowering of scalar `NOT IN` subqueries (producing
    /// `JoinType::LeftAnti` at the top level of a filter or `JoinType::LeftMark`
    /// inside a larger expression). When `true`, NULLs in the join keys follow
    /// SQL `NOT IN` three-valued logic rather than ordinary equi-join semantics.
    /// A join filter holds the non-equality part of a correlated subquery, and
    /// only the probe rows that pass it take part in the three-valued logic.
    ///
    /// `JoinSelection` may swap a null-aware `LeftAnti` into a `RightAnti`
    /// join that builds on the subquery side and decides each outer (probe)
    /// row as it streams.
    ///
    /// Key-ordering convention (relied on positionally, not enforced): for a
    /// null-aware join, `on[..V]` are the `NOT IN` value keys and `on[V..]`
    /// the correlated equality scope keys, where `V` is
    /// [`Self::null_aware_value_keys`].
    /// Reordering these keys would silently produce wrong results, which is why
    /// such joins are pinned to `PartitionMode::CollectLeft` (the only key
    /// reorderer acts solely on `PartitionMode::Partitioned`).
    pub null_aware: bool,
    /// Number of `NOT IN` value keys of a null-aware join; ignored unless
    /// [`Self::null_aware`] is set.
    ///
    /// A scalar `x NOT IN (SELECT y ...)` has one value key; a multi-column
    /// `(a, b) NOT IN (SELECT x, y ...)` has one per tuple element. The tuple
    /// comparison is UNKNOWN rather than FALSE when no element pair is a
    /// definite mismatch and at least one of them involves a NULL, so a NULL in
    /// one element does not make every comparison UNKNOWN the way a scalar
    /// NULL does.
    ///
    /// Such a join decides UNKNOWN per row, like a correlated scalar `NOT IN`:
    /// without correlation keys every NULL-valued row is paired with every row
    /// on the other side to check its other elements. See
    /// <https://github.com/apache/datafusion/issues/26088> for the follow-up.
    ///
    /// `0` leaves the count unset, the default of [`HashJoinExecBuilder::new`]
    /// and [`Self::try_new`]. An unset count is accepted only for a single-key
    /// join, a scalar `NOT IN`; a null-aware join with more keys must set it
    /// with [`HashJoinExecBuilder::with_null_aware_value_keys`].
    pub null_aware_value_keys: usize,
    /// Cache holding plan properties like equivalences, output partitioning etc.
    cache: Arc<PlanProperties>,
    /// Dynamic filter for pushing down to the probe side
    /// Set when dynamic filter pushdown is detected in handle_child_pushdown_result.
    /// HashJoinExec also needs to keep a shared bounds accumulator for coordinating updates.
    dynamic_filter: Option<HashJoinExecDynamicFilter>,
    /// Maximum number of rows to return
    fetch: Option<usize>,
}

#[derive(Clone)]
struct HashJoinExecDynamicFilter {
    /// Dynamic filter that we'll update with the results of the build side once that is done.
    filter: Arc<DynamicFilterPhysicalExpr>,
    /// Build accumulator to collect build-side information (hash maps and/or bounds) from each partition.
    /// It is lazily initialized during execution to make sure we use the actual execution time partition counts.
    build_accumulator: OnceLock<Arc<SharedBuildAccumulator>>,
}

impl fmt::Debug for HashJoinExec {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HashJoinExec")
            .field("left", &self.left)
            .field("right", &self.right)
            .field("on", &self.on)
            .field("filter", &self.filter)
            .field("join_type", &self.join_type)
            .field("join_schema", &self.join_schema)
            .field("left_fut", &self.left_fut)
            .field("prepared_build", &self.prepared_build)
            .field("random_state", &self.random_state)
            .field("mode", &self.mode)
            .field("null_aware", &self.null_aware)
            .field("null_aware_value_keys", &self.null_aware_value_keys)
            .field("metrics", &self.metrics)
            .field("projection", &self.projection)
            .field("column_indices", &self.column_indices)
            .field("null_equality", &self.null_equality)
            .field("cache", &self.cache)
            // Explicitly exclude dynamic_filter to avoid runtime state differences in tests
            .finish()
    }
}

impl EmbeddedProjection for HashJoinExec {
    fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
        self.with_projection(projection)
    }
}

impl HashJoinExec {
    /// Tries to create a new [`HashJoinExec`].
    ///
    /// # Error
    /// This function errors when it is not possible to join the left and right sides on keys `on`.
    #[expect(clippy::too_many_arguments)]
    pub fn try_new(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        filter: Option<JoinFilter>,
        join_type: &JoinType,
        projection: Option<Vec<usize>>,
        partition_mode: PartitionMode,
        null_equality: NullEquality,
        null_aware: bool,
    ) -> Result<Self> {
        HashJoinExecBuilder::new(left, right, on, *join_type)
            .with_filter(filter)
            .with_projection(projection)
            .with_partition_mode(partition_mode)
            .with_null_equality(null_equality)
            .with_null_aware(null_aware)
            .build()
    }

    /// Create a builder based on the existing [`HashJoinExec`].
    ///
    /// Returned builder preserves all existing fields. If a field requiring properties
    /// recomputation is modified, this will be done automatically during the node build.
    ///
    pub fn builder(&self) -> HashJoinExecBuilder {
        self.into()
    }

    fn create_dynamic_filter(on: &JoinOn) -> Arc<DynamicFilterPhysicalExpr> {
        // Extract the right-side keys (probe side keys) from the `on` clauses
        // Dynamic filter will be created from build side values (left side) and applied to probe side (right side)
        let right_keys: Vec<_> = on.iter().map(|(_, r)| Arc::clone(r)).collect();
        // Initialize with a placeholder expression (true) that will be updated when the hash table is built
        Arc::new(DynamicFilterPhysicalExpr::new(right_keys, lit(true)))
    }

    /// Join types whose output rows all carry a matching key on both sides.
    ///
    /// For these a parent filter over one side's join keys can be transferred
    /// to the other side's input: an input row that fails the transferred
    /// filter can only pair with rows that fail the original, so pruning it
    /// changes nothing, and once the transferred filter is applied exactly on
    /// one side every output row satisfies the original. Outer, anti and mark
    /// joins also emit unmatched rows, whose key on the other side is absent,
    /// so the transferred filter is not exact for them.
    fn supports_key_transfer(join_type: JoinType) -> bool {
        matches!(
            join_type,
            JoinType::Inner | JoinType::LeftSemi | JoinType::RightSemi
        )
    }

    /// Maps each output column that is a plain `Column` join key on one side
    /// to the key expression on the other side, as `(to_right, to_left)`.
    ///
    /// `column_indices` are the (projected) output columns of this join. A key
    /// column that appears in several `on` pairs maps to the first of them.
    fn key_transfer_maps(
        &self,
        column_indices: &[ColumnIndex],
    ) -> (KeyTransferMap, KeyTransferMap) {
        // A transferred filter compares the other side's key with literals
        // typed for this side's key. The planner coerces both keys to one
        // type, and `try_new` does not check it, so make the assumption
        // explicit here.
        debug_assert!(
            self.on.iter().all(|(left_key, right_key)| {
                left_key.data_type(&self.left.schema()).ok()
                    == right_key.data_type(&self.right.schema()).ok()
            }),
            "join key data types differ: {:?}",
            self.on
        );
        let mut to_right = HashMap::new();
        let mut to_left = HashMap::new();
        for (output_idx, ci) in column_indices.iter().enumerate() {
            let (map, other_key) = match ci.side {
                JoinSide::Left => (
                    &mut to_right,
                    self.on
                        .iter()
                        .find(|(left_key, _)| is_column_at(left_key, ci.index))
                        .map(|(_, right_key)| right_key),
                ),
                JoinSide::Right => (
                    &mut to_left,
                    self.on
                        .iter()
                        .find(|(_, right_key)| is_column_at(right_key, ci.index))
                        .map(|(left_key, _)| left_key),
                ),
                // Only mark joins produce mark columns, and
                // `supports_key_transfer` excludes them; this arm is here for
                // exhaustiveness.
                JoinSide::None => continue,
            };
            if let Some(other_key) = other_key {
                map.insert(output_idx, Arc::clone(other_key));
            }
        }
        (to_right, to_left)
    }

    fn allow_join_dynamic_filter_pushdown(&self, config: &ConfigOptions) -> bool {
        let (_, probe_preserved) = self.join_type.on_lr_is_preserved();
        if !probe_preserved || !config.optimizer.enable_join_dynamic_filter_pushdown {
            return false;
        }

        // Null-aware joins tolerate probe pruning only while the build side
        // has no NULL keys (the pushed filter keeps NULL-valued probe rows via
        // the `IS NULL` escape in `preserve_probe_nulls`, but prunes others):
        // - LeftAnti emits a build-side NULL only when the probe is truly
        //   empty, and pruning every probe row would surface that NULL wrongly.
        // - Null-aware LeftMark marks a NULL-valued build row UNKNOWN when any
        //   probe row shares its correlation scope, and a pruned probe row
        //   would be missed by that scan.
        // NOT NULL build keys rule out both, so the filter stays there.
        if self.null_aware
            && self.on.iter().any(|(build_key, _)| {
                build_key.nullable(&self.left.schema()).unwrap_or(true)
            })
        {
            return false;
        }

        // Under `preserve_file_partitions`, file groups can report Hash without following
        // the dynamic filter hash router and look like a real hash repartition, so reject
        // Hash. Range inputs with matching split points are safe.
        // Follow-up work: enable dynamic filtering for preserve_file_partitioned scans (issue #20195).
        // https://github.com/apache/datafusion/issues/20195
        if config.optimizer.preserve_file_partitions > 0
            && self.mode == PartitionMode::Partitioned
            && matches!(
                (
                    self.left.output_partitioning(),
                    self.right.output_partitioning()
                ),
                (Partitioning::Hash(_, _), Partitioning::Hash(_, _))
            )
        {
            return false;
        }

        if self.mode == PartitionMode::Partitioned
            && !self.has_partitioned_dynamic_filter_routing()
        {
            return false;
        }

        true
    }

    fn has_partitioned_dynamic_filter_routing(&self) -> bool {
        match (
            self.left.output_partitioning(),
            self.right.output_partitioning(),
        ) {
            (
                Partitioning::Hash(_, left_partition_count),
                Partitioning::Hash(_, right_partition_count),
            ) => left_partition_count == right_partition_count,
            (Partitioning::Range(_), Partitioning::Range(_)) => {
                let children = [self.left.as_ref(), self.right.as_ref()];
                matches!(
                    self.input_distribution_requirements()
                        .unsatisfied_co_partitioned_children(self.name(), &children),
                    Ok(unsatisfied) if unsatisfied.is_empty()
                )
            }
            (left_partitioning, right_partitioning) => {
                left_partitioning.partition_count() == 1
                    && right_partitioning.partition_count() == 1
            }
        }
    }

    /// left (build) side which gets hashed
    pub fn left(&self) -> &Arc<dyn ExecutionPlan> {
        &self.left
    }

    /// right (probe) side which are filtered by the hash table
    pub fn right(&self) -> &Arc<dyn ExecutionPlan> {
        &self.right
    }

    /// Set of common columns used to join on
    pub fn on(&self) -> &[(PhysicalExprRef, PhysicalExprRef)] {
        &self.on
    }

    /// Filters applied before join output
    pub fn filter(&self) -> Option<&JoinFilter> {
        self.filter.as_ref()
    }

    /// How the join is performed
    pub fn join_type(&self) -> &JoinType {
        &self.join_type
    }

    /// The schema after join. Please be careful when using this schema,
    /// if there is a projection, the schema isn't the same as the output schema.
    pub fn join_schema(&self) -> &SchemaRef {
        &self.join_schema
    }

    /// The partitioning mode of this hash join
    pub fn partition_mode(&self) -> &PartitionMode {
        &self.mode
    }

    /// Get null_equality
    pub fn null_equality(&self) -> NullEquality {
        self.null_equality
    }

    /// Returns the dynamic filter expression produced by this hash join, if set.
    #[deprecated(
        since = "55.0.0",
        note = "Use ExecutionPlan::dynamic_expressions_produced instead"
    )]
    pub fn dynamic_filter_expr(&self) -> Option<&Arc<DynamicFilterPhysicalExpr>> {
        self.dynamic_filter.as_ref().map(|df| &df.filter)
    }

    /// Set the dynamic filter on this hash join.
    ///
    /// Setting a dynamic filter is what makes the join compute and publish
    /// build-side bounds during execution. [`Self::handle_child_pushdown_result`]
    /// sets one after finding a consumer for it in the probe side. Callers wiring a
    /// filter up by hand take on that check themselves.
    ///
    /// Resets any internal state that depends on any existing dynamic filter.
    ///
    /// Validates that the filter's children reference valid columns in
    /// the probe (right) side's schema.
    #[deprecated(
        since = "56.0.0",
        note = "unused by DataFusion; `HashJoinExec` restores its dynamic filter in `HashJoinExec::try_from_proto`, which sets the field directly. There is no replacement; please open an issue if you have a use case for it."
    )]
    pub fn with_dynamic_filter_expr(
        self,
        filter: Arc<DynamicFilterPhysicalExpr>,
    ) -> Result<Self> {
        self.set_dynamic_filter(filter)
    }

    /// Set the dynamic filter on this hash join, resetting any internal state
    /// that depends on an existing one and validating that the filter's
    /// children reference valid columns in the probe (right) side's schema.
    ///
    /// Only used to restore the filter when decoding a serialized plan: every
    /// other code path installs the filter in
    /// [`ExecutionPlan::handle_child_pushdown_result`].
    fn set_dynamic_filter(
        mut self,
        filter: Arc<DynamicFilterPhysicalExpr>,
    ) -> Result<Self> {
        let probe_schema = self.right.schema();
        for child in filter.children() {
            child.data_type(&probe_schema)?;
        }
        self.dynamic_filter = Some(HashJoinExecDynamicFilter {
            filter,
            // Initialize with an empty accumulator which will be lazily populated
            // during execution.
            build_accumulator: OnceLock::new(),
        });
        Ok(self)
    }

    /// The null-aware semantics of this join, if [`Self::null_aware`] is set.
    ///
    /// Errors if `null_aware` is set on a join that does not support it.
    pub(super) fn not_in(&self) -> Result<Option<NotIn>> {
        self.null_aware
            .then(|| {
                NotIn::try_new(
                    self.join_type,
                    self.mode,
                    self.on.len(),
                    self.null_aware_value_keys,
                    self.filter.is_some(),
                )
            })
            .transpose()
    }

    /// Calculate order preservation flags for this hash join.
    fn maintains_input_order(join_type: JoinType) -> Vec<bool> {
        // The output follows the probe (right) order only when every output
        // row is produced while scanning the probe side. Joins that also emit
        // rows from the build-side visited bitmap at the end break that order.
        vec![false, !need_produce_result_in_final(join_type)]
    }

    /// Get probe side information for the hash join.
    pub fn probe_side() -> JoinSide {
        // In current implementation right side is always probe side.
        JoinSide::Right
    }

    /// Return whether the join contains a projection
    pub fn contains_projection(&self) -> bool {
        self.projection.is_some()
    }

    /// Return new instance of [HashJoinExec] with the given projection.
    pub fn with_projection(&self, projection: Option<Vec<usize>>) -> Result<Self> {
        let projection = projection.map(Into::into);
        //  check if the projection is valid
        can_project(&self.schema(), projection.as_deref())?;
        let projection =
            combine_projections(projection.as_ref(), self.projection.as_ref())?;
        self.builder().with_projection_ref(projection).build()
    }

    /// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
    fn compute_properties(
        left: &Arc<dyn ExecutionPlan>,
        right: &Arc<dyn ExecutionPlan>,
        schema: &SchemaRef,
        join_type: JoinType,
        on: JoinOnRef,
        mode: PartitionMode,
        projection: Option<&[usize]>,
    ) -> Result<PlanProperties> {
        // Calculate equivalence properties:
        let mut eq_properties = join_equivalence_properties(
            left.equivalence_properties().clone(),
            right.equivalence_properties().clone(),
            &join_type,
            Arc::clone(schema),
            &Self::maintains_input_order(join_type),
            Some(Self::probe_side()),
            on,
        )?;

        let mut output_partitioning = match mode {
            PartitionMode::CollectLeft => {
                asymmetric_join_output_partitioning(left, right, &join_type)?
            }
            PartitionMode::Auto => Partitioning::UnknownPartitioning(
                right.output_partitioning().partition_count(),
            ),
            PartitionMode::Partitioned => {
                symmetric_join_output_partitioning(left, right, &join_type)?
            }
        };

        let emission_type =
            // LeftSemi does not emit rows during probing. It records matching build-side
            // rows in a bitmap and can only emit them after the probe side is exhausted.
            if left.boundedness().is_unbounded() || join_type == JoinType::LeftSemi {
                EmissionType::Final
            } else if right.pipeline_behavior() == EmissionType::Incremental {
                // Unmatched build-side rows can only be emitted once the probe side
                // is exhausted; everything else is emitted incrementally.
                if emits_unmatched_left_rows(join_type) {
                    EmissionType::Both
                } else {
                    EmissionType::Incremental
                }
            } else {
                right.pipeline_behavior()
            };

        // If contains projection, update the PlanProperties.
        if let Some(projection) = projection {
            // construct a map from the input expressions to the output expression of the Projection
            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,
            emission_type,
            boundedness_from_children([left, right]),
        ))
    }

    /// Returns a new `ExecutionPlan` that computes the same join as this one,
    /// with the left and right inputs swapped using the  specified
    /// `partition_mode`.
    ///
    /// # Notes:
    ///
    /// This function is public so other downstream projects can use it to
    /// construct `HashJoinExec` with right side as the build side.
    ///
    /// For using this interface directly, please refer to below:
    ///
    /// Hash join execution may require specific input partitioning (for example,
    /// the left child may have a single partition while the right child has multiple).
    ///
    /// Calling this function on join nodes whose children have already been repartitioned
    /// (e.g., after a `RepartitionExec` has been inserted) may break the partitioning
    /// requirements of the hash join. Therefore, ensure you call this function
    /// before inserting any repartitioning operators on the join's children.
    ///
    /// In DataFusion's default SQL interface, this function is used by the `JoinSelection`
    /// physical optimizer rule to determine a good join order, which is
    /// executed before the `EnforceDistribution` rule (the rule that may
    /// insert `RepartitionExec` operators).
    ///
    /// # Public Only for Internal Use:
    ///
    /// This is not a public API and is for internal use only; see [API policy] for details.
    ///
    /// Direct use of this API in downstream projects is discouraged because
    /// correctness depends on strict preconditions. See the notes above for
    /// correct usage.
    ///
    /// This API may change frequently as internal join optimizations evolve.
    ///
    /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
    #[doc(hidden)]
    pub fn swap_inputs(
        &self,
        partition_mode: PartitionMode,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        assert_or_internal_err!(
            self.dynamic_filter.is_none(),
            "Cannot swap HashJoinExec inputs after dynamic filters have been constructed. \
             Optimizer rules that reorder join inputs must run before optimizer rules `FilterPushdown::new_post_optimization()`"
        );

        let left = self.left();
        let right = self.right();
        let new_join = self
            .builder()
            .with_type(self.join_type.swap())
            .with_new_children(vec![Arc::clone(right), Arc::clone(left)])?
            .with_on(
                self.on()
                    .iter()
                    .map(|(l, r)| (Arc::clone(r), Arc::clone(l)))
                    .collect(),
            )
            .with_filter(self.filter().map(JoinFilter::swap))
            .with_projection(swap_join_projection(
                left.schema().fields().len(),
                right.schema().fields().len(),
                self.projection.as_deref(),
                self.join_type(),
            ))
            .with_partition_mode(partition_mode)
            .build()?;
        // Semi / anti / mark joins output columns from one side only, so
        // swapping does not reorder them; an embedded projection already fixes
        // the order too. Otherwise a projection restores the original order.
        if is_existence_join(self.join_type) || self.projection.is_some() {
            Ok(Arc::new(new_join))
        } else {
            reorder_output_after_swap(Arc::new(new_join), &left.schema(), &right.schema())
        }
    }
}

impl DisplayAs for HashJoinExec {
    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
        match t {
            DisplayFormatType::Default | DisplayFormatType::Verbose => {
                let display_filter = self.filter.as_ref().map_or_else(
                    || "".to_string(),
                    |f| format!(", filter={}", f.expression()),
                );
                let display_projections = if self.contains_projection() {
                    format!(
                        ", projection=[{}]",
                        self.projection
                            .as_ref()
                            .unwrap()
                            .iter()
                            .map(|index| format!(
                                "{}@{}",
                                self.join_schema.fields().get(*index).unwrap().name(),
                                index
                            ))
                            .collect::<Vec<_>>()
                            .join(", ")
                    )
                } else {
                    "".to_string()
                };
                let display_null_equality =
                    if self.null_equality() == NullEquality::NullEqualsNull {
                        ", NullsEqual: true"
                    } else {
                        ""
                    };
                let display_fetch = self
                    .fetch
                    .map_or_else(String::new, |f| format!(", fetch={f}"));
                let display_null_aware =
                    match (self.null_aware, self.null_aware_value_keys) {
                        (false, _) => String::new(),
                        (true, 0 | 1) => ", null_aware".to_string(),
                        (true, n) => format!(", null_aware(value_keys={n})"),
                    };
                let display_prepared = self
                    .prepared_build
                    .as_ref()
                    .map_or_else(String::new, |prepared| {
                        format!(", prepared_build={} rows", prepared.num_rows())
                    });
                let on = self
                    .on
                    .iter()
                    .map(|(c1, c2)| format!("({c1}, {c2})"))
                    .collect::<Vec<String>>()
                    .join(", ");
                write!(
                    f,
                    "HashJoinExec: mode={:?}, join_type={:?}, on=[{}]{}{}{}{}{}{}",
                    self.mode,
                    self.join_type,
                    on,
                    display_filter,
                    display_projections,
                    display_null_equality,
                    display_fetch,
                    display_null_aware,
                    display_prepared,
                )
            }
            DisplayFormatType::TreeRender => {
                let on = self
                    .on
                    .iter()
                    .map(|(c1, c2)| {
                        format!("({} = {})", fmt_sql(c1.as_ref()), fmt_sql(c2.as_ref()))
                    })
                    .collect::<Vec<String>>()
                    .join(", ");

                if *self.join_type() != JoinType::Inner {
                    writeln!(f, "join_type={:?}", self.join_type)?;
                }

                writeln!(f, "on={on}")?;

                if let Some(prepared) = &self.prepared_build {
                    writeln!(f, "prepared_build={} rows", prepared.num_rows())?;
                }

                if self.null_equality() == NullEquality::NullEqualsNull {
                    writeln!(f, "NullsEqual: true")?;
                }

                if self.null_aware {
                    if self.null_aware_value_keys <= 1 {
                        writeln!(f, "null_aware")?;
                    } else {
                        writeln!(
                            f,
                            "null_aware(value_keys={})",
                            self.null_aware_value_keys
                        )?;
                    }
                }

                if let Some(filter) = self.filter.as_ref() {
                    writeln!(f, "filter={filter}")?;
                }

                if let Some(fetch) = self.fetch {
                    writeln!(f, "fetch={fetch}")?;
                }

                Ok(())
            }
        }
    }
}

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

    fn properties(&self) -> &Arc<PlanProperties> {
        &self.cache
    }

    fn required_input_distribution(&self) -> Vec<Distribution> {
        self.input_distribution_requirements().into_per_child()
    }

    fn input_distribution_requirements(&self) -> InputDistributionRequirements {
        match self.mode {
            PartitionMode::Partitioned => {
                let (left_expr, right_expr) = self
                    .on
                    .iter()
                    .map(|(l, r)| (Arc::clone(l), Arc::clone(r)))
                    .unzip();
                InputDistributionRequirements::co_partitioned(vec![
                    Distribution::KeyPartitioned(left_expr),
                    Distribution::KeyPartitioned(right_expr),
                ])
            }
            PartitionMode::CollectLeft => InputDistributionRequirements::new(vec![
                Distribution::SinglePartition,
                Distribution::UnspecifiedDistribution,
            ]),
            PartitionMode::Auto => InputDistributionRequirements::new(vec![
                Distribution::UnspecifiedDistribution,
                Distribution::UnspecifiedDistribution,
            ]),
        }
    }

    // For [JoinType::Inner] and [JoinType::RightSemi] in hash joins, the probe phase initiates by
    // applying the hash function to convert the join key(s) in each row into a hash value from the
    // probe side table in the order they're arranged. The hash value is used to look up corresponding
    // entries in the hash table that was constructed from the build side table during the build phase.
    //
    // Because of the immediate generation of result rows once a match is found,
    // the output of the join tends to follow the order in which the rows were read from
    // the probe side table. This is simply due to the sequence in which the rows were processed.
    // Hence, it appears that the hash join is preserving the order of the probe side.
    //
    // Meanwhile, in the case of a [JoinType::RightAnti] hash join,
    // the unmatched rows from the probe side are also kept in order.
    // This is because the **`RightAnti`** join is designed to return rows from the right
    // (probe side) table that have no match in the left (build side) table. Because the rows
    // are processed sequentially in the probe phase, and unmatched rows are directly output
    // as results, these results tend to retain the order of the probe side table.
    fn maintains_input_order(&self) -> Vec<bool> {
        Self::maintains_input_order(self.join_type)
    }

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

    fn apply_expressions(
        &self,
        f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
    ) -> Result<TreeNodeRecursion> {
        let join_keys = self
            .on
            .iter()
            .flat_map(|(left, right)| [Arc::clone(left), Arc::clone(right)]);
        let filter = self
            .filter
            .iter()
            .map(|filter| Arc::clone(filter.expression()));
        let dynamic_filter = self.dynamic_filter.iter().map(|dynamic_filter| {
            Arc::<DynamicFilterPhysicalExpr>::clone(&dynamic_filter.filter)
                as Arc<dyn PhysicalExpr>
        });
        crate::apply_expression_roots(join_keys.chain(filter).chain(dynamic_filter), f)
    }

    fn dynamic_expressions_produced(&self) -> Vec<Arc<dyn PhysicalExpr>> {
        self.dynamic_filter
            .iter()
            .map(|dynamic_filter| {
                Arc::<DynamicFilterPhysicalExpr>::clone(&dynamic_filter.filter)
                    as Arc<dyn PhysicalExpr>
            })
            .collect()
    }

    /// Creates a new HashJoinExec with different children while preserving configuration.
    ///
    /// This method is called during query optimization when the optimizer creates new
    /// plan nodes. Importantly, it creates a fresh bounds_accumulator via `try_new`
    /// rather than cloning the existing one because partitioning may have changed.
    fn replace_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
        options: ReplaceChildrenOptions,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        validate_child_count!(self, children);
        match options.children_properties {
            ChildrenPropertiesMode::Keep => {
                self.builder().with_new_children(children)?.build_exec()
            }
            ChildrenPropertiesMode::Recompute => self
                .builder()
                .recompute_properties()
                .with_new_children(children)?
                .build_exec(),
        }
    }

    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 reset_state(self: Arc<Self>) -> Result<Arc<dyn ExecutionPlan>> {
        self.builder().reset_state().build_exec()
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        let on_left = self
            .on
            .iter()
            .map(|on| Arc::clone(&on.0))
            .collect::<Vec<_>>();
        let left_partitions = self.left.output_partitioning().partition_count();
        let right_partitions = self.right.output_partitioning().partition_count();

        assert_or_internal_err!(
            self.mode != PartitionMode::Partitioned
                || left_partitions == right_partitions,
            "Invalid HashJoinExec, partition count mismatch {left_partitions}!={right_partitions},\
             consider using RepartitionExec"
        );

        assert_or_internal_err!(
            self.mode != PartitionMode::CollectLeft || left_partitions == 1,
            "Invalid HashJoinExec, the output partition count of the left child must be 1 in CollectLeft mode,\
             consider using CoalescePartitionsExec or the EnforceDistribution rule"
        );

        let enable_dynamic_filter_pushdown = self
            .allow_join_dynamic_filter_pushdown(context.session_config().options())
            && self.dynamic_filter.is_some();

        let join_metrics = BuildProbeJoinMetrics::new(partition, &self.metrics);

        let not_in = self.not_in()?;

        let array_map_created_count = MetricBuilder::new(&self.metrics)
            .with_category(MetricCategory::Rows)
            .counter(ARRAY_MAP_CREATED_COUNT_METRIC_NAME, partition);

        // Initialize build_accumulator lazily with runtime partition counts (only if enabled)
        // Use RepartitionExec's random state (seeds: 0,0,0,0) for partition routing
        let repartition_random_state = REPARTITION_RANDOM_STATE;
        let build_accumulator = enable_dynamic_filter_pushdown
            .then(|| {
                self.dynamic_filter.as_ref().map(|df| {
                    let filter = Arc::clone(&df.filter);
                    let on_right = self
                        .on
                        .iter()
                        .map(|(_, right_expr)| Arc::clone(right_expr))
                        .collect::<Vec<_>>();
                    Some(Arc::clone(df.build_accumulator.get_or_init(|| {
                        Arc::new(SharedBuildAccumulator::new_from_partition_mode(
                            self.mode,
                            self.left.as_ref(),
                            self.right.as_ref(),
                            filter,
                            on_right,
                            repartition_random_state,
                            self.null_equality,
                            not_in,
                            &context.session_config().options().optimizer,
                        ))
                    })))
                })
            })
            .flatten()
            .flatten();

        let left_fut = match (&self.prepared_build, self.mode) {
            (Some(prepared), _) => {
                // Public join fields can change after builder validation.
                prepared.validate(self)?;
                let prepared = Arc::clone(prepared);
                self.left_fut.try_once(|| {
                    Ok(async move { Ok(prepared.probe_data(right_partitions)) })
                })?
            }
            (None, PartitionMode::CollectLeft) => self.left_fut.try_once(|| {
                let left_stream = self.left.execute(0, Arc::clone(&context))?;

                let reservation =
                    MemoryConsumer::new("HashJoinInput").register(context.memory_pool());

                Ok(collect_left_input(
                    self.random_state.random_state().clone(),
                    left_stream,
                    on_left.clone(),
                    join_metrics.clone(),
                    reservation,
                    need_produce_result_in_final(self.join_type),
                    right_partitions,
                    enable_dynamic_filter_pushdown,
                    Arc::clone(context.session_config().options()),
                    self.null_equality,
                    not_in,
                    array_map_created_count,
                    BuildMode::Ordinary,
                ))
            })?,
            (None, PartitionMode::Partitioned) => {
                let left_stream = self.left.execute(partition, Arc::clone(&context))?;

                let reservation =
                    MemoryConsumer::new(format!("HashJoinInput[{partition}]"))
                        .register(context.memory_pool());
                OnceFut::new(collect_left_input(
                    self.random_state.random_state().clone(),
                    left_stream,
                    on_left.clone(),
                    join_metrics.clone(),
                    reservation,
                    need_produce_result_in_final(self.join_type),
                    1,
                    enable_dynamic_filter_pushdown,
                    Arc::clone(context.session_config().options()),
                    self.null_equality,
                    not_in,
                    array_map_created_count,
                    BuildMode::Ordinary,
                ))
            }
            (None, PartitionMode::Auto) => {
                return plan_err!(
                    "Invalid HashJoinExec, unsupported PartitionMode {:?} in execute()",
                    PartitionMode::Auto
                );
            }
        };

        let batch_size = context.session_config().batch_size();

        // we have the batches and the hash map with their keys. We can how create a stream
        // over the right that uses this information to issue new batches.
        let right_stream = self.right.execute(partition, context)?;

        // update column indices to reflect the projection
        let column_indices_after_projection = match self.projection.as_ref() {
            Some(projection) => projection
                .iter()
                .map(|i| self.column_indices[*i].clone())
                .collect(),
            None => self.column_indices.clone(),
        };

        let on_right = self
            .on
            .iter()
            .map(|(_, right_expr)| Arc::clone(right_expr))
            .collect::<Vec<_>>();

        Ok(Box::pin(HashJoinStream::new(
            partition,
            self.schema(),
            on_right,
            self.filter.clone(),
            self.join_type,
            right_stream,
            self.random_state.random_state().clone(),
            join_metrics,
            column_indices_after_projection,
            self.null_equality,
            HashJoinStreamState::WaitBuildSide,
            BuildSide::Initial(BuildSideInitialState { left_fut }),
            batch_size,
            vec![],
            self.right.output_ordering().is_some(),
            build_accumulator,
            self.mode,
            self.fetch,
        )))
    }

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

    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
        match (partition, self.mode) {
            // Left side is broadcast, so it always needs overall stats
            // Right side is partitioned, so it needs per-partition stats
            (Some(_), PartitionMode::CollectLeft) => {
                vec![ChildStats::At(None), ChildStats::At(partition)]
            }
            // For Partitioned mode, both sides are hash-partitioned symmetrically,
            // so each output partition uses the matching partition from both sides.
            (Some(_), PartitionMode::Partitioned) => {
                vec![ChildStats::At(partition), ChildStats::At(partition)]
            }
            // Overall stats requested, look up overall child stats.
            (None, _) => vec![ChildStats::At(None), ChildStats::At(None)],
            // Auto mode hasn't decided partitioning yet, so it needs
            // overall stats from both sides.
            (Some(_), PartitionMode::Auto) => {
                vec![ChildStats::At(None), ChildStats::At(None)]
            }
        }
    }

    fn statistics_from_inputs(
        &self,
        input_stats: &[Arc<Statistics>],
        args: &StatisticsArgs,
    ) -> Result<Arc<Statistics>> {
        let left_stats = if let Some(prepared) = &self.prepared_build {
            // The declared left child supplies the schema but is never executed.
            Statistics::new_unknown(self.left.schema().as_ref())
                .with_num_rows(Precision::Exact(prepared.num_rows()))
        } else {
            input_stats[0].as_ref().clone()
        };
        let right_stats = input_stats[1].as_ref().clone();
        let stats = estimate_join_statistics(
            left_stats,
            right_stats,
            &self.on,
            self.null_equality,
            &self.join_type,
            &self.join_schema,
        )?;
        // Project statistics if there is a projection
        let stats = stats.project(self.projection.as_ref());
        // Apply the fetch, which limits each output partition separately
        Ok(Arc::new(with_per_partition_fetch(
            stats,
            self.fetch,
            self.properties().output_partitioning().partition_count(),
            args,
        )?))
    }

    /// Tries to push `projection` down through `hash_join`. If possible, performs the
    /// pushdown and returns a new [`HashJoinExec`] as the top plan which has projections
    /// as its children. Otherwise, returns `None`.
    fn try_swapping_with_projection(
        &self,
        projection: &ProjectionExec,
    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
        // TODO: currently if there is projection in HashJoinExec, we can't push down projection to left or right input. Maybe we can pushdown the mixed projection later.
        if self.contains_projection() {
            return Ok(None);
        }
        if self.prepared_build.is_some() {
            return try_embed_projection(projection, self);
        }

        let schema = self.schema();
        if let Some(JoinData {
            projected_left_child,
            projected_right_child,
            join_filter,
            join_on,
        }) = try_pushdown_through_join_with_column_indices(
            projection,
            self.left(),
            self.right(),
            self.on(),
            &schema,
            self.filter(),
            self.column_indices.as_slice(),
        )? {
            self.builder()
                .with_new_children(vec![
                    Arc::new(projected_left_child),
                    Arc::new(projected_right_child),
                ])?
                .with_on(join_on)
                .with_filter(join_filter)
                // Returned early if projection is not None
                .with_projection(None)
                .build_exec()
                .map(Some)
        } else {
            try_embed_projection(projection, self)
        }
    }

    fn gather_filters_for_pushdown(
        &self,
        phase: FilterPushdownPhase,
        parent_filters: Vec<Arc<dyn PhysicalExpr>>,
        config: &ConfigOptions,
    ) -> Result<FilterDescription> {
        // This is the physical-plan equivalent of `push_down_all_join` in
        // `datafusion/optimizer/src/push_down_filter.rs`. That function uses `lr_is_preserved`
        // to decide which parent predicates can be pushed past a logical join to its children,
        // then checks column references to route each predicate to the correct side.
        //
        // We apply the same two-level logic here:
        // 1. `lr_is_preserved` gates whether a side is eligible at all.
        // 2. For each filter, we check that all column references belong to the
        //    target child (using `column_indices` to map output column positions
        //    to join sides). Columns are mapped by position, never by name:
        //    different join sides, or a nested join on one side, can produce
        //    columns with the same name (e.g. nested mark joins both producing
        //    "mark" columns, or several `id` columns).
        let (left_preserved, right_preserved) = lr_is_preserved(self.join_type);

        // Map each output position to its input position, accounting for the
        // join's projection.
        let column_indices: Vec<ColumnIndex> = match self.projection.as_ref() {
            Some(projection) => projection
                .iter()
                .map(|i| self.column_indices[*i].clone())
                .collect(),
            None => self.column_indices.clone(),
        };

        let (mut left_mapping, mut right_mapping) = (HashMap::new(), HashMap::new());
        for (output_idx, ci) in column_indices.iter().enumerate() {
            match ci.side {
                JoinSide::Left => {
                    left_mapping.insert(output_idx, ci.index);
                }
                JoinSide::Right => {
                    right_mapping.insert(output_idx, ci.index);
                }
                // Mark columns cannot be pushed to either side.
                JoinSide::None => {}
            }
        }

        // Transfer filters across the equi-join keys: a parent filter over one
        // side's join-key columns holds for every matching row of the other
        // side too, so it is also pushed there, rewritten over that side's key
        // expressions. This is how a dynamic filter from a join above reaches
        // the scans on both sides of this join, and how a semi join prunes its
        // non-output side. Like the plain column routing, a transfer only
        // targets a side that `lr_is_preserved` permits.
        let (to_right, to_left) = if Self::supports_key_transfer(self.join_type) {
            self.key_transfer_maps(&column_indices)
        } else {
            Default::default()
        };
        let describe_child = |preserved: bool,
                              column_mapping: HashMap<usize, usize>,
                              key_map: &KeyTransferMap,
                              child: &Arc<dyn ExecutionPlan>|
         -> Result<ChildFilterDescription> {
            if !preserved {
                return Ok(ChildFilterDescription::all_unsupported(&parent_filters));
            }
            let mut description = ChildFilterDescription::from_child_with_column_mapping(
                &parent_filters,
                column_mapping,
                child,
            )?;
            transfer_key_filters(&parent_filters, key_map, &mut description)?;
            Ok(description)
        };

        let left_child =
            describe_child(left_preserved, left_mapping, &to_left, self.left())?;
        let mut right_child =
            describe_child(right_preserved, right_mapping, &to_right, self.right())?;

        // Add dynamic filters in Post phase if enabled. Skip when this join
        // already carries a dynamic filter from a previous pass — the shared
        // `Arc<DynamicFilterPhysicalExpr>` is still wired into the probe-side
        // scan's predicate, and re-creating it would AND a fresh duplicate
        // onto every Post-phase invocation (apache/datafusion-ballista#1359
        // surfaces this in AQE replan loops).
        if phase == FilterPushdownPhase::Post
            && self.dynamic_filter.is_none()
            && self.allow_join_dynamic_filter_pushdown(config)
        {
            // Add actual dynamic filter to right side (probe side)
            let dynamic_filter = Self::create_dynamic_filter(&self.on);
            right_child = right_child.with_self_filter(dynamic_filter);
        }

        Ok(FilterDescription::new()
            .with_child(left_child)
            .with_child(right_child))
    }

    fn handle_child_pushdown_result(
        &self,
        _phase: FilterPushdownPhase,
        child_pushdown_result: ChildPushdownResult,
        _config: &ConfigOptions,
    ) -> Result<FilterPushdownPropagation<Arc<dyn ExecutionPlan>>> {
        let mut result = FilterPushdownPropagation::if_any(child_pushdown_result.clone());
        assert_eq!(child_pushdown_result.self_filters.len(), 2); // Should always be 2, we have 2 children
        let right_child_self_filters = &child_pushdown_result.self_filters[1]; // We only push down filters to the right child
        // We expect 0 or 1 self filters
        if let Some(filter) = right_child_self_filters.first() {
            let predicate = Arc::clone(&filter.predicate);
            if let Ok(dynamic_filter) =
                Arc::downcast::<DynamicFilterPhysicalExpr>(predicate)
            {
                // Note that we don't check `PushedDownPredicate::discriminant`: a node
                // that replies `PushedDown::No` may still retain the filter for
                // statistics pruning, so the reply does not tell us whether anyone will
                // actually read the filter. Instead we look for a consumer holding the
                // expression in the probe subtree.
                //
                // `self` here is the join with its post-pushdown children, so anything
                // that accepted the filter is already wired into `self.right`. Searching
                // from `self` would always find the producer expression pushed by this
                // join. This is the last chance to make the decision: the Post-phase
                // `FilterPushdown` rule is the final rule that mutates the plan.
                let has_consumer = dynamic_filter
                    .expression_id()
                    .map(|id| plan_contains_expression_id(&self.right, id))
                    .transpose()?
                    .unwrap_or(false);
                if has_consumer {
                    // Our self filter reached a consumer: rebuild the node holding onto
                    // the dynamic filter so that `execute` populates it from the build
                    // side. If it did not, we leave `dynamic_filter` as `None` and skip
                    // the (not cheap) bounds accumulation entirely.
                    let new_node = self
                        .builder()
                        .with_dynamic_filter(Some(HashJoinExecDynamicFilter {
                            filter: dynamic_filter,
                            build_accumulator: OnceLock::new(),
                        }))
                        .build_exec()?;
                    result = result.with_updated_node(new_node);
                }
            }
        }
        Ok(result)
    }

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

    fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn ExecutionPlan>> {
        self.builder()
            .with_fetch(limit)
            .build()
            .ok()
            .map(|exec| Arc::new(exec) as _)
    }
    #[cfg(feature = "proto")]
    fn try_to_proto(
        &self,
        ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
        use datafusion_common::internal_datafusion_err;
        use datafusion_proto_models::protobuf;

        // Destructure exhaustively (no `..`) so that a newly added field is a
        // compile error here instead of being silently left out of the proto.
        let Self {
            left,
            right,
            on,
            filter,
            join_type,
            mode,
            projection,
            null_equality,
            null_aware,
            null_aware_value_keys,
            dynamic_filter,
            fetch,
            // derived from the children's schemas by the builder on decode
            join_schema: _,
            // runtime build-side state, not part of the plan
            left_fut: _,
            prepared_build,
            // the fixed `HASH_JOIN_SEED` constant, set identically by the
            // builder on decode
            random_state: _,
            // runtime metrics, not part of the plan
            metrics: _,
            // recomputed by the builder on decode
            column_indices: _,
            // recomputed by the builder on decode
            cache: _,
        } = self;

        if prepared_build.is_some() {
            return datafusion_common::not_impl_err!(
                "HashJoinExec with a prepared build cannot be serialized"
            );
        }
        let left = ctx.encode_child(left)?;
        let right = ctx.encode_child(right)?;

        let on = on
            .iter()
            .map(|(l, r)| -> Result<protobuf::JoinOn> {
                Ok(protobuf::JoinOn {
                    left: Some(ctx.encode_expr(l)?),
                    right: Some(ctx.encode_expr(r)?),
                })
            })
            .collect::<Result<Vec<_>>>()?;

        let join_type = crate::joins::proto::join_type_to_proto(*join_type);
        let null_equality = crate::joins::proto::null_equality_to_proto(*null_equality);
        // `PartitionMode` is specific to `HashJoinExec`, so its conversion stays
        // inline (by-name on purpose: the enums are numbered differently).
        let partition_mode = match mode {
            PartitionMode::CollectLeft => protobuf::PartitionMode::CollectLeft,
            PartitionMode::Partitioned => protobuf::PartitionMode::Partitioned,
            PartitionMode::Auto => protobuf::PartitionMode::Auto,
        };

        let filter = filter
            .as_ref()
            .map(|f| crate::joins::proto::join_filter_to_proto(f, ctx))
            .transpose()?;

        let dynamic_filter = dynamic_filter
            .as_ref()
            .map(|df| {
                let df_expr: Arc<dyn PhysicalExpr> =
                    Arc::clone(&df.filter) as Arc<dyn PhysicalExpr>;
                ctx.encode_expr(&df_expr)
            })
            .transpose()?;

        Ok(Some(protobuf::PhysicalPlanNode {
            physical_plan_type: Some(
                protobuf::physical_plan_node::PhysicalPlanType::HashJoin(Box::new(
                    protobuf::HashJoinExecNode {
                        left: Some(Box::new(left)),
                        right: Some(Box::new(right)),
                        on,
                        join_type: join_type.into(),
                        partition_mode: partition_mode.into(),
                        null_equality: null_equality.into(),
                        filter,
                        // Proto3 `repeated` cannot distinguish `None` from
                        // `Some(vec![])`. `Some(vec![])` (reachable via
                        // `try_embed_projection` for e.g. `SELECT count(1) … JOIN …`)
                        // changes the output schema, so it is encoded with the
                        // single-element sentinel `[u32::MAX]` (never a valid column
                        // index); every other state is sent as-is. See
                        // `try_from_proto` for the matching decoder.
                        projection: match projection.as_ref() {
                            None => Vec::new(),
                            Some(v) if v.is_empty() => vec![u32::MAX],
                            Some(v) => v.iter().map(|x| *x as u32).collect(),
                        },
                        null_aware: *null_aware,
                        null_aware_value_keys: u32::try_from(*null_aware_value_keys)
                            .map_err(|_| {
                                internal_datafusion_err!(
                                    "HashJoinExec: null_aware_value_keys {null_aware_value_keys} does not fit in u32"
                                )
                            })?,
                        dynamic_filter,
                        fetch: fetch.map(|f| f as u64),
                    },
                )),
            ),
        }))
    }
}

#[cfg(feature = "proto")]
impl HashJoinExec {
    /// Reconstruct a [`HashJoinExec`] from its protobuf representation.
    pub fn try_from_proto(
        node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
        ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        use datafusion_common::{internal_datafusion_err, utils::usize_from_wire};
        use datafusion_proto_models::protobuf;
        use std::any::Any;

        let hashjoin = crate::expect_plan_variant!(
            node,
            protobuf::physical_plan_node::PhysicalPlanType::HashJoin,
            "HashJoinExec",
        );

        // Destructure exhaustively (no `..`) so that a newly added proto field
        // is a compile error here instead of being silently ignored.
        let protobuf::HashJoinExecNode {
            left,
            right,
            on,
            join_type,
            partition_mode,
            null_equality,
            filter,
            projection,
            null_aware,
            null_aware_value_keys,
            dynamic_filter,
            fetch,
        } = &**hashjoin;

        let left = ctx.decode_required_child(left.as_deref(), "HashJoinExec", "left")?;
        let right =
            ctx.decode_required_child(right.as_deref(), "HashJoinExec", "right")?;
        let left_schema = left.schema();
        let right_schema = right.schema();

        let on: Vec<(PhysicalExprRef, PhysicalExprRef)> = on
            .iter()
            .map(|col| {
                let l = ctx.decode_required_expr(
                    col.left.as_ref(),
                    left_schema.as_ref(),
                    "HashJoinExec",
                    "on.left",
                )?;
                let r = ctx.decode_required_expr(
                    col.right.as_ref(),
                    right_schema.as_ref(),
                    "HashJoinExec",
                    "on.right",
                )?;
                Ok((l, r))
            })
            .collect::<Result<_>>()?;

        let join_type =
            crate::joins::proto::join_type_from_proto(*join_type, "HashJoinExec")?;
        let null_equality = crate::joins::proto::null_equality_from_proto(
            *null_equality,
            "HashJoinExec",
        )?;
        // `PartitionMode` is specific to `HashJoinExec`, so its conversion stays
        // inline (by-name on purpose: the enums are numbered differently).
        let partition_mode = match protobuf::PartitionMode::try_from(*partition_mode)
            .map_err(|_| {
                internal_datafusion_err!(
                    "HashJoinExec: unknown PartitionMode {partition_mode}"
                )
            })? {
            protobuf::PartitionMode::CollectLeft => PartitionMode::CollectLeft,
            protobuf::PartitionMode::Partitioned => PartitionMode::Partitioned,
            protobuf::PartitionMode::Auto => PartitionMode::Auto,
        };

        let filter = filter
            .as_ref()
            .map(|f| crate::joins::proto::join_filter_from_proto(f, ctx, "HashJoinExec"))
            .transpose()?;

        // Preserve the empty-projection sentinel written by `try_to_proto`.
        let projection = match projection.as_slice() {
            [] => None,
            [u32::MAX] => Some(Vec::new()),
            indices => Some(indices.iter().map(|i| *i as usize).collect()),
        };

        // Restore the row limit that `limit_pushdown` may have pushed into the
        // join. The field is presence-tracked, so a message written before it
        // existed decodes to `None` (no limit) rather than to `Some(0)`.
        let fetch = fetch
            .map(|fetch| usize_from_wire(fetch, "HashJoinExec", "fetch"))
            .transpose()?;

        let mut hash_join = HashJoinExecBuilder::new(left, right, on, join_type)
            .with_filter(filter)
            .with_projection(projection)
            .with_partition_mode(partition_mode)
            .with_null_equality(null_equality)
            .with_null_aware(*null_aware)
            // `0` is an unset count, which `build` accepts only for a single
            // key. Messages predating the field decode it as 0; they can only
            // hold scalar `NOT IN` joins.
            .with_null_aware_value_keys(usize_from_wire(
                u64::from(*null_aware_value_keys),
                "HashJoinExec",
                "null_aware_value_keys",
            )?)
            .with_fetch(fetch)
            .build()?;

        if let Some(dynamic_filter_proto) = dynamic_filter {
            // The dynamic filter is a `DynamicFilterPhysicalExpr` over the probe
            // (right) side; decode against the right schema then downcast.
            let dynamic_filter_expr =
                ctx.decode_expr(dynamic_filter_proto, right_schema.as_ref())?;
            let df = (dynamic_filter_expr as Arc<dyn Any + Send + Sync>)
                .downcast::<DynamicFilterPhysicalExpr>()
                .map_err(|_| {
                    internal_datafusion_err!(
                        "HashJoinExec dynamic_filter did not decode to a DynamicFilterPhysicalExpr"
                    )
                })?;
            hash_join = hash_join.set_dynamic_filter(df)?;
        }

        Ok(Arc::new(hash_join))
    }
}

/// Field-level tests for the `try_to_proto` / `try_from_proto` hooks.
///
/// These cover the three states of `projection` that proto3 cannot express
/// directly (the `[u32::MAX]` sentinel), `fetch` presence semantics — the field
/// dropped in #24165, which the central `Debug`-comparing round-trip tests
/// could not see — and the by-name `PartitionMode` mapping, whose discriminants
/// deliberately differ between the plan and the wire.
#[cfg(all(test, feature = "proto"))]
mod proto_tests {
    use super::*;
    use crate::proto::{ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx};
    use crate::proto_test_util::{
        StubPlanDecoder, StubPlanEncoder, UnreachablePlanDecoder, column_node,
        encoded_child_node, stub_child,
    };
    use datafusion_physical_expr::expressions::Column;
    use datafusion_proto_models::protobuf;

    /// An inner hash join on `a = a` between two stub children.
    fn join_builder() -> HashJoinExecBuilder {
        let on: Vec<(PhysicalExprRef, PhysicalExprRef)> =
            vec![(Arc::new(Column::new("a", 0)), Arc::new(Column::new("a", 0)))];
        HashJoinExecBuilder::new(stub_child(), stub_child(), on, JoinType::Inner)
    }

    /// Encode `plan` with a stub encoder, returning the `HashJoinExecNode`.
    fn encode(
        plan: &HashJoinExec,
        encoder: &StubPlanEncoder,
    ) -> protobuf::HashJoinExecNode {
        let ctx = ExecutionPlanEncodeCtx::new(encoder);
        let node = plan
            .try_to_proto(&ctx)
            .unwrap()
            .expect("HashJoinExec should encode to Some(node)");
        match node.physical_plan_type {
            Some(protobuf::physical_plan_node::PhysicalPlanType::HashJoin(join)) => *join,
            other => panic!("expected a HashJoin node, got {other:?}"),
        }
    }

    /// Encode a join whose only non-default state is its projection.
    fn encode_projection(projection: Option<Vec<usize>>) -> Vec<u32> {
        let plan = join_builder().with_projection(projection).build().unwrap();
        encode(&plan, &StubPlanEncoder::ok()).projection
    }

    /// A hand-built `HashJoinExecNode` wrapped in its `PhysicalPlanNode`.
    fn join_node(node: protobuf::HashJoinExecNode) -> protobuf::PhysicalPlanNode {
        protobuf::PhysicalPlanNode {
            physical_plan_type: Some(
                protobuf::physical_plan_node::PhysicalPlanType::HashJoin(Box::new(node)),
            ),
        }
    }

    /// A decodable `HashJoinExecNode`: two children, one join key, no filter.
    fn decodable_node() -> protobuf::HashJoinExecNode {
        protobuf::HashJoinExecNode {
            left: Some(Box::new(encoded_child_node())),
            right: Some(Box::new(encoded_child_node())),
            on: vec![protobuf::JoinOn {
                left: Some(column_node("a", 0)),
                right: Some(column_node("a", 0)),
            }],
            join_type: protobuf::JoinType::Inner.into(),
            partition_mode: protobuf::PartitionMode::Partitioned.into(),
            null_equality: protobuf::NullEquality::NullEqualsNothing.into(),
            filter: None,
            projection: vec![],
            null_aware: false,
            null_aware_value_keys: 0,
            dynamic_filter: None,
            fetch: None,
        }
    }

    /// Decode `node` with a stub decoder.
    fn decode(node: protobuf::HashJoinExecNode) -> Arc<dyn ExecutionPlan> {
        let decoder = StubPlanDecoder::ok();
        let ctx = ExecutionPlanDecodeCtx::new(&decoder);
        HashJoinExec::try_from_proto(&join_node(node), &ctx).unwrap()
    }

    /// View a decoded plan as the `HashJoinExec` it must be.
    fn as_join(plan: &Arc<dyn ExecutionPlan>) -> &HashJoinExec {
        plan.downcast_ref::<HashJoinExec>()
            .expect("decoded plan should be a HashJoinExec")
    }

    /// "No projection" is the empty repeated field.
    #[test]
    fn try_to_proto_encodes_an_absent_projection_as_empty() {
        assert_eq!(encode_projection(None), Vec::<u32>::new());
    }

    /// An *empty* projection changes the output schema, so it cannot share the
    /// "absent" encoding: it goes out as the `[u32::MAX]` sentinel.
    #[test]
    fn try_to_proto_encodes_an_empty_projection_as_the_sentinel() {
        assert_eq!(encode_projection(Some(vec![])), vec![u32::MAX]);
    }

    #[test]
    fn try_to_proto_encodes_a_non_empty_projection_as_is() {
        assert_eq!(encode_projection(Some(vec![0, 2])), vec![0, 2]);
    }

    #[test]
    fn try_from_proto_decodes_an_empty_projection_field_as_absent() {
        let plan = decode(decodable_node());

        assert!(as_join(&plan).projection.is_none());
    }

    #[test]
    fn try_from_proto_decodes_the_sentinel_as_an_empty_projection() {
        let mut node = decodable_node();
        node.projection = vec![u32::MAX];

        let plan = decode(node);
        let projection = as_join(&plan)
            .projection
            .as_ref()
            .expect("the sentinel decodes to Some(empty)");
        assert!(projection.is_empty());
    }

    #[test]
    fn try_from_proto_decodes_a_non_empty_projection_as_is() {
        let mut node = decodable_node();
        node.projection = vec![0, 2];

        let plan = decode(node);
        assert_eq!(
            as_join(&plan).projection.as_deref(),
            Some([0, 2].as_slice())
        );
    }

    /// The regression guard for #24165: an unlimited join must not encode as
    /// `Some(0)`, and a limited one must keep its limit.
    #[test]
    fn try_to_proto_encodes_fetch_by_presence() {
        let unlimited = join_builder().build().unwrap();
        assert_eq!(encode(&unlimited, &StubPlanEncoder::ok()).fetch, None);

        let limited = join_builder().with_fetch(Some(10)).build().unwrap();
        assert_eq!(encode(&limited, &StubPlanEncoder::ok()).fetch, Some(10));

        let empty = join_builder().with_fetch(Some(0)).build().unwrap();
        assert_eq!(encode(&empty, &StubPlanEncoder::ok()).fetch, Some(0));
    }

    /// A message written before `fetch` existed has no value on the wire, and
    /// must decode to "no limit" rather than to `Some(0)` ("no rows").
    #[test]
    fn try_from_proto_decodes_an_absent_fetch_as_no_limit() {
        assert_eq!(as_join(&decode(decodable_node())).fetch, None);
    }

    #[test]
    fn try_from_proto_decodes_a_present_fetch() {
        let mut node = decodable_node();
        node.fetch = Some(10);
        assert_eq!(as_join(&decode(node)).fetch, Some(10));

        let mut node = decodable_node();
        node.fetch = Some(0);
        assert_eq!(as_join(&decode(node)).fetch, Some(0));
    }

    /// `fetch` is a `u64` on the wire and a `usize` in the plan. The conversion
    /// is checked rather than `as usize`, so a value too large for the target
    /// is reported instead of truncated — on a 64-bit target every `u64` fits,
    /// and the largest one must come back intact rather than wrapping.
    #[test]
    #[cfg(target_pointer_width = "64")]
    fn try_from_proto_decodes_the_largest_fetch_without_truncating() {
        let plan = decode({
            let mut node = decodable_node();
            node.fetch = Some(u64::MAX);
            node
        });

        assert_eq!(as_join(&plan).fetch, Some(usize::MAX));
    }

    /// The plan-side and wire-side `PartitionMode` discriminants differ, so the
    /// mapping has to be by name in both directions.
    #[test]
    fn partition_mode_round_trips_by_name() {
        for (mode, wire) in [
            (
                PartitionMode::CollectLeft,
                protobuf::PartitionMode::CollectLeft,
            ),
            (
                PartitionMode::Partitioned,
                protobuf::PartitionMode::Partitioned,
            ),
            (PartitionMode::Auto, protobuf::PartitionMode::Auto),
        ] {
            let plan = join_builder().with_partition_mode(mode).build().unwrap();
            let node = encode(&plan, &StubPlanEncoder::ok());
            assert_eq!(node.partition_mode, i32::from(wire), "encoding {mode:?}");

            let mut decodable = decodable_node();
            decodable.partition_mode = node.partition_mode;
            assert_eq!(*as_join(&decode(decodable)).partition_mode(), mode);
        }
    }

    #[test]
    fn try_from_proto_rejects_an_unknown_partition_mode() {
        let decoder = StubPlanDecoder::ok();
        let ctx = ExecutionPlanDecodeCtx::new(&decoder);
        let mut node = decodable_node();
        node.partition_mode = 42;

        let err = HashJoinExec::try_from_proto(&join_node(node), &ctx).unwrap_err();
        assert!(
            err.to_string()
                .contains("HashJoinExec: unknown PartitionMode 42")
        );
    }

    /// `null_aware` is only legal on a `LeftAnti` join, so the round trip has
    /// to carry the join type with it.
    #[test]
    fn null_aware_round_trips() {
        let plan = join_builder()
            .with_type(JoinType::LeftAnti)
            .with_null_aware(true)
            .build()
            .unwrap();
        assert!(encode(&plan, &StubPlanEncoder::ok()).null_aware);

        let mut node = decodable_node();
        node.join_type = protobuf::JoinType::Leftanti.into();
        node.null_aware = true;
        // `decodable_node` is `Partitioned`, which a null-aware join rejects
        // (see `try_from_proto_rejects_a_null_aware_partitioned_join`).
        node.partition_mode = protobuf::PartitionMode::CollectLeft.into();
        assert!(as_join(&decode(node)).null_aware);
    }

    /// A null-aware join decides in the final stage from state shared across
    /// the probe partitions, which `PartitionMode::Partitioned` does not give
    /// it. Decoding goes through the same builder as `try_new`, so a node
    /// written with that combination is rejected rather than silently
    /// returning rows for a `NOT IN` whose subquery contains NULL.
    #[test]
    fn try_from_proto_rejects_a_null_aware_partitioned_join() {
        let decoder = StubPlanDecoder::ok();
        let ctx = ExecutionPlanDecodeCtx::new(&decoder);
        let mut node = decodable_node();
        node.join_type = protobuf::JoinType::Leftanti.into();
        node.null_aware = true;
        assert_eq!(
            node.partition_mode,
            protobuf::PartitionMode::Partitioned as i32
        );

        let err = HashJoinExec::try_from_proto(&join_node(node), &ctx).unwrap_err();
        assert!(
            err.to_string()
                .contains("null_aware joins require PartitionMode::CollectLeft"),
            "{err}"
        );
    }

    /// A multi-column `NOT IN` keeps its value key count through the round
    /// trip. A count of 0, which is also how a node written before the field
    /// existed decodes it, stays unset: accepted for a single key, rejected
    /// for more.
    #[test]
    fn null_aware_value_keys_round_trip() {
        let on: Vec<(PhysicalExprRef, PhysicalExprRef)> = vec![
            (Arc::new(Column::new("a", 0)), Arc::new(Column::new("a", 0))),
            (Arc::new(Column::new("a", 0)), Arc::new(Column::new("a", 0))),
        ];
        let plan =
            HashJoinExecBuilder::new(stub_child(), stub_child(), on, JoinType::LeftAnti)
                .with_partition_mode(PartitionMode::CollectLeft)
                .with_null_aware(true)
                .with_null_aware_value_keys(2)
                .build()
                .unwrap();
        assert_eq!(
            encode(&plan, &StubPlanEncoder::ok()).null_aware_value_keys,
            2
        );

        let mut node = decodable_node();
        node.join_type = protobuf::JoinType::Leftanti.into();
        node.partition_mode = protobuf::PartitionMode::CollectLeft.into();
        node.null_aware = true;
        node.on = vec![node.on[0].clone(), node.on[0].clone()];
        node.null_aware_value_keys = 2;
        assert_eq!(as_join(&decode(node.clone())).null_aware_value_keys, 2);

        node.null_aware_value_keys = 0;
        let decoder = StubPlanDecoder::ok();
        let ctx = ExecutionPlanDecodeCtx::new(&decoder);
        let err =
            HashJoinExec::try_from_proto(&join_node(node.clone()), &ctx).unwrap_err();
        assert!(
            err.to_string().contains("with_null_aware_value_keys"),
            "{err}"
        );

        node.on.truncate(1);
        assert_eq!(as_join(&decode(node)).null_aware_value_keys, 0);
    }

    #[test]
    fn try_to_proto_encodes_both_children_and_both_key_sides() {
        let encoder = StubPlanEncoder::ok();
        let node = encode(&join_builder().build().unwrap(), &encoder);

        assert_eq!(encoder.plan_calls(), 2);
        assert_eq!(encoder.expr_calls(), 2);
        assert_eq!(node.left, Some(Box::new(encoded_child_node())));
        assert_eq!(node.right, Some(Box::new(encoded_child_node())));
    }

    #[test]
    fn try_to_proto_propagates_child_encode_error() {
        let plan = join_builder().build().unwrap();
        let encoder = StubPlanEncoder::failing_on_plan(2);
        let ctx = ExecutionPlanEncodeCtx::new(&encoder);

        let err = plan.try_to_proto(&ctx).unwrap_err();
        assert!(
            err.to_string()
                .contains("stub plan encode failure on call 2")
        );
    }

    #[test]
    fn try_from_proto_rejects_a_different_plan_variant() {
        let decoder = UnreachablePlanDecoder::new();
        let ctx = ExecutionPlanDecodeCtx::new(&decoder);

        let err = HashJoinExec::try_from_proto(&encoded_child_node(), &ctx).unwrap_err();
        assert!(err.to_string().contains("not a HashJoinExec"));
    }

    #[test]
    fn try_from_proto_rejects_a_missing_child() {
        let decoder = UnreachablePlanDecoder::new();
        let ctx = ExecutionPlanDecodeCtx::new(&decoder);
        let mut node = decodable_node();
        node.left = None;

        let err = HashJoinExec::try_from_proto(&join_node(node), &ctx).unwrap_err();
        assert!(
            err.to_string()
                .contains("HashJoinExec is missing required field 'left'")
        );
    }
}

/// Output column index of a join, mapped to the equivalent join-key expression
/// on the other side of the join (in that side's input schema).
type KeyTransferMap = HashMap<usize, PhysicalExprRef>;

fn is_column_at(expr: &PhysicalExprRef, index: usize) -> bool {
    expr.downcast_ref::<Column>()
        .is_some_and(|column| column.index() == index)
}

/// Marks every parent filter whose columns are all join keys in `key_map` as
/// supported for `child`, rewritten over the other side's key expressions.
///
/// `key_map` only holds columns of the other side, so a filter it rewrites is
/// one the plain column analysis marked unsupported for `child`. A filter that
/// references any other column is left as that analysis routed it. A filter
/// with no columns comes back unchanged and was already accepted, so
/// rewriting it is a no-op.
fn transfer_key_filters(
    parent_filters: &[Arc<dyn PhysicalExpr>],
    key_map: &KeyTransferMap,
    child: &mut ChildFilterDescription,
) -> Result<()> {
    if key_map.is_empty() {
        return Ok(());
    }
    for (filter, pushed) in parent_filters.iter().zip(child.parent_filters.iter_mut()) {
        if let Some(transferred) = transfer_filter_across_keys(filter, key_map)? {
            *pushed = PushedDownPredicate::supported(transferred);
        }
    }
    Ok(())
}

/// Rewrites `filter` over the other side's join keys, or returns `None` when
/// it references a column that is not a transferable key.
///
/// A [`DynamicFilterPhysicalExpr`] comes out as a view sharing the original's
/// state with its key columns remapped, so it keeps tracking the build side.
fn transfer_filter_across_keys(
    filter: &Arc<dyn PhysicalExpr>,
    key_map: &KeyTransferMap,
) -> Result<Option<Arc<dyn PhysicalExpr>>> {
    let mut all_keys = true;
    let transformed = Arc::clone(filter).transform_down(|expr| {
        let Some(column) = expr.downcast_ref::<Column>() else {
            return Ok(Transformed::no(expr));
        };
        match key_map.get(&column.index()) {
            // The replacement is in the other side's input schema, so its
            // columns are not output indices of this join: `Jump` over it.
            // Descending would substitute again whenever the key column's
            // index is also an output index, e.g. `CAST(k@0 AS Int64)` for
            // output column 0, and never terminate.
            Some(other_key) => Ok(Transformed::new(
                Arc::clone(other_key),
                true,
                TreeNodeRecursion::Jump,
            )),
            None => {
                all_keys = false;
                Ok(Transformed::new(expr, false, TreeNodeRecursion::Stop))
            }
        }
    })?;
    Ok(all_keys.then_some(transformed.data))
}

/// Determines which sides of a join are "preserved" for filter pushdown.
///
/// A preserved side means filters on that side's columns can be safely pushed
/// below the join. This mostly mirrors the logical optimizer's `lr_is_preserved`;
/// semi joins additionally allow join-key filters on the non-output side.
fn lr_is_preserved(join_type: JoinType) -> (bool, bool) {
    match join_type {
        JoinType::Inner => (true, true),
        JoinType::Left => (true, false),
        JoinType::Right => (false, true),
        JoinType::Full => (false, false),
        // A semi join emits only matched rows, so pruning either input by a
        // filter its output satisfies is exact. The non-output side has no
        // output columns, so the column routing sends it nothing but
        // column-free filters; key filters reach it through the transfer in
        // `HashJoinExec::gather_filters_for_pushdown`.
        JoinType::LeftSemi | JoinType::RightSemi => (true, true),
        JoinType::LeftAnti | JoinType::LeftMark => (true, false),
        JoinType::RightAnti | JoinType::RightMark => (false, true),
    }
}

/// Accumulator for collecting min/max bounds from build-side data during hash join.
///
/// This struct encapsulates the logic for progressively computing column bounds
/// (minimum and maximum values) for a specific join key expression as batches
/// are processed during the build phase of a hash join.
///
/// The bounds are used for dynamic filter pushdown optimization, where filters
/// based on the actual data ranges can be pushed down to the probe side to
/// eliminate unnecessary data early.
struct CollectLeftAccumulator {
    /// The physical expression to evaluate for each batch
    expr: Arc<dyn PhysicalExpr>,
    /// Accumulator for tracking the minimum value across all batches
    min: MinAccumulator,
    /// Accumulator for tracking the maximum value across all batches
    max: MaxAccumulator,
}

impl CollectLeftAccumulator {
    /// Creates a new accumulator for tracking bounds of a join key expression.
    ///
    /// # Arguments
    /// * `expr` - The physical expression to track bounds for
    /// * `schema` - The schema of the input data
    ///
    /// # Returns
    /// A new `CollectLeftAccumulator` instance configured for the expression's data type
    fn try_new(expr: Arc<dyn PhysicalExpr>, schema: &SchemaRef) -> Result<Self> {
        /// Recursively unwraps dictionary types to get the underlying value type.
        fn dictionary_value_type(data_type: &DataType) -> DataType {
            match data_type {
                DataType::Dictionary(_, value_type) => {
                    dictionary_value_type(value_type.as_ref())
                }
                _ => data_type.clone(),
            }
        }

        let data_type = expr
            .data_type(schema)
            // Min/Max can operate on dictionary data but expect to be initialized with the underlying value type
            .map(|dt| dictionary_value_type(&dt))?;
        Ok(Self {
            expr,
            min: MinAccumulator::try_new(&data_type)?,
            max: MaxAccumulator::try_new(&data_type)?,
        })
    }

    /// Updates the accumulators with values from a new batch.
    ///
    /// Evaluates the expression on the batch and updates both min and max
    /// accumulators with the resulting values.
    ///
    /// # Arguments
    /// * `batch` - The record batch to process
    ///
    /// # Returns
    /// Ok(()) if the update succeeds, or an error if expression evaluation fails
    fn update_batch(&mut self, batch: &RecordBatch) -> Result<()> {
        let array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
        self.min.update_batch(std::slice::from_ref(&array))?;
        self.max.update_batch(std::slice::from_ref(&array))?;
        Ok(())
    }

    /// Finalizes the accumulation and returns the computed bounds.
    ///
    /// Consumes self to extract the final min and max values from the accumulators.
    ///
    /// # Returns
    /// The `ColumnBounds` containing the minimum and maximum values observed
    fn evaluate(mut self) -> Result<ColumnBounds> {
        Ok(ColumnBounds::new(
            self.min.evaluate()?,
            self.max.evaluate()?,
        ))
    }
}

#[derive(PartialEq, Eq)]
enum BuildMode {
    Ordinary,
    Prepared,
}

/// State for collecting the build-side data during hash join
struct BuildSideState {
    batches: Vec<RecordBatch>,
    num_rows: usize,
    metrics: BuildProbeJoinMetrics,
    reservation: MemoryReservation,
    bounds_accumulators: Option<Vec<CollectLeftAccumulator>>,
    /// Counts the memory of `batches` for `reservation`. Batches can share
    /// underlying buffers (e.g. when the input emits zero-copy slices of one
    /// larger batch), so each buffer must be reserved only once.
    memory_counter: RecordBatchMemoryCounter,
}

impl BuildSideState {
    /// Create a new BuildSideState with optional accumulators for bounds computation
    fn try_new(
        metrics: BuildProbeJoinMetrics,
        reservation: MemoryReservation,
        on_left: Vec<Arc<dyn PhysicalExpr>>,
        schema: &SchemaRef,
        should_compute_dynamic_filters: bool,
    ) -> Result<Self> {
        Ok(Self {
            batches: Vec::new(),
            num_rows: 0,
            metrics,
            reservation,
            memory_counter: RecordBatchMemoryCounter::new(),
            bounds_accumulators: should_compute_dynamic_filters
                .then(|| {
                    on_left
                        .into_iter()
                        .map(|expr| CollectLeftAccumulator::try_new(expr, schema))
                        .collect::<Result<Vec<_>>>()
                })
                .transpose()?,
        })
    }
}

/// Returns whether the build side could be joined with an [`ArrayMap`]
/// (perfect hash join): a single join key of a supported integer type.
///
/// Only a candidate: the final decision also depends on the observed key
/// range and density, see [`array_map_key_range`].
fn is_perfect_hash_join_candidate(
    on_left: &[PhysicalExprRef],
    schema: &SchemaRef,
) -> Result<bool> {
    if on_left.len() != 1 {
        return Ok(false);
    }

    let expr = &on_left[0];
    let data_type = expr.data_type(schema)?;
    Ok(ArrayMap::is_supported_type(&data_type))
}

pub(super) fn new_join_hashmap(
    num_rows: usize,
    reservation: &mut MemoryReservation,
    metrics: &BuildProbeJoinMetrics,
) -> Result<Box<dyn JoinHashMapType>> {
    let fixed_size_u32 = size_of::<JoinHashMapU32>();
    let fixed_size_u64 = size_of::<JoinHashMapU64>();

    if num_rows > u32::MAX as usize {
        let estimated_hashtable_size =
            estimate_memory_size::<(u64, u64)>(num_rows, fixed_size_u64)?
                // Each build row also owns an index in the duplicate-key chain.
                .checked_add(num_rows * size_of::<u64>())
                .ok_or_else(|| {
                    datafusion_common::exec_datafusion_err!(
                        "Hash join table size overflow"
                    )
                })?;
        reservation.try_grow(estimated_hashtable_size)?;
        metrics.build_mem_used.add(estimated_hashtable_size);
        Ok(Box::new(JoinHashMapU64::with_capacity(num_rows)))
    } else {
        let estimated_hashtable_size =
            estimate_memory_size::<(u32, u64)>(num_rows, fixed_size_u32)?
                // Each build row also owns an index in the duplicate-key chain.
                .checked_add(num_rows * size_of::<u32>())
                .ok_or_else(|| {
                    datafusion_common::exec_datafusion_err!(
                        "Hash join table size overflow"
                    )
                })?;
        reservation.try_grow(estimated_hashtable_size)?;
        metrics.build_mem_used.add(estimated_hashtable_size);
        Ok(Box::new(JoinHashMapU32::with_capacity(num_rows)))
    }
}

/// Estimates the memory newly allocated for `array`'s share of a concatenated
/// array.
///
/// Concatenating view arrays copies only the views and keeps sharing the data
/// buffers of the inputs, which are already accounted for.
fn estimate_concat_allocation(array: &dyn Array) -> Result<usize> {
    match array.data_type() {
        DataType::Utf8View | DataType::BinaryView => {
            let nulls = array
                .nulls()
                .map(|_| bit_util::ceil(array.len(), 8))
                .unwrap_or_default();
            Ok(array.len() * size_of::<u128>() + nulls)
        }
        _ => Ok(array.to_data().get_slice_memory_size()?),
    }
}

/// Concatenates the build side `batches` into a single batch, keeping
/// `reservation` ahead of the actual memory usage.
///
/// `inputs_reserved` is the memory `reservation` already holds for `batches`.
/// The copy is reserved before it is made, and once `batches` are dropped the
/// reservation is trimmed to the memory retained by the returned batch.
/// On success, `batches` contains that batch; errors retain all input rows.
fn concat_build_batches(
    schema: &SchemaRef,
    batches: &mut Vec<RecordBatch>,
    inputs_reserved: usize,
    reservation: &mut MemoryReservation,
    metrics: &BuildProbeJoinMetrics,
) -> Result<RecordBatch> {
    // Concatenating a single batch is zero-copy
    let copy_size = if batches.len() > 1 {
        let mut copy_size = 0;
        for batch in batches.iter() {
            for array in batch.columns() {
                copy_size += estimate_concat_allocation(array.as_ref())?;
            }
        }
        copy_size
    } else {
        0
    };
    reservation.try_grow(copy_size)?;
    metrics.build_mem_used.add(copy_size);

    let batch = concat_batches(schema, batches.iter())?;
    batches.clear();
    batches.push(batch.clone());

    // The inputs are gone: only hold on to what the concatenated batch retains,
    // which includes any buffers it still shares with the inputs.
    let held = inputs_reserved + copy_size;
    let retained = get_record_batch_memory_size(&batch);
    if retained > held {
        reservation.try_grow(retained - held)?;
        metrics.build_mem_used.add(retained - held);
    } else {
        reservation.shrink(held - retained);
        metrics.build_mem_used.sub(held - retained);
    }

    Ok(batch)
}

/// Collects all batches from the left (build) side stream and creates a hash map for joining.
///
/// This function is responsible for:
/// 1. Consuming the entire left stream and collecting all batches into memory
/// 2. Building a hash map from the join key columns for efficient probe operations
/// 3. Computing bounds for dynamic filter pushdown (if enabled)
/// 4. Preparing visited indices bitmap for certain join types
///
/// # Parameters
/// * `random_state` - Random state for consistent hashing across partitions
/// * `left_stream` - Stream of record batches from the build side
/// * `on_left` - Physical expressions for the left side join keys
/// * `metrics` - Metrics collector for tracking memory usage and row counts
/// * `reservation` - Memory reservation tracker for the hash table and data
/// * `with_visited_indices_bitmap` - Whether to track visited indices (for outer joins)
/// * `probe_threads_count` - Number of threads that will probe this hash table
/// * `should_compute_dynamic_filters` - Whether to compute min/max bounds for dynamic filtering
/// * `null_aware` - The null-aware join mode, including whether per-build-row
///   bitmaps and correlation-scope maps are required
///
/// # Memory Accounting
/// Build batches are added to `reservation` as they arrive. They are then copied
/// into a single batch, see [`concat_build_batches`]: the copy is reserved
/// before it is made, and the reservation is trimmed to what the single batch
/// retains once the input batches are dropped. Join key arrays that do not
/// share the buffers of that batch are reserved as well.
///
/// # Dynamic Filter Coordination
/// When `should_compute_dynamic_filters` is true, this function computes the min/max bounds
/// for each join key column but does NOT update the dynamic filter. Instead, the
/// bounds are stored in the returned `JoinLeftData` and later coordinated by
/// `SharedBuildAccumulator` to ensure all partitions contribute their bounds
/// before updating the filter exactly once.
///
/// # Returns
/// `JoinLeftData` containing the hash map, consolidated batch, join key values,
/// visited indices bitmap, and computed bounds (if requested).
#[expect(clippy::too_many_arguments)]
async fn collect_left_input(
    random_state: RandomState,
    mut left_stream: SendableRecordBatchStream,
    on_left: Vec<PhysicalExprRef>,
    metrics: BuildProbeJoinMetrics,
    reservation: MemoryReservation,
    with_visited_indices_bitmap: bool,
    probe_threads_count: usize,
    should_compute_dynamic_filters: bool,
    config: Arc<ConfigOptions>,
    null_equality: NullEquality,
    not_in: Option<NotIn>,
    array_map_created_count: Count,
    mode: BuildMode,
) -> Result<JoinLeftData> {
    let schema = left_stream.schema();
    let prepared = mode == BuildMode::Prepared;

    let is_phj_candidate = is_perfect_hash_join_candidate(&on_left, &schema)?;

    let mut state = BuildSideState::try_new(
        metrics,
        reservation,
        on_left.clone(),
        &schema,
        should_compute_dynamic_filters || is_phj_candidate,
    )?;

    let mut max_batch_rows = 0;
    while let Some(batch) = left_stream.try_next().await? {
        max_batch_rows = max_batch_rows.max(batch.num_rows());
        if let Some(accumulators) = &mut state.bounds_accumulators {
            for accumulator in accumulators {
                accumulator.update_batch(&batch)?;
            }
        }
        let batch_size = state.memory_counter.count_batch(&batch);
        state.reservation.try_grow(batch_size)?;
        state.metrics.build_mem_used.add(batch_size);
        state.metrics.build_input_batches.add(1);
        state.metrics.build_input_rows.add(batch.num_rows());
        state.num_rows += batch.num_rows();
        state.batches.push(batch);
    }
    drop(left_stream);
    if prepared && state.batches.is_empty() {
        // Even empty UTF-8 output retains an offset buffer.
        let empty = RecordBatch::new_empty(Arc::clone(&schema));
        state
            .reservation
            .try_grow(state.memory_counter.count_batch(&empty))?;
        state.batches.push(empty);
    }
    let input_bytes = state.memory_counter.memory_usage();

    // Bind the reservation first so error paths release allocations before their charge.
    let BuildSideState {
        reservation,
        mut batches,
        num_rows,
        metrics,
        bounds_accumulators,
        memory_counter: _,
    } = state;

    // Admit concatenation copies while the original batches are retained.
    // Arrow keeps a single batch as an inexpensive slice.
    let copy_bytes = if prepared && batches.len() > 1 {
        let copy_bytes = prepared::prepared_copy_bytes(&batches)?;
        reservation.try_grow(copy_bytes)?;
        copy_bytes
    } else {
        0
    };

    // Compute bounds
    let bounds = match bounds_accumulators {
        Some(accumulators) if num_rows > 0 => {
            let bounds = accumulators
                .into_iter()
                .map(CollectLeftAccumulator::evaluate)
                .collect::<Result<Vec<_>>>()?;
            Some(PartitionBounds::new(bounds))
        }
        _ => None,
    };

    build_in_memory(
        &random_state,
        &schema,
        &mut batches,
        num_rows,
        max_batch_rows,
        input_bytes,
        copy_bytes,
        &on_left,
        &metrics,
        reservation,
        bounds,
        with_visited_indices_bitmap,
        probe_threads_count,
        should_compute_dynamic_filters,
        &config,
        null_equality,
        not_in,
        &array_map_created_count,
        prepared,
    )
}

/// Builds the hash table (or perfect-hash [`ArrayMap`]) and the bitmaps over
/// the collected build `batches`, the second half of [`collect_left_input`].
///
/// `reservation` already covers `batches`; the structures built here grow it
/// further. On error the reservation is dropped, releasing everything, while
/// `batches` keeps every build row (possibly concatenated into one batch) for
/// callers that need to recover from a failed build.
#[expect(clippy::too_many_arguments)]
fn build_in_memory(
    random_state: &RandomState,
    schema: &SchemaRef,
    batches: &mut Vec<RecordBatch>,
    num_rows: usize,
    max_batch_rows: usize,
    input_bytes: usize,
    copy_bytes: usize,
    on_left: &[PhysicalExprRef],
    metrics: &BuildProbeJoinMetrics,
    mut reservation: MemoryReservation,
    mut bounds: Option<PartitionBounds>,
    with_visited_indices_bitmap: bool,
    probe_threads_count: usize,
    should_compute_dynamic_filters: bool,
    config: &ConfigOptions,
    null_equality: NullEquality,
    not_in: Option<NotIn>,
    array_map_created_count: &Count,
    prepared: bool,
) -> Result<JoinLeftData> {
    let is_phj_candidate = is_perfect_hash_join_candidate(on_left, schema)?;

    let (join_hash_map, batch, left_values) = if let Some((min_val, max_val)) =
        array_map_key_range(
            bounds.as_ref(),
            schema,
            batches,
            on_left,
            &mut reservation,
            config.execution.perfect_hash_join_small_build_threshold,
            config.execution.perfect_hash_join_min_key_density,
            null_equality,
        )? {
        let batch = if prepared {
            concat_batches(schema, batches.iter())?
        } else {
            concat_build_batches(schema, batches, input_bytes, &mut reservation, metrics)?
        };
        let left_values = evaluate_expressions_to_arrays(on_left, &batch)?;
        let array_map = ArrayMap::try_new(&left_values[0], min_val, max_val)?;

        array_map_created_count.add(1);
        metrics.build_mem_used.add(array_map.size());

        (Map::ArrayMap(array_map), batch, left_values)
    } else {
        // Estimation of memory size, required for hashtable, prior to allocation.
        // Final result can be verified using `RawTable.allocation_info()`
        // Use `u32` indices for the JoinHashMap when num_rows ≤ u32::MAX, otherwise use the
        // `u64` indice variant
        // Arc is used instead of Box to allow sharing with SharedBuildAccumulator for hash map pushdown
        let mut hashmap = new_join_hashmap(num_rows, &mut reservation, metrics)?;

        let scratch_reservation = reservation.new_empty();
        if prepared {
            scratch_reservation.try_grow(prepared::prepared_scratch_bytes(
                max_batch_rows,
                on_left.len(),
                null_equality,
            )?)?;
        }
        // The maximum is known: avoid geometric growth and its excess capacity.
        let mut hashes_buffer = Vec::with_capacity(max_batch_rows);
        let mut offset = num_rows;

        // Update the hashmap starting from the last batch, so rows with smaller
        // indices end up on top of the chains. Each batch is indexed at its
        // position in the forward concatenation below.
        for batch in batches.iter().rev() {
            offset -= batch.num_rows();
            hashes_buffer.clear();
            hashes_buffer.resize(batch.num_rows(), 0);
            update_hash(
                on_left,
                batch,
                &mut *hashmap,
                offset,
                random_state,
                &mut hashes_buffer,
                0,
                true,
                null_equality,
            )?;
        }

        // Merge all batches into a single batch, so we can directly index into the arrays
        let batch = if prepared {
            concat_batches(schema, batches.iter())?
        } else {
            concat_build_batches(schema, batches, input_bytes, &mut reservation, metrics)?
        };

        let left_values = evaluate_expressions_to_arrays(on_left, &batch)?;

        (Map::HashMap(hashmap), batch, left_values)
    };

    // Rewrite float `-0.0` to `+0.0` once here, so the per probe batch key
    // comparison does not rescan the build side. Arrays without `-0.0`, and
    // non-float keys, are shared rather than copied.
    let normalized_values: Vec<ArrayRef> =
        left_values.iter().map(normalize_floats).collect();

    // Join keys that are plain columns share the buffers of `batch`, any other
    // expression evaluates to new arrays that are kept for the whole join.
    // The same goes for normalized keys: only a rewritten copy adds memory.
    let mut key_counter = RecordBatchMemoryCounter::new();
    key_counter.count_batch(&batch);
    let keys_size = left_values
        .iter()
        .chain(&normalized_values)
        .map(|values| key_counter.count_array(values.as_ref()))
        .sum::<usize>();
    reservation.try_grow(keys_size)?;
    metrics.build_mem_used.add(keys_size);

    let allocate_bitmap = || -> Result<BooleanBufferBuilder> {
        let bitmap_size = bit_util::ceil(batch.num_rows(), 8);
        reservation.try_grow(bitmap_size)?;
        metrics.build_mem_used.add(bitmap_size);

        let mut bitmap = BooleanBufferBuilder::new(batch.num_rows());
        bitmap.append_n(num_rows, false);
        Ok(bitmap)
    };

    // Reserve additional memory for visited indices bitmap and create shared builder
    let visited_indices_bitmap = if with_visited_indices_bitmap {
        allocate_bitmap()?
    } else {
        BooleanBufferBuilder::new(0)
    };

    let not_in = not_in
        .map(|not_in| {
            NotInBuild::try_new(
                not_in,
                on_left,
                &batch,
                &left_values,
                &normalized_values,
                random_state,
                &mut reservation,
                metrics,
            )
        })
        .transpose()?;

    let map = Arc::new(join_hash_map);

    // For an ordinary build, nothing reads the strategy unless this join's own
    // dynamic filter accumulator exists. A prepared build is shared with joins
    // decided later, so it must always be ready to serve one.
    let membership = if num_rows == 0 || (!prepared && !should_compute_dynamic_filters) {
        PushdownStrategy::Empty
    } else {
        // If the build side is small enough we can use IN list pushdown.
        // If it's too big we fall back to pushing down a reference to the hash table.
        // See `PushdownStrategy` for more details.
        let estimated_size = left_values
            .iter()
            .map(|arr| arr.get_array_memory_size())
            .sum::<usize>();

        let pushdown_inlist = !left_values.is_empty()
            && !left_values[0].is_empty()
            && estimated_size <= config.optimizer.hash_join_inlist_pushdown_max_size
            && map.num_of_distinct_key()
                <= config
                    .optimizer
                    .hash_join_inlist_pushdown_max_distinct_values;

        if pushdown_inlist
            && let Some(in_list_values) = build_struct_inlist_values(&left_values)?
        {
            PushdownStrategy::InList(in_list_values)
        } else {
            // Past the InList threshold use a bucket bitmap for container pruning.
            let pruning_bitmap = match (left_values.as_slice(), bounds.as_ref()) {
                ([keys], Some(bounds)) if !keys.is_empty() => bounds
                    .get_column_bounds(0)
                    .and_then(|b| {
                        KeyRangeBitmap::try_new(
                            keys,
                            &b.min,
                            &b.max,
                            map.num_of_distinct_key(),
                        )
                    })
                    .map(Arc::new),
                _ => None,
            };
            // Held for the join's lifetime, so charge it like the maps; it is
            // optional, so skip it rather than fail when the pool is full.
            let pruning_bitmap = pruning_bitmap.filter(|bitmap| {
                let ok = reservation.try_grow(bitmap.size()).is_ok();
                if ok {
                    metrics.build_mem_used.add(bitmap.size());
                }
                ok
            });
            PushdownStrategy::Map(Arc::clone(&map), pruning_bitmap)
        }
    };

    if is_phj_candidate && !should_compute_dynamic_filters {
        bounds = None;
    }

    if prepared {
        batches.clear();
        // Prepared keys are direct columns. IN-list arrays share these batch
        // buffers, including through multi-key StructArray children.
        let retained = RecordBatchMemoryCounter::new().count_batch(&batch);
        prepared::reconcile_prepared_copy_reservation(
            &reservation,
            input_bytes,
            copy_bytes,
            retained,
        )?;
    }

    let data = JoinLeftData {
        build: Arc::new(JoinBuildData {
            map,
            batch,
            values: normalized_values,
            bounds,
            membership,
            reservation,
        }),
        not_in,
        visited_indices_bitmap: Mutex::new(visited_indices_bitmap),
        probe_completion: ProbeCompletion::new(probe_threads_count),
    };

    Ok(data)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::joins::hash_join::not_in::{NotInOutput, NotInScope};

    fn assert_phj_used(metrics: &MetricsSet, use_phj: bool) {
        if use_phj {
            assert!(
                metrics
                    .sum_by_name(ARRAY_MAP_CREATED_COUNT_METRIC_NAME)
                    .expect("should have array_map_created_count metrics")
                    .as_usize()
                    >= 1
            );
        } else {
            assert_eq!(
                metrics
                    .sum_by_name(ARRAY_MAP_CREATED_COUNT_METRIC_NAME)
                    .map(|v| v.as_usize())
                    .unwrap_or(0),
                0
            )
        }
    }

    #[track_caller]
    fn assert_ratio_metric(
        metrics: &MetricsSet,
        metric_name: &str,
        expected_part: usize,
        expected_total: usize,
    ) {
        let Some(MetricValue::Ratio { ratio_metrics, .. }) =
            metrics.sum_by_name(metric_name)
        else {
            panic!("should have {metric_name} metrics")
        };
        assert_eq!(
            (ratio_metrics.part(), ratio_metrics.total()),
            (expected_part, expected_total),
            "{metric_name} (part, total) mismatch",
        );
    }

    fn build_schema_and_on() -> Result<(SchemaRef, SchemaRef, JoinOn)> {
        let left_schema = Arc::new(Schema::new(vec![
            Field::new("a1", DataType::Int32, true),
            Field::new("b1", DataType::Int32, true),
        ]));
        let right_schema = Arc::new(Schema::new(vec![
            Field::new("a2", DataType::Int32, true),
            Field::new("b1", DataType::Int32, true),
        ]));
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left_schema)?) as _,
            Arc::new(Column::new_with_schema("b1", &right_schema)?) as _,
        )];
        Ok((left_schema, right_schema, on))
    }

    use crate::coalesce_partitions::CoalescePartitionsExec;
    use crate::execution_plan::Boundedness;
    use crate::filter::FilterExecBuilder;
    use crate::joins::hash_join::stream::lookup_join_hashmap;
    use crate::statistics::StatisticsContext;
    use crate::test::{TestMemoryExec, assert_join_metrics};
    use crate::{ChildrenPropertiesMode, ReplaceChildrenOptions};
    use crate::{
        common, expressions::Column, repartition::RepartitionExec, test::build_table_i32,
        test::exec::MockExec,
    };

    use crate::joins::join_hash_map::ProbeOffset::AtRow;
    use arrow::array::{
        Array, ArrayRef, AsArray, BinaryViewArray, Date32Array, DictionaryArray,
        Float32Array, Float64Array, Int32Array, Int64Array, StringArray, StringViewArray,
        StructArray, UInt32Array, UInt64Array,
    };
    use arrow::buffer::NullBuffer;
    use arrow::datatypes::{DataType, Field, Float32Type, Float64Type, Int32Type};
    use datafusion_common::hash_utils::create_hashes;
    use datafusion_common::stats::Precision;
    use datafusion_common::test_util::{batches_to_sort_string, batches_to_string};
    use datafusion_common::{
        ScalarValue, assert_batches_eq, assert_batches_sorted_eq, assert_contains,
        exec_err, internal_err,
    };
    use datafusion_execution::config::SessionConfig;
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryPool, UnboundedMemoryPool,
    };
    use datafusion_execution::runtime_env::RuntimeEnvBuilder;
    use datafusion_expr::Operator;
    use datafusion_physical_expr::expressions::{BinaryExpr, Literal};
    use datafusion_physical_expr::{
        EquivalenceProperties, PhysicalSortExpr, RangePartitioning, SplitPoint,
    };
    use datafusion_physical_expr_common::metrics::MetricValue;
    use futures::StreamExt;
    use hashbrown::HashTable;
    use insta::{allow_duplicates, assert_snapshot};
    use rstest::*;
    use rstest_reuse::*;

    #[test]
    fn hash_map_admits_row_indices_before_allocation() -> Result<()> {
        use datafusion_execution::memory_pool::{GreedyMemoryPool, MemoryPool};

        let rows = 1024;
        let buckets =
            estimate_memory_size::<(u32, u64)>(rows, size_of::<JoinHashMapU32>())?;
        let bytes = buckets + rows * size_of::<u32>();
        for (limit, succeeds) in [(bytes - 1, false), (bytes, true)] {
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
            let mut reservation = MemoryConsumer::new("row indices").register(&pool);
            let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
            let result = new_join_hashmap(rows, &mut reservation, &metrics);
            if succeeds {
                let map = result?;
                assert_eq!(reservation.size(), bytes);
                assert_eq!(metrics.build_mem_used.value(), bytes);
                drop(map);
            } else {
                assert!(matches!(
                    result,
                    Err(datafusion_common::DataFusionError::ResourcesExhausted(_))
                ));
                assert_eq!(reservation.size(), 0);
                assert_eq!(metrics.build_mem_used.value(), 0);
            }
            drop(reservation);
            assert_eq!(pool.reserved(), 0);
        }
        Ok(())
    }

    /// Runs a join whose 200 keys spread over 2M would size a pruning bitmap
    /// at the 128 KiB cap, and reports the bytes the build side reserved.
    ///
    /// Forces the IN-list threshold off: under `force_hash_collisions` every
    /// key hashes to the same bucket, so `num_of_distinct_key()` no longer
    /// reflects the real 200 distinct keys and would otherwise take the
    /// IN-list branch instead of the one under test.
    async fn build_mem_used(limit: usize, dynamic_filters: bool) -> Result<usize> {
        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int64, false)]));
        let batch = |keys: Vec<i64>| {
            let column = Arc::new(Int64Array::from(keys)) as ArrayRef;
            let batch = RecordBatch::try_new(Arc::clone(&schema), vec![column])?;
            TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)
        };
        let on = vec![(
            Arc::new(Column::new_with_schema("k", &schema)?) as _,
            Arc::new(Column::new_with_schema("k", &schema)?) as _,
        )];
        let build = batch((0..200).map(|i| i * 10_000).collect())?;
        let probe = batch(vec![0, 500_000, 1_500_000])?;
        let join = if dynamic_filters {
            hash_join_with_dynamic_filter(build, probe, on, JoinType::Inner)?.0
        } else {
            join(
                build,
                probe,
                on,
                &JoinType::Inner,
                NullEquality::NullEqualsNothing,
            )?
        };

        let runtime = RuntimeEnvBuilder::new()
            .with_memory_limit(limit, 1.0)
            .build_arc()?;
        let mut config = SessionConfig::new();
        config
            .options_mut()
            .optimizer
            .hash_join_inlist_pushdown_max_size = 0;
        let task_ctx = Arc::new(
            TaskContext::default()
                .with_runtime(runtime)
                .with_session_config(config),
        );
        let batches = common::collect(join.execute(0, task_ctx)?).await?;
        assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 3);
        Ok(join
            .metrics()
            .unwrap()
            .sum_by_name("build_mem_used")
            .unwrap()
            .as_usize())
    }

    /// The bitmap is pruning-only: never built when no dynamic filter will read
    /// it, and dropped rather than fatal when the pool cannot fit it.
    #[tokio::test]
    async fn pruning_bitmap_is_optional() -> Result<()> {
        assert!(build_mem_used(1_000_000, false).await? < 100_000);
        assert!(build_mem_used(1_000_000, true).await? > 100_000);
        build_mem_used(100_000, true).await?;
        Ok(())
    }

    #[derive(Debug)]
    struct PartitionedTestExec {
        cache: Arc<PlanProperties>,
    }

    impl PartitionedTestExec {
        fn try_new(schema: SchemaRef, partitioning: Partitioning) -> Result<Self> {
            Ok(Self {
                cache: Arc::new(PlanProperties::new(
                    EquivalenceProperties::new(Arc::clone(&schema)),
                    partitioning,
                    EmissionType::Incremental,
                    Boundedness::Bounded,
                )),
            })
        }
    }

    impl DisplayAs for PartitionedTestExec {
        fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "PartitionedTestExec")
        }
    }

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

        fn properties(&self) -> &Arc<PlanProperties> {
            &self.cache
        }

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

        fn apply_expressions(
            &self,
            _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
        ) -> Result<TreeNodeRecursion> {
            Ok(TreeNodeRecursion::Continue)
        }

        fn replace_children(
            self: Arc<Self>,
            _: Vec<Arc<dyn ExecutionPlan>>,
            _: ReplaceChildrenOptions,
        ) -> Result<Arc<dyn ExecutionPlan>> {
            Ok(self)
        }

        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 execute(
            &self,
            _partition: usize,
            _context: Arc<TaskContext>,
        ) -> Result<SendableRecordBatchStream> {
            unreachable!()
        }
    }

    fn div_ceil(a: usize, b: usize) -> usize {
        a.div_ceil(b)
    }

    #[template]
    #[rstest]
    fn hash_join_exec_configs(
        #[values(8192, 10, 5, 2, 1)] batch_size: usize,
        #[values(true, false)] use_perfect_hash_join_as_possible: bool,
    ) {
    }

    fn prepare_task_ctx(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Arc<TaskContext> {
        let mut session_config = SessionConfig::default().with_batch_size(batch_size);

        // Either always take the perfect hash join path, or never take it.
        let (small_build_threshold, min_key_density) =
            if use_perfect_hash_join_as_possible {
                (819200, 0.0)
            } else {
                (0, f64::INFINITY)
            };
        let execution = &mut session_config.options_mut().execution;
        execution.perfect_hash_join_small_build_threshold = small_build_threshold;
        execution.perfect_hash_join_min_key_density = min_key_density;
        Arc::new(TaskContext::default().with_session_config(session_config))
    }

    fn build_table(
        a: (&str, &Vec<i32>),
        b: (&str, &Vec<i32>),
        c: (&str, &Vec<i32>),
    ) -> Arc<dyn ExecutionPlan> {
        let batch = build_table_i32(a, b, c);
        let schema = batch.schema();
        TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
    }

    /// Build a table with two columns supporting nullable values
    fn build_table_two_cols(
        a: (&str, &Vec<Option<i32>>),
        b: (&str, &Vec<Option<i32>>),
    ) -> Arc<dyn ExecutionPlan> {
        let schema = Arc::new(Schema::new(vec![
            Field::new(a.0, DataType::Int32, true),
            Field::new(b.0, DataType::Int32, true),
        ]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(a.1.clone())),
                Arc::new(Int32Array::from(b.1.clone())),
            ],
        )
        .unwrap();
        TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
    }

    /// Build a two-column table whose join key is a dictionary.
    ///
    /// `dict_values` are the dictionary entries; `keys` are all physically
    /// valid indices into that dictionary. When `dict_values` contains NULL,
    /// the resulting array can have `null_count() == 0` but
    /// `logical_null_count() > 0`.
    fn build_table_dict_key(
        key_name: &str,
        dict_values: Vec<Option<i32>>,
        keys: Vec<i32>,
        dummy_name: &str,
        dummy: Vec<Option<i32>>,
    ) -> Arc<dyn ExecutionPlan> {
        let dict_type =
            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Int32));
        let schema = Arc::new(Schema::new(vec![
            Field::new(key_name, dict_type, true),
            Field::new(dummy_name, DataType::Int32, true),
        ]));
        let values = Int32Array::from(dict_values);
        let key_array = Int32Array::from(keys);
        let dict: ArrayRef = Arc::new(DictionaryArray::new(key_array, Arc::new(values)));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![dict, Arc::new(Int32Array::from(dummy))],
        )
        .unwrap();
        TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
    }

    fn join(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        join_type: &JoinType,
        null_equality: NullEquality,
    ) -> Result<HashJoinExec> {
        HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            join_type,
            None,
            PartitionMode::CollectLeft,
            null_equality,
            false,
        )
    }

    fn join_with_filter(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        filter: JoinFilter,
        join_type: &JoinType,
        null_equality: NullEquality,
    ) -> Result<HashJoinExec> {
        HashJoinExec::try_new(
            left,
            right,
            on,
            Some(filter),
            join_type,
            None,
            PartitionMode::CollectLeft,
            null_equality,
            false,
        )
    }

    fn empty_build_with_probe_error_inputs()
    -> (Arc<dyn ExecutionPlan>, Arc<dyn ExecutionPlan>, JoinOn) {
        let left_batch =
            build_table_i32(("a1", &vec![]), ("b1", &vec![]), ("c1", &vec![]));
        let left_schema = left_batch.schema();
        let left: Arc<dyn ExecutionPlan> = TestMemoryExec::try_new_exec(
            &[vec![left_batch]],
            Arc::clone(&left_schema),
            None,
        )
        .unwrap();

        let err = exec_err!("bad data error");
        let right_batch =
            build_table_i32(("a2", &vec![]), ("b1", &vec![]), ("c2", &vec![]));
        let right_schema = right_batch.schema();
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left_schema).unwrap()) as _,
            Arc::new(Column::new_with_schema("b1", &right_schema).unwrap()) as _,
        )];
        let right: Arc<dyn ExecutionPlan> = Arc::new(
            MockExec::new(vec![Ok(right_batch), err], right_schema)
                .with_use_task(false)
                // The planted error must only surface if the probe side is
                // polled, not when a parent node computes statistics during
                // planning.
                .with_unknown_statistics(),
        );

        (left, right, on)
    }

    async fn assert_empty_build_probe_behavior(
        join_types: &[JoinType],
        expect_probe_error: bool,
        with_filter: bool,
    ) {
        let (left, right, on) = empty_build_with_probe_error_inputs();
        let filter = prepare_join_filter();

        for join_type in join_types {
            let join = if with_filter {
                join_with_filter(
                    Arc::clone(&left),
                    Arc::clone(&right),
                    on.clone(),
                    filter.clone(),
                    join_type,
                    NullEquality::NullEqualsNothing,
                )
                .unwrap()
            } else {
                join(
                    Arc::clone(&left),
                    Arc::clone(&right),
                    on.clone(),
                    join_type,
                    NullEquality::NullEqualsNothing,
                )
                .unwrap()
            };

            let result = common::collect(
                join.execute(0, Arc::new(TaskContext::default())).unwrap(),
            )
            .await;

            if expect_probe_error {
                let result_string = result.unwrap_err().to_string();
                assert!(
                    result_string.contains("bad data error"),
                    "actual: {result_string}"
                );
            } else {
                let batches = result.unwrap();
                assert!(
                    batches.is_empty(),
                    "expected no output batches for {join_type}, got {batches:?}"
                );
            }
        }
    }

    fn hash_join_with_dynamic_filter(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        join_type: JoinType,
    ) -> Result<(HashJoinExec, Arc<DynamicFilterPhysicalExpr>)> {
        hash_join_with_dynamic_filter_and_mode(
            left,
            right,
            on,
            join_type,
            PartitionMode::CollectLeft,
        )
    }

    fn hash_join_with_dynamic_filter_and_mode(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        join_type: JoinType,
        mode: PartitionMode,
    ) -> Result<(HashJoinExec, Arc<DynamicFilterPhysicalExpr>)> {
        let dynamic_filter = HashJoinExec::create_dynamic_filter(&on);
        let consumer: Arc<dyn PhysicalExpr> = Arc::clone(&dynamic_filter) as _;
        let right = Arc::new(FilterExecBuilder::new(consumer, right).build()?);
        let mut join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &join_type,
            None,
            mode,
            NullEquality::NullEqualsNothing,
            false,
        )?;
        join.dynamic_filter = Some(HashJoinExecDynamicFilter {
            filter: Arc::clone(&dynamic_filter),
            build_accumulator: OnceLock::new(),
        });

        Ok((join, dynamic_filter))
    }

    async fn join_collect(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        join_type: &JoinType,
        null_equality: NullEquality,
        context: Arc<TaskContext>,
    ) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
        let join = join(left, right, on, join_type, null_equality)?;
        let columns_header = columns(&join.schema());

        let stream = join.execute(0, context)?;
        let batches = common::collect(stream).await?;
        let metrics = join.metrics().unwrap();

        Ok((columns_header, batches, metrics))
    }

    async fn partitioned_join_collect(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        join_type: &JoinType,
        null_equality: NullEquality,
        context: Arc<TaskContext>,
    ) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
        join_collect_with_partition_mode(
            left,
            right,
            on,
            join_type,
            PartitionMode::Partitioned,
            null_equality,
            context,
        )
        .await
    }

    async fn join_collect_with_partition_mode(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        join_type: &JoinType,
        partition_mode: PartitionMode,
        null_equality: NullEquality,
        context: Arc<TaskContext>,
    ) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
        let partition_count = 4;

        let (left_expr, right_expr) = on
            .iter()
            .map(|(l, r)| (Arc::clone(l), Arc::clone(r)))
            .unzip();

        let left_repartitioned: Arc<dyn ExecutionPlan> = match partition_mode {
            PartitionMode::CollectLeft => Arc::new(CoalescePartitionsExec::new(left)),
            PartitionMode::Partitioned => Arc::new(RepartitionExec::try_new(
                left,
                Partitioning::Hash(left_expr, partition_count),
            )?),
            PartitionMode::Auto => {
                return internal_err!("Unexpected PartitionMode::Auto in join tests");
            }
        };

        let right_repartitioned: Arc<dyn ExecutionPlan> = match partition_mode {
            PartitionMode::CollectLeft => {
                let partition_column_name = right.schema().field(0).name().clone();
                let partition_expr = vec![Arc::new(Column::new_with_schema(
                    &partition_column_name,
                    &right.schema(),
                )?) as _];
                Arc::new(RepartitionExec::try_new(
                    right,
                    Partitioning::Hash(partition_expr, partition_count),
                )?) as _
            }
            PartitionMode::Partitioned => Arc::new(RepartitionExec::try_new(
                right,
                Partitioning::Hash(right_expr, partition_count),
            )?),
            PartitionMode::Auto => {
                return internal_err!("Unexpected PartitionMode::Auto in join tests");
            }
        };

        let join = HashJoinExec::try_new(
            left_repartitioned,
            right_repartitioned,
            on,
            None,
            join_type,
            None,
            partition_mode,
            null_equality,
            false,
        )?;

        let columns = columns(&join.schema());

        let mut batches = vec![];
        for i in 0..partition_count {
            let stream = join.execute(i, Arc::clone(&context))?;
            let more_batches = common::collect(stream).await?;
            batches.extend(
                more_batches
                    .into_iter()
                    .filter(|b| b.num_rows() > 0)
                    .collect::<Vec<_>>(),
            );
        }
        let metrics = join.metrics().unwrap();

        Ok((columns, batches, metrics))
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_inner_one(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 5]), // this has a repetition
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        allow_duplicates! {
            // Inner join output is expected to preserve both inputs order
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 3  | 5  | 9  | 20 | 5  | 80 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn partitioned_join_inner_one(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 5]), // this has a repetition
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = partitioned_join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 3  | 5  | 9  | 20 | 5  | 80 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    /// Two-column keys (Int32, Float64) take the general comparator path.
    /// Small batch sizes split each probe batch into several lookup chunks,
    /// so the key comparison must stay correct across chunk boundaries:
    /// `-0.0` still equals `0.0`. NULL keys are also present on both sides;
    /// under `NullEqualsNothing` those rows are skipped by the lookup before
    /// any key comparison, so they must not appear in the output.
    #[rstest]
    #[tokio::test]
    async fn join_inner_multi_key_float_zero_and_nulls_across_chunks(
        #[values(8192, 3, 2, 1)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        let schema = |suffix: &str| {
            Arc::new(Schema::new(vec![
                Field::new(format!("k{suffix}"), DataType::Int32, true),
                Field::new(format!("f{suffix}"), DataType::Float64, true),
                Field::new(format!("v{suffix}"), DataType::Int32, true),
            ]))
        };
        let table = |suffix: &str,
                     k: Vec<Option<i32>>,
                     f: Vec<Option<f64>>,
                     v: Vec<i32>|
         -> Result<Arc<dyn ExecutionPlan>> {
            let schema = schema(suffix);
            let batch = RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(k)),
                    Arc::new(Float64Array::from(f)),
                    Arc::new(Int32Array::from(v)),
                ],
            )?;
            TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)
                .map(|exec| exec as _)
        };

        let left = table(
            "1",
            vec![Some(1), Some(1), Some(1), Some(2), Some(1)],
            vec![Some(-0.0), Some(0.0), None, Some(1.5), Some(-0.0)],
            vec![10, 11, 12, 13, 14],
        )?;
        let right = table(
            "2",
            vec![Some(1), Some(1), Some(2), Some(1)],
            vec![Some(0.0), None, Some(1.5), Some(-0.0)],
            vec![100, 101, 102, 103],
        )?;

        let on = vec![
            (
                Arc::new(Column::new_with_schema("k1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("k2", &right.schema())?) as _,
            ),
            (
                Arc::new(Column::new_with_schema("f1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("f2", &right.schema())?) as _,
            ),
        ];

        let (_, batches, _) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+------+----+----+------+-----+
            | k1 | f1   | v1 | k2 | f2   | v2  |
            +----+------+----+----+------+-----+
            | 1  | -0.0 | 10 | 1  | -0.0 | 103 |
            | 1  | -0.0 | 10 | 1  | 0.0  | 100 |
            | 1  | -0.0 | 14 | 1  | -0.0 | 103 |
            | 1  | -0.0 | 14 | 1  | 0.0  | 100 |
            | 1  | 0.0  | 11 | 1  | -0.0 | 103 |
            | 1  | 0.0  | 11 | 1  | 0.0  | 100 |
            | 2  | 1.5  | 13 | 2  | 1.5  | 102 |
            +----+------+----+----+------+-----+
            ");
        }

        Ok(())
    }

    /// Collects a single-column build side keyed on that column.
    async fn collect_float_build(
        keys: ArrayRef,
    ) -> Result<(JoinLeftData, BuildProbeJoinMetrics)> {
        let schema = Arc::new(Schema::new(vec![Field::new(
            "f",
            keys.data_type().clone(),
            true,
        )]));
        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![keys])?;
        let exec = TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)?;
        let stream = exec.execute(0, Arc::new(TaskContext::default()))?;
        let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
        let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
        let on_left: Vec<PhysicalExprRef> = vec![Arc::new(Column::new("f", 0))];
        let left_data = collect_left_input(
            RandomState::with_seed(0),
            stream,
            on_left,
            metrics.clone(),
            MemoryConsumer::new("HashJoinInput").register(&pool),
            false,
            1,
            false,
            Arc::new(ConfigOptions::default()),
            NullEquality::NullEqualsNothing,
            None,
            Count::new(),
            BuildMode::Ordinary,
        )
        .await?;
        Ok((left_data, metrics))
    }

    /// The stored build keys have `-0.0` rewritten to `+0.0`, while the build
    /// batch keeps the original value. The rewritten copy is charged to the
    /// build memory, and keys without `-0.0` are shared with the batch.
    #[tokio::test]
    async fn collect_left_input_stores_normalized_float_keys() -> Result<()> {
        let (with_neg_zero, neg_metrics) =
            collect_float_build(Arc::new(Float64Array::from(vec![-0.0, 1.0]))).await?;
        let stored = with_neg_zero.values()[0].as_primitive::<Float64Type>();
        assert_eq!(stored.value(0).to_bits(), 0.0_f64.to_bits());
        assert_eq!(stored.value(1), 1.0);
        let original = with_neg_zero
            .batch()
            .column(0)
            .as_primitive::<Float64Type>();
        assert_eq!(original.value(0).to_bits(), (-0.0_f64).to_bits());

        let (without_neg_zero, pos_metrics) =
            collect_float_build(Arc::new(Float64Array::from(vec![0.0, 1.0]))).await?;
        assert!(Arc::ptr_eq(
            &without_neg_zero.values()[0],
            without_neg_zero.batch().column(0)
        ));

        // Both builds are the same shape, so they differ only by the copy.
        assert_eq!(
            neg_metrics.build_mem_used.value(),
            pos_metrics.build_mem_used.value() + stored.values().inner().capacity()
        );

        let (f32_build, _) =
            collect_float_build(Arc::new(Float32Array::from(vec![-0.0_f32, 1.0])))
                .await?;
        let stored = f32_build.values()[0].as_primitive::<Float32Type>();
        assert_eq!(stored.value(0).to_bits(), 0.0_f32.to_bits());
        let original = f32_build.batch().column(0).as_primitive::<Float32Type>();
        assert_eq!(original.value(0).to_bits(), (-0.0_f32).to_bits());
        Ok(())
    }

    /// A single Float64 key takes the general comparator path. Build and
    /// probe both hold `-0.0` and `0.0`, which must all match each other,
    /// while the output keeps each side's original sign.
    #[rstest]
    #[tokio::test]
    async fn join_inner_single_float_key_negative_zero(
        #[values(8192, 1)] batch_size: usize,
        #[values(NullEquality::NullEqualsNothing, NullEquality::NullEqualsNull)]
        null_equality: NullEquality,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        let table = |suffix: &str,
                     f: Vec<Option<f64>>,
                     v: Vec<i32>|
         -> Result<Arc<dyn ExecutionPlan>> {
            let schema = Arc::new(Schema::new(vec![
                Field::new(format!("f{suffix}"), DataType::Float64, true),
                Field::new(format!("v{suffix}"), DataType::Int32, true),
            ]));
            let batch = RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Float64Array::from(f)),
                    Arc::new(Int32Array::from(v)),
                ],
            )?;
            TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)
                .map(|exec| exec as _)
        };

        let left = table(
            "1",
            vec![Some(-0.0), Some(0.0), Some(1.5), None],
            vec![10, 11, 12, 13],
        )?;
        let right = table(
            "2",
            vec![Some(0.0), Some(-0.0), Some(1.5), None],
            vec![20, 21, 22, 23],
        )?;
        let on = vec![(
            Arc::new(Column::new_with_schema("f1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("f2", &right.schema())?) as _,
        )];

        let (_, batches, _) =
            join_collect(left, right, on, &JoinType::Inner, null_equality, task_ctx)
                .await?;

        // The NULL keys only pair up when NULL equals NULL.
        allow_duplicates! {
            match null_equality {
                NullEquality::NullEqualsNothing => {
                    assert_snapshot!(batches_to_sort_string(&batches), @r"
                    +------+----+------+----+
                    | f1   | v1 | f2   | v2 |
                    +------+----+------+----+
                    | -0.0 | 10 | -0.0 | 21 |
                    | -0.0 | 10 | 0.0  | 20 |
                    | 0.0  | 11 | -0.0 | 21 |
                    | 0.0  | 11 | 0.0  | 20 |
                    | 1.5  | 12 | 1.5  | 22 |
                    +------+----+------+----+
                    ");
                }
                NullEquality::NullEqualsNull => {
                    assert_snapshot!(batches_to_sort_string(&batches), @r"
                    +------+----+------+----+
                    | f1   | v1 | f2   | v2 |
                    +------+----+------+----+
                    |      | 13 |      | 23 |
                    | -0.0 | 10 | -0.0 | 21 |
                    | -0.0 | 10 | 0.0  | 20 |
                    | 0.0  | 11 | -0.0 | 21 |
                    | 0.0  | 11 | 0.0  | 20 |
                    | 1.5  | 12 | 1.5  | 22 |
                    +------+----+------+----+
                    ");
                }
            }
        }

        Ok(())
    }

    /// Two probe batches carry different multi-column keys at the same row
    /// positions. Each batch has to be compared against its own key arrays;
    /// a comparator left over from the first batch would drop the second
    /// batch's match.
    #[rstest]
    #[tokio::test]
    async fn join_inner_multi_key_across_probe_batches(
        #[values(8192, 1)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);
        let left = build_table_two_cols(
            ("a1", &vec![Some(1), Some(1)]),
            ("b1", &vec![Some(10), Some(20)]),
        );

        let right_schema = Arc::new(Schema::new(vec![
            Field::new("a2", DataType::Int32, true),
            Field::new("b2", DataType::Int32, true),
        ]));
        let probe_batch = |b: i32| {
            RecordBatch::try_new(
                Arc::clone(&right_schema),
                vec![
                    Arc::new(Int32Array::from(vec![1])),
                    Arc::new(Int32Array::from(vec![b])),
                ],
            )
        };
        let right = TestMemoryExec::try_new_exec(
            &[vec![probe_batch(10)?, probe_batch(20)?]],
            Arc::clone(&right_schema),
            None,
        )?;

        let on = vec![
            (
                Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
            ),
            (
                Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
            ),
        ];

        let (_, batches, _) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+
            | a1 | b1 | a2 | b2 |
            +----+----+----+----+
            | 1  | 10 | 1  | 10 |
            | 1  | 20 | 1  | 20 |
            +----+----+----+----+
            ");
        }

        Ok(())
    }

    /// An integer key joined through the perfect hash (array map) path, with
    /// more candidate pairs than the batch size so each probe batch is
    /// emitted over several chunks.
    #[rstest]
    #[tokio::test]
    async fn join_inner_array_map_across_chunks(
        #[values(8192, 3, 2, 1)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, true);
        let left = build_table(
            ("a1", &vec![1, 2, 3, 4, 5, 6]),
            ("b1", &vec![1, 1, 1, 2, 2, 3]),
            ("c1", &vec![7, 8, 9, 10, 11, 12]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30, 40]),
            ("b1", &vec![1, 2, 3, 4]),
            ("c2", &vec![70, 80, 90, 100]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (_, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 1  | 7  | 10 | 1  | 70 |
            | 2  | 1  | 8  | 10 | 1  | 70 |
            | 3  | 1  | 9  | 10 | 1  | 70 |
            | 4  | 2  | 10 | 20 | 2  | 80 |
            | 5  | 2  | 11 | 20 | 2  | 80 |
            | 6  | 3  | 12 | 30 | 3  | 90 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 6);
        assert_phj_used(&metrics, true);

        Ok(())
    }

    #[tokio::test]
    async fn join_inner_one_no_shared_column_names() -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 5]), // this has a repetition
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b2", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);

        // Inner join output is expected to preserve both inputs order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b2 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 3  | 5  | 9  | 20 | 5  | 80 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);

        Ok(())
    }

    #[tokio::test]
    async fn join_inner_one_randomly_ordered() -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        let left = build_table(
            ("a1", &vec![0, 3, 2, 1]),
            ("b1", &vec![4, 5, 5, 4]),
            ("c1", &vec![6, 9, 8, 7]),
        );
        let right = build_table(
            ("a2", &vec![20, 30, 10]),
            ("b2", &vec![5, 6, 4]),
            ("c2", &vec![80, 90, 70]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);

        // Inner join output is expected to preserve both inputs order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b2 | c2 |
            +----+----+----+----+----+----+
            | 3  | 5  | 9  | 20 | 5  | 80 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 0  | 4  | 6  | 10 | 4  | 70 |
            | 1  | 4  | 7  | 10 | 4  | 70 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 4);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_inner_two(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 2]),
            ("b2", &vec![1, 2, 2]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b2", &vec![1, 2, 2]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![
            (
                Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("a1", &right.schema())?) as _,
            ),
            (
                Arc::new(Column::new_with_schema("b2", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
            ),
        ];

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b2", "c1", "a1", "b2", "c2"]);

        let expected_batch_count = if cfg!(not(feature = "force_hash_collisions")) {
            // Expected number of hash table matches = 3
            // in case batch_size is 1 - additional empty batch for remaining 3-2 row
            let mut expected_batch_count = div_ceil(3, batch_size);
            if batch_size == 1 {
                expected_batch_count += 1;
            }
            expected_batch_count
        } else {
            // With hash collisions enabled, all records will match each other
            // and filtered later.
            div_ceil(9, batch_size)
        };

        // With batch coalescing, we may have fewer batches than expected
        assert!(
            batches.len() <= expected_batch_count,
            "expected at most {expected_batch_count} batches, got {}",
            batches.len()
        );

        // Inner join output is expected to preserve both inputs order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b2 | c1 | a1 | b2 | c2 |
            +----+----+----+----+----+----+
            | 1  | 1  | 7  | 1  | 1  | 70 |
            | 2  | 2  | 8  | 2  | 2  | 80 |
            | 2  | 2  | 9  | 2  | 2  | 80 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);

        Ok(())
    }

    /// Test where the left has 2 parts, the right with 1 part => 1 part
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_inner_one_two_parts_left(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let batch1 = build_table_i32(
            ("a1", &vec![1, 2]),
            ("b2", &vec![1, 2]),
            ("c1", &vec![7, 8]),
        );
        let batch2 =
            build_table_i32(("a1", &vec![2]), ("b2", &vec![2]), ("c1", &vec![9]));
        let schema = batch1.schema();
        let left =
            TestMemoryExec::try_new_exec(&[vec![batch1], vec![batch2]], schema, None)
                .unwrap();
        let left = Arc::new(CoalescePartitionsExec::new(left));

        let right = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b2", &vec![1, 2, 2]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![
            (
                Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("a1", &right.schema())?) as _,
            ),
            (
                Arc::new(Column::new_with_schema("b2", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
            ),
        ];

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b2", "c1", "a1", "b2", "c2"]);

        let expected_batch_count = if cfg!(not(feature = "force_hash_collisions")) {
            // Expected number of hash table matches = 3
            // in case batch_size is 1 - additional empty batch for remaining 3-2 row
            let mut expected_batch_count = div_ceil(3, batch_size);
            if batch_size == 1 {
                expected_batch_count += 1;
            }
            expected_batch_count
        } else {
            // With hash collisions enabled, all records will match each other
            // and filtered later.
            div_ceil(9, batch_size)
        };

        // With batch coalescing, we may have fewer batches than expected
        assert!(
            batches.len() <= expected_batch_count,
            "expected at most {expected_batch_count} batches, got {}",
            batches.len()
        );

        // Inner join output is expected to preserve both inputs order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b2 | c1 | a1 | b2 | c2 |
            +----+----+----+----+----+----+
            | 1  | 1  | 7  | 1  | 1  | 70 |
            | 2  | 2  | 8  | 2  | 2  | 80 |
            | 2  | 2  | 9  | 2  | 2  | 80 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_inner_one_two_parts_left_randomly_ordered(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let batch1 = build_table_i32(
            ("a1", &vec![0, 3]),
            ("b1", &vec![4, 5]),
            ("c1", &vec![6, 9]),
        );
        let batch2 = build_table_i32(
            ("a1", &vec![2, 1]),
            ("b1", &vec![5, 4]),
            ("c1", &vec![8, 7]),
        );
        let schema = batch1.schema();

        let left =
            TestMemoryExec::try_new_exec(&[vec![batch1], vec![batch2]], schema, None)
                .unwrap();
        let left = Arc::new(CoalescePartitionsExec::new(left));
        let right = build_table(
            ("a2", &vec![20, 30, 10]),
            ("b2", &vec![5, 6, 4]),
            ("c2", &vec![80, 90, 70]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);

        // Inner join output is expected to preserve both inputs order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b2 | c2 |
            +----+----+----+----+----+----+
            | 3  | 5  | 9  | 20 | 5  | 80 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 0  | 4  | 6  | 10 | 4  | 70 |
            | 1  | 4  | 7  | 10 | 4  | 70 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 4);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    /// Test where the left has 1 part, the right has 2 parts => 2 parts
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_inner_one_two_parts_right(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 5]), // this has a repetition
            ("c1", &vec![7, 8, 9]),
        );

        let batch1 = build_table_i32(
            ("a2", &vec![10, 20]),
            ("b1", &vec![4, 6]),
            ("c2", &vec![70, 80]),
        );
        let batch2 =
            build_table_i32(("a2", &vec![30]), ("b1", &vec![5]), ("c2", &vec![90]));
        let schema = batch1.schema();
        let right =
            TestMemoryExec::try_new_exec(&[vec![batch1], vec![batch2]], schema, None)
                .unwrap();

        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        // first part
        let stream = join.execute(0, Arc::clone(&task_ctx))?;
        let batches = common::collect(stream).await?;

        let expected_batch_count = if cfg!(not(feature = "force_hash_collisions")) {
            // Expected number of hash table matches for first right batch = 1
            // and additional empty batch for non-joined 20-6-80
            let mut expected_batch_count = div_ceil(1, batch_size);
            if batch_size == 1 {
                expected_batch_count += 1;
            }
            expected_batch_count
        } else {
            // With hash collisions enabled, all records will match each other
            // and filtered later.
            div_ceil(6, batch_size)
        };
        // With batch coalescing, we may have fewer batches than expected
        assert!(
            batches.len() <= expected_batch_count,
            "expected at most {expected_batch_count} batches, got {}",
            batches.len()
        );

        // Inner join output is expected to preserve both inputs order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  | 10 | 4  | 70 |
            +----+----+----+----+----+----+
            ");
        }

        // second part
        let stream = join.execute(1, Arc::clone(&task_ctx))?;
        let batches = common::collect(stream).await?;

        let expected_batch_count = if cfg!(not(feature = "force_hash_collisions")) {
            // Expected number of hash table matches for second right batch = 2
            div_ceil(2, batch_size)
        } else {
            // With hash collisions enabled, all records will match each other
            // and filtered later.
            div_ceil(3, batch_size)
        };
        // With batch coalescing, we may have fewer batches than expected
        assert!(
            batches.len() <= expected_batch_count,
            "expected at most {expected_batch_count} batches, got {}",
            batches.len()
        );

        // Inner join output is expected to preserve both inputs order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 2  | 5  | 8  | 30 | 5  | 90 |
            | 3  | 5  | 9  | 30 | 5  | 90 |
            +----+----+----+----+----+----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    fn build_table_two_batches(
        a: (&str, &Vec<i32>),
        b: (&str, &Vec<i32>),
        c: (&str, &Vec<i32>),
    ) -> Arc<dyn ExecutionPlan> {
        let batch = build_table_i32(a, b, c);
        let schema = batch.schema();
        TestMemoryExec::try_new_exec(&[vec![batch.clone(), batch]], schema, None).unwrap()
    }

    /// The hash map and array map paths must emit unmatched build rows of a
    /// `LeftAnti` join in the same order. Build order is not a plan-level
    /// guarantee (see #26235).
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_anti_keeps_build_order_across_batches(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let batch1 = build_table_i32(
            ("a1", &vec![1, 2]),
            ("b1", &vec![10, 20]),
            ("c1", &vec![7, 8]),
        );
        let batch2 = build_table_i32(
            ("a1", &vec![3, 4]),
            ("b1", &vec![3000, 4000]),
            ("c1", &vec![9, 10]),
        );
        let schema = batch1.schema();
        let left =
            TestMemoryExec::try_new_exec(&[vec![batch1, batch2]], schema, None).unwrap();
        let right = build_table(("a2", &vec![1]), ("b1", &vec![1]), ("c2", &vec![1]));
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::LeftAnti,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1"]);
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+------+----+
            | a1 | b1   | c1 |
            +----+------+----+
            | 1  | 10   | 7  |
            | 2  | 20   | 8  |
            | 3  | 3000 | 9  |
            | 4  | 4000 | 10 |
            +----+------+----+
            ");
        }
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    /// `probe_hit_rate` and `avg_fanout` must count each probe row once, even
    /// when a probe batch is processed in several chunks. Every probe row matches
    /// all 3 build rows, so any `batch_size` below 9 splits the probe batch into
    /// chunks, and some splits cut a single row's matches across chunks.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_probe_metrics_count_each_probe_row_once(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![2, 2, 2]),
            ("c1", &vec![3, 4, 5]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![2, 2, 2]),
            ("c2", &vec![30, 40, 50]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 2  | 3  | 10 | 2  | 30 |
            | 2  | 2  | 4  | 10 | 2  | 30 |
            | 3  | 2  | 5  | 10 | 2  | 30 |
            | 1  | 2  | 3  | 20 | 2  | 40 |
            | 2  | 2  | 4  | 20 | 2  | 40 |
            | 3  | 2  | 5  | 20 | 2  | 40 |
            | 1  | 2  | 3  | 30 | 2  | 50 |
            | 2  | 2  | 4  | 30 | 2  | 50 |
            | 3  | 2  | 5  | 30 | 2  | 50 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 9);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        assert_ratio_metric(&metrics, "probe_hit_rate", 3, 3);
        assert_ratio_metric(&metrics, "avg_fanout", 9, 3);

        Ok(())
    }

    /// Complements `join_probe_metrics_count_each_probe_row_once`: with unique
    /// build keys each probe row has at most one match, so chunks always split
    /// between probe rows. A probe row that starts a new chunk must still be
    /// counted, even though the lookup offset already points at it.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_probe_metrics_count_probe_row_starting_new_chunk(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 6]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 25, 30]),
            ("b1", &vec![4, 4, 4, 40]),
            ("c2", &vec![70, 80, 85, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 1  | 4  | 7  | 20 | 4  | 80 |
            | 1  | 4  | 7  | 25 | 4  | 85 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        assert_ratio_metric(&metrics, "probe_hit_rate", 3, 4);
        assert_ratio_metric(&metrics, "avg_fanout", 3, 3);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_multi_batch(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table_two_batches(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema()).unwrap()) as _,
        )];

        let join = join(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Left,
            NullEquality::NullEqualsNothing,
        )
        .unwrap();

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        let (_, batches, metrics) = join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Left,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 3  | 7  | 9  |    |    |    |
            +----+----+----+----+----+----+
            ");
        }

        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
        return Ok(());
    }

    /// Build side keyed `0..num_build_rows`, probe side holding only
    /// `matched_keys`, joined on the key column.
    fn final_build_rows_inputs(
        num_build_rows: i32,
        matched_keys: &[i32],
    ) -> (Arc<dyn ExecutionPlan>, Arc<dyn ExecutionPlan>, JoinOn) {
        let build_keys: Vec<i32> = (0..num_build_rows).collect();
        let probe_keys = matched_keys.to_vec();
        let left = build_table(
            ("a1", &build_keys),
            ("b1", &build_keys),
            ("c1", &build_keys),
        );
        let right = build_table(
            ("a2", &probe_keys),
            ("b2", &probe_keys),
            ("c2", &probe_keys),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
        )];
        (left, right, on)
    }

    /// Returns the sorted `(a1, matched)` pairs of the joined output, where
    /// `matched` is read from the mark column for `LeftMark`, from the
    /// presence of probe-side data for `Left`/`Full`, and is `None` for
    /// existence joins whose output carries no match information.
    fn build_rows_with_match_flag(batches: &[RecordBatch]) -> Vec<(i32, Option<bool>)> {
        let mut rows = vec![];
        for batch in batches {
            let a1 = batch
                .column_by_name("a1")
                .unwrap()
                .as_primitive::<Int32Type>();
            let matched: Vec<Option<bool>> = match batch.column_by_name("mark") {
                Some(mark) => mark.as_boolean().iter().collect(),
                None => match batch.column_by_name("a2") {
                    Some(a2) => (0..a2.len()).map(|i| Some(a2.is_valid(i))).collect(),
                    None => vec![None; batch.num_rows()],
                },
            };
            rows.extend(a1.values().iter().copied().zip(matched));
        }
        rows.sort_unstable();
        rows
    }

    /// The `(a1, matched)` pairs a join of [`final_build_rows_inputs`] must
    /// produce, in the format of [`build_rows_with_match_flag`].
    fn expected_final_build_rows(
        join_type: JoinType,
        num_build_rows: i32,
        matched_keys: &[i32],
    ) -> Vec<(i32, Option<bool>)> {
        (0..num_build_rows)
            .filter_map(|key| {
                let matched = matched_keys.contains(&key);
                match join_type {
                    JoinType::LeftSemi => matched.then_some((key, None)),
                    JoinType::LeftAnti => (!matched).then_some((key, None)),
                    _ => Some((key, Some(matched))),
                }
            })
            .collect()
    }

    /// The final build-side rows (unmatched rows, or matched rows for
    /// `LeftSemi`) must be emitted in chunks bounded by `batch_size` instead
    /// of one batch over the whole build side.
    #[rstest]
    #[tokio::test]
    async fn join_emits_final_build_rows_in_batch_size_chunks(
        #[values(
            JoinType::Left,
            JoinType::Full,
            JoinType::LeftAnti,
            JoinType::LeftSemi,
            JoinType::LeftMark
        )]
        join_type: JoinType,
        #[values(1, 7, 8192)] batch_size: usize,
        #[values(true, false)] use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let num_build_rows = 100;
        let matched_keys = [3, 50, 97];
        let (left, right, on) = final_build_rows_inputs(num_build_rows, &matched_keys);

        let (_, batches, metrics) = join_collect(
            left,
            right,
            on,
            &join_type,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        let expected =
            expected_final_build_rows(join_type, num_build_rows, &matched_keys);
        assert_eq!(build_rows_with_match_flag(&batches), expected);

        for batch in &batches {
            assert!(
                batch.num_rows() <= batch_size,
                "{join_type} join emitted a batch of {} rows with batch_size {batch_size}",
                batch.num_rows()
            );
        }
        assert!(
            batches.len() >= expected.len().div_ceil(batch_size),
            "{join_type} join emitted {} batches for {} rows with batch_size {batch_size}",
            batches.len(),
            expected.len()
        );

        Ok(())
    }

    /// A `fetch` limit that is reached in the middle of the final build-side
    /// rows stops the emission at exactly `fetch` rows.
    #[rstest]
    #[tokio::test]
    async fn join_fetch_stops_final_build_rows_mid_chunk(
        #[values(JoinType::Left, JoinType::LeftAnti, JoinType::LeftMark)]
        join_type: JoinType,
    ) -> Result<()> {
        let batch_size = 7;
        let fetch = 20;
        let num_build_rows = 100;
        let matched_keys = [3, 50, 97];
        let task_ctx = prepare_task_ctx(batch_size, false);
        let (left, right, on) = final_build_rows_inputs(num_build_rows, &matched_keys);

        let join = HashJoinExecBuilder::new(left, right, on, join_type)
            .with_partition_mode(PartitionMode::CollectLeft)
            .with_fetch(Some(fetch))
            .build()?;
        let batches = common::collect(join.execute(0, task_ctx)?).await?;

        let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(num_rows, fetch);
        for batch in &batches {
            assert!(batch.num_rows() <= batch_size);
        }
        // Every emitted row is a genuine join result row.
        let expected =
            expected_final_build_rows(join_type, num_build_rows, &matched_keys);
        for row in build_rows_with_match_flag(&batches) {
            assert!(expected.contains(&row), "unexpected output row {row:?}");
        }

        Ok(())
    }

    /// `fetch` stops each output partition separately, so the overall
    /// statistics must allow for the rows of every partition.
    #[tokio::test]
    async fn join_fetch_statistics_count_every_output_partition() -> Result<()> {
        let values: Vec<i32> = (0..100).collect();
        let left = build_table(("a1", &values), ("b1", &values), ("c1", &values));
        let batch = build_table_i32(("a2", &values), ("b2", &values), ("c2", &values));
        let schema = batch.schema();
        let right = TestMemoryExec::try_new_exec(&vec![vec![batch]; 4], schema, None)?;
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];
        let join: Arc<dyn ExecutionPlan> = Arc::new(
            HashJoinExecBuilder::new(left, right, on, JoinType::Inner)
                .with_partition_mode(PartitionMode::CollectLeft)
                .with_fetch(Some(10))
                .build()?,
        );
        assert_eq!(join.properties().output_partitioning().partition_count(), 4);

        // Each right row matches one left row, and each of the four output
        // partitions stops after 10 rows.
        let emitted: usize =
            crate::collect(Arc::clone(&join), prepare_task_ctx(8192, false))
                .await?
                .iter()
                .map(|batch| batch.num_rows())
                .sum();
        assert_eq!(emitted, 40);

        let num_rows = |partition| {
            StatisticsContext::new()
                .compute(
                    join.as_ref(),
                    &StatisticsArgs::new().with_partition(partition),
                )
                .map(|stats| stats.num_rows)
        };
        assert_eq!(num_rows(None)?, Precision::Inexact(40));
        assert_eq!(num_rows(Some(0))?, Precision::Inexact(10));
        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_full_multi_batch(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        // create two identical batches for the right side
        let right = build_table_two_batches(
            ("a2", &vec![10, 20, 30]),
            ("b2", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::Full,
            NullEquality::NullEqualsNothing,
        )
        .unwrap();

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);

        let stream = join.execute(0, task_ctx).unwrap();
        let batches = common::collect(stream).await.unwrap();
        let metrics = join.metrics().unwrap();

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b2 | c2 |
            +----+----+----+----+----+----+
            |    |    |    | 30 | 6  | 90 |
            |    |    |    | 30 | 6  | 90 |
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 3  | 7  | 9  |    |    |    |
            +----+----+----+----+----+----+
            ");
        }

        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_empty_right(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table_i32(("a2", &vec![]), ("b1", &vec![]), ("c2", &vec![]));
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema()).unwrap()) as _,
        )];
        let schema = right.schema();
        let right = TestMemoryExec::try_new_exec(&[vec![right]], schema, None).unwrap();
        let join = join(
            left,
            right,
            on,
            &JoinType::Left,
            NullEquality::NullEqualsNothing,
        )
        .unwrap();

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        let stream = join.execute(0, task_ctx).unwrap();
        let batches = common::collect(stream).await.unwrap();
        let metrics = join.metrics().unwrap();

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  |    |    |    |
            | 2  | 5  | 8  |    |    |    |
            | 3  | 7  | 9  |    |    |    |
            +----+----+----+----+----+----+
            ");
        }

        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_full_empty_right(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table_i32(("a2", &vec![]), ("b2", &vec![]), ("c2", &vec![]));
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
        )];
        let schema = right.schema();
        let right = TestMemoryExec::try_new_exec(&[vec![right]], schema, None).unwrap();
        let join = join(
            left,
            right,
            on,
            &JoinType::Full,
            NullEquality::NullEqualsNothing,
        )
        .unwrap();

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);

        let stream = join.execute(0, task_ctx).unwrap();
        let batches = common::collect(stream).await.unwrap();
        let metrics = join.metrics().unwrap();

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b2 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  |    |    |    |
            | 2  | 5  | 8  |    |    |    |
            | 3  | 7  | 9  |    |    |    |
            +----+----+----+----+----+----+
            ");
        }

        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_one(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Left,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 3  | 7  | 9  |    |    |    |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    /// Under NullEqualsNothing, NULL join keys are not inserted into the hash
    /// map, so a build side whose keys are all NULL produces an empty map even
    /// though it contains rows. Join types that emit unmatched build rows must
    /// still produce them from the visited bitmap.
    #[rstest]
    #[tokio::test]
    async fn join_all_null_build_keys(
        #[values(PartitionMode::CollectLeft, PartitionMode::Partitioned)]
        partition_mode: PartitionMode,
    ) -> Result<()> {
        let left = build_table_two_cols(
            ("a1", &vec![Some(1), Some(2)]),
            ("b1", &vec![None, None]), // all build-side join keys are NULL
        );
        let right = build_table_two_cols(
            ("a2", &vec![Some(10), Some(20), Some(30)]),
            ("b1", &vec![Some(4), None, Some(6)]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        for join_type in [
            JoinType::Inner,
            JoinType::Left,
            JoinType::Right,
            JoinType::Full,
            JoinType::LeftSemi,
            JoinType::LeftAnti,
            JoinType::RightSemi,
            JoinType::RightAnti,
            JoinType::LeftMark,
            JoinType::RightMark,
        ] {
            let (_, batches, metrics) = join_collect_with_partition_mode(
                Arc::clone(&left),
                Arc::clone(&right),
                on.clone(),
                &join_type,
                partition_mode,
                NullEquality::NullEqualsNothing,
                Arc::new(TaskContext::default()),
            )
            .await?;

            // For join types whose output requires a build-side match, an
            // empty map guarantees an empty result, so `state_after_build_ready`
            // completes the stream without ever fetching a probe batch (probe
            // `input_rows` stays 0). All other join types must still scan the
            // probe side. `input_rows` is summed across every partition.
            let probe_rows = metrics
                .sum_by_name("input_rows")
                .map(|v| v.as_usize())
                .unwrap_or(0);
            if join_type.empty_map_produces_empty_result() {
                assert_eq!(
                    probe_rows, 0,
                    "{join_type} should skip the probe side for an all-NULL build"
                );
            } else {
                assert!(probe_rows > 0, "{join_type} must scan the probe side");
            }

            match join_type {
                JoinType::Inner | JoinType::LeftSemi | JoinType::RightSemi => {
                    let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
                    assert_eq!(num_rows, 0, "unexpected rows for {join_type}");
                }
                JoinType::Left => {
                    allow_duplicates! {
                        assert_snapshot!(batches_to_sort_string(&batches), @r"
                        +----+----+----+----+
                        | a1 | b1 | a2 | b1 |
                        +----+----+----+----+
                        | 1  |    |    |    |
                        | 2  |    |    |    |
                        +----+----+----+----+
                        ");
                    }
                }
                JoinType::Right => {
                    allow_duplicates! {
                        assert_snapshot!(batches_to_sort_string(&batches), @r"
                        +----+----+----+----+
                        | a1 | b1 | a2 | b1 |
                        +----+----+----+----+
                        |    |    | 10 | 4  |
                        |    |    | 20 |    |
                        |    |    | 30 | 6  |
                        +----+----+----+----+
                        ");
                    }
                }
                JoinType::Full => {
                    allow_duplicates! {
                        assert_snapshot!(batches_to_sort_string(&batches), @r"
                        +----+----+----+----+
                        | a1 | b1 | a2 | b1 |
                        +----+----+----+----+
                        |    |    | 10 | 4  |
                        |    |    | 20 |    |
                        |    |    | 30 | 6  |
                        | 1  |    |    |    |
                        | 2  |    |    |    |
                        +----+----+----+----+
                        ");
                    }
                }
                JoinType::LeftAnti => {
                    allow_duplicates! {
                        assert_snapshot!(batches_to_sort_string(&batches), @r"
                        +----+----+
                        | a1 | b1 |
                        +----+----+
                        | 1  |    |
                        | 2  |    |
                        +----+----+
                        ");
                    }
                }
                JoinType::RightAnti => {
                    allow_duplicates! {
                        assert_snapshot!(batches_to_sort_string(&batches), @r"
                        +----+----+
                        | a2 | b1 |
                        +----+----+
                        | 10 | 4  |
                        | 20 |    |
                        | 30 | 6  |
                        +----+----+
                        ");
                    }
                }
                JoinType::LeftMark => {
                    allow_duplicates! {
                        assert_snapshot!(batches_to_sort_string(&batches), @r"
                        +----+----+-------+
                        | a1 | b1 | mark  |
                        +----+----+-------+
                        | 1  |    | false |
                        | 2  |    | false |
                        +----+----+-------+
                        ");
                    }
                }
                JoinType::RightMark => {
                    allow_duplicates! {
                        assert_snapshot!(batches_to_sort_string(&batches), @r"
                        +----+----+-------+
                        | a2 | b1 | mark  |
                        +----+----+-------+
                        | 10 | 4  | false |
                        | 20 |    | false |
                        | 30 | 6  | false |
                        +----+----+-------+
                        ");
                    }
                }
            }
        }

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn partitioned_join_left_one(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = partitioned_join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Left,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 3  | 7  | 9  |    |    |    |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    fn build_semi_anti_left_table() -> Arc<dyn ExecutionPlan> {
        // just two line match
        // b1 = 10
        build_table(
            ("a1", &vec![1, 3, 5, 7, 9, 11, 13]),
            ("b1", &vec![1, 3, 5, 7, 8, 8, 10]),
            ("c1", &vec![10, 30, 50, 70, 90, 110, 130]),
        )
    }

    fn build_semi_anti_right_table() -> Arc<dyn ExecutionPlan> {
        // just two line match
        // b2 = 10
        build_table(
            ("a2", &vec![8, 12, 6, 2, 10, 4]),
            ("b2", &vec![8, 10, 6, 2, 10, 4]),
            ("c2", &vec![20, 40, 60, 80, 100, 120]),
        )
    }

    #[tokio::test]
    async fn test_semi_left_join_reports_final_emission() -> Result<()> {
        let (left_schema, right_schema, on) = build_schema_and_on()?;

        let left = TestMemoryExec::try_new_exec(&[vec![]], left_schema, None)?;

        let right = TestMemoryExec::try_new_exec(&[vec![]], right_schema, None)?;

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftSemi,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            false,
        )?;

        assert_eq!(join.properties().emission_type, EmissionType::Final);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_semi(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_semi_anti_left_table();
        let right = build_semi_anti_right_table();
        // left_table left semi join right_table on left_table.b1 = right_table.b2
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::LeftSemi,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a1", "b1", "c1"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // ignore the order
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+-----+
            | a1 | b1 | c1  |
            +----+----+-----+
            | 11 | 8  | 110 |
            | 13 | 10 | 130 |
            | 9  | 8  | 90  |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_semi_with_filter(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_semi_anti_left_table();
        let right = build_semi_anti_right_table();

        // left_table left semi join right_table on left_table.b1 = right_table.b2 and right_table.a2 != 10
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let column_indices = vec![ColumnIndex {
            index: 0,
            side: JoinSide::Right,
        }];
        let intermediate_schema =
            Schema::new(vec![Field::new("x", DataType::Int32, true)]);

        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::NotEq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        )) as Arc<dyn PhysicalExpr>;

        let filter = JoinFilter::new(
            filter_expression,
            column_indices.clone(),
            Arc::new(intermediate_schema.clone()),
        );

        let join = join_with_filter(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            filter,
            &JoinType::LeftSemi,
            NullEquality::NullEqualsNothing,
        )?;

        let columns_header = columns(&join.schema());
        assert_eq!(columns_header.clone(), vec!["a1", "b1", "c1"]);

        let stream = join.execute(0, Arc::clone(&task_ctx))?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+-----+
            | a1 | b1 | c1  |
            +----+----+-----+
            | 11 | 8  | 110 |
            | 13 | 10 | 130 |
            | 9  | 8  | 90  |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        // left_table left semi join right_table on left_table.b1 = right_table.b2 and right_table.a2 > 10
        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        )) as Arc<dyn PhysicalExpr>;
        let filter = JoinFilter::new(
            filter_expression,
            column_indices,
            Arc::new(intermediate_schema),
        );

        let join = join_with_filter(
            left,
            right,
            on,
            filter,
            &JoinType::LeftSemi,
            NullEquality::NullEqualsNothing,
        )?;

        let columns_header = columns(&join.schema());
        assert_eq!(columns_header, vec!["a1", "b1", "c1"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+-----+
            | a1 | b1 | c1  |
            +----+----+-----+
            | 13 | 10 | 130 |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_right_semi(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_semi_anti_left_table();
        let right = build_semi_anti_right_table();

        // left_table right semi join right_table on left_table.b1 = right_table.b2
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::RightSemi,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a2", "b2", "c2"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // RightSemi join output is expected to preserve right input order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+-----+
            | a2 | b2 | c2  |
            +----+----+-----+
            | 8  | 8  | 20  |
            | 12 | 10 | 40  |
            | 10 | 10 | 100 |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_right_semi_with_filter(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_semi_anti_left_table();
        let right = build_semi_anti_right_table();

        // left_table right semi join right_table on left_table.b1 = right_table.b2 on left_table.a1!=9
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let column_indices = vec![ColumnIndex {
            index: 0,
            side: JoinSide::Left,
        }];
        let intermediate_schema =
            Schema::new(vec![Field::new("x", DataType::Int32, true)]);

        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::NotEq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(9)))),
        )) as Arc<dyn PhysicalExpr>;

        let filter = JoinFilter::new(
            filter_expression,
            column_indices.clone(),
            Arc::new(intermediate_schema.clone()),
        );

        let join = join_with_filter(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            filter,
            &JoinType::RightSemi,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a2", "b2", "c2"]);

        let stream = join.execute(0, Arc::clone(&task_ctx))?;
        let batches = common::collect(stream).await?;

        // RightSemi join output is expected to preserve right input order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+-----+
            | a2 | b2 | c2  |
            +----+----+-----+
            | 8  | 8  | 20  |
            | 12 | 10 | 40  |
            | 10 | 10 | 100 |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        // left_table right semi join right_table on left_table.b1 = right_table.b2 on left_table.a1!=9
        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::Gt,
            Arc::new(Literal::new(ScalarValue::Int32(Some(11)))),
        )) as Arc<dyn PhysicalExpr>;

        let filter = JoinFilter::new(
            filter_expression,
            column_indices,
            Arc::new(intermediate_schema.clone()),
        );

        let join = join_with_filter(
            left,
            right,
            on,
            filter,
            &JoinType::RightSemi,
            NullEquality::NullEqualsNothing,
        )?;
        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // RightSemi join output is expected to preserve right input order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+-----+
            | a2 | b2 | c2  |
            +----+----+-----+
            | 12 | 10 | 40  |
            | 10 | 10 | 100 |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_anti(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_semi_anti_left_table();
        let right = build_semi_anti_right_table();
        // left_table left anti join right_table on left_table.b1 = right_table.b2
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::LeftAnti,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a1", "b1", "c1"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+
            | a1 | b1 | c1 |
            +----+----+----+
            | 1  | 1  | 10 |
            | 3  | 3  | 30 |
            | 5  | 5  | 50 |
            | 7  | 7  | 70 |
            +----+----+----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_anti_with_filter(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_semi_anti_left_table();
        let right = build_semi_anti_right_table();
        // left_table left anti join right_table on left_table.b1 = right_table.b2 and right_table.a2!=8
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let column_indices = vec![ColumnIndex {
            index: 0,
            side: JoinSide::Right,
        }];
        let intermediate_schema =
            Schema::new(vec![Field::new("x", DataType::Int32, true)]);
        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::NotEq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(8)))),
        )) as Arc<dyn PhysicalExpr>;

        let filter = JoinFilter::new(
            filter_expression,
            column_indices.clone(),
            Arc::new(intermediate_schema.clone()),
        );

        let join = join_with_filter(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            filter,
            &JoinType::LeftAnti,
            NullEquality::NullEqualsNothing,
        )?;

        let columns_header = columns(&join.schema());
        assert_eq!(columns_header, vec!["a1", "b1", "c1"]);

        let stream = join.execute(0, Arc::clone(&task_ctx))?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+-----+
            | a1 | b1 | c1  |
            +----+----+-----+
            | 1  | 1  | 10  |
            | 11 | 8  | 110 |
            | 3  | 3  | 30  |
            | 5  | 5  | 50  |
            | 7  | 7  | 70  |
            | 9  | 8  | 90  |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        // left_table left anti join right_table on left_table.b1 = right_table.b2 and right_table.a2 != 13
        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::NotEq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(8)))),
        )) as Arc<dyn PhysicalExpr>;

        let filter = JoinFilter::new(
            filter_expression,
            column_indices,
            Arc::new(intermediate_schema),
        );

        let join = join_with_filter(
            left,
            right,
            on,
            filter,
            &JoinType::LeftAnti,
            NullEquality::NullEqualsNothing,
        )?;

        let columns_header = columns(&join.schema());
        assert_eq!(columns_header, vec!["a1", "b1", "c1"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+-----+
            | a1 | b1 | c1  |
            +----+----+-----+
            | 1  | 1  | 10  |
            | 11 | 8  | 110 |
            | 3  | 3  | 30  |
            | 5  | 5  | 50  |
            | 7  | 7  | 70  |
            | 9  | 8  | 90  |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_right_anti(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_semi_anti_left_table();
        let right = build_semi_anti_right_table();
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::RightAnti,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a2", "b2", "c2"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // RightAnti join output is expected to preserve right input order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+-----+
            | a2 | b2 | c2  |
            +----+----+-----+
            | 6  | 6  | 60  |
            | 2  | 2  | 80  |
            | 4  | 4  | 120 |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_right_anti_with_filter(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_semi_anti_left_table();
        let right = build_semi_anti_right_table();
        // left_table right anti join right_table on left_table.b1 = right_table.b2 and left_table.a1!=13
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        let column_indices = vec![ColumnIndex {
            index: 0,
            side: JoinSide::Left,
        }];
        let intermediate_schema =
            Schema::new(vec![Field::new("x", DataType::Int32, true)]);

        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::NotEq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(13)))),
        )) as Arc<dyn PhysicalExpr>;

        let filter = JoinFilter::new(
            filter_expression,
            column_indices,
            Arc::new(intermediate_schema.clone()),
        );

        let join = join_with_filter(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            filter,
            &JoinType::RightAnti,
            NullEquality::NullEqualsNothing,
        )?;

        let columns_header = columns(&join.schema());
        assert_eq!(columns_header, vec!["a2", "b2", "c2"]);

        let stream = join.execute(0, Arc::clone(&task_ctx))?;
        let batches = common::collect(stream).await?;

        // RightAnti join output is expected to preserve right input order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+-----+
            | a2 | b2 | c2  |
            +----+----+-----+
            | 12 | 10 | 40  |
            | 6  | 6  | 60  |
            | 2  | 2  | 80  |
            | 10 | 10 | 100 |
            | 4  | 4  | 120 |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        // left_table right anti join right_table on left_table.b1 = right_table.b2 and right_table.b2!=8
        let column_indices = vec![ColumnIndex {
            index: 1,
            side: JoinSide::Right,
        }];
        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::NotEq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(8)))),
        )) as Arc<dyn PhysicalExpr>;

        let filter = JoinFilter::new(
            filter_expression,
            column_indices,
            Arc::new(intermediate_schema),
        );

        let join = join_with_filter(
            left,
            right,
            on,
            filter,
            &JoinType::RightAnti,
            NullEquality::NullEqualsNothing,
        )?;

        let columns_header = columns(&join.schema());
        assert_eq!(columns_header, vec!["a2", "b2", "c2"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // RightAnti join output is expected to preserve right input order
        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +----+----+-----+
            | a2 | b2 | c2  |
            +----+----+-----+
            | 8  | 8  | 20  |
            | 6  | 6  | 60  |
            | 2  | 2  | 80  |
            | 4  | 4  | 120 |
            +----+----+-----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_right_one(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]), // 6 does not exist on the left
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Right,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            |    |    |    | 30 | 6  | 90 |
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn partitioned_join_right_one(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]), // 6 does not exist on the left
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = partitioned_join_collect(
            left,
            right,
            on,
            &JoinType::Right,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b1", "c2"]);

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b1 | c2 |
            +----+----+----+----+----+----+
            |    |    |    | 30 | 6  | 90 |
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            +----+----+----+----+----+----+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_full_one(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b2", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::Full,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+----+----+----+
            | a1 | b1 | c1 | a2 | b2 | c2 |
            +----+----+----+----+----+----+
            |    |    |    | 30 | 6  | 90 |
            | 1  | 4  | 7  | 10 | 4  | 70 |
            | 2  | 5  | 8  | 20 | 5  | 80 |
            | 3  | 7  | 9  |    |    |    |
            +----+----+----+----+----+----+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_mark(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::LeftMark,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "mark"]);

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+-------+
            | a1 | b1 | c1 | mark  |
            +----+----+----+-------+
            | 1  | 4  | 7  | true  |
            | 2  | 5  | 8  | true  |
            | 3  | 7  | 9  | false |
            +----+----+----+-------+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn partitioned_join_left_mark(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30, 40]),
            ("b1", &vec![4, 4, 5, 6]),
            ("c2", &vec![60, 70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = partitioned_join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::LeftMark,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "mark"]);

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+-------+
            | a1 | b1 | c1 | mark  |
            +----+----+----+-------+
            | 1  | 4  | 7  | true  |
            | 2  | 5  | 8  | true  |
            | 3  | 7  | 9  | false |
            +----+----+----+-------+
            ");
        }

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_right_mark(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]), // 6 does not exist on the left
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::RightMark,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a2", "b1", "c2", "mark"]);

        let expected = [
            "+----+----+----+-------+",
            "| a2 | b1 | c2 | mark  |",
            "+----+----+----+-------+",
            "| 10 | 4  | 70 | true  |",
            "| 20 | 5  | 80 | true  |",
            "| 30 | 6  | 90 | false |",
            "+----+----+----+-------+",
        ];
        assert_batches_sorted_eq!(expected, &batches);

        assert_join_metrics!(metrics, 3);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn partitioned_join_right_mark(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]), // 7 does not exist on the right
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30, 40]),
            ("b1", &vec![4, 4, 5, 6]), // 6 does not exist on the left
            ("c2", &vec![60, 70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = partitioned_join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::RightMark,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a2", "b1", "c2", "mark"]);

        let expected = [
            "+----+----+----+-------+",
            "| a2 | b1 | c2 | mark  |",
            "+----+----+----+-------+",
            "| 10 | 4  | 60 | true  |",
            "| 20 | 4  | 70 | true  |",
            "| 30 | 5  | 80 | true  |",
            "| 40 | 6  | 90 | false |",
            "+----+----+----+-------+",
        ];
        assert_batches_sorted_eq!(expected, &batches);

        assert_join_metrics!(metrics, 4);
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[test]
    fn join_with_hash_collisions_64() -> Result<()> {
        let mut hashmap_left = HashTable::with_capacity(4);
        let left = build_table_i32(
            ("a", &vec![10, 20]),
            ("x", &vec![100, 200]),
            ("y", &vec![200, 300]),
        );

        let random_state = RandomState::with_seed(0);
        let hashes_buff = &mut vec![0; left.num_rows()];
        let hashes = create_hashes([&left.columns()[0]], &random_state, hashes_buff)?;

        // Maps both values to both indices (1 and 2, representing input 0 and 1)
        // 0 -> (0, 1)
        // 1 -> (0, 2)
        // The equality check will make sure only hashes[0] maps to 0 and hashes[1] maps to 1
        hashmap_left.insert_unique(hashes[0], (hashes[0], 1), |(h, _)| *h);
        hashmap_left.insert_unique(hashes[0], (hashes[0], 2), |(h, _)| *h);

        hashmap_left.insert_unique(hashes[1], (hashes[1], 1), |(h, _)| *h);
        hashmap_left.insert_unique(hashes[1], (hashes[1], 2), |(h, _)| *h);

        let next = vec![2, 0];

        let right = build_table_i32(
            ("a", &vec![10, 20]),
            ("b", &vec![0, 0]),
            ("c", &vec![30, 40]),
        );

        // Join key column for both join sides
        let key_column: PhysicalExprRef = Arc::new(Column::new("a", 0)) as _;

        let join_hash_map = JoinHashMapU64::new(hashmap_left, next);

        let left_keys_values = key_column.evaluate(&left)?.into_array(left.num_rows())?;
        let right_keys_values =
            key_column.evaluate(&right)?.into_array(right.num_rows())?;
        let mut hashes_buffer = vec![0; right.num_rows()];
        create_hashes([&right_keys_values], &random_state, &mut hashes_buffer)?;

        let mut probe_indices_buffer = Vec::new();
        let mut build_indices_buffer = Vec::new();
        let (l, r, _) = lookup_join_hashmap(
            &join_hash_map,
            &[left_keys_values],
            &[right_keys_values],
            NullEquality::NullEqualsNothing,
            &hashes_buffer,
            None,
            8192,
            AtRow { row: 0 },
            &mut probe_indices_buffer,
            &mut build_indices_buffer,
            &mut None,
        )?;

        let left_ids: UInt64Array = vec![0, 1].into();

        let right_ids: UInt32Array = vec![0, 1].into();

        assert_eq!(left_ids, l);

        assert_eq!(right_ids, r);

        Ok(())
    }

    #[test]
    fn join_with_hash_collisions_u32() -> Result<()> {
        let mut hashmap_left = HashTable::with_capacity(4);
        let left = build_table_i32(
            ("a", &vec![10, 20]),
            ("x", &vec![100, 200]),
            ("y", &vec![200, 300]),
        );

        let random_state = RandomState::with_seed(0);
        let hashes_buff = &mut vec![0; left.num_rows()];
        let hashes = create_hashes([&left.columns()[0]], &random_state, hashes_buff)?;

        hashmap_left.insert_unique(hashes[0], (hashes[0], 1u32), |(h, _)| *h);
        hashmap_left.insert_unique(hashes[0], (hashes[0], 2u32), |(h, _)| *h);
        hashmap_left.insert_unique(hashes[1], (hashes[1], 1u32), |(h, _)| *h);
        hashmap_left.insert_unique(hashes[1], (hashes[1], 2u32), |(h, _)| *h);

        let next: Vec<u32> = vec![2, 0];

        let right = build_table_i32(
            ("a", &vec![10, 20]),
            ("b", &vec![0, 0]),
            ("c", &vec![30, 40]),
        );

        let key_column: PhysicalExprRef = Arc::new(Column::new("a", 0)) as _;

        let join_hash_map = JoinHashMapU32::new(hashmap_left, next);

        let left_keys_values = key_column.evaluate(&left)?.into_array(left.num_rows())?;
        let right_keys_values =
            key_column.evaluate(&right)?.into_array(right.num_rows())?;
        let mut hashes_buffer = vec![0; right.num_rows()];
        create_hashes([&right_keys_values], &random_state, &mut hashes_buffer)?;

        let mut probe_indices_buffer = Vec::new();
        let mut build_indices_buffer = Vec::new();
        let (l, r, _) = lookup_join_hashmap(
            &join_hash_map,
            &[left_keys_values],
            &[right_keys_values],
            NullEquality::NullEqualsNothing,
            &hashes_buffer,
            None,
            8192,
            AtRow { row: 0 },
            &mut probe_indices_buffer,
            &mut build_indices_buffer,
            &mut None,
        )?;

        // We still expect to match rows 0 and 1 on both sides
        let left_ids: UInt64Array = vec![0, 1].into();
        let right_ids: UInt32Array = vec![0, 1].into();

        assert_eq!(left_ids, l);
        assert_eq!(right_ids, r);

        Ok(())
    }

    #[tokio::test]
    async fn join_with_duplicated_column_names() -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        let left = build_table(
            ("a", &vec![1, 2, 3]),
            ("b", &vec![4, 5, 7]),
            ("c", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a", &vec![10, 20, 30]),
            ("b", &vec![1, 2, 7]),
            ("c", &vec![70, 80, 90]),
        );
        let on = vec![(
            // join on a=b so there are duplicate column names on unjoined columns
            Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +---+---+---+----+---+----+
            | a | b | c | a  | b | c  |
            +---+---+---+----+---+----+
            | 1 | 4 | 7 | 10 | 1 | 70 |
            | 2 | 5 | 8 | 20 | 2 | 80 |
            +---+---+---+----+---+----+
            ");
        }

        Ok(())
    }

    fn prepare_join_filter() -> JoinFilter {
        let column_indices = vec![
            ColumnIndex {
                index: 2,
                side: JoinSide::Left,
            },
            ColumnIndex {
                index: 2,
                side: JoinSide::Right,
            },
        ];
        let intermediate_schema = Schema::new(vec![
            Field::new("c", DataType::Int32, true),
            Field::new("c", DataType::Int32, true),
        ]);
        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("c", 0)),
            Operator::Gt,
            Arc::new(Column::new("c", 1)),
        )) as Arc<dyn PhysicalExpr>;

        JoinFilter::new(
            filter_expression,
            column_indices,
            Arc::new(intermediate_schema),
        )
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_inner_with_filter(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a", &vec![0, 1, 2, 2]),
            ("b", &vec![4, 5, 7, 8]),
            ("c", &vec![7, 8, 9, 1]),
        );
        let right = build_table(
            ("a", &vec![10, 20, 30, 40]),
            ("b", &vec![2, 2, 3, 4]),
            ("c", &vec![7, 5, 6, 4]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
        )];
        let filter = prepare_join_filter();

        let join = join_with_filter(
            left,
            right,
            on,
            filter,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +---+---+---+----+---+---+
            | a | b | c | a  | b | c |
            +---+---+---+----+---+---+
            | 2 | 7 | 9 | 10 | 2 | 7 |
            | 2 | 7 | 9 | 20 | 2 | 5 |
            +---+---+---+----+---+---+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_left_with_filter(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a", &vec![0, 1, 2, 2]),
            ("b", &vec![4, 5, 7, 8]),
            ("c", &vec![7, 8, 9, 1]),
        );
        let right = build_table(
            ("a", &vec![10, 20, 30, 40]),
            ("b", &vec![2, 2, 3, 4]),
            ("c", &vec![7, 5, 6, 4]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
        )];
        let filter = prepare_join_filter();

        let join = join_with_filter(
            left,
            right,
            on,
            filter,
            &JoinType::Left,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +---+---+---+----+---+---+
            | a | b | c | a  | b | c |
            +---+---+---+----+---+---+
            | 0 | 4 | 7 |    |   |   |
            | 1 | 5 | 8 |    |   |   |
            | 2 | 7 | 9 | 10 | 2 | 7 |
            | 2 | 7 | 9 | 20 | 2 | 5 |
            | 2 | 8 | 1 |    |   |   |
            +---+---+---+----+---+---+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_right_with_filter(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a", &vec![0, 1, 2, 2]),
            ("b", &vec![4, 5, 7, 8]),
            ("c", &vec![7, 8, 9, 1]),
        );
        let right = build_table(
            ("a", &vec![10, 20, 30, 40]),
            ("b", &vec![2, 2, 3, 4]),
            ("c", &vec![7, 5, 6, 4]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
        )];
        let filter = prepare_join_filter();

        let join = join_with_filter(
            left,
            right,
            on,
            filter,
            &JoinType::Right,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +---+---+---+----+---+---+
            | a | b | c | a  | b | c |
            +---+---+---+----+---+---+
            |   |   |   | 30 | 3 | 6 |
            |   |   |   | 40 | 4 | 4 |
            | 2 | 7 | 9 | 10 | 2 | 7 |
            | 2 | 7 | 9 | 20 | 2 | 5 |
            +---+---+---+----+---+---+
            ");
        }

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn join_full_with_filter(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let left = build_table(
            ("a", &vec![0, 1, 2, 2]),
            ("b", &vec![4, 5, 7, 8]),
            ("c", &vec![7, 8, 9, 1]),
        );
        let right = build_table(
            ("a", &vec![10, 20, 30, 40]),
            ("b", &vec![2, 2, 3, 4]),
            ("c", &vec![7, 5, 6, 4]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b", &right.schema()).unwrap()) as _,
        )];
        let filter = prepare_join_filter();

        let join = join_with_filter(
            left,
            right,
            on,
            filter,
            &JoinType::Full,
            NullEquality::NullEqualsNothing,
        )?;

        let columns = columns(&join.schema());
        assert_eq!(columns, vec!["a", "b", "c", "a", "b", "c"]);

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        let expected = [
            "+---+---+---+----+---+---+",
            "| a | b | c | a  | b | c |",
            "+---+---+---+----+---+---+",
            "|   |   |   | 30 | 3 | 6 |",
            "|   |   |   | 40 | 4 | 4 |",
            "| 2 | 7 | 9 | 10 | 2 | 7 |",
            "| 2 | 7 | 9 | 20 | 2 | 5 |",
            "| 0 | 4 | 7 |    |   |   |",
            "| 1 | 5 | 8 |    |   |   |",
            "| 2 | 8 | 1 |    |   |   |",
            "+---+---+---+----+---+---+",
        ];
        assert_batches_sorted_eq!(expected, &batches);

        let metrics = join.metrics().unwrap();
        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        // THIS MIGRATION HALTED DUE TO ISSUE #15312
        //allow_duplicates! {
        //    assert_snapshot!(batches_to_sort_string(&batches), @r#"
        //    +---+---+---+----+---+---+
        //    | a | b | c | a  | b | c |
        //    +---+---+---+----+---+---+
        //    |   |   |   | 30 | 3 | 6 |
        //    |   |   |   | 40 | 4 | 4 |
        //    | 2 | 7 | 9 | 10 | 2 | 7 |
        //    | 2 | 7 | 9 | 20 | 2 | 5 |
        //    | 0 | 4 | 7 |    |   |   |
        //    | 1 | 5 | 8 |    |   |   |
        //    | 2 | 8 | 1 |    |   |   |
        //    +---+---+---+----+---+---+
        //        "#)
        //}

        Ok(())
    }

    /// Test for parallelized HashJoinExec with PartitionMode::CollectLeft
    #[tokio::test]
    async fn test_collect_left_multiple_partitions_join() -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b2", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
        )];

        let expected_inner = vec![
            "+----+----+----+----+----+----+",
            "| a1 | b1 | c1 | a2 | b2 | c2 |",
            "+----+----+----+----+----+----+",
            "| 1  | 4  | 7  | 10 | 4  | 70 |",
            "| 2  | 5  | 8  | 20 | 5  | 80 |",
            "+----+----+----+----+----+----+",
        ];
        let expected_left = vec![
            "+----+----+----+----+----+----+",
            "| a1 | b1 | c1 | a2 | b2 | c2 |",
            "+----+----+----+----+----+----+",
            "| 1  | 4  | 7  | 10 | 4  | 70 |",
            "| 2  | 5  | 8  | 20 | 5  | 80 |",
            "| 3  | 7  | 9  |    |    |    |",
            "+----+----+----+----+----+----+",
        ];
        let expected_right = vec![
            "+----+----+----+----+----+----+",
            "| a1 | b1 | c1 | a2 | b2 | c2 |",
            "+----+----+----+----+----+----+",
            "|    |    |    | 30 | 6  | 90 |",
            "| 1  | 4  | 7  | 10 | 4  | 70 |",
            "| 2  | 5  | 8  | 20 | 5  | 80 |",
            "+----+----+----+----+----+----+",
        ];
        let expected_full = vec![
            "+----+----+----+----+----+----+",
            "| a1 | b1 | c1 | a2 | b2 | c2 |",
            "+----+----+----+----+----+----+",
            "|    |    |    | 30 | 6  | 90 |",
            "| 1  | 4  | 7  | 10 | 4  | 70 |",
            "| 2  | 5  | 8  | 20 | 5  | 80 |",
            "| 3  | 7  | 9  |    |    |    |",
            "+----+----+----+----+----+----+",
        ];
        let expected_left_semi = vec![
            "+----+----+----+",
            "| a1 | b1 | c1 |",
            "+----+----+----+",
            "| 1  | 4  | 7  |",
            "| 2  | 5  | 8  |",
            "+----+----+----+",
        ];
        let expected_left_anti = vec![
            "+----+----+----+",
            "| a1 | b1 | c1 |",
            "+----+----+----+",
            "| 3  | 7  | 9  |",
            "+----+----+----+",
        ];
        let expected_right_semi = vec![
            "+----+----+----+",
            "| a2 | b2 | c2 |",
            "+----+----+----+",
            "| 10 | 4  | 70 |",
            "| 20 | 5  | 80 |",
            "+----+----+----+",
        ];
        let expected_right_anti = vec![
            "+----+----+----+",
            "| a2 | b2 | c2 |",
            "+----+----+----+",
            "| 30 | 6  | 90 |",
            "+----+----+----+",
        ];
        let expected_left_mark = vec![
            "+----+----+----+-------+",
            "| a1 | b1 | c1 | mark  |",
            "+----+----+----+-------+",
            "| 1  | 4  | 7  | true  |",
            "| 2  | 5  | 8  | true  |",
            "| 3  | 7  | 9  | false |",
            "+----+----+----+-------+",
        ];
        let expected_right_mark = vec![
            "+----+----+----+-------+",
            "| a2 | b2 | c2 | mark  |",
            "+----+----+----+-------+",
            "| 10 | 4  | 70 | true  |",
            "| 20 | 5  | 80 | true  |",
            "| 30 | 6  | 90 | false |",
            "+----+----+----+-------+",
        ];

        let test_cases = vec![
            (JoinType::Inner, expected_inner),
            (JoinType::Left, expected_left),
            (JoinType::Right, expected_right),
            (JoinType::Full, expected_full),
            (JoinType::LeftSemi, expected_left_semi),
            (JoinType::LeftAnti, expected_left_anti),
            (JoinType::RightSemi, expected_right_semi),
            (JoinType::RightAnti, expected_right_anti),
            (JoinType::LeftMark, expected_left_mark),
            (JoinType::RightMark, expected_right_mark),
        ];

        for (join_type, expected) in test_cases {
            let (_, batches, metrics) = join_collect_with_partition_mode(
                Arc::clone(&left),
                Arc::clone(&right),
                on.clone(),
                &join_type,
                PartitionMode::CollectLeft,
                NullEquality::NullEqualsNothing,
                Arc::clone(&task_ctx),
            )
            .await?;
            assert_batches_sorted_eq!(expected, &batches);
            assert_join_metrics!(metrics, expected.len() - 4);
        }

        Ok(())
    }

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

        let dates: ArrayRef = Arc::new(Date32Array::from(vec![19107, 19108, 19109]));
        let n: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![dates, n])?;
        let left =
            TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)
                .unwrap();
        let dates: ArrayRef = Arc::new(Date32Array::from(vec![19108, 19108, 19109]));
        let n: ArrayRef = Arc::new(Int32Array::from(vec![4, 5, 6]));
        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![dates, n])?;
        let right = TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap();
        let on = vec![(
            Arc::new(Column::new_with_schema("date", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("date", &right.schema()).unwrap()) as _,
        )];

        let join = join(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
        )?;

        let task_ctx = Arc::new(TaskContext::default());
        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +------------+---+------------+---+
            | date       | n | date       | n |
            +------------+---+------------+---+
            | 2022-04-26 | 2 | 2022-04-26 | 4 |
            | 2022-04-26 | 2 | 2022-04-26 | 5 |
            | 2022-04-27 | 3 | 2022-04-27 | 6 |
            +------------+---+------------+---+
            ");
        }

        Ok(())
    }

    #[tokio::test]
    async fn join_with_error_right() {
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 7]),
            ("c1", &vec![7, 8, 9]),
        );

        // right input stream returns one good batch and then one error.
        // The error should be returned.
        let err = exec_err!("bad data error");
        let right = build_table_i32(("a2", &vec![]), ("b1", &vec![]), ("c2", &vec![]));

        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema()).unwrap()) as _,
        )];
        let schema = right.schema();
        let right = build_table_i32(("a2", &vec![]), ("b1", &vec![]), ("c2", &vec![]));
        let right_input = Arc::new(MockExec::new(vec![Ok(right), err], schema));

        let join_types = vec![
            JoinType::Inner,
            JoinType::Left,
            JoinType::Right,
            JoinType::Full,
            JoinType::LeftSemi,
            JoinType::LeftAnti,
            JoinType::RightSemi,
            JoinType::RightAnti,
        ];

        for join_type in join_types {
            let join = join(
                Arc::clone(&left),
                Arc::clone(&right_input) as Arc<dyn ExecutionPlan>,
                on.clone(),
                &join_type,
                NullEquality::NullEqualsNothing,
            )
            .unwrap();
            let task_ctx = Arc::new(TaskContext::default());

            let stream = join.execute(0, task_ctx).unwrap();

            // Expect that an error is returned
            let result_string = common::collect(stream).await.unwrap_err().to_string();
            assert!(
                result_string.contains("bad data error"),
                "actual: {result_string}"
            );
        }
    }

    #[tokio::test]
    async fn join_does_not_consume_probe_when_empty_build_fixes_output() {
        assert_empty_build_probe_behavior(
            &[
                JoinType::Inner,
                JoinType::Left,
                JoinType::LeftSemi,
                JoinType::LeftAnti,
                JoinType::LeftMark,
                JoinType::RightSemi,
            ],
            false,
            false,
        )
        .await;
    }

    #[tokio::test]
    async fn join_does_not_consume_probe_when_empty_build_fixes_output_with_filter() {
        assert_empty_build_probe_behavior(
            &[
                JoinType::Inner,
                JoinType::Left,
                JoinType::LeftSemi,
                JoinType::LeftAnti,
                JoinType::LeftMark,
                JoinType::RightSemi,
            ],
            false,
            true,
        )
        .await;
    }

    #[tokio::test]
    async fn join_still_consumes_probe_when_empty_build_needs_probe_rows() {
        assert_empty_build_probe_behavior(
            &[
                JoinType::Right,
                JoinType::Full,
                JoinType::RightAnti,
                JoinType::RightMark,
            ],
            true,
            false,
        )
        .await;
    }

    #[tokio::test]
    async fn join_still_consumes_probe_when_empty_build_needs_probe_rows_with_filter() {
        assert_empty_build_probe_behavior(
            &[
                JoinType::Right,
                JoinType::Full,
                JoinType::RightAnti,
                JoinType::RightMark,
            ],
            true,
            true,
        )
        .await;
    }

    #[tokio::test]
    async fn join_split_batch() {
        let left = build_table(
            ("a1", &vec![1, 2, 3, 4]),
            ("b1", &vec![1, 1, 1, 1]),
            ("c1", &vec![0, 0, 0, 0]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30, 40, 50]),
            ("b2", &vec![1, 1, 1, 1, 1]),
            ("c2", &vec![0, 0, 0, 0, 0]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
        )];

        let join_types = vec![
            JoinType::Inner,
            JoinType::Left,
            JoinType::Right,
            JoinType::Full,
            JoinType::RightSemi,
            JoinType::RightAnti,
            JoinType::LeftSemi,
            JoinType::LeftAnti,
        ];
        let expected_resultset_records = 20;
        let common_result = [
            "+----+----+----+----+----+----+",
            "| a1 | b1 | c1 | a2 | b2 | c2 |",
            "+----+----+----+----+----+----+",
            "| 1  | 1  | 0  | 10 | 1  | 0  |",
            "| 2  | 1  | 0  | 10 | 1  | 0  |",
            "| 3  | 1  | 0  | 10 | 1  | 0  |",
            "| 4  | 1  | 0  | 10 | 1  | 0  |",
            "| 1  | 1  | 0  | 20 | 1  | 0  |",
            "| 2  | 1  | 0  | 20 | 1  | 0  |",
            "| 3  | 1  | 0  | 20 | 1  | 0  |",
            "| 4  | 1  | 0  | 20 | 1  | 0  |",
            "| 1  | 1  | 0  | 30 | 1  | 0  |",
            "| 2  | 1  | 0  | 30 | 1  | 0  |",
            "| 3  | 1  | 0  | 30 | 1  | 0  |",
            "| 4  | 1  | 0  | 30 | 1  | 0  |",
            "| 1  | 1  | 0  | 40 | 1  | 0  |",
            "| 2  | 1  | 0  | 40 | 1  | 0  |",
            "| 3  | 1  | 0  | 40 | 1  | 0  |",
            "| 4  | 1  | 0  | 40 | 1  | 0  |",
            "| 1  | 1  | 0  | 50 | 1  | 0  |",
            "| 2  | 1  | 0  | 50 | 1  | 0  |",
            "| 3  | 1  | 0  | 50 | 1  | 0  |",
            "| 4  | 1  | 0  | 50 | 1  | 0  |",
            "+----+----+----+----+----+----+",
        ];
        let left_batch = [
            "+----+----+----+",
            "| a1 | b1 | c1 |",
            "+----+----+----+",
            "| 1  | 1  | 0  |",
            "| 2  | 1  | 0  |",
            "| 3  | 1  | 0  |",
            "| 4  | 1  | 0  |",
            "+----+----+----+",
        ];
        let right_batch = [
            "+----+----+----+",
            "| a2 | b2 | c2 |",
            "+----+----+----+",
            "| 10 | 1  | 0  |",
            "| 20 | 1  | 0  |",
            "| 30 | 1  | 0  |",
            "| 40 | 1  | 0  |",
            "| 50 | 1  | 0  |",
            "+----+----+----+",
        ];
        let right_empty = [
            "+----+----+----+",
            "| a2 | b2 | c2 |",
            "+----+----+----+",
            "+----+----+----+",
        ];
        let left_empty = [
            "+----+----+----+",
            "| a1 | b1 | c1 |",
            "+----+----+----+",
            "+----+----+----+",
        ];

        // validation of partial join results output for different batch_size setting
        for join_type in join_types {
            for batch_size in (1..21).rev() {
                let task_ctx = prepare_task_ctx(batch_size, true);

                let join = join(
                    Arc::clone(&left),
                    Arc::clone(&right),
                    on.clone(),
                    &join_type,
                    NullEquality::NullEqualsNothing,
                )
                .unwrap();

                let stream = join.execute(0, task_ctx).unwrap();
                let batches = common::collect(stream).await.unwrap();

                // For inner/right join expected batch count equals dev_ceil result,
                // as there is no need to append non-joined build side data.
                // For other join types it'll be div_ceil + 1 -- for additional batch
                // containing not visited build side rows (empty in this test case).
                let expected_batch_count = match join_type {
                    JoinType::Inner
                    | JoinType::Right
                    | JoinType::RightSemi
                    | JoinType::RightAnti => {
                        div_ceil(expected_resultset_records, batch_size)
                    }
                    _ => div_ceil(expected_resultset_records, batch_size) + 1,
                };
                // With batch coalescing, we may have fewer batches than expected
                assert!(
                    batches.len() <= expected_batch_count,
                    "expected at most {expected_batch_count} output batches for {join_type} join with batch_size = {batch_size}, got {}",
                    batches.len()
                );

                let expected = match join_type {
                    JoinType::RightSemi => right_batch.to_vec(),
                    JoinType::RightAnti => right_empty.to_vec(),
                    JoinType::LeftSemi => left_batch.to_vec(),
                    JoinType::LeftAnti => left_empty.to_vec(),
                    _ => common_result.to_vec(),
                };
                // For anti joins with empty results, we may get zero batches
                // (with coalescing) instead of one empty batch with schema
                if batches.is_empty() {
                    // Verify this is an expected empty result case
                    assert!(
                        matches!(join_type, JoinType::RightAnti | JoinType::LeftAnti),
                        "Unexpected empty result for {join_type} join"
                    );
                } else {
                    assert_batches_eq!(expected, &batches);
                }
            }
        }
    }

    #[tokio::test]
    async fn single_partition_join_overallocation() -> Result<()> {
        let left = build_table(
            ("a1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
            ("b1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
            ("c1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
        );
        let right = build_table(
            ("a2", &vec![10, 11]),
            ("b2", &vec![12, 13]),
            ("c2", &vec![14, 15]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("a1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema()).unwrap()) as _,
        )];

        let join_types = vec![
            JoinType::Inner,
            JoinType::Left,
            JoinType::Right,
            JoinType::Full,
            JoinType::LeftSemi,
            JoinType::LeftAnti,
            JoinType::RightSemi,
            JoinType::RightAnti,
            JoinType::LeftMark,
            JoinType::RightMark,
        ];

        for join_type in join_types {
            let runtime = RuntimeEnvBuilder::new()
                .with_memory_limit(100, 1.0)
                .build_arc()?;
            let task_ctx = TaskContext::default().with_runtime(runtime);
            let task_ctx = Arc::new(task_ctx);

            let join = join(
                Arc::clone(&left),
                Arc::clone(&right),
                on.clone(),
                &join_type,
                NullEquality::NullEqualsNothing,
            )?;

            let stream = join.execute(0, task_ctx)?;
            let err = common::collect(stream).await.unwrap_err();

            // Asserting that operator-level reservation attempting to overallocate
            assert_contains!(
                err.to_string(),
                "Resources exhausted: Additional allocation failed for HashJoinInput with top memory consumers (across reservations) as:\n  HashJoinInput"
            );

            assert_contains!(
                err.to_string(),
                "Failed to allocate additional 120.0 B for HashJoinInput"
            );
        }

        Ok(())
    }

    #[tokio::test]
    async fn build_side_sliced_batches_memory_accounting() -> Result<()> {
        // The build side emits zero-copy slices of one large batch, as e.g. an
        // aggregate emitting its output in batch_size chunks does. The buffers
        // shared by the slices must be reserved once in total, not once per
        // slice: per-slice accounting reserves number_of_slices x parent size
        // and aborts queries that fit in memory with room to spare.
        let n = 4096;
        let v: Vec<i32> = (0..n).collect();
        let parent = build_table_i32(("a1", &v), ("b1", &v), ("c1", &v));
        let slices: Vec<RecordBatch> =
            (0..16).map(|i| parent.slice(i * 256, 256)).collect();
        let left =
            TestMemoryExec::try_new_exec(&[slices], parent.schema(), None).unwrap();

        let right_batch = build_table_i32(
            ("a2", &vec![10, 11]),
            ("b2", &vec![0, 1]),
            ("c2", &vec![14, 15]),
        );
        let right = TestMemoryExec::try_new_exec(
            &[vec![right_batch.clone()]],
            right_batch.schema(),
            None,
        )
        .unwrap();
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &parent.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right_batch.schema())?) as _,
        )];

        // Enough for the parent batch (~48KB) plus the join hash table, but far
        // below the ~768KB that per-slice accounting would reserve
        let runtime = RuntimeEnvBuilder::new()
            .with_memory_limit(400_000, 1.0)
            .build_arc()?;
        let task_ctx = TaskContext::default().with_runtime(runtime);
        let task_ctx = Arc::new(task_ctx);

        let join = join(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;
        let num_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(num_rows, 2);

        Ok(())
    }

    #[tokio::test]
    async fn partitioned_join_overallocation() -> Result<()> {
        // Prepare partitioned inputs for HashJoinExec
        // No need to adjust partitioning, as execution should fail with `Resources exhausted` error
        let left_batch = build_table_i32(
            ("a1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
            ("b1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
            ("c1", &vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 0]),
        );
        let left = TestMemoryExec::try_new_exec(
            &[vec![left_batch.clone()], vec![left_batch.clone()]],
            left_batch.schema(),
            None,
        )
        .unwrap();
        let right_batch = build_table_i32(
            ("a2", &vec![10, 11]),
            ("b2", &vec![12, 13]),
            ("c2", &vec![14, 15]),
        );
        let right = TestMemoryExec::try_new_exec(
            &[vec![right_batch.clone()], vec![right_batch.clone()]],
            right_batch.schema(),
            None,
        )
        .unwrap();
        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left_batch.schema())?) as _,
            Arc::new(Column::new_with_schema("b2", &right_batch.schema())?) as _,
        )];

        let join_types = vec![
            JoinType::Inner,
            JoinType::Left,
            JoinType::Right,
            JoinType::Full,
            JoinType::LeftSemi,
            JoinType::LeftAnti,
            JoinType::RightSemi,
            JoinType::RightAnti,
        ];

        for join_type in join_types {
            let runtime = RuntimeEnvBuilder::new()
                .with_memory_limit(100, 1.0)
                .build_arc()?;
            let session_config = SessionConfig::default().with_batch_size(50);
            let task_ctx = TaskContext::default()
                .with_session_config(session_config)
                .with_runtime(runtime);
            let task_ctx = Arc::new(task_ctx);

            let join = HashJoinExec::try_new(
                Arc::clone(&left) as Arc<dyn ExecutionPlan>,
                Arc::clone(&right) as Arc<dyn ExecutionPlan>,
                on.clone(),
                None,
                &join_type,
                None,
                PartitionMode::Partitioned,
                NullEquality::NullEqualsNothing,
                false,
            )?;

            let stream = join.execute(1, task_ctx)?;
            let err = common::collect(stream).await.unwrap_err();

            // Asserting that stream-level reservation attempting to overallocate
            assert_contains!(
                err.to_string(),
                "Resources exhausted: Additional allocation failed for HashJoinInput[1] with top memory consumers (across reservations) as:\n  HashJoinInput[1]"
            );

            assert_contains!(
                err.to_string(),
                "Failed to allocate additional 120.0 B for HashJoinInput[1]"
            );
        }

        Ok(())
    }

    /// Build side batches of `num_batches` x `num_rows` rows with distinct
    /// buffers: an Int32 key, a Utf8, a Utf8View and a BinaryView payload.
    fn concat_test_batches(num_batches: usize, num_rows: usize) -> Vec<RecordBatch> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("k", DataType::Int32, false),
            Field::new("s", DataType::Utf8, true),
            Field::new("v", DataType::Utf8View, true),
            Field::new("bv", DataType::BinaryView, true),
        ]));
        (0..num_batches)
            .map(|b| {
                let start = (b * num_rows) as i32;
                let keys = Int32Array::from_iter_values(start..start + num_rows as i32);
                let strings = (0..num_rows)
                    .map(|i| (i % 7 != 0).then(|| format!("string-{b}-{i}")))
                    .collect::<StringArray>();
                let views = (0..num_rows)
                    .map(|i| {
                        (i % 5 != 0).then(|| format!("a long string view value {b}-{i}"))
                    })
                    .collect::<StringViewArray>();
                let binary_views = (0..num_rows)
                    .map(|i| {
                        (i % 3 != 0).then(|| format!("a long binary view value {b}-{i}"))
                    })
                    .collect::<BinaryViewArray>();
                RecordBatch::try_new(
                    Arc::clone(&schema),
                    vec![
                        Arc::new(keys),
                        Arc::new(strings),
                        Arc::new(views),
                        Arc::new(binary_views),
                    ],
                )
                .unwrap()
            })
            .collect()
    }

    /// Reserves `batches` the way `collect_left_input` does.
    fn reserve_inputs(
        batches: &[RecordBatch],
        pool: &Arc<dyn MemoryPool>,
    ) -> Result<(MemoryReservation, usize)> {
        let reservation = MemoryConsumer::new("HashJoinInput").register(pool);
        let mut counter = RecordBatchMemoryCounter::new();
        for batch in batches {
            reservation.try_grow(counter.count_batch(batch))?;
        }
        Ok((reservation, counter.memory_usage()))
    }

    #[test]
    fn concat_build_batches_matches_concat_batches() -> Result<()> {
        let batches = concat_test_batches(4, 100);
        let schema = batches[0].schema();
        let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());

        let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
        let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
        let expected = concat_batches(&schema, batches.iter())?;
        let batch = concat_build_batches(
            &schema,
            &mut batches.clone(),
            inputs_reserved,
            &mut reservation,
            &metrics,
        )?;
        assert_eq!(batch, expected);
        Ok(())
    }

    #[test]
    fn concat_build_batches_reserves_copy() -> Result<()> {
        let mut batches = concat_test_batches(4, 1000);
        let schema = batches[0].schema();
        let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
        let inputs: usize = batches.iter().map(get_record_batch_memory_size).sum();

        // The inputs fit, but not together with their concatenated copy
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(inputs * 5 / 4));
        let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
        assert_eq!(inputs_reserved, inputs);
        let original = batches.clone();
        let err = concat_build_batches(
            &schema,
            &mut batches,
            inputs_reserved,
            &mut reservation,
            &metrics,
        )
        .unwrap_err();
        assert_contains!(err.to_string(), "Resources exhausted");
        assert_eq!(batches, original);
        drop(original);
        drop(reservation);

        // With room for the copy, the reservation ends up at what is retained
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(inputs * 2));
        let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
        let batch = concat_build_batches(
            &schema,
            &mut batches,
            inputs_reserved,
            &mut reservation,
            &metrics,
        )?;
        assert_eq!(reservation.size(), get_record_batch_memory_size(&batch));
        assert_eq!(pool.reserved(), reservation.size());
        assert_eq!(batches, vec![batch]);
        Ok(())
    }

    /// Concatenating a single batch is zero-copy, so nothing more is reserved.
    #[test]
    fn concat_build_batches_single_batch_not_reserved_twice() -> Result<()> {
        let mut batches = concat_test_batches(1, 1000);
        let schema = batches[0].schema();
        let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
        let inputs = get_record_batch_memory_size(&batches[0]);

        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(inputs));
        let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
        let batch = concat_build_batches(
            &schema,
            &mut batches,
            inputs_reserved,
            &mut reservation,
            &metrics,
        )?;
        assert_eq!(batch.num_rows(), 1000);
        assert_eq!(reservation.size(), inputs);
        Ok(())
    }

    /// Only the views of a view array are copied, its data buffers stay shared.
    #[rstest]
    fn concat_build_batches_view_data_not_reserved_twice(
        #[values("v", "bv")] column: &str,
    ) -> Result<()> {
        let batches = concat_test_batches(4, 1000);
        let column = batches[0].schema().index_of(column)?;
        let mut batches = batches
            .into_iter()
            .map(|batch| batch.project(&[column]))
            .collect::<Result<Vec<_>, _>>()?;
        let schema = batches[0].schema();
        let metrics = BuildProbeJoinMetrics::new(0, &ExecutionPlanMetricsSet::new());
        let inputs: usize = batches.iter().map(get_record_batch_memory_size).sum();
        let views = 4 * 1000 * size_of::<u128>();
        assert!(inputs > 2 * views);

        let pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(inputs + views * 5 / 4));
        let (mut reservation, inputs_reserved) = reserve_inputs(&batches, &pool)?;
        let batch = concat_build_batches(
            &schema,
            &mut batches,
            inputs_reserved,
            &mut reservation,
            &metrics,
        )?;
        assert_eq!(reservation.size(), get_record_batch_memory_size(&batch));
        Ok(())
    }

    /// The build side is concatenated into a single batch, and that copy must
    /// be visible to the memory pool while the input batches are still alive.
    #[rstest]
    #[tokio::test]
    async fn join_build_concat_is_reserved(
        #[values(PartitionMode::CollectLeft, PartitionMode::Partitioned)]
        mode: PartitionMode,
        #[values(false, true)] use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let num_rows = 4000;
        let values = (0..num_rows).collect::<Vec<i32>>();
        let batches = (0..4)
            .map(|_| build_table_i32(("a1", &values), ("b1", &values), ("c1", &values)))
            .collect::<Vec<_>>();
        let inputs: usize = batches.iter().map(get_record_batch_memory_size).sum();
        let left_schema = batches[0].schema();
        let right = build_table(
            ("a2", &vec![10, 11]),
            ("b2", &vec![12, 13]),
            ("c2", &vec![14, 15]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("a1", &left_schema)?) as _,
            Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
        )];

        // Reserved on top of the inputs and their copy
        let build_rows = batches.len() * num_rows as usize;
        let map = if use_perfect_hash_join_as_possible {
            ArrayMap::estimate_memory_size(0, num_rows as u64 - 1, build_rows)
        } else {
            estimate_memory_size::<(u32, u64)>(build_rows, size_of::<JoinHashMapU32>())?
                + build_rows * size_of::<u32>()
        };

        for (limit, fits) in [(map + inputs * 3 / 2, false), (map + inputs * 3, true)] {
            let left = TestMemoryExec::try_new_exec(
                std::slice::from_ref(&batches),
                Arc::clone(&left_schema),
                None,
            )?;
            let join = HashJoinExec::try_new(
                left,
                Arc::clone(&right),
                on.clone(),
                None,
                &JoinType::Inner,
                None,
                mode,
                NullEquality::NullEqualsNothing,
                false,
            )?;

            let runtime = RuntimeEnvBuilder::new()
                .with_memory_limit(limit, 1.0)
                .build_arc()?;
            let task_ctx = prepare_task_ctx(8192, use_perfect_hash_join_as_possible);
            let task_ctx = Arc::new(
                TaskContext::default()
                    .with_session_config(task_ctx.session_config().clone())
                    .with_runtime(runtime),
            );

            let result = common::collect(join.execute(0, task_ctx)?).await;
            if fits {
                result?;
            } else {
                assert_contains!(
                    result.unwrap_err().to_string(),
                    "Resources exhausted: Additional allocation failed for HashJoinInput"
                );
            }
        }
        Ok(())
    }

    /// Join keys that are not plain columns evaluate to new arrays, which are
    /// kept for the whole join and must be reserved.
    #[rstest]
    #[tokio::test]
    async fn join_build_key_arrays_are_reserved(
        #[values(false, true)] use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let num_rows = 16000;
        let values = (0..num_rows).collect::<Vec<i32>>();
        // A single build batch, so that there is no concatenated copy
        let batch = build_table_i32(("a1", &values), ("b1", &values), ("c1", &values));
        let inputs = get_record_batch_memory_size(&batch);
        let keys = inputs / 3;
        let left_schema = batch.schema();
        let right = build_table(
            ("a2", &vec![10, 11]),
            ("b2", &vec![12, 13]),
            ("c2", &vec![14, 15]),
        );

        let map = if use_perfect_hash_join_as_possible {
            ArrayMap::estimate_memory_size(1, num_rows as u64, num_rows as usize)
        } else {
            estimate_memory_size::<(u32, u64)>(
                num_rows as usize,
                size_of::<JoinHashMapU32>(),
            )? + num_rows as usize * size_of::<u32>()
        };

        for (computed_key, limit, fits) in [
            (false, inputs + map + keys / 2, true),
            (true, inputs + map + keys / 2, false),
            (true, inputs + map + keys * 2, true),
        ] {
            let column = Arc::new(Column::new_with_schema("a1", &left_schema)?) as _;
            let left_key: PhysicalExprRef = if computed_key {
                Arc::new(BinaryExpr::new(
                    column,
                    Operator::Plus,
                    Arc::new(Literal::new(ScalarValue::Int32(Some(1)))),
                ))
            } else {
                column
            };
            let on = vec![(
                left_key,
                Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
            )];
            let left = TestMemoryExec::try_new_exec(
                &[vec![batch.clone()]],
                Arc::clone(&left_schema),
                None,
            )?;
            let join = HashJoinExec::try_new(
                left,
                Arc::clone(&right),
                on,
                None,
                &JoinType::Inner,
                None,
                PartitionMode::CollectLeft,
                NullEquality::NullEqualsNothing,
                false,
            )?;

            let runtime = RuntimeEnvBuilder::new()
                .with_memory_limit(limit, 1.0)
                .build_arc()?;
            let task_ctx = prepare_task_ctx(8192, use_perfect_hash_join_as_possible);
            let task_ctx = Arc::new(
                TaskContext::default()
                    .with_session_config(task_ctx.session_config().clone())
                    .with_runtime(runtime),
            );

            let result = common::collect(join.execute(0, task_ctx)?).await;
            if fits {
                result?;
            } else {
                assert_contains!(
                    result.unwrap_err().to_string(),
                    "Resources exhausted: Additional allocation failed for HashJoinInput"
                );
            }
        }
        Ok(())
    }

    fn build_table_struct(
        struct_name: &str,
        field_name_and_values: (&str, &Vec<Option<i32>>),
        nulls: Option<NullBuffer>,
    ) -> Arc<dyn ExecutionPlan> {
        let (field_name, values) = field_name_and_values;
        let inner_fields = vec![Field::new(field_name, DataType::Int32, true)];
        let schema = Schema::new(vec![Field::new(
            struct_name,
            DataType::Struct(inner_fields.clone().into()),
            nulls.is_some(),
        )]);

        let batch = RecordBatch::try_new(
            Arc::new(schema),
            vec![Arc::new(StructArray::new(
                inner_fields.into(),
                vec![Arc::new(Int32Array::from(values.clone()))],
                nulls,
            ))],
        )
        .unwrap();
        let schema_ref = batch.schema();
        TestMemoryExec::try_new_exec(&[vec![batch]], schema_ref, None).unwrap()
    }

    #[tokio::test]
    #[expect(
        clippy::literal_string_with_formatting_args,
        reason = "The braces are part of the expected struct output, not format args"
    )]
    async fn join_on_struct() -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        let left =
            build_table_struct("n1", ("a", &vec![None, Some(1), Some(2), Some(3)]), None);
        let right =
            build_table_struct("n2", ("a", &vec![None, Some(1), Some(2), Some(4)]), None);
        let on = vec![(
            Arc::new(Column::new_with_schema("n1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("n2", &right.schema())?) as _,
        )];

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["n1", "n2"]);

        allow_duplicates! {
            assert_snapshot!(batches_to_string(&batches), @r"
            +--------+--------+
            | n1     | n2     |
            +--------+--------+
            | {a: }  | {a: }  |
            | {a: 1} | {a: 1} |
            | {a: 2} | {a: 2} |
            +--------+--------+
            ");
        }

        assert_join_metrics!(metrics, 3);

        Ok(())
    }

    #[tokio::test]
    async fn join_on_struct_with_nulls() -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        let left =
            build_table_struct("n1", ("a", &vec![None]), Some(NullBuffer::new_null(1)));
        let right =
            build_table_struct("n2", ("a", &vec![None]), Some(NullBuffer::new_null(1)));
        let on = vec![(
            Arc::new(Column::new_with_schema("n1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("n2", &right.schema())?) as _,
        )];

        let (_, batches_null_eq, metrics) = join_collect(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            &JoinType::Inner,
            NullEquality::NullEqualsNull,
            Arc::clone(&task_ctx),
        )
        .await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches_null_eq), @r"
            +----+----+
            | n1 | n2 |
            +----+----+
            |    |    |
            +----+----+
            ");
        }

        assert_join_metrics!(metrics, 1);

        let (_, batches_null_neq, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_join_metrics!(metrics, 0);

        // With batch coalescing, empty results may not emit any batches
        // Check that either we have no batches, or an empty batch with proper schema
        if batches_null_neq.is_empty() {
            // This is fine - no output rows
        } else {
            let expected_null_neq =
                ["+----+----+", "| n1 | n2 |", "+----+----+", "+----+----+"];
            assert_batches_eq!(expected_null_neq, &batches_null_neq);
        }

        Ok(())
    }

    /// Returns the column names on the schema
    fn columns(schema: &Schema) -> Vec<String> {
        schema.fields().iter().map(|f| f.name().clone()).collect()
    }

    /// This test verifies that the dynamic filter is marked as complete after HashJoinExec finishes building the hash table.
    #[tokio::test]
    async fn test_hash_join_marks_filter_complete() -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        let left = build_table(
            ("a1", &vec![1, 2, 3]),
            ("b1", &vec![4, 5, 6]),
            ("c1", &vec![7, 8, 9]),
        );
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (join, dynamic_filter) =
            hash_join_with_dynamic_filter(left, right, on, JoinType::Inner)?;

        // Execute the join
        let stream = join.execute(0, task_ctx)?;
        let _batches = common::collect(stream).await?;

        // After the join completes, the dynamic filter should be marked as complete
        // wait_complete() should return immediately
        dynamic_filter.wait_complete().await;

        Ok(())
    }

    /// This test verifies that the dynamic filter is marked as complete even when the build side is empty.
    #[tokio::test]
    async fn test_hash_join_marks_filter_complete_empty_build_side() -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        // Empty left side (build side)
        let left = build_table(("a1", &vec![]), ("b1", &vec![]), ("c1", &vec![]));
        let right = build_table(
            ("a2", &vec![10, 20, 30]),
            ("b1", &vec![4, 5, 6]),
            ("c2", &vec![70, 80, 90]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("b1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("b1", &right.schema())?) as _,
        )];

        let (join, dynamic_filter) =
            hash_join_with_dynamic_filter(left, right, on, JoinType::Inner)?;

        // Execute the join
        let stream = join.execute(0, task_ctx)?;
        let _batches = common::collect(stream).await?;

        // Even with empty build side, the dynamic filter should be marked as complete
        // wait_complete() should return immediately
        dynamic_filter.wait_complete().await;

        Ok(())
    }

    #[tokio::test]
    async fn test_partitioned_dynamic_filter_reports_empty_canceled_partitions()
    -> Result<()> {
        let mut session_config = SessionConfig::default();
        session_config
            .options_mut()
            .optimizer
            .enable_dynamic_filter_pushdown = true;
        let task_ctx =
            Arc::new(TaskContext::default().with_session_config(session_config));

        let child_left_schema = Arc::new(Schema::new(vec![
            Field::new("child_left_payload", DataType::Int32, false),
            Field::new("child_key", DataType::Int32, false),
            Field::new("child_left_extra", DataType::Int32, false),
        ]));
        let child_right_schema = Arc::new(Schema::new(vec![
            Field::new("child_right_payload", DataType::Int32, false),
            Field::new("child_right_key", DataType::Int32, false),
            Field::new("child_right_extra", DataType::Int32, false),
        ]));
        let parent_left_schema = Arc::new(Schema::new(vec![
            Field::new("parent_payload", DataType::Int32, false),
            Field::new("parent_key", DataType::Int32, false),
            Field::new("parent_extra", DataType::Int32, false),
        ]));

        let child_left: Arc<dyn ExecutionPlan> = TestMemoryExec::try_new_exec(
            &[
                vec![build_table_i32(
                    ("child_left_payload", &vec![10]),
                    ("child_key", &vec![0]),
                    ("child_left_extra", &vec![100]),
                )],
                vec![build_table_i32(
                    ("child_left_payload", &vec![11]),
                    ("child_key", &vec![1]),
                    ("child_left_extra", &vec![101]),
                )],
                vec![build_table_i32(
                    ("child_left_payload", &vec![12]),
                    ("child_key", &vec![2]),
                    ("child_left_extra", &vec![102]),
                )],
                vec![build_table_i32(
                    ("child_left_payload", &vec![13]),
                    ("child_key", &vec![3]),
                    ("child_left_extra", &vec![103]),
                )],
            ],
            Arc::clone(&child_left_schema),
            None,
        )?;
        let child_right: Arc<dyn ExecutionPlan> = TestMemoryExec::try_new_exec(
            &[
                vec![build_table_i32(
                    ("child_right_payload", &vec![20]),
                    ("child_right_key", &vec![0]),
                    ("child_right_extra", &vec![200]),
                )],
                vec![build_table_i32(
                    ("child_right_payload", &vec![21]),
                    ("child_right_key", &vec![1]),
                    ("child_right_extra", &vec![201]),
                )],
                vec![build_table_i32(
                    ("child_right_payload", &vec![22]),
                    ("child_right_key", &vec![2]),
                    ("child_right_extra", &vec![202]),
                )],
                vec![build_table_i32(
                    ("child_right_payload", &vec![23]),
                    ("child_right_key", &vec![3]),
                    ("child_right_extra", &vec![203]),
                )],
            ],
            Arc::clone(&child_right_schema),
            None,
        )?;
        let parent_left: Arc<dyn ExecutionPlan> = TestMemoryExec::try_new_exec(
            &[
                vec![build_table_i32(
                    ("parent_payload", &vec![30]),
                    ("parent_key", &vec![0]),
                    ("parent_extra", &vec![300]),
                )],
                vec![RecordBatch::new_empty(Arc::clone(&parent_left_schema))],
                vec![build_table_i32(
                    ("parent_payload", &vec![32]),
                    ("parent_key", &vec![2]),
                    ("parent_extra", &vec![302]),
                )],
                vec![RecordBatch::new_empty(Arc::clone(&parent_left_schema))],
            ],
            Arc::clone(&parent_left_schema),
            None,
        )?;

        let child_on = vec![(
            Arc::new(Column::new_with_schema("child_key", &child_left_schema)?) as _,
            Arc::new(Column::new_with_schema(
                "child_right_key",
                &child_right_schema,
            )?) as _,
        )];
        let (child_join, _child_dynamic_filter) = hash_join_with_dynamic_filter_and_mode(
            child_left,
            child_right,
            child_on,
            JoinType::Inner,
            PartitionMode::Partitioned,
        )?;
        let child_join: Arc<dyn ExecutionPlan> = Arc::new(child_join);

        let parent_on = vec![(
            Arc::new(Column::new_with_schema("parent_key", &parent_left_schema)?) as _,
            Arc::new(Column::new_with_schema("child_key", &child_join.schema())?) as _,
        )];
        let parent_join = HashJoinExec::try_new(
            parent_left,
            child_join,
            parent_on,
            None,
            &JoinType::RightSemi,
            None,
            PartitionMode::Partitioned,
            NullEquality::NullEqualsNothing,
            false,
        )?;

        let batches = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            crate::execution_plan::collect(Arc::new(parent_join), task_ctx),
        )
        .await
        .expect("partitioned right-semi join should not hang")?;

        assert_batches_sorted_eq!(
            [
                "+--------------------+-----------+------------------+---------------------+-----------------+-------------------+",
                "| child_left_payload | child_key | child_left_extra | child_right_payload | child_right_key | child_right_extra |",
                "+--------------------+-----------+------------------+---------------------+-----------------+-------------------+",
                "| 10                 | 0         | 100              | 20                  | 0               | 200               |",
                "| 12                 | 2         | 102              | 22                  | 2               | 202               |",
                "+--------------------+-----------+------------------+---------------------+-----------------+-------------------+",
            ],
            &batches
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_hash_join_skips_probe_on_empty_build_after_partition_bounds_report()
    -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());
        let (left, right, on) = empty_build_with_probe_error_inputs();

        // Keep an extra consumer reference so execute() enables dynamic filter pushdown
        // and enters the WaitPartitionBoundsReport path before deciding whether to poll
        // the probe side.
        let (join, dynamic_filter) =
            hash_join_with_dynamic_filter(left, right, on, JoinType::Inner)?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;
        assert!(batches.is_empty());

        dynamic_filter.wait_complete().await;

        Ok(())
    }

    #[tokio::test]
    async fn test_perfect_hash_join_with_negative_numbers() -> Result<()> {
        let task_ctx = prepare_task_ctx(8192, true);
        let (left_schema, right_schema, on) = build_schema_and_on()?;

        let left_batch = RecordBatch::try_new(
            Arc::clone(&left_schema),
            vec![
                Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef,
                Arc::new(Int32Array::from(vec![-1, 0, 1])) as ArrayRef,
            ],
        )?;
        let left = TestMemoryExec::try_new_exec(&[vec![left_batch]], left_schema, None)?;

        let right_batch = RecordBatch::try_new(
            Arc::clone(&right_schema),
            vec![
                Arc::new(Int32Array::from(vec![10, 20, 30, 40])) as ArrayRef,
                Arc::new(Int32Array::from(vec![1, -1, 0, 2])) as ArrayRef,
            ],
        )?;
        let right =
            TestMemoryExec::try_new_exec(&[vec![right_batch]], right_schema, None)?;

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "a2", "b1"]);

        assert_batches_sorted_eq!(
            [
                "+----+----+----+----+",
                "| a1 | b1 | a2 | b1 |",
                "+----+----+----+----+",
                "| 1  | -1 | 20 | -1 |",
                "| 2  | 0  | 30 | 0  |",
                "| 3  | 1  | 10 | 1  |",
                "+----+----+----+----+",
            ],
            &batches
        );

        assert_phj_used(&metrics, true);

        Ok(())
    }

    #[tokio::test]
    async fn test_perfect_hash_join_overflow_full_int64_range() -> Result<()> {
        let task_ctx = prepare_task_ctx(8192, true);
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, true)]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int64Array::from(vec![i64::MIN, i64::MAX]))],
        )?;
        let left = TestMemoryExec::try_new_exec(
            &[vec![batch.clone()]],
            Arc::clone(&schema),
            None,
        )?;
        let right = TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)?;
        let on: JoinOn = vec![(
            Arc::new(Column::new_with_schema("a", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("a", &right.schema())?) as _,
        )];
        let (_columns, batches, _metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, 2);
        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_phj_null_equals_null_build_no_nulls_probe_has_nulls(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let (left_schema, right_schema, on) = build_schema_and_on()?;

        let left_batch = RecordBatch::try_new(
            Arc::clone(&left_schema),
            vec![
                Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef,
                Arc::new(Int32Array::from(vec![10, 20])) as ArrayRef,
            ],
        )?;
        let left = TestMemoryExec::try_new_exec(&[vec![left_batch]], left_schema, None)?;

        let right_batch = RecordBatch::try_new(
            Arc::clone(&right_schema),
            vec![
                Arc::new(Int32Array::from(vec![3, 4])) as ArrayRef,
                Arc::new(Int32Array::from(vec![Some(10), None])) as ArrayRef,
            ],
        )?;
        let right =
            TestMemoryExec::try_new_exec(&[vec![right_batch]], right_schema, None)?;

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNull,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "a2", "b1"]);
        assert_batches_sorted_eq!(
            [
                "+----+----+----+----+",
                "| a1 | b1 | a2 | b1 |",
                "+----+----+----+----+",
                "| 1  | 10 | 3  | 10 |",
                "+----+----+----+----+",
            ],
            &batches
        );

        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_phj_null_equals_nothing_build_probe_all_have_nulls(
        batch_size: usize,
        use_perfect_hash_join_as_possible: bool,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, use_perfect_hash_join_as_possible);
        let (left_schema, right_schema, on) = build_schema_and_on()?;

        let left_batch = RecordBatch::try_new(
            Arc::clone(&left_schema),
            vec![
                Arc::new(Int32Array::from(vec![Some(1), Some(2)])) as ArrayRef,
                Arc::new(Int32Array::from(vec![Some(10), None])) as ArrayRef,
            ],
        )?;
        let left = TestMemoryExec::try_new_exec(&[vec![left_batch]], left_schema, None)?;

        let right_batch = RecordBatch::try_new(
            Arc::clone(&right_schema),
            vec![
                Arc::new(Int32Array::from(vec![Some(3), Some(4)])) as ArrayRef,
                Arc::new(Int32Array::from(vec![Some(10), None])) as ArrayRef,
            ],
        )?;
        let right =
            TestMemoryExec::try_new_exec(&[vec![right_batch]], right_schema, None)?;

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNothing,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "a2", "b1"]);
        assert_batches_sorted_eq!(
            [
                "+----+----+----+----+",
                "| a1 | b1 | a2 | b1 |",
                "+----+----+----+----+",
                "| 1  | 10 | 3  | 10 |",
                "+----+----+----+----+",
            ],
            &batches
        );

        assert_phj_used(&metrics, use_perfect_hash_join_as_possible);

        Ok(())
    }

    #[tokio::test]
    async fn test_phj_null_equals_null_build_have_nulls() -> Result<()> {
        let task_ctx = prepare_task_ctx(8192, true);
        let (left_schema, right_schema, on) = build_schema_and_on()?;

        let left_batch = RecordBatch::try_new(
            Arc::clone(&left_schema),
            vec![
                Arc::new(Int32Array::from(vec![Some(1), Some(2), Some(3)])) as ArrayRef,
                Arc::new(Int32Array::from(vec![Some(10), Some(20), None])) as ArrayRef,
            ],
        )?;
        let left = TestMemoryExec::try_new_exec(&[vec![left_batch]], left_schema, None)?;

        let right_batch = RecordBatch::try_new(
            Arc::clone(&right_schema),
            vec![
                Arc::new(Int32Array::from(vec![Some(3), Some(4)])) as ArrayRef,
                Arc::new(Int32Array::from(vec![Some(10), Some(30)])) as ArrayRef,
            ],
        )?;
        let right =
            TestMemoryExec::try_new_exec(&[vec![right_batch]], right_schema, None)?;

        let (columns, batches, metrics) = join_collect(
            left,
            right,
            on,
            &JoinType::Inner,
            NullEquality::NullEqualsNull,
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "a2", "b1"]);
        assert_batches_sorted_eq!(
            [
                "+----+----+----+----+",
                "| a1 | b1 | a2 | b1 |",
                "+----+----+----+----+",
                "| 1  | 10 | 3  | 10 |",
                "+----+----+----+----+",
            ],
            &batches
        );

        assert_phj_used(&metrics, false);

        Ok(())
    }

    /// Test null-aware anti join when probe side (right) contains NULL
    /// Expected: no rows should be output (NULL in subquery means all results are unknown)
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_anti_join_probe_null(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        // Build left table (rows to potentially output)
        let left = build_table_two_cols(
            ("c1", &vec![Some(1), Some(2), Some(3), Some(4)]),
            ("dummy", &vec![Some(10), Some(20), Some(30), Some(40)]),
        );

        // Build right table (subquery with NULL)
        let right = build_table_two_cols(
            ("c2", &vec![Some(1), Some(2), Some(3), None]),
            ("dummy", &vec![Some(100), Some(200), Some(300), Some(400)]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        // Create null-aware anti join
        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true, // null_aware = true
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Expected: empty result (probe side has NULL, so no rows should be output)
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            ++
            ++
            ");
        }
        Ok(())
    }

    /// Builds a two-partition probe side for the cross-partition null-aware
    /// tests: partition 0 holds the only NULL key, partition 1 holds none.
    fn build_two_partition_probe_with_null_in_partition_0() -> Arc<dyn ExecutionPlan> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("c2", DataType::Int32, true),
            Field::new("dummy", DataType::Int32, true),
        ]));
        let partition_0 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(vec![Some(1), None])),
                Arc::new(Int32Array::from(vec![Some(100), Some(400)])),
            ],
        )
        .unwrap();
        let partition_1 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(vec![Some(2)])),
                Arc::new(Int32Array::from(vec![Some(200)])),
            ],
        )
        .unwrap();
        TestMemoryExec::try_new_exec(
            &[vec![partition_0], vec![partition_1]],
            schema,
            None,
        )
        .unwrap()
    }

    /// Builds the dictionary-encoded twin of
    /// [`build_two_partition_probe_with_null_in_partition_0`]: the same two
    /// probe partitions, but the join key is a dictionary and partition 0's
    /// NULL exists only logically.
    ///
    /// Every dictionary key is a physically valid index; one of them points at
    /// a NULL dictionary value. The array therefore reports
    /// `null_count() == 0` while `logical_null_count() > 0`, which is the case
    /// that a physical-NULL check silently misses.
    fn build_two_partition_dict_probe_with_logical_null_in_partition_0()
    -> Arc<dyn ExecutionPlan> {
        let dict_type =
            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Int32));
        let schema = Arc::new(Schema::new(vec![
            Field::new("c2", dict_type, true),
            Field::new("dummy", DataType::Int32, true),
        ]));

        // Dictionary values: [1, NULL]; keys: [0, 1] => logical [1, NULL].
        let with_logical_null: ArrayRef = Arc::new(DictionaryArray::new(
            Int32Array::from(vec![0, 1]),
            Arc::new(Int32Array::from(vec![Some(1), None])),
        ));
        assert_eq!(
            with_logical_null.null_count(),
            0,
            "the probe NULL must be logical only, or this test stops covering \
             the logical_null_count path"
        );
        assert!(
            with_logical_null.logical_null_count() > 0,
            "the probe key must carry a logical NULL"
        );

        let partition_0 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                with_logical_null,
                Arc::new(Int32Array::from(vec![Some(100), Some(400)])),
            ],
        )
        .unwrap();

        // Dictionary values: [2]; keys: [0] => logical [2], no NULL anywhere.
        let partition_1 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(DictionaryArray::new(
                    Int32Array::from(vec![0]),
                    Arc::new(Int32Array::from(vec![Some(2)])),
                )),
                Arc::new(Int32Array::from(vec![Some(200)])),
            ],
        )
        .unwrap();

        TestMemoryExec::try_new_exec(
            &[vec![partition_0], vec![partition_1]],
            schema,
            None,
        )
        .unwrap()
    }

    /// Drains the probe partitions of `join` one after another in the given
    /// order and returns everything they emitted.
    async fn collect_partitions_in_order(
        join: &HashJoinExec,
        order: &[usize],
        task_ctx: &Arc<TaskContext>,
    ) -> Result<Vec<RecordBatch>> {
        let mut batches = vec![];
        for &partition in order {
            let stream = join.execute(partition, Arc::clone(task_ctx))?;
            batches.extend(common::collect(stream).await?);
        }
        Ok(batches)
    }

    /// A NULL probe key silences a null-aware anti join even when the
    /// partition that saw it is not the one emitting the final build rows.
    ///
    /// `CollectLeft` with several probe partitions is what the planner
    /// produces for `NOT IN`, and only the last partition to finish emits the
    /// build rows, reading what its siblings recorded. Both finishing orders
    /// must produce no rows.
    ///
    /// These partitions are drained sequentially, so this covers the
    /// cross-partition plumbing, not the concurrent race that motivated
    /// [`ProbeCompletion`]. The interleavings are model-checked in
    /// `probe_completion::loom_tests` instead.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_anti_join_probe_null_in_other_partition(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        for order in [[0, 1], [1, 0]] {
            let left = build_table_two_cols(
                ("c1", &vec![Some(1), Some(2), Some(3), Some(4)]),
                ("dummy", &vec![Some(10), Some(20), Some(30), Some(40)]),
            );
            let right = build_two_partition_probe_with_null_in_partition_0();

            let on = vec![(
                Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
            )];

            let join = HashJoinExec::try_new(
                left,
                right,
                on,
                None,
                &JoinType::LeftAnti,
                None,
                PartitionMode::CollectLeft,
                NullEquality::NullEqualsNothing,
                true, // null_aware = true
            )?;

            let batches = collect_partitions_in_order(&join, &order, &task_ctx).await?;
            let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
            assert_eq!(
                rows, 0,
                "probe order {order:?} emitted rows although a probe partition saw NULL"
            );
        }
        Ok(())
    }

    /// The dictionary counterpart of
    /// [`test_null_aware_anti_join_probe_null_in_other_partition`], where the
    /// silencing probe NULL exists only logically.
    ///
    /// A dictionary key that points at a NULL dictionary value has
    /// `null_count() == 0`, so only the `logical_null_count()` check in
    /// `NotInProbe::before_lookup` records it. This pins that check to the
    /// cross-partition summary: the partition holding the logical NULL is not
    /// the one that emits the build rows, in either drain order.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_anti_join_probe_logical_null_in_other_partition(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        for order in [[0, 1], [1, 0]] {
            // Build keys are dictionary-encoded too, and NULL-free.
            let left = build_table_dict_key(
                "c1",
                vec![Some(1), Some(2), Some(3), Some(4)],
                vec![0, 1, 2, 3],
                "dummy",
                vec![Some(10), Some(20), Some(30), Some(40)],
            );
            let right = build_two_partition_dict_probe_with_logical_null_in_partition_0();

            let on = vec![(
                Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
            )];

            let join = HashJoinExec::try_new(
                left,
                right,
                on,
                None,
                &JoinType::LeftAnti,
                None,
                PartitionMode::CollectLeft,
                NullEquality::NullEqualsNothing,
                true, // null_aware = true
            )?;

            let batches = collect_partitions_in_order(&join, &order, &task_ctx).await?;
            let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
            assert_eq!(
                rows, 0,
                "probe order {order:?} emitted rows although a probe partition saw a logical NULL"
            );
        }
        Ok(())
    }

    /// The null-aware mark join counterpart of
    /// [`test_null_aware_anti_join_probe_null_in_other_partition`]: an
    /// unmatched build row must get an UNKNOWN (NULL) mark when the NULL probe
    /// key was seen by a sibling partition, whichever partition finishes last.
    ///
    /// Sequentially drained, with the same caveat as that test.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_mark_probe_null_in_other_partition(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        for order in [[0, 1], [1, 0]] {
            let left = build_table_two_cols(
                ("c1", &vec![Some(1), Some(4)]),
                ("dummy", &vec![Some(10), Some(40)]),
            );
            let right = build_two_partition_probe_with_null_in_partition_0();

            let on = vec![(
                Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
            )];

            let join = HashJoinExec::try_new(
                left,
                right,
                on,
                None,
                &JoinType::LeftMark,
                None,
                PartitionMode::CollectLeft,
                NullEquality::NullEqualsNothing,
                true, // null_aware = true
            )?;

            let batches = collect_partitions_in_order(&join, &order, &task_ctx).await?;

            // c1=1 matches probe row 1 (mark true); c1=4 is unmatched and the
            // probe side had a NULL, so its mark is UNKNOWN.
            allow_duplicates! {
                assert_snapshot!(batches_to_sort_string(&batches), @r"
                +----+-------+------+
                | c1 | dummy | mark |
                +----+-------+------+
                | 1  | 10    | true |
                | 4  | 40    |      |
                +----+-------+------+
                ");
            }
        }
        Ok(())
    }

    /// The dictionary counterpart of
    /// [`test_null_aware_left_mark_probe_null_in_other_partition`], where the
    /// probe NULL exists in a dictionary value instead of the key bitmap.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_mark_probe_logical_null_in_other_partition(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        for order in [[0, 1], [1, 0]] {
            let left = build_table_dict_key(
                "c1",
                vec![Some(1), Some(4)],
                vec![0, 1],
                "dummy",
                vec![Some(10), Some(40)],
            );
            let right = build_two_partition_dict_probe_with_logical_null_in_partition_0();

            let on = vec![(
                Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
            )];

            let join = HashJoinExec::try_new(
                left,
                right,
                on,
                None,
                &JoinType::LeftMark,
                None,
                PartitionMode::CollectLeft,
                NullEquality::NullEqualsNothing,
                true,
            )?;

            let batches = collect_partitions_in_order(&join, &order, &task_ctx).await?;

            allow_duplicates! {
                assert_snapshot!(batches_to_sort_string(&batches), @r"
                +----+-------+------+
                | c1 | dummy | mark |
                +----+-------+------+
                | 1  | 10    | true |
                | 4  | 40    |      |
                +----+-------+------+
                ");
            }
        }
        Ok(())
    }

    /// Test null-aware anti join when build side (left) contains NULL keys
    /// Expected: rows with NULL keys should not be output
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_anti_join_build_null(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        // Build left table with NULL key (this row should not be output)
        let left = build_table_two_cols(
            ("c1", &vec![Some(1), Some(4), None]),
            ("dummy", &vec![Some(10), Some(40), Some(0)]),
        );

        // Build right table (no NULL, so probe-side check passes)
        let right = build_table_two_cols(
            ("c2", &vec![Some(1), Some(2), Some(3)]),
            ("dummy", &vec![Some(100), Some(200), Some(300)]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        // Create null-aware anti join
        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true, // null_aware = true
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Expected: only c1=4 (not c1=1 which matches, not c1=NULL)
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-------+
            | c1 | dummy |
            +----+-------+
            | 4  | 40    |
            +----+-------+
            ");
        }
        Ok(())
    }

    /// Test null-aware anti join with no NULLs (should work like regular anti join)
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_anti_join_no_nulls(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        // Build left table (no NULLs)
        let left = build_table_two_cols(
            ("c1", &vec![Some(1), Some(2), Some(4), Some(5)]),
            ("dummy", &vec![Some(10), Some(20), Some(40), Some(50)]),
        );

        // Build right table (no NULLs)
        let right = build_table_two_cols(
            ("c2", &vec![Some(1), Some(2), Some(3)]),
            ("dummy", &vec![Some(100), Some(200), Some(300)]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        // Create null-aware anti join
        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true, // null_aware = true
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Expected: c1=4 and c1=5 (they don't match anything in right)
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-------+
            | c1 | dummy |
            +----+-------+
            | 4  | 40    |
            | 5  | 50    |
            +----+-------+
            ");
        }
        Ok(())
    }

    /// Test null-aware RightAnti when build side (subquery) contains NULL
    /// Expected: no rows should be output
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_right_anti_build_null(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        // Build left table (subquery with NULL)
        let left = build_table_two_cols(
            ("c1", &vec![Some(1), Some(2), Some(3), None]),
            ("dummy", &vec![Some(100), Some(200), Some(300), Some(400)]),
        );

        // Build right table (outer rows to potentially output)
        let right = build_table_two_cols(
            ("c2", &vec![Some(1), Some(2), Some(3), Some(4)]),
            ("dummy", &vec![Some(10), Some(20), Some(30), Some(40)]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::RightAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            ++
            ++
            ");
        }
        Ok(())
    }

    /// Test null-aware RightAnti when probe side (outer) contains NULL keys
    /// Expected: rows with NULL keys should not be output
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_right_anti_probe_null(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        // Build left table (subquery, no NULL)
        let left = build_table_two_cols(
            ("c1", &vec![Some(1), Some(2), Some(3)]),
            ("dummy", &vec![Some(100), Some(200), Some(300)]),
        );

        // Build right table with NULL key (this row should not be output)
        let right = build_table_two_cols(
            ("c2", &vec![Some(1), Some(4), None]),
            ("dummy", &vec![Some(10), Some(40), Some(0)]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::RightAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Expected: only c2=4 (not c2=1 which matches, not c2=NULL)
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-------+
            | c2 | dummy |
            +----+-------+
            | 4  | 40    |
            +----+-------+
            ");
        }
        Ok(())
    }

    /// Test null-aware RightAnti with no NULLs (should work like regular RightAnti)
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_right_anti_no_nulls(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        // Build left table (subquery, no NULLs)
        let left = build_table_two_cols(
            ("c1", &vec![Some(1), Some(2), Some(3)]),
            ("dummy", &vec![Some(100), Some(200), Some(300)]),
        );

        // Build right table (outer, no NULLs)
        let right = build_table_two_cols(
            ("c2", &vec![Some(1), Some(2), Some(4), Some(5)]),
            ("dummy", &vec![Some(10), Some(20), Some(40), Some(50)]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::RightAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Expected: c2=4 and c2=5 (they don't match anything in left)
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-------+
            | c2 | dummy |
            +----+-------+
            | 4  | 40    |
            | 5  | 50    |
            +----+-------+
            ");
        }
        Ok(())
    }

    /// Test null-aware RightAnti when build side (subquery) is empty
    /// Expected: all outer rows should be output, including NULL keys
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_right_anti_empty_build(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        // Build left table (empty subquery)
        let left = build_table_two_cols(("c1", &vec![]), ("dummy", &vec![]));

        // Build right table (outer)
        let right = build_table_two_cols(
            ("c2", &vec![Some(1), None, Some(4)]),
            ("dummy", &vec![Some(10), Some(0), Some(40)]),
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::RightAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-------+
            | c2 | dummy |
            +----+-------+
            |    | 0     |
            | 1  | 10    |
            | 4  | 40    |
            +----+-------+
            ");
        }
        Ok(())
    }

    /// Null-aware RightAnti must treat dictionary keys that point at a null
    /// dictionary value as build-side NULLs, even when the key bitmap has no
    /// physical nulls (`null_count() == 0` but `logical_null_count() > 0`).
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_right_anti_build_logical_null(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        // Dictionary values: [1, NULL, 2]; keys: [0, 1, 2] => logical [1, NULL, 2]
        let left = build_table_dict_key(
            "c1",
            vec![Some(1), None, Some(2)],
            vec![0, 1, 2],
            "dummy",
            vec![Some(100), Some(200), Some(300)],
        );
        let left_key = left
            .execute(0, Arc::clone(&task_ctx))?
            .next()
            .await
            .unwrap()?;
        assert_eq!(left_key.column(0).null_count(), 0);
        assert_eq!(left_key.column(0).logical_null_count(), 1);

        let right = build_table_dict_key(
            "c2",
            vec![Some(1), Some(2), Some(3), Some(4)],
            vec![0, 1, 2, 3],
            "dummy",
            vec![Some(10), Some(20), Some(30), Some(40)],
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::RightAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            ++
            ++
            ");
        }
        Ok(())
    }

    /// Regression test for a `NullEqualsNull` join whose build-side join key is
    /// a dictionary with NULL stored in the dictionary *values*.
    ///
    /// Such a key is only logically NULL: `null_count() == 0` because the key
    /// bitmap has no physical nulls, but `logical_null_count() > 0`. The hash
    /// join must still treat it as a NULL key in two places:
    ///
    /// 1. The build side must not be turned into an `ArrayMap` (perfect hash
    ///    join), which only supports plain integer keys. Bounds are collected
    ///    for the dynamic filter regardless of key type, so the `ArrayMap`
    ///    path must check the key type itself instead of inferring it from
    ///    the presence of bounds; otherwise the build fails with
    ///    `Unsupported type for ArrayMap`.
    /// 2. The dynamic filter pushed to the probe side must be widened with
    ///    `c2 IS NULL OR ...`, so the probe row with a NULL key still reaches
    ///    the join and null-matches the build NULL. Without it the filter
    ///    `c2 >= 1 AND c2 <= 2 AND c2 IN (...)` evaluates to NULL for that
    ///    row and silently drops it.
    ///
    /// Setup: build keys `[1, NULL, 2]`, probe keys `[1, NULL, 4]`, inner join
    /// with a `FilterExec` consuming the join's dynamic filter on the probe side.
    /// Expected output: the `1 = 1` row and the `NULL = NULL` row.
    #[tokio::test]
    async fn test_null_equal_dynamic_filter_keeps_probe_nulls_for_build_logical_null()
    -> Result<()> {
        let task_ctx = Arc::new(TaskContext::default());

        // Dictionary values: [1, NULL, 2]; keys: [0, 1, 2] => logical [1, NULL, 2]
        let left = build_table_dict_key(
            "c1",
            vec![Some(1), None, Some(2)],
            vec![0, 1, 2],
            "d1",
            vec![Some(100), Some(200), Some(300)],
        );
        let left_key = left
            .execute(0, Arc::clone(&task_ctx))?
            .next()
            .await
            .unwrap()?;
        assert_eq!(left_key.column(0).null_count(), 0);
        assert_eq!(left_key.column(0).logical_null_count(), 1);

        // Dictionary values: [1, NULL, 4]; keys: [0, 1, 2] => logical [1, NULL, 4]
        let right = build_table_dict_key(
            "c2",
            vec![Some(1), None, Some(4)],
            vec![0, 1, 2],
            "d2",
            vec![Some(10), Some(20), Some(40)],
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        // Wire the join's dynamic filter into a FilterExec over the probe side so
        // that the filter is actually built (bounds are only collected when the
        // probe subtree contains a consumer) and applied to the probe rows.
        let dynamic_filter = HashJoinExec::create_dynamic_filter(&on);
        let consumer: Arc<dyn PhysicalExpr> = Arc::clone(&dynamic_filter) as _;
        let right = Arc::new(FilterExecBuilder::new(consumer, right).build()?);
        let mut join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::Inner,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNull,
            false,
        )?;
        join.dynamic_filter = Some(HashJoinExecDynamicFilter {
            filter: Arc::clone(&dynamic_filter),
            build_accumulator: OnceLock::new(),
        });

        // (1) Building the hash table must not fail on the dictionary key.
        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // (2) The build-side logical NULL must widen the pushed filter with
        // `IS NULL`, because the join is NullEqualsNull.
        dynamic_filter.wait_complete().await;
        let filter = dynamic_filter.current()?.to_string();
        assert!(
            filter.contains("c2@0 IS NULL OR"),
            "expected an IS NULL disjunct in the pushed filter, got: {filter}"
        );

        // The NULL-NULL row (d1 = 200, d2 = 20) is only produced if the probe
        // NULL survived the pushed filter.
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-----+----+----+
            | c1 | d1  | c2 | d2 |
            +----+-----+----+----+
            |    | 200 |    | 20 |
            | 1  | 100 | 1  | 10 |
            +----+-----+----+----+
            ");
        }
        Ok(())
    }

    /// The [`PartitionMode::Partitioned`] counterpart of
    /// [`test_null_equal_dynamic_filter_keeps_probe_nulls_for_build_logical_null`].
    ///
    /// Here the build-side logical NULL lives in exactly one build partition, so
    /// the `keys_have_null` flag has to survive the per-partition aggregation in
    /// `build_partitioned_filter` and widen the *routed* filter as a whole: the
    /// probe NULL is routed to a single `CASE` branch, and OR-ing `IS NULL` into
    /// that one branch would still drop it for every other route.
    #[tokio::test]
    async fn test_partitioned_null_equal_dynamic_filter_keeps_probe_nulls_for_build_logical_null()
    -> Result<()> {
        let mut session_config = SessionConfig::default();
        session_config
            .options_mut()
            .optimizer
            .enable_dynamic_filter_pushdown = true;
        let task_ctx =
            Arc::new(TaskContext::default().with_session_config(session_config));

        let partition_count = 4;

        // Dictionary values: [1, NULL, 2]; keys: [0, 1, 2] => logical [1, NULL, 2]
        let left = build_table_dict_key(
            "c1",
            vec![Some(1), None, Some(2)],
            vec![0, 1, 2],
            "d1",
            vec![Some(100), Some(200), Some(300)],
        );
        // Dictionary values: [1, NULL, 4]; keys: [0, 1, 2] => logical [1, NULL, 4]
        let right = build_table_dict_key(
            "c2",
            vec![Some(1), None, Some(4)],
            vec![0, 1, 2],
            "d2",
            vec![Some(10), Some(20), Some(40)],
        );

        let left_key =
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as PhysicalExprRef;
        let right_key =
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as PhysicalExprRef;
        let on = vec![(Arc::clone(&left_key), Arc::clone(&right_key))];

        // Hash-repartition both sides so the join runs with real partition routing:
        // the build NULL and the probe NULL land in the same partition, and every
        // other partition reports a NULL-free build.
        let left_repartitioned: Arc<dyn ExecutionPlan> =
            Arc::new(RepartitionExec::try_new(
                left,
                Partitioning::Hash(vec![left_key], partition_count),
            )?);
        let right_repartitioned: Arc<dyn ExecutionPlan> =
            Arc::new(RepartitionExec::try_new(
                right,
                Partitioning::Hash(vec![Arc::clone(&right_key)], partition_count),
            )?);

        // The FilterExec sits above the repartition so each probe partition is only
        // read after the join has waited for every partition's build report, which
        // makes the finalized (routed and widened) filter the one actually applied.
        let dynamic_filter = HashJoinExec::create_dynamic_filter(&on);
        let consumer: Arc<dyn PhysicalExpr> = Arc::clone(&dynamic_filter) as _;
        let right_filtered: Arc<dyn ExecutionPlan> =
            Arc::new(FilterExecBuilder::new(consumer, right_repartitioned).build()?);

        let mut join = HashJoinExec::try_new(
            left_repartitioned,
            right_filtered,
            on,
            None,
            &JoinType::Inner,
            None,
            PartitionMode::Partitioned,
            NullEquality::NullEqualsNull,
            false,
        )?;
        join.dynamic_filter = Some(HashJoinExecDynamicFilter {
            filter: Arc::clone(&dynamic_filter),
            build_accumulator: OnceLock::new(),
        });

        let batches = crate::execution_plan::collect(Arc::new(join), task_ctx).await?;

        dynamic_filter.wait_complete().await;
        let filter = dynamic_filter.current()?.to_string();
        // The aggregated build-side NULL must widen the whole merged filter once,
        // at the top: `c2 IS NULL OR <membership over every partition>`.
        assert!(
            filter.starts_with("c2@0 IS NULL OR"),
            "expected the IS NULL disjunct to wrap the whole routed filter, got: {filter}"
        );

        // The NULL-NULL row (d1 = 200, d2 = 20) is only produced if the probe
        // NULL survived the pushed filter on its route.
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-----+----+----+
            | c1 | d1  | c2 | d2 |
            +----+-----+----+----+
            |    | 200 |    | 20 |
            | 1  | 100 | 1  | 10 |
            +----+-----+----+----+
            ");
        }
        Ok(())
    }

    /// Null-aware RightAnti must drop outer rows whose dictionary key is only
    /// logically NULL (key points at a null dictionary value).
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_right_anti_probe_logical_null(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        let left = build_table_dict_key(
            "c1",
            vec![Some(1), Some(2), Some(3)],
            vec![0, 1, 2],
            "dummy",
            vec![Some(100), Some(200), Some(300)],
        );

        // Dictionary values: [1, NULL, 4]; keys: [0, 1, 2] => logical [1, NULL, 4]
        let right = build_table_dict_key(
            "c2",
            vec![Some(1), None, Some(4)],
            vec![0, 1, 2],
            "dummy",
            vec![Some(10), Some(0), Some(40)],
        );
        let right_key = right
            .execute(0, Arc::clone(&task_ctx))?
            .next()
            .await
            .unwrap()?;
        assert_eq!(right_key.column(0).null_count(), 0);
        assert_eq!(right_key.column(0).logical_null_count(), 1);

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::RightAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Expected: only c2=4 (not c2=1 which matches, not logically NULL c2)
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-------+
            | c2 | dummy |
            +----+-------+
            | 4  | 40    |
            +----+-------+
            ");
        }
        Ok(())
    }

    /// Test that null_aware validation rejects non-LeftAnti join types
    #[tokio::test]
    async fn test_null_aware_validation_wrong_join_type() {
        let left =
            build_table_two_cols(("c1", &vec![Some(1)]), ("dummy", &vec![Some(10)]));
        let right =
            build_table_two_cols(("c2", &vec![Some(1)]), ("dummy", &vec![Some(100)]));

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema()).unwrap()) as _,
        )];

        // Try to create null-aware Inner join (should fail)
        let result = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::Inner,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true, // null_aware = true (invalid for Inner join)
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains(
            "null_aware can only be true for LeftAnti joins and RightAnti joins"
        ));
    }

    /// Test that null_aware RightAnti rejects Partitioned mode
    #[tokio::test]
    async fn test_null_aware_validation_right_anti_partitioned() {
        let left =
            build_table_two_cols(("c1", &vec![Some(1)]), ("dummy", &vec![Some(10)]));
        let right =
            build_table_two_cols(("c2", &vec![Some(1)]), ("dummy", &vec![Some(100)]));

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema()).unwrap()) as _,
        )];

        let result = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::RightAnti,
            None,
            PartitionMode::Partitioned,
            NullEquality::NullEqualsNothing,
            true,
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains(
            "null_aware can only be true for LeftAnti joins and RightAnti joins"
        ));
    }

    /// An uncorrelated null-aware `LeftAnti` must reject
    /// `PartitionMode::Partitioned` just like the correlated forms do.
    ///
    /// `LeftAnti` emits build rows in the final stage, and the "a probe
    /// partition saw a NULL `NOT IN` key" flag lives on the build data
    /// (`JoinLeftData::probe_completion`). In `Partitioned` mode every output
    /// partition builds its own build side, so a NULL probe key, hashed to a
    /// single partition, would only silence that partition's build rows while
    /// the others still emitted their unmatched ones.
    #[tokio::test]
    async fn test_null_aware_validation_left_anti_partitioned() {
        let left =
            build_table_two_cols(("c1", &vec![Some(1)]), ("dummy", &vec![Some(10)]));
        let right =
            build_table_two_cols(("c2", &vec![Some(1)]), ("dummy", &vec![Some(100)]));

        // A single join key and no filter, so this is the uncorrelated
        // `LeftAnti` form, which the partition-mode check used to let through.
        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema()).unwrap()) as _,
        )];

        let err = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::Partitioned,
            NullEquality::NullEqualsNothing,
            true,
        )
        .expect_err("null_aware LeftAnti must reject PartitionMode::Partitioned");

        assert!(
            err.to_string()
                .contains("null_aware joins require PartitionMode::CollectLeft"),
            "{err}"
        );
    }

    /// A null-aware join for a scalar `NOT IN` on `on[0]`, correlated by any
    /// keys after it: it states one `NOT IN` value key, which a multi-key
    /// join must.
    fn try_new_scalar_not_in(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        on: JoinOn,
        filter: Option<JoinFilter>,
        join_type: JoinType,
        partition_mode: PartitionMode,
    ) -> Result<HashJoinExec> {
        HashJoinExecBuilder::new(left, right, on, join_type)
            .with_filter(filter)
            .with_partition_mode(partition_mode)
            .with_null_aware(true)
            .with_null_aware_value_keys(1)
            .build()
    }

    /// Test that null_aware validation rejects PartitionMode::Partitioned (must be CollectLeft).
    #[tokio::test]
    async fn test_null_aware_validation_partitioned() {
        let left = build_table(("a", &vec![1]), ("b", &vec![2]), ("c", &vec![3]));
        let right = build_table(("x", &vec![1]), ("y", &vec![2]), ("z", &vec![3]));

        let on = vec![
            (
                Arc::new(Column::new_with_schema("a", &left.schema()).unwrap()) as _,
                Arc::new(Column::new_with_schema("x", &right.schema()).unwrap()) as _,
            ),
            (
                Arc::new(Column::new_with_schema("b", &left.schema()).unwrap()) as _,
                Arc::new(Column::new_with_schema("y", &right.schema()).unwrap()) as _,
            ),
        ];

        // A correlated (multi-key) LeftMark requires CollectLeft.
        let result = try_new_scalar_not_in(
            left,
            right,
            on,
            None,
            JoinType::LeftMark,
            PartitionMode::Partitioned,
        );

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("null_aware joins require PartitionMode::CollectLeft")
        );
    }

    /// A correlated null-aware anti join, with more than one key or a join
    /// filter (a decorrelated correlated `NOT IN`), is accepted both as
    /// `LeftAnti` and as the `RightAnti` that `JoinSelection` swaps it into.
    #[rstest]
    #[case::right_anti_multi_key(JoinType::RightAnti, true, false)]
    #[case::right_anti_filter(JoinType::RightAnti, false, true)]
    #[case::left_anti_filter(JoinType::LeftAnti, false, true)]
    fn test_null_aware_correlated_anti_join_accepted(
        #[case] join_type: JoinType,
        #[case] multi_key: bool,
        #[case] with_filter: bool,
    ) -> Result<()> {
        let left =
            build_table_two_cols(("c1", &vec![Some(1)]), ("dummy", &vec![Some(10)]));
        let right =
            build_table_two_cols(("c2", &vec![Some(1)]), ("dummy", &vec![Some(100)]));
        let key = |l: &str, r: &str| -> Result<(PhysicalExprRef, PhysicalExprRef)> {
            Ok((
                Arc::new(Column::new_with_schema(l, &left.schema())?) as _,
                Arc::new(Column::new_with_schema(r, &right.schema())?) as _,
            ))
        };
        let mut on = vec![key("c1", "c2")?];
        if multi_key {
            on.push(key("dummy", "dummy")?);
        }
        let join = try_new_scalar_not_in(
            Arc::clone(&left),
            Arc::clone(&right),
            on,
            with_filter.then(prepare_join_filter),
            join_type,
            PartitionMode::CollectLeft,
        )?;
        let scope = NotInScope::Correlated { value_keys: 1 };
        let expected = match join_type {
            JoinType::RightAnti => NotIn::ProbeRows { scope },
            _ => NotIn::BuildRows {
                scope,
                output: NotInOutput::Rows,
            },
        };
        assert_eq!(join.not_in()?, Some(expected));
        Ok(())
    }

    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_anti_probe_logical_null(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        let left = build_table_dict_key(
            "c1",
            vec![Some(1), Some(2), Some(3)],
            vec![0, 1, 2],
            "dummy",
            vec![Some(100), Some(200), Some(300)],
        );

        let right = build_table_dict_key(
            "c2",
            vec![Some(1), None, Some(4)],
            vec![0, 1, 2],
            "dummy",
            vec![Some(10), Some(0), Some(40)],
        );
        let right_key = right
            .execute(0, Arc::clone(&task_ctx))?
            .next()
            .await
            .unwrap()?;
        assert_eq!(right_key.column(0).null_count(), 0);
        assert_eq!(right_key.column(0).logical_null_count(), 1);

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            ++
            ++
            ");
        }
        Ok(())
    }

    /// The build side counterpart of
    /// [`test_null_aware_left_anti_probe_logical_null`]: `NULL NOT IN (5, 6)`
    /// is UNKNOWN, so the build row whose key points at a NULL dictionary
    /// value is dropped.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_anti_build_logical_null(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        let left = build_table_dict_key(
            "c1",
            vec![Some(1), None, Some(2)],
            vec![0, 1, 2],
            "dummy",
            vec![Some(10), Some(0), Some(20)],
        );
        let left_key = left
            .execute(0, Arc::clone(&task_ctx))?
            .next()
            .await
            .unwrap()?;
        assert_eq!(left_key.column(0).null_count(), 0);
        assert_eq!(left_key.column(0).logical_null_count(), 1);

        let right = build_table_dict_key(
            "c2",
            vec![Some(5), Some(6)],
            vec![0, 1],
            "dummy",
            vec![Some(50), Some(60)],
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-------+
            | c1 | dummy |
            +----+-------+
            | 1  | 10    |
            | 2  | 20    |
            +----+-------+
            ");
        }
        Ok(())
    }

    /// A dictionary key that points to a NULL dictionary value is a NULL build
    /// key even when the dictionary key bitmap itself has no NULLs.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_mark_build_logical_null(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        let left = build_table_dict_key(
            "c1",
            vec![Some(1), None, Some(4)],
            vec![0, 1, 2],
            "dummy",
            vec![Some(10), Some(0), Some(40)],
        );
        let left_key = left
            .execute(0, Arc::clone(&task_ctx))?
            .next()
            .await
            .unwrap()?;
        assert_eq!(left_key.column(0).null_count(), 0);
        assert_eq!(left_key.column(0).logical_null_count(), 1);

        let right = build_table_dict_key(
            "c2",
            vec![Some(1), Some(2), Some(3)],
            vec![0, 1, 2],
            "dummy",
            vec![Some(100), Some(200), Some(300)],
        );

        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftMark,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-------+-------+
            | c1 | dummy | mark  |
            +----+-------+-------+
            |    | 0     |       |
            | 1  | 10    | true  |
            | 4  | 40    | false |
            +----+-------+-------+
            ");
        }
        Ok(())
    }

    fn build_single_column_table(name: &str, array: ArrayRef) -> Arc<dyn ExecutionPlan> {
        let schema = Arc::new(Schema::new(vec![Field::new(
            name,
            array.data_type().clone(),
            true,
        )]));
        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![array]).unwrap();
        TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
    }

    fn nested_dictionary_array(
        leaf_values: Vec<Option<i32>>,
        inner_keys: Vec<i32>,
        outer_keys: Vec<i32>,
    ) -> ArrayRef {
        let leaf_values: ArrayRef = Arc::new(Int32Array::from(leaf_values));
        let inner_keys = Int32Array::from(inner_keys);
        let inner_values: ArrayRef =
            Arc::new(DictionaryArray::<Int32Type>::new(inner_keys, leaf_values));
        Arc::new(DictionaryArray::<Int32Type>::new(
            Int32Array::from(outer_keys),
            inner_values,
        ))
    }

    /// A nested dictionary's logical null bitmap must be computed once for the
    /// complete build key and remain indexed by the original build row.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_mark_nested_dictionary_logical_null(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);
        let left_key = nested_dictionary_array(
            vec![Some(1), None, Some(4)],
            vec![0, 1, 2],
            vec![0, 1, 2],
        );
        assert_eq!(left_key.logical_null_count(), 1);
        let left = build_single_column_table("c1", left_key);
        let right = build_single_column_table(
            "c2",
            nested_dictionary_array(
                vec![Some(1), Some(2), Some(3)],
                vec![0, 1, 2],
                vec![0, 1, 2],
            ),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("c1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("c2", &right.schema())?) as _,
        )];
        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftMark,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let batches = common::collect(join.execute(0, task_ctx)?).await?;
        let marks = batches
            .iter()
            .flat_map(|batch| batch.column(batch.num_columns() - 1).as_boolean().iter())
            .collect::<Vec<_>>();
        assert_eq!(marks, vec![Some(true), None, Some(false)]);
        Ok(())
    }

    /// Scalar correlated null-aware left mark join where only the build side's
    /// value key contains NULL.
    ///
    /// This isolates the NULL-value scope map direction of
    /// `mark_null_candidates_for_probe_batch`: NULL-valued build rows become
    /// UNKNOWN as soon as any probe row shares their correlation scope, while
    /// non-null build rows stay `true`/`false`.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_mark_correlated_build_null_only(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        let left = build_table_two_cols(
            ("id", &vec![Some(1), None, None, Some(3)]),
            ("grp", &vec![Some(1), Some(1), Some(2), Some(3)]),
        );

        let right = build_table_two_cols(
            ("id", &vec![Some(2), Some(1)]),
            ("grp", &vec![Some(1), Some(2)]),
        );

        let on = vec![
            (
                Arc::new(Column::new_with_schema("id", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("id", &right.schema())?) as _,
            ),
            (
                Arc::new(Column::new_with_schema("grp", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("grp", &right.schema())?) as _,
            ),
        ];

        let join = try_new_scalar_not_in(
            left,
            right,
            on,
            None,
            JoinType::LeftMark,
            PartitionMode::CollectLeft,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // `(NULL, 1)` and `(NULL, 2)` have non-empty correlated scopes, so
        // their marks are UNKNOWN. `(1, 1)` finds no equal value and no NULL in
        // its scope (false); `(3, 3)` has an empty correlated scope (false).
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-----+-------+
            | id | grp | mark  |
            +----+-----+-------+
            |    | 1   |       |
            |    | 2   |       |
            | 1  | 1   | false |
            | 3  | 3   | false |
            +----+-----+-------+
            ");
        }

        Ok(())
    }

    /// Scalar correlated null-aware left mark join where only the probe side's
    /// value key contains NULL.
    ///
    /// This isolates the NULL-valued-probe-row direction of
    /// `mark_null_candidates_for_probe_batch`: every unmatched build row whose
    /// correlation scope contains a NULL-valued probe row becomes UNKNOWN.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_mark_correlated_probe_null_only(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        let left = build_table_two_cols(
            ("id", &vec![Some(1), Some(2), Some(5), Some(7)]),
            ("grp", &vec![Some(1), Some(1), Some(2), Some(3)]),
        );

        let right = build_table_two_cols(
            ("id", &vec![Some(2), None, Some(4)]),
            ("grp", &vec![Some(1), Some(1), Some(2)]),
        );

        let on = vec![
            (
                Arc::new(Column::new_with_schema("id", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("id", &right.schema())?) as _,
            ),
            (
                Arc::new(Column::new_with_schema("grp", &left.schema())?) as _,
                Arc::new(Column::new_with_schema("grp", &right.schema())?) as _,
            ),
        ];

        let join = try_new_scalar_not_in(
            left,
            right,
            on,
            None,
            JoinType::LeftMark,
            PartitionMode::CollectLeft,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // `(1, 1)` is unmatched and its scope contains a NULL value (UNKNOWN);
        // `(2, 1)` matches (true); `(5, 2)`'s scope holds only `4` (false);
        // `(7, 3)` has an empty correlated scope (false).
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+-----+-------+
            | id | grp | mark  |
            +----+-----+-------+
            | 1  | 1   |       |
            | 2  | 1   | true  |
            | 5  | 2   | false |
            | 7  | 3   | false |
            +----+-----+-------+
            ");
        }

        Ok(())
    }

    /// `left.z > right.z` over the second column of two-column tables: the
    /// non-equality correlation of
    /// `id NOT IN (SELECT r.id FROM r WHERE r.z < l.z)`.
    fn prepare_second_column_gt_filter() -> JoinFilter {
        let column_indices = vec![
            ColumnIndex {
                index: 1,
                side: JoinSide::Left,
            },
            ColumnIndex {
                index: 1,
                side: JoinSide::Right,
            },
        ];
        let intermediate_schema = Schema::new(vec![
            Field::new("z", DataType::Int32, true),
            Field::new("z", DataType::Int32, true),
        ]);
        let filter_expression = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("z", 0)),
            Operator::Gt,
            Arc::new(Column::new("z", 1)),
        )) as Arc<dyn PhysicalExpr>;

        JoinFilter::new(
            filter_expression,
            column_indices,
            Arc::new(intermediate_schema),
        )
    }

    /// Build and probe sides of a null-aware join whose only correlation is
    /// the non-equality filter from [`prepare_second_column_gt_filter`].
    ///
    /// For each build row, the probe rows with a smaller `z` form its
    /// subquery result:
    /// - `(1, 10)` and `(2, 20)`: `{1, NULL}`
    /// - `(NULL, 30)`: `{1, NULL}`
    /// - `(4, 40)`: `{1, 4, NULL}`
    /// - `(NULL, 1)` and `(5, 1)`: empty
    ///
    /// The probe row `(NULL, 50)` never passes the filter.
    fn build_null_aware_filter_only_inputs()
    -> (Arc<dyn ExecutionPlan>, Arc<dyn ExecutionPlan>, JoinOn) {
        let left = build_table_two_cols(
            ("id", &vec![Some(1), Some(2), None, Some(4), None, Some(5)]),
            (
                "z",
                &vec![Some(10), Some(20), Some(30), Some(40), Some(1), Some(1)],
            ),
        );
        let right = build_table_two_cols(
            ("id", &vec![Some(1), None, Some(4), None]),
            ("z", &vec![Some(5), Some(50), Some(35), Some(2)]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("id", &left.schema()).unwrap()) as _,
            Arc::new(Column::new_with_schema("id", &right.schema()).unwrap()) as _,
        )];
        (left, right, on)
    }

    /// Null-aware `LeftAnti` with a join filter and no correlation scope keys.
    ///
    /// A NULL on either side only makes `NOT IN` UNKNOWN for the build rows
    /// where the filter keeps the NULL, so the NULLs must not remove every row.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_anti_filter_only(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);
        let (left, right, on) = build_null_aware_filter_only_inputs();

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            Some(prepare_second_column_gt_filter()),
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Only the rows with an empty subquery result are TRUE.
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+---+
            | id | z |
            +----+---+
            |    | 1 |
            | 5  | 1 |
            +----+---+
            ");
        }

        Ok(())
    }

    /// Null-aware `LeftMark` with a join filter and no correlation scope keys.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_mark_filter_only(batch_size: usize) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);
        let (left, right, on) = build_null_aware_filter_only_inputs();

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            Some(prepare_second_column_gt_filter()),
            &JoinType::LeftMark,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // `(1, 10)` and `(4, 40)` match (true); `(2, 20)` and `(NULL, 30)`
        // keep the NULL probe row (UNKNOWN); `(NULL, 1)` and `(5, 1)` have an
        // empty subquery result (false).
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+-------+
            | id | z  | mark  |
            +----+----+-------+
            |    | 1  | false |
            |    | 30 |       |
            | 1  | 10 | true  |
            | 2  | 20 |       |
            | 4  | 40 | true  |
            | 5  | 1  | false |
            +----+----+-------+
            ");
        }

        Ok(())
    }

    /// The value key count must name no more keys than the join has. An
    /// unset count (`0`) is a scalar `NOT IN` with a single key, and is
    /// rejected with more keys rather than guessing which of them are `NOT IN`
    /// value keys and which are correlation scope keys.
    #[test]
    fn test_null_aware_validation_value_keys() -> Result<()> {
        let left = build_table_two_cols(("a", &vec![Some(1)]), ("b", &vec![None]));
        let right = build_table_two_cols(("x", &vec![Some(1)]), ("y", &vec![Some(5)]));
        let key = |l: &str, r: &str| -> Result<(PhysicalExprRef, PhysicalExprRef)> {
            Ok((
                Arc::new(Column::new_with_schema(l, &left.schema())?) as _,
                Arc::new(Column::new_with_schema(r, &right.schema())?) as _,
            ))
        };
        let two_keys = vec![key("a", "x")?, key("b", "y")?];
        let build = |on: JoinOn, join_type, partition_mode, value_keys| {
            HashJoinExecBuilder::new(Arc::clone(&left), Arc::clone(&right), on, join_type)
                .with_partition_mode(partition_mode)
                .with_null_aware(true)
                .with_null_aware_value_keys(value_keys)
                .build()
        };

        for (value_keys, expected) in [
            (
                0,
                "join with 2 keys needs the number of its `NOT IN` value keys, set it with `with_null_aware_value_keys`",
            ),
            (3, "needs between 1 and 2 `NOT IN` value keys"),
        ] {
            let err = build(
                two_keys.clone(),
                JoinType::LeftAnti,
                PartitionMode::CollectLeft,
                value_keys,
            )
            .unwrap_err();
            assert!(err.to_string().contains(expected), "{err}");
        }

        // `HashJoinExec::try_new` cannot set the count, so it only builds
        // single-key null-aware joins, as before value keys existed.
        let err = HashJoinExec::try_new(
            Arc::clone(&left),
            Arc::clone(&right),
            two_keys.clone(),
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("with_null_aware_value_keys"),
            "{err}"
        );

        let join = build(
            vec![key("a", "x")?],
            JoinType::LeftAnti,
            PartitionMode::CollectLeft,
            0,
        )?;
        assert_eq!(join.not_in()?.map(NotIn::value_keys), Some(1));

        // A join that no count can make valid reports what is wrong with it,
        // not the missing count.
        for (on, join_type, partition_mode, expected) in [
            (
                two_keys.clone(),
                JoinType::Inner,
                PartitionMode::CollectLeft,
                "null_aware can only be true for LeftAnti joins",
            ),
            (
                two_keys.clone(),
                JoinType::RightAnti,
                PartitionMode::Partitioned,
                "null_aware can only be true for LeftAnti joins",
            ),
            (
                two_keys,
                JoinType::LeftAnti,
                PartitionMode::Partitioned,
                "null_aware joins require PartitionMode::CollectLeft",
            ),
            (
                vec![],
                JoinType::LeftAnti,
                PartitionMode::CollectLeft,
                "On constraints in HashJoinExec should be non-empty",
            ),
        ] {
            let err = build(on, join_type, partition_mode, 0).unwrap_err();
            assert!(err.to_string().contains(expected), "{join_type}: {err}");
        }
        Ok(())
    }

    /// Correlated null-aware `LeftAnti` with a two-column correlation scope,
    /// so scope lookups compare keys with the general multi-column comparator.
    ///
    /// Each NULL-marking direction yields several scope matches for a single
    /// probe batch, which small batch sizes split across many lookup chunks.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_anti_multi_column_scope(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        fn table(
            id: Vec<Option<i32>>,
            g1: Vec<Option<i32>>,
            g2: Vec<Option<i32>>,
        ) -> Arc<dyn ExecutionPlan> {
            let schema = Arc::new(Schema::new(vec![
                Field::new("id", DataType::Int32, true),
                Field::new("g1", DataType::Int32, true),
                Field::new("g2", DataType::Int32, true),
            ]));
            let batch = RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(id)),
                    Arc::new(Int32Array::from(g1)),
                    Arc::new(Int32Array::from(g2)),
                ],
            )
            .unwrap();
            TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
        }

        let left = table(
            vec![
                Some(1),
                Some(2),
                None,
                None,
                Some(6),
                Some(8),
                Some(9),
                Some(10),
                None,
            ],
            vec![
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(2),
                Some(3),
            ],
            vec![
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(2),
                Some(2),
                Some(2),
                Some(1),
                Some(3),
            ],
        );
        let right = table(
            vec![
                Some(2),
                Some(3),
                Some(4),
                Some(5),
                None,
                None,
                Some(7),
                Some(11),
            ],
            vec![
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(2),
            ],
            vec![
                Some(1),
                Some(1),
                Some(1),
                Some(1),
                Some(2),
                Some(2),
                Some(2),
                Some(1),
            ],
        );

        let on = ["id", "g1", "g2"]
            .into_iter()
            .map(|name| {
                Ok((
                    Arc::new(Column::new_with_schema(name, &left.schema())?) as _,
                    Arc::new(Column::new_with_schema(name, &right.schema())?) as _,
                ))
            })
            .collect::<Result<JoinOn>>()?;

        // The outer side `left` as the build side (`LeftAnti`), and swapped to
        // the probe side (`RightAnti`), must keep the same rows.
        let left_anti = try_new_scalar_not_in(
            Arc::clone(&left),
            Arc::clone(&right),
            on.clone(),
            None,
            JoinType::LeftAnti,
            PartitionMode::CollectLeft,
        )?;
        let right_anti = swap_for_separate_execution(&left_anti)?;
        let batches =
            common::collect(left_anti.execute(0, Arc::clone(&task_ctx))?).await?;
        let swapped = common::collect(right_anti.execute(0, task_ctx)?).await?;
        assert_eq!(
            batches_to_sort_string(&batches),
            batches_to_sort_string(&swapped)
        );

        // Scope (1, 1) holds 2, 3, 4 and 5: `(1, 1, 1)` is kept, `(2, 1, 1)`
        // matches, and both NULL-valued build rows there are UNKNOWN. Scope
        // (1, 2) holds two NULLs, so all of its build rows are UNKNOWN. Scope
        // (2, 1) holds only 11, so `(10, 2, 1)` is kept, and `(NULL, 3, 3)`
        // has an empty scope.
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+----+----+
            | id | g1 | g2 |
            +----+----+----+
            |    | 3  | 3  |
            | 1  | 1  | 1  |
            | 10 | 2  | 1  |
            +----+----+----+
            ");
        }

        Ok(())
    }

    /// Swaps a null-aware `LeftAnti` into the `RightAnti` that `JoinSelection`
    /// plans, with its own build state so that both can be executed.
    fn swap_for_separate_execution(
        left_anti: &HashJoinExec,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        let swapped = left_anti.swap_inputs(PartitionMode::CollectLeft)?;
        let swapped = swapped.downcast_ref::<HashJoinExec>().unwrap();
        Ok(Arc::new(swapped.builder().reset_state().build()?))
    }

    /// A correlated null-aware join whose build value keys are all NULL: under
    /// `NullEqualsNothing` its full-key map is empty, but the UNKNOWN marks
    /// still depend on each scope. `NULL NOT IN (5)` and `NULL NOT IN (7)` are
    /// UNKNOWN; `NULL NOT IN (empty)`, in scope 3, is TRUE. For `RightAnti`,
    /// `5 NOT IN (NULL)` and `7 NOT IN (NULL)` are UNKNOWN and `9 NOT IN
    /// (empty)`, in scope 4, is TRUE: only `(9, 4)` is emitted, from the same
    /// probe batch as the dropped `(7, 2)`. The probe side arrives in two
    /// batches.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_correlated_all_null_build_values(
        batch_size: usize,
    ) -> Result<()> {
        fn table(id: Vec<Option<i32>>, g: Vec<Option<i32>>) -> RecordBatch {
            let schema = Arc::new(Schema::new(vec![
                Field::new("id", DataType::Int32, true),
                Field::new("g", DataType::Int32, true),
            ]));
            RecordBatch::try_new(
                schema,
                vec![
                    Arc::new(Int32Array::from(id)),
                    Arc::new(Int32Array::from(g)),
                ],
            )
            .unwrap()
        }
        let build = table(vec![None, None, None], vec![Some(1), Some(2), Some(3)]);
        let probe = [
            table(vec![Some(5)], vec![Some(1)]),
            table(vec![Some(7), Some(9)], vec![Some(2), Some(4)]),
        ];

        let mut results = vec![];
        for join_type in [JoinType::LeftAnti, JoinType::LeftMark, JoinType::RightAnti] {
            let task_ctx = prepare_task_ctx(batch_size, false);
            let left = TestMemoryExec::try_new_exec(
                &[vec![build.clone()]],
                build.schema(),
                None,
            )?;
            let right =
                TestMemoryExec::try_new_exec(&[probe.to_vec()], probe[0].schema(), None)?;
            let on = ["id", "g"]
                .into_iter()
                .map(|name| {
                    Ok((
                        Arc::new(Column::new_with_schema(name, &left.schema())?) as _,
                        Arc::new(Column::new_with_schema(name, &right.schema())?) as _,
                    ))
                })
                .collect::<Result<JoinOn>>()?;
            let join = try_new_scalar_not_in(
                left,
                right,
                on,
                None,
                join_type,
                PartitionMode::CollectLeft,
            )?;
            let batches = common::collect(join.execute(0, task_ctx)?).await?;
            results.push(batches_to_sort_string(&batches));
        }

        allow_duplicates! {
            assert_snapshot!(results.join("\n"), @r"
            +----+---+
            | id | g |
            +----+---+
            |    | 3 |
            +----+---+
            +----+---+-------+
            | id | g | mark  |
            +----+---+-------+
            |    | 1 |       |
            |    | 2 |       |
            |    | 3 | false |
            +----+---+-------+
            +----+---+
            | id | g |
            +----+---+
            | 9  | 4 |
            +----+---+
            ");
        }
        Ok(())
    }

    /// Correlated null-aware `LeftAnti` whose two scope keys are Float64, with
    /// `-0.0` on the build side and `0.0` on the probe side. Both scopes must
    /// still match in every direction: the full key lookup, NULL probe values
    /// against all build rows, and NULL build values against the probe rows.
    #[apply(hash_join_exec_configs)]
    #[tokio::test]
    async fn test_null_aware_left_anti_float_scope_negative_zero(
        batch_size: usize,
    ) -> Result<()> {
        let task_ctx = prepare_task_ctx(batch_size, false);

        fn table(
            id: Vec<Option<i32>>,
            g1: Vec<f64>,
            g2: Vec<f64>,
        ) -> Arc<dyn ExecutionPlan> {
            let schema = Arc::new(Schema::new(vec![
                Field::new("id", DataType::Int32, true),
                Field::new("g1", DataType::Float64, true),
                Field::new("g2", DataType::Float64, true),
            ]));
            let batch = RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(id)),
                    Arc::new(Float64Array::from(g1)),
                    Arc::new(Float64Array::from(g2)),
                ],
            )
            .unwrap();
            TestMemoryExec::try_new_exec(&[vec![batch]], schema, None).unwrap()
        }

        let left = table(
            vec![Some(1), Some(3), None, Some(4), Some(5), None, Some(6)],
            vec![-0.0, -0.0, -0.0, 2.0, -0.0, 3.0, 2.0],
            vec![1.0, 1.0, 1.0, -0.0, -0.0, -0.0, 1.0],
        );
        let right = table(
            vec![Some(1), Some(2), None, Some(7)],
            vec![0.0, 0.0, 2.0, 2.0],
            vec![1.0, 1.0, 0.0, 1.0],
        );

        let on = ["id", "g1", "g2"]
            .into_iter()
            .map(|name| {
                Ok((
                    Arc::new(Column::new_with_schema(name, &left.schema())?) as _,
                    Arc::new(Column::new_with_schema(name, &right.schema())?) as _,
                ))
            })
            .collect::<Result<JoinOn>>()?;

        let join = try_new_scalar_not_in(
            left,
            right,
            on,
            None,
            JoinType::LeftAnti,
            PartitionMode::CollectLeft,
        )?;

        let stream = join.execute(0, task_ctx)?;
        let batches = common::collect(stream).await?;

        // Scope (0, 1) holds 1 and 2: `1` matches and is dropped, `3` is kept,
        // and the NULL build value there is UNKNOWN. Scope (2, 0) holds a
        // NULL probe value, so `4` is UNKNOWN. Scopes (0, 0) and (3, 0) are
        // empty, so `5` and the NULL build value in (3, 0) are kept. Scope
        // (2, 1) holds only 7, so `6` is kept.
        allow_duplicates! {
            assert_snapshot!(batches_to_sort_string(&batches), @r"
            +----+------+------+
            | id | g1   | g2   |
            +----+------+------+
            |    | 3.0  | -0.0 |
            | 3  | -0.0 | 1.0  |
            | 5  | -0.0 | -0.0 |
            | 6  | 2.0  | 1.0  |
            +----+------+------+
            ");
        }

        Ok(())
    }

    #[test]
    fn test_lr_is_preserved() {
        assert_eq!(lr_is_preserved(JoinType::Inner), (true, true));
        assert_eq!(lr_is_preserved(JoinType::Left), (true, false));
        assert_eq!(lr_is_preserved(JoinType::Right), (false, true));
        assert_eq!(lr_is_preserved(JoinType::Full), (false, false));
        assert_eq!(lr_is_preserved(JoinType::LeftSemi), (true, true));
        assert_eq!(lr_is_preserved(JoinType::LeftAnti), (true, false));
        assert_eq!(lr_is_preserved(JoinType::LeftMark), (true, false));
        assert_eq!(lr_is_preserved(JoinType::RightSemi), (true, true));
        assert_eq!(lr_is_preserved(JoinType::RightAnti), (false, true));
        assert_eq!(lr_is_preserved(JoinType::RightMark), (false, true));
    }

    #[test]
    fn test_with_dynamic_filter() -> Result<()> {
        let (_, _, on) = build_schema_and_on()?;
        let left = build_table(("a1", &vec![1]), ("b1", &vec![1]), ("c1", &vec![1]));
        let right = build_table(("a2", &vec![1]), ("b1", &vec![1]), ("c2", &vec![1]));

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::Inner,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            false,
        )?;
        assert!(join.dynamic_expressions_produced().is_empty());

        let df = Arc::new(DynamicFilterPhysicalExpr::new(
            vec![Arc::new(Column::new("b1", 1)) as _],
            lit(true),
        ));
        let join = join.set_dynamic_filter(Arc::clone(&df))?;

        let produced = join.dynamic_expressions_produced();
        assert_eq!(produced.len(), 1);
        assert_eq!(
            produced[0]
                .expression_id()
                .expect("DynamicFilterPhysicalExpr always has an expression_id"),
            df.expression_id()
                .expect("DynamicFilterPhysicalExpr always has an expression_id"),
        );
        Ok(())
    }

    #[test]
    fn test_swap_inputs_rejects_dynamic_filter() -> Result<()> {
        let left = build_table(
            ("l_key", &vec![1]),
            ("l_payload", &vec![10]),
            ("l_other", &vec![100]),
        );
        let right = build_table(
            ("r_payload", &vec![20]),
            ("r_key", &vec![1]),
            ("r_other", &vec![200]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("l_key", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("r_key", &right.schema())?) as _,
        )];

        let dynamic_filter = HashJoinExec::create_dynamic_filter(&on);
        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftSemi,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            false,
        )?
        .set_dynamic_filter(dynamic_filter)?;

        let err = join.swap_inputs(PartitionMode::CollectLeft).unwrap_err();
        assert_contains!(
            err.to_string(),
            "Cannot swap HashJoinExec inputs after dynamic filters have been constructed"
        );
        Ok(())
    }

    #[test]
    fn test_dynamic_filter_pushdown_allowed_for_null_equal_join() -> Result<()> {
        let (_, _, on) = build_schema_and_on()?;
        let left = build_table(("a1", &vec![1]), ("b1", &vec![1]), ("c1", &vec![1]));
        let right = build_table(("a2", &vec![1]), ("b1", &vec![1]), ("c2", &vec![1]));

        let mut session_config = SessionConfig::default();
        session_config
            .options_mut()
            .optimizer
            .enable_join_dynamic_filter_pushdown = true;

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::RightSemi,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNull,
            false,
        )?;

        // Null-equal joins keep dynamic filter pushdown: the pushed predicate carries an
        // `IS NULL` disjunct so a probe-side NULL still reaches the join.
        assert!(join.allow_join_dynamic_filter_pushdown(session_config.options()));

        Ok(())
    }

    #[test]
    fn test_dynamic_filter_pushdown_rejects_null_aware_nullable_build_key() -> Result<()>
    {
        let left = build_table_two_cols(
            ("a1", &vec![Some(1), None]),
            ("b1", &vec![Some(1), Some(2)]),
        );
        let right = build_table_two_cols(
            ("a2", &vec![Some(2), Some(3)]),
            ("b2", &vec![Some(1), Some(2)]),
        );
        let on = vec![(
            Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
        )];

        let mut session_config = SessionConfig::default();
        session_config
            .options_mut()
            .optimizer
            .enable_join_dynamic_filter_pushdown = true;

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        assert!(!join.allow_join_dynamic_filter_pushdown(session_config.options()));

        Ok(())
    }

    #[test]
    fn test_dynamic_filter_pushdown_allows_null_aware_non_null_build_key() -> Result<()> {
        // A NOT NULL build key cannot surface a build-side NULL, so the
        // pushdown must stay enabled.
        let left = build_table(("a1", &vec![1]), ("b1", &vec![1]), ("c1", &vec![1]));
        let right = build_table(("a2", &vec![2]), ("b2", &vec![2]), ("c2", &vec![2]));
        let on = vec![(
            Arc::new(Column::new_with_schema("a1", &left.schema())?) as _,
            Arc::new(Column::new_with_schema("a2", &right.schema())?) as _,
        )];

        let mut session_config = SessionConfig::default();
        session_config
            .options_mut()
            .optimizer
            .enable_join_dynamic_filter_pushdown = true;

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::LeftAnti,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            true,
        )?;

        assert!(join.allow_join_dynamic_filter_pushdown(session_config.options()));

        Ok(())
    }

    fn range_partitioned_dynamic_filter_test_join(
        left_split: i32,
        right_split: i32,
    ) -> Result<(HashJoinExec, JoinOn)> {
        let (left_schema, right_schema, on) = build_schema_and_on()?;
        let left_partitioning = Partitioning::Range(RangePartitioning::try_new(
            [PhysicalSortExpr {
                expr: Arc::clone(&on[0].0),
                options: Default::default(),
            }]
            .into(),
            vec![SplitPoint::new(vec![ScalarValue::Int32(Some(left_split))])],
        )?);
        let right_partitioning = Partitioning::Range(RangePartitioning::try_new(
            [PhysicalSortExpr {
                expr: Arc::clone(&on[0].1),
                options: Default::default(),
            }]
            .into(),
            vec![SplitPoint::new(vec![ScalarValue::Int32(Some(right_split))])],
        )?);
        let left = Arc::new(PartitionedTestExec::try_new(
            left_schema,
            left_partitioning,
        )?);
        let right = Arc::new(PartitionedTestExec::try_new(
            right_schema,
            right_partitioning,
        )?);

        let join = HashJoinExec::try_new(
            left,
            right,
            on.clone(),
            None,
            &JoinType::Inner,
            None,
            PartitionMode::Partitioned,
            NullEquality::NullEqualsNothing,
            false,
        )?;
        Ok((join, on))
    }

    fn with_hash_partitioned_children(
        join: &HashJoinExec,
        on: &JoinOn,
    ) -> Result<HashJoinExec> {
        join.builder()
            .with_new_children(vec![
                Arc::new(PartitionedTestExec::try_new(
                    join.left().schema(),
                    Partitioning::Hash(vec![Arc::clone(&on[0].0)], 2),
                )?),
                Arc::new(PartitionedTestExec::try_new(
                    join.right().schema(),
                    Partitioning::Hash(vec![Arc::clone(&on[0].1)], 2),
                )?),
            ])?
            .build()
    }

    #[test]
    fn test_partitioned_dynamic_filter_pushdown_allows_supported_partitioning()
    -> Result<()> {
        let (range_join, on) = range_partitioned_dynamic_filter_test_join(10, 10)?;
        let hash_join = with_hash_partitioned_children(&range_join, &on)?;
        let mut session_config = SessionConfig::default();
        session_config
            .options_mut()
            .optimizer
            .enable_join_dynamic_filter_pushdown = true;

        assert!(range_join.allow_join_dynamic_filter_pushdown(session_config.options()));
        assert!(hash_join.allow_join_dynamic_filter_pushdown(session_config.options()));

        session_config
            .options_mut()
            .optimizer
            .preserve_file_partitions = 1;
        assert!(range_join.allow_join_dynamic_filter_pushdown(session_config.options()));

        Ok(())
    }

    #[test]
    fn test_partitioned_dynamic_filter_pushdown_rejects_unsupported_partitioning()
    -> Result<()> {
        let (range_join, on) = range_partitioned_dynamic_filter_test_join(10, 10)?;
        let hash_join = with_hash_partitioned_children(&range_join, &on)?;
        let (mismatched_range_join, _) =
            range_partitioned_dynamic_filter_test_join(10, 11)?;
        let mut session_config = SessionConfig::default();
        session_config
            .options_mut()
            .optimizer
            .enable_join_dynamic_filter_pushdown = true;

        assert!(
            !mismatched_range_join
                .allow_join_dynamic_filter_pushdown(session_config.options())
        );

        session_config
            .options_mut()
            .optimizer
            .preserve_file_partitions = 1;
        assert!(!hash_join.allow_join_dynamic_filter_pushdown(session_config.options()));

        Ok(())
    }

    #[test]
    fn test_with_dynamic_filter_rejects_invalid_columns() -> Result<()> {
        let (_, _, on) = build_schema_and_on()?;
        let left = build_table(("a1", &vec![1]), ("b1", &vec![1]), ("c1", &vec![1]));
        let right = build_table(("a2", &vec![1]), ("b1", &vec![1]), ("c2", &vec![1]));

        let join = HashJoinExec::try_new(
            left,
            right,
            on,
            None,
            &JoinType::Inner,
            None,
            PartitionMode::CollectLeft,
            NullEquality::NullEqualsNothing,
            false,
        )?;

        // Column index 99 is out of bounds for the right (probe) side schema.
        let df = Arc::new(DynamicFilterPhysicalExpr::new(
            vec![Arc::new(Column::new("bad", 99)) as _],
            lit(true),
        ));
        assert!(join.set_dynamic_filter(df).is_err());
        Ok(())
    }
    fn fallback_inputs() -> Result<(Arc<dyn ExecutionPlan>, Arc<dyn ExecutionPlan>)> {
        let side = |offset: i32| {
            let batches = (0..32)
                .map(|i| {
                    let ids: Vec<i32> = (i * 16..(i + 1) * 16).collect();
                    let keys: Vec<i32> = ids.iter().map(|id| id % 47 + offset).collect();
                    build_table_i32(("id", &ids), ("key", &keys), ("value", &ids))
                })
                .collect::<Vec<_>>();
            TestMemoryExec::try_new_exec(
                std::slice::from_ref(&batches),
                batches[0].schema(),
                None,
            )
            .map(|exec| exec as Arc<dyn ExecutionPlan>)
        };
        Ok((side(0)?, side(5)?))
    }

    fn fallback_context(limit: Option<usize>) -> Arc<TaskContext> {
        let mut runtime = RuntimeEnvBuilder::new();
        if let Some(limit) = limit {
            runtime = runtime.with_memory_limit(limit, 1.0);
        }
        Arc::new(
            TaskContext::default()
                .with_session_config(
                    SessionConfig::default()
                        .with_batch_size(16)
                        .with_sort_spill_reservation_bytes(0),
                )
                .with_runtime(runtime.build_arc().unwrap()),
        )
    }

    fn fallback_join(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        join_type: JoinType,
    ) -> Result<HashJoinExec> {
        HashJoinExecBuilder::new(
            left,
            right,
            vec![(
                Arc::new(Column::new("key", 1)),
                Arc::new(Column::new("key", 1)),
            )],
            join_type,
        )
        .with_partition_mode(PartitionMode::Partitioned)
        .build()
    }

    #[tokio::test]
    async fn partitioned_join_memory_limit() -> Result<()> {
        let (left, right) = fallback_inputs()?;
        let reference =
            fallback_join(Arc::clone(&left), Arc::clone(&right), JoinType::Inner)?;
        let expected =
            common::collect(reference.execute(0, fallback_context(None))?).await?;
        assert!(!expected.is_empty());
        let join = fallback_join(left, right, JoinType::Inner)?;
        let error = common::collect(join.execute(0, fallback_context(Some(4 * 1024)))?)
            .await
            .unwrap_err();
        assert_contains!(error.to_string(), "Resources exhausted");
        Ok(())
    }

    #[tokio::test]
    async fn sort_merge_fallback_preserves_promised_ordering() -> Result<()> {
        let (left, right) = fallback_inputs()?;
        let right = Arc::new(crate::sorts::sort::SortExec::new(
            [PhysicalSortExpr::new_default(Arc::new(Column::new(
                "id", 0,
            )))]
            .into(),
            right,
        ));
        let join = fallback_join(left, right, JoinType::Inner)?;
        assert!(join.properties().output_ordering().is_some());
        let error = common::collect(join.execute(0, fallback_context(Some(4096)))?)
            .await
            .unwrap_err();
        assert_contains!(error.to_string(), "Resources exhausted");
        Ok(())
    }

    #[tokio::test]
    async fn memory_limited_join_keeps_streaming_inputs() -> Result<()> {
        let (left, right) = fallback_inputs()?;
        let batches = common::collect(right.execute(0, fallback_context(None))?).await?;
        let right: Arc<dyn ExecutionPlan> =
            Arc::new(crate::streaming::StreamingTableExec::try_new(
                right.schema(),
                vec![Arc::new(
                    crate::test::TestPartitionStream::new_with_batches(batches),
                )],
                None,
                [],
                true,
                None,
            )?);
        // A hash join can stream this probe. A fallback must not turn it into a
        // sort that waits forever for an unbounded source to finish.
        assert!(right.boundedness().is_unbounded());
        let join = fallback_join(left, right, JoinType::Inner)?;
        let error = common::collect(join.execute(0, fallback_context(Some(4096)))?)
            .await
            .unwrap_err();
        assert_contains!(error.to_string(), "Resources exhausted");
        Ok(())
    }
}