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
// 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

//! [`NestedLoopJoinExec`]: joins without equijoin (equality predicates).

use std::fmt::Formatter;
use std::ops::{BitOr, ControlFlow};
use std::sync::Arc;
use std::task::Poll;

use super::utils::{
    asymmetric_join_output_partitioning, need_produce_result_in_final,
    reorder_output_after_swap, swap_join_projection,
};
use crate::common::can_project;
use crate::execution_plan::{EmissionType, boundedness_from_children};
use crate::filter_pushdown::{
    ChildFilterDescription, FilterDescription, FilterPushdownPhase, PushedDownPredicate,
};
use crate::joins::SharedBitmapBuilder;
use crate::joins::logical_batch::{BatchRow, LogicalBatch, RowIndices};
use crate::joins::probe_completion::{Completion, ProbeCompletion};
use crate::joins::utils::{
    BuildProbeJoinMetrics, ColumnIndex, JoinFilter, OnceAsync, OnceFut,
    boolean_mask_from_filter, build_join_schema, check_join_is_valid,
    estimate_join_statistics, need_produce_right_in_final,
};
use crate::metrics::{
    Count, ExecutionPlanMetricsSet, MetricBuilder, MetricType, MetricsSet, RatioMetrics,
    Time,
};
use crate::projection::{
    EmbeddedProjection, JoinData, ProjectionExec, try_embed_projection,
    try_pushdown_through_join_with_column_indices,
};
use crate::statistics::{ChildStats, StatisticsArgs};
use crate::{
    ChildrenPropertiesMode, DisplayAs, DisplayFormatType, Distribution, ExecutionPlan,
    ExecutionPlanProperties, PlanProperties, RecordBatchStream, ReplaceChildrenOptions,
    SendableRecordBatchStream, validate_child_count,
};

use arrow::array::{
    Array, BooleanArray, BooleanBufferBuilder, RecordBatchOptions, UInt32Array,
    UInt64Array, new_null_array,
};
use arrow::buffer::BooleanBuffer;
use arrow::compute::{
    BatchCoalescer, filter, filter_record_batch, not, take, take_record_batch,
};
use arrow::datatypes::{Schema, SchemaRef};
use arrow::record_batch::RecordBatch;
use arrow::util::bit_iterator::BitIndexIterator;
use arrow_schema::DataType;
use datafusion_common::cast::as_boolean_array;
use datafusion_common::config::ConfigOptions;
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::{
    DataFusionError, JoinSide, NullEquality, Result, ScalarValue, SharedResult,
    Statistics, arrow_err, assert_eq_or_internal_err, internal_datafusion_err,
    internal_err, project_schema, unwrap_or_internal_err,
};
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
use datafusion_execution::{SpillFile, TaskContext};
use datafusion_expr::JoinType;
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr::equivalence::{
    ProjectionMapping, join_equivalence_properties,
};
use datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr;

use datafusion_physical_expr::projection::{ProjectionRef, combine_projections};
use futures::future::{BoxFuture, Shared};
use futures::{FutureExt, Stream, StreamExt};
use log::debug;
use parking_lot::Mutex;

use crate::metrics::SpillMetrics;
use crate::spill::replayable_spill_input::ReplayableStreamSource;
use crate::spill::spill_manager::SpillManager;

#[expect(rustdoc::private_intra_doc_links)]
/// NestedLoopJoinExec is a build-probe join operator designed for joins that
/// do not have equijoin keys in their `ON` clause.
///
/// # Execution Flow
///
/// ```text
///                                                Incoming right batch
///                Left Side Buffered Batches
///                       ┌───────────┐              ┌───────────────┐
///                       │ ┌───────┐ │              │               │
///                       │ │       │ │              │               │
///  Current Left Row ───▶│ ├───────├─┤──────────┐   │               │
///                       │ │       │ │          │   └───────────────┘
///                       │ │       │ │          │           │
///                       │ │       │ │          │           │
///                       │ └───────┘ │          │           │
///                       │ ┌───────┐ │          │           │
///                       │ │       │ │          │     ┌─────┘
///                       │ │       │ │          │     │
///                       │ │       │ │          │     │
///                       │ │       │ │          │     │
///                       │ │       │ │          │     │
///                       │ └───────┘ │          ▼     ▼
///                       │   ......  │  ┌──────────────────────┐
///                       │           │  │X (Cartesian Product) │
///                       │           │  └──────────┬───────────┘
///                       └───────────┘             │
///                                                 │
///                                                 ▼
///                                      ┌───────┬───────────────┐
///                                      │       │               │
///                                      │       │               │
///                                      │       │               │
///                                      └───────┴───────────────┘
///                                        Intermediate Batch
///                                  (For join predicate evaluation)
/// ```
///
/// The execution follows a two-phase design:
///
/// ## 1. Buffering Left Input
/// - The operator eagerly buffers all left-side input batches into memory,
///   util a memory limit is reached. The batches are kept as they arrive and
///   addressed as one contiguous batch (see `LogicalBatch`), so buffering
///   does not copy them into a merged batch.
///   Currently, an out-of-memory error will be thrown if all the left-side input batches
///   cannot fit into memory at once.
///   In the future, it's possible to make this case finish execution. (see
///   'Memory-limited Execution' section)
/// - The rationale for buffering the left side is that scanning the right side
///   can be expensive (e.g., decoding Parquet files), so buffering more left
///   rows reduces the number of right-side scan passes required.
///
/// ## 2. Probing Right Input
/// - Right-side input is streamed batch by batch.
/// - For each right-side batch:
///   - It evaluates the join filter against the full buffered left input.
///     This results in a Cartesian product between the right batch and each
///     left row -- with the join predicate/filter applied -- for each inner
///     loop iteration.
///   - Matched results are accumulated into an output buffer. (see more in
///     `Output Buffering Strategy` section)
/// - This process continues until all right-side input is consumed.
///
/// # Producing unmatched build-side data
/// - For special join types like left/full joins, it's required to also output
///   unmatched pairs. During execution, bitmaps are kept for both left and right
///   sides of the input; they'll be handled by dedicated states in `NLJStream`.
/// - The final output of the left side unmatched rows is handled by a single
///   partition for simplicity, since it only counts a small portion of the
///   execution time. (e.g. if probe side has 10k rows, the final output of
///   unmatched build side only roughly counts for 1/10k of the total time)
///
/// # Output Buffering Strategy
/// The operator uses an intermediate output buffer to accumulate results. Once
/// the output threshold is reached (currently set to the same value as
/// `batch_size` in the configuration), the results will be eagerly output.
///
/// # Extra Notes
/// - The operator always considers the **left** side as the build (buffered) side.
///   Therefore, the physical optimizer should assign the smaller input to the left.
/// - The design try to minimize the intermediate data size to approximately
///   1 batch, for better cache locality and memory efficiency.
///
/// # Memory-limited Execution
/// When the memory budget is exceeded during left-side buffering, the operator
/// falls back to a multi-pass strategy:
/// 1. Buffer as many left rows as fit in memory (one "chunk")
/// 2. On the first pass, the right side is both processed and spilled to disk
/// 3. For each subsequent left chunk, the right side is re-read from the spill file
///
/// The fallback is triggered automatically when the initial in-memory load
/// fails with `ResourcesExhausted` and disk spilling is available. The left
/// child is executed once and spilled to one file during that same load, and
/// each output partition spills its own right input.
///
/// Re-reading the right side once per left chunk is the cost of the fallback,
/// so chunks should be as large as memory allows. All output partitions
/// therefore share one chunk at a time, which is as large as it gets, and move
/// on to the next one together (see [`LeftChunkBarrier`]).
///
/// All join types are supported, and both sides defer their unmatched rows
/// until every chunk has been probed:
/// - For RIGHT/FULL/RIGHT SEMI/RIGHT ANTI/RIGHT MARK joins, each partition
///   keeps a global right-side bitmap (indexed by right batch sequence number)
///   that accumulates matches across all left chunks. After the last left
///   chunk, the right side is replayed one more time to emit unmatched right
///   rows using the accumulated bitmap.
/// - For LEFT/FULL/LEFT SEMI/LEFT ANTI/LEFT MARK joins, one global left-side
///   bitmap (one bit per spilled left row, see [`LeftSpillData`]) is shared by
///   all partitions. Each partition merges a chunk's matches into it when it
///   finishes the chunk, and the last partition to finish streams the left
///   spill file once more to emit the final left rows, the same way the
///   in-memory path elects a single partition for that step.
///
/// Tracking issue: <https://github.com/apache/datafusion/issues/15760>
///
/// # 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`]
#[derive(Debug)]
pub struct NestedLoopJoinExec {
    /// left side
    pub(crate) left: Arc<dyn ExecutionPlan>,
    /// right side
    pub(crate) right: Arc<dyn ExecutionPlan>,
    /// Filters which are applied while finding matching rows
    pub(crate) filter: Option<JoinFilter>,
    /// How the join is performed
    pub(crate) join_type: JoinType,
    /// The full concatenated schema of left and right children should be distinct from
    /// the output schema of the operator
    join_schema: SchemaRef,
    /// Future that consumes left input and buffers it in memory
    ///
    /// This structure is *shared* across all output streams.
    ///
    /// Each output stream waits on the `OnceAsync` to signal the completion of
    /// the build(left) side data, and buffer them all for later joining.
    build_side_data: OnceAsync<LeftLoad>,
    /// Paces the output streams through the left chunks when the left side is
    /// spilled. *Shared* across all output streams, like `build_side_data`.
    left_chunk_barrier: Arc<LeftChunkBarrier>,
    /// Information of index and left / right placement of columns
    column_indices: Vec<ColumnIndex>,
    /// Projection to apply to the output of the join
    projection: Option<ProjectionRef>,

    /// Execution metrics
    metrics: ExecutionPlanMetricsSet,
    /// Cache holding plan properties like equivalences, output partitioning etc.
    cache: Arc<PlanProperties>,
}

/// Helps to build [`NestedLoopJoinExec`].
pub struct NestedLoopJoinExecBuilder {
    left: Arc<dyn ExecutionPlan>,
    right: Arc<dyn ExecutionPlan>,
    join_type: JoinType,
    filter: Option<JoinFilter>,
    projection: Option<ProjectionRef>,
}

impl NestedLoopJoinExecBuilder {
    /// Make a new [`NestedLoopJoinExecBuilder`].
    pub fn new(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        join_type: JoinType,
    ) -> Self {
        Self {
            left,
            right,
            join_type,
            filter: None,
            projection: None,
        }
    }

    /// 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.projection = projection;
        self
    }

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

    /// Build resulting execution plan.
    pub fn build(self) -> Result<NestedLoopJoinExec> {
        let Self {
            left,
            right,
            join_type,
            filter,
            projection,
        } = self;

        let left_schema = left.schema();
        let right_schema = right.schema();
        check_join_is_valid(&left_schema, &right_schema, &[])?;
        let (join_schema, column_indices) =
            build_join_schema(&left_schema, &right_schema, &join_type);
        let join_schema = Arc::new(join_schema);
        let cache = NestedLoopJoinExec::compute_properties(
            &left,
            &right,
            &join_schema,
            join_type,
            projection.as_deref(),
        )?;
        let left_chunk_barrier = Arc::new(LeftChunkBarrier::new(
            right.output_partitioning().partition_count(),
        ));
        Ok(NestedLoopJoinExec {
            left,
            right,
            filter,
            join_type,
            join_schema,
            build_side_data: Default::default(),
            left_chunk_barrier,
            column_indices,
            projection,
            metrics: Default::default(),
            cache: Arc::new(cache),
        })
    }
}

impl From<&NestedLoopJoinExec> for NestedLoopJoinExecBuilder {
    fn from(exec: &NestedLoopJoinExec) -> Self {
        Self {
            left: Arc::clone(exec.left()),
            right: Arc::clone(exec.right()),
            join_type: exec.join_type,
            filter: exec.filter.clone(),
            projection: exec.projection.clone(),
        }
    }
}

impl NestedLoopJoinExec {
    /// Try to create a new [`NestedLoopJoinExec`]
    pub fn try_new(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        filter: Option<JoinFilter>,
        join_type: &JoinType,
        projection: Option<Vec<usize>>,
    ) -> Result<Self> {
        NestedLoopJoinExecBuilder::new(left, right, *join_type)
            .with_projection(projection)
            .with_filter(filter)
            .build()
    }

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

    /// right side
    pub fn right(&self) -> &Arc<dyn ExecutionPlan> {
        &self.right
    }

    /// 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
    }

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

    /// 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,
        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),
            None,
            // No on columns in nested loop join
            &[],
        )?;

        let mut output_partitioning =
            asymmetric_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 {
                match join_type {
                    // If we only need to generate matched rows from the probe side,
                    // we can emit rows incrementally.
                    JoinType::Inner
                    | JoinType::LeftSemi
                    | JoinType::RightSemi
                    | JoinType::Right
                    | JoinType::RightAnti
                    | JoinType::RightMark => EmissionType::Incremental,
                    // If we need to generate unmatched rows from the *build side*,
                    // we need to emit them at the end.
                    JoinType::Left
                    | JoinType::LeftAnti
                    | JoinType::LeftMark
                    | JoinType::Full => EmissionType::Both,
                }
            } else {
                right.pipeline_behavior()
            };

        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]),
        ))
    }

    /// This join implementation does not preserve the input order of either side.
    fn maintains_input_order(_join_type: JoinType) -> Vec<bool> {
        vec![false, false]
    }

    pub fn contains_projection(&self) -> bool {
        self.projection.is_some()
    }

    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())?;
        NestedLoopJoinExecBuilder::from(self)
            .with_projection_ref(projection)
            .build()
    }

    /// Returns a new `ExecutionPlan` that runs NestedLoopsJoins with the left
    /// and right inputs swapped.
    ///
    /// # Notes:
    ///
    /// This function should be called BEFORE inserting any repartitioning
    /// operators on the join's children. Check [`super::HashJoinExec::swap_inputs`]
    /// for more details.
    ///
    /// # 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) -> Result<Arc<dyn ExecutionPlan>> {
        let left = self.left();
        let right = self.right();
        let new_join = NestedLoopJoinExecBuilder::new(
            Arc::clone(right),
            Arc::clone(left),
            self.join_type().swap(),
        )
        .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(),
        ))
        .build()?;

        // For Semi/Anti joins, swap result will produce same output schema,
        // no need to wrap them into additional projection
        let plan: Arc<dyn ExecutionPlan> = if matches!(
            self.join_type(),
            JoinType::LeftSemi
                | JoinType::RightSemi
                | JoinType::LeftAnti
                | JoinType::RightAnti
                | JoinType::LeftMark
                | JoinType::RightMark
        ) || self.projection.is_some()
        {
            Arc::new(new_join)
        } else {
            reorder_output_after_swap(
                Arc::new(new_join),
                &self.left().schema(),
                &self.right().schema(),
            )?
        };

        Ok(plan)
    }
}

impl DisplayAs for NestedLoopJoinExec {
    fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> std::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()
                };
                write!(
                    f,
                    "NestedLoopJoinExec: join_type={:?}{}{}",
                    self.join_type, display_filter, display_projections
                )
            }
            DisplayFormatType::TreeRender => {
                if *self.join_type() != JoinType::Inner {
                    writeln!(f, "join_type={:?}", self.join_type)
                } else {
                    Ok(())
                }
            }
        }
    }
}

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

    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) -> crate::InputDistributionRequirements {
        crate::InputDistributionRequirements::new(vec![
            Distribution::SinglePartition,
            Distribution::UnspecifiedDistribution,
        ])
    }

    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> {
        // Apply to join filter expressions if present
        crate::apply_expression_roots(
            self.filter.iter().map(|filter| filter.expression()),
            f,
        )
    }

    fn replace_children(
        self: Arc<Self>,
        mut children: Vec<Arc<dyn ExecutionPlan>>,
        options: ReplaceChildrenOptions,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        validate_child_count!(self, children);
        match options.children_properties {
            ChildrenPropertiesMode::Keep => {
                let left = children.swap_remove(0);
                let right = children.swap_remove(0);
                // Counts the partitions of the right child, so it is built for
                // the new one rather than shared with `self`.
                let left_chunk_barrier = Arc::new(LeftChunkBarrier::new(
                    right.output_partitioning().partition_count(),
                ));
                Ok(Arc::new(Self {
                    left,
                    right,
                    metrics: ExecutionPlanMetricsSet::new(),
                    build_side_data: Default::default(),
                    left_chunk_barrier,
                    cache: Arc::clone(&self.cache),
                    filter: self.filter.clone(),
                    join_type: self.join_type,
                    join_schema: Arc::clone(&self.join_schema),
                    column_indices: self.column_indices.clone(),
                    projection: self.projection.clone(),
                }))
            }
            ChildrenPropertiesMode::Recompute => Ok(Arc::new(
                NestedLoopJoinExecBuilder::new(
                    Arc::clone(&children[0]),
                    Arc::clone(&children[1]),
                    self.join_type,
                )
                .with_filter(self.filter.clone())
                .with_projection_ref(self.projection.clone())
                .build()?,
            )),
        }
    }

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

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

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        assert_eq_or_internal_err!(
            self.left.output_partitioning().partition_count(),
            1,
            "Invalid NestedLoopJoinExec, the output partition count of the left child must be 1,\
                 consider using CoalescePartitionsExec or the EnforceDistribution rule"
        );

        let metrics = NestedLoopJoinMetrics::new(&self.metrics, partition);
        let batch_size = context.session_config().batch_size();

        // 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 right_partition_count = self.right().output_partitioning().partition_count();

        // Always try to buffer all left data in memory via OnceFut. If it does not fit, the load
        // spills the left side during the same pass and the stream runs in memory-limited mode.
        let load_reservation =
            MemoryConsumer::new(format!("NestedLoopJoinLoad[{partition}]"))
                .register(context.memory_pool());

        // Determine if memory-limited mode is possible.
        // Conditions:
        // 1. Disk manager supports temp files (needed for spilling).
        // 2. Join types whose final emission reads the visited-left bitmap
        //    (LEFT, LEFT SEMI, LEFT ANTI, LEFT MARK, FULL) need that bitmap
        //    complete across every probe partition. The memory-limited path
        //    shares one global bitmap and one probe-thread counter, seeded
        //    with `right_partition_count`, through [`LeftSpillData`], exactly
        //    as the single-pass path does through [`JoinLeftData`].
        //
        //    That sharing assumes all right partitions run in the same
        //    process. A distributed engine executes each partition as an
        //    independent task with its own copy of the shared state, so the
        //    counter would never reach zero, and the partitions it never
        //    runs would be waited for at every left chunk (see
        //    [`LeftChunkBarrier`]). Such engines set
        //    `enable_nlj_coordinated_fallback = false` to opt out for the
        //    affected join types (left-emitting joins over a multi-partition
        //    right side), which then fail with resource exhaustion under
        //    memory pressure instead of stalling. Single-partition joins
        //    always keep the fallback, as do non-left-emitting ones.
        let coordinated_fallback_disabled = !context
            .session_config()
            .options()
            .execution
            .enable_nlj_coordinated_fallback
            && need_produce_result_in_final(self.join_type)
            && right_partition_count > 1;
        let can_spill = context.runtime_env().disk_manager.tmp_files_enabled()
            && !coordinated_fallback_disabled;

        let build_side_data = self.build_side_data.try_once(|| {
            let stream = self.left.execute(0, Arc::clone(&context))?;
            // Built here rather than on demand: by the time the load hits the memory limit the
            // stream is partly consumed, and it has to be spillable at that point without going
            // back to the left child.
            let left_spill_manager = can_spill.then(|| {
                SpillManager::new(
                    context.runtime_env(),
                    metrics.spill_metrics.clone(),
                    stream.schema(),
                )
                .with_compression_type(context.session_config().spill_compression())
            });

            Ok(collect_left_input(
                stream,
                metrics.join_metrics.clone(),
                load_reservation,
                need_produce_result_in_final(self.join_type),
                right_partition_count,
                left_spill_manager,
                Arc::clone(&self.left_chunk_barrier),
            ))
        })?;

        let probe_side_data = self.right.execute(partition, Arc::clone(&context))?;

        let spill_state = if can_spill {
            SpillState::Pending {
                task_context: Arc::clone(&context),
                partition,
                left_chunk_barrier: Arc::clone(&self.left_chunk_barrier),
            }
        } else {
            SpillState::Disabled
        };

        Ok(Box::pin(NestedLoopJoinStream::new(
            self.schema(),
            self.filter.clone(),
            self.join_type,
            probe_side_data,
            build_side_data,
            column_indices_after_projection,
            metrics,
            batch_size,
            spill_state,
        )))
    }

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

    fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
        // Left side is always broadcast, so it always needs overall stats.
        // Right side is partitioned, so it needs per-partition stats.
        vec![ChildStats::At(None), ChildStats::At(partition)]
    }

    fn statistics_from_inputs(
        &self,
        input_stats: &[Arc<Statistics>],
        _args: &StatisticsArgs,
    ) -> Result<Arc<Statistics>> {
        // NestedLoopJoinExec is designed for joins without equijoin keys in the
        // ON clause (e.g., `t1 JOIN t2 ON (t1.v1 + t2.v1) % 2 = 0`). Any join
        // predicates are stored in `self.filter`, but `estimate_join_statistics`
        // currently doesn't support selectivity estimation for such arbitrary
        // filter expressions. We pass an empty join column list, which means
        // the cardinality estimation cannot use column statistics and returns
        // unknown row counts.
        let join_columns = Vec::new();

        let left_stats = input_stats[0].as_ref().clone();
        let right_stats = input_stats[1].as_ref().clone();

        let stats = estimate_join_statistics(
            left_stats,
            right_stats,
            &join_columns,
            NullEquality::NullEqualsNothing,
            &self.join_type,
            &self.join_schema,
        )?;

        Ok(Arc::new(stats.project(self.projection.as_ref())))
    }

    fn gather_filters_for_pushdown(
        &self,
        phase: FilterPushdownPhase,
        parent_filters: Vec<Arc<dyn PhysicalExpr>>,
        config: &ConfigOptions,
    ) -> Result<FilterDescription> {
        if phase != FilterPushdownPhase::Post
            || !config.optimizer.enable_join_dynamic_filter_pushdown
        {
            return Ok(FilterDescription::new()
                .with_child(ChildFilterDescription::all_unsupported(&parent_filters))
                .with_child(ChildFilterDescription::all_unsupported(&parent_filters)));
        }

        // Removing rows from the non-preserved side of an outer or anti join
        // can create new unmatched rows. Only route filters to output-preserving
        // inputs; unlike a hash join, an NLJ has no equijoin keys to translate
        // filters onto the other input of a semi join.
        let (left_preserved, right_preserved) = match self.join_type {
            JoinType::Inner => (true, true),
            JoinType::Left
            | JoinType::LeftSemi
            | JoinType::LeftAnti
            | JoinType::LeftMark => (true, false),
            JoinType::Right
            | JoinType::RightSemi
            | JoinType::RightAnti
            | JoinType::RightMark => (false, true),
            JoinType::Full => (false, false),
        };
        let output_indices: Vec<_> = match &self.projection {
            Some(projection) => projection.to_vec(),
            None => (0..self.column_indices.len()).collect(),
        };
        let mut description = FilterDescription::new();
        for (side, preserved, child) in [
            (JoinSide::Left, left_preserved, self.left()),
            (JoinSide::Right, right_preserved, self.right()),
        ] {
            // Map positions explicitly: names can repeat within an input as
            // well as across the two sides of the join.
            let column_mapping = output_indices
                .iter()
                .enumerate()
                .filter_map(|(output, input)| {
                    let column = &self.column_indices[*input];
                    (column.side == side).then_some((output, column.index))
                })
                .collect();
            let mut child_description = if preserved {
                ChildFilterDescription::from_child_with_column_mapping(
                    &parent_filters,
                    column_mapping,
                    child,
                )?
            } else {
                ChildFilterDescription::all_unsupported(&parent_filters)
            };
            for (filter, pushed) in parent_filters
                .iter()
                .zip(&mut child_description.parent_filters)
            {
                if !filter.is::<DynamicFilterPhysicalExpr>() {
                    *pushed = PushedDownPredicate::unsupported(Arc::clone(filter));
                }
            }
            description = description.with_child(child_description);
        }
        Ok(description)
    }

    /// Tries to push `projection` down through `nested_loop_join`. If possible, performs the
    /// pushdown and returns a new [`NestedLoopJoinExec`] 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 NestedLoopJoinExec, 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);
        }

        let schema = self.schema();
        if let Some(JoinData {
            projected_left_child,
            projected_right_child,
            join_filter,
            ..
        }) = try_pushdown_through_join_with_column_indices(
            projection,
            self.left(),
            self.right(),
            &[],
            &schema,
            self.filter(),
            self.column_indices.as_slice(),
        )? {
            Ok(Some(Arc::new(
                NestedLoopJoinExecBuilder::new(
                    Arc::new(projected_left_child),
                    Arc::new(projected_right_child),
                    *self.join_type(),
                )
                .with_filter(join_filter)
                .build()?,
            )))
        } else {
            try_embed_projection(projection, self)
        }
    }
    #[cfg(feature = "proto")]
    fn try_to_proto(
        &self,
        ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
        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,
            filter,
            join_type,
            projection,
            // derived from the children's schemas by `try_new` on decode
            join_schema: _,
            // runtime build-side state, not part of the plan
            build_side_data: _,
            left_chunk_barrier: _,
            // recomputed by `try_new` on decode
            column_indices: _,
            // runtime metrics, not part of the plan
            metrics: _,
            // recomputed by `try_new` on decode
            cache: _,
        } = self;

        let left = ctx.encode_child(left)?;
        let right = ctx.encode_child(right)?;

        let join_type = crate::joins::proto::join_type_to_proto(*join_type);

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

        Ok(Some(protobuf::PhysicalPlanNode {
            physical_plan_type: Some(
                protobuf::physical_plan_node::PhysicalPlanType::NestedLoopJoin(Box::new(
                    protobuf::NestedLoopJoinExecNode {
                        left: Some(Box::new(left)),
                        right: Some(Box::new(right)),
                        join_type: join_type.into(),
                        filter,
                        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(),
                        },
                    },
                )),
            ),
        }))
    }
}

#[cfg(feature = "proto")]
impl NestedLoopJoinExec {
    pub fn try_from_proto(
        node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
        ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        use datafusion_proto_models::protobuf;

        let join = crate::expect_plan_variant!(
            node,
            protobuf::physical_plan_node::PhysicalPlanType::NestedLoopJoin,
            "NestedLoopJoinExec",
        );

        // Destructure exhaustively (no `..`) so that a newly added proto field
        // is a compile error here instead of being silently ignored.
        let protobuf::NestedLoopJoinExecNode {
            left,
            right,
            join_type,
            filter,
            projection,
        } = &**join;

        let left =
            ctx.decode_required_child(left.as_deref(), "NestedLoopJoinExec", "left")?;
        let right =
            ctx.decode_required_child(right.as_deref(), "NestedLoopJoinExec", "right")?;

        let join_type =
            crate::joins::proto::join_type_from_proto(*join_type, "NestedLoopJoinExec")?;

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

        let projection = match projection.as_slice() {
            [] => None,
            [u32::MAX] => Some(Vec::new()),
            indices => Some(indices.iter().map(|i| *i as usize).collect()),
        };

        Ok(Arc::new(NestedLoopJoinExec::try_new(
            left, right, filter, &join_type, projection,
        )?))
    }
}

/// Field-level tests for the `try_to_proto` / `try_from_proto` hooks.
///
/// `projection` carries the same three states as on `HashJoinExec`, encoded the
/// same way; the mapping is written out again here, so it is tested again here.
#[cfg(all(test, feature = "proto"))]
mod proto_tests {
    use super::*;
    use crate::proto::{ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx};
    use crate::proto_test_util::{
        StubPlanDecoder, StubPlanEncoder, UnreachablePlanDecoder, encoded_child_node,
        stub_child,
    };
    use datafusion_proto_models::protobuf;

    /// Encode an inner nested loop join with the given projection.
    fn encode_projection(projection: Option<Vec<usize>>) -> Vec<u32> {
        let plan = NestedLoopJoinExec::try_new(
            stub_child(),
            stub_child(),
            None,
            &JoinType::Inner,
            projection,
        )
        .unwrap();
        let encoder = StubPlanEncoder::ok();
        let ctx = ExecutionPlanEncodeCtx::new(&encoder);
        let node = plan
            .try_to_proto(&ctx)
            .unwrap()
            .expect("NestedLoopJoinExec should encode to Some(node)");
        match node.physical_plan_type {
            Some(protobuf::physical_plan_node::PhysicalPlanType::NestedLoopJoin(
                join,
            )) => join.projection,
            other => panic!("expected a NestedLoopJoin node, got {other:?}"),
        }
    }

    /// A hand-built `NestedLoopJoinExecNode` wrapped in its `PhysicalPlanNode`.
    fn join_node(projection: Vec<u32>) -> protobuf::PhysicalPlanNode {
        protobuf::PhysicalPlanNode {
            physical_plan_type: Some(
                protobuf::physical_plan_node::PhysicalPlanType::NestedLoopJoin(Box::new(
                    protobuf::NestedLoopJoinExecNode {
                        left: Some(Box::new(encoded_child_node())),
                        right: Some(Box::new(encoded_child_node())),
                        join_type: protobuf::JoinType::Inner.into(),
                        filter: None,
                        projection,
                    },
                )),
            ),
        }
    }

    /// Decode a node with the given projection field, returning the plan's
    /// reconstructed projection.
    fn decode_projection(projection: Vec<u32>) -> Option<Vec<usize>> {
        let decoder = StubPlanDecoder::ok();
        let ctx = ExecutionPlanDecodeCtx::new(&decoder);
        let plan =
            NestedLoopJoinExec::try_from_proto(&join_node(projection), &ctx).unwrap();
        plan.downcast_ref::<NestedLoopJoinExec>()
            .expect("decoded plan should be a NestedLoopJoinExec")
            .projection
            .as_ref()
            .map(|p| p.to_vec())
    }

    #[test]
    fn projection_states_survive_the_encode_side() {
        assert_eq!(encode_projection(None), Vec::<u32>::new());
        // An empty projection changes the output schema, so it must not share
        // the "absent" encoding.
        assert_eq!(encode_projection(Some(vec![])), vec![u32::MAX]);
        assert_eq!(encode_projection(Some(vec![0, 1])), vec![0, 1]);
    }

    #[test]
    fn projection_states_survive_the_decode_side() {
        assert_eq!(decode_projection(vec![]), None);
        assert_eq!(decode_projection(vec![u32::MAX]), Some(vec![]));
        assert_eq!(decode_projection(vec![0, 1]), Some(vec![0, 1]));
    }

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

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

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

/// Left (build-side) data
pub(crate) struct JoinLeftData {
    /// Build-side rows. See [`LogicalBatch`] for details on this layout
    /// and why it is used.
    batch: LogicalBatch,
    /// Shared bitmap builder for visited left indices
    bitmap: SharedBitmapBuilder,
    /// Memory reservation for tracking batch and bitmap
    /// Cleared on `JoinLeftData` drop
    /// reservation is cleared on Drop
    #[expect(dead_code)]
    reservation: MemoryReservation,
}

impl JoinLeftData {
    pub(crate) fn new(
        batch: LogicalBatch,
        bitmap: SharedBitmapBuilder,
        reservation: MemoryReservation,
    ) -> Self {
        Self {
            batch,
            bitmap,
            reservation,
        }
    }

    pub(crate) fn batch(&self) -> &LogicalBatch {
        &self.batch
    }

    pub(crate) fn bitmap(&self) -> &SharedBitmapBuilder {
        &self.bitmap
    }
}

/// Asynchronously collect the left input in a single pass over the stream.
///
/// The whole side is buffered in memory when it fits the budget. When it does not and
/// `spill_manager` is available, the batches collected so far and the rest of the same stream are
/// written to one spill file, which is what the memory-limited mode then reads in chunks. The
/// stream is consumed exactly once either way, so a left child that cannot be executed twice (or
/// replayed) stays correct.
async fn collect_left_input(
    mut stream: SendableRecordBatchStream,
    join_metrics: BuildProbeJoinMetrics,
    reservation: MemoryReservation,
    with_visited_left_side: bool,
    probe_threads_count: usize,
    spill_manager: Option<SpillManager>,
    left_chunk_barrier: Arc<LeftChunkBarrier>,
) -> Result<LeftLoad> {
    let schema = stream.schema();
    let metrics = join_metrics;
    let mut batches: Vec<RecordBatch> = Vec::new();

    while let Some(batch) = stream.next().await {
        let batch = batch?;
        let build_timer = metrics.build_time.timer();
        let batch_size = batch.get_array_memory_size();
        match reservation.try_grow(batch_size) {
            Ok(()) => {
                metrics.build_mem_used.add(batch_size);
                metrics.build_input_batches.add(1);
                metrics.build_input_rows.add(batch.num_rows());
                batches.push(batch);
            }
            Err(e) if is_spillable_oom(&e, spill_manager.as_ref()) => {
                // Do not keep the operator timer running while the spill path
                // drains the child stream.
                build_timer.done();
                let spill_manager = spill_manager.expect("checked by is_spillable_oom");
                let spilled = spill_left_input(
                    spill_manager,
                    batches,
                    Some(batch),
                    stream,
                    metrics,
                    &reservation,
                )
                .await?;
                return Ok(left_load_from_spill(
                    spilled,
                    schema,
                    with_visited_left_side,
                    probe_threads_count,
                    reservation,
                    &left_chunk_barrier,
                ));
            }
            Err(e) => return Err(e),
        }
    }

    // Only time the build-side materialization performed by this operator, not
    // polling the child stream above.
    let build_timer = metrics.build_time.timer();

    let buffered_build_batch = LogicalBatch::new(Arc::clone(&schema), batches)?;

    // Reserve memory for visited_left_side bitmap if required by join type
    let visited_left_side = if with_visited_left_side {
        let n_rows = buffered_build_batch.num_rows();
        let buffer_size = n_rows.div_ceil(8);
        match reservation.try_grow(buffer_size) {
            Ok(()) => {}
            Err(e) if is_spillable_oom(&e, spill_manager.as_ref()) => {
                // `spill_left_input` owns its timing and polls the input stream
                // outside that timer.
                build_timer.done();
                let spill_manager = spill_manager.expect("checked by is_spillable_oom");
                let spilled = spill_left_input(
                    spill_manager,
                    buffered_build_batch.into_batches(),
                    None,
                    stream,
                    metrics,
                    &reservation,
                )
                .await?;
                return Ok(left_load_from_spill(
                    spilled,
                    schema,
                    with_visited_left_side,
                    probe_threads_count,
                    reservation,
                    &left_chunk_barrier,
                ));
            }
            Err(e) => return Err(e),
        }
        metrics.build_mem_used.add(buffer_size);

        let mut buffer = BooleanBufferBuilder::new(n_rows);
        buffer.append_n(n_rows, false);
        buffer
    } else {
        BooleanBufferBuilder::new(0)
    };

    Ok(LeftLoad::InMemory {
        left_data: Arc::new(JoinLeftData::new(
            buffered_build_batch,
            Mutex::new(visited_left_side),
            reservation,
        )),
        probe_completion: Arc::new(ProbeCompletion::new(probe_threads_count)),
    })
}

/// A left side with no rows needs no spill file, so it stays on the in-memory path.
fn left_load_from_spill(
    spilled: Option<SpilledLeftFile>,
    schema: SchemaRef,
    with_visited_left_side: bool,
    probe_threads_count: usize,
    reservation: MemoryReservation,
    left_chunk_barrier: &LeftChunkBarrier,
) -> LeftLoad {
    match spilled {
        Some(spilled) => {
            let left_spill = Arc::new(LeftSpillData::new(
                spilled,
                schema,
                with_visited_left_side,
                probe_threads_count,
                reservation,
            ));
            left_chunk_barrier.register_left_spill(&left_spill);
            LeftLoad::Spilled(left_spill)
        }
        // No rows means no bitmap either, whatever the join type.
        None => LeftLoad::InMemory {
            left_data: Arc::new(JoinLeftData::new(
                LogicalBatch::new_empty(schema),
                Mutex::new(BooleanBufferBuilder::new(0)),
                reservation,
            )),
            probe_completion: Arc::new(ProbeCompletion::new(probe_threads_count)),
        },
    }
}

/// Whether a failed reservation is an exhausted pool that the caller can spill its way out of.
fn is_spillable_oom(
    error: &DataFusionError,
    spill_manager: Option<&SpillManager>,
) -> bool {
    spill_manager.is_some()
        && matches!(error.find_root(), DataFusionError::ResourcesExhausted(_))
}

/// Write the already-buffered left batches plus the remainder of the same stream to one spill file.
/// Returns `None` when the left side carried no rows at all, which needs no spill file.
async fn spill_left_input(
    spill_manager: SpillManager,
    buffered: Vec<RecordBatch>,
    pending: Option<RecordBatch>,
    mut stream: SendableRecordBatchStream,
    metrics: BuildProbeJoinMetrics,
    reservation: &MemoryReservation,
) -> Result<Option<SpilledLeftFile>> {
    let build_timer = metrics.build_time.timer();
    let mut spill_file =
        spill_manager.create_in_progress_file("NestedLoopJoin left spill")?;
    let mut num_rows = 0;

    for batch in buffered {
        if batch.num_rows() > 0 {
            num_rows += batch.num_rows();
            spill_file.append_batch(&batch)?;
        }
    }
    // The in-memory batches are spilled and dropped, so their reservation goes back to the pool
    // before the rest of the stream is drained.
    reservation.free();

    for batch in pending.into_iter() {
        if batch.num_rows() > 0 {
            metrics.build_input_batches.add(1);
            metrics.build_input_rows.add(batch.num_rows());
            num_rows += batch.num_rows();
            spill_file.append_batch(&batch)?;
        }
    }
    build_timer.done();

    while let Some(batch) = stream.next().await {
        let batch = batch?;
        let _build_timer = metrics.build_time.timer();
        if batch.num_rows() > 0 {
            metrics.build_input_batches.add(1);
            metrics.build_input_rows.add(batch.num_rows());
            num_rows += batch.num_rows();
            spill_file.append_batch(&batch)?;
        }
    }

    let _build_timer = metrics.build_time.timer();
    Ok(spill_file.finish()?.map(|spill_file| SpilledLeftFile {
        spill_manager,
        spill_file,
        num_rows,
    }))
}

/// States for join processing. See `poll_next()` comment for more details about
/// state transitions.
#[derive(Debug, Clone, Copy)]
enum NLJState {
    BufferingLeft,
    FetchingRight,
    ProbeRight,
    EmitRightUnmatched,
    /// Entered exactly once per stream, when it has finished probing the whole
    /// left side: the probe (right) side is exhausted or, in memory-limited
    /// mode, every left chunk has been probed. This state owns the single
    /// probe-completion report that decrements the shared probe-threads
    /// counter, and records in `is_unmatched_left_emitter` whether this stream
    /// is the one responsible for emitting unmatched-left rows. Splitting this
    /// decision out of `EmitLeftUnmatched` makes "decrement exactly once" a
    /// structural property of the state graph, so the (re-enterable) emit state
    /// no longer has to guard against decrementing twice.
    ProbeEnd,
    EmitLeftUnmatched,
    /// Emit unmatched right rows using the global bitmap accumulated across
    /// all left chunks. Only used in memory-limited mode for join types that
    /// require tracking right-side matches in the final output (RIGHT, FULL,
    /// RIGHT SEMI, RIGHT ANTI, RIGHT MARK).
    EmitGlobalRightUnmatched,
    Done,
}
/// Outcome of the single pass over the left (build) input.
pub(crate) enum LeftLoad {
    /// The left side fit the memory budget and is buffered as one batch.
    InMemory {
        /// The buffered left side
        left_data: Arc<JoinLeftData>,
        /// Partitions that are still probing `left_data`
        probe_completion: Arc<ProbeCompletion>,
    },
    /// The budget ran out, so the left side was spilled during that same pass. Every partition
    /// shares this handle, and the chunks that are read back from the file.
    Spilled(Arc<LeftSpillData>),
}

/// The spill file [`spill_left_input`] wrote, before it is wrapped in a [`LeftSpillData`].
struct SpilledLeftFile {
    spill_manager: SpillManager,
    spill_file: Arc<dyn SpillFile>,
    /// Total number of rows written to `spill_file`
    num_rows: usize,
}

/// The spilled left side, shared by every output partition.
///
/// This is the memory-limited counterpart of [`LeftLoad::InMemory`]: the rows
/// live in a spill file instead of memory, but the visited bitmap and the
/// probe-threads counter cover the whole left side and are shared by all
/// partitions in the same way.
///
/// The rows come back one chunk at a time (see [`LeftChunkBarrier`]), while the
/// bitmap spans all of them: bits are addressed by the row's position in the
/// file. Keeping match tracking apart from the chunks is what lets a chunk be
/// dropped as soon as it has been probed, with the final left rows emitted in
/// one pass at the very end.
pub(crate) struct LeftSpillData {
    /// SpillManager used to read the spill file (has the left schema)
    spill_manager: SpillManager,
    /// The spill file containing all left-side batches
    spill_file: Arc<dyn SpillFile>,
    /// Left-side schema
    schema: SchemaRef,
    /// Total number of rows in `spill_file`
    num_rows: usize,
    /// The pass over `spill_file` that chunks are read from. Each chunk load
    /// takes it and hands it back for the load of the following chunk.
    reader: Arc<Mutex<Option<LeftChunkReader>>>,
    /// Visited bitmap over every row of `spill_file`. Empty when the join type
    /// does not need it.
    visited: SharedBitmapBuilder,
    /// Partitions that have neither finished probing every chunk nor gone
    /// away, and whether any went away before it finished
    probe_completion: ProbeCompletion,
    /// Memory reservation for `visited`
    reservation: MemoryReservation,
}

impl LeftSpillData {
    fn new(
        spilled: SpilledLeftFile,
        schema: SchemaRef,
        with_visited_left_side: bool,
        probe_threads_count: usize,
        reservation: MemoryReservation,
    ) -> Self {
        let SpilledLeftFile {
            spill_manager,
            spill_file,
            num_rows,
        } = spilled;
        let visited = if with_visited_left_side {
            // Use infallible `grow`: one bit per row is all that stays in
            // memory, and the fallback path has no other recourse.
            reservation.grow(num_rows.div_ceil(8));
            let mut buffer = BooleanBufferBuilder::new(num_rows);
            buffer.append_n(num_rows, false);
            buffer
        } else {
            BooleanBufferBuilder::new(0)
        };
        Self {
            spill_manager,
            spill_file,
            schema,
            num_rows,
            reader: Arc::new(Mutex::new(None)),
            visited: Mutex::new(visited),
            probe_completion: ProbeCompletion::new(probe_threads_count),
            reservation,
        }
    }

    /// Open a new pass over the spilled left rows
    fn open_pass(&self) -> Result<SendableRecordBatchStream> {
        self.spill_manager
            .read_spill_as_stream(Arc::clone(&self.spill_file), None)
    }

    /// Load the next chunk, accounting for it in `reservation`.
    ///
    /// The load is a shared future, the way the whole left side is a shared
    /// [`OnceFut`]: every partition waiting for the chunk holds a clone, and
    /// whichever of them is polled drives it. So it does not matter which
    /// partition started the load, or whether that one is still around.
    fn load_chunk(
        &self,
        reservation: MemoryReservation,
        build_time: &Time,
    ) -> LeftChunkFut {
        load_left_chunk(
            Arc::clone(&self.reader),
            self.spill_manager.clone(),
            Arc::clone(&self.spill_file),
            Arc::clone(&self.schema),
            reservation,
            build_time.clone(),
        )
        .map(|chunk| chunk.map(Arc::new).map_err(Arc::new))
        .boxed()
        .shared()
    }

    /// Record the matches of a finished chunk, whose first row is the
    /// `row_offset`-th row of the spill file.
    fn merge_visited(&self, row_offset: usize, chunk_visited: &BooleanBufferBuilder) {
        let mut visited = self.visited.lock();
        for idx in BitIndexIterator::new(chunk_visited.as_slice(), 0, chunk_visited.len())
        {
            visited.set_bit(row_offset + idx, true);
        }
    }

    /// Decrements counter of running threads. If the caller is the last
    /// running thread and no partition went away unfinished, it is the emitter
    /// and gets the complete visited bitmap, which it must account for.
    fn report_probe_completed(&self) -> Option<BooleanBuffer> {
        match self.probe_completion.report_completed() {
            Completion::NotLast => None,
            Completion::Emit(_) => Some(self.take_visited()),
            // Nobody will emit, so nobody needs the bitmap
            Completion::Abandoned => {
                drop(self.take_visited());
                None
            }
        }
    }

    /// `count` partitions went away before they finished probing.
    ///
    /// They are taken out of the probe-threads counter, like a report of probe
    /// completion, so that the bitmap is released by whichever partition is
    /// the last to finish or go away, while the plan may live on. But the final
    /// left rows are then not emitted.
    fn depart_unfinished(&self, count: usize) {
        if self.probe_completion.abandon(count) {
            drop(self.take_visited());
        }
    }

    /// Take the visited bitmap for the final emission, or to release it when
    /// there is none. Only the last partition to finish or go away may call
    /// this, after which no partition updates the bitmap.
    ///
    /// The bitmap's memory is no longer accounted for here afterwards, so that
    /// a plan that outlives its execution does not keep it reserved. The
    /// caller accounts for the returned buffer instead.
    fn take_visited(&self) -> BooleanBuffer {
        self.reservation.free();
        self.visited.lock().finish()
    }
}

/// One chunk of the spilled left side, shared by the partitions probing it.
struct LeftChunk {
    batch: LogicalBatch,
    /// Memory reservation for `batch`, cleared on drop
    #[expect(dead_code)]
    reservation: MemoryReservation,
}

/// A load of a [`LeftChunk`] that several partitions can wait on
type LeftChunkFut = Shared<BoxFuture<'static, SharedResult<Arc<LeftChunk>>>>;

/// The pass over the left spill file that chunks are read from
struct LeftChunkReader {
    stream: SendableRecordBatchStream,
    /// The batch that did not fit the previous chunk, which starts the next
    carryover: Option<RecordBatch>,
}

/// Load the next chunk: as many batches as `reservation` accepts, and always at
/// least one so that the join makes progress.
async fn load_left_chunk(
    reader_slot: Arc<Mutex<Option<LeftChunkReader>>>,
    spill_manager: SpillManager,
    spill_file: Arc<dyn SpillFile>,
    schema: SchemaRef,
    reservation: MemoryReservation,
    build_time: Time,
) -> Result<LeftChunk> {
    // Chunks are loaded one after another, so the reader the previous load
    // handed back is where this chunk starts. The first load opens it.
    let reader = reader_slot.lock().take();
    let mut reader = match reader {
        Some(reader) => reader,
        None => LeftChunkReader {
            stream: spill_manager.read_spill_as_stream(spill_file, None)?,
            carryover: None,
        },
    };

    let mut batches = vec![];
    // The batch that did not fit the previous chunk is already in memory, so it
    // is accounted for infallibly.
    if let Some(batch) = reader.carryover.take() {
        reservation.grow(batch.get_array_memory_size());
        batches.push(batch);
    }
    while let Some(batch) = reader.stream.next().await {
        let batch = batch?;
        // Times only the work this operator does on the batch, not the wait
        // for the spill stream to produce it.
        let _build_timer = build_time.timer();
        if batch.num_rows() == 0 {
            continue;
        }
        let batch_size = batch.get_array_memory_size();
        if reservation.try_grow(batch_size).is_err() {
            if !batches.is_empty() {
                // Chunk is full, defer this batch to the next chunk.
                reader.carryover = Some(batch);
                break;
            }
            // No batches yet -- accept the batch even over budget so we make
            // progress.
            reservation.grow(batch_size);
        }
        batches.push(batch);
    }

    let _build_timer = build_time.timer();
    let batch = LogicalBatch::new(schema, batches)?;
    *reader_slot.lock() = Some(reader);
    Ok(LeftChunk { batch, reservation })
}

/// Lets the partitions of a memory-limited join share one left chunk at a time.
///
/// Re-reading the right side once per left chunk is what the fallback costs, so
/// chunks should be as large as memory allows. One chunk shared by every
/// partition is as large as it gets, but it means the next chunk can only be
/// loaded once every partition is done with the current one. That is all this
/// type arranges: it counts the partitions that have finished the current
/// chunk, and moves on when all of them have.
///
/// It lives on the plan, next to the shared left load, because partitions take
/// part before it is known whether the left side spills at all. A partition
/// that goes away unfinished is taken out of the count, so the others carry on
/// without it, as they do when the left side fits in memory.
#[derive(Debug)]
pub(crate) struct LeftChunkBarrier {
    inner: Mutex<LeftChunkBarrierInner>,
    /// Signalled when the barrier moves on to the next chunk
    notify: tokio::sync::Notify,
}

struct LeftChunkBarrierInner {
    /// Index of the chunk the partitions are on
    chunk_index: usize,
    /// The load of that chunk, once a partition has asked for it. Holding it
    /// keeps the chunk in memory for partitions that get to it later.
    chunk: Option<LeftChunkFut>,
    /// Partitions that have not gone away
    live: usize,
    /// How many of them have finished the current chunk
    finished: usize,
    /// Accounts for the chunks. Registered by the first load, because partitions
    /// take part before it is known that there will be one.
    reservation: Option<MemoryReservation>,
    /// The spilled left side, once the load has spilled it. Partitions that go
    /// away before they finished probing are taken out of its probe-threads
    /// counter through here, since a partition may not have seen it yet.
    left_spill: Option<Arc<LeftSpillData>>,
    /// Partitions that went away unfinished before the left side was spilled,
    /// to take out of its counter once it is.
    departed_before_spill: usize,
}

impl std::fmt::Debug for LeftChunkBarrierInner {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LeftChunkBarrierInner")
            .field("chunk_index", &self.chunk_index)
            .field("live", &self.live)
            .field("finished", &self.finished)
            .finish()
    }
}

impl LeftChunkBarrierInner {
    /// Move on if every remaining partition has finished the current chunk.
    /// Returns whether it did.
    fn advance_if_all_finished(&mut self) -> bool {
        if self.live > 0 && self.finished < self.live {
            return false;
        }
        // Letting go of the load is what frees the chunk: by now no partition
        // holds it either.
        self.chunk = None;
        self.chunk_index += 1;
        self.finished = 0;
        true
    }
}

impl LeftChunkBarrier {
    fn new(right_partition_count: usize) -> Self {
        Self {
            inner: Mutex::new(LeftChunkBarrierInner {
                chunk_index: 0,
                chunk: None,
                live: right_partition_count,
                finished: 0,
                reservation: None,
                left_spill: None,
                departed_before_spill: 0,
            }),
            notify: tokio::sync::Notify::new(),
        }
    }

    /// The chunk with index `chunk_index`, once every partition has finished
    /// the one before it.
    async fn chunk(
        self: Arc<Self>,
        chunk_index: usize,
        left_spill: Arc<LeftSpillData>,
        memory_pool: Arc<dyn MemoryPool>,
        build_time: Time,
    ) -> Result<Arc<LeftChunk>> {
        loop {
            // Created under the lock, so that it cannot miss the signal of an
            // advance that happens right after the lock is released.
            let advanced = {
                let mut inner = self.inner.lock();
                if chunk_index == inner.chunk_index {
                    let inner = &mut *inner;
                    let reservation = inner.reservation.get_or_insert_with(|| {
                        MemoryConsumer::new("NestedLoopJoinFallbackChunk")
                            .with_can_spill(true)
                            .register(&memory_pool)
                    });
                    let chunk = inner.chunk.get_or_insert_with(|| {
                        left_spill.load_chunk(reservation.new_empty(), &build_time)
                    });
                    Err(chunk.clone())
                } else {
                    Ok(self.notify.notified())
                }
            };
            match advanced {
                Ok(advanced) => advanced.await,
                Err(chunk) => return chunk.await.map_err(DataFusionError::Shared),
            }
        }
    }

    /// A partition has finished the current chunk
    fn finish_chunk(&self) {
        let mut inner = self.inner.lock();
        inner.finished += 1;
        if inner.advance_if_all_finished() {
            drop(inner);
            self.notify.notify_waiters();
        }
    }

    /// The load has spilled the left side
    fn register_left_spill(&self, left_spill: &Arc<LeftSpillData>) {
        let mut inner = self.inner.lock();
        left_spill.depart_unfinished(inner.departed_before_spill);
        inner.left_spill = Some(Arc::clone(left_spill));
    }

    /// A partition has gone away before finishing.
    ///
    /// `chunk_index` is the index the partition had advanced to: that of the
    /// chunk it was probing or waiting for, or one past the last chunk once it
    /// has probed them all. `probe_reported` is whether it had already reported
    /// probe completion, in which case the left side's counter already
    /// accounts for it.
    fn depart(&self, chunk_index: usize, probe_reported: bool) {
        let mut inner = self.inner.lock();
        inner.live = inner.live.saturating_sub(1);
        if chunk_index > inner.chunk_index {
            // It had finished the current chunk and was waiting for the next
            inner.finished = inner.finished.saturating_sub(1);
        }
        if !probe_reported {
            match &inner.left_spill {
                Some(left_spill) => left_spill.depart_unfinished(1),
                None => inner.departed_before_spill += 1,
            }
        }
        if inner.advance_if_all_finished() {
            drop(inner);
            self.notify.notify_waiters();
        }
    }
}

/// Tracks the state of the memory-limited spill fallback for NLJ.
///
/// The NLJ always tries to buffer the whole left side in memory. If that does not fit and
/// conditions allow, the load spills the left side (see [`collect_left_input`]) and the operator
/// switches to a multi-pass strategy where left chunks are read back from that spill file and the
/// right side is spilled for re-scanning.
pub(crate) enum SpillState {
    /// Memory-limited mode is not possible (e.g., join type requires global right bitmap,
    /// or disk manager is disabled). OOM errors will propagate as-is.
    Disabled,

    /// Memory-limited mode is possible but not entered: the left side is still expected to fit.
    /// Holds the context needed to set the mode up.
    Pending {
        /// TaskContext for reservations and SpillManager creation
        task_context: Arc<TaskContext>,
        /// Output partition of this stream, used to name its reservations
        partition: usize,
        /// Paces this stream through the left chunks, together with the
        /// streams of the other partitions.
        left_chunk_barrier: Arc<LeftChunkBarrier>,
    },

    /// Memory-limited mode is running. Left data is read back in chunks
    /// and the right side is spilled to disk for re-scanning.
    Active(Box<SpillStateActive>),
}

/// State for active memory-limited spill execution.
/// Boxed inside [`SpillState::Active`] to reduce enum size.
pub(crate) struct SpillStateActive {
    /// The spilled left side, shared by every partition.
    left_spill: Arc<LeftSpillData>,
    /// Paces this stream through the left chunks, together with the streams of
    /// the other partitions.
    left_chunk_barrier: Arc<LeftChunkBarrier>,
    /// Index of the chunk being probed, or of the next one while none is
    chunk_index: usize,
    /// The wait for the next chunk, while it is in flight
    chunk_fetch: Option<BoxFuture<'static, Result<Arc<LeftChunk>>>>,
    /// The chunk being probed, held to keep its memory accounted for
    current_chunk: Option<Arc<LeftChunk>>,
    /// Memory pool the chunks are accounted in
    memory_pool: Arc<dyn MemoryPool>,
    /// Accounts for what this partition keeps beside the shared chunk: its
    /// visited bitmap for the chunk and, for the emitter, the global one.
    chunk_reservation: MemoryReservation,
    /// Position in the left spill file of the current chunk's first row. See
    /// [`LeftSpillData`] for why bits are addressed this way.
    chunk_row_offset: usize,
    /// Final pass over the left spill file that emits the unmatched-left rows.
    /// Only the elected emitter has one, from `ProbeEnd` on.
    left_unmatched_pass: Option<LeftUnmatchedPass>,
    /// Right-side schema, used to build NULL-padded right columns.
    right_schema: SchemaRef,
    /// Right input that spills on the first pass and replays from spill later.
    right_input: ReplayableStreamSource,
    /// Per-batch accumulated right bitmaps across all left chunks.
    /// Index = right batch sequence number (0-based, non-empty batches only).
    /// Only populated when `should_track_unmatched_right` is true.
    global_right_bitmaps: Vec<BooleanBuffer>,
    /// Separate reservation for `global_right_bitmaps`. These buffers live
    /// for the full operator lifetime (not per-chunk).
    global_right_bitmaps_reservation: MemoryReservation,
    /// Current right batch sequence index within the current pass.
    right_batch_index: usize,
}

/// The emitter's final pass over the left spill file. See
/// [`NestedLoopJoinStream::handle_emit_left_unmatched_memory_limited`].
struct LeftUnmatchedPass {
    /// Opened on the first entry to `EmitLeftUnmatched`
    stream: Option<SendableRecordBatchStream>,
    /// The complete global visited bitmap, taken from [`LeftSpillData`] and
    /// accounted for in the stream's `chunk_reservation`, so it is released
    /// with the stream whichever way the pass ends.
    visited: BooleanBuffer,
    /// Position in the left spill file of the next batch's first row
    row_offset: usize,
}

impl SpillStateActive {
    /// Merge a per-pass right bitmap into the global accumulator at the
    /// given batch index, growing the dedicated reservation when seeing
    /// a batch index for the first time.
    ///
    /// On first encounter of `idx`, the bitmap is stored as-is and its
    /// size is reserved. On subsequent encounters (later left chunk
    /// passes over the same right batch), the existing entry is OR-merged
    /// with `values`. Because `bitor` produces a buffer of the same bit
    /// length, the reservation does not need to be adjusted on merge.
    fn merge_current_right_bitmap(&mut self, idx: usize, values: BooleanBuffer) {
        if idx >= self.global_right_bitmaps.len() {
            // First encounter of this right batch — account memory and store.
            // The bitmap has one bit per right row, so for very large right
            // inputs the accumulated size can be non-negligible (e.g.,
            // 1M rows ≈ 125 KB per batch).
            // Use infallible `grow` because we must accept the bitmap to
            // preserve correctness — the fallback path has no other recourse.
            let bytes = values.len().div_ceil(8);
            self.global_right_bitmaps_reservation.grow(bytes);
            self.global_right_bitmaps.push(values);
        } else {
            // Subsequent left chunk pass — OR merge. Same bit length, so
            // no reservation adjustment is needed.
            self.global_right_bitmaps[idx] =
                self.global_right_bitmaps[idx].bitor(&values);
        }
    }
}

/// Probe state for RightSemi/RightAnti within one buffered left chunk.
/// The original right batch stays in the stream for output and spill replay.
struct RightExistenceProbe {
    /// Only the right columns referenced by the filter, cached across probes.
    candidates: RecordBatch,
    /// Filter with right column indices remapped to `candidates`.
    filter: Option<JoinFilter>,
    /// Candidate row -> original right row. None until the first compaction.
    original_indices: Option<Vec<usize>>,
    /// Matches in original right-row coordinates, for output/spill merging.
    matched: BooleanBufferBuilder,
    /// Matches in candidate coordinates, reset after compaction.
    candidate_matched: Vec<u64>,
    remaining: usize,
}

impl RightExistenceProbe {
    fn new(right: &RecordBatch, filter: Option<&JoinFilter>) -> Result<Self> {
        let mut projection = Vec::new();
        let mut filter = filter.cloned();
        if let Some(filter) = &mut filter {
            for column in &mut filter.column_indices {
                if column.side == JoinSide::Right {
                    let index = projection.iter().position(|&i| i == column.index);
                    column.index = index.unwrap_or_else(|| {
                        projection.push(column.index);
                        projection.len() - 1
                    });
                }
            }
        }
        let rows = right.num_rows();
        let mut matched = BooleanBufferBuilder::new(rows);
        matched.append_n(rows, false);
        Ok(Self {
            candidates: right.project(&projection)?,
            filter,
            original_indices: None,
            matched,
            candidate_matched: vec![0; rows.div_ceil(64)],
            remaining: rows,
        })
    }

    /// Probe the next left range, returning the number of left rows consumed.
    fn probe(
        &mut self,
        left: &LogicalBatch,
        start: usize,
        batch_size: usize,
    ) -> Result<usize> {
        let candidate_rows = self.candidates.num_rows();
        let rows_per_range = batch_size / candidate_rows;
        let count = if rows_per_range > 10 {
            rows_per_range
        } else {
            1
        };
        let count = count.min(left.num_rows() - start);
        let remaining_before = self.remaining;

        let matches = match &self.filter {
            Some(filter) if count == 1 => apply_filter_to_row_join_batch(
                left.row(start)?,
                &self.candidates,
                filter,
            )?,
            Some(filter) => {
                let left_indices = left.row_indices(
                    (start..start + count)
                        .flat_map(|i| std::iter::repeat_n(i, candidate_rows)),
                )?;
                let right_indices = UInt32Array::from_iter_values(
                    (0..count).flat_map(|_| 0..candidate_rows as u32),
                );
                apply_filter_to_indices(
                    left,
                    &self.candidates,
                    &left_indices,
                    &right_indices,
                    filter,
                )?
            }
            None => {
                BooleanArray::new(BooleanBuffer::new_set(count * candidate_rows), None)
            }
        };
        if !matches.has_true() {
            return Ok(count);
        }
        self.update_matches(matches.values());

        if start + count < left.num_rows()
            && self.remaining > 0
            && self.remaining < remaining_before
            && self.remaining <= candidate_rows / 2
        {
            self.compact()?;
        }
        Ok(count)
    }

    fn update_matches(&mut self, matches: &BooleanBuffer) {
        let candidate_rows = self.candidates.num_rows();
        // Each left row contributes one candidate-sized segment. BitChunks handles
        // both sliced filter results and segments that start within a byte/word.
        for offset in (0..matches.len()).step_by(candidate_rows) {
            let segment = matches.slice(offset, candidate_rows);
            let chunks = segment.bit_chunks();
            for (word_index, (previous, current)) in self
                .candidate_matched
                .iter_mut()
                .zip(chunks.iter_padded())
                .enumerate()
            {
                let mut new_matches = current & !*previous;
                *previous |= current;
                self.remaining -= new_matches.count_ones() as usize;
                // Only visit new matches, including when several left rows match
                // the same candidate in this range or in subsequent probes.
                while new_matches != 0 {
                    let candidate =
                        word_index * 64 + new_matches.trailing_zeros() as usize;
                    let original = self
                        .original_indices
                        .as_ref()
                        .map_or(candidate, |indices| indices[candidate]);
                    self.matched.set_bit(original, true);
                    new_matches &= new_matches - 1;
                }
            }
            if self.remaining == 0 {
                break;
            }
        }
    }

    fn compact(&mut self) -> Result<()> {
        let indices = UInt32Array::from_iter_values(
            (0..self.candidates.num_rows())
                .filter(|&i| self.candidate_matched[i / 64] & (1 << (i % 64)) == 0)
                .map(|i| i as u32),
        );
        let original_indices = indices
            .values()
            .iter()
            .map(|&i| {
                self.original_indices
                    .as_ref()
                    .map_or(i as usize, |original| original[i as usize])
            })
            .collect();
        // Take the cached projection only when compacting, never the original
        // payload or the original right columns on every probe.
        self.candidates = if self.candidates.num_columns() == 0 {
            create_record_batch_with_empty_schema(
                self.candidates.schema(),
                indices.len(),
            )?
        } else {
            take_record_batch(&self.candidates, &indices)?
        };
        self.original_indices = Some(original_indices);
        self.candidate_matched.clear();
        self.candidate_matched
            .resize(self.remaining.div_ceil(64), 0);
        Ok(())
    }
}

pub(crate) struct NestedLoopJoinStream {
    // ========================================================================
    // PROPERTIES:
    // Operator's properties that remain constant
    //
    // Note: The implementation uses the terms left/build-side table and
    // right/probe-side table interchangeably. Treating the left side as the
    // build side is a convention in DataFusion: the planner always tries to
    // swap the smaller table to the left side.
    // ========================================================================
    /// Output schema
    pub(crate) output_schema: Arc<Schema>,
    /// join filter
    pub(crate) join_filter: Option<JoinFilter>,
    /// type of the join
    pub(crate) join_type: JoinType,
    /// the probe-side(right) table data of the nested loop join
    /// `Option` is used because memory-limited path requires resetting it.
    pub(crate) right_data: Option<SendableRecordBatchStream>,
    /// the build-side table data of the nested loop join
    pub(crate) left_data: OnceFut<LeftLoad>,
    /// Projection to construct the output schema from the left and right tables.
    /// Example:
    /// - output_schema: `['a', 'c']`
    /// - left_schema: `['a', 'b']`
    /// - right_schema: `['c']`
    ///
    /// The column indices would be [(left, 0), (right, 0)] -- taking the left
    /// 0th column and right 0th column can construct the output schema.
    ///
    /// Note there are other columns ('b' in the example) still kept after
    /// projection pushdown; this is because they might be used to evaluate
    /// the join filter (e.g., `JOIN ON (b+c)>0`).
    pub(crate) column_indices: Vec<ColumnIndex>,
    /// Join execution metrics
    pub(crate) metrics: NestedLoopJoinMetrics,

    /// `batch_size` from configuration
    batch_size: usize,

    /// See comments in [`need_produce_right_in_final`] for more detail
    should_track_unmatched_right: bool,

    // ========================================================================
    // STATE FLAGS/BUFFERS:
    // Fields that hold intermediate data/flags during execution
    // ========================================================================
    /// State Tracking
    state: NLJState,

    /// Output buffer holds the join result to output. It will emit eagerly when
    /// the threshold is reached.
    output_buffer: Box<BatchCoalescer>,
    /// See comments in [`NLJState::Done`] for its purpose
    handled_empty_output: bool,

    // Buffer(left) side
    // -----------------
    /// The current buffered left data to join
    buffered_left_data: Option<Arc<JoinLeftData>>,
    /// Probe partitions still running over the in-memory left side, shared by
    /// all of them. `None` on the spill path, which reports on
    /// [`LeftSpillData`] instead.
    in_memory_probe_completion: Option<Arc<ProbeCompletion>>,
    /// Index into the left buffered batch. Used in `ProbeRight` state
    left_probe_idx: usize,
    /// Index into the left buffered batch. Used in `EmitLeftUnmatched` state
    left_emit_idx: usize,
    /// Should we go back to `BufferingLeft` state again after `EmitLeftUnmatched`
    /// state is over.
    left_exhausted: bool,

    // Probe(right) side
    // -----------------
    /// The current probe batch to process
    current_right_batch: Option<RecordBatch>,
    // For right join, keep track of matched rows in `current_right_batch`
    // Constructed when fetching each new incoming right batch in `FetchingRight` state.
    current_right_batch_matched: Option<BooleanArray>,
    /// Candidate pruning for right semi/anti joins in the current left chunk.
    right_existence_probe: Option<RightExistenceProbe>,

    /// Memory-limited spill fallback state. See [`SpillState`] for details.
    spill_state: SpillState,

    /// Whether this stream is the one responsible for emitting unmatched-left
    /// rows. Set in the [`NLJState::ProbeEnd`] state, which is entered exactly
    /// once per stream and owns the single probe-completion report (on
    /// [`LeftLoad::InMemory`]'s [`ProbeCompletion`], or on [`LeftSpillData`] in
    /// memory-limited mode): the
    /// stream that drives the
    /// shared probe-threads counter to zero (the last to finish probing) becomes
    /// the emitter. Because the decrement happens once in `ProbeEnd` rather than
    /// in the re-enterable `EmitLeftUnmatched` state, the counter can never be
    /// decremented twice, so it cannot reach zero before all partitions finish
    /// probing (which would otherwise let a partition emit spurious NULL-padded
    /// unmatched-left rows early).
    is_unmatched_left_emitter: bool,
}

pub(crate) struct NestedLoopJoinMetrics {
    /// Join execution metrics
    pub(crate) join_metrics: BuildProbeJoinMetrics,
    /// Selectivity of the join: output_rows / (left_rows * right_rows)
    pub(crate) selectivity: RatioMetrics,
    /// Spill metrics for memory-limited execution
    pub(crate) spill_metrics: SpillMetrics,
}

impl NestedLoopJoinMetrics {
    pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
        Self {
            join_metrics: BuildProbeJoinMetrics::new(partition, metrics),
            selectivity: MetricBuilder::new(metrics)
                .with_type(MetricType::Summary)
                .ratio_metrics("selectivity", partition),
            spill_metrics: SpillMetrics::new(metrics, partition),
        }
    }
}

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

    /// See the comments [`NestedLoopJoinExec`] for high-level design ideas.
    ///
    /// # Implementation
    ///
    /// This function is the entry point of NLJ operator's state machine
    /// transitions. The rough state transition graph is as follow, for more
    /// details see the comment in each state's matching arm.
    ///
    /// ============================
    /// State transition graph:
    /// ============================
    ///
    /// (start) --> BufferingLeft
    /// ----------------------------
    /// BufferingLeft → FetchingRight
    ///
    /// FetchingRight → ProbeRight (if right batch available)
    /// FetchingRight → ProbeEnd (if right exhausted)
    ///
    /// ProbeRight → ProbeRight (next left row or after yielding output)
    /// ProbeRight → EmitRightUnmatched (for special join types like right join)
    /// ProbeRight → FetchingRight (done with the current right batch)
    ///
    /// EmitRightUnmatched → FetchingRight
    ///
    /// ProbeEnd → EmitLeftUnmatched (records whether this stream is the
    /// unmatched-left emitter, then always continues to EmitLeftUnmatched)
    ///
    /// EmitLeftUnmatched → EmitLeftUnmatched (only process 1 chunk for each
    /// iteration)
    /// EmitLeftUnmatched → Done (if finished)
    /// ----------------------------
    /// Done → (end)
    ///
    /// Memory-limited mode (see 'Memory-limited Execution' in
    /// [`NestedLoopJoinExec`]) loops over left chunks before reaching `ProbeEnd`:
    ///
    /// BufferingLeft → FetchingRight (next left chunk loaded)
    /// FetchingRight → BufferingLeft (right pass exhausted, more chunks remain)
    /// FetchingRight → EmitGlobalRightUnmatched → ProbeEnd (after the last chunk,
    /// for join types tracking unmatched right rows)
    /// FetchingRight → ProbeEnd (after the last chunk, otherwise)
    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        loop {
            match self.state {
                // # NLJState transitions
                // --> FetchingRight
                // This state will prepare the left side batches, next state
                // `FetchingRight` is responsible for preparing a single probe
                // side batch, before start joining.
                NLJState::BufferingLeft => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    match self.handle_buffering_left(cx) {
                        ControlFlow::Continue(()) => {}
                        ControlFlow::Break(poll) => return poll,
                    }
                }

                // # NLJState transitions:
                // 1. --> ProbeRight
                //    Start processing the join for the newly fetched right
                //    batch.
                // 2. --> ProbeEnd: When the right side input is exhausted,
                //    probing for the buffered left data is finished.
                //    (Memory-limited mode moves on to the next left chunk
                //    first, see `finish_left_chunk`.)
                //
                // After fetching a new batch from the right side, it will
                // process all rows from the buffered left data:
                // ```text
                // for batch in right_side:
                //     for row in left_buffer:
                //         join(batch, row)
                // ```
                // Note: the implementation does this step incrementally,
                // instead of materializing all intermediate Cartesian products
                // at once in memory.
                //
                // So after the right side input is exhausted, the join phase
                // for the current buffered left data is finished. We go to the
                // `ProbeEnd` state, which records probe completion before the
                // `EmitLeftUnmatched` phase checks if there is any special
                // handling (e.g., in cases like left join).
                NLJState::FetchingRight => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    match self.handle_fetching_right(cx) {
                        ControlFlow::Continue(()) => {}
                        ControlFlow::Break(poll) => return poll,
                    }
                }

                // NLJState transitions:
                // 1. --> ProbeRight(1)
                //    If we have already buffered enough output to yield, it
                //    will first give back control to the parent state machine,
                //    then resume at the same place.
                // 2. --> ProbeRight(2)
                //    After probing one right batch, and evaluating the
                //    join filter on (left-row x right-batch), it will advance
                //    to the next left row, then re-enter the current state and
                //    continue joining.
                // 3. --> FetchRight
                //    After it has done with the current right batch (to join
                //    with all rows in the left buffer), it will go to
                //    FetchRight state to check what to do next.
                NLJState::ProbeRight => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    // stop on drop
                    let join_metric = self.metrics.join_metrics.join_time.clone();
                    let _join_timer = join_metric.timer();

                    match self.handle_probe_right() {
                        ControlFlow::Continue(()) => {}
                        ControlFlow::Break(poll) => {
                            return self.metrics.join_metrics.baseline.record_poll(poll);
                        }
                    }
                }

                // In the `current_right_batch_matched` bitmap, all trues mean
                // it has been output by the join. In this state we have to
                // output unmatched rows for current right batch (with null
                // padding for left relation)
                // Precondition: we have checked the join type so that it's
                // possible to output right unmatched (e.g. it's right join)
                NLJState::EmitRightUnmatched => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    // stop on drop
                    let join_metric = self.metrics.join_metrics.join_time.clone();
                    let _join_timer = join_metric.timer();

                    match self.handle_emit_right_unmatched() {
                        ControlFlow::Continue(()) => {}
                        ControlFlow::Break(poll) => {
                            return self.metrics.join_metrics.baseline.record_poll(poll);
                        }
                    }
                }

                // NLJState transitions:
                // 1. --> EmitLeftUnmatched
                //    Probing for the whole left side is finished. Report
                //    probe completion exactly once (decrementing the shared
                //    probe-threads counter) and record whether this stream is
                //    the unmatched-left emitter, then always advance to
                //    `EmitLeftUnmatched`.
                NLJState::ProbeEnd => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    // stop on drop
                    let join_metric = self.metrics.join_metrics.join_time.clone();
                    let _join_timer = join_metric.timer();

                    match self.handle_probe_end() {
                        ControlFlow::Continue(()) => {}
                        ControlFlow::Break(poll) => {
                            return self.metrics.join_metrics.baseline.record_poll(poll);
                        }
                    }
                }

                // NLJState transitions:
                // 1. --> EmitLeftUnmatched(1)
                //    If we have already buffered enough output to yield, it
                //    will first give back control to the parent state machine,
                //    then resume at the same place.
                // 2. --> EmitLeftUnmatched(2)
                //    After processing some unmatched rows, it will re-enter
                //    the same state, to check if there are any more final
                //    results to output.
                // 3. --> Done
                //    It has processed all data, go to the final state and ready
                //    to exit.
                //
                // In memory-limited mode the left rows are no longer buffered,
                // so the emitter streams them from the left spill file instead.
                NLJState::EmitLeftUnmatched if self.is_memory_limited() => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    match self.handle_emit_left_unmatched_memory_limited(cx) {
                        ControlFlow::Continue(()) => {}
                        ControlFlow::Break(poll) => {
                            return self.metrics.join_metrics.baseline.record_poll(poll);
                        }
                    }
                }
                NLJState::EmitLeftUnmatched => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    // stop on drop
                    let join_metric = self.metrics.join_metrics.join_time.clone();
                    let _join_timer = join_metric.timer();

                    match self.handle_emit_left_unmatched() {
                        ControlFlow::Continue(()) => {}
                        ControlFlow::Break(poll) => {
                            return self.metrics.join_metrics.baseline.record_poll(poll);
                        }
                    }
                }

                // Replay all right batches from spill and emit unmatched
                // right rows using the global bitmap accumulated across all
                // left chunks. Only entered in memory-limited mode for join
                // types where `should_track_unmatched_right` is true
                // (RIGHT, FULL, RIGHT SEMI, RIGHT ANTI, RIGHT MARK).
                NLJState::EmitGlobalRightUnmatched => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    match self.handle_emit_global_right_unmatched(cx) {
                        ControlFlow::Continue(()) => {}
                        ControlFlow::Break(poll) => {
                            return self.metrics.join_metrics.baseline.record_poll(poll);
                        }
                    }
                }

                // The final state and the exit point
                NLJState::Done => {
                    debug!("[NLJState] Entering: {:?}", self.state);

                    // stop on drop
                    let join_metric = self.metrics.join_metrics.join_time.clone();
                    let _join_timer = join_metric.timer();
                    // counting it in join timer due to there might be some
                    // final resout batches to output in this state

                    let poll = self.handle_done();
                    return self.metrics.join_metrics.baseline.record_poll(poll);
                }
            }
        }
    }
}

impl RecordBatchStream for NestedLoopJoinStream {
    fn schema(&self) -> SchemaRef {
        Arc::clone(&self.output_schema)
    }
}

/// A stream that goes away before it has finished stops being waited for.
///
/// The partitions of a memory-limited join move through the left chunks
/// together (see [`LeftChunkBarrier`]), so the others would otherwise wait for
/// it forever. They carry on without it, the same as when the left side fits in
/// memory: there the streams share nothing but the visited bitmap, and a stream
/// that never reports probe completion only means that the final left rows are
/// not emitted. That holds here too. What differs is the bitmap's memory: with
/// no emitter to take it, it is released by the last partition to finish or go
/// away rather than kept for as long as the plan.
impl Drop for NestedLoopJoinStream {
    fn drop(&mut self) {
        if matches!(self.state, NLJState::Done) {
            return;
        }
        // `ProbeEnd` is the only way into `EmitLeftUnmatched`
        let probe_reported = matches!(self.state, NLJState::EmitLeftUnmatched);
        match &self.spill_state {
            SpillState::Active(active) => active
                .left_chunk_barrier
                .depart(active.chunk_index, probe_reported),
            // Not known yet whether the left side spills. If it does not, the
            // barrier is never used and this has no effect.
            SpillState::Pending {
                left_chunk_barrier, ..
            } => left_chunk_barrier.depart(0, probe_reported),
            SpillState::Disabled => {}
        }
    }
}

impl NestedLoopJoinStream {
    #[expect(clippy::too_many_arguments)]
    pub(crate) fn new(
        schema: Arc<Schema>,
        filter: Option<JoinFilter>,
        join_type: JoinType,
        right_data: SendableRecordBatchStream,
        left_data: OnceFut<LeftLoad>,
        column_indices: Vec<ColumnIndex>,
        metrics: NestedLoopJoinMetrics,
        batch_size: usize,
        spill_state: SpillState,
    ) -> Self {
        Self {
            output_schema: Arc::clone(&schema),
            join_filter: filter,
            join_type,
            right_data: Some(right_data),
            column_indices,
            left_data,
            metrics,
            in_memory_probe_completion: None,
            buffered_left_data: None,
            output_buffer: Box::new(BatchCoalescer::new(schema, batch_size)),
            batch_size,
            current_right_batch: None,
            current_right_batch_matched: None,
            right_existence_probe: None,
            state: NLJState::BufferingLeft,
            left_probe_idx: 0,
            left_emit_idx: 0,
            left_exhausted: false,
            handled_empty_output: false,
            should_track_unmatched_right: need_produce_right_in_final(join_type),
            spill_state,
            is_unmatched_left_emitter: false,
        }
    }

    /// Returns true if this stream is operating in memory-limited mode
    fn is_memory_limited(&self) -> bool {
        matches!(self.spill_state, SpillState::Active(_))
    }

    /// Enter memory-limited mode with the left side already spilled by the load.
    ///
    /// Every partition resolves the same shared `LeftLoad`, so they all read the
    /// one spill file the load wrote; the left child is never executed a second
    /// time.
    fn enter_memory_limited_mode(
        &mut self,
        left_spill: Arc<LeftSpillData>,
    ) -> Result<()> {
        let SpillState::Pending {
            task_context: context,
            partition,
            left_chunk_barrier,
        } = std::mem::replace(&mut self.spill_state, SpillState::Disabled)
        else {
            return internal_err!(
                "enter_memory_limited_mode called in non-Pending spill state"
            );
        };

        let chunk_reservation =
            MemoryConsumer::new(format!("NestedLoopJoinLeftVisited[{partition}]"))
                .register(context.memory_pool());

        // Separate reservation for the global right bitmaps. These buffers
        // are per-partition (each partition tracks matches against its own
        // right input) and persist across all left chunks.
        let global_right_bitmaps_reservation =
            MemoryConsumer::new("NestedLoopJoinGlobalRightBitmaps".to_string())
                .register(context.memory_pool());

        // Create SpillManager for right-side spilling
        let right_schema = self
            .right_data
            .as_ref()
            .expect("right_data must be present before entering memory-limited mode")
            .schema();
        let right_data = self
            .right_data
            .take()
            .expect("right_data must be present before entering memory-limited mode");
        let right_spill_manager = SpillManager::new(
            context.runtime_env(),
            self.metrics.spill_metrics.clone(),
            Arc::clone(&right_schema),
        )
        .with_compression_type(context.session_config().spill_compression());

        self.spill_state = SpillState::Active(Box::new(SpillStateActive {
            left_spill,
            left_chunk_barrier,
            chunk_index: 0,
            chunk_fetch: None,
            current_chunk: None,
            memory_pool: Arc::clone(context.memory_pool()),
            chunk_reservation,
            chunk_row_offset: 0,
            left_unmatched_pass: None,
            right_schema,
            right_input: ReplayableStreamSource::new(
                right_data,
                right_spill_manager,
                "NestedLoopJoin right spill",
            ),
            global_right_bitmaps: Vec::new(),
            global_right_bitmaps_reservation,
            right_batch_index: 0,
        }));

        // State stays BufferingLeft — next poll will enter
        // handle_buffering_left_memory_limited via is_memory_limited() check
        self.state = NLJState::BufferingLeft;

        Ok(())
    }

    // ==== State handler functions ====

    /// Handle BufferingLeft state - prepare left side batches.
    ///
    /// In standard mode, uses OnceFut to load all left data at once.
    /// In memory-limited mode, incrementally buffers left batches until the
    /// memory budget is reached or the left stream is exhausted.
    fn handle_buffering_left(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        if self.is_memory_limited() {
            self.handle_buffering_left_memory_limited(cx)
        } else {
            // Standard path: use OnceFut
            match self.left_data.get_shared(cx) {
                Poll::Ready(Ok(load)) => match load.as_ref() {
                    LeftLoad::InMemory {
                        left_data,
                        probe_completion,
                    } => {
                        self.in_memory_probe_completion =
                            Some(Arc::clone(probe_completion));
                        self.buffered_left_data = Some(Arc::clone(left_data));
                        self.left_exhausted = true;
                        self.state = NLJState::FetchingRight;
                        ControlFlow::Continue(())
                    }
                    LeftLoad::Spilled(left_spill) => {
                        debug!(
                            "NestedLoopJoin: left side exceeded the budget and was spilled, \
                             entering memory-limited mode"
                        );
                        match self.enter_memory_limited_mode(Arc::clone(left_spill)) {
                            Ok(()) => ControlFlow::Continue(()),
                            Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
                        }
                    }
                },
                Poll::Ready(Err(e)) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
                Poll::Pending => ControlFlow::Break(Poll::Pending),
            }
        }
    }

    /// Memory-limited path for handle_buffering_left.
    ///
    /// Gets the next left chunk, which every partition shares (see
    /// [`LeftChunkBarrier`]).
    fn handle_buffering_left_memory_limited(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        let build_time = self.metrics.join_metrics.build_time.clone();
        let SpillState::Active(active) = &mut self.spill_state else {
            unreachable!(
                "handle_buffering_left_memory_limited called without Active spill state"
            );
        };

        let row_offset = active.chunk_row_offset;
        if row_offset >= active.left_spill.num_rows {
            // Only an empty spill file ends up here, and the load does not
            // write one. Handled anyway: there is nothing left to probe.
            self.left_exhausted = true;
            self.enter_state_after_last_left_chunk();
            return ControlFlow::Continue(());
        }

        if active.chunk_fetch.is_none() {
            active.chunk_fetch = Some(
                Arc::clone(&active.left_chunk_barrier)
                    .chunk(
                        active.chunk_index,
                        Arc::clone(&active.left_spill),
                        Arc::clone(&active.memory_pool),
                        build_time.clone(),
                    )
                    .boxed(),
            );
        }
        let chunk_fetch = active
            .chunk_fetch
            .as_mut()
            .expect("chunk_fetch installed above");
        let chunk = match chunk_fetch.poll_unpin(cx) {
            Poll::Ready(Ok(chunk)) => chunk,
            Poll::Ready(Err(e)) => return ControlFlow::Break(Poll::Ready(Some(Err(e)))),
            Poll::Pending => return ControlFlow::Break(Poll::Pending),
        };
        active.chunk_fetch = None;

        let _build_timer = build_time.timer();
        let batch = chunk.batch.clone();
        let n_rows = batch.num_rows();
        self.left_exhausted = row_offset + n_rows >= active.left_spill.num_rows;

        // Matches are tracked per partition while probing, so the probe path
        // never contends with other partitions, and merged into the global
        // bitmap once in `finish_left_chunk`.
        let visited_left_side = if need_produce_result_in_final(self.join_type) {
            // Use infallible `grow` for the bitmap -- it's small
            active.chunk_reservation.grow(n_rows.div_ceil(8));
            let mut buffer = BooleanBufferBuilder::new(n_rows);
            buffer.append_n(n_rows, false);
            buffer
        } else {
            BooleanBufferBuilder::new(0)
        };

        // This `JoinLeftData` is private to the partition: it shares the
        // chunk's rows but has its own bitmap. Probe completion is reported
        // once for the whole left side, on `LeftSpillData`.
        self.buffered_left_data = Some(Arc::new(JoinLeftData::new(
            batch,
            Mutex::new(visited_left_side),
            active.chunk_reservation.take(),
        )));
        active.current_chunk = Some(chunk);

        active.right_batch_index = 0;
        match active.right_input.open_pass() {
            Ok(stream) => {
                self.right_data = Some(stream);
            }
            Err(e) => {
                return ControlFlow::Break(Poll::Ready(Some(Err(e))));
            }
        }

        self.state = NLJState::FetchingRight;
        ControlFlow::Continue(())
    }

    /// Record the matches of the chunk that was just probed and move on to the
    /// next one. Memory-limited mode only.
    ///
    /// Unmatched-left rows are not emitted here, which would mean holding on to
    /// the chunk until every partition had probed it and one of them had gone
    /// through its rows again. Emission is deferred until every partition has
    /// probed every chunk, see
    /// [`Self::handle_emit_left_unmatched_memory_limited`].
    fn finish_left_chunk(&mut self) -> Result<()> {
        let Some(left_data) = self.buffered_left_data.take() else {
            return internal_err!("LeftData should be available");
        };
        let SpillState::Active(active) = &mut self.spill_state else {
            return internal_err!("finish_left_chunk called without Active spill state");
        };

        if need_produce_result_in_final(self.join_type) {
            active
                .left_spill
                .merge_visited(active.chunk_row_offset, &left_data.bitmap().lock());
        }
        active.chunk_row_offset += left_data.batch().num_rows();
        // Let go of the chunk before reporting, so that its memory is free by
        // the time the last partition has reported and the next one is loaded.
        drop(left_data);
        active.current_chunk = None;
        // These two go together: `LeftChunkBarrier::depart` tells a stream that
        // has finished the current chunk from one still probing it by
        // `chunk_index` being past the barrier's.
        active.chunk_index += 1;
        active.left_chunk_barrier.finish_chunk();

        self.left_probe_idx = 0;
        if self.left_exhausted {
            self.enter_state_after_last_left_chunk();
        } else {
            self.state = NLJState::BufferingLeft;
        }
        Ok(())
    }

    /// Every left chunk has been probed. Memory-limited mode only.
    fn enter_state_after_last_left_chunk(&mut self) {
        if self.should_track_unmatched_right {
            // Drop the exhausted right stream so that EmitGlobalRightUnmatched
            // opens a fresh replay pass from the spill file.
            self.right_data = None;
            self.state = NLJState::EmitGlobalRightUnmatched;
        } else {
            self.state = NLJState::ProbeEnd;
        }
    }

    /// Handle FetchingRight state - fetch next right batch and prepare for processing.
    ///
    /// In memory-limited mode during the first pass, each right batch is also
    /// written to a spill file so it can be re-read on subsequent passes.
    fn handle_fetching_right(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        let result = match self
            .right_data
            .as_mut()
            .expect("right_data must be present while fetching right")
            .poll_next_unpin(cx)
        {
            Poll::Ready(result) => result,
            Poll::Pending => return ControlFlow::Break(Poll::Pending),
        };

        let join_metric = self.metrics.join_metrics.join_time.clone();
        let _join_timer = join_metric.timer();

        match result {
            Some(Ok(right_batch)) => {
                // Update metrics
                let right_batch_rows = right_batch.num_rows();
                self.metrics.join_metrics.input_rows.add(right_batch_rows);
                self.metrics.join_metrics.input_batches.add(1);

                // Skip the empty batch
                if right_batch_rows == 0 {
                    return ControlFlow::Continue(());
                }

                self.current_right_batch = Some(right_batch);

                // Prepare right bitmap
                if self.should_track_unmatched_right
                    && !matches!(
                        self.join_type,
                        JoinType::RightSemi | JoinType::RightAnti
                    )
                {
                    let zeroed_buf = BooleanBuffer::new_unset(right_batch_rows);
                    self.current_right_batch_matched =
                        Some(BooleanArray::new(zeroed_buf, None));
                }

                self.left_probe_idx = 0;
                self.state = NLJState::ProbeRight;
                ControlFlow::Continue(())
            }
            Some(Err(e)) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
            None if self.is_memory_limited() => {
                // Right pass exhausted: probing for the current left chunk
                // is finished, but more chunks may remain.
                match self.finish_left_chunk() {
                    Ok(()) => ControlFlow::Continue(()),
                    Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
                }
            }
            None => {
                // Right side exhausted: probing is finished. `ProbeEnd`
                // reports probe completion before emitting unmatched-left
                // rows.
                self.state = NLJState::ProbeEnd;
                ControlFlow::Continue(())
            }
        }
    }

    /// Handle ProbeRight state - process current probe batch
    fn handle_probe_right(&mut self) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        // Return any completed batches first
        if let Some(poll) = self.maybe_flush_ready_batch() {
            return ControlFlow::Break(poll);
        }

        // Process current probe state
        match self.process_probe_batch() {
            // State unchanged (ProbeRight)
            // Continue probing until we have done joining the
            // current right batch with all buffered left rows.
            Ok(true) => ControlFlow::Continue(()),
            // To next FetchRightState
            // We have finished joining
            // (cur_right_batch x buffered_left_batches)
            Ok(false) => {
                // Left exhausted, transition to FetchingRight
                self.left_probe_idx = 0;

                // Selectivity Metric: Update total possibilities for the batch (left_rows * right_rows)
                // If memory-limited execution is implemented, this logic must be updated accordingly.
                if let (Ok(left_data), Some(right_batch)) =
                    (self.get_left_data(), self.current_right_batch.as_ref())
                {
                    let left_rows = left_data.batch().num_rows();
                    let right_rows = right_batch.num_rows();
                    self.metrics.selectivity.add_total(left_rows * right_rows);
                }

                if self.should_track_unmatched_right {
                    debug_assert!(
                        self.current_right_batch_matched.is_some(),
                        "If it's required to track matched rows in the right input, the right bitmap must be present"
                    );
                    self.state = NLJState::EmitRightUnmatched;
                } else {
                    self.current_right_batch = None;
                    self.state = NLJState::FetchingRight;
                }
                ControlFlow::Continue(())
            }
            Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
        }
    }

    /// Handle EmitRightUnmatched state - emit unmatched right rows.
    ///
    /// In memory-limited mode, instead of emitting unmatched right rows
    /// per-batch (which would be incorrect since more left chunks may
    /// match those rows), we merge the bitmap into the global accumulator
    /// and defer emission to `EmitGlobalRightUnmatched`.
    fn handle_emit_right_unmatched(
        &mut self,
    ) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        // In memory-limited mode, merge bitmap into global and move on
        if self.is_memory_limited() {
            debug_assert!(
                self.current_right_batch_matched.is_some(),
                "right bitmap must be present"
            );
            let bitmap = std::mem::take(&mut self.current_right_batch_matched)
                .expect("right bitmap should be available");
            let (values, _nulls) = bitmap.into_parts();

            if let SpillState::Active(ref mut active) = self.spill_state {
                let idx = active.right_batch_index;
                active.merge_current_right_bitmap(idx, values);
                active.right_batch_index += 1;
            }

            self.current_right_batch = None;
            self.state = NLJState::FetchingRight;
            return ControlFlow::Continue(());
        }

        // Standard (single-pass) mode: emit unmatched right rows immediately
        // Return any completed batches first
        if let Some(poll) = self.maybe_flush_ready_batch() {
            return ControlFlow::Break(poll);
        }

        debug_assert!(
            self.current_right_batch_matched.is_some()
                && self.current_right_batch.is_some(),
            "This state is yielding output for unmatched rows in the current right batch, so both the right batch and the bitmap must be present"
        );
        match self.process_right_unmatched() {
            Ok(Some(batch)) => match self.output_buffer.push_batch(batch) {
                Ok(()) => {
                    debug_assert!(self.current_right_batch.is_none());
                    self.state = NLJState::FetchingRight;
                    ControlFlow::Continue(())
                }
                Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
            },
            Ok(None) => {
                debug_assert!(self.current_right_batch.is_none());
                self.state = NLJState::FetchingRight;
                ControlFlow::Continue(())
            }
            Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
        }
    }

    /// Handle ProbeEnd state - record probe completion for this stream.
    ///
    /// Entered exactly once per stream, when it has probed the whole left side.
    /// This is the single place that decrements the shared probe-threads counter
    /// via [`ProbeCompletion::report_completed`]: the stream that drives the
    /// counter to zero (the last to finish probing) is the one responsible for
    /// emitting unmatched-left rows, recorded in `is_unmatched_left_emitter`.
    ///
    /// Owning the decrement here — rather than in the re-enterable
    /// `EmitLeftUnmatched` state — makes "decrement exactly once per stream" a
    /// structural property of the state graph, so the counter cannot reach zero
    /// before all partitions finish probing (which would let a partition emit
    /// spurious NULL-padded unmatched-left rows early).
    ///
    /// Always transitions to `EmitLeftUnmatched`.
    fn handle_probe_end(&mut self) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        // Decrement the shared counter exactly once for this stream. The
        // last stream to finish probing (the one that drives the counter to
        // zero) becomes the unmatched-left emitter.
        let is_emitter = if let SpillState::Active(active) = &mut self.spill_state {
            match active.left_spill.report_probe_completed() {
                Some(visited) => {
                    if need_produce_result_in_final(self.join_type) {
                        // Every chunk is done, which leaves `chunk_reservation`
                        // free to account for the bitmap this stream now owns.
                        active.chunk_reservation.grow(visited.len().div_ceil(8));
                        active.left_unmatched_pass = Some(LeftUnmatchedPass {
                            stream: None,
                            visited,
                            row_offset: 0,
                        });
                    }
                    true
                }
                None => false,
            }
        } else {
            match self.get_in_memory_probe_completion() {
                Ok(probe_completion) => match probe_completion.report_completed() {
                    Completion::NotLast => false,
                    // Nothing abandons the in-memory left side
                    Completion::Abandoned => false,
                    Completion::Emit(_) => true,
                },
                Err(e) => return ControlFlow::Break(Poll::Ready(Some(Err(e)))),
            }
        };
        self.is_unmatched_left_emitter = is_emitter;
        self.state = NLJState::EmitLeftUnmatched;
        ControlFlow::Continue(())
    }

    /// Handle EmitLeftUnmatched state - emit unmatched left rows.
    fn handle_emit_left_unmatched(
        &mut self,
    ) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        // Return any completed batches first
        if let Some(poll) = self.maybe_flush_ready_batch() {
            return ControlFlow::Break(poll);
        }

        // Process current unmatched state
        match self.process_left_unmatched() {
            // State unchanged (EmitLeftUnmatched)
            // Continue processing until we have processed all unmatched rows
            Ok(true) => ControlFlow::Continue(()),
            // We have finished processing all unmatched rows
            Ok(false) => match self.output_buffer.finish_buffered_batch() {
                Ok(()) => {
                    self.buffered_left_data = None;
                    self.in_memory_probe_completion = None;
                    self.state = NLJState::Done;
                    ControlFlow::Continue(())
                }
                Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
            },
            Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
        }
    }

    /// Memory-limited path for handle_emit_left_unmatched.
    ///
    /// The global visited bitmap is complete once the last stream has reported
    /// probe completion, and that stream is the emitter. It streams the left
    /// spill file one more time and emits the final left rows batch by batch,
    /// so no left chunk has to be held in memory for it. This mirrors
    /// `EmitGlobalRightUnmatched` on the right side.
    fn handle_emit_left_unmatched_memory_limited(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        // Return any completed batches first
        if let Some(poll) = self.maybe_flush_ready_batch() {
            return ControlFlow::Break(poll);
        }

        let SpillState::Active(active) = &mut self.spill_state else {
            unreachable!("memory-limited EmitLeftUnmatched without Active spill state");
        };

        // On first entry, the emitter opens its pass over the left spill file
        if let Some(pass) = active.left_unmatched_pass.as_mut()
            && pass.stream.is_none()
        {
            let join_metric = self.metrics.join_metrics.join_time.clone();
            let _join_timer = join_metric.timer();
            match active.left_spill.open_pass() {
                Ok(stream) => pass.stream = Some(stream),
                Err(e) => return ControlFlow::Break(Poll::Ready(Some(Err(e)))),
            }
        }

        // Poll the spill stream for the next left batch. Streams that are not
        // the emitter have nothing to read.
        let result = match active.left_unmatched_pass.as_mut() {
            Some(pass) => match pass
                .stream
                .as_mut()
                .expect("the pass was opened above")
                .poll_next_unpin(cx)
            {
                Poll::Ready(result) => result,
                Poll::Pending => return ControlFlow::Break(Poll::Pending),
            },
            None => None,
        };

        let join_metric = self.metrics.join_metrics.join_time.clone();
        let _join_timer = join_metric.timer();
        match result {
            Some(Ok(left_batch)) => {
                let pass = active
                    .left_unmatched_pass
                    .as_mut()
                    .expect("a left batch was read from the pass");
                let n_rows = left_batch.num_rows();
                let bitmap =
                    BooleanArray::new(pass.visited.slice(pass.row_offset, n_rows), None);
                pass.row_offset += n_rows;

                match build_unmatched_batch(
                    &self.output_schema,
                    &left_batch,
                    bitmap,
                    &active.right_schema,
                    &self.column_indices,
                    self.join_type,
                    JoinSide::Left,
                ) {
                    Ok(Some(batch)) => match self.output_buffer.push_batch(batch) {
                        Ok(()) => ControlFlow::Continue(()),
                        Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
                    },
                    Ok(None) => ControlFlow::Continue(()),
                    Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
                }
            }
            Some(Err(e)) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
            None => {
                active.left_unmatched_pass = None;
                active.chunk_reservation.free();
                match self.output_buffer.finish_buffered_batch() {
                    Ok(()) => {
                        self.state = NLJState::Done;
                        ControlFlow::Continue(())
                    }
                    Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
                }
            }
        }
    }

    /// Handle EmitGlobalRightUnmatched state.
    ///
    /// Replays all right batches from the spill file and emits unmatched
    /// right rows using the global bitmap accumulated across all left chunks.
    fn handle_emit_global_right_unmatched(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> ControlFlow<Poll<Option<Result<RecordBatch>>>> {
        // Flush any completed batches first
        if let Some(poll) = self.maybe_flush_ready_batch() {
            return ControlFlow::Break(poll);
        }

        // On first entry, open a new replay pass on the right input
        if self.right_data.is_none() {
            let join_metric = self.metrics.join_metrics.join_time.clone();
            let _join_timer = join_metric.timer();
            let SpillState::Active(ref mut active) = self.spill_state else {
                unreachable!("EmitGlobalRightUnmatched without Active spill state");
            };
            active.right_batch_index = 0;
            match active.right_input.open_pass() {
                Ok(stream) => {
                    self.right_data = Some(stream);
                }
                Err(e) => {
                    return ControlFlow::Break(Poll::Ready(Some(Err(e))));
                }
            }
        }

        // Poll the replay stream for the next right batch
        let result = match self
            .right_data
            .as_mut()
            .expect("right_data must be present")
            .poll_next_unpin(cx)
        {
            Poll::Ready(result) => result,
            Poll::Pending => return ControlFlow::Break(Poll::Pending),
        };

        let join_metric = self.metrics.join_metrics.join_time.clone();
        let _join_timer = join_metric.timer();
        match result {
            Some(Ok(right_batch)) => {
                if right_batch.num_rows() == 0 {
                    return ControlFlow::Continue(());
                }

                let SpillState::Active(ref mut active) = self.spill_state else {
                    unreachable!();
                };
                let idx = active.right_batch_index;
                active.right_batch_index += 1;

                // Build BooleanArray from the global bitmap
                let bitmap = if idx < active.global_right_bitmaps.len() {
                    BooleanArray::new(active.global_right_bitmaps[idx].clone(), None)
                } else {
                    // Batch never seen — treat all rows as unmatched
                    BooleanArray::new(
                        BooleanBuffer::new_unset(right_batch.num_rows()),
                        None,
                    )
                };

                match build_unmatched_batch(
                    &self.output_schema,
                    &right_batch,
                    bitmap,
                    &active.left_spill.schema,
                    &self.column_indices,
                    self.join_type,
                    JoinSide::Right,
                ) {
                    Ok(Some(batch)) => match self.output_buffer.push_batch(batch) {
                        Ok(()) => ControlFlow::Continue(()),
                        Err(e) => ControlFlow::Break(Poll::Ready(Some(arrow_err!(e)))),
                    },
                    Ok(None) => ControlFlow::Continue(()),
                    Err(e) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
                }
            }
            Some(Err(e)) => ControlFlow::Break(Poll::Ready(Some(Err(e)))),
            None => {
                // All right batches replayed. This stream has now probed the
                // whole left side, which `ProbeEnd` reports.
                self.right_data = None;
                self.state = NLJState::ProbeEnd;
                ControlFlow::Continue(())
            }
        }
    }

    /// Handle Done state - final state processing
    fn handle_done(&mut self) -> Poll<Option<Result<RecordBatch>>> {
        // Return any remaining completed batches before final termination
        if let Some(poll) = self.maybe_flush_ready_batch() {
            return poll;
        }

        // HACK for the doc test in https://github.com/apache/datafusion/blob/main/datafusion/core/src/dataframe/mod.rs#L1265
        // If this operator directly return `Poll::Ready(None)`
        // for empty result, the final result will become an empty
        // batch with empty schema, however the expected result
        // should be with the expected schema for this operator
        if !self.handled_empty_output {
            let zero_count = Count::new();
            if *self.metrics.join_metrics.baseline.output_rows() == zero_count {
                let empty_batch = RecordBatch::new_empty(Arc::clone(&self.output_schema));
                self.handled_empty_output = true;
                return Poll::Ready(Some(Ok(empty_batch)));
            }
        }

        Poll::Ready(None)
    }

    // ==== Core logic handling for each state ====

    /// Returns bool to indicate should it continue probing
    /// true -> continue in the same ProbeRight state
    /// false -> It has done with the (buffered_left x cur_right_batch), go to
    /// next state (ProbeRight)
    fn process_probe_batch(&mut self) -> Result<bool> {
        let left_data = Arc::clone(self.get_left_data()?);
        if matches!(self.join_type, JoinType::RightSemi | JoinType::RightAnti) {
            if self.right_existence_probe.is_none() {
                let right = self.current_right_batch.as_ref().ok_or_else(|| {
                    internal_datafusion_err!("Right batch should be available")
                })?;
                self.right_existence_probe =
                    Some(RightExistenceProbe::new(right, self.join_filter.as_ref())?);
            }
            let probe = self.right_existence_probe.as_mut().unwrap();
            if probe.remaining == 0 || self.left_probe_idx >= left_data.batch().num_rows()
            {
                let mut probe = self.right_existence_probe.take().unwrap();
                self.current_right_batch_matched =
                    Some(BooleanArray::new(probe.matched.finish(), None));
                // In spill mode this completes only the current left chunk.
                // EmitRightUnmatched merges these original-row matches across chunks.
                return Ok(false);
            }
            self.left_probe_idx +=
                probe.probe(left_data.batch(), self.left_probe_idx, self.batch_size)?;
            return Ok(true);
        }
        let right_batch = self
            .current_right_batch
            .as_ref()
            .ok_or_else(|| internal_datafusion_err!("Right batch should be available"))?
            .clone();

        // stop probing, the caller will go to the next state
        if self.left_probe_idx >= left_data.batch().num_rows() {
            return Ok(false);
        }

        // ========
        // Join (l_row x right_batch)
        // and push the result into output_buffer
        // ========

        // Special case:
        // When the right batch is very small, join with multiple left rows at once,
        //
        // The regular implementation is not efficient if the plan's right child is
        // very small (e.g. 1 row total), because inside the inner loop of NLJ, it's
        // handling one input right batch at once, if it's not large enough, the
        // overheads like filter evaluation can't be amortized through vectorization.
        debug_assert_ne!(
            right_batch.num_rows(),
            0,
            "When fetching the right batch, empty batches will be skipped"
        );

        let l_row_cnt_ratio = self.batch_size / right_batch.num_rows();
        if l_row_cnt_ratio > 10 {
            // Calculate max left rows to handle at once. This operator tries to handle
            // up to `datafusion.execution.batch_size` rows at once in the intermediate
            // batch.
            let l_row_count = std::cmp::min(
                l_row_cnt_ratio,
                left_data.batch().num_rows() - self.left_probe_idx,
            );

            debug_assert!(
                l_row_count != 0,
                "This function should only be entered when there are remaining left rows to process"
            );
            let joined_batch = self.process_left_range_join(
                &left_data,
                &right_batch,
                self.left_probe_idx,
                l_row_count,
            )?;

            if let Some(batch) = joined_batch {
                self.output_buffer.push_batch(batch)?;
            }

            self.left_probe_idx += l_row_count;

            return Ok(true);
        }

        let l_idx = self.left_probe_idx;
        let joined_batch =
            self.process_single_left_row_join(&left_data, &right_batch, l_idx)?;

        if let Some(batch) = joined_batch {
            self.output_buffer.push_batch(batch)?;
        }

        // ==== Prepare for the next iteration ====

        // Advance left cursor
        self.left_probe_idx += 1;

        // Return true to continue probing
        Ok(true)
    }

    /// Process [l_start_index, l_start_index + l_count) JOIN right_batch
    /// Returns a RecordBatch containing the join results (None if empty)
    ///
    /// Side Effect: If the join type requires, left or right side matched bitmap
    /// will be set for matched indices.
    fn process_left_range_join(
        &mut self,
        left_data: &JoinLeftData,
        right_batch: &RecordBatch,
        l_start_index: usize,
        l_row_count: usize,
    ) -> Result<Option<RecordBatch>> {
        // Construct the Cartesian product between the specified range of left rows
        // and the entire right_batch. First, it calculates the index vectors, then
        // materializes the intermediate batch, and finally applies the join filter
        // to it.
        // -----------------------------------------------------------
        let left_batch = left_data.batch();
        let right_rows = right_batch.num_rows();
        let total_rows = l_row_count * right_rows;

        // Build index arrays for cartesian product: left_range X right_batch
        let left_indices = left_batch.row_indices(
            (0..l_row_count)
                .flat_map(|i| std::iter::repeat_n(l_start_index + i, right_rows)),
        )?;
        let right_indices: UInt32Array = UInt32Array::from_iter_values(
            (0..l_row_count).flat_map(|_| 0..right_rows as u32),
        );

        debug_assert!(
            left_indices.len() == right_indices.len()
                && right_indices.len() == total_rows,
            "The length or cartesian product should be (left_size * right_size)",
        );

        // Evaluate the join filter (if any) over an intermediate batch built
        // using the filter's own schema/column indices.
        let bitmap_combined = if let Some(filter) = &self.join_filter {
            apply_filter_to_indices(
                left_data.batch(),
                right_batch,
                &left_indices,
                &right_indices,
                filter,
            )?
        } else {
            // No filter: all pairs match
            BooleanArray::new(BooleanBuffer::new_set(total_rows), None)
        };

        // Update the global left or right bitmap for matched indices
        // -----------------------------------------------------------

        // None means we don't have to update left bitmap for this join type
        let mut left_bitmap = if need_produce_result_in_final(self.join_type) {
            Some(left_data.bitmap().lock())
        } else {
            None
        };

        // 'local' meaning: we want to collect 'is_matched' flag for the current
        // right batch, after it has joining all of the left buffer, here it's only
        // the partial result for joining given left range
        let mut local_right_bitmap = if self.should_track_unmatched_right {
            let mut current_right_batch_bitmap = BooleanBufferBuilder::new(right_rows);
            // Ensure builder has logical length so set_bit is in-bounds
            current_right_batch_bitmap.append_n(right_rows, false);
            Some(current_right_batch_bitmap)
        } else {
            None
        };

        // Set the matched bit for left and right side bitmap
        for (i, is_matched) in bitmap_combined.iter().enumerate() {
            let is_matched = is_matched.ok_or_else(|| {
                internal_datafusion_err!("Must be Some after the previous combining step")
            })?;

            let l_index = l_start_index + i / right_rows;
            let r_index = i % right_rows;

            if let Some(bitmap) = left_bitmap.as_mut()
                && is_matched
            {
                // Map local index back to absolute left index within the batch
                bitmap.set_bit(l_index, true);
            }

            if let Some(bitmap) = local_right_bitmap.as_mut()
                && is_matched
            {
                bitmap.set_bit(r_index, true);
            }
        }

        // Apply the local right bitmap to the global bitmap
        if self.should_track_unmatched_right {
            // Remember to put it back after update
            let global_right_bitmap =
                std::mem::take(&mut self.current_right_batch_matched).ok_or_else(
                    || internal_datafusion_err!("right batch's bitmap should be present"),
                )?;
            let (buf, nulls) = global_right_bitmap.into_parts();
            debug_assert!(nulls.is_none());

            let current_right_bitmap = local_right_bitmap
                .ok_or_else(|| {
                    internal_datafusion_err!(
                        "Should be Some if the current join type requires right bitmap"
                    )
                })?
                .finish();
            let updated_global_right_bitmap = buf.bitor(&current_right_bitmap);

            self.current_right_batch_matched =
                Some(BooleanArray::new(updated_global_right_bitmap, None));
        }

        // For the following join types: only bitmaps are updated; do not emit rows now
        if matches!(
            self.join_type,
            JoinType::LeftAnti
                | JoinType::LeftSemi
                | JoinType::LeftMark
                | JoinType::RightAnti
                | JoinType::RightMark
                | JoinType::RightSemi
        ) {
            return Ok(None);
        }

        // Build the projected output batch (using output schema/column_indices),
        // then apply the bitmap filter to it.
        if self.output_schema.fields().is_empty() {
            // Empty projection: only row count matters
            let row_count = bitmap_combined.true_count();
            return Ok(Some(create_record_batch_with_empty_schema(
                Arc::clone(&self.output_schema),
                row_count,
            )?));
        }

        let mut out_columns: Vec<Arc<dyn Array>> =
            Vec::with_capacity(self.output_schema.fields().len());
        for column_index in &self.column_indices {
            let array = if column_index.side == JoinSide::Left {
                left_batch.take_column(column_index.index, &left_indices)?
            } else {
                let col = right_batch.column(column_index.index);
                take(col.as_ref(), &right_indices, None)?
            };
            out_columns.push(array);
        }
        let pre_filtered =
            RecordBatch::try_new(Arc::clone(&self.output_schema), out_columns)?;
        let filtered = filter_record_batch(&pre_filtered, &bitmap_combined)?;
        Ok(Some(filtered))
    }

    /// Process a single left row join with the current right batch.
    /// Returns a RecordBatch containing the join results (None if empty)
    ///
    /// Side Effect: If the join type requires, left or right side matched bitmap
    /// will be set for matched indices.
    fn process_single_left_row_join(
        &mut self,
        left_data: &JoinLeftData,
        right_batch: &RecordBatch,
        l_index: usize,
    ) -> Result<Option<RecordBatch>> {
        let right_row_count = right_batch.num_rows();
        if right_row_count == 0 {
            return Ok(None);
        }

        let left_row = left_data.batch().row(l_index)?;
        let cur_right_bitmap = if let Some(filter) = &self.join_filter {
            apply_filter_to_row_join_batch(left_row, right_batch, filter)?
        } else {
            BooleanArray::new(BooleanBuffer::new_set(right_row_count), None)
        };

        self.update_matched_bitmap(l_index, &cur_right_bitmap)?;

        // For the following join types: here we only have to set the left/right
        // bitmap, and no need to output result
        if matches!(
            self.join_type,
            JoinType::LeftAnti
                | JoinType::LeftSemi
                | JoinType::LeftMark
                | JoinType::RightAnti
                | JoinType::RightMark
                | JoinType::RightSemi
        ) {
            return Ok(None);
        }

        if !cur_right_bitmap.has_true() {
            // If none of the pairs has passed the join predicate/filter
            Ok(None)
        } else {
            // Use the optimized approach similar to build_intermediate_batch_for_single_left_row
            let join_batch = build_row_join_batch(
                &self.output_schema,
                left_row,
                right_batch,
                Some(cur_right_bitmap),
                &self.column_indices,
                JoinSide::Left,
            )?;
            Ok(join_batch)
        }
    }

    /// Returns bool to indicate should it continue processing unmatched rows
    /// true -> continue in the same EmitLeftUnmatched state
    /// false -> next state (Done)
    fn process_left_unmatched(&mut self) -> Result<bool> {
        let left_data = self.get_left_data()?;
        let left_batch = left_data.batch();

        // ========
        // Check early return conditions
        // ========

        // Early return if join type can't have unmatched rows
        let join_type_no_produce_left = !need_produce_result_in_final(self.join_type);
        // Stop processing unmatched rows, the caller will go to the next state
        let finished = self.left_emit_idx >= left_batch.num_rows();

        // `ProbeEnd` already recorded whether this stream emits unmatched-left
        // rows. Every probe partition passes through this state, but only the
        // one that finished probing last is the emitter, so this flag is false
        // for the others.
        if join_type_no_produce_left || !self.is_unmatched_left_emitter || finished {
            return Ok(false);
        }

        // ========
        // Process unmatched rows and push the result into output_buffer
        // Each time, the number to process is up to batch size
        // ========
        let start_idx = self.left_emit_idx;
        let end_idx = std::cmp::min(start_idx + self.batch_size, left_batch.num_rows());

        if let Some(batch) =
            self.process_left_unmatched_range(left_data, start_idx, end_idx)?
        {
            self.output_buffer.push_batch(batch)?;
        }

        // ==== Prepare for the next iteration ====
        self.left_emit_idx = end_idx;

        // Return true to continue processing unmatched rows
        Ok(true)
    }

    /// Process unmatched rows from the left data within the specified range.
    /// Returns a RecordBatch containing the unmatched rows (None if empty).
    ///
    /// # Arguments
    /// * `left_data` - The left side data containing the batch and bitmap
    /// * `start_idx` - Start index (inclusive) of the range to process
    /// * `end_idx` - End index (exclusive) of the range to process
    ///
    /// # Safety
    /// The caller is responsible for ensuring that `start_idx` and `end_idx` are
    /// within valid bounds of the left batch. This function does not perform
    /// bounds checking.
    fn process_left_unmatched_range(
        &self,
        left_data: &JoinLeftData,
        start_idx: usize,
        end_idx: usize,
    ) -> Result<Option<RecordBatch>> {
        if start_idx == end_idx {
            return Ok(None);
        }

        // Slice both left batch, and bitmap to range [start_idx, end_idx)
        // The range is bit index (not byte)
        let left_batch_sliced =
            left_data.batch().slice(start_idx, end_idx - start_idx)?;

        let bitmap_sliced = {
            let bitmap = left_data.bitmap().lock();
            BooleanBuffer::collect_bool(end_idx - start_idx, |i| {
                bitmap.get_bit(start_idx + i)
            })
        };
        let bitmap_sliced = BooleanArray::new(bitmap_sliced, None);

        let right_schema = self
            .right_data
            .as_ref()
            .expect("right_data must be present when building unmatched batch")
            .schema();
        build_unmatched_batch(
            &self.output_schema,
            &left_batch_sliced,
            bitmap_sliced,
            &right_schema,
            &self.column_indices,
            self.join_type,
            JoinSide::Left,
        )
    }

    /// Process unmatched rows from the current right batch and reset the bitmap.
    /// Returns a RecordBatch containing the unmatched right rows (None if empty).
    fn process_right_unmatched(&mut self) -> Result<Option<RecordBatch>> {
        // ==== Take current right batch and its bitmap ====
        let right_batch_bitmap: BooleanArray =
            std::mem::take(&mut self.current_right_batch_matched).ok_or_else(|| {
                internal_datafusion_err!("right bitmap should be available")
            })?;

        let right_batch = self.current_right_batch.take();
        let cur_right_batch = unwrap_or_internal_err!(right_batch);

        let left_data = self.get_left_data()?;
        let left_schema = left_data.batch().schema();

        let res = build_unmatched_batch(
            &self.output_schema,
            &cur_right_batch,
            right_batch_bitmap,
            &left_schema,
            &self.column_indices,
            self.join_type,
            JoinSide::Right,
        );

        // ==== Clean-up ====
        self.current_right_batch_matched = None;

        res
    }

    // ==== Utilities ====

    /// Get the build-side data of the left input, errors if it's None
    fn get_left_data(&self) -> Result<&Arc<JoinLeftData>> {
        self.buffered_left_data
            .as_ref()
            .ok_or_else(|| internal_datafusion_err!("LeftData should be available"))
    }

    fn get_in_memory_probe_completion(&self) -> Result<&Arc<ProbeCompletion>> {
        self.in_memory_probe_completion.as_ref().ok_or_else(|| {
            internal_datafusion_err!("In-memory probe completion should be available")
        })
    }

    /// Flush the `output_buffer` if there are batches ready to output
    /// None if no result batch ready.
    fn maybe_flush_ready_batch(&mut self) -> Option<Poll<Option<Result<RecordBatch>>>> {
        if self.output_buffer.has_completed_batch()
            && let Some(batch) = self.output_buffer.next_completed_batch()
        {
            // Update output rows for selectivity metric
            let output_rows = batch.num_rows();
            self.metrics.selectivity.add_part(output_rows);

            return Some(Poll::Ready(Some(Ok(batch))));
        }

        None
    }

    /// After joining (l_index@left_buffer x current_right_batch), it will result
    /// in a bitmap (the same length as current_right_batch) as the join match
    /// result. Use this bitmap to update the global bitmap, for special join
    /// types like full joins.
    ///
    /// Example:
    /// After joining l_index=1 (1-indexed row in the left buffer), and the
    /// current right batch with 3 elements, this function will be called with
    /// arguments: l_index = 1, r_matched = [false, false, true]
    /// - If the join type is FullJoin, the 1-index in the left bitmap will be
    ///   set to true, and also the right bitmap will be bitwise-ORed with the
    ///   input r_matched bitmap.
    /// - For join types that don't require output unmatched rows, this
    ///   function can be a no-op. For inner joins, this function is a no-op; for left
    ///   joins, only the left bitmap may be updated.
    fn update_matched_bitmap(
        &mut self,
        l_index: usize,
        r_matched_bitmap: &BooleanArray,
    ) -> Result<()> {
        let left_data = self.get_left_data()?;

        // 1. Maybe update the left bitmap
        if need_produce_result_in_final(self.join_type) && r_matched_bitmap.has_true() {
            let mut bitmap = left_data.bitmap().lock();
            bitmap.set_bit(l_index, true);
        }

        // 2. Maybe update the right bitmap
        if self.should_track_unmatched_right {
            debug_assert!(self.current_right_batch_matched.is_some());
            // after bit-wise or, it will be put back
            let right_bitmap = std::mem::take(&mut self.current_right_batch_matched)
                .ok_or_else(|| {
                    internal_datafusion_err!("right batch's bitmap should be present")
                })?;
            let (buf, nulls) = right_bitmap.into_parts();
            debug_assert!(nulls.is_none());
            let updated_right_bitmap = buf.bitor(r_matched_bitmap.values());

            self.current_right_batch_matched =
                Some(BooleanArray::new(updated_right_bitmap, None));
        }

        Ok(())
    }
}

// ==== Utilities ====

/// Evaluate a Cartesian product using only the columns referenced by the filter.
fn apply_filter_to_indices(
    left: &LogicalBatch,
    right: &RecordBatch,
    left_indices: &RowIndices,
    right_indices: &UInt32Array,
    filter: &JoinFilter,
) -> Result<BooleanArray> {
    let columns = filter
        .column_indices()
        .iter()
        .map(|column| {
            if column.side == JoinSide::Left {
                left.take_column(column.index, left_indices)
            } else {
                Ok(take(
                    right.column(column.index).as_ref(),
                    right_indices,
                    None,
                )?)
            }
        })
        .collect::<Result<Vec<_>>>()?;
    let options = RecordBatchOptions::new().with_row_count(Some(left_indices.len()));
    let intermediate = RecordBatch::try_new_with_options(
        Arc::clone(filter.schema()),
        columns,
        &options,
    )?;
    let result = filter
        .expression()
        .evaluate(&intermediate)?
        .into_array(intermediate.num_rows())?;
    Ok(boolean_mask_from_filter(as_boolean_array(&result)?))
}

/// Apply the join filter between:
/// (left_row in left buffer) x (right batch)
/// Returns a bitmap, with successfully joined indices set to true
fn apply_filter_to_row_join_batch(
    left_row: BatchRow<'_>,
    right_batch: &RecordBatch,
    filter: &JoinFilter,
) -> Result<BooleanArray> {
    debug_assert!(right_batch.num_rows() != 0);

    let intermediate_batch = if filter.schema.fields().is_empty() {
        // If filter is constant (e.g. literal `true`), empty batch can be used
        // in the later filter step.
        create_record_batch_with_empty_schema(
            Arc::new((*filter.schema).clone()),
            right_batch.num_rows(),
        )?
    } else {
        build_row_join_batch(
            &filter.schema,
            left_row,
            right_batch,
            None,
            &filter.column_indices,
            JoinSide::Left,
        )?
        .ok_or_else(|| internal_datafusion_err!("This function assume input batch is not empty, so the intermediate batch can't be empty too"))?
    };

    let filter_result = filter
        .expression()
        .evaluate(&intermediate_batch)?
        .into_array(intermediate_batch.num_rows())?;
    let filter_arr = as_boolean_array(&filter_result)?;

    // Convert boolean array with potential nulls into a unified mask bitmap
    let bitmap_combined = boolean_mask_from_filter(filter_arr);

    Ok(bitmap_combined)
}

/// This function performs the following steps:
/// 1. Apply filter to probe-side batch
/// 2. Broadcast the build row (`build_row`) to the filtered probe-side batch
/// 3. Concat them together according to `col_indices`, and return the result
///    (None if the result is empty)
///
/// Example:
/// build side batch:
/// a
/// ----
/// 1
/// 2
/// 3
///
/// # 0 index row of the build side batch (that is `1`) will be used
/// build_row: row 0
///
/// probe_side_batch:
/// b
/// ----
/// 10
/// 20
/// 30
/// 40
///
/// # After applying it, only index 1 and 3 elements in probe_side_batch will be
/// # kept
/// probe_side_filter:
/// false
/// true
/// false
/// true
///
///
/// # Projections to the build/probe side batch, to construct the output batch
/// col_indices:
/// [(left, 0), (right, 0)]
///
/// build_side: left
///
/// ====
/// Result batch:
/// a b
/// ----
/// 1 20
/// 1 40
fn build_row_join_batch(
    output_schema: &Schema,
    build_row: BatchRow<'_>,
    probe_side_batch: &RecordBatch,
    probe_side_filter: Option<BooleanArray>,
    // See [`NLJStream`] struct's `column_indices` field for more detail
    col_indices: &[ColumnIndex],
    // If the build side is left or right, used to interpret the side information
    // in `col_indices`
    build_side: JoinSide,
) -> Result<Option<RecordBatch>> {
    debug_assert_ne!(build_side, JoinSide::None);

    // TODO(perf): since the output might be projection of right batch, this
    // filtering step is more efficient to be done inside the column_index loop
    let filtered_probe_batch = if let Some(filter) = probe_side_filter {
        &filter_record_batch(probe_side_batch, &filter)?
    } else {
        probe_side_batch
    };

    if filtered_probe_batch.num_rows() == 0 {
        return Ok(None);
    }

    // Edge case: downstream operator does not require any columns from this NLJ,
    // so allow an empty projection.
    // Example:
    //  SELECT DISTINCT 32 AS col2
    //  FROM tab0 AS cor0
    //  LEFT OUTER JOIN tab2 AS cor1
    //  ON ( NULL ) IS NULL;
    if output_schema.fields.is_empty() {
        return Ok(Some(create_record_batch_with_empty_schema(
            Arc::new(output_schema.clone()),
            filtered_probe_batch.num_rows(),
        )?));
    }

    let mut columns: Vec<Arc<dyn Array>> =
        Vec::with_capacity(output_schema.fields().len());

    for column_index in col_indices {
        let array = if column_index.side == build_side {
            // Broadcast the single build-side row to match the filtered
            // probe-side batch length
            let original_left_array = build_row.column(column_index.index)?;

            // Use `arrow::compute::take` directly for `List(Utf8View)` rather
            // than going through `ScalarValue::to_array_of_size()`, which
            // avoids some intermediate allocations.
            //
            // In other cases, `to_array_of_size()` is faster.
            match original_left_array.data_type() {
                DataType::List(field) | DataType::LargeList(field)
                    if field.data_type() == &DataType::Utf8View =>
                {
                    let indices_iter = std::iter::repeat_n(
                        build_row.index() as u64,
                        filtered_probe_batch.num_rows(),
                    );
                    let indices_array = UInt64Array::from_iter_values(indices_iter);
                    take(original_left_array.as_ref(), &indices_array, None)?
                }
                _ => {
                    let scalar_value = ScalarValue::try_from_array(
                        original_left_array.as_ref(),
                        build_row.index(),
                    )?;
                    scalar_value.to_array_of_size(filtered_probe_batch.num_rows())?
                }
            }
        } else {
            // Take the filtered probe-side column using compute::take
            Arc::clone(filtered_probe_batch.column(column_index.index))
        };

        columns.push(array);
    }

    Ok(Some(RecordBatch::try_new(
        Arc::new(output_schema.clone()),
        columns,
    )?))
}

/// Special case for `PlaceHolderRowExec`
/// Minimal example:  SELECT 1 WHERE EXISTS (SELECT 1);
//
/// # Return
/// If Some, that's the result batch
/// If None, it's not for this special case. Continue execution.
fn build_unmatched_batch_empty_schema(
    output_schema: &SchemaRef,
    batch_bitmap: &BooleanArray,
    // For left/right/full joins, it needs to fill nulls for another side
    join_type: JoinType,
) -> Result<Option<RecordBatch>> {
    let result_size = match join_type {
        JoinType::Left
        | JoinType::Right
        | JoinType::Full
        | JoinType::LeftAnti
        | JoinType::RightAnti => batch_bitmap.false_count(),
        JoinType::LeftSemi | JoinType::RightSemi => batch_bitmap.true_count(),
        JoinType::LeftMark | JoinType::RightMark => batch_bitmap.len(),
        _ => unreachable!(),
    };

    if output_schema.fields().is_empty() {
        Ok(Some(create_record_batch_with_empty_schema(
            Arc::clone(output_schema),
            result_size,
        )?))
    } else {
        Ok(None)
    }
}

/// Creates an empty RecordBatch with a specific row count.
/// This is useful for cases where we need a batch with the correct schema and row count
/// but no actual data columns (e.g., for constant filters).
fn create_record_batch_with_empty_schema(
    schema: SchemaRef,
    row_count: usize,
) -> Result<RecordBatch> {
    let options = RecordBatchOptions::new()
        .with_match_field_names(true)
        .with_row_count(Some(row_count));

    RecordBatch::try_new_with_options(schema, vec![], &options).map_err(|e| {
        internal_datafusion_err!("Failed to create empty record batch: {}", e)
    })
}

/// # Example:
/// batch:
/// a
/// ----
/// 1
/// 2
/// 3
///
/// batch_bitmap:
/// ----
/// false
/// true
/// false
///
/// another_side_schema:
/// [(b, bool), (c, int32)]
///
/// join_type: JoinType::Left
///
/// col_indices: ...(please refer to the comment in `NLJStream::column_indices``)
///
/// batch_side: right
///
/// # Walkthrough:
///
/// This executor is performing a right join, and the currently processed right
/// batch is as above. After joining it with all buffered left rows, the joined
/// entries are marked by the `batch_bitmap`.
/// This method will keep the unmatched indices on the batch side (right), and pad
/// the left side with nulls. The result would be:
///
/// b          c           a
/// ------------------------
/// Null(bool) Null(Int32) 1
/// Null(bool) Null(Int32) 3
fn build_unmatched_batch(
    output_schema: &SchemaRef,
    batch: &RecordBatch,
    batch_bitmap: BooleanArray,
    // For left/right/full joins, it needs to fill nulls for another side
    another_side_schema: &SchemaRef,
    col_indices: &[ColumnIndex],
    join_type: JoinType,
    batch_side: JoinSide,
) -> Result<Option<RecordBatch>> {
    // Should not call it for inner joins
    debug_assert_ne!(join_type, JoinType::Inner);
    debug_assert_ne!(batch_side, JoinSide::None);

    // Handle special case (see function comment)
    if let Some(batch) =
        build_unmatched_batch_empty_schema(output_schema, &batch_bitmap, join_type)?
    {
        return Ok(Some(batch));
    }

    match join_type {
        JoinType::Full | JoinType::Right | JoinType::Left => {
            if join_type == JoinType::Right {
                debug_assert_eq!(batch_side, JoinSide::Right);
            }
            if join_type == JoinType::Left {
                debug_assert_eq!(batch_side, JoinSide::Left);
            }

            // 1. Filter the batch with *flipped* bitmap
            // 2. Fill left side with nulls
            let flipped_bitmap = not(&batch_bitmap)?;

            // create a record batch, with left_schema, of only one row of all nulls
            let left_null_columns: Vec<Arc<dyn Array>> = another_side_schema
                .fields()
                .iter()
                .map(|field| new_null_array(field.data_type(), 1))
                .collect();

            // Hack: If the left schema is not nullable, the full join result
            // might contain null, this is only a temporary batch to construct
            // such full join result.
            let nullable_left_schema = Arc::new(Schema::new(
                another_side_schema
                    .fields()
                    .iter()
                    .map(|field| (**field).clone().with_nullable(true))
                    .collect::<Vec<_>>(),
            ));
            let left_null_batch = if nullable_left_schema.fields.is_empty() {
                // Keep the placeholder row even when no columns from this
                // side are projected, so BatchRow can address row 0.
                create_record_batch_with_empty_schema(nullable_left_schema, 1)?
            } else {
                RecordBatch::try_new(nullable_left_schema, left_null_columns)?
            };

            debug_assert_ne!(batch_side, JoinSide::None);
            let opposite_side = batch_side.negate();

            build_row_join_batch(
                output_schema,
                BatchRow::new(&left_null_batch, 0)?,
                batch,
                Some(flipped_bitmap),
                col_indices,
                opposite_side,
            )
        }
        JoinType::RightSemi
        | JoinType::RightAnti
        | JoinType::LeftSemi
        | JoinType::LeftAnti => {
            if matches!(join_type, JoinType::RightSemi | JoinType::RightAnti) {
                debug_assert_eq!(batch_side, JoinSide::Right);
            }
            if matches!(join_type, JoinType::LeftSemi | JoinType::LeftAnti) {
                debug_assert_eq!(batch_side, JoinSide::Left);
            }

            let bitmap = if matches!(join_type, JoinType::LeftSemi | JoinType::RightSemi)
            {
                batch_bitmap.clone()
            } else {
                not(&batch_bitmap)?
            };

            if !bitmap.has_true() {
                return Ok(None);
            }

            let mut columns: Vec<Arc<dyn Array>> =
                Vec::with_capacity(output_schema.fields().len());

            for column_index in col_indices {
                debug_assert_eq!(column_index.side, batch_side);

                let col = batch.column(column_index.index);
                let filtered_col = filter(col, &bitmap)?;

                columns.push(filtered_col);
            }

            Ok(Some(RecordBatch::try_new(
                Arc::clone(output_schema),
                columns,
            )?))
        }
        JoinType::RightMark | JoinType::LeftMark => {
            if join_type == JoinType::RightMark {
                debug_assert_eq!(batch_side, JoinSide::Right);
            }
            if join_type == JoinType::LeftMark {
                debug_assert_eq!(batch_side, JoinSide::Left);
            }

            let mut columns: Vec<Arc<dyn Array>> =
                Vec::with_capacity(output_schema.fields().len());

            // Hack to deal with the borrow checker
            let mut right_batch_bitmap_opt = Some(batch_bitmap);

            for column_index in col_indices {
                if column_index.side == batch_side {
                    let col = batch.column(column_index.index);

                    columns.push(Arc::clone(col));
                } else if column_index.side == JoinSide::None {
                    let right_batch_bitmap = std::mem::take(&mut right_batch_bitmap_opt);
                    match right_batch_bitmap {
                        Some(right_batch_bitmap) => {
                            columns.push(Arc::new(right_batch_bitmap))
                        }
                        None => unreachable!("Should only be one mark column"),
                    }
                } else {
                    return internal_err!(
                        "Not possible to have this join side for RightMark join"
                    );
                }
            }

            Ok(Some(RecordBatch::try_new(
                Arc::clone(output_schema),
                columns,
            )?))
        }
        _ => internal_err!(
            "If batch is at right side, this function must be handling Full/Right/RightSemi/RightAnti/RightMark joins"
        ),
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use std::pin::Pin;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    use super::*;
    use crate::statistics::{StatisticsArgs, StatisticsContext};
    use crate::test::{TestMemoryExec, assert_join_metrics};
    use crate::{
        common, expressions::Column, repartition::RepartitionExec, test::build_table_i32,
    };

    use arrow::compute::SortOptions;
    use arrow::datatypes::{DataType, Field};
    use bytes::Bytes;
    use datafusion_common::assert_contains;
    use datafusion_common::instant::Instant;
    use datafusion_common::test_util::batches_to_sort_string;
    use datafusion_common_runtime::SpawnedTask;
    use datafusion_execution::disk_manager::{
        DiskManager, DiskManagerBuilder, DiskManagerMode,
    };
    use datafusion_execution::runtime_env::RuntimeEnvBuilder;
    use datafusion_execution::spill_file::{SpillFile, SpillWriter, TempFileFactory};
    use datafusion_expr::Operator;
    use datafusion_physical_expr::expressions::{BinaryExpr, Literal};
    use datafusion_physical_expr::{Partitioning, PhysicalExpr};
    use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};

    use insta::allow_duplicates;
    use insta::assert_snapshot;
    use rstest::rstest;

    #[test]
    fn test_nlj_dynamic_filter_pushdown() -> Result<()> {
        use crate::filter_pushdown::PushedDown;
        use arrow::array::record_batch;
        use datafusion_physical_expr::expressions::lit;

        // Identical names within and across inputs must not affect routing.
        // Reordered outputs also exercise the NLJ's embedded projection.
        let batch = record_batch!(("key", Int32, [1, 2]), ("key", Int32, [2, 1]))?;
        let input: Arc<dyn ExecutionPlan> =
            TestMemoryExec::try_new_exec(&[vec![batch.clone()]], batch.schema(), None)?;
        for join_type in [
            JoinType::Inner,
            JoinType::Left,
            JoinType::Right,
            JoinType::Full,
            JoinType::LeftSemi,
            JoinType::RightSemi,
            JoinType::LeftAnti,
            JoinType::RightAnti,
            JoinType::LeftMark,
            JoinType::RightMark,
        ] {
            let join = NestedLoopJoinExec::try_new(
                Arc::clone(&input),
                Arc::clone(&input),
                None,
                &join_type,
                None,
            )?;
            for reorder in [false, true] {
                let projection =
                    reorder.then(|| (0..join.schema().fields().len()).rev().collect());
                let join = join.with_projection(projection)?;
                for output in 0..join.schema().fields().len() {
                    let column: Arc<dyn PhysicalExpr> =
                        Arc::new(Column::new(join.schema().field(output).name(), output));
                    let source = Arc::new(DynamicFilterPhysicalExpr::new(
                        vec![Arc::clone(&column)],
                        lit(true),
                    ));
                    let filters = join
                        .gather_filters_for_pushdown(
                            FilterPushdownPhase::Post,
                            vec![Arc::clone(&source) as _],
                            &ConfigOptions::default(),
                        )?
                        .parent_filters();
                    let unprojected =
                        join.projection.as_ref().map_or(output, |p| p[output]);
                    let side = join.column_indices[unprojected].side;
                    let expected = match join_type {
                        JoinType::Inner => {
                            [side == JoinSide::Left, side == JoinSide::Right]
                        }
                        JoinType::Left
                        | JoinType::LeftSemi
                        | JoinType::LeftAnti
                        | JoinType::LeftMark => [side == JoinSide::Left, false],
                        JoinType::Right
                        | JoinType::RightSemi
                        | JoinType::RightAnti
                        | JoinType::RightMark => [false, side == JoinSide::Right],
                        JoinType::Full => [false, false],
                    };
                    // Update after routing to prove the remapped consumer stays live.
                    source.update(Arc::new(BinaryExpr::new(
                        column,
                        Operator::Eq,
                        lit(2i32),
                    )))?;
                    for (child, accepted) in filters.iter().zip(expected) {
                        assert_eq!(
                            matches!(child[0].discriminant, PushedDown::Yes),
                            accepted,
                            "{join_type:?}, reorder={reorder}, output={output}"
                        );
                        if accepted {
                            assert_eq!(
                                child[0].predicate.expression_id(),
                                source.expression_id()
                            );
                            let values = child[0]
                                .predicate
                                .evaluate(&batch)?
                                .into_array(batch.num_rows())?;
                            assert_eq!(
                                as_boolean_array(&values)?.iter().collect::<Vec<_>>(),
                                if join.column_indices[unprojected].index == 0 {
                                    vec![Some(false), Some(true)]
                                } else {
                                    vec![Some(true), Some(false)]
                                }
                            );
                        }
                    }
                }
            }
        }

        let join = NestedLoopJoinExec::try_new(
            Arc::clone(&input),
            input,
            None,
            &JoinType::Inner,
            None,
        )?;
        let left: Arc<dyn PhysicalExpr> = Arc::new(Column::new("key", 0));
        let right: Arc<dyn PhysicalExpr> = Arc::new(Column::new("key", 2));
        let whole: Arc<dyn PhysicalExpr> = Arc::new(DynamicFilterPhysicalExpr::new(
            vec![Arc::clone(&left)],
            lit(true),
        ));
        let mixed: Arc<dyn PhysicalExpr> = Arc::new(DynamicFilterPhysicalExpr::new(
            vec![Arc::clone(&left), right],
            lit(true),
        ));
        let static_filter: Arc<dyn PhysicalExpr> =
            Arc::new(BinaryExpr::new(left, Operator::Eq, lit(2i32)));
        for (phase, enabled, filters) in [
            (FilterPushdownPhase::Pre, true, vec![Arc::clone(&whole)]),
            (FilterPushdownPhase::Post, false, vec![whole]),
            (FilterPushdownPhase::Post, true, vec![mixed, static_filter]),
        ] {
            let mut config = ConfigOptions::default();
            config.optimizer.enable_join_dynamic_filter_pushdown = enabled;
            let description =
                join.gather_filters_for_pushdown(phase, filters, &config)?;
            assert!(
                description
                    .parent_filters()
                    .iter()
                    .flatten()
                    .all(|f| matches!(f.discriminant, PushedDown::No))
            );
        }
        Ok(())
    }

    fn delayed_stream(batch: RecordBatch, delay: Duration) -> SendableRecordBatchStream {
        let schema = batch.schema();
        Box::pin(crate::stream::RecordBatchStreamAdapter::new(
            schema,
            futures::stream::once(async move {
                std::thread::sleep(delay);
                Ok(batch)
            }),
        ))
    }

    /// Delays the first item while the spill stream is polled, making an
    /// incorrectly scoped operator timer include the delay.
    struct DelayedReadSpillFile {
        inner: Arc<dyn SpillFile>,
        delay: Duration,
        read_count: Arc<AtomicUsize>,
    }

    impl SpillFile for DelayedReadSpillFile {
        fn path(&self) -> Option<&std::path::Path> {
            self.inner.path()
        }

        fn size(&self) -> Option<u64> {
            self.inner.size()
        }

        fn read_stream(
            &self,
        ) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes>> + Send>>> {
            let delay = self.delay;
            let read_count = Arc::clone(&self.read_count);
            let mut delay_first_item = true;
            let stream = self.inner.read_stream()?.map(move |item| {
                if delay_first_item {
                    delay_first_item = false;
                    read_count.fetch_add(1, Ordering::Relaxed);
                    std::thread::sleep(delay);
                }
                item
            });
            Ok(Box::pin(stream))
        }

        fn open_writer(&self) -> Result<Box<dyn SpillWriter>> {
            self.inner.open_writer()
        }
    }

    /// Wraps local spill files so replay reads can be delayed deterministically.
    struct DelayedReadTempFileFactory {
        inner: Arc<DiskManager>,
        delay: Duration,
        read_count: Arc<AtomicUsize>,
    }

    impl TempFileFactory for DelayedReadTempFileFactory {
        fn create_temp_file(&self, description: &str) -> Result<Arc<dyn SpillFile>> {
            Ok(Arc::new(DelayedReadSpillFile {
                inner: self.inner.create_tmp_file(description)?,
                delay: self.delay,
                read_count: Arc::clone(&self.read_count),
            }))
        }
    }

    fn build_table(
        a: (&str, &Vec<i32>),
        b: (&str, &Vec<i32>),
        c: (&str, &Vec<i32>),
        batch_size: Option<usize>,
        sorted_column_names: Vec<&str>,
    ) -> Arc<dyn ExecutionPlan> {
        let batch = build_table_i32(a, b, c);
        let schema = batch.schema();

        let batches = if let Some(batch_size) = batch_size {
            let num_batches = batch.num_rows().div_ceil(batch_size);
            (0..num_batches)
                .map(|i| {
                    let start = i * batch_size;
                    let remaining_rows = batch.num_rows() - start;
                    batch.slice(start, batch_size.min(remaining_rows))
                })
                .collect::<Vec<_>>()
        } else {
            vec![batch]
        };

        let mut sort_info = vec![];
        for name in sorted_column_names {
            let index = schema.index_of(name).unwrap();
            let sort_expr = PhysicalSortExpr::new(
                Arc::new(Column::new(name, index)),
                SortOptions::new(false, false),
            );
            sort_info.push(sort_expr);
        }
        let mut source = TestMemoryExec::try_new(&[batches], schema, None).unwrap();
        if let Some(ordering) = LexOrdering::new(sort_info) {
            source = source.try_with_sort_information(vec![ordering]).unwrap();
        }

        let source = Arc::new(source);
        Arc::new(TestMemoryExec::update_cache(&source))
    }

    /// An input that can be executed only once: later executions yield no batches, the way a
    /// stream backed by an external one-shot iterator behaves.
    #[derive(Debug)]
    struct OneShotExec {
        inner: Arc<dyn ExecutionPlan>,
        executions: Arc<AtomicUsize>,
    }

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

    impl ExecutionPlan for OneShotExec {
        fn name(&self) -> &str {
            "OneShotExec"
        }

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

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

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

        fn with_new_children(
            self: Arc<Self>,
            _children: Vec<Arc<dyn ExecutionPlan>>,
        ) -> Result<Arc<dyn ExecutionPlan>> {
            Ok(self)
        }

        fn execute(
            &self,
            partition: usize,
            context: Arc<TaskContext>,
        ) -> Result<SendableRecordBatchStream> {
            if self.executions.fetch_add(1, Ordering::Relaxed) == 0 {
                self.inner.execute(partition, context)
            } else {
                Ok(Box::pin(crate::stream::RecordBatchStreamAdapter::new(
                    self.inner.schema(),
                    futures::stream::empty(),
                )))
            }
        }
    }

    /// The left side is spilled by the load that consumed it, so nothing asks the left child for
    /// its batches a second time. Before that, the memory-limited fallback re-executed the child
    /// and silently dropped every batch the first pass had already consumed.
    #[tokio::test]
    async fn memory_limited_left_side_reads_the_child_once() -> Result<()> {
        let executions = Arc::new(AtomicUsize::new(0));
        let left = Arc::new(OneShotExec {
            inner: build_left_table(),
            executions: Arc::clone(&executions),
        });
        let right = build_right_table();
        let filter = prepare_join_filter();
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;

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

        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "expected the tight memory limit to spill the left side"
        );
        assert_eq!(
            executions.load(Ordering::Relaxed),
            1,
            "the left child must be executed exactly once"
        );
        // Same answer as the in-memory path (see test_nlj_memory_limited_inner_join).
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+----+----+----+
        | a1 | b1 | c1 | a2 | b2 | c2 |
        +----+----+----+----+----+----+
        | 5  | 5  | 50 | 2  | 2  | 80 |
        +----+----+----+----+----+----+
        "));
        Ok(())
    }

    fn build_left_table() -> Arc<dyn ExecutionPlan> {
        build_table(
            ("a1", &vec![5, 9, 11]),
            ("b1", &vec![5, 8, 8]),
            ("c1", &vec![50, 90, 110]),
            None,
            Vec::new(),
        )
    }

    fn build_right_table() -> Arc<dyn ExecutionPlan> {
        build_table(
            ("a2", &vec![12, 2, 10]),
            ("b2", &vec![10, 2, 10]),
            ("c2", &vec![40, 80, 100]),
            None,
            Vec::new(),
        )
    }

    async fn run_join_with_child_poll_delays(
        left_delay: Duration,
        right_delay: Duration,
        memory_limited: bool,
    ) -> Result<(Duration, Duration, Duration)> {
        run_join_with_poll_delays(
            left_delay,
            right_delay,
            memory_limited,
            JoinType::Inner,
            None,
        )
        .await
    }

    async fn run_join_with_poll_delays(
        left_delay: Duration,
        right_delay: Duration,
        memory_limited: bool,
        join_type: JoinType,
        spill_read_delay: Option<(Duration, Arc<AtomicUsize>)>,
    ) -> Result<(Duration, Duration, Duration)> {
        let left_batch =
            build_table_i32(("a1", &vec![1]), ("b1", &vec![2]), ("c1", &vec![3]));
        let right_batch =
            build_table_i32(("a2", &vec![4]), ("b2", &vec![5]), ("c2", &vec![6]));
        let left_schema = left_batch.schema();
        let right_schema = right_batch.schema();

        let left_stream = delayed_stream(left_batch.clone(), left_delay);
        let right_stream = delayed_stream(right_batch, right_delay);

        let task_ctx = if let Some((delay, read_count)) = spill_read_delay {
            let inner = Arc::new(
                DiskManagerBuilder::default()
                    .with_mode(DiskManagerMode::OsTmpDirectory)
                    .build()?,
            );
            let runtime = RuntimeEnvBuilder::new()
                .with_disk_manager_builder(DiskManagerBuilder::default().with_mode(
                    DiskManagerMode::Custom(Arc::new(DelayedReadTempFileFactory {
                        inner,
                        delay,
                        read_count,
                    })),
                ))
                .build_arc()?;
            Arc::new(TaskContext::default().with_runtime(runtime))
        } else {
            Arc::new(TaskContext::default())
        };
        let metrics_set = ExecutionPlanMetricsSet::new();
        let metrics = NestedLoopJoinMetrics::new(&metrics_set, 0);
        let build_time = metrics.join_metrics.build_time.clone();
        let join_time = metrics.join_metrics.join_time.clone();
        let (left_data, right_stream, spill_state) = if memory_limited {
            let global_right_bitmaps_reservation =
                MemoryConsumer::new("NestedLoopJoinGlobalRightBitmaps[test]".to_string())
                    .register(task_ctx.memory_pool());
            let spill_manager = SpillManager::new(
                task_ctx.runtime_env(),
                metrics.spill_metrics.clone(),
                Arc::clone(&right_schema),
            );
            let left_spill_manager = SpillManager::new(
                task_ctx.runtime_env(),
                metrics.spill_metrics.clone(),
                Arc::clone(&left_schema),
            );
            let mut left_spill_file =
                left_spill_manager.create_in_progress_file("test left spill")?;
            left_spill_file.append_batch(&left_batch)?;
            let left_spill_file = left_spill_file
                .finish()?
                .expect("the test left spill contains one batch");
            let left_spill = LeftSpillData::new(
                SpilledLeftFile {
                    spill_manager: left_spill_manager,
                    spill_file: left_spill_file,
                    num_rows: left_batch.num_rows(),
                },
                Arc::clone(&left_schema),
                need_produce_result_in_final(join_type),
                1,
                MemoryConsumer::new("NestedLoopJoinLoad[test]".to_string())
                    .register(task_ctx.memory_pool()),
            );
            // The left chunk is read from the delayed stream rather than from
            // the spill file. `build_time_excludes_spill_stream_poll` needs
            // that delay on the build side, and it keeps the final right replay
            // the only spill read, which is what
            // `join_time_excludes_global_right_unmatched_replay_poll` counts.
            *left_spill.reader.lock() = Some(LeftChunkReader {
                stream: left_stream,
                carryover: None,
            });
            let active = SpillStateActive {
                left_spill: Arc::new(left_spill),
                left_chunk_barrier: Arc::new(LeftChunkBarrier::new(1)),
                chunk_index: 0,
                chunk_fetch: None,
                current_chunk: None,
                memory_pool: Arc::clone(task_ctx.memory_pool()),
                chunk_reservation: MemoryConsumer::new(
                    "NestedLoopJoinLeftVisited[test]".to_string(),
                )
                .register(task_ctx.memory_pool()),
                chunk_row_offset: 0,
                left_unmatched_pass: None,
                right_schema: Arc::clone(&right_schema),
                right_input: ReplayableStreamSource::new(
                    right_stream,
                    spill_manager,
                    "test right spill",
                ),
                global_right_bitmaps: Vec::new(),
                global_right_bitmaps_reservation,
                right_batch_index: 0,
            };
            (
                OnceFut::new(async { internal_err!("unused left data was polled") }),
                Box::pin(crate::EmptyRecordBatchStream::new(Arc::clone(
                    &right_schema,
                ))) as SendableRecordBatchStream,
                SpillState::Active(Box::new(active)),
            )
        } else {
            let reservation = MemoryConsumer::new("NestedLoopJoinLoad[test]".to_string())
                .register(task_ctx.memory_pool());
            (
                OnceFut::new(collect_left_input(
                    left_stream,
                    metrics.join_metrics.clone(),
                    reservation,
                    false,
                    1,
                    None,
                    Arc::new(LeftChunkBarrier::new(1)),
                )),
                right_stream,
                SpillState::Disabled,
            )
        };
        let (output_schema, column_indices) =
            build_join_schema(&left_schema, &right_schema, &join_type);
        let stream = NestedLoopJoinStream::new(
            Arc::new(output_schema),
            None,
            join_type,
            right_stream,
            left_data,
            column_indices,
            metrics,
            1024,
            spill_state,
        );

        let start = Instant::now();
        let batches = common::collect(Box::pin(stream)).await?;
        let wall_time = start.elapsed();
        assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 1);

        Ok((
            Duration::from_nanos(build_time.value() as u64),
            Duration::from_nanos(join_time.value() as u64),
            wall_time,
        ))
    }

    async fn check_child_poll_time_excluded<F, Fut>(mut run: F) -> Result<()>
    where
        F: FnMut(Duration) -> Fut,
        Fut: Future<Output = Result<(Duration, Duration)>>,
    {
        // Escalating the delay filters out fixed-size scheduler preemption without
        // masking the bug: an incorrectly scoped timer grows with every delay.
        let mut delay = Duration::from_millis(50);
        for attempt in 0..3 {
            let (operator_time, wall_time) = run(delay).await?;
            assert!(
                !operator_time.is_zero(),
                "operator work should still be timed"
            );
            assert!(
                wall_time >= delay,
                "child poll delay should dominate wall time: {wall_time:?} < {delay:?}"
            );
            if operator_time < delay {
                return Ok(());
            }
            assert!(
                attempt < 2,
                "operator time ({operator_time:?}) included the child poll delay ({delay:?})"
            );
            delay *= 4;
        }
        unreachable!()
    }

    #[tokio::test]
    async fn build_time_excludes_left_child_poll() -> Result<()> {
        check_child_poll_time_excluded(|delay| async move {
            let (build_time, _, wall_time) =
                run_join_with_child_poll_delays(delay, Duration::ZERO, false).await?;
            Ok((build_time, wall_time))
        })
        .await
    }

    #[tokio::test]
    async fn join_time_excludes_right_child_poll() -> Result<()> {
        check_child_poll_time_excluded(|delay| async move {
            let (_, join_time, wall_time) =
                run_join_with_child_poll_delays(Duration::ZERO, delay, false).await?;
            Ok((join_time, wall_time))
        })
        .await
    }

    #[tokio::test]
    async fn build_time_excludes_spill_stream_poll() -> Result<()> {
        check_child_poll_time_excluded(|delay| async move {
            let (build_time, _, wall_time) =
                run_join_with_child_poll_delays(delay, Duration::ZERO, true).await?;
            Ok((build_time, wall_time))
        })
        .await
    }

    #[tokio::test]
    async fn join_time_excludes_replayable_input_poll() -> Result<()> {
        check_child_poll_time_excluded(|delay| async move {
            let (_, join_time, wall_time) =
                run_join_with_child_poll_delays(Duration::ZERO, delay, true).await?;
            Ok((join_time, wall_time))
        })
        .await
    }

    #[tokio::test(flavor = "current_thread")]
    async fn join_time_excludes_global_right_unmatched_replay_poll() -> Result<()> {
        check_child_poll_time_excluded(|delay| async move {
            let read_count = Arc::new(AtomicUsize::new(0));
            // The only left chunk is supplied directly, so the sole spill read
            // is the final right replay in EmitGlobalRightUnmatched.
            let (_, join_time, wall_time) = run_join_with_poll_delays(
                Duration::ZERO,
                Duration::ZERO,
                true,
                JoinType::Right,
                Some((delay, Arc::clone(&read_count))),
            )
            .await?;
            assert_eq!(
                read_count.load(Ordering::Relaxed),
                1,
                "EmitGlobalRightUnmatched should replay the right spill exactly once"
            );
            Ok((join_time, wall_time))
        })
        .await
    }

    fn prepare_join_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("x", DataType::Int32, true),
            Field::new("x", DataType::Int32, true),
        ]);
        // left.b1!=8
        let left_filter = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 0)),
            Operator::NotEq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(8)))),
        )) as Arc<dyn PhysicalExpr>;
        // right.b2!=10
        let right_filter = Arc::new(BinaryExpr::new(
            Arc::new(Column::new("x", 1)),
            Operator::NotEq,
            Arc::new(Literal::new(ScalarValue::Int32(Some(10)))),
        )) as Arc<dyn PhysicalExpr>;
        // filter = left.b1!=8 and right.b2!=10
        // after filter:
        // left table:
        // ("a1", &vec![5]),
        // ("b1", &vec![5]),
        // ("c1", &vec![50]),
        // right table:
        // ("a2", &vec![12, 2]),
        // ("b2", &vec![10, 2]),
        // ("c2", &vec![40, 80]),
        let filter_expression =
            Arc::new(BinaryExpr::new(left_filter, Operator::And, right_filter))
                as Arc<dyn PhysicalExpr>;

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

    pub(crate) async fn multi_partitioned_join_collect(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        join_type: &JoinType,
        join_filter: Option<JoinFilter>,
        context: Arc<TaskContext>,
    ) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
        let partition_count = 4;

        // Redistributing right input
        let right = Arc::new(RepartitionExec::try_new(
            right,
            Partitioning::RoundRobinBatch(partition_count),
        )?) as Arc<dyn ExecutionPlan>;

        // Use the required distribution for nested loop join to test partition data
        let nested_loop_join =
            NestedLoopJoinExec::try_new(left, right, join_filter, join_type, None)?;
        let columns = columns(&nested_loop_join.schema());
        let mut batches = vec![];
        for i in 0..partition_count {
            let stream = nested_loop_join.execute(i, Arc::clone(&context))?;
            let more_batches = common::collect(stream).await?;
            batches.extend(
                more_batches
                    .into_iter()
                    .inspect(|b| {
                        assert!(b.num_rows() <= context.session_config().batch_size())
                    })
                    .filter(|b| b.num_rows() > 0)
                    .collect::<Vec<_>>(),
            );
        }

        let metrics = nested_loop_join.metrics().unwrap();

        Ok((columns, batches, metrics))
    }

    fn new_task_ctx(batch_size: usize) -> Arc<TaskContext> {
        let base = TaskContext::default();
        // limit max size of intermediate batch used in nlj to 1
        let cfg = base.session_config().clone().with_batch_size(batch_size);
        Arc::new(base.with_session_config(cfg))
    }

    #[rstest]
    #[tokio::test]
    async fn join_inner_with_filter(#[values(1, 2, 16)] batch_size: usize) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::Inner,
            Some(filter),
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+----+----+----+
        | a1 | b1 | c1 | a2 | b2 | c2 |
        +----+----+----+----+----+----+
        | 5  | 5  | 50 | 2  | 2  | 80 |
        +----+----+----+----+----+----+
        "));

        assert_join_metrics!(metrics, 1);

        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_left_with_filter(#[values(1, 2, 16)] batch_size: usize) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::Left,
            Some(filter),
            task_ctx,
        )
        .await?;
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+----+----+----+
        | a1 | b1 | c1  | a2 | b2 | c2 |
        +----+----+-----+----+----+----+
        | 11 | 8  | 110 |    |    |    |
        | 5  | 5  | 50  | 2  | 2  | 80 |
        | 9  | 8  | 90  |    |    |    |
        +----+----+-----+----+----+----+
        "));

        assert_join_metrics!(metrics, 3);

        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_right_with_filter(#[values(1, 2, 16)] batch_size: usize) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::Right,
            Some(filter),
            task_ctx,
        )
        .await?;
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+----+----+-----+
        | a1 | b1 | c1 | a2 | b2 | c2  |
        +----+----+----+----+----+-----+
        |    |    |    | 10 | 10 | 100 |
        |    |    |    | 12 | 10 | 40  |
        | 5  | 5  | 50 | 2  | 2  | 80  |
        +----+----+----+----+----+-----+
        "));

        assert_join_metrics!(metrics, 3);

        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_full_with_filter(#[values(1, 2, 16)] batch_size: usize) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::Full,
            Some(filter),
            task_ctx,
        )
        .await?;
        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+----+----+-----+
        | a1 | b1 | c1  | a2 | b2 | c2  |
        +----+----+-----+----+----+-----+
        |    |    |     | 10 | 10 | 100 |
        |    |    |     | 12 | 10 | 40  |
        | 11 | 8  | 110 |    |    |     |
        | 5  | 5  | 50  | 2  | 2  | 80  |
        | 9  | 8  | 90  |    |    |     |
        +----+----+-----+----+----+-----+
        "));

        assert_join_metrics!(metrics, 5);

        Ok(())
    }

    #[tokio::test]
    async fn test_left_semi_join_reports_final_emission() -> Result<()> {
        let left = build_left_table();
        let right = build_right_table();
        let join =
            NestedLoopJoinExec::try_new(left, right, None, &JoinType::LeftSemi, None)?;

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

        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_left_semi_with_filter(
        #[values(1, 2, 16)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::LeftSemi,
            Some(filter),
            task_ctx,
        )
        .await?;
        assert_eq!(columns, vec!["a1", "b1", "c1"]);
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+
        | a1 | b1 | c1 |
        +----+----+----+
        | 5  | 5  | 50 |
        +----+----+----+
        "));

        assert_join_metrics!(metrics, 1);

        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_left_anti_with_filter(
        #[values(1, 2, 16)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::LeftAnti,
            Some(filter),
            task_ctx,
        )
        .await?;
        assert_eq!(columns, vec!["a1", "b1", "c1"]);
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+
        | a1 | b1 | c1  |
        +----+----+-----+
        | 11 | 8  | 110 |
        | 9  | 8  | 90  |
        +----+----+-----+
        "));

        assert_join_metrics!(metrics, 2);

        Ok(())
    }

    #[tokio::test]
    async fn join_has_correct_stats() -> Result<()> {
        let left = build_left_table();
        let right = build_right_table();
        let nested_loop_join = NestedLoopJoinExec::try_new(
            left,
            right,
            None,
            &JoinType::Left,
            Some(vec![1, 2]),
        )?;
        let stats = StatisticsContext::new()
            .compute(&nested_loop_join, &StatisticsArgs::new())?;
        assert_eq!(
            nested_loop_join.schema().fields().len(),
            stats.column_statistics.len(),
        );
        assert_eq!(2, stats.column_statistics.len());
        Ok(())
    }

    #[test]
    fn right_existence_compacts_zero_column_candidates() -> Result<()> {
        let right = create_record_batch_with_empty_schema(Arc::new(Schema::empty()), 5)?;
        let mut probe = RightExistenceProbe::new(&right, None)?;
        // A row-varying predicate can partially match even when it references
        // no right columns. Retain the row count of this empty projection.
        probe.update_matches(&BooleanBuffer::from(vec![true, false, true, true, false]));
        probe.compact()?;
        assert_eq!(probe.candidates.num_columns(), 0);
        assert_eq!(probe.candidates.num_rows(), 2);
        assert_eq!(probe.original_indices, Some(vec![1, 4]));
        probe.update_matches(&BooleanBuffer::from(vec![false, true]));
        assert_eq!(probe.remaining, 1);
        assert_eq!(
            probe.matched.finish().set_indices().collect::<Vec<_>>(),
            vec![0, 2, 3, 4]
        );
        Ok(())
    }

    #[rstest]
    fn right_existence_sliced_match_words(
        #[values(63, 64, 65)] rows: usize,
    ) -> Result<()> {
        let right =
            create_record_batch_with_empty_schema(Arc::new(Schema::empty()), rows)?;
        let mut probe = RightExistenceProbe::new(&right, None)?;
        // Set surrounding bits too, so failing to mask the tail or honor the
        // non-byte-aligned slice would incorrectly match extra candidates.
        let mut bits = vec![true; 3 + rows * 3 + 7];
        for left in 0..3 {
            for candidate in 0..rows {
                bits[3 + left * rows + candidate] =
                    candidate == 0 || candidate == rows - 1;
            }
        }
        let mask = BooleanBuffer::from(bits).slice(3, rows * 3);
        probe.update_matches(&mask);
        probe.update_matches(&mask);
        assert_eq!(probe.remaining, rows - 2);
        assert_eq!(
            probe.matched.finish().set_indices().collect::<Vec<_>>(),
            vec![0, rows - 1]
        );
        Ok(())
    }

    #[rstest]
    #[case(JoinType::RightSemi)]
    #[case(JoinType::RightAnti)]
    #[tokio::test]
    async fn right_existence_stops_after_all_rows_match(
        #[case] join_type: JoinType,
        #[values(false, true)] with_filter: bool,
    ) -> Result<()> {
        let ctx = new_task_ctx(65);
        let left = create_record_batch_with_empty_schema(Arc::new(Schema::empty()), 32)?;
        let right = create_record_batch_with_empty_schema(Arc::new(Schema::empty()), 65)?;
        let schema = right.schema();
        let filter = with_filter.then(|| {
            JoinFilter::new(
                Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))),
                vec![],
                Arc::clone(&schema),
            )
        });
        let left_data = JoinLeftData::new(
            left.into(),
            Mutex::new(BooleanBufferBuilder::new(0)),
            MemoryConsumer::new("test").register(ctx.memory_pool()),
        );
        let mut stream = NestedLoopJoinStream::new(
            Arc::clone(&schema),
            filter,
            join_type,
            Box::pin(crate::stream::RecordBatchStreamAdapter::new(
                schema,
                futures::stream::iter(vec![Ok(right)]),
            )),
            OnceFut::new(async { internal_err!("unused left input") }),
            vec![],
            NestedLoopJoinMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
            65,
            SpillState::Disabled,
        );
        stream.buffered_left_data = Some(Arc::new(left_data));
        let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
        assert!(stream.handle_fetching_right(&mut cx).is_continue());
        assert!(stream.process_probe_batch()?);
        assert_eq!(stream.left_probe_idx, 1);
        assert!(
            !stream.process_probe_batch()?,
            "all right rows already matched"
        );
        let output = stream.process_right_unmatched()?;
        let rows = output.map_or(0, |batch| batch.num_rows());
        assert_eq!(
            rows,
            if join_type == JoinType::RightSemi {
                65
            } else {
                0
            }
        );
        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_right_semi_with_filter(
        #[values(1, 2, 16)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::RightSemi,
            Some(filter),
            task_ctx,
        )
        .await?;
        assert_eq!(columns, vec!["a2", "b2", "c2"]);
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+
        | a2 | b2 | c2 |
        +----+----+----+
        | 2  | 2  | 80 |
        +----+----+----+
        "));

        assert_join_metrics!(metrics, 1);

        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_right_anti_with_filter(
        #[values(1, 2, 16)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::RightAnti,
            Some(filter),
            task_ctx,
        )
        .await?;
        assert_eq!(columns, vec!["a2", "b2", "c2"]);
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+
        | a2 | b2 | c2  |
        +----+----+-----+
        | 10 | 10 | 100 |
        | 12 | 10 | 40  |
        +----+----+-----+
        "));

        assert_join_metrics!(metrics, 2);

        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_left_mark_with_filter(
        #[values(1, 2, 16)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::LeftMark,
            Some(filter),
            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  |
        +----+----+-----+-------+
        | 11 | 8  | 110 | false |
        | 5  | 5  | 50  | true  |
        | 9  | 8  | 90  | false |
        +----+----+-----+-------+
        "));

        assert_join_metrics!(metrics, 3);

        Ok(())
    }

    #[rstest]
    #[tokio::test]
    async fn join_right_mark_with_filter(
        #[values(1, 2, 16)] batch_size: usize,
    ) -> Result<()> {
        let task_ctx = new_task_ctx(batch_size);
        let left = build_left_table();
        let right = build_right_table();

        let filter = prepare_join_filter();
        let (columns, batches, metrics) = multi_partitioned_join_collect(
            left,
            right,
            &JoinType::RightMark,
            Some(filter),
            task_ctx,
        )
        .await?;
        assert_eq!(columns, vec!["a2", "b2", "c2", "mark"]);

        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+-------+
        | a2 | b2 | c2  | mark  |
        +----+----+-----+-------+
        | 10 | 10 | 100 | false |
        | 12 | 10 | 40  | false |
        | 2  | 2  | 80  | true  |
        +----+----+-----+-------+
        "));

        assert_join_metrics!(metrics, 3);

        Ok(())
    }

    #[tokio::test]
    async fn test_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]),
            None,
            Vec::new(),
        );
        let right = build_table(
            ("a2", &vec![10, 11]),
            ("b2", &vec![12, 13]),
            ("c2", &vec![14, 15]),
            None,
            Vec::new(),
        );
        let filter = prepare_join_filter();

        // All join types support memory-limited fallback under
        // multi-partition right inputs (left visited state is shared
        // across partitions via `FallbackCoordinator`).
        let fallback_join_types = vec![
            JoinType::Inner,
            JoinType::Right,
            JoinType::RightSemi,
            JoinType::RightAnti,
            JoinType::RightMark,
            JoinType::Full,
        ];

        for join_type in &fallback_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);

            // Should succeed via spill fallback, not OOM
            let _result = multi_partitioned_join_collect(
                Arc::clone(&left),
                Arc::clone(&right),
                join_type,
                Some(filter.clone()),
                task_ctx,
            )
            .await?;
        }

        Ok(())
    }

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

    // ========================================================================
    // Memory-limited execution tests
    // ========================================================================

    /// Helper to run a NLJ using partition 0 and collect results + metrics.
    async fn join_collect(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        join_type: &JoinType,
        join_filter: Option<JoinFilter>,
        context: Arc<TaskContext>,
    ) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
        let nested_loop_join =
            NestedLoopJoinExec::try_new(left, right, join_filter, join_type, None)?;
        let columns = columns(&nested_loop_join.schema());
        let stream = nested_loop_join.execute(0, context)?;
        let batches: Vec<RecordBatch> = common::collect(stream)
            .await?
            .into_iter()
            .filter(|b| b.num_rows() > 0)
            .collect();
        let metrics = nested_loop_join.metrics().unwrap();
        Ok((columns, batches, metrics))
    }

    /// Create a TaskContext with tight memory limit and disk spilling enabled.
    fn task_ctx_with_memory_limit(
        memory_limit: usize,
        batch_size: usize,
    ) -> Result<Arc<TaskContext>> {
        let runtime = RuntimeEnvBuilder::new()
            .with_memory_limit(memory_limit, 1.0)
            .build_arc()?;
        let cfg = TaskContext::default()
            .session_config()
            .clone()
            .with_batch_size(batch_size);
        let task_ctx = TaskContext::default()
            .with_runtime(runtime)
            .with_session_config(cfg);
        Ok(Arc::new(task_ctx))
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_inner_join() -> Result<()> {
        // Use a very small memory limit to force OOM → fallback to spill.
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

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

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

        // Verify spill actually occurred (memory-limited path was taken)
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Result should be identical to the non-memory-limited case
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+----+----+----+
        | a1 | b1 | c1 | a2 | b2 | c2 |
        +----+----+----+----+----+----+
        | 5  | 5  | 50 | 2  | 2  | 80 |
        +----+----+----+----+----+----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_left_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) =
            join_collect(left, right, &JoinType::Left, Some(filter), task_ctx).await?;

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

        // Verify spill actually occurred
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+----+----+----+
        | a1 | b1 | c1  | a2 | b2 | c2 |
        +----+----+-----+----+----+----+
        | 11 | 8  | 110 |    |    |    |
        | 5  | 5  | 50  | 2  | 2  | 80 |
        | 9  | 8  | 90  |    |    |    |
        +----+----+-----+----+----+----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_left_semi_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) =
            join_collect(left, right, &JoinType::LeftSemi, Some(filter), task_ctx)
                .await?;

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

        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Left semi: only left rows that matched at least one right row.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+
        | a1 | b1 | c1 |
        +----+----+----+
        | 5  | 5  | 50 |
        +----+----+----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_left_anti_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

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

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

        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Left anti: left rows that did NOT match any right row.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+
        | a1 | b1 | c1  |
        +----+----+-----+
        | 11 | 8  | 110 |
        | 9  | 8  | 90  |
        +----+----+-----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_left_mark_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) =
            join_collect(left, right, &JoinType::LeftMark, Some(filter), task_ctx)
                .await?;

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

        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Left mark: all left rows with a bool column indicating match.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+-------+
        | a1 | b1 | c1  | mark  |
        +----+----+-----+-------+
        | 11 | 8  | 110 | false |
        | 5  | 5  | 50  | true  |
        | 9  | 8  | 90  | false |
        +----+----+-----+-------+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_fits_in_memory_no_spill() -> Result<()> {
        // Use a large memory limit — everything fits, no spilling needed.
        let task_ctx = task_ctx_with_memory_limit(10_000_000, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

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

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

        // Verify no spilling occurred (standard OnceFut path was used)
        assert_eq!(
            metrics.spill_count().unwrap_or(0),
            0,
            "Expected no spilling with generous memory limit"
        );

        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+----+----+----+
        | a1 | b1 | c1 | a2 | b2 | c2 |
        +----+----+----+----+----+----+
        | 5  | 5  | 50 | 2  | 2  | 80 |
        +----+----+----+----+----+----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_empty_inputs() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;

        // Empty left table
        let empty_left = build_table(
            ("a1", &vec![]),
            ("b1", &vec![]),
            ("c1", &vec![]),
            None,
            Vec::new(),
        );
        let right = build_right_table();
        let filter = prepare_join_filter();

        let (_columns, batches, _metrics) =
            join_collect(empty_left, right, &JoinType::Inner, Some(filter), task_ctx)
                .await?;
        assert!(batches.is_empty() || batches.iter().all(|b| b.num_rows() == 0));

        // Empty right table
        let task_ctx2 = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let empty_right = build_table(
            ("a2", &vec![]),
            ("b2", &vec![]),
            ("c2", &vec![]),
            None,
            Vec::new(),
        );
        let filter2 = prepare_join_filter();

        let (_columns, batches, _metrics) = join_collect(
            left,
            empty_right,
            &JoinType::Inner,
            Some(filter2),
            task_ctx2,
        )
        .await?;
        assert!(batches.is_empty() || batches.iter().all(|b| b.num_rows() == 0));

        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_no_disk_falls_back_to_oom() -> Result<()> {
        // When disk is disabled, fallback is not possible and OOM should occur.
        use datafusion_execution::disk_manager::{DiskManagerBuilder, DiskManagerMode};

        let runtime = RuntimeEnvBuilder::new()
            .with_memory_limit(100, 1.0)
            .with_disk_manager_builder(
                DiskManagerBuilder::default().with_mode(DiskManagerMode::Disabled),
            )
            .build_arc()?;
        let task_ctx = Arc::new(TaskContext::default().with_runtime(runtime));

        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

        let err = join_collect(left, right, &JoinType::Inner, Some(filter), task_ctx)
            .await
            .unwrap_err();

        assert_contains!(err.to_string(), "Resources exhausted");
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_right_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

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

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

        // Verify spill actually occurred
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Right join: all right rows appear. Unmatched right rows get NULLs on left.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+----+----+-----+
        | a1 | b1 | c1 | a2 | b2 | c2  |
        +----+----+----+----+----+-----+
        |    |    |    | 10 | 10 | 100 |
        |    |    |    | 12 | 10 | 40  |
        | 5  | 5  | 50 | 2  | 2  | 80  |
        +----+----+----+----+----+-----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_full_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) =
            join_collect(left, right, &JoinType::Full, Some(filter), task_ctx).await?;

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

        // Verify spill actually occurred
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Full join: unmatched from both sides appear with NULL padding.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+----+----+-----+
        | a1 | b1 | c1  | a2 | b2 | c2  |
        +----+----+-----+----+----+-----+
        |    |    |     | 10 | 10 | 100 |
        |    |    |     | 12 | 10 | 40  |
        | 11 | 8  | 110 |    |    |     |
        | 5  | 5  | 50  | 2  | 2  | 80  |
        | 9  | 8  | 90  |    |    |     |
        +----+----+-----+----+----+-----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_right_semi_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) =
            join_collect(left, right, &JoinType::RightSemi, Some(filter), task_ctx)
                .await?;

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

        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Right semi: only right rows that matched at least one left row.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+
        | a2 | b2 | c2 |
        +----+----+----+
        | 2  | 2  | 80 |
        +----+----+----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_right_anti_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) =
            join_collect(left, right, &JoinType::RightAnti, Some(filter), task_ctx)
                .await?;

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

        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Right anti: right rows that did NOT match any left row.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+
        | a2 | b2 | c2  |
        +----+----+-----+
        | 10 | 10 | 100 |
        | 12 | 10 | 40  |
        +----+----+-----+
        "));
        Ok(())
    }

    #[tokio::test]
    async fn test_nlj_memory_limited_right_mark_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table();
        let right = build_right_table();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) =
            join_collect(left, right, &JoinType::RightMark, Some(filter), task_ctx)
                .await?;

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

        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling to occur under tight memory limit"
        );

        // Right mark: all right rows with a bool column indicating match.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+-------+
        | a2 | b2 | c2  | mark  |
        +----+----+-----+-------+
        | 10 | 10 | 100 | false |
        | 12 | 10 | 40  | false |
        | 2  | 2  | 80  | true  |
        +----+----+-----+-------+
        "));
        Ok(())
    }

    // ========================================================================
    // Multi-partition memory-limited correctness tests
    //
    // These tests reproduce the cross-partition coordination bug in the
    // memory-limited fallback path: each output partition independently
    // constructs a per-chunk `JoinLeftData` with `AtomicUsize::new(1)`,
    // so left-side visited state is not shared across right partitions.
    // For join types that emit unmatched left rows in the final output
    // (LEFT, LEFT SEMI, LEFT ANTI, LEFT MARK, FULL), this leads to a
    // left row being emitted as unmatched by partitions whose right
    // input did not match it — even when another partition did match.
    // ========================================================================

    /// Build the right table as one batch per row, so RepartitionExec can
    /// distribute rows across multiple output partitions.
    fn build_right_table_one_batch_per_row() -> Arc<dyn ExecutionPlan> {
        build_table(
            ("a2", &vec![12, 2, 10]),
            ("b2", &vec![10, 2, 10]),
            ("c2", &vec![40, 80, 100]),
            Some(1),
            Vec::new(),
        )
    }

    /// A left table with one batch per row, spanning enough rows that the
    /// memory-limited fallback must split it across MULTIPLE chunks. Only
    /// `(5,5,50)` matches the right side under `prepare_join_filter`
    /// (`b1 != 8`); every other row has `b1 = 8` and is therefore an
    /// unmatched left row.
    fn build_left_table_multi_chunk() -> Arc<dyn ExecutionPlan> {
        build_table(
            ("a1", &vec![5, 9, 11, 13, 15, 17, 19, 21]),
            ("b1", &vec![5, 8, 8, 8, 8, 8, 8, 8]),
            ("c1", &vec![50, 90, 110, 130, 150, 170, 190, 210]),
            // One row per batch, so the tight per-chunk memory budget forces
            // each row to be loaded as a separate chunk.
            Some(1),
            Vec::new(),
        )
    }

    /// Run a NLJ across 4 right partitions under a tight memory limit, so
    /// every output partition takes the memory-limited fallback path. The
    /// right side is shuffled via `RepartitionExec(RoundRobinBatch(4))`.
    ///
    /// The partitions are collected concurrently, which mirrors how they run
    /// under the runtime. They have to be: they share one left chunk at a
    /// time, so the next chunk is only loaded once every partition has
    /// finished the current one (see [`LeftChunkBarrier`]).
    async fn multi_partition_memory_limited_join_collect(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        join_type: &JoinType,
        join_filter: Option<JoinFilter>,
        context: Arc<TaskContext>,
    ) -> Result<(Vec<String>, Vec<RecordBatch>, MetricsSet)> {
        let partition_count = 4;
        let right = Arc::new(RepartitionExec::try_new(
            right,
            Partitioning::RoundRobinBatch(partition_count),
        )?) as Arc<dyn ExecutionPlan>;

        let nested_loop_join =
            NestedLoopJoinExec::try_new(left, right, join_filter, join_type, None)?;
        let columns = columns(&nested_loop_join.schema());

        let mut handles = vec![];
        for i in 0..partition_count {
            let stream = nested_loop_join.execute(i, Arc::clone(&context))?;
            handles.push(SpawnedTask::spawn(
                async move { common::collect(stream).await },
            ));
        }
        let mut batches = vec![];
        for handle in handles {
            batches.extend(handle.join().await.expect("partition task panicked")?);
        }
        batches.retain(|b| b.num_rows() > 0);

        let metrics = nested_loop_join.metrics().unwrap();
        Ok((columns, batches, metrics))
    }

    /// The left side is split into multiple chunks, and every partition reads
    /// its own. Every left row must appear exactly once: duplicates would
    /// indicate that the visited-left bitmap was not shared across right
    /// partitions, and missing rows that a chunk's matches were merged at the
    /// wrong offset.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_multi_partition_left_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table_multi_chunk();
        let right = build_right_table_one_batch_per_row();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
            left,
            right,
            &JoinType::Left,
            Some(filter),
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling under tight memory limit"
        );

        // (5,5,50) matches (2,2,80); all other left rows (b1 = 8) are
        // unmatched and appear exactly once.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+----+----+----+
        | a1 | b1 | c1  | a2 | b2 | c2 |
        +----+----+-----+----+----+----+
        | 11 | 8  | 110 |    |    |    |
        | 13 | 8  | 130 |    |    |    |
        | 15 | 8  | 150 |    |    |    |
        | 17 | 8  | 170 |    |    |    |
        | 19 | 8  | 190 |    |    |    |
        | 21 | 8  | 210 |    |    |    |
        | 5  | 5  | 50  | 2  | 2  | 80 |
        | 9  | 8  | 90  |    |    |    |
        +----+----+-----+----+----+----+
        "));
        Ok(())
    }

    /// In addition to the global left bitmap exercised by the LEFT case, this
    /// covers the global right-unmatched bitmap accumulated ACROSS all left
    /// chunks and emitted once in `EmitGlobalRightUnmatched`. The two right
    /// rows with `b2 = 10` are filtered out of every match and must appear
    /// exactly once as unmatched-right rows, regardless of how many left
    /// chunks were processed.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_multi_partition_full_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table_multi_chunk();
        let right = build_right_table_one_batch_per_row();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
            left,
            right,
            &JoinType::Full,
            Some(filter),
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "a2", "b2", "c2"]);
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling under tight memory limit"
        );

        // Matched: (5,5,50)+(2,2,80). Unmatched left: the seven b1 = 8 rows.
        // Unmatched right: (12,10,40) and (10,10,100), each emitted once from
        // the global right bitmap accumulated across all left chunks.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+----+----+-----+
        | a1 | b1 | c1  | a2 | b2 | c2  |
        +----+----+-----+----+----+-----+
        |    |    |     | 10 | 10 | 100 |
        |    |    |     | 12 | 10 | 40  |
        | 11 | 8  | 110 |    |    |     |
        | 13 | 8  | 130 |    |    |     |
        | 15 | 8  | 150 |    |    |     |
        | 17 | 8  | 170 |    |    |     |
        | 19 | 8  | 190 |    |    |     |
        | 21 | 8  | 210 |    |    |     |
        | 5  | 5  | 50  | 2  | 2  | 80  |
        | 9  | 8  | 90  |    |    |     |
        +----+----+-----+----+----+-----+
        "));
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_multi_partition_left_semi_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table_multi_chunk();
        // Two right rows that both match the same left row (5,5,50). Without
        // shared left-visited state across partitions, each matching partition
        // emits the left row once, producing duplicates.
        let right = build_table(
            ("a2", &vec![2, 3, 10]),
            ("b2", &vec![2, 2, 10]),
            ("c2", &vec![80, 70, 100]),
            Some(1),
            Vec::new(),
        );
        let filter = prepare_join_filter();

        let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
            left,
            right,
            &JoinType::LeftSemi,
            Some(filter),
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1"]);
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling under tight memory limit"
        );

        // Left semi: each left row appears at most once, even if it matches
        // multiple right rows distributed across partitions.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+
        | a1 | b1 | c1 |
        +----+----+----+
        | 5  | 5  | 50 |
        +----+----+----+
        "));
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_multi_partition_left_anti_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table_multi_chunk();
        let right = build_right_table_one_batch_per_row();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
            left,
            right,
            &JoinType::LeftAnti,
            Some(filter),
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1"]);
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling under tight memory limit"
        );

        // Left anti: only left rows with no matching right row.
        // (5,5,50) matches (2,2,80) under the filter, so it must NOT appear.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+
        | a1 | b1 | c1  |
        +----+----+-----+
        | 11 | 8  | 110 |
        | 13 | 8  | 130 |
        | 15 | 8  | 150 |
        | 17 | 8  | 170 |
        | 19 | 8  | 190 |
        | 21 | 8  | 210 |
        | 9  | 8  | 90  |
        +----+----+-----+
        "));
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_multi_partition_left_mark_join() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit(50, 16)?;
        let left = build_left_table_multi_chunk();
        let right = build_right_table_one_batch_per_row();
        let filter = prepare_join_filter();

        let (columns, batches, metrics) = multi_partition_memory_limited_join_collect(
            left,
            right,
            &JoinType::LeftMark,
            Some(filter),
            task_ctx,
        )
        .await?;

        assert_eq!(columns, vec!["a1", "b1", "c1", "mark"]);
        assert!(
            metrics.spill_count().unwrap_or(0) > 0,
            "Expected spilling under tight memory limit"
        );

        // Left mark: every left row appears exactly once with a bool
        // indicating whether it matched at least one right row.
        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+-----+-------+
        | a1 | b1 | c1  | mark  |
        +----+----+-----+-------+
        | 11 | 8  | 110 | false |
        | 13 | 8  | 130 | false |
        | 15 | 8  | 150 | false |
        | 17 | 8  | 170 | false |
        | 19 | 8  | 190 | false |
        | 21 | 8  | 210 | false |
        | 5  | 5  | 50  | true  |
        | 9  | 8  | 90  | false |
        +----+----+-----+-------+
        "));
        Ok(())
    }

    /// A finished execution must not keep memory accounted, even while the plan
    /// itself is still alive, as a cached or still-referenced physical plan
    /// would be. The barrier lives on the plan and holds the load of the current
    /// chunk, so it has to let go of the last one as well.
    async fn assert_memory_released_after_completion(join_type: JoinType) -> Result<()> {
        let runtime = RuntimeEnvBuilder::new()
            .with_memory_limit(50, 1.0)
            .build_arc()?;
        let pool = Arc::clone(&runtime.memory_pool);
        let cfg = TaskContext::default()
            .session_config()
            .clone()
            .with_batch_size(16);
        let task_ctx = Arc::new(
            TaskContext::default()
                .with_runtime(runtime)
                .with_session_config(cfg),
        );

        let partition_count = 4;
        let right = Arc::new(RepartitionExec::try_new(
            build_right_table_one_batch_per_row(),
            Partitioning::RoundRobinBatch(partition_count),
        )?) as Arc<dyn ExecutionPlan>;
        // Held for the whole test, exactly as a cached or still-referenced
        // physical plan would be after its query finished.
        let nested_loop_join = Arc::new(NestedLoopJoinExec::try_new(
            build_left_table_multi_chunk(),
            right,
            Some(prepare_join_filter()),
            &join_type,
            None,
        )?);

        let mut handles = vec![];
        for i in 0..partition_count {
            let stream = nested_loop_join.execute(i, Arc::clone(&task_ctx))?;
            handles.push(SpawnedTask::spawn(
                async move { common::collect(stream).await },
            ));
        }
        for handle in handles {
            handle.join().await.expect("partition task panicked")?;
        }
        assert!(
            nested_loop_join
                .metrics()
                .unwrap()
                .spill_count()
                .unwrap_or(0)
                > 0,
            "{join_type}: expected spilling under a tight memory limit"
        );

        assert_eq!(
            pool.reserved(),
            0,
            "{join_type}: memory is still reserved after every partition finished"
        );
        Ok(())
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_releases_memory_left_join() -> Result<()> {
        assert_memory_released_after_completion(JoinType::Left).await
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_releases_memory_full_join() -> Result<()> {
        assert_memory_released_after_completion(JoinType::Full).await
    }

    /// The join types that emit final left rows, which are the ones whose
    /// partitions share the visited bitmap
    const LEFT_EMITTING_JOIN_TYPES: [JoinType; 5] = [
        JoinType::Left,
        JoinType::LeftSemi,
        JoinType::LeftAnti,
        JoinType::LeftMark,
        JoinType::Full,
    ];

    /// The final left rows among `batches`: for LEFT and FULL the rows with a
    /// left row and NULL right columns, and for the other left-emitting types
    /// every row, as they emit nothing else.
    fn count_final_left_rows(join_type: JoinType, batches: &[RecordBatch]) -> usize {
        batches
            .iter()
            .map(|batch| match join_type {
                JoinType::Left | JoinType::Full => {
                    let left = batch.column(0);
                    let right = batch.column(3);
                    (0..batch.num_rows())
                        .filter(|&i| left.is_valid(i) && right.is_null(i))
                        .count()
                }
                _ => batch.num_rows(),
            })
            .sum()
    }

    /// A two-partition join over a left side of several chunks, under a memory
    /// limit that makes it spill.
    fn dropped_partition_test_plan(
        right: Arc<dyn ExecutionPlan>,
        join_type: JoinType,
    ) -> Result<(Arc<NestedLoopJoinExec>, Arc<TaskContext>)> {
        let task_ctx = task_ctx_with_memory_limit(50, 1)?;
        let right = Arc::new(RepartitionExec::try_new(
            right,
            Partitioning::RoundRobinBatch(2),
        )?) as Arc<dyn ExecutionPlan>;
        let plan = Arc::new(NestedLoopJoinExec::try_new(
            build_left_table_multi_chunk(),
            right,
            Some(prepare_join_filter()),
            &join_type,
            None,
        )?);
        Ok((plan, task_ctx))
    }

    /// The partitions move through the left chunks together, so one that is
    /// dropped before it finishes (as a `LIMIT` above the join may do) has to
    /// stop being waited for. The others then carry on without it, and neither
    /// stall nor fail. As on the in-memory path, the dropped partition never
    /// reports probe completion, so the final left rows are not emitted.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_dropped_partition_does_not_stall_peers() -> Result<()>
    {
        let (plan, task_ctx) = dropped_partition_test_plan(
            build_right_table_one_batch_per_row(),
            JoinType::Left,
        )?;

        // Every partition is dropped as soon as it returns rows. The only match
        // comes from the first left chunk, so the partition that finds it goes
        // away with most chunks still to probe, and the other one runs to the
        // end.
        let mut handles = vec![];
        for i in 0..2 {
            let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;
            handles.push(SpawnedTask::spawn(async move {
                while let Some(batch) = stream.next().await {
                    let batch = batch?;
                    if batch.num_rows() > 0 {
                        return Ok(Some(batch));
                    }
                }
                Ok::<_, DataFusionError>(None)
            }));
        }
        let mut batches = vec![];
        for handle in handles {
            let batch = tokio::time::timeout(Duration::from_secs(30), handle.join())
                .await
                .expect("a partition stalled after its peer was dropped")
                .expect("partition task panicked")?;
            batches.extend(batch);
        }
        assert!(
            plan.metrics().unwrap().spill_count().unwrap_or(0) > 0,
            "Expected spilling under tight memory limit"
        );

        allow_duplicates!(assert_snapshot!(batches_to_sort_string(&batches), @r"
        +----+----+----+----+----+----+
        | a1 | b1 | c1 | a2 | b2 | c2 |
        +----+----+----+----+----+----+
        | 5  | 5  | 50 | 2  | 2  | 80 |
        +----+----+----+----+----+----+
        "));
        // Nothing stays reserved, although the plan is still alive
        assert_eq!(
            task_ctx.memory_pool().reserved(),
            0,
            "a dropped partition must not strand the chunk's or the bitmap's memory"
        );
        drop(plan);
        Ok(())
    }

    /// A partition that has finished the current chunk and is waiting for the
    /// others is counted among the finished ones. When it is dropped it must
    /// come out of that count as well, or the barrier would move on before the
    /// remaining partition has probed the chunk.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_partition_dropped_while_waiting_for_peers()
    -> Result<()> {
        for join_type in LEFT_EMITTING_JOIN_TYPES {
            assert_partition_dropped_while_waiting_for_peers(join_type).await?;
        }
        Ok(())
    }

    async fn assert_partition_dropped_while_waiting_for_peers(
        join_type: JoinType,
    ) -> Result<()> {
        // No right row matches, so the join returns nothing until the very end
        let right = build_table(
            ("a2", &vec![12, 10]),
            ("b2", &vec![10, 10]),
            ("c2", &vec![40, 100]),
            Some(1),
            Vec::new(),
        );
        let (plan, task_ctx) = dropped_partition_test_plan(right, join_type)?;
        let mut waiting = plan.execute(0, Arc::clone(&task_ctx))?;
        let survivor = plan.execute(1, Arc::clone(&task_ctx))?;

        tokio::time::timeout(Duration::from_secs(30), async {
            while plan.left_chunk_barrier.inner.lock().finished == 0 {
                assert!(
                    futures::poll!(waiting.next()).is_pending(),
                    "the partition cannot get past the first chunk on its own"
                );
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        })
        .await
        .expect("the partition never finished the first chunk");
        drop(waiting);
        {
            let barrier = plan.left_chunk_barrier.inner.lock();
            assert_eq!(
                (barrier.chunk_index, barrier.live, barrier.finished),
                (0, 1, 0)
            );
        }

        let batches =
            tokio::time::timeout(Duration::from_secs(30), common::collect(survivor))
                .await
                .expect("the remaining partition stalled")?;
        // No final left rows, as the dropped partition never reported. A FULL
        // join still emits the survivor's own unmatched right row.
        let expected_rows = usize::from(join_type == JoinType::Full);
        assert_eq!(
            batches.iter().map(RecordBatch::num_rows).sum::<usize>(),
            expected_rows,
            "{join_type}"
        );
        assert_eq!(plan.left_chunk_barrier.inner.lock().chunk_index, 8);

        // Nothing stays reserved, although the plan is still alive
        assert_eq!(task_ctx.memory_pool().reserved(), 0, "{join_type}");
        Ok(())
    }

    /// The load of a chunk is not tied to the partition that started it, so
    /// dropping that partition right away leaves the chunk to the others.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_partition_dropped_while_loading() -> Result<()> {
        let (plan, task_ctx) = dropped_partition_test_plan(
            build_right_table_one_batch_per_row(),
            JoinType::Left,
        )?;
        let mut loading = plan.execute(0, Arc::clone(&task_ctx))?;
        let survivor = plan.execute(1, Arc::clone(&task_ctx))?;

        // Far enough to spill the left side and ask for the first chunk
        tokio::time::timeout(Duration::from_secs(30), async {
            while plan.left_chunk_barrier.inner.lock().chunk.is_none() {
                let _ = futures::poll!(loading.next());
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        })
        .await
        .expect("the partition never asked for the first chunk");
        drop(loading);

        tokio::time::timeout(Duration::from_secs(30), common::collect(survivor))
            .await
            .expect("the remaining partition stalled")?;
        assert_eq!(plan.left_chunk_barrier.inner.lock().chunk_index, 8);

        // Nothing stays reserved, although the plan is still alive
        assert_eq!(task_ctx.memory_pool().reserved(), 0);
        Ok(())
    }

    /// Fails every `read_stream` of the left spill file after the first, which
    /// is the one the chunks are read from. The final pass is the second.
    struct FailFinalPassSpillFile {
        inner: Arc<dyn SpillFile>,
        reads: AtomicUsize,
    }

    impl SpillFile for FailFinalPassSpillFile {
        fn path(&self) -> Option<&std::path::Path> {
            self.inner.path()
        }

        fn size(&self) -> Option<u64> {
            self.inner.size()
        }

        fn read_stream(
            &self,
        ) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes>> + Send>>> {
            if self.reads.fetch_add(1, Ordering::Relaxed) > 0 {
                return internal_err!("final pass cannot be opened");
            }
            self.inner.read_stream()
        }

        fn open_writer(&self) -> Result<Box<dyn SpillWriter>> {
            self.inner.open_writer()
        }
    }

    #[derive(Debug)]
    struct FailFinalPassTempFileFactory {
        inner: Arc<DiskManager>,
    }

    impl TempFileFactory for FailFinalPassTempFileFactory {
        fn create_temp_file(&self, description: &str) -> Result<Arc<dyn SpillFile>> {
            let file = self.inner.create_tmp_file(description)?;
            if description != "NestedLoopJoin left spill" {
                return Ok(file);
            }
            Ok(Arc::new(FailFinalPassSpillFile {
                inner: file,
                reads: AtomicUsize::new(0),
            }))
        }
    }

    /// The emitter owns the global bitmap from `ProbeEnd` on, so an error
    /// opening the final pass does not leave it reserved on a live plan.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_final_pass_open_error_releases_bitmap() -> Result<()>
    {
        let inner = Arc::new(
            DiskManagerBuilder::default()
                .with_mode(DiskManagerMode::OsTmpDirectory)
                .build()?,
        );
        let runtime = RuntimeEnvBuilder::new()
            .with_memory_limit(50, 1.0)
            .with_disk_manager_builder(DiskManagerBuilder::default().with_mode(
                DiskManagerMode::Custom(Arc::new(FailFinalPassTempFileFactory { inner })),
            ))
            .build_arc()?;
        let cfg = TaskContext::default()
            .session_config()
            .clone()
            .with_batch_size(1);
        let task_ctx = Arc::new(
            TaskContext::default()
                .with_runtime(runtime)
                .with_session_config(cfg),
        );
        let right = Arc::new(RepartitionExec::try_new(
            build_right_table_one_batch_per_row(),
            Partitioning::RoundRobinBatch(2),
        )?) as Arc<dyn ExecutionPlan>;
        let plan = Arc::new(NestedLoopJoinExec::try_new(
            build_left_table_multi_chunk(),
            right,
            Some(prepare_join_filter()),
            &JoinType::Left,
            None,
        )?);

        let streams = (0..2)
            .map(|i| plan.execute(i, Arc::clone(&task_ctx)))
            .collect::<Result<Vec<_>>>()?;
        let results = tokio::time::timeout(
            Duration::from_secs(30),
            futures::future::join_all(streams.into_iter().map(common::collect)),
        )
        .await
        .expect("the join stalled");
        let err = results
            .into_iter()
            .find_map(Result::err)
            .expect("the emitter fails to open the final pass");
        assert_contains!(err.to_string(), "final pass cannot be opened");

        // Nothing stays reserved, although the plan is still alive
        assert_eq!(task_ctx.memory_pool().reserved(), 0);
        Ok(())
    }

    /// A partition dropped before it was ever polled has not seen the spilled
    /// left side, whether or not it exists yet. It must still stop counting as
    /// a partition that will report probe completion, or the bitmap would stay
    /// reserved for as long as the plan.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_unpolled_partition_dropped() -> Result<()> {
        for join_type in LEFT_EMITTING_JOIN_TYPES {
            for after_spill in [false, true] {
                let (plan, task_ctx) = dropped_partition_test_plan(
                    build_right_table_one_batch_per_row(),
                    join_type,
                )?;
                let unpolled = plan.execute(0, Arc::clone(&task_ctx))?;
                let mut survivor = plan.execute(1, Arc::clone(&task_ctx))?;
                let mut batches = vec![];
                if after_spill {
                    // The survivor finishes the first chunk, then waits for
                    // the unpolled partition
                    tokio::time::timeout(Duration::from_secs(30), async {
                        while plan.left_chunk_barrier.inner.lock().finished == 0 {
                            if let Poll::Ready(Some(batch)) =
                                futures::poll!(survivor.next())
                            {
                                batches.push(batch?);
                            }
                            tokio::time::sleep(Duration::from_millis(1)).await;
                        }
                        Ok::<_, DataFusionError>(())
                    })
                    .await
                    .expect("the survivor never finished the first chunk")?;
                    assert!(plan.left_chunk_barrier.inner.lock().left_spill.is_some());
                }
                drop(unpolled);

                batches.extend(
                    tokio::time::timeout(
                        Duration::from_secs(30),
                        common::collect(survivor),
                    )
                    .await
                    .expect("the remaining partition stalled")?,
                );
                assert!(
                    plan.metrics().unwrap().spill_count().unwrap_or(0) > 0,
                    "{join_type}: expected spilling under tight memory limit"
                );
                // No final left rows, as the dropped partition never reported
                assert_eq!(
                    count_final_left_rows(join_type, &batches),
                    0,
                    "{join_type} after_spill={after_spill}"
                );
                assert_eq!(
                    task_ctx.memory_pool().reserved(),
                    0,
                    "{join_type} after_spill={after_spill}: memory still reserved \
                     while the plan is alive"
                );
            }
        }
        Ok(())
    }

    /// A FULL partition that has probed every chunk goes on to replay its right
    /// spill file for the unmatched right rows, and only reports probe
    /// completion after that. Dropping it during the replay leaves it past the
    /// barrier's last chunk but unreported.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_full_join_dropped_during_right_replay() -> Result<()>
    {
        let (plan, task_ctx) = dropped_partition_test_plan(
            build_right_table_one_batch_per_row(),
            JoinType::Full,
        )?;
        let mut streams = vec![
            plan.execute(0, Arc::clone(&task_ctx))?,
            plan.execute(1, Arc::clone(&task_ctx))?,
        ];

        // Poll both until one of them emits an unmatched right row (NULL left
        // columns), which only happens in the final right replay. With a batch
        // size of 1 it has not reported probe completion by then.
        let replaying = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                for (i, stream) in streams.iter_mut().enumerate() {
                    if let Poll::Ready(Some(batch)) = futures::poll!(stream.next()) {
                        let batch = batch?;
                        if batch.num_rows() > 0 && batch.column(0).null_count() > 0 {
                            return Ok::<_, DataFusionError>(i);
                        }
                    }
                }
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        })
        .await
        .expect("no partition reached the right replay")?;
        let left_spill = Arc::clone(
            plan.left_chunk_barrier
                .inner
                .lock()
                .left_spill
                .as_ref()
                .expect("the left side spilled"),
        );
        drop(streams.remove(replaying));
        let survivor = streams.pop().unwrap();

        let batches =
            tokio::time::timeout(Duration::from_secs(30), common::collect(survivor))
                .await
                .expect("the remaining partition stalled")?;
        // The survivor emits its own unmatched right rows, but the final left
        // rows are not emitted. Had the replaying partition already reported,
        // they would be.
        assert_eq!(
            count_final_left_rows(JoinType::Full, &batches),
            0,
            "the replaying partition must not have reported before it was dropped"
        );
        drop(left_spill);

        // Nothing stays reserved, although the plan is still alive. The bitmap
        // is only released once every partition has finished or gone away.
        assert_eq!(task_ctx.memory_pool().reserved(), 0);
        Ok(())
    }

    /// Like `task_ctx_with_memory_limit`, but also sets
    /// `enable_nlj_coordinated_fallback = false` (the opt-out a distributed
    /// engine would use).
    fn task_ctx_with_memory_limit_no_coordinated_fallback(
        memory_limit: usize,
        batch_size: usize,
    ) -> Result<Arc<TaskContext>> {
        let runtime = RuntimeEnvBuilder::new()
            .with_memory_limit(memory_limit, 1.0)
            .build_arc()?;
        let mut cfg = TaskContext::default()
            .session_config()
            .clone()
            .with_batch_size(batch_size);
        cfg.options_mut().execution.enable_nlj_coordinated_fallback = false;
        let task_ctx = TaskContext::default()
            .with_runtime(runtime)
            .with_session_config(cfg);
        Ok(Arc::new(task_ctx))
    }

    /// Collect a multi-partition NLJ under a tight memory limit and return the
    /// first error, if any. Used to assert that the opt-out makes a
    /// left-emitting multi-partition join fail with resource exhaustion (rather
    /// than spill, or -- in a distributed setting -- lose its final left rows).
    async fn multi_partition_join_collect_err(
        left: Arc<dyn ExecutionPlan>,
        right: Arc<dyn ExecutionPlan>,
        join_type: &JoinType,
        join_filter: Option<JoinFilter>,
        context: Arc<TaskContext>,
    ) -> Result<()> {
        let partition_count = 4;
        let right = Arc::new(RepartitionExec::try_new(
            right,
            Partitioning::RoundRobinBatch(partition_count),
        )?) as Arc<dyn ExecutionPlan>;
        let nested_loop_join = Arc::new(NestedLoopJoinExec::try_new(
            left,
            right,
            join_filter,
            join_type,
            None,
        )?);

        let mut handles = vec![];
        for i in 0..partition_count {
            let stream = nested_loop_join.execute(i, Arc::clone(&context))?;
            handles.push(SpawnedTask::spawn(
                async move { common::collect(stream).await },
            ));
        }
        for handle in handles {
            handle.join().await.expect("partition task panicked")?;
        }
        Ok(())
    }

    /// When `enable_nlj_coordinated_fallback` is disabled, a LEFT join with
    /// a multi-partition right side must NOT take the fallback: it fails with
    /// resource exhaustion under a tight memory limit instead. This is the
    /// distributed-safe opt-out (across processes, the partitions would not
    /// share the visited-left bitmap the fallback relies on).
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_fallback_disabled_left_join_oom() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit_no_coordinated_fallback(50, 16)?;
        let left = build_left_table_multi_chunk();
        let right = build_right_table_one_batch_per_row();
        let filter = prepare_join_filter();

        let err = multi_partition_join_collect_err(
            left,
            right,
            &JoinType::Left,
            Some(filter),
            task_ctx,
        )
        .await
        .unwrap_err();
        assert_contains!(err.to_string(), "Resources exhausted");
        Ok(())
    }

    /// FULL join counterpart of the above: the opt-out disables the fallback
    /// for FULL (also a left-emitting join) with a multi-partition right side,
    /// so it fails with resource exhaustion rather than spilling.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_fallback_disabled_full_join_oom() -> Result<()> {
        let task_ctx = task_ctx_with_memory_limit_no_coordinated_fallback(50, 16)?;
        let left = build_left_table_multi_chunk();
        let right = build_right_table_one_batch_per_row();
        let filter = prepare_join_filter();

        let err = multi_partition_join_collect_err(
            left,
            right,
            &JoinType::Full,
            Some(filter),
            task_ctx,
        )
        .await
        .unwrap_err();
        assert_contains!(err.to_string(), "Resources exhausted");
        Ok(())
    }

    /// The opt-out is scoped to *left-emitting* joins. A RIGHT join over a
    /// multi-partition right side needs no visited-left bitmap -- each
    /// partition owns its right rows exclusively -- so the opt-out must still
    /// leave it spilling rather than failing. This pins the scope of the guard
    /// so a future change cannot quietly turn off the spill fallback for join
    /// types that never needed the shared bitmap.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_nlj_memory_limited_fallback_disabled_right_join_still_spills()
    -> Result<()> {
        for join_type in [JoinType::Right, JoinType::Inner] {
            let task_ctx = task_ctx_with_memory_limit_no_coordinated_fallback(50, 16)?;
            let (_columns, _batches, metrics) =
                multi_partition_memory_limited_join_collect(
                    build_left_table_multi_chunk(),
                    build_right_table_one_batch_per_row(),
                    &join_type,
                    Some(prepare_join_filter()),
                    task_ctx,
                )
                .await?;
            assert!(
                metrics.spill_count().unwrap_or(0) > 0,
                "{join_type}: the opt-out must not disable the spill fallback for \
                 a join type that does not need left-bitmap coordination"
            );
        }
        Ok(())
    }
}