datafusion-physical-plan 56.0.0

Physical (ExecutionPlan) implementations for DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
// 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

//! TopK: Combination of Sort / LIMIT

use arrow::{
    array::{Array, AsArray},
    compute::{
        FilterBuilder, interleave_record_batch, prep_null_mask_filter, take_record_batch,
    },
    row::{RowConverter, Rows, SortField},
};
use datafusion_expr::{ColumnarValue, Operator};
use std::borrow::Borrow;
use std::mem::size_of;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use std::{cmp::Ordering, collections::BinaryHeap, sync::Arc};

use super::metrics::{
    BaselineMetrics, Count, ExecutionPlanMetricsSet, MetricBuilder, MetricCategory,
    RecordOutput,
};
use crate::{SendableRecordBatchStream, stream::RecordBatchStreamAdapter};

use arrow::array::{ArrayRef, RecordBatch, UInt32Array, UInt64Array};
use arrow::datatypes::{FieldRef, Schema, SchemaRef};
use datafusion_common::utils::memory::RecordBatchMemoryTracker;
use datafusion_common::{
    HashMap, Result, ScalarValue, internal_datafusion_err, internal_err,
};
use datafusion_execution::{
    memory_pool::{MemoryConsumer, MemoryReservation, proxy::VecAllocExt},
    runtime_env::RuntimeEnv,
};
use datafusion_physical_expr::{
    PhysicalExpr,
    expressions::{BinaryExpr, DynamicFilterPhysicalExpr, is_not_null, is_null, lit},
};
use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
use parking_lot::RwLock;

/// TopK
///
/// # Background
///
/// "Top K" is a common query optimization used for queries such as
/// "find the top 3 customers by revenue". The (simplified) SQL for
/// such a query might be:
///
/// ```sql
/// SELECT customer_id, revenue FROM 'sales.csv' ORDER BY revenue DESC limit 3;
/// ```
///
/// The simple plan would be:
///
/// ```sql
/// > explain SELECT customer_id, revenue FROM sales ORDER BY revenue DESC limit 3;
/// +--------------+----------------------------------------+
/// | plan_type    | plan                                   |
/// +--------------+----------------------------------------+
/// | logical_plan | Limit: 3                               |
/// |              |   Sort: revenue DESC NULLS FIRST       |
/// |              |     Projection: customer_id, revenue   |
/// |              |       TableScan: sales                 |
/// +--------------+----------------------------------------+
/// ```
///
/// While this plan produces the correct answer, it will fully sorts the
/// input before discarding everything other than the top 3 elements.
///
/// The same answer can be produced by simply keeping track of the top
/// K=3 elements, reducing the total amount of required buffer memory.
///
/// # Partial Sort Optimization
///
/// This implementation additionally optimizes queries where the input is already
/// partially sorted by a common prefix of the requested ordering. If subsequent
/// rows are guaranteed to be strictly greater (in sort order) than a known TopK
/// boundary on this prefix, the operator safely terminates early.
///
/// For a local TopK, that boundary comes from the local heap once it has K rows.
/// For a partitioned `SortExec`, a shared dynamic-filter threshold can provide
/// the same prefix boundary before a lagging partition has filled its local heap.
///
/// ## Example
///
/// For input sorted by `(day DESC)`, but not by `timestamp`, a query such as:
///
/// ```sql
/// SELECT day, timestamp FROM sensor ORDER BY day DESC, timestamp DESC LIMIT 10;
/// ```
///
/// can terminate scanning early once sufficient rows from the latest days have been
/// collected, skipping older data.
///
/// # Structure
///
/// This operator tracks the top K items using a `TopKHeap`.
pub struct TopK {
    /// schema of the output (and the input)
    schema: SchemaRef,
    /// Runtime metrics
    metrics: TopKMetrics,
    /// Reservation
    reservation: MemoryReservation,
    /// The target number of rows for output batches
    batch_size: usize,
    /// sort expressions
    expr: LexOrdering,
    /// row converter, for sort keys
    row_converter: RowConverter,
    /// scratch space for converting rows
    scratch_rows: Rows,
    /// stores the top k values and their sort key values, in order
    heap: TopKHeap,
    /// row converter, for common keys between the sort keys and the input ordering
    common_sort_prefix_converter: Option<RowConverter>,
    /// Common sort prefix between the input and the sort expressions to allow early exit optimization
    common_sort_prefix: Arc<[PhysicalSortExpr]>,
    /// Filter matching the state of the `TopK` heap used for dynamic filter pushdown
    filter: Arc<RwLock<TopKDynamicFilters>>,
    /// If true, indicates that all rows of subsequent batches are guaranteed
    /// to be greater (by byte order, after row conversion) than the top K,
    /// which means the top K won't change and the computation can be finished early.
    pub(crate) finished: bool,
}

/// For more background, please also see the [Dynamic Filters: Passing Information Between Operators During Execution for 25x Faster Queries blog]
///
/// [Dynamic Filters: Passing Information Between Operators During Execution for 25x Faster Queries blog]: https://datafusion.apache.org/blog/2025/09/10/dynamic-filters
///
/// # Example
///
/// Create a [`TopKDynamicFilters`] and pass it to [`TopK::try_new`]:
///
/// ```
/// # use std::sync::Arc;
/// # use arrow::datatypes::{DataType, Field, Schema};
/// # use datafusion_execution::runtime_env::RuntimeEnv;
/// # use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr};
/// # use datafusion_physical_plan::expressions::{DynamicFilterPhysicalExpr, col, lit};
/// # use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
/// # use parking_lot::RwLock;
/// use datafusion_physical_plan::{TopK, TopKDynamicFilters};
///
/// # fn main() -> datafusion_common::Result<()> {
/// let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
/// let sort_expr = PhysicalSortExpr::new_default(col("a", &schema)?);
///
/// // The dynamic filter starts as `true` and is tightened as the TopK heap fills
/// let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(
///     vec![col("a", &schema)?],
///     lit(true),
/// ));
/// let filter = Arc::new(RwLock::new(TopKDynamicFilters::new(dynamic_filter)));
///
/// let topk = TopK::try_new(
///     0,                                // partition_id
///     Arc::clone(&schema),              // schema
///     vec![],                           // common_sort_prefix
///     LexOrdering::from([sort_expr]),   // expr
///     10,                               // k
///     8192,                             // batch_size
///     Arc::new(RuntimeEnv::default()),  // runtime
///     &ExecutionPlanMetricsSet::new(),  // metrics
///     filter,                           // filter
/// )?;
/// # let _ = topk;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct TopKDynamicFilters {
    /// The current threshold shared by all TopK emitters that use this dynamic
    /// filter. Any emitter may tighten it.
    ///
    /// The full sort-key row and common-prefix row are stored together so they
    /// always describe the same heap row.
    shared_threshold: Option<TopKThreshold>,
    /// The expression used to evaluate the dynamic filter
    /// Only updated when lock held for the duration of the update
    expr: Arc<DynamicFilterPhysicalExpr>,
    /// Number of local TopK emitters that have not called `emit` yet.
    ///
    /// A partition-preserving `SortExec` creates one local TopK per output
    /// partition. The shared dynamic filter is complete only after every local
    /// TopK has emitted.
    ///
    /// `emit` only needs a read guard on the shared filter wrapper, so
    /// concurrent emitters use this atomic counter instead of taking an
    /// exclusive lock just to mark their partition done.
    remaining_topk_emitters: AtomicUsize,
}

#[derive(Debug, Clone)]
struct TopKThreshold {
    /// The full sort-key row bytes for efficient comparison.
    full_sort_key_row: Vec<u8>,
    /// The same heap row encoded with the common-prefix converter, when the
    /// input ordering shares a prefix with the TopK ordering.
    ///
    /// This lets each partition stop from a shared TopK threshold even if its
    /// local heap has not filled yet.
    common_prefix_row: Option<Vec<u8>>,
}

impl TopKThreshold {
    fn new(full_sort_key_row: Vec<u8>, common_prefix_row: Option<Vec<u8>>) -> Self {
        Self {
            full_sort_key_row,
            common_prefix_row,
        }
    }

    fn full_sort_key_row(&self) -> &[u8] {
        self.full_sort_key_row.as_slice()
    }

    fn common_prefix_row(&self) -> Option<&[u8]> {
        self.common_prefix_row.as_deref()
    }

    fn is_more_selective_than(&self, current: &Self) -> bool {
        self.full_sort_key_row() < current.full_sort_key_row()
    }
}

#[derive(Clone, Copy)]
struct TopKHeapBoundaryRow<'a> {
    row: &'a TopKRow,
}

impl<'a> TopKHeapBoundaryRow<'a> {
    fn new(row: &'a TopKRow) -> Self {
        Self { row }
    }

    fn full_sort_key_row(&self) -> &[u8] {
        self.row.row()
    }

    fn is_more_selective_than(&self, current: Option<&TopKThreshold>) -> bool {
        current
            .map(|current| self.full_sort_key_row() < current.full_sort_key_row())
            .unwrap_or(true)
    }
}

#[derive(Clone, Copy)]
struct TopKHeapBoundary<'a> {
    row: &'a TopKRow,
    batch: &'a RecordBatch,
}

impl<'a> TopKHeapBoundary<'a> {
    fn new(row: &'a TopKRow, batch: &'a RecordBatch) -> Self {
        Self { row, batch }
    }

    fn threshold_values(
        &self,
        sort_exprs: &[PhysicalSortExpr],
    ) -> Result<Vec<ScalarValue>> {
        let mut scalar_values = Vec::with_capacity(sort_exprs.len());
        let row = self.batch.slice(self.row.index, 1);
        for sort_expr in sort_exprs {
            let value = sort_expr.expr.evaluate(&row)?;

            let scalar = match value {
                ColumnarValue::Scalar(scalar) => scalar,
                ColumnarValue::Array(array) if array.len() == 1 => {
                    ScalarValue::try_from_array(&array, 0)?
                }
                array => {
                    return internal_err!("Expected a scalar value, got {:?}", array);
                }
            };
            scalar_values.push(scalar);
        }

        Ok(scalar_values)
    }

    fn threshold(&self, common_prefix_row: Option<Vec<u8>>) -> TopKThreshold {
        TopKThreshold::new(self.row.row().to_vec(), common_prefix_row)
    }
}

impl TopKDynamicFilters {
    /// Create a new `TopKDynamicFilters` with the given expression
    pub fn new(expr: Arc<DynamicFilterPhysicalExpr>) -> Self {
        Self::new_with_topk_emitter_count(expr, 1)
    }

    /// Create a new `TopKDynamicFilters` with the expected number of local
    /// TopK emitters that share it.
    pub fn new_with_topk_emitter_count(
        expr: Arc<DynamicFilterPhysicalExpr>,
        topk_emitter_count: usize,
    ) -> Self {
        debug_assert!(topk_emitter_count > 0);
        Self {
            shared_threshold: None,
            expr,
            remaining_topk_emitters: AtomicUsize::new(topk_emitter_count),
        }
    }

    pub fn expr(&self) -> Arc<DynamicFilterPhysicalExpr> {
        Arc::clone(&self.expr)
    }

    fn mark_topk_emitted(&self) {
        let previous = self
            .remaining_topk_emitters
            .try_update(
                AtomicOrdering::AcqRel,
                AtomicOrdering::Acquire,
                |remaining| remaining.checked_sub(1),
            )
            .unwrap_or(0);
        debug_assert!(
            previous > 0,
            "TopK dynamic filter emitter completed more times than expected"
        );

        if previous == 1 {
            self.expr.mark_complete();
        }
    }
}

// Guesstimate for memory allocation: estimated number of bytes used per row in the RowConverter
const ESTIMATED_BYTES_PER_ROW: usize = 20;

pub(crate) fn build_sort_fields(
    ordering: &[PhysicalSortExpr],
    schema: &SchemaRef,
) -> Result<Vec<SortField>> {
    ordering
        .iter()
        .map(|e| {
            Ok(SortField::new_with_options(
                e.expr.data_type(schema)?,
                e.options,
            ))
        })
        .collect::<Result<_>>()
}

impl TopK {
    /// Create a new [`TopK`] that stores the top `k` values, as
    /// defined by the sort expressions in `expr`.
    // TODO: make a builder or some other nicer API
    #[expect(clippy::too_many_arguments)]
    #[expect(clippy::needless_pass_by_value)]
    pub fn try_new(
        partition_id: usize,
        schema: SchemaRef,
        common_sort_prefix: Vec<PhysicalSortExpr>,
        expr: LexOrdering,
        k: usize,
        batch_size: usize,
        runtime: Arc<RuntimeEnv>,
        metrics: &ExecutionPlanMetricsSet,
        filter: Arc<RwLock<TopKDynamicFilters>>,
    ) -> Result<Self> {
        let reservation = MemoryConsumer::new(format!("TopK[{partition_id}]"))
            .register(&runtime.memory_pool);

        let sort_fields = build_sort_fields(&expr, &schema)?;

        // TODO there is potential to add special cases for single column sort fields
        // to improve performance
        let row_converter = RowConverter::new(sort_fields)?;
        let scratch_rows =
            row_converter.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);

        let common_prefix_row_converter = if common_sort_prefix.is_empty() {
            None
        } else {
            let input_sort_fields = build_sort_fields(&common_sort_prefix, &schema)?;
            Some(RowConverter::new(input_sort_fields)?)
        };

        Ok(Self {
            schema: Arc::clone(&schema),
            metrics: TopKMetrics::new(metrics, partition_id),
            reservation,
            batch_size,
            expr,
            row_converter,
            scratch_rows,
            heap: TopKHeap::new(k),
            common_sort_prefix_converter: common_prefix_row_converter,
            common_sort_prefix: Arc::from(common_sort_prefix),
            finished: false,
            filter,
        })
    }

    /// Insert `batch`, remembering if any of its values are among
    /// the top k seen so far.
    pub fn insert_batch(&mut self, batch: RecordBatch) -> Result<()> {
        // Updates on drop
        let elapsed_compute = self.metrics.baseline.elapsed_compute().clone();
        let _timer = elapsed_compute.timer();

        let mut selected_rows = None;

        // If a filter is provided, update it with the new rows
        let filter = self.filter.read().expr.current()?;
        let filtered = filter.evaluate(&batch)?;
        let num_rows = batch.num_rows();
        let array = filtered.into_array(num_rows)?;
        let mut filter = array.as_boolean().clone();
        if !filter.has_true() {
            // The heap is unchanged, but a fully rejected batch can still prove
            // that the shared sort prefix has passed the heap boundary.
            self.attempt_early_completion(&batch)?;
            return Ok(());
        }

        // Sort keys are only needed once some row passes the threshold
        let mut sort_keys: Vec<ArrayRef> = self
            .expr
            .iter()
            .map(|expr| {
                let value = expr.expr.evaluate(&batch)?;
                value.into_array(num_rows)
            })
            .collect::<Result<Vec<_>>>()?;

        // only update the keys / rows if the filter does not match all rows
        if filter.null_count() > 0 || filter.has_false() {
            // Indices in `set_indices` should be correct if filter contains nulls
            // So we prepare the filter here. Note this is also done in the `FilterBuilder`
            // so there is no overhead to do this here.
            if filter.nulls().is_some() {
                filter = prep_null_mask_filter(&filter);
            }

            let filter_predicate = FilterBuilder::new(&filter);
            let filter_predicate = if sort_keys.len() > 1 {
                // Optimize filter when it has multiple sort keys
                filter_predicate.optimize().build()
            } else {
                filter_predicate.build()
            };
            selected_rows = Some(filter);
            sort_keys = sort_keys
                .iter()
                .map(|key| filter_predicate.filter(key).map_err(|x| x.into()))
                .collect::<Result<Vec<_>>>()?;
        }
        // reuse existing `Rows` to avoid reallocations
        let rows = &mut self.scratch_rows;
        rows.clear();
        self.row_converter.append(rows, &sort_keys)?;

        let mut batch_entry = self.heap.register_batch(batch);

        let replacements = match selected_rows {
            Some(filter) => {
                self.find_new_topk_items(filter.values().set_indices(), &mut batch_entry)
            }
            None => self.find_new_topk_items(0..sort_keys[0].len(), &mut batch_entry),
        };

        if replacements > 0 {
            self.metrics.row_replacements.add(replacements);

            // The heap takes ownership of the batch (and compaction may drop
            // it), so encode its last row's prefix while it is still at hand.
            let last_row_prefix = self.last_row_common_prefix(&batch_entry.batch)?;

            self.heap.insert_batch_entry(batch_entry);

            // conserve memory
            self.heap.maybe_compact()?;

            // update memory reservation
            self.reservation.try_resize(self.size())?;

            // flag the topK as finished if we know that all
            // subsequent batches are guaranteed to be greater (by byte order, after row conversion) than the top K,
            // which means the top K won't change and the computation can be finished early.
            self.finish_if_prefix_past_boundary(last_row_prefix.as_ref())?;

            // update the filter representation of our TopK heap
            self.update_filter()?;
        } else {
            // The heap did not change, but this batch's prefix may still prove
            // that no later rows can enter the TopK.
            self.attempt_early_completion(&batch_entry.batch)?;
        }

        Ok(())
    }

    fn find_new_topk_items(
        &mut self,
        items: impl Iterator<Item = usize>,
        batch_entry: &mut RecordBatchEntry,
    ) -> usize {
        let mut replacements = 0;
        let rows = &mut self.scratch_rows;
        for (index, row) in items.zip(rows.iter()) {
            match self.heap.max() {
                // heap has k items, and the new row is greater than the
                // current max in the heap ==> it is not a new topk
                Some(max_row) if row.as_ref() >= max_row.row() => {}
                // don't yet have k items or new item is lower than the currently k low values
                None | Some(_) => {
                    self.heap.add(batch_entry, row, index);
                    replacements += 1;
                }
            }
        }
        replacements
    }

    fn current_heap_boundary_row(&self) -> Option<TopKHeapBoundaryRow<'_>> {
        self.heap.max().map(TopKHeapBoundaryRow::new)
    }

    fn current_heap_boundary(&self) -> Result<Option<TopKHeapBoundary<'_>>> {
        let Some(row) = self.heap.max() else {
            return Ok(None);
        };

        self.heap_boundary(row).map(Some)
    }

    fn heap_boundary<'a>(&'a self, row: &'a TopKRow) -> Result<TopKHeapBoundary<'a>> {
        let batch_entry = self
            .heap
            .store
            .get(row.batch_id)
            .ok_or_else(|| internal_datafusion_err!("Invalid batch ID in TopKRow"))?;

        Ok(TopKHeapBoundary::new(row, &batch_entry.batch))
    }

    /// Update the filter representation of our TopK heap.
    /// For example, given the sort expression `ORDER BY a DESC, b ASC LIMIT 3`,
    /// and the current heap values `[(1, 5), (1, 4), (2, 3)]`,
    /// the filter will be updated to:
    ///
    /// ```sql
    /// (a > 1 OR (a = 1 AND b < 5)) AND
    /// (a > 1 OR (a = 1 AND b < 4)) AND
    /// (a > 2 OR (a = 2 AND b < 3))
    /// ```
    fn update_filter(&mut self) -> Result<()> {
        // If the heap doesn't have k elements yet, we can't create thresholds
        let Some(boundary_row) = self.current_heap_boundary_row() else {
            return Ok(());
        };

        // Fast path: check if the current value in topk is better than what is
        // currently set in the filter with a read only lock
        let needs_update = {
            let filter = self.filter.read();
            boundary_row.is_more_selective_than(filter.shared_threshold.as_ref())
        };

        // exit early if the current values are better
        if !needs_update {
            return Ok(());
        }

        let boundary = self.heap_boundary(boundary_row.row)?;

        // Extract scalar values BEFORE acquiring lock to reduce critical section
        let thresholds = boundary.threshold_values(&self.expr)?;

        // Build the filter expression OUTSIDE any synchronization
        let predicate = Self::build_filter_expression(&self.expr, &thresholds)?;
        let new_threshold =
            boundary.threshold(self.encode_topk_common_prefix_row(boundary)?);

        // update the threshold. Since there was a lock gap, we must check if it is still the best
        // may have changed while we were building the expression without the lock
        let mut filter = self.filter.write();
        let still_needs_update = filter
            .shared_threshold
            .as_ref()
            .map(|current| new_threshold.is_more_selective_than(current))
            .unwrap_or(true);
        if !still_needs_update {
            // some other thread updated the threshold to a better one while we
            // were building so there is no need to update the filter
            return Ok(());
        }
        filter.shared_threshold = Some(new_threshold);

        // Update the filter expression
        if let Some(pred) = predicate
            && !pred.eq(&lit(true))
        {
            filter.expr.update(pred)?;
        }

        Ok(())
    }

    /// Build the filter expression with the given thresholds.
    /// This is now called outside of any locks to reduce critical section time.
    fn build_filter_expression(
        sort_exprs: &[PhysicalSortExpr],
        thresholds: &[ScalarValue],
    ) -> Result<Option<Arc<dyn PhysicalExpr>>> {
        // Create filter expressions for each threshold
        let mut filters: Vec<Arc<dyn PhysicalExpr>> =
            Vec::with_capacity(thresholds.len());

        let mut prev_sort_expr: Option<Arc<dyn PhysicalExpr>> = None;
        for (sort_expr, value) in sort_exprs.iter().zip(thresholds.iter()) {
            // Comparisons on nested types (List, Struct, ...) order NULL elements
            // with fixed default options rather than the sort's `nulls_first`, so
            // `col < threshold` could drop rows that belong in the TopK. Stop at
            // the first nested key: keep rows whose earlier keys equal the
            // threshold and do not filter on this or any later key.
            if value.data_type().is_nested() {
                if let Some(prev) = prev_sort_expr.take() {
                    filters.push(prev);
                }
                break;
            }

            // Create the appropriate operator based on sort order
            let op = if sort_expr.options.descending {
                // For descending sort, we want col > threshold (exclude smaller values)
                Operator::Gt
            } else {
                // For ascending sort, we want col < threshold (exclude larger values)
                Operator::Lt
            };

            let value_null = value.is_null();

            let comparison = Arc::new(BinaryExpr::new(
                Arc::clone(&sort_expr.expr),
                op,
                lit(value.clone()),
            ));

            let comparison_with_null = match (sort_expr.options.nulls_first, value_null) {
                // For nulls first, transform to (threshold.value is not null) and (threshold.expr is null or comparison)
                (true, true) => lit(false),
                (true, false) => Arc::new(BinaryExpr::new(
                    is_null(Arc::clone(&sort_expr.expr))?,
                    Operator::Or,
                    comparison,
                )),
                // For nulls last, transform to (threshold.value is null and threshold.expr is not null)
                // or (threshold.value is not null and comparison)
                (false, true) => is_not_null(Arc::clone(&sort_expr.expr))?,
                (false, false) => comparison,
            };

            let mut eq_expr = Arc::new(BinaryExpr::new(
                Arc::clone(&sort_expr.expr),
                Operator::Eq,
                lit(value.clone()),
            ));

            if value_null {
                eq_expr = Arc::new(BinaryExpr::new(
                    is_null(Arc::clone(&sort_expr.expr))?,
                    Operator::Or,
                    eq_expr,
                ));
            }

            // For a query like order by a, b, the filter for column `b` is only applied if
            // the condition a = threshold.value (considering null equality) is met.
            // Therefore, we add equality predicates for all preceding fields to the filter logic of the current field,
            // and include the current field's equality predicate in `prev_sort_expr` for use with subsequent fields.
            match prev_sort_expr.take() {
                None => {
                    prev_sort_expr = Some(eq_expr);
                    filters.push(comparison_with_null);
                }
                Some(p) => {
                    filters.push(Arc::new(BinaryExpr::new(
                        Arc::clone(&p),
                        Operator::And,
                        comparison_with_null,
                    )));

                    prev_sort_expr =
                        Some(Arc::new(BinaryExpr::new(p, Operator::And, eq_expr)));
                }
            }
        }

        let dynamic_predicate = filters
            .into_iter()
            .reduce(|a, b| Arc::new(BinaryExpr::new(a, Operator::Or, b)));

        Ok(dynamic_predicate)
    }

    /// If input ordering shares a common sort prefix with the TopK,
    /// check if the computation can be finished early.
    ///
    /// This is the case if the last row of the current batch is strictly
    /// greater than either the shared dynamic-filter threshold prefix or the max
    /// row in the local heap, comparing only on the shared prefix columns.
    fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
        let last_row_prefix = self.last_row_common_prefix(batch)?;
        self.finish_if_prefix_past_boundary(last_row_prefix.as_ref())
    }

    /// Encodes the shared sort prefix of the last row of `batch`.
    ///
    /// Returns `None` when the batch is empty (there is no last row) or when
    /// the input ordering shares no prefix with the TopK.
    fn last_row_common_prefix(&self, batch: &RecordBatch) -> Result<Option<Rows>> {
        // Early exit if the batch is empty as there is no last row to extract from it.
        if batch.num_rows() == 0 {
            return Ok(None);
        }

        // common_prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
        // so early exit if it is `None`.
        let Some(prefix_converter) = &self.common_sort_prefix_converter else {
            return Ok(None);
        };

        // Evaluate the prefix for the last row of the current batch.
        let last_row_idx = batch.num_rows() - 1;
        let mut batch_prefix_scratch =
            prefix_converter.empty_rows(1, ESTIMATED_BYTES_PER_ROW); // 1 row with capacity ESTIMATED_BYTES_PER_ROW

        self.append_common_prefix_row(
            prefix_converter,
            batch,
            last_row_idx,
            &mut batch_prefix_scratch,
        )?;
        Ok(Some(batch_prefix_scratch))
    }

    /// Marks the TopK finished when a batch's last-row prefix, as produced by
    /// [`Self::last_row_common_prefix`], lies past the shared or local boundary.
    fn finish_if_prefix_past_boundary(
        &mut self,
        last_row_prefix: Option<&Rows>,
    ) -> Result<()> {
        let Some(batch_prefix_rows) = last_row_prefix else {
            return Ok(());
        };
        let batch_common_prefix_row = batch_prefix_rows.row(0);
        let batch_common_prefix = batch_common_prefix_row.as_ref();

        let finished_by_shared_threshold = self
            .filter
            .read()
            .shared_threshold
            .as_ref()
            .and_then(TopKThreshold::common_prefix_row)
            .map(|common_prefix_row| batch_common_prefix > common_prefix_row)
            .unwrap_or(false);
        if finished_by_shared_threshold {
            self.finished = true;
            return Ok(());
        }

        // Early exit only from the local heap once it has a full boundary row.
        let Some(boundary) = self.current_heap_boundary()? else {
            return Ok(());
        };

        if self.batch_prefix_exceeds_heap_boundary(batch_common_prefix, boundary)? {
            self.finished = true;
        }

        Ok(())
    }

    fn batch_prefix_exceeds_heap_boundary(
        &self,
        batch_common_prefix: &[u8],
        boundary: TopKHeapBoundary<'_>,
    ) -> Result<bool> {
        let Some(heap_common_prefix_row) =
            self.encode_topk_common_prefix_row(boundary)?
        else {
            return Ok(false);
        };

        Ok(batch_common_prefix > heap_common_prefix_row.as_slice())
    }

    fn encode_topk_common_prefix_row(
        &self,
        boundary: TopKHeapBoundary<'_>,
    ) -> Result<Option<Vec<u8>>> {
        let Some(prefix_converter) = &self.common_sort_prefix_converter else {
            return Ok(None);
        };

        let mut scratch = prefix_converter.empty_rows(1, ESTIMATED_BYTES_PER_ROW);
        self.append_common_prefix_row(
            prefix_converter,
            boundary.batch,
            boundary.row.index,
            &mut scratch,
        )?;
        Ok(Some(scratch.row(0).as_ref().to_vec()))
    }

    fn append_common_prefix_row(
        &self,
        prefix_converter: &RowConverter,
        batch: &RecordBatch,
        row_idx: usize,
        scratch: &mut Rows,
    ) -> Result<()> {
        let row = batch.slice(row_idx, 1);
        let prefix_columns: Vec<ArrayRef> = self
            .common_sort_prefix
            .iter()
            .map(|expr| expr.expr.evaluate(&row)?.into_array(1))
            .collect::<Result<_>>()?;

        prefix_converter.append(scratch, &prefix_columns)?;
        Ok(())
    }

    /// Returns the top k results broken into `batch_size` [`RecordBatch`]es, consuming the heap
    pub fn emit(self) -> Result<SendableRecordBatchStream> {
        let Self {
            schema,
            metrics,
            reservation: _,
            batch_size,
            expr: _,
            row_converter: _,
            scratch_rows: _,
            mut heap,
            common_sort_prefix_converter: _,
            common_sort_prefix: _,
            finished: _,
            filter,
        } = self;
        let _timer = metrics.baseline.elapsed_compute().timer(); // time updated on drop

        // Mark this local TopK as emitted. For shared filters, the final
        // local emitter marks the dynamic filter complete.
        filter.read().mark_topk_emitted();

        // break into record batches as needed
        let mut batches = vec![];
        if let Some(mut batch) = heap.emit()? {
            loop {
                if batch.num_rows() <= batch_size {
                    (&batch).record_output(&metrics.baseline);
                    batches.push(Ok(batch));
                    break;
                } else {
                    let head = batch.slice(0, batch_size);
                    (&head).record_output(&metrics.baseline);
                    batches.push(Ok(head));
                    let remaining_length = batch.num_rows() - batch_size;
                    batch = batch.slice(batch_size, remaining_length);
                }
            }
        }
        Ok(Box::pin(RecordBatchStreamAdapter::new(
            schema,
            futures::stream::iter(batches),
        )))
    }

    /// return the size of memory used by this operator, in bytes
    fn size(&self) -> usize {
        size_of::<Self>()
            + self.row_converter.size()
            + self
                .common_sort_prefix_converter
                .as_ref()
                .map_or(0, RowConverter::size)
            + self.scratch_rows.size()
            + self.heap.size()
    }
}

struct TopKMetrics {
    /// metrics
    pub baseline: BaselineMetrics,

    /// count of how many rows were replaced in the heap
    pub row_replacements: Count,
}

impl TopKMetrics {
    fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
        Self {
            baseline: BaselineMetrics::new(metrics, partition),
            row_replacements: MetricBuilder::new(metrics)
                .with_category(MetricCategory::Rows)
                .counter("row_replacements", partition),
        }
    }
}

/// Rows a [`RecordBatchStore`] may hold per row still referenced by a heap,
/// before the referencing operator rewrites it.
///
/// A store entry is freed only when the last row referencing it is evicted, so
/// what it holds tracks the *input* rather than the rows retained. Both top-K
/// paths bound that the same way — compact once the store holds this multiple
/// of what is still referenced — and only the denominator differs: one heap's
/// length in [`TopKHeap::maybe_compact`], every partition's retained rows
/// (heap slots, plus ties for `RANK`) in [`RecordBatchStore::compact`]. The
/// multiplier avoids compacting when the savings would be marginal.
const STORE_COMPACTION_RATIO: usize = 2;

/// This structure keeps at most the *smallest* k items, using the
/// [arrow::row] format for sort keys. While it is called "topK" for
/// values like `1, 2, 3, 4, 5` the "top 3" really means the
/// *smallest* 3 , `1, 2, 3`, not the *largest* 3 `3, 4, 5`.
///
/// Using the `Row` format handles things such as ascending vs
/// descending and nulls first vs nulls last.
struct TopKHeap {
    /// The maximum number of elements to store in this heap.
    k: usize,
    /// Storage for up at most `k` items using a BinaryHeap. Reversed
    /// so that the smallest k so far is on the top
    inner: BinaryHeap<TopKRow>,
    /// Storage the original row values (TopKRow only has the sort key)
    store: RecordBatchStore,
    /// The size of all owned data held by this heap
    owned_bytes: usize,
}

impl TopKHeap {
    fn new(k: usize) -> Self {
        assert!(k > 0);
        Self {
            k,
            inner: BinaryHeap::new(),
            store: RecordBatchStore::new(),
            owned_bytes: 0,
        }
    }

    /// Register a [`RecordBatch`] with the heap, returning the
    /// appropriate entry
    pub fn register_batch(&mut self, batch: RecordBatch) -> RecordBatchEntry {
        self.store.register(batch)
    }

    /// Insert a [`RecordBatchEntry`] created by a previous call to
    /// [`Self::register_batch`] into storage.
    pub fn insert_batch_entry(&mut self, entry: RecordBatchEntry) {
        self.store.insert(entry)
    }

    /// Returns the largest value stored by the heap if there are k
    /// items, otherwise returns None. Remember this structure is
    /// keeping the "smallest" k values
    fn max(&self) -> Option<&TopKRow> {
        if self.inner.len() < self.k {
            None
        } else {
            self.inner.peek()
        }
    }

    /// Adds `row` to this heap. If inserting this new item would
    /// increase the size past `k`, removes the previously smallest
    /// item.
    fn add(
        &mut self,
        batch_entry: &mut RecordBatchEntry,
        row: impl AsRef<[u8]>,
        index: usize,
    ) {
        let batch_id = batch_entry.id;
        batch_entry.uses += 1;

        assert!(self.inner.len() <= self.k);
        let row = row.as_ref();

        // Reuse storage for evicted item if possible
        if self.inner.len() == self.k {
            let mut prev_min = self.inner.peek_mut().unwrap();

            // Update batch use
            if prev_min.batch_id == batch_entry.id {
                batch_entry.uses -= 1;
            } else {
                self.store.unuse(prev_min.batch_id);
            }

            // update memory accounting
            self.owned_bytes -= prev_min.owned_size();

            prev_min.replace_with(row, batch_id, index);

            self.owned_bytes += prev_min.owned_size();
        } else {
            let new_row = TopKRow::new(row, batch_id, index);
            self.owned_bytes += new_row.owned_size();
            // put the new row into the heap
            self.inner.push(new_row);
        }
    }

    /// Returns the values stored in this heap, from values low to
    /// high, as a single [`RecordBatch`], resetting the inner heap
    pub fn emit(&mut self) -> Result<Option<RecordBatch>> {
        Ok(self.emit_with_state()?.0)
    }

    /// Returns the values stored in this heap, from values low to
    /// high, as a single [`RecordBatch`], and a sorted vec of the
    /// current heap's contents
    fn emit_with_state(&mut self) -> Result<(Option<RecordBatch>, Vec<TopKRow>)> {
        // generate sorted rows
        let topk_rows = std::mem::take(&mut self.inner).into_sorted_vec();

        if self.store.is_empty() {
            return Ok((None, topk_rows));
        }

        // The batch ids are not continuous, so `indices` below is built through
        // the store's "batch_id -> array_pos" mapping.
        let (record_batches, batch_id_array_pos) = self.store.positional();

        let indices: Vec<_> = topk_rows
            .iter()
            .map(|k| (batch_id_array_pos[&k.batch_id], k.index))
            .collect();

        // At this point `indices` contains indexes within the
        // rows and `input_arrays` contains a reference to the
        // relevant RecordBatch for that index. `interleave_record_batch` pulls
        // them together into a single new batch
        let new_batch = interleave_record_batch(&record_batches, &indices)?;

        Ok((Some(new_batch), topk_rows))
    }

    /// Compact this heap, rewriting all stored batches into a single
    /// input batch
    pub fn maybe_compact(&mut self) -> Result<()> {
        // Don't compact if there's only one batch (compacting into itself is pointless)
        if self.store.len() <= 1 {
            return Ok(());
        }

        let total_rows = self.store.total_rows;
        let num_rows = self.inner.len();

        // Compact when the store holds more than STORE_COMPACTION_RATIO x what
        // the compacted result would need. The multiplier avoids compacting when the
        // savings would be marginal.
        if total_rows <= num_rows * STORE_COMPACTION_RATIO {
            return Ok(());
        }

        // at first, compact the entire thing always into a new batch
        // (maybe we can get fancier in the future about ignoring
        // batches that have a high usage ratio already

        // Note: new batch is in the same order as inner
        let (new_batch, mut topk_rows) = self.emit_with_state()?;
        let Some(new_batch) = new_batch else {
            return Ok(());
        };

        // clear all old entries in store (this invalidates all
        // store_ids in `inner`)
        self.store.clear();

        let mut batch_entry = self.register_batch(new_batch);
        batch_entry.uses = num_rows;

        // rewrite all existing entries to use the new batch, and
        // remove old entries. The sortedness and their relative
        // position do not change
        for (i, topk_row) in topk_rows.iter_mut().enumerate() {
            topk_row.batch_id = batch_entry.id;
            topk_row.index = i;
        }
        self.insert_batch_entry(batch_entry);
        // restore the heap
        self.inner = BinaryHeap::from(topk_rows);

        Ok(())
    }

    /// return the size of memory used by this heap, in bytes
    fn size(&self) -> usize {
        size_of::<Self>()
            + (self.inner.capacity() * size_of::<TopKRow>())
            + self.store.size()
            + self.owned_bytes
    }
}

/// Represents one of the top K rows held in this heap. Orders
/// according to memcmp of row (e.g. the arrow Row format, but could
/// also be primitive values)
///
/// Reuses allocations to minimize runtime overhead of creating new Vecs
#[derive(Debug, PartialEq)]
struct TopKRow {
    /// the value of the sort key for this row. This contains the
    /// bytes that could be stored in `OwnedRow` but uses `Vec<u8>` to
    /// reuse allocations.
    row: Vec<u8>,
    /// the RecordBatch this row came from: an id into a [`RecordBatchStore`]
    batch_id: u32,
    /// the index in this record batch the row came from
    index: usize,
}

impl TopKRow {
    /// Create a new TopKRow with new allocation
    fn new(row: impl AsRef<[u8]>, batch_id: u32, index: usize) -> Self {
        Self {
            row: row.as_ref().to_vec(),
            batch_id,
            index,
        }
    }

    // Replace the existing row capacity with new values
    fn replace_with(&mut self, new_row: impl AsRef<[u8]>, batch_id: u32, index: usize) {
        self.row.clear();
        self.row.extend_from_slice(new_row.as_ref());

        self.batch_id = batch_id;
        self.index = index;
    }

    /// Returns the number of bytes owned by this row in the heap (not
    /// including itself)
    fn owned_size(&self) -> usize {
        self.row.capacity()
    }

    /// Returns a slice to the owned row value
    fn row(&self) -> &[u8] {
        self.row.as_slice()
    }
}

impl Eq for TopKRow {}

impl PartialOrd for TopKRow {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        // TODO PartialOrd is not consistent with PartialEq; PartialOrd contract is violated
        Some(self.cmp(other))
    }
}

impl Ord for TopKRow {
    fn cmp(&self, other: &Self) -> Ordering {
        self.row.cmp(&other.row)
    }
}

#[derive(Debug)]
struct RecordBatchEntry {
    id: u32,
    batch: RecordBatch,
    // for this batch, how many times has it been used
    uses: usize,
}

/// This structure tracks [`RecordBatch`] by an id so that:
///
/// 1. The baches can be tracked via an id that can be copied cheaply
/// 2. The total memory held by all batches is tracked
#[derive(Debug)]
struct RecordBatchStore {
    /// id generator
    next_id: u32,
    /// storage
    batches: HashMap<u32, RecordBatchEntry>,
    /// Counts the buffers of the stored batches. Stored input batches can be
    /// zero-copy slices of one larger batch, which keep all of its buffers
    /// alive, so each shared buffer is counted once.
    batch_memory: RecordBatchMemoryTracker,
    /// total size of all record batches tracked by this store
    batches_size: usize,
    /// row count of all the batches
    total_rows: usize,
}

impl RecordBatchStore {
    fn new() -> Self {
        Self {
            next_id: 0,
            batches: HashMap::new(),
            batch_memory: RecordBatchMemoryTracker::new(),
            batches_size: 0,
            total_rows: 0,
        }
    }

    /// Register this batch with the store and assign an ID. No
    /// attempt is made to compare this batch to other batches
    pub fn register(&mut self, batch: RecordBatch) -> RecordBatchEntry {
        let id = self.next_id;
        self.next_id += 1;
        RecordBatchEntry { id, batch, uses: 0 }
    }

    /// The id the next [`Self::register`] call will assign.
    fn next_batch_id(&self) -> u32 {
        self.next_id
    }

    /// Start the entry a partitioned operator's `insert_batch` fills: slots can
    /// point at its id during the admission pass, before the gathered batch
    /// exists. Finished by [`Self::insert_rows`]; valid until the next
    /// `register`, which nothing may call in between.
    fn pending(&self) -> PendingEntry {
        PendingEntry {
            id: self.next_batch_id(),
            uses: 0,
        }
    }

    /// Drop one use of entry `id` for a retained row going away. A row of the
    /// batch being inserted is not in the store yet, so its use comes off
    /// `pending` rather than through [`Self::unuse`], which would panic on the
    /// unregistered id.
    fn release(&mut self, pending: &mut PendingEntry, id: u32) {
        if id == pending.id {
            pending.uses -= 1;
        } else {
            self.unuse(id);
        }
    }

    /// Insert a record batch entry into this store, tracking its
    /// memory use, if it has any uses
    pub fn insert(&mut self, entry: RecordBatchEntry) {
        // uses of 0 means that none of the rows in the batch were stored in the topk
        if entry.uses > 0 {
            self.batches_size += self.batch_memory.count_batch(&entry.batch);
            self.total_rows += entry.batch.num_rows();
            self.batches.insert(entry.id, entry);
        }
    }

    /// Finish `pending`: gather `rows` of `batch` into its entry and insert
    /// it, or do nothing if no slot still points at it, leaving the id to the
    /// next batch.
    ///
    /// For the partitioned operators' decide-then-gather: each slot's row is
    /// its position in `rows`, which the gather keeps. Takes `pending` by
    /// value so no use can be released against it once it is finished.
    #[expect(clippy::needless_pass_by_value)]
    fn insert_rows(
        &mut self,
        batch: &RecordBatch,
        rows: &[u32],
        pending: PendingEntry,
    ) -> Result<()> {
        let PendingEntry { id, uses } = pending;
        if uses == 0 {
            return Ok(());
        }
        let gather_idx = UInt32Array::from_iter_values(rows.iter().copied());
        let mut entry = self.register(take_record_batch(batch, &gather_idx)?);
        debug_assert_eq!(
            entry.id, id,
            "the id handed to the slots must be the id the gather got"
        );
        entry.uses = uses;
        self.insert(entry);
        Ok(())
    }

    /// Clear all values in this store, invalidating all previous batch ids
    fn clear(&mut self) {
        self.batches.clear();
        self.batch_memory = RecordBatchMemoryTracker::new();
        self.batches_size = 0;
        self.total_rows = 0;
    }

    fn get(&self, id: u32) -> Option<&RecordBatchEntry> {
        self.batches.get(&id)
    }

    /// returns the total number of batches stored in this store
    fn len(&self) -> usize {
        self.batches.len()
    }

    /// The stored batches in iteration order, paired with the
    /// `batch_id -> position` map that indexes them.
    ///
    /// `interleave_record_batch` addresses its inputs positionally while this
    /// store keys them by a non-contiguous id, so every caller that interleaves
    /// out of the store needs both. The batches are borrowed; a caller that
    /// needs them to outlive the store clones them itself.
    fn positional(&self) -> (Vec<&RecordBatch>, HashMap<u32, usize>) {
        let mut batches = Vec::with_capacity(self.batches.len());
        let mut positions = HashMap::with_capacity(self.batches.len());
        for (pos, (batch_id, entry)) in self.batches.iter().enumerate() {
            batches.push(&entry.batch);
            positions.insert(*batch_id, pos);
        }
        (batches, positions)
    }

    /// returns true if the store has nothing stored
    fn is_empty(&self) -> bool {
        self.batches.is_empty()
    }

    /// remove a use from the specified batch id. If the use count
    /// reaches zero the batch entry is removed from the store
    ///
    /// panics if there were no remaining uses of id
    pub fn unuse(&mut self, id: u32) {
        let remove = if let Some(batch_entry) = self.batches.get_mut(&id) {
            batch_entry.uses = batch_entry.uses.checked_sub(1).expect("underflow");
            batch_entry.uses == 0
        } else {
            panic!("No entry for id {id}");
        };

        if remove {
            let old_entry = self.batches.remove(&id).unwrap();
            self.batches_size = self
                .batches_size
                .checked_sub(self.batch_memory.uncount_batch(&old_entry.batch))
                .unwrap();

            self.total_rows = self
                .total_rows
                .checked_sub(old_entry.batch.num_rows())
                .unwrap();
        }
    }

    /// returns the size of memory used by this store, including all
    /// referenced `RecordBatch`es, in bytes
    pub fn size(&self) -> usize {
        size_of::<Self>()
            + self.batches.capacity() * (size_of::<u32>() + size_of::<RecordBatchEntry>())
            + self.batches_size
    }

    /// Rewrite the store to hold only the rows `partitions` still reference,
    /// once it holds [`STORE_COMPACTION_RATIO`]× more than the `live_slots` of
    /// them, and repoint every partition at the rows' new places.
    /// [`PartitionedTopK`] and [`PartitionedTopKRank`] call this at the end of
    /// every `insert_batch`.
    ///
    /// An entry holds every row *admitted* from its input batch and is freed
    /// only when the last of them is evicted, so when survivors spread thinly
    /// one live row keeps a whole entry resident and residency tracks the
    /// *input*, not `partitions × K`: 512 partitions of `K = 1` fed 512 batches
    /// pin 131 K rows to retain 512. Nothing else bounds that. A single entry is
    /// no exception — rows admitted then superseded within their own batch stay
    /// in the gather unreferenced — so this does not skip a one-entry store.
    /// `RANK` ties add a second way to leave rows unreferenced, since a
    /// boundary move releases every tie of the partition at once.
    ///
    /// Amortized O(1) per admitted row: one pass over the live slots, and it
    /// cannot recur until the store has taken on another `live_slots` rows.
    ///
    /// Rows are rewritten into `batch_size` chunks, not one batch: an entry is
    /// released only when its last slot is evicted, so a single batch of every
    /// live row would free nothing until every partition has churned.
    ///
    /// Peak residency is the old store plus the new one — chunks are built
    /// before the old entries drop, and the reservation is not resized until
    /// `insert_batch` returns — so a pool sized at the steady-state bound can be
    /// exceeded transiently without erroring.
    ///
    /// All-or-nothing: plan the move and interleave, which is the only fallible
    /// step, before rewriting the slots and the store. A failing interleave
    /// leaves the operator as it was rather than holding slots pointing at ids
    /// the store never got.
    fn compact<P: StoreSlots>(
        &mut self,
        partitions: &mut HashMap<Vec<u8>, P>,
        live_slots: usize,
        batch_size: usize,
    ) -> Result<()> {
        if self.total_rows <= live_slots * STORE_COMPACTION_RATIO {
            return Ok(());
        }

        // Scoped so the borrows of the old batches end before the store is
        // rewritten.
        let first_id = self.next_batch_id();
        // The slot's old place in walk order, so debug builds can check the
        // repoint walk below visits the slots in the same order.
        #[cfg(debug_assertions)]
        let mut walked: Vec<StoreRef> = Vec::with_capacity(live_slots);
        let chunks = {
            let (old, array_pos) = self.positional();

            // The `n`th slot this walk visits moves to the `n`th row of the
            // compacted store. The repoint walk below finds each slot's new
            // place by counting, which holds because an unmodified map yields
            // `values()` and `values_mut()` in the same order, and
            // `StoreSlots` requires `store_rows` and `repoint` to agree.
            let mut coords: Vec<(usize, usize)> = Vec::with_capacity(live_slots);
            for at in partitions.values().flat_map(P::store_rows) {
                let pos = *array_pos
                    .get(&at.batch_id)
                    .expect("a live slot's batch_id is present in the store");
                coords.push((pos, at.row as usize));
                #[cfg(debug_assertions)]
                walked.push(at);
            }
            debug_assert_eq!(
                coords.len(),
                live_slots,
                "live_slots must count exactly the slots that reference the store"
            );
            #[cfg(debug_assertions)]
            debug_assert_eq!(
                walked
                    .iter()
                    .collect::<std::collections::HashSet<_>>()
                    .len(),
                walked.len(),
                "two slots must not share a store row"
            );

            let mut chunks: Vec<(RecordBatch, usize)> =
                Vec::with_capacity(coords.len().div_ceil(batch_size));
            let mut remap = vec![usize::MAX; old.len()];
            for chunk in coords.chunks(batch_size) {
                chunks
                    .push((interleave_referenced(&old, chunk, &mut remap)?, chunk.len()));
            }
            chunks
        };

        let mut moved_to = 0usize;
        for partition in partitions.values_mut() {
            partition.repoint(|at| {
                #[cfg(debug_assertions)]
                assert_eq!(
                    walked[moved_to], at,
                    "store_rows and repoint must visit slots in the same order"
                );
                #[cfg(not(debug_assertions))]
                let _ = at;
                let new_place = StoreRef {
                    batch_id: first_id + (moved_to / batch_size) as u32,
                    row: (moved_to % batch_size) as u32,
                };
                moved_to += 1;
                new_place
            });
        }
        debug_assert_eq!(moved_to, live_slots, "repoint must visit every slot");
        self.clear();
        for (chunk_idx, (batch, uses)) in chunks.into_iter().enumerate() {
            let mut entry = self.register(batch);
            debug_assert_eq!(
                entry.id,
                first_id + chunk_idx as u32,
                "the ids handed to the slots must be the ids the chunks got"
            );
            entry.uses = uses;
            self.insert(entry);
        }
        Ok(())
    }
}

/// `interleave_record_batch` over only the `batches` that `indices`
/// references.
///
/// The kernel does per-input work for every batch it is handed — for a
/// dictionary column, a scan of all of `indices` per input — so handing it
/// the whole store would make every chunk's cost grow with the store. When a
/// chunk touches a few of many stored batches, as when input arrives
/// clustered by partition key, that is the difference between linear and
/// quadratic in the input.
///
/// `remap` is scratch with one entry per batch, all `usize::MAX` on entry;
/// only the entries this chunk set are reset, so a chunk costs
/// `O(indices.len())` however many batches the store holds.
fn interleave_referenced<B: Borrow<RecordBatch>>(
    batches: &[B],
    indices: &[(usize, usize)],
    remap: &mut [usize],
) -> Result<RecordBatch> {
    debug_assert_eq!(remap.len(), batches.len());
    let mut used: Vec<usize> = Vec::new();
    let local: Vec<(usize, usize)> = indices
        .iter()
        .map(|&(pos, row)| {
            if remap[pos] == usize::MAX {
                remap[pos] = used.len();
                used.push(pos);
            }
            (remap[pos], row)
        })
        .collect();
    let refs: Vec<&RecordBatch> = used.iter().map(|&pos| batches[pos].borrow()).collect();
    let batch = interleave_record_batch(&refs, &local);
    for pos in used {
        remap[pos] = usize::MAX;
    }
    Ok(batch?)
}

/// A partition's retained rows as [`RecordBatchStore`] coordinates: what
/// [`RecordBatchStore::compact`] reads to plan the move, and rewrites after it.
///
/// `repoint` must visit the slots in the order `store_rows` yields them:
/// `compact` assigns new places by position in that walk rather than looking
/// each slot up. Debug builds check this.
trait StoreSlots {
    /// Where every retained row lives.
    fn store_rows(&self) -> impl Iterator<Item = StoreRef> + '_;

    /// Rewrite where every retained row lives through `moved_to`, called once
    /// per slot in [`Self::store_rows`] order.
    fn repoint(&mut self, moved_to: impl FnMut(StoreRef) -> StoreRef);
}

/// The store entry a partitioned operator's `insert_batch` is filling, from
/// [`RecordBatchStore::pending`] to [`RecordBatchStore::insert_rows`].
///
/// Like a [`RecordBatchEntry`] whose batch does not exist yet: the rows to
/// gather are known only once the admission pass is over, but slots point at
/// `id` during it, and `uses` counts those still doing so.
#[derive(Debug)]
struct PendingEntry {
    id: u32,
    uses: usize,
}

/// Store coordinates of one retained row: row `row` of the shared
/// [`RecordBatchStore`] batch `batch_id`.
///
/// What a [`PartitionSlot`] holds besides its key, on its own. Rows tied at a
/// `RANK` boundary all share the boundary's key, so they need nothing more.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct StoreRef {
    batch_id: u32,
    row: u32,
}

/// One retained row: its sort key by value, its output columns by reference.
///
/// `key` is the row-encoded ORDER BY tuple, owned inline. It is
/// byte-comparable, so `Ord` on the bytes is the sort order — the heap compares
/// rows without dereferencing anything, and eviction needs no access to the
/// payload at all.
///
/// `at` locates the output columns in the operator's shared
/// [`RecordBatchStore`], which refcounts each batch by the slots pointing into
/// it. A slot's existence is what keeps its batch alive.
#[derive(Debug)]
struct PartitionSlot {
    key: Vec<u8>,
    at: StoreRef,
}

impl PartialEq for PartitionSlot {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}
impl Eq for PartitionSlot {}
impl PartialOrd for PartitionSlot {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for PartitionSlot {
    fn cmp(&self, other: &Self) -> Ordering {
        self.key.cmp(&other.key)
    }
}

/// A single partition's top-K.
///
/// A max-heap on `key`, so the root is the *worst* retained row and a new row
/// only has to beat that one. Replacement mutates the root in place (reusing its
/// `Vec` capacity) and lets `PeekMut` sift down on drop — so a steady-state
/// eviction performs no allocation and no teardown.
///
/// There is one of these per *distinct partition key*, so every field is
/// multiplied by the partition count. Hence it is nothing but the heap, 24
/// bytes: the batches live in the operator's one shared [`RecordBatchStore`],
/// and `k` is a single constant for the whole operator, so it is passed to the
/// methods that need it rather than stored per partition.
#[derive(Debug, Default)]
struct PartitionHeap {
    inner: BinaryHeap<PartitionSlot>,
}

impl PartitionHeap {
    /// True if `key` belongs in the top-`k`: the heap is not yet full, or
    /// `key` beats the worst retained row.
    fn qualifies(&self, k: usize, key: &[u8]) -> bool {
        matches!(self.classify(k, key), None | Some(Ordering::Less))
    }

    /// How `key` compares with the worst retained row, or `None` while the
    /// heap holds fewer than `k` rows and so admits anything.
    ///
    /// The worst retained row is the root, so this is one comparison. `RANK`
    /// needs all three outcomes, since `Equal` is a tie at the boundary;
    /// `ROW_NUMBER` only needs [`Self::qualifies`].
    fn classify(&self, k: usize, key: &[u8]) -> Option<Ordering> {
        if self.inner.len() < k {
            return None;
        }
        self.inner.peek().map(|worst| key.cmp(worst.key.as_slice()))
    }

    /// The worst retained row's key — the admission boundary once the heap is
    /// full.
    fn worst_key(&self) -> Option<&[u8]> {
        self.inner.peek().map(|worst| worst.key.as_slice())
    }

    /// Retain `key`, with its output columns at `at` in the store, evicting
    /// the worst retained row if the heap is already full.
    ///
    /// Returns where the evicted row lives, which the caller owes the store an
    /// `unuse` for — this type does not touch the store itself, because the
    /// in-flight batch is not registered yet and only the caller knows that —
    /// along with the bytes this call newly allocated, which the operator
    /// folds into its running total. Returning the delta rather than keeping a
    /// running sum per heap is what lets this type hold nothing but the heap.
    /// `RANK` evicts through [`Self::replace_worst`] instead, since it needs
    /// the evicted key back.
    fn add(&mut self, k: usize, key: &[u8], at: StoreRef) -> (Option<StoreRef>, usize) {
        debug_assert!(self.inner.len() <= k);
        if self.inner.len() == k {
            let mut worst = self.inner.peek_mut().expect("heap is full");
            let before = worst.key.capacity();
            worst.key.clear();
            worst.key.extend_from_slice(key);
            let grown = worst.key.capacity() - before;
            let evicted = std::mem::replace(&mut worst.at, at);
            drop(worst);
            (Some(evicted), grown)
        } else {
            let slot = PartitionSlot {
                key: key.to_vec(),
                at,
            };
            let key_bytes = slot.key.capacity();
            let inner_before = self.inner.capacity();
            self.inner.push(slot);
            let grown = key_bytes
                + (self.inner.capacity() - inner_before) * size_of::<PartitionSlot>();
            (None, grown)
        }
    }

    /// [`Self::add`] on a full heap that hands the evicted key back in
    /// `evicted_key` rather than overwriting it: `key` is written into
    /// `evicted_key`'s buffer and the two buffers swap, one copy instead of
    /// two. Returns where the evicted row lives and the bytes `evicted_key`
    /// grew by — the buffers only trade places, so their combined capacity
    /// changes by exactly that.
    fn replace_worst(
        &mut self,
        key: &[u8],
        at: StoreRef,
        evicted_key: &mut Vec<u8>,
    ) -> (StoreRef, usize) {
        let before = evicted_key.capacity();
        evicted_key.clear();
        evicted_key.extend_from_slice(key);
        let grown = evicted_key.capacity() - before;
        let mut worst = self.inner.peek_mut().expect("heap is full");
        std::mem::swap(&mut worst.key, evicted_key);
        let evicted = std::mem::replace(&mut worst.at, at);
        drop(worst);
        (evicted, grown)
    }

    /// The retained slots, in unspecified order.
    fn slots(&self) -> impl Iterator<Item = &PartitionSlot> + '_ {
        self.inner.iter()
    }

    /// Retained rows in ascending ORDER BY order, leaving this heap empty.
    fn drain_sorted(&mut self) -> Vec<PartitionSlot> {
        std::mem::take(&mut self.inner).into_sorted_vec()
    }
}

impl StoreSlots for PartitionHeap {
    fn store_rows(&self) -> impl Iterator<Item = StoreRef> + '_ {
        self.slots().map(|slot| slot.at)
    }

    /// Leaves the keys — and so the heap order — untouched. `into_vec` hands
    /// back the heap's own allocation and `BinaryHeap::from` takes it again,
    /// so this allocates nothing.
    fn repoint(&mut self, mut moved_to: impl FnMut(StoreRef) -> StoreRef) {
        let mut slots = std::mem::take(&mut self.inner).into_vec();
        for slot in &mut slots {
            slot.at = moved_to(slot.at);
        }
        self.inner = BinaryHeap::from(slots);
    }
}

/// Output schema of `PartitionedTopKExec`: its input's columns, plus
/// `ranking_field` when the operator emits the ranking column itself.
///
/// Built once, by the exec, and handed to each partition's state as is, so the
/// batches a state emits and the schema the exec declares are the same
/// `SchemaRef` rather than two schemas that happen to agree.
pub(crate) fn partitioned_topk_output_schema(
    input_schema: &SchemaRef,
    ranking_field: Option<&FieldRef>,
) -> SchemaRef {
    let Some(field) = ranking_field else {
        return Arc::clone(input_schema);
    };
    let mut fields = input_schema.fields().to_vec();
    fields.push(Arc::clone(field));
    Arc::new(Schema::new_with_metadata(
        fields,
        input_schema.metadata().clone(),
    ))
}

/// What [`PartitionedTopK`] and [`PartitionedTopKRank`] share: the two
/// [`RowConverter`]s — one for the partition key, one for the ORDER BY key —
/// and their scratch [`Rows`], the [`MemoryReservation`], [`TopKMetrics`], one
/// per-partition state `S` per distinct partition key, and the
/// [`RecordBatchStore`] holding every retained row.
///
/// Both operators run the same three phases per batch: encode both column
/// sets once ([`Self::encode`]), one admission pass over the rows, then one
/// gather into the store ([`Self::finish_batch`]). Only the admission pass —
/// the retention rule — differs, so each operator writes its own row loop over
/// these fields between the two calls.
struct PartitionedTopKCore<S> {
    /// The schema `emit` produces: the input's columns, plus the ranking
    /// column when [`Self::emit_ranks`] is set.
    output_schema: SchemaRef,
    /// When set, `emit` appends a column holding each retained row's ranking
    /// value, as computed by the operator's drain in [`Self::emit_with`]. That
    /// lets the rewrite drop the `BoundedWindowAggExec` that would otherwise
    /// re-derive the same values over this operator's output.
    emit_ranks: bool,
    metrics: TopKMetrics,
    reservation: MemoryReservation,
    /// ORDER BY expressions (excludes PARTITION BY).
    expr: LexOrdering,
    /// Encoder for the ORDER BY columns, whose encoding is the heap key.
    row_converter: RowConverter,
    /// Scratch row buffer for the ORDER BY encoding, reused across
    /// `insert_batch` calls.
    scratch_rows: Rows,
    /// PARTITION BY expressions.
    partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
    /// Encoder for the partition key. The encoding is byte-comparable with
    /// ASC/DESC and NULLS FIRST/LAST folded in, so the encoded bytes sort
    /// identically to the partition ordering — which is what lets `emit`
    /// recover partition-key order by sorting the keys directly.
    partition_converter: RowConverter,
    /// Scratch row buffer for partition-key encoding. Reused across
    /// `insert_batch` calls (cleared + appended each batch).
    partition_scratch_rows: Rows,
    /// One state per distinct partition key seen so far, keyed by the
    /// row-encoded PARTITION BY key.
    ///
    /// `entry_ref` owns the key only on Vacant, so a key is allocated once per
    /// partition for the lifetime of the operator — not once per row, and not
    /// once per partition per batch (which is what draining a per-batch map
    /// would cost). Map order is arbitrary, so `emit` sorts the keys itself.
    partitions: HashMap<Vec<u8>, S>,
    /// The batches holding every retained row's output columns, refcounted by
    /// the slots pointing into them.
    ///
    /// One store for the whole operator rather than one per partition, which is
    /// what [`TopKHeap`] would give. Each entry holds only the rows that were
    /// admitted from one input batch — see [`Self::finish_batch`] — and is
    /// dropped as soon as the last slot referencing it is released. When that
    /// alone leaves it holding far more than the partitions point at,
    /// `RecordBatchStore::compact` rewrites it.
    store: RecordBatchStore,
    /// Rows of the batch currently being inserted that were admitted, in
    /// ascending row order. Reused across `insert_batch` calls.
    admitted_rows: Vec<u32>,
    /// Rows the partitions currently hold, i.e. slots pointing into `store`.
    ///
    /// Tracked incrementally for the same reason as `heaps_bytes`: it is the
    /// denominator of `RecordBatchStore::compact`'s ratio, read on every
    /// batch, and summing over the partitions would be O(partitions seen so
    /// far). For `ROW_NUMBER` slots are replaced rather than removed, so it
    /// only grows and settles at `partitions × K`; for `RANK` it also shrinks,
    /// when a boundary move releases a partition's ties.
    live_slots: usize,
    /// Running sum of the bytes every [`PartitionHeap`] has allocated: each
    /// slot's key and the `BinaryHeap`'s own buffer (for `RANK`, also
    /// `evicted_key`'s buffer, which swaps with heap keys).
    ///
    /// Maintained incrementally because `size()` runs on every batch: summing
    /// over the heaps would make it O(partitions seen so far) per batch, which
    /// is quadratic in the input whenever partition count grows with it. Every
    /// allocation it tracks only grows, so a running total stays exact without a
    /// decrement path. `PartitionHeap::add` returns each call's delta rather
    /// than keeping its own running sum, so the heaps stay free of a field that
    /// would be multiplied by the partition count.
    heaps_bytes: usize,
    /// Running sum of the partition keys `partitions` has interned, one per
    /// distinct key for the operator's lifetime.
    ///
    /// Counted by length rather than capacity: `entry_ref` builds the owned key
    /// with `to_vec`, so the two are equal. Separate from [`Self::heaps_bytes`]
    /// because it is the map's allocation, not any one heap's.
    index_bytes: usize,
    k: usize,
    batch_size: usize,
}

impl<S: StoreSlots> PartitionedTopKCore<S> {
    /// `name` labels the memory consumer, as `name[partition_id]`.
    /// `ranked_schema` is the exec's output schema when it emits the ranking
    /// column, which makes `emit` append it, and `None` to emit `schema` as is.
    #[expect(clippy::too_many_arguments)]
    fn try_new(
        name: &str,
        partition_id: usize,
        schema: &SchemaRef,
        partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
        partition_sort_fields: Vec<SortField>,
        order_expr: LexOrdering,
        k: usize,
        batch_size: usize,
        runtime: &Arc<RuntimeEnv>,
        metrics: &ExecutionPlanMetricsSet,
        ranked_schema: Option<SchemaRef>,
    ) -> Result<Self> {
        assert!(k > 0, "{name} requires k > 0");
        let reservation = MemoryConsumer::new(format!("{name}[{partition_id}]"))
            .register(&runtime.memory_pool);

        // Both encoders are shared by every partition, and each scratch buffer
        // is sized to hold a whole batch so an `insert_batch` pass encodes once
        // per column set with no regrowth.
        let order_sort_fields = build_sort_fields(&order_expr, schema)?;
        let row_converter = RowConverter::new(order_sort_fields)?;
        let scratch_rows =
            row_converter.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);

        let partition_converter = RowConverter::new(partition_sort_fields)?;
        let partition_scratch_rows = partition_converter
            .empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);

        Ok(Self {
            emit_ranks: ranked_schema.is_some(),
            output_schema: ranked_schema.unwrap_or_else(|| Arc::clone(schema)),
            metrics: TopKMetrics::new(metrics, partition_id),
            reservation,
            expr: order_expr,
            row_converter,
            scratch_rows,
            partition_exprs,
            partition_converter,
            partition_scratch_rows,
            partitions: HashMap::new(),
            store: RecordBatchStore::new(),
            admitted_rows: Vec::new(),
            live_slots: 0,
            heaps_bytes: 0,
            index_bytes: 0,
            k,
            batch_size,
        })
    }

    /// Phase 1: evaluate the partition and ORDER BY columns of a non-empty
    /// `batch` and encode each once for the whole batch into the scratch
    /// buffers. Both encodes are whole-batch kernels that do not care how the
    /// rows group, which is what lets the admission pass be a single row loop.
    fn encode(&mut self, batch: &RecordBatch) -> Result<()> {
        let num_rows = batch.num_rows();
        let pk_arrays: Vec<ArrayRef> = self
            .partition_exprs
            .iter()
            .map(|e| e.evaluate(batch).and_then(|v| v.into_array(num_rows)))
            .collect::<Result<_>>()?;
        self.partition_scratch_rows.clear();
        self.partition_converter
            .append(&mut self.partition_scratch_rows, &pk_arrays)?;

        let ob_arrays: Vec<ArrayRef> = self
            .expr
            .iter()
            .map(|e| e.expr.evaluate(batch).and_then(|v| v.into_array(num_rows)))
            .collect::<Result<_>>()?;
        self.scratch_rows.clear();
        self.row_converter
            .append(&mut self.scratch_rows, &ob_arrays)?;
        Ok(())
    }

    /// Phase 3: gather the rows this batch contributed into a single batch and
    /// hand it to the store, then compact the store if it needs it. Only rows
    /// admitted at some point during the pass are kept, so what stays pinned is
    /// bounded by admissions rather than by input size — and the entry is
    /// freed as soon as the last slot referencing it is released.
    ///
    /// No uses left on `pending` means every admission from this batch was
    /// released again before the pass ended, so there is nothing to keep and
    /// the id goes back to the next batch.
    ///
    /// The caller resizes the reservation afterwards, since only it knows its
    /// full size.
    fn finish_batch(
        &mut self,
        batch: &RecordBatch,
        pending: PendingEntry,
        replacements: usize,
    ) -> Result<()> {
        self.store
            .insert_rows(batch, &self.admitted_rows, pending)?;
        if replacements > 0 {
            self.metrics.row_replacements.add(replacements);
        }
        self.store
            .compact(&mut self.partitions, self.live_slots, self.batch_size)
    }

    /// Drain every partition in partition-key order, each through `drain` into
    /// its retained rows in output order, and return them as a stream of
    /// `RecordBatch`es ordered by `(partition_keys, order_keys)`.
    ///
    /// `drain` pairs each row with its ranking value, which is what the
    /// operator emits when [`Self::emit_ranks`] is set and is ignored
    /// otherwise.
    ///
    /// Only the order is resolved here; [`EmitState::stream`] interleaves the
    /// rows out one `batch_size` chunk per poll, carrying the reservation until
    /// the stream is dropped since the store's batches stay pinned until then.
    fn emit_with<I: IntoIterator<Item = (StoreRef, u64)>>(
        self,
        drain: impl FnMut(S) -> I,
    ) -> Result<SendableRecordBatchStream> {
        let Self {
            output_schema,
            emit_ranks,
            metrics,
            reservation,
            partitions,
            store,
            live_slots,
            batch_size,
            ..
        } = self;

        // Map order is arbitrary, so partition-key order has to be recovered
        // explicitly here.
        let timer = metrics.baseline.elapsed_compute().timer();
        let mut sorted: Vec<(Vec<u8>, S)> = partitions.into_iter().collect();
        sorted.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
        drop(timer);

        let slots = sorted
            .into_iter()
            .map(|(_key, state)| state)
            .flat_map(drain);
        EmitState::stream(
            output_schema,
            emit_ranks,
            metrics,
            reservation,
            batch_size,
            &store,
            slots,
            live_slots,
        )
    }

    /// The bytes these shared fields hold on the heap, beyond the operator
    /// struct itself: encoders, scratch buffers, the partition map and its
    /// keys, every heap, and every batch the store still pins.
    ///
    /// Every term is O(1): this runs on every batch, so the per-partition
    /// contributions are the running totals `heaps_bytes` and `index_bytes`
    /// rather than a sum over partitions.
    fn allocated_size(&self) -> usize {
        self.row_converter.size()
            + self.partition_converter.size()
            + self.scratch_rows.size()
            + self.partition_scratch_rows.size()
            + self.admitted_rows.allocated_size()
            + self.partitions.capacity() * (size_of::<Vec<u8>>() + size_of::<S>())
            + self.heaps_bytes
            + self.index_bytes
            + self.store.size()
    }
}

/// Top-K-per-partition operator state.
///
/// Sibling to [`TopK`]. Where `TopK` maintains a single global heap,
/// `PartitionedTopK` maintains one [`PartitionHeap`] per distinct partition
/// key while sharing everything else in [`PartitionedTopKCore`] across all
/// partitions.
///
/// This sharing is the point of the type: with N distinct partition
/// keys, a naive `HashMap<_, TopK>` pays N × constant overhead for
/// `RowConverter::new`, `MemoryConsumer::register`, `RecordBatchStore::new`,
/// and metric counter setup. `PartitionedTopK` pays it once.
pub(crate) struct PartitionedTopK {
    core: PartitionedTopKCore<PartitionHeap>,
}

impl PartitionedTopK {
    #[expect(clippy::too_many_arguments)]
    pub(crate) fn try_new(
        partition_id: usize,
        schema: &SchemaRef,
        partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
        partition_sort_fields: Vec<SortField>,
        order_expr: LexOrdering,
        k: usize,
        batch_size: usize,
        runtime: &Arc<RuntimeEnv>,
        metrics: &ExecutionPlanMetricsSet,
        ranked_schema: Option<SchemaRef>,
    ) -> Result<Self> {
        Ok(Self {
            core: PartitionedTopKCore::try_new(
                "PartitionedTopK",
                partition_id,
                schema,
                partition_exprs,
                partition_sort_fields,
                order_expr,
                k,
                batch_size,
                runtime,
                metrics,
                ranked_schema,
            )?,
        })
    }

    /// Encode the partition and ORDER BY columns once each for the whole batch,
    /// admit every qualifying row into the [`PartitionHeap`] of the partition it
    /// belongs to, then register the admitted rows in the shared store.
    pub(crate) fn insert_batch(&mut self, batch: &RecordBatch) -> Result<()> {
        let elapsed_compute = self.core.metrics.baseline.elapsed_compute().clone();
        let _timer = elapsed_compute.timer();

        let num_rows = batch.num_rows();
        if num_rows == 0 {
            return Ok(());
        }

        // 1. Encode both column sets once for the whole batch.
        self.core.encode(batch)?;

        // 2. One pass over the rows: find the row's partition and admit it to
        //    that partition's heap if it qualifies. Only the key is copied
        //    here; an admission records which row it kept and phase 3 gathers
        //    them all in one `take`, so a batch is materialized once no matter
        //    how many partitions it touched.
        //
        //    Rows are visited in batch order rather than grouped by partition.
        //    Interleaving groups cannot change a decision — a heap is only
        //    read and written by rows of its own partition, which still reach
        //    it in ascending row order — and it costs no pass over the
        //    partitions seen so far, which would be quadratic in the input
        //    whenever partition count grows with it.
        let core = &mut self.core;
        let k = core.k;
        let mut replacements: usize = 0;
        core.admitted_rows.clear();
        // The gathered batch does not exist yet, but its id does, so a slot can
        // point at it during the pass with no back-patching afterwards.
        let mut pending = core.store.pending();
        {
            let pk_rows = &core.partition_scratch_rows;
            let ob_rows = &core.scratch_rows;
            let heaps = &mut core.partitions;
            let admitted_rows = &mut core.admitted_rows;
            let store = &mut core.store;
            // Accumulated locally and folded in once, so the running totals are
            // not touched per row.
            let mut interned_bytes = 0usize;
            let mut admitted_bytes = 0usize;
            let mut new_slots = 0usize;

            for row in 0..num_rows {
                let pk = pk_rows.row(row);
                // One probe per row, and `entry_ref` owns the key only on
                // Vacant, so a key is allocated once per partition for the
                // operator's lifetime — not once per row.
                let mut interned = false;
                let heap = heaps.entry_ref(pk.as_ref()).or_insert_with(|| {
                    interned = true;
                    PartitionHeap::default()
                });
                if interned {
                    // The map has just taken the only copy of this key.
                    interned_bytes += pk.as_ref().len();
                }
                let key = ob_rows.row(row);
                if !heap.qualifies(k, key.as_ref()) {
                    continue;
                }
                // An admission's row in the gathered batch is its position in
                // `admitted_rows`, because the gather preserves that order.
                let at = StoreRef {
                    batch_id: pending.id,
                    row: admitted_rows.len() as u32,
                };
                pending.uses += 1;
                let (evicted, grown) = heap.add(k, key.as_ref(), at);
                admitted_bytes += grown;
                match evicted {
                    Some(evicted) => store.release(&mut pending, evicted.batch_id),
                    // The heap was not yet full, so this slot is a new
                    // reference into the store rather than a replaced one.
                    None => new_slots += 1,
                }
                admitted_rows.push(row as u32);
                replacements += 1;
            }

            core.index_bytes += interned_bytes;
            core.heaps_bytes += admitted_bytes;
            core.live_slots += new_slots;
        }

        // 3. Gather this batch's admissions into the store, then compact it.
        core.finish_batch(batch, pending, replacements)?;
        self.core.reservation.try_resize(self.size())?;
        Ok(())
    }

    /// Drain all heaps in partition-key order and return the rows as
    /// a stream of `RecordBatch`es ordered by
    /// `(partition_keys, order_keys)`.
    ///
    /// Retained rows live in the shared store as `(batch_id, row)` references,
    /// so this resolves them to `(array_pos, row)` pairs and interleaves them
    /// out in `batch_size` chunks. Because the chunking happens here the output
    /// batches are already the right size and no coalescing pass is needed.
    ///
    /// Only the ordering is done eagerly; the interleave happens one chunk per
    /// poll, which keeps `P × K` rows' worth of *output* arrays from existing at
    /// once. The store's batches stay pinned for the whole stream either way, so
    /// the reservation is carried into [`EmitState`] and released when the stream
    /// is dropped rather than when this returns.
    pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
        // Each heap drains its partition's rows in ORDER BY order, low to
        // high, so a row's `ROW_NUMBER()` is just its 1-based position in that
        // drain.
        self.core.emit_with(|mut heap| {
            heap.drain_sorted()
                .into_iter()
                .zip(1u64..)
                .map(|(slot, row_number)| (slot.at, row_number))
        })
    }

    /// Total memory currently held by this operator, including all
    /// per-partition heaps and every batch the store still pins. O(1), see
    /// [`PartitionedTopKCore::allocated_size`].
    fn size(&self) -> usize {
        size_of::<Self>() + self.core.allocated_size()
    }
}

/// Hands out `batch_size` rows at a time, interleaved out of the store batches
/// the heaps referenced.
struct EmitState {
    /// The input's columns, plus the ranking column when `ranks` is set.
    output_schema: SchemaRef,
    metrics: TopKMetrics,
    /// Covers the pinned batches, `ordered` and `ranks` for as long as they
    /// are held.
    ///
    /// Carried here rather than dropped at the end of `emit` so the bytes stay
    /// accounted for until the stream is, and released by this struct's drop.
    /// Never resized: the store's batches are pinned until the last chunk, so
    /// there is nothing to hand back as chunks are emitted. Underscored because
    /// it is held only for that drop, as in `HashJoinStream` and `AsofJoinStream`.
    _reservation: MemoryReservation,
    batch_size: usize,
    /// The store's batches, positionally indexed by `ordered`.
    batches: Vec<RecordBatch>,
    /// `(array_pos, row)` pairs in `(partition_keys, order_keys)` order.
    ordered: Vec<(usize, usize)>,
    /// Each `ordered` row's ranking value, when the operator emits it.
    ranks: Option<Vec<u64>>,
    /// Scratch for [`interleave_referenced`], one entry per batch.
    remap: Vec<usize>,
    pos: usize,
}

impl EmitState {
    /// Resolve `slots`, `len` of them in output order, against `store`, and
    /// return the stream that emits them. Shared by [`PartitionedTopK::emit`]
    /// and [`PartitionedTopKRank::emit`], which differ only in that order and
    /// in how they derive each row's ranking value, which is kept only when
    /// `emit_ranks` is set.
    #[expect(clippy::too_many_arguments)]
    fn stream(
        output_schema: SchemaRef,
        emit_ranks: bool,
        metrics: TopKMetrics,
        reservation: MemoryReservation,
        batch_size: usize,
        store: &RecordBatchStore,
        slots: impl Iterator<Item = (StoreRef, u64)>,
        len: usize,
    ) -> Result<SendableRecordBatchStream> {
        let timer = metrics.baseline.elapsed_compute().timer();
        // Cloned, an `Arc` bump per column, because the batches outlive the
        // store, which the caller drops as `emit` returns.
        let (batches, batch_id_array_pos) = store.positional();
        let batches: Vec<RecordBatch> = batches.into_iter().cloned().collect();

        // Flattened in output order, so the emit itself is a slice walk.
        let mut ordered: Vec<(usize, usize)> = Vec::with_capacity(len);
        // Parallel to `ordered`.
        let mut ranks: Option<Vec<u64>> = emit_ranks.then(|| Vec::with_capacity(len));
        for (slot, rank) in slots {
            let array_pos = *batch_id_array_pos
                .get(&slot.batch_id)
                .expect("a retained slot's batch_id is present in the store");
            ordered.push((array_pos, slot.row as usize));
            if let Some(ranks) = &mut ranks {
                ranks.push(rank);
            }
        }
        drop(timer);

        // What survives this function is the store's batches — pinned until the
        // returned stream is dropped — plus `ordered`, one 16-byte pair per
        // retained row, `ranks`, 8 more bytes per row when the ranking column
        // is emitted, and `remap`, one entry per batch. Everything else the
        // operator held (its scratch buffers, every partition and its interned
        // key) is freed by now, so the resize below is normally a shrink. The
        // reservation moves into the stream state rather than being dropped
        // here: releasing it while the store is still pinned would stop
        // accounting for bytes that are still held, which is the one direction
        // that matters.
        reservation.try_resize(
            size_of::<EmitState>()
                + store.batches_size
                + batches.capacity() * size_of::<RecordBatch>()
                + ordered.capacity() * size_of::<(usize, usize)>()
                + ranks
                    .as_ref()
                    .map_or(0, |r| r.capacity() * size_of::<u64>())
                + batches.len() * size_of::<usize>(),
        )?;

        let state = EmitState {
            output_schema: Arc::clone(&output_schema),
            metrics,
            _reservation: reservation,
            batch_size,
            remap: vec![usize::MAX; batches.len()],
            batches,
            ordered,
            ranks,
            pos: 0,
        };

        Ok(Box::pin(RecordBatchStreamAdapter::new(
            output_schema,
            futures::stream::try_unfold(state, |mut state| async move {
                Ok(state.next_batch()?.map(|batch| (batch, state)))
            }),
        )))
    }

    /// Build the next chunk, or `None` once every retained row has been
    /// emitted.
    fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
        if self.pos == self.ordered.len() {
            return Ok(None);
        }
        let _timer = self.metrics.baseline.elapsed_compute().timer();

        let start = self.pos;
        let end = (start + self.batch_size).min(self.ordered.len());
        self.pos = end;

        let batch = interleave_referenced(
            &self.batches,
            &self.ordered[start..end],
            &mut self.remap,
        )?;
        let ranks = self.ranks.as_ref().map(|r| r[start..end].iter().copied());
        finish_chunk(batch, ranks, &self.output_schema, &self.metrics).map(Some)
    }
}

/// Finish one output chunk: append `ranks` as its last column under
/// `output_schema` when the operator emits the ranking column, then count the
/// chunk in `output_rows`.
///
/// Each of the three retention policies derives the values differently —
/// see [`PartitionedTopK::emit`], [`PartitionedTopKRank::emit`], and
/// [`PartitionedTopKDenseRank::emit`] — but all three know them by the time
/// they build an output batch, which is what makes the
/// `BoundedWindowAggExec` above the operator removable. `RecordBatch::try_new`
/// rejects a `ranks` whose length differs from the chunk's.
fn finish_chunk(
    batch: RecordBatch,
    ranks: Option<impl IntoIterator<Item = u64>>,
    output_schema: &SchemaRef,
    metrics: &TopKMetrics,
) -> Result<RecordBatch> {
    let batch = match ranks {
        None => batch,
        Some(ranks) => {
            let mut columns = batch.columns().to_vec();
            columns.push(Arc::new(UInt64Array::from_iter_values(ranks)));
            RecordBatch::try_new(Arc::clone(output_schema), columns)?
        }
    };
    (&batch).record_output(&metrics.baseline);
    Ok(batch)
}

/// Per-partition state for `RANK()` semantics.
///
/// `RANK ≤ K` keeps the K best rows by ORDER BY plus every row tied at the
/// K-th-best ORDER BY value — the boundary — so a partition can retain more
/// than K rows when ties straddle it. The K best live in `heap`; the rows
/// tied with its root beyond those K live in `ties`.
///
/// Like [`PartitionHeap`], this holds only store coordinates: the output
/// columns of every retained row, heap or tie, live in the operator's one
/// shared [`RecordBatchStore`].
#[derive(Debug, Default)]
struct RankPartitionState {
    heap: PartitionHeap,
    /// Rows tied with `heap`'s root. They all share its key, so none is stored.
    /// Only ever non-empty while `heap` is full.
    ties: Vec<StoreRef>,
}

impl RankPartitionState {
    /// Add a tie at `at`, returning the bytes this newly allocated for the
    /// operator to fold into its running total, as [`PartitionHeap::add`] does.
    fn push_tie(&mut self, at: StoreRef) -> usize {
        let before = self.ties.capacity();
        self.ties.push(at);
        (self.ties.capacity() - before) * size_of::<StoreRef>()
    }
}

impl StoreSlots for RankPartitionState {
    fn store_rows(&self) -> impl Iterator<Item = StoreRef> + '_ {
        self.heap.store_rows().chain(self.ties.iter().copied())
    }

    fn repoint(&mut self, mut moved_to: impl FnMut(StoreRef) -> StoreRef) {
        self.heap.repoint(&mut moved_to);
        for tie in &mut self.ties {
            *tie = moved_to(*tie);
        }
    }
}

/// Sibling to [`PartitionedTopK`] implementing `RANK()` semantics.
///
/// Per partition, retains the K-best rows plus every row tied at the
/// K-th-best ORDER BY value (so `WHERE rk <= K` may keep more than K
/// rows when ties straddle the boundary). Shares everything in
/// [`PartitionedTopKCore`] with [`PartitionedTopK`] and admits rows the same
/// way — decide per row, then gather everything the batch contributed once —
/// with a [`RankPartitionState`] per partition in place of a bare heap.
///
/// # Algorithm (per row)
///
/// Compare the row's encoded ORDER BY bytes against the heap's root — the
/// K-th-best row, which is by definition the admission boundary. There is
/// no boundary until the heap fills to K rows:
///
/// - heap not full → admit to the heap
/// - row's ob `==` boundary → admit to ties
/// - row's ob `>` boundary → drop
/// - row's ob `<` boundary → admit to the heap, evicting the root. If the
///   new root still has the evicted row's key, the evicted row is still tied
///   at the boundary and moves to ties; otherwise the boundary moved up, the
///   old ties no longer satisfy `rk ≤ K`, and they are released along with
///   the evicted row.
pub(crate) struct PartitionedTopKRank {
    core: PartitionedTopKCore<RankPartitionState>,
    /// The key of the row an admission just evicted, so the new boundary can
    /// be compared against it. Trades buffers with the heap root on every
    /// strictly-better admission, so its capacity is counted in
    /// `core.heaps_bytes`.
    evicted_key: Vec<u8>,
    /// Running sum of every tie list's buffer. A boundary move frees the
    /// partition's buffer rather than clearing it, so a partition that once
    /// held many ties does not keep their capacity for the operator's
    /// lifetime; this shrinks with it.
    ties_bytes: usize,
}

impl PartitionedTopKRank {
    #[expect(clippy::too_many_arguments)]
    pub(crate) fn try_new(
        partition_id: usize,
        schema: &SchemaRef,
        partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
        partition_sort_fields: Vec<SortField>,
        order_expr: LexOrdering,
        k: usize,
        batch_size: usize,
        runtime: &Arc<RuntimeEnv>,
        metrics: &ExecutionPlanMetricsSet,
        ranked_schema: Option<SchemaRef>,
    ) -> Result<Self> {
        Ok(Self {
            core: PartitionedTopKCore::try_new(
                "PartitionedTopKRank",
                partition_id,
                schema,
                partition_exprs,
                partition_sort_fields,
                order_expr,
                k,
                batch_size,
                runtime,
                metrics,
                ranked_schema,
            )?,
            evicted_key: Vec::new(),
            ties_bytes: 0,
        })
    }

    /// Encode the partition and ORDER BY columns once each for the whole batch,
    /// run every row through its partition's rank classifier, then register
    /// the admitted rows in the shared store with one gather.
    pub(crate) fn insert_batch(&mut self, batch: &RecordBatch) -> Result<()> {
        let elapsed_compute = self.core.metrics.baseline.elapsed_compute().clone();
        let _timer = elapsed_compute.timer();

        let num_rows = batch.num_rows();
        if num_rows == 0 {
            return Ok(());
        }

        // 1. Encode both column sets once for the whole batch.
        self.core.encode(batch)?;

        // 2. One pass over the rows in batch order, as in
        //    `PartitionedTopK::insert_batch`: a partition's heap and ties are
        //    only touched by its own rows, which still arrive in ascending row
        //    order, so interleaving partitions cannot change a decision. An
        //    admission, to the heap or to ties, records which row it kept;
        //    phase 3 gathers them all at once.
        let core = &mut self.core;
        let k = core.k;
        let mut replacements: usize = 0;
        core.admitted_rows.clear();
        // The gathered batch's id is known before the batch exists, so slots
        // can point at it during the pass.
        let mut pending = core.store.pending();
        {
            let pk_rows = &core.partition_scratch_rows;
            let ob_rows = &core.scratch_rows;
            let states = &mut core.partitions;
            let admitted_rows = &mut core.admitted_rows;
            let store = &mut core.store;
            let evicted_key = &mut self.evicted_key;
            // Accumulated locally and folded in once.
            let mut interned_bytes = 0usize;
            let mut admitted_bytes = 0usize;
            let mut ties_grown = 0usize;
            let mut ties_freed = 0usize;
            let mut new_slots = 0usize;
            let mut released_slots = 0usize;

            for row in 0..num_rows {
                let pk = pk_rows.row(row);
                let mut interned = false;
                let state = states.entry_ref(pk.as_ref()).or_insert_with(|| {
                    interned = true;
                    RankPartitionState::default()
                });
                if interned {
                    interned_bytes += pk.as_ref().len();
                }
                let key = ob_rows.row(row);
                let key = key.as_ref();
                // An admission's row in the gathered batch is its position in
                // `admitted_rows`, because the gather preserves that order.
                let at = StoreRef {
                    batch_id: pending.id,
                    row: admitted_rows.len() as u32,
                };
                match state.heap.classify(k, key) {
                    // Strictly worse than the boundary: drop the row.
                    Some(Ordering::Greater) => continue,
                    Some(Ordering::Equal) => {
                        ties_grown += state.push_tie(at);
                        new_slots += 1;
                    }

                    None => {
                        let (evicted, grown) = state.heap.add(k, key, at);
                        debug_assert!(
                            evicted.is_none(),
                            "a heap that is not full evicts nothing"
                        );
                        admitted_bytes += grown;
                        new_slots += 1;
                    }
                    Some(Ordering::Less) => {
                        // The old root's key comes back in `evicted_key`, to
                        // tell whether the boundary moved.
                        let (evicted, grown) =
                            state.heap.replace_worst(key, at, evicted_key);
                        admitted_bytes += grown;
                        if state.heap.worst_key() == Some(evicted_key.as_slice()) {
                            // Boundary unchanged: the evicted row is still
                            // tied at it. Its slot moves to the tie list, and
                            // its store use with it — no gather, no release.
                            ties_grown += state.push_tie(evicted);
                            new_slots += 1;
                        } else {
                            // Boundary moved up: the evicted row and every tie
                            // (from this batch or earlier ones) now rank
                            // below K.
                            store.release(&mut pending, evicted.batch_id);
                            for tie in &state.ties {
                                store.release(&mut pending, tie.batch_id);
                            }
                            released_slots += state.ties.len();
                            ties_freed += state.ties.capacity() * size_of::<StoreRef>();
                            state.ties = Vec::new();
                        }
                    }
                }
                // Every arm but `Greater` admitted the row, to the heap or to
                // ties, so each counts, as every admission does in
                // `PartitionedTopK`.
                pending.uses += 1;
                admitted_rows.push(row as u32);
                replacements += 1;
            }

            core.index_bytes += interned_bytes;
            core.heaps_bytes += admitted_bytes;
            self.ties_bytes = self.ties_bytes + ties_grown - ties_freed;
            core.live_slots = core.live_slots + new_slots - released_slots;
        }

        // 3. Gather this batch's admissions into the store, then compact it.
        core.finish_batch(batch, pending, replacements)?;
        self.core.reservation.try_resize(self.size())?;
        Ok(())
    }

    /// Drain every partition in partition-key order and return the rows as a
    /// stream of `RecordBatch`es ordered by `(partition_keys, order_keys)`.
    /// Within a partition, heap rows come first (sorted by ob), then tie rows
    /// (all sharing the boundary ob).
    pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
        self.core.emit_with(|mut state| {
            let heap = state.heap.drain_sorted();
            // `RANK` is `1 + (rows with a strictly smaller ORDER BY value)`.
            // Counting positions is only valid because the retained set is a
            // *complete* order-prefix of the partition: the heap keeps the K
            // smallest keys and the ties only add rows equal to the boundary, so
            // no row with a smaller key than a retained row was ever dropped.
            //
            // The ties all sit at the boundary, the heap's largest key, so they
            // share the rank of the first heap row holding it. Ties exist only
            // while the heap is full, so a heap with no rows has none.
            let boundary_rank = heap.last().map_or(0, |worst| {
                heap.partition_point(|slot| slot.key < worst.key) as u64 + 1
            });
            // Over the sorted heap, a row either ties with its predecessor and
            // repeats its rank or starts a new one at its own 1-based position.
            let mut prev: Option<Vec<u8>> = None;
            let mut rank = 0;
            let heap = heap.into_iter().zip(1u64..).map(move |(slot, position)| {
                if prev.as_ref() != Some(&slot.key) {
                    rank = position;
                }
                prev = Some(slot.key);
                (slot.at, rank)
            });
            heap.chain(state.ties.into_iter().map(move |at| (at, boundary_rank)))
        })
    }

    /// Total memory currently held by this operator, including every
    /// partition's heap and ties and every batch the store still pins. O(1),
    /// see [`PartitionedTopKCore::allocated_size`].
    fn size(&self) -> usize {
        size_of::<Self>() + self.core.allocated_size() + self.ties_bytes
    }
}

/// A run of rows from a single source [`RecordBatch`] sharing one
/// distinct ORDER BY value. Materialized at emit time via
/// [`take_record_batch`].
///
/// The batch is referenced by `batch_id` rather than held directly, so the
/// operator-scoped [`RecordBatchStore`] can charge each distinct source
/// batch once however many entries reference it. Holding a batch per entry
/// and charging its bytes per entry would inflate the reservation by a
/// factor of (partitions × K), since a single batch contributes an entry to
/// every partition and ob group it touches.
#[derive(Debug)]
struct GroupEntry {
    /// Indices into the batch identified by `batch_id`. Always non-empty
    /// by construction.
    row_indices: Vec<u32>,
    /// Key into `PartitionedTopKDenseRank::store`.
    batch_id: u32,
}

/// Per-partition state for `DENSE_RANK()` semantics.
///
/// A `HashMap<Vec<u8>, Vec<GroupEntry>>` keyed by the row-encoded ORDER
/// BY bytes, capped at `k` distinct keys. Each key's `Vec<GroupEntry>`
/// holds every row seen at that ob value, one entry per contributing
/// source `RecordBatch`.
#[derive(Default)]
struct DenseRankPartitionState {
    groups: HashMap<Vec<u8>, Vec<GroupEntry>>,
    /// The same keys as `groups`, in a max-heap: the admission boundary
    /// (the largest tracked ob value) is an O(1) `peek()` check, and
    /// admission / removal are O(log K).
    ///
    /// INVARIANT: `keys` and `groups.keys()` hold the same set. Every
    /// insertion into / removal from `groups` must mirror into `keys`.
    keys: BinaryHeap<Vec<u8>>,
    /// Running total of the heap allocations owned by the *contents* of
    /// `groups` and `keys`: the key bytes, the per-key `Vec<GroupEntry>`
    /// buffers, and each entry's `row_indices`. Excludes the two
    /// containers' own tables, which `capacity()` reports in O(1).
    ///
    /// INVARIANT: equals `recompute_contents_bytes` (test-only, so not
    /// linkable from rustdoc). Every mutation of `groups` or `keys` must
    /// adjust it; the
    /// `test_partitioned_topk_dense_rank_contents_bytes_tracks_recompute`
    /// test checks this against a full recompute after a randomized
    /// workload.
    contents_bytes: usize,
}

impl DenseRankPartitionState {
    fn size(&self) -> usize {
        let table_overhead = self.groups.capacity()
            * (size_of::<Vec<u8>>() + size_of::<Vec<GroupEntry>>());
        // The heap's backing Vec: one `Vec<u8>` slot per reserved element.
        let keys_overhead = self.keys.capacity() * size_of::<Vec<u8>>();
        table_overhead + self.contents_bytes + keys_overhead
    }

    /// Bytes owned by one entry's `row_indices` buffer.
    fn entry_bytes(entry: &GroupEntry) -> usize {
        entry.row_indices.capacity() * size_of::<u32>()
    }

    /// Track a previously unseen ob value, holding `run_indices` as its
    /// first (and so far only) entry, and charge everything it allocates.
    ///
    /// `keys` and `groups` each own a copy of the key bytes; the clone's
    /// capacity is read after the fact rather than assumed equal to the
    /// original's, so the charge matches what was really allocated.
    fn insert_new_group(
        &mut self,
        ob_key: Vec<u8>,
        run_indices: Vec<u32>,
        batch_id: u32,
    ) {
        let key_copy = ob_key.clone();
        self.contents_bytes += key_copy.capacity() + ob_key.capacity();
        self.keys.push(key_copy);

        let entry = GroupEntry {
            row_indices: run_indices,
            batch_id,
        };
        self.contents_bytes += Self::entry_bytes(&entry);
        let entries = vec![entry];
        self.contents_bytes += entries.capacity() * size_of::<GroupEntry>();
        self.groups.insert(ob_key, entries);
    }

    /// The value [`Self::contents_bytes`] must hold, computed the slow
    /// way. Used to assert the incremental accounting in tests.
    #[cfg(test)]
    fn recompute_contents_bytes(&self) -> usize {
        let groups: usize = self
            .groups
            .iter()
            .map(|(key, entries)| {
                key.capacity()
                    + entries.capacity() * size_of::<GroupEntry>()
                    + entries.iter().map(Self::entry_bytes).sum::<usize>()
            })
            .sum();
        // `keys` duplicates every key's bytes.
        groups + self.keys.iter().map(|k| k.capacity()).sum::<usize>()
    }
}

/// Sibling to [`PartitionedTopK`] / [`PartitionedTopKRank`] implementing
/// `DENSE_RANK()` semantics.
///
/// Per partition, retains every row whose ORDER BY value is among the K
/// distinct-smallest ob values seen for that partition. The total row
/// count kept per partition is unbounded in `rows_per_distinct_value`
/// (unlike `RANK`, which is bounded above by K + boundary ties).
///
/// Like [`PartitionedTopK`], the [`RowConverter`], [`MemoryReservation`],
/// scratch [`Rows`] buffer, and [`TopKMetrics`] are shared across all
/// partitions for this operator instance. So is the
/// [`RecordBatchStore`]: retained rows are held as `(batch_id, indices)`
/// so each source batch is charged once for the whole operator, however
/// many partitions and ob groups reference it.
///
/// # Algorithm (per batch)
///
/// Evaluate + encode partition-by and order-by columns once, then group
/// the batch's row indices by partition key. For each partition, bucket
/// that partition's rows by distinct ob value (a within-call
/// accumulation), then merge each bucket into the partition state. Every
/// bucket is built from the current batch's rows, so each `GroupEntry` is
/// pinned to the batch its `row_indices` point into.
///
/// For each partition, for each distinct `ob_key` run in this batch:
/// - `ob_key` already in `state.groups` → push this batch's run as a
///   new `GroupEntry` (one entry per contributing batch).
/// - `ob_key` new, `state.groups.len() < k` → insert the run as a new
///   group.
/// - `ob_key` new, `state.groups.len() == k` → the largest tracked ob
///   value is the admission boundary, read from the `state.keys` max-heap
///   in O(1):
///   - `ob_key < max` → remove the max key (evict the entire max-key
///     group — up to many rows) and insert the run. The evicted group's
///     row count is added to the `row_replacements` metric.
///   - `ob_key >= max` → drop the whole run; no map mutation.
pub(crate) struct PartitionedTopKDenseRank {
    metrics: TopKMetrics,
    reservation: MemoryReservation,
    /// ORDER BY expressions (excludes PARTITION BY).
    expr: LexOrdering,
    /// Encoder for ORDER BY columns. Reused across partitions.
    row_converter: RowConverter,
    /// Scratch row buffer reused across `insert_batch` calls.
    scratch_rows: Rows,
    /// PARTITION BY expressions.
    partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
    /// Encoder for the partition key.
    partition_converter: RowConverter,
    /// Scratch row buffer for partition-key encoding. Reused across
    /// `insert_batch` calls (cleared + appended each batch).
    partition_scratch_rows: Rows,
    /// One state per distinct partition key seen so far. Keyed by the
    /// row-encoded PARTITION BY bytes (byte-comparable encoding, so the
    /// `Vec<u8>` hashes, compares, and sorts identically to an
    /// `OwnedRow`) which lets `insert_batch` look partitions up with
    /// `entry_ref` — allocating a key only on first sight of a partition
    /// rather than once per row.
    states: HashMap<Vec<u8>, DenseRankPartitionState>,
    /// Scratch map reused across `insert_batch` calls to group a batch's
    /// row indices by partition key. Drained (not reallocated) each batch
    /// so its backing table is allocated once, not per batch.
    partition_groups: HashMap<Vec<u8>, Vec<u32>>,
    /// Scratch map reused across partitions within a batch to bucket a
    /// partition's rows by distinct ORDER BY value. Drained (not
    /// reallocated) per partition so its backing table is allocated once,
    /// not once per distinct partition key.
    ob_runs: HashMap<Vec<u8>, Vec<u32>>,
    /// Source batches referenced by the retained `GroupEntry`s, held once
    /// for the whole operator with a use count per batch. This is what
    /// keeps the reservation proportional to the batches actually pinned
    /// rather than to the number of entries pointing at them.
    store: RecordBatchStore,
    /// When set, `emit` appends a column holding each retained row's
    /// `DENSE_RANK()`, letting the rewrite drop the `BoundedWindowAggExec`
    /// that would otherwise re-derive it.
    emit_ranks: bool,
    /// The schema `emit` produces: the input's columns, plus the ranking
    /// column when [`Self::emit_ranks`] is set.
    output_schema: SchemaRef,
    k: usize,
    batch_size: usize,
}

impl PartitionedTopKDenseRank {
    /// `ranked_schema` is as for [`PartitionedTopKCore::try_new`].
    #[expect(clippy::too_many_arguments)]
    pub(crate) fn try_new(
        partition_id: usize,
        schema: &SchemaRef,
        partition_exprs: Vec<Arc<dyn PhysicalExpr>>,
        partition_sort_fields: Vec<SortField>,
        order_expr: LexOrdering,
        k: usize,
        batch_size: usize,
        runtime: &Arc<RuntimeEnv>,
        metrics: &ExecutionPlanMetricsSet,
        ranked_schema: Option<SchemaRef>,
    ) -> Result<Self> {
        assert!(k > 0, "PartitionedTopKDenseRank requires k > 0");
        let reservation =
            MemoryConsumer::new(format!("PartitionedTopKDenseRank[{partition_id}]"))
                .register(&runtime.memory_pool);

        let order_sort_fields = build_sort_fields(&order_expr, schema)?;
        let row_converter = RowConverter::new(order_sort_fields)?;
        let scratch_rows =
            row_converter.empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);

        let partition_converter = RowConverter::new(partition_sort_fields)?;
        let partition_scratch_rows = partition_converter
            .empty_rows(batch_size, ESTIMATED_BYTES_PER_ROW * batch_size);

        Ok(Self {
            emit_ranks: ranked_schema.is_some(),
            output_schema: ranked_schema.unwrap_or_else(|| Arc::clone(schema)),
            metrics: TopKMetrics::new(metrics, partition_id),
            reservation,
            expr: order_expr,
            row_converter,
            scratch_rows,
            partition_exprs,
            partition_converter,
            partition_scratch_rows,
            states: HashMap::new(),
            partition_groups: HashMap::new(),
            ob_runs: HashMap::new(),
            store: RecordBatchStore::new(),
            k,
            batch_size,
        })
    }

    /// Encode PARTITION BY and ORDER BY columns once, demultiplex the
    /// batch's rows by partition key, then per partition bucket the rows
    /// by distinct ob value and merge each bucket into the partition
    /// state as one [`GroupEntry`].
    pub(crate) fn insert_batch(&mut self, batch: &RecordBatch) -> Result<()> {
        let elapsed_compute = self.metrics.baseline.elapsed_compute().clone();
        let _timer = elapsed_compute.timer();

        let num_rows = batch.num_rows();
        if num_rows == 0 {
            return Ok(());
        }

        // Register this batch with the store up front. `uses` is bumped
        // once per `GroupEntry` created below but lives on this local
        // entry, so the store sees a single insert per batch rather than
        // one per group — and `insert` drops batches that retained
        // nothing without ever charging for them.
        let mut batch_entry = self.store.register(batch.clone());
        let batch_id = batch_entry.id;

        // 1. Encode partition columns.
        let pk_arrays: Vec<ArrayRef> = self
            .partition_exprs
            .iter()
            .map(|e| e.evaluate(batch).and_then(|v| v.into_array(num_rows)))
            .collect::<Result<_>>()?;
        self.partition_scratch_rows.clear();
        self.partition_converter
            .append(&mut self.partition_scratch_rows, &pk_arrays)?;

        // 2. Group this batch's row indices by partition key.
        //    `partition_groups` is a reused scratch map: taken out here
        //    and drained below, so its backing table is allocated once
        //    for the operator, not once per batch. `entry_ref` owns the
        //    key only on Vacant, so it allocates one `Vec<u8>` per
        //    distinct partition rather than one per row.
        let mut groups = std::mem::take(&mut self.partition_groups);
        groups.clear();
        {
            let pk_rows = &self.partition_scratch_rows;
            for i in 0..num_rows {
                groups
                    .entry_ref(pk_rows.row(i).as_ref())
                    .or_default()
                    .push(i as u32);
            }
        }

        // 3. Evaluate ORDER BY columns and encode ONCE.
        let ob_arrays: Vec<ArrayRef> = self
            .expr
            .iter()
            .map(|e| e.expr.evaluate(batch).and_then(|v| v.into_array(num_rows)))
            .collect::<Result<_>>()?;
        self.scratch_rows.clear();
        self.row_converter
            .append(&mut self.scratch_rows, &ob_arrays)?;

        let k = self.k;
        let mut replacements: usize = 0;

        // 4. Per-partition: bucket this batch's rows by distinct ob value
        //    (within-call accumulation), then merge each bucket into the
        //    partition state as a single `GroupEntry`.
        for (pk, indices) in groups.drain() {
            let state = self
                .states
                .entry(pk)
                .or_insert_with(DenseRankPartitionState::default);

            // Bucket by ob key. `ob_runs` is a reused scratch map (taken
            // out and drained below) so its backing table is allocated
            // once, not once per distinct partition key. `entry_ref` owns
            // the key only on Vacant, so repeated rows of the same ob
            // value don't re-allocate.
            let mut runs = std::mem::take(&mut self.ob_runs);
            runs.clear();
            // Once the partition holds its full K distinct ob values, the
            // largest of them is the bar a new value must beat, and that bar
            // only ever gets stricter: with K values held there is no free
            // slot left for a new (possibly larger) one, and the only way in
            // from here is to evict that largest and put something strictly
            // smaller in its place. So a row worse than today's bar is worse
            // than every later bar too — it is not held now and can never be
            // admitted — and can be dropped before it costs a bucket. Rows
            // *equal* to the bar must still go through: that value is one of
            // the K being held, so its rows belong to a live group.
            let boundary: Option<&[u8]> = if state.groups.len() == k {
                state.keys.peek().map(Vec::as_slice)
            } else {
                None
            };
            for &orig_idx in &indices {
                let ob_row = self.scratch_rows.row(orig_idx as usize);
                if boundary.is_some_and(|b| ob_row.as_ref() > b) {
                    continue;
                }
                runs.entry_ref(ob_row.as_ref()).or_default().push(orig_idx);
            }

            for (ob_key, run_indices) in runs.drain() {
                // Case A: ob already tracked — push this batch's run as a
                // new `GroupEntry` (one entry per contributing batch).
                if let Some(entries) = state.groups.get_mut(&ob_key) {
                    batch_entry.uses += 1;
                    let before = entries.capacity() * size_of::<GroupEntry>();
                    let entry = GroupEntry {
                        row_indices: run_indices,
                        batch_id,
                    };
                    state.contents_bytes += DenseRankPartitionState::entry_bytes(&entry);
                    entries.push(entry);
                    // The push may have grown the buffer.
                    state.contents_bytes +=
                        entries.capacity() * size_of::<GroupEntry>() - before;
                    continue;
                }

                // Case B: new ob, room available.
                if state.groups.len() < k {
                    batch_entry.uses += 1;
                    state.insert_new_group(ob_key, run_indices, batch_id);
                    continue;
                }

                // Case C: new ob, at K distinct keys. The largest tracked
                // ob value is the admission boundary.
                let max_key = state.keys.peek().expect("state.groups has k >= 1 keys");
                if ob_key.as_slice() < max_key.as_slice() {
                    // Evict the entire max-key group, from both the map
                    // and its ordered mirror. `keys` and `groups` own
                    // separate copies of the key bytes, so both are
                    // uncharged — with their own capacities, which is why
                    // `remove_entry` is used to recover the map's copy
                    // rather than assuming it matches the popped one.
                    let evicted_key = state.keys.pop().expect("max key present");
                    let (map_key, evicted) = state
                        .groups
                        .remove_entry(&evicted_key)
                        .expect("keys mirrors groups");
                    state.contents_bytes -= evicted_key.capacity()
                        + map_key.capacity()
                        + evicted.capacity() * size_of::<GroupEntry>()
                        + evicted
                            .iter()
                            .map(DenseRankPartitionState::entry_bytes)
                            .sum::<usize>();
                    for e in &evicted {
                        replacements += e.row_indices.len();
                        if e.batch_id == batch_id {
                            // Admitted earlier in this same call, so the
                            // store has not seen `batch_entry` yet — drop
                            // the pending use rather than calling `unuse`,
                            // which panics on an unregistered id.
                            batch_entry.uses -= 1;
                        } else {
                            self.store.unuse(e.batch_id);
                        }
                    }
                    batch_entry.uses += 1;
                    state.insert_new_group(ob_key, run_indices, batch_id);
                }
                // else: ob >= max — drop the whole run.
            }

            // Return the drained scratch map (capacity retained) for the
            // next partition to reuse.
            self.ob_runs = runs;
        }

        // Return the drained scratch map (capacity retained) for the next
        // batch to reuse.
        self.partition_groups = groups;

        // Charges `batch` once if any group retained rows from it.
        self.store.insert(batch_entry);

        if replacements > 0 {
            self.metrics.row_replacements.add(replacements);
        }
        self.reservation.try_resize(self.size())?;
        Ok(())
    }

    /// Drain all per-partition maps in partition-key order and return
    /// the rows as a stream of coalesced [`RecordBatch`]es ordered by
    /// `(partition_keys, order_keys)`. Within a partition the distinct
    /// ob keys are sorted (byte-comparable encoding == sort order) so
    /// emitted rows are in ob-sorted order.
    pub(crate) fn emit(self) -> Result<SendableRecordBatchStream> {
        let Self {
            output_schema,
            emit_ranks,
            metrics,
            reservation: _,
            expr: _,
            row_converter: _,
            scratch_rows: _,
            partition_exprs: _,
            partition_converter: _,
            partition_scratch_rows: _,
            mut states,
            partition_groups: _,
            ob_runs: _,
            store,
            k: _,
            batch_size,
        } = self;
        let _timer = metrics.baseline.elapsed_compute().timer();

        let mut sorted_pks: Vec<Vec<u8>> = states.keys().cloned().collect();
        sorted_pks.sort();

        let mut out: Vec<Result<RecordBatch>> = Vec::new();

        // Gather every retained row with a single `interleave_record_batch`
        // per output batch rather than one `take_record_batch` per
        // `GroupEntry`. A group entry holds only the rows one source batch
        // contributed at one ob value, so entries are numerous and tiny —
        // with P partitions, K distinct ob values and B contributing
        // batches there are up to P × K × B of them, and gathering each
        // one separately builds and tears down that many `RecordBatch`es.
        // `interleave` takes `(batch_pos, row)` pairs across *different*
        // source batches in one call, which is exactly the shape here.
        //
        // The pairs are pushed in emit order — partitions in sorted key
        // order, ob values ascending within a partition, entries in
        // insertion order within an ob value — so the interleaved output
        // is already ordered and needs no post-sort.
        //
        // `batch_refs` holds only the batches the current chunk references
        // and is rebuilt per chunk: for Dictionary columns `interleave`
        // does work for every input array it is handed, referenced or not,
        // so passing the whole store to each chunk made emit
        // O(chunks × store batches). A batch's slot is resolved once per
        // entry, not per row.
        let mut batch_refs: Vec<&RecordBatch> = Vec::new();
        let mut batch_id_pos: HashMap<u32, usize> = HashMap::new();
        let mut indices: Vec<(usize, usize)> = Vec::with_capacity(batch_size);
        let mut sorted_obs: Vec<(Vec<u8>, Vec<GroupEntry>)> = Vec::new();
        // Parallel to `indices`: each row's `DENSE_RANK()`, when emitted.
        let mut ranks: Option<Vec<u64>> =
            emit_ranks.then(|| Vec::with_capacity(batch_size));

        // Chunk at `batch_size` so the operator emits the same batch sizes
        // as before and no single `interleave` output exceeds `batch_size`.
        for pk in sorted_pks {
            let DenseRankPartitionState {
                groups,
                keys: _,
                contents_bytes: _,
            } = states.remove(&pk).expect("key from states.keys()");
            // Sort the <= K distinct ob keys so rows emit ascending
            // (byte-comparable encoding == sort order).
            sorted_obs.extend(groups);
            sorted_obs.sort_by(|a, b| a.0.cmp(&b.0));
            // `DENSE_RANK` is the 1-based index of a row's distinct ob value
            // within its partition, and the state holds exactly the K
            // distinct-smallest values — so the loop counter *is* the rank,
            // shared by every row of the group.
            for (dense_rank, (_ob, entries)) in (1u64..).zip(sorted_obs.drain(..)) {
                for entry in entries {
                    let batch = &store
                        .get(entry.batch_id)
                        .expect("retained batch_id present in store")
                        .batch;
                    // Resolved lazily so a chunk boundary inside the entry
                    // re-registers its batch in the next chunk's slice.
                    let mut array_pos = None;
                    for row in entry.row_indices {
                        let pos = *array_pos.get_or_insert_with(|| {
                            *batch_id_pos.entry(entry.batch_id).or_insert_with(|| {
                                batch_refs.push(batch);
                                batch_refs.len() - 1
                            })
                        });
                        indices.push((pos, row as usize));
                        if let Some(ranks) = &mut ranks {
                            ranks.push(dense_rank);
                        }
                        if indices.len() == batch_size {
                            let b = interleave_record_batch(&batch_refs, &indices)?;
                            let ranks = ranks.as_mut().map(|r| r.drain(..));
                            out.push(Ok(finish_chunk(
                                b,
                                ranks,
                                &output_schema,
                                &metrics,
                            )?));
                            indices.clear();
                            batch_refs.clear();
                            batch_id_pos.clear();
                            array_pos = None;
                        }
                    }
                }
            }
        }
        if !indices.is_empty() {
            let b = interleave_record_batch(&batch_refs, &indices)?;
            let ranks = ranks.as_mut().map(|r| r.drain(..));
            out.push(Ok(finish_chunk(b, ranks, &output_schema, &metrics)?));
        }

        Ok(Box::pin(RecordBatchStreamAdapter::new(
            output_schema,
            futures::stream::iter(out),
        )))
    }

    /// Total memory currently held, including all per-partition states.
    fn size(&self) -> usize {
        // Per partition: the state itself plus the encoded partition key
        // owned by the map. The key bytes are a heap allocation the table
        // slot doesn't cover, and with wide or numerous partition keys
        // they dominate the fixed-size slots.
        let states_contents: usize = self
            .states
            .iter()
            .map(|(pk, state)| pk.capacity() + state.size())
            .sum();
        // `partition_groups` and `ob_runs` are drained, not dropped, so
        // their backing tables outlive every `insert_batch` call. Both are
        // empty by the time `size()` runs (drained above), so only the
        // retained capacity is charged.
        let scratch_tables = self.partition_groups.capacity()
            * (size_of::<Vec<u8>>() + size_of::<Vec<u32>>())
            + self.ob_runs.capacity() * (size_of::<Vec<u8>>() + size_of::<Vec<u32>>());
        size_of::<Self>()
            + self.row_converter.size()
            + self.partition_converter.size()
            + self.scratch_rows.size()
            + self.partition_scratch_rows.size()
            + states_contents
            + self.states.capacity()
                * (size_of::<Vec<u8>>() + size_of::<DenseRankPartitionState>())
            + scratch_tables
            + self.store.size()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metrics::MetricValue;
    use crate::spill::get_record_batch_memory_size;
    use arrow::array::{
        AsArray, BooleanArray, Float64Array, Int32Array, Int64Array, StringArray,
        StringDictionaryBuilder,
    };
    use arrow::datatypes::{DataType, Field, Int32Type, Int64Type, Schema, UInt64Type};
    use arrow_schema::SortOptions;
    use datafusion_common::utils::memory::RecordBatchMemoryCounter;
    use datafusion_common::{assert_batches_eq, exec_datafusion_err};
    use datafusion_execution::memory_pool::GreedyMemoryPool;
    use datafusion_execution::runtime_env::RuntimeEnvBuilder;
    use datafusion_physical_expr::{DynamicFilterTracking, expressions::col};
    use futures::TryStreamExt;

    /// This test ensures the size calculation is correct for RecordBatches with multiple columns.
    #[test]
    fn test_record_batch_store_size() {
        // given
        let schema = Arc::new(Schema::new(vec![
            Field::new("ints", DataType::Int32, true),
            Field::new("float64", DataType::Float64, false),
        ]));
        let mut record_batch_store = RecordBatchStore::new();
        let int_array =
            Int32Array::from(vec![Some(1), Some(2), Some(3), Some(4), Some(5)]); // 5 * 4 = 20
        let float64_array = Float64Array::from(vec![1.0, 2.0, 3.0, 4.0, 5.0]); // 5 * 8 = 40

        let record_batch_entry = RecordBatchEntry {
            id: 0,
            batch: RecordBatch::try_new(
                schema,
                vec![Arc::new(int_array), Arc::new(float64_array)],
            )
            .unwrap(),
            uses: 1,
        };

        // when insert record batch entry
        record_batch_store.insert(record_batch_entry);
        assert_eq!(record_batch_store.batches_size, 60);

        // when unuse record batch entry
        record_batch_store.unuse(0);
        assert_eq!(record_batch_store.batches_size, 0);
    }

    fn make_ab_schema() -> SchemaRef {
        make_ab_schema_with_nullable_a(false)
    }

    fn make_ab_schema_with_nullable_a(a_nullable: bool) -> SchemaRef {
        Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, a_nullable),
            Field::new("b", DataType::Float64, false),
        ]))
    }

    // Local TopK tests use one emitter; shared-filter cases pass the partition count explicitly.
    fn make_topk_filter() -> Arc<RwLock<TopKDynamicFilters>> {
        make_shared_topk_filter(1)
    }

    fn make_shared_topk_filter(
        topk_emitter_count: usize,
    ) -> Arc<RwLock<TopKDynamicFilters>> {
        Arc::new(RwLock::new(
            TopKDynamicFilters::new_with_topk_emitter_count(
                Arc::new(DynamicFilterPhysicalExpr::new(vec![], lit(true))),
                topk_emitter_count,
            ),
        ))
    }

    /// Builds the `(a, b)` fixture used by prefix-completion tests:
    /// full sort `(a, b)`, input prefix `[a]`, `k = 3`, and batch size 2.
    fn make_ab_topk(
        schema: SchemaRef,
        filter: Arc<RwLock<TopKDynamicFilters>>,
    ) -> Result<TopK> {
        make_ab_topk_with_options(0, schema, filter, SortOptions::default())
    }

    fn make_ab_topk_with_options(
        partition_id: usize,
        schema: SchemaRef,
        filter: Arc<RwLock<TopKDynamicFilters>>,
        a_options: SortOptions,
    ) -> Result<TopK> {
        let sort_expr_a = PhysicalSortExpr {
            expr: col("a", schema.as_ref())?,
            options: a_options,
        };
        let sort_expr_b = PhysicalSortExpr {
            expr: col("b", schema.as_ref())?,
            options: SortOptions::default(),
        };

        TopK::try_new(
            partition_id,
            schema,
            vec![sort_expr_a.clone()],
            LexOrdering::from([sort_expr_a, sort_expr_b]),
            3,
            2,
            Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            filter,
        )
    }

    #[test]
    fn test_topk_size_common_sort_prefix_converter() -> Result<()> {
        let schema = make_ab_schema();
        let sort_expr = PhysicalSortExpr {
            expr: col("a", schema.as_ref())?,
            options: SortOptions::default(),
        };
        let make_topk = |common_sort_prefix| {
            TopK::try_new(
                0,
                Arc::clone(&schema),
                common_sort_prefix,
                LexOrdering::from([sort_expr.clone()]),
                3,
                2,
                Arc::new(RuntimeEnv::default()),
                &ExecutionPlanMetricsSet::new(),
                make_topk_filter(),
            )
        };
        let without_prefix = make_topk(vec![])?;
        let with_prefix = make_topk(vec![sort_expr.clone()])?;
        let converter_size = with_prefix
            .common_sort_prefix_converter
            .as_ref()
            .expect("common sort prefix converter")
            .size();
        assert!(converter_size > 0);
        assert!(without_prefix.common_sort_prefix_converter.is_none());
        assert_eq!(
            without_prefix.size(),
            size_of::<TopK>()
                + without_prefix.row_converter.size()
                + without_prefix.scratch_rows.size()
                + without_prefix.heap.size()
        );
        assert_eq!(with_prefix.size(), without_prefix.size() + converter_size);

        Ok(())
    }

    /// Reads the `output_batches` and `output_rows` metrics recorded by an emit.
    fn output_batches_and_rows(metrics: &ExecutionPlanMetricsSet) -> (usize, usize) {
        let metrics = metrics.clone_inner();
        let batches = metrics
            .sum(|m| matches!(m.value(), MetricValue::OutputBatches(_)))
            .expect("output_batches metric")
            .as_usize();
        (batches, metrics.output_rows().expect("output_rows metric"))
    }

    /// Regression test for #24468: `emit` splits the heap's single batch into
    /// `batch_size` chunks, so `output_batches` must count each emitted chunk
    /// rather than the one pre-split batch.
    #[tokio::test]
    async fn test_topk_output_batches_metric_counts_emitted_batches() -> Result<()> {
        let schema = make_ab_schema();
        let metrics = ExecutionPlanMetricsSet::new();
        let sort_expr = PhysicalSortExpr {
            expr: col("a", schema.as_ref())?,
            options: SortOptions::default(),
        };
        // k = 5 with batch_size = 2 => emitted batches of [2, 2, 1]
        let mut topk = TopK::try_new(
            0,
            Arc::clone(&schema),
            vec![],
            LexOrdering::from([sort_expr]),
            5,
            2,
            Arc::new(RuntimeEnv::default()),
            &metrics,
            make_topk_filter(),
        )?;

        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(5), Some(4), Some(3), Some(2), Some(1), Some(0)],
            &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
        )?)?;

        let results: Vec<_> = topk.emit()?.try_collect().await?;
        let row_counts: Vec<usize> = results.iter().map(|b| b.num_rows()).collect();
        assert_eq!(row_counts, vec![2, 2, 1]);
        assert_eq!(output_batches_and_rows(&metrics), (3, 5));

        Ok(())
    }

    fn make_ab_batch(
        schema: SchemaRef,
        a: &[Option<i32>],
        b: &[f64],
    ) -> Result<RecordBatch> {
        Ok(RecordBatch::try_new(
            schema,
            vec![
                Arc::new(Int32Array::from(a.to_vec())) as ArrayRef,
                Arc::new(Float64Array::from(b.to_vec())) as ArrayRef,
            ],
        )?)
    }

    type AbRow = (Option<i32>, f64);

    fn make_ab_rows_batch(schema: SchemaRef, rows: &[AbRow]) -> Result<RecordBatch> {
        let (a, b): (Vec<_>, Vec<_>) = rows.iter().copied().unzip();
        make_ab_batch(schema, &a, &b)
    }

    #[tokio::test]
    async fn test_early_completion_marks_finished_with_prefix() -> Result<()> {
        let schema = make_ab_schema();
        let mut topk = make_ab_topk(Arc::clone(&schema), make_topk_filter())?;

        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(1), Some(1), Some(2)],
            &[20.0, 15.0, 30.0],
        )?)?;
        assert!(!topk.finished);

        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(2), Some(3)],
            &[10.0, 20.0],
        )?)?;
        assert!(topk.finished);

        let results: Vec<_> = topk.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+---+------+",
                "| a | b    |",
                "+---+------+",
                "| 1 | 15.0 |",
                "| 1 | 20.0 |",
                "| 2 | 10.0 |",
                "+---+------+",
            ],
            &results
        );

        Ok(())
    }

    /// Regression test for #22849: a batch whose rows are entirely rejected by the
    /// heap's dynamic filter must still trigger `attempt_early_completion` when its
    /// last row's prefix is worse than the heap's worst.
    #[tokio::test]
    async fn test_early_completion_fires_when_filter_rejects_entire_batch() -> Result<()>
    {
        let schema = make_ab_schema();
        let mut topk = make_ab_topk(Arc::clone(&schema), make_topk_filter())?;

        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(1), Some(1), Some(2)],
            &[20.0, 15.0, 30.0],
        )?)?;
        assert!(!topk.finished);

        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(3), Some(3)],
            &[10.0, 20.0],
        )?)?;
        assert!(topk.finished);

        let results: Vec<_> = topk.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+---+------+",
                "| a | b    |",
                "+---+------+",
                "| 1 | 15.0 |",
                "| 1 | 20.0 |",
                "| 2 | 30.0 |",
                "+---+------+",
            ],
            &results
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_early_completion_fires_when_batch_makes_no_replacements() -> Result<()>
    {
        let schema = make_ab_schema();
        let filter = make_topk_filter();
        let mut topk = make_ab_topk(Arc::clone(&schema), Arc::clone(&filter))?;

        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(1), Some(1), Some(2)],
            &[20.0, 15.0, 30.0],
        )?)?;
        assert!(!topk.finished);

        let replacements_before = topk.metrics.row_replacements.value();

        // Keep the dynamic filter permissive so the second batch reaches
        // `find_new_topk_items`; all of its rows are worse than the heap max,
        // so this specifically exercises the `replacements == 0` path.
        filter.read().expr().update(lit(true))?;
        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(3), Some(3)],
            &[10.0, 20.0],
        )?)?;
        assert_eq!(topk.metrics.row_replacements.value(), replacements_before);
        assert!(topk.finished);

        let results: Vec<_> = topk.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+---+------+",
                "| a | b    |",
                "+---+------+",
                "| 1 | 15.0 |",
                "| 1 | 20.0 |",
                "| 2 | 30.0 |",
                "+---+------+",
            ],
            &results
        );

        Ok(())
    }

    /// An empty batch has no last row to prove early completion with, so it
    /// must leave the TopK unchanged, both with an empty heap and a full one.
    #[tokio::test]
    async fn test_empty_batch_with_prefix_does_not_finish() -> Result<()> {
        let schema = make_ab_schema();
        let mut topk = make_ab_topk(Arc::clone(&schema), make_topk_filter())?;
        let empty = RecordBatch::new_empty(Arc::clone(&schema));

        topk.insert_batch(empty.clone())?;
        assert!(!topk.finished);
        assert_eq!(topk.heap.store.len(), 0);

        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(1), Some(1), Some(2)],
            &[20.0, 15.0, 30.0],
        )?)?;
        let heap_before = heap_snapshot(&topk);
        let store_len_before = topk.heap.store.len();

        topk.insert_batch(empty)?;
        assert!(!topk.finished);
        assert_eq!(heap_snapshot(&topk), heap_before);
        assert_eq!(topk.heap.store.len(), store_len_before);

        let results: Vec<_> = topk.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+---+------+",
                "| a | b    |",
                "+---+------+",
                "| 1 | 15.0 |",
                "| 1 | 20.0 |",
                "| 2 | 30.0 |",
                "+---+------+",
            ],
            &results
        );

        Ok(())
    }

    /// Builds a `k = 3` TopK over `(a, b)` sorted by the single key `expr`,
    /// with no input sort prefix.
    fn make_single_key_topk(
        schema: SchemaRef,
        expr: Arc<dyn PhysicalExpr>,
        metrics: &ExecutionPlanMetricsSet,
    ) -> Result<TopK> {
        TopK::try_new(
            0,
            schema,
            vec![],
            LexOrdering::from([PhysicalSortExpr {
                expr,
                options: SortOptions::default(),
            }]),
            3,
            2,
            Arc::new(RuntimeEnv::default()),
            metrics,
            make_topk_filter(),
        )
    }

    fn heap_snapshot(topk: &TopK) -> Vec<(Vec<u8>, u32, usize)> {
        topk.heap
            .inner
            .iter()
            .map(|r| (r.row.clone(), r.batch_id, r.index))
            .collect()
    }

    #[tokio::test]
    async fn test_batch_rejected_by_threshold_leaves_heap_untouched() -> Result<()> {
        let schema = make_ab_schema();
        let metrics = ExecutionPlanMetricsSet::new();
        let mut topk =
            make_single_key_topk(Arc::clone(&schema), col("a", &schema)?, &metrics)?;

        topk.insert_batch(make_ab_batch(
            Arc::clone(&schema),
            &[Some(3), Some(1), Some(2)],
            &[0.0, 1.0, 2.0],
        )?)?;

        let rejected = make_ab_batch(
            Arc::clone(&schema),
            &[Some(7), Some(5), Some(9)],
            &[3.0, 4.0, 5.0],
        )?;
        // The heap is full, so the threshold must now reject every row.
        let threshold = topk.filter.read().expr.current()?;
        let passing = threshold
            .evaluate(&rejected)?
            .into_array(rejected.num_rows())?;
        assert!(!passing.as_boolean().has_true());

        let heap_before = heap_snapshot(&topk);
        let store_len_before = topk.heap.store.len();
        let replacements_before = topk.metrics.row_replacements.value();

        topk.insert_batch(rejected)?;

        assert_eq!(heap_snapshot(&topk), heap_before);
        assert_eq!(topk.heap.store.len(), store_len_before);
        assert_eq!(topk.metrics.row_replacements.value(), replacements_before);

        let results: Vec<_> = topk.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+---+-----+",
                "| a | b   |",
                "+---+-----+",
                "| 1 | 1.0 |",
                "| 2 | 2.0 |",
                "| 3 | 0.0 |",
                "+---+-----+",
            ],
            &results
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_expression_sort_key_matches_column_sort_key() -> Result<()> {
        let schema = make_ab_schema();
        let column_metrics = ExecutionPlanMetricsSet::new();
        let expr_metrics = ExecutionPlanMetricsSet::new();
        let mut by_column = make_single_key_topk(
            Arc::clone(&schema),
            col("a", &schema)?,
            &column_metrics,
        )?;
        let a_plus_one = Arc::new(BinaryExpr::new(
            col("a", &schema)?,
            Operator::Plus,
            lit(1i32),
        ));
        let mut by_expr =
            make_single_key_topk(Arc::clone(&schema), a_plus_one, &expr_metrics)?;

        let inputs: [&[Option<i32>]; 4] = [
            &[Some(8), Some(5), Some(9)],
            &[Some(4), Some(10), Some(2)],
            &[Some(11), Some(12)],
            &[Some(6), Some(1), Some(7)],
        ];
        for a in inputs {
            let b: Vec<f64> = a.iter().map(|v| f64::from(v.unwrap()) / 2.0).collect();
            let batch = make_ab_batch(Arc::clone(&schema), a, &b)?;
            by_column.insert_batch(batch.clone())?;
            by_expr.insert_batch(batch)?;
            assert_eq!(
                by_expr.metrics.row_replacements.value(),
                by_column.metrics.row_replacements.value()
            );
        }

        let column_results: Vec<_> = by_column.emit()?.try_collect().await?;
        let expr_results: Vec<_> = by_expr.emit()?.try_collect().await?;
        let expected = [
            "+---+-----+",
            "| a | b   |",
            "+---+-----+",
            "| 1 | 0.5 |",
            "| 2 | 1.0 |",
            "| 4 | 2.0 |",
            "+---+-----+",
        ];
        assert_batches_eq!(expected, &column_results);
        assert_batches_eq!(expected, &expr_results);
        assert_eq!(
            output_batches_and_rows(&expr_metrics),
            output_batches_and_rows(&column_metrics)
        );

        Ok(())
    }

    struct SharedPrefixCase {
        name: &'static str,
        a_nullable: bool,
        a_options: SortOptions,
        threshold_source_rows: &'static [AbRow],
        lagging_partition_rows: &'static [AbRow],
        expected_finished: bool,
    }

    fn assert_shared_prefix_case(case: SharedPrefixCase) -> Result<()> {
        let schema = make_ab_schema_with_nullable_a(case.a_nullable);
        let filter = make_shared_topk_filter(2);

        let mut threshold_source = make_ab_topk_with_options(
            0,
            Arc::clone(&schema),
            Arc::clone(&filter),
            case.a_options,
        )?;
        threshold_source.insert_batch(make_ab_rows_batch(
            Arc::clone(&schema),
            case.threshold_source_rows,
        )?)?;
        assert!(
            filter
                .read()
                .shared_threshold
                .as_ref()
                .and_then(TopKThreshold::common_prefix_row)
                .is_some(),
            "{}: threshold-source partition should establish the shared prefix threshold",
            case.name
        );

        let mut lagging_partition = make_ab_topk_with_options(
            1,
            Arc::clone(&schema),
            Arc::clone(&filter),
            case.a_options,
        )?;
        lagging_partition
            .insert_batch(make_ab_rows_batch(schema, case.lagging_partition_rows)?)?;

        assert!(
            lagging_partition.heap.inner.is_empty(),
            "{}: lagging partition's local heap should remain empty",
            case.name
        );
        assert_eq!(
            lagging_partition.finished, case.expected_finished,
            "{}",
            case.name
        );

        Ok(())
    }

    #[test]
    fn test_shared_filter_can_finish_partition_before_local_heap_is_full() -> Result<()> {
        assert_shared_prefix_case(SharedPrefixCase {
            name: "shared threshold should finish lagging partition",
            a_nullable: false,
            a_options: SortOptions::default(),
            threshold_source_rows: &[(Some(1), 20.0), (Some(1), 15.0), (Some(2), 30.0)],
            lagging_partition_rows: &[(Some(3), 10.0), (Some(3), 20.0)],
            expected_finished: true,
        })
    }

    #[test]
    fn test_shared_prefix_threshold_boundary_cases() -> Result<()> {
        for case in [
            SharedPrefixCase {
                name: "equal prefix cannot prove completion",
                a_nullable: false,
                a_options: SortOptions::default(),
                threshold_source_rows: &[
                    (Some(1), 20.0),
                    (Some(1), 15.0),
                    (Some(2), 30.0),
                ],
                lagging_partition_rows: &[(Some(2), 40.0), (Some(2), 50.0)],
                expected_finished: false,
            },
            SharedPrefixCase {
                name: "descending prefix uses sort-order row encoding",
                a_nullable: false,
                a_options: SortOptions {
                    descending: true,
                    nulls_first: true,
                },
                threshold_source_rows: &[
                    (Some(10), 1.0),
                    (Some(10), 2.0),
                    (Some(9), 3.0),
                ],
                lagging_partition_rows: &[(Some(8), 1.0), (Some(8), 2.0)],
                expected_finished: true,
            },
            SharedPrefixCase {
                name: "NULLS LAST prefix uses sort-order row encoding",
                a_nullable: true,
                a_options: SortOptions {
                    descending: false,
                    nulls_first: false,
                },
                threshold_source_rows: &[
                    (Some(1), 20.0),
                    (Some(1), 15.0),
                    (Some(2), 30.0),
                ],
                lagging_partition_rows: &[(None, 10.0), (None, 20.0)],
                expected_finished: true,
            },
        ] {
            assert_shared_prefix_case(case)?;
        }
        Ok(())
    }

    fn make_single_column_topk(
        dynamic_filter: Arc<DynamicFilterPhysicalExpr>,
    ) -> Result<(SchemaRef, TopK)> {
        make_single_column_topk_with_filter(
            0,
            Arc::new(RwLock::new(TopKDynamicFilters::new(dynamic_filter))),
        )
    }

    fn make_single_column_topk_with_filter(
        partition_id: usize,
        filter: Arc<RwLock<TopKDynamicFilters>>,
    ) -> Result<(SchemaRef, TopK)> {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
        let sort_expr = PhysicalSortExpr {
            expr: col("a", schema.as_ref())?,
            options: SortOptions::default(),
        };

        let topk = TopK::try_new(
            partition_id,
            Arc::clone(&schema),
            vec![sort_expr.clone()],
            LexOrdering::from([sort_expr]),
            2,
            10,
            Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            filter,
        )?;

        Ok((schema, topk))
    }

    #[tokio::test]
    async fn test_topk_marks_filter_complete() -> Result<()> {
        let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], lit(true)));
        let dynamic_filter_clone = Arc::clone(&dynamic_filter);
        let (schema, mut topk) = make_single_column_topk(dynamic_filter)?;

        let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(3), Some(1), Some(2)]));
        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![array])?;
        topk.insert_batch(batch)?;

        let _results: Vec<_> = topk.emit()?.try_collect().await?;

        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            dynamic_filter_clone.wait_complete(),
        )
        .await
        .expect("single-emitter TopK should mark the dynamic filter complete");

        Ok(())
    }

    #[tokio::test]
    async fn test_shared_topk_filter_completes_after_last_emitter() -> Result<()> {
        let dynamic_filter = Arc::new(DynamicFilterPhysicalExpr::new(vec![], lit(true)));
        let dynamic_filter_clone = Arc::clone(&dynamic_filter);
        let shared_filter = Arc::new(RwLock::new(
            TopKDynamicFilters::new_with_topk_emitter_count(dynamic_filter, 2),
        ));

        let (schema, mut topk_0) =
            make_single_column_topk_with_filter(0, Arc::clone(&shared_filter))?;
        let (_, mut topk_1) =
            make_single_column_topk_with_filter(1, Arc::clone(&shared_filter))?;

        let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(3), Some(1), Some(2)]));
        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![array])?;
        topk_0.insert_batch(batch)?;
        let _results: Vec<_> = topk_0.emit()?.try_collect().await?;

        let dynamic_filter_expr: Arc<dyn PhysicalExpr> =
            Arc::<DynamicFilterPhysicalExpr>::clone(&dynamic_filter_clone);
        assert!(
            matches!(
                DynamicFilterTracking::classify(&dynamic_filter_expr),
                DynamicFilterTracking::Watching(_)
            ),
            "the shared filter should remain watchable until every TopK emits"
        );

        let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(6), Some(4), Some(5)]));
        let batch = RecordBatch::try_new(schema, vec![array])?;
        topk_1.insert_batch(batch)?;
        let _results: Vec<_> = topk_1.emit()?.try_collect().await?;

        tokio::time::timeout(
            std::time::Duration::from_secs(1),
            dynamic_filter_clone.wait_complete(),
        )
        .await
        .expect("the final shared TopK emitter should mark the dynamic filter complete");

        Ok(())
    }

    /// Schema for the `UNION ALL` fixture: `c0` is constant within each
    /// partition but differs between partitions, and `c1` orders the rows.
    fn make_c0_c1_schema() -> SchemaRef {
        Arc::new(Schema::new(vec![
            Field::new("c0", DataType::Int64, false),
            Field::new("c1", DataType::Int64, false),
        ]))
    }

    fn make_c0_c1_batch(schema: SchemaRef, rows: &[(i64, i64)]) -> Result<RecordBatch> {
        let c0: ArrayRef =
            Arc::new(Int64Array::from_iter_values(rows.iter().map(|row| row.0)));
        let c1: ArrayRef =
            Arc::new(Int64Array::from_iter_values(rows.iter().map(|row| row.1)));
        Ok(RecordBatch::try_new(schema, vec![c0, c1])?)
    }

    fn c0_c1_sort_exprs(
        schema: &SchemaRef,
    ) -> Result<(PhysicalSortExpr, PhysicalSortExpr)> {
        Ok((
            PhysicalSortExpr {
                expr: col("c0", schema.as_ref())?,
                options: SortOptions::default(),
            },
            PhysicalSortExpr {
                expr: col("c1", schema.as_ref())?,
                options: SortOptions::default(),
            },
        ))
    }

    fn make_c0_c1_topk(
        partition_id: usize,
        schema: SchemaRef,
        common_sort_prefix: Vec<PhysicalSortExpr>,
        expr: LexOrdering,
        filter: Arc<RwLock<TopKDynamicFilters>>,
    ) -> Result<TopK> {
        TopK::try_new(
            partition_id,
            schema,
            common_sort_prefix,
            expr,
            2,
            8192,
            Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            filter,
        )
    }

    /// Inserts the `c0 = 5` and `c0 = 1` partitions into two TopKs that share
    /// `filter`, in the requested order, then returns the top 2 rows after
    /// merging the partition outputs on the full `[c0, c1]` key (what the
    /// `SortPreservingMergeExec` above the TopK does).
    async fn merged_c0_c1_top2(
        schema: &SchemaRef,
        topk_ordering: LexOrdering,
        common_sort_prefix: Vec<PhysicalSortExpr>,
        five_first: bool,
    ) -> Result<Vec<(i64, i64)>> {
        let filter = make_shared_topk_filter(2);
        let mut five = make_c0_c1_topk(
            0,
            Arc::clone(schema),
            common_sort_prefix.clone(),
            topk_ordering.clone(),
            Arc::clone(&filter),
        )?;
        let mut one = make_c0_c1_topk(
            1,
            Arc::clone(schema),
            common_sort_prefix,
            topk_ordering,
            filter,
        )?;

        let five_batch = make_c0_c1_batch(Arc::clone(schema), &[(5, 0), (5, 1)])?;
        let one_batch = make_c0_c1_batch(Arc::clone(schema), &[(1, 0), (1, 1)])?;
        if five_first {
            five.insert_batch(five_batch)?;
            one.insert_batch(one_batch)?;
        } else {
            one.insert_batch(one_batch)?;
            five.insert_batch(five_batch)?;
        }

        collect_c0_c1_top2([five, one]).await
    }

    async fn collect_c0_c1_top2(topks: [TopK; 2]) -> Result<Vec<(i64, i64)>> {
        let mut rows = Vec::new();
        for topk in topks {
            let batches: Vec<RecordBatch> = topk.emit()?.try_collect().await?;
            for batch in batches {
                let c0 = batch.column(0).as_primitive::<Int64Type>();
                let c1 = batch.column(1).as_primitive::<Int64Type>();
                rows.extend((0..batch.num_rows()).map(|i| (c0.value(i), c1.value(i))));
            }
        }
        // `SortPreservingMergeExec` merges on the full `[c0, c1]` key. With
        // four rows, sorting and truncating is equivalent.
        rows.sort_unstable();
        rows.truncate(2);
        Ok(rows)
    }

    /// The shared TopK threshold is comparable across partitions only when the
    /// sort key covers the constant that differs between them. With `[c0, c1]`
    /// as the TopK key and `[c0]` as the input sort prefix, both feeding orders
    /// keep both rows of the `c0 = 1` partition that the top 2 needs.
    #[tokio::test]
    async fn test_shared_filter_keeps_heterogeneous_constant_in_key() -> Result<()> {
        let schema = make_c0_c1_schema();
        let (sort_c0, sort_c1) = c0_c1_sort_exprs(&schema)?;

        for five_first in [true, false] {
            let rows = merged_c0_c1_top2(
                &schema,
                LexOrdering::from([sort_c0.clone(), sort_c1.clone()]),
                vec![sort_c0.clone()],
                five_first,
            )
            .await?;
            assert_eq!(rows, vec![(1, 0), (1, 1)], "five_first={five_first}");
        }

        Ok(())
    }

    /// A better partition must keep reading until it has enough rows, while a
    /// worse partition can stop once the shared prefix threshold passes it.
    #[tokio::test]
    async fn test_shared_filter_heterogeneous_prefix_across_batches() -> Result<()> {
        let schema = make_c0_c1_schema();
        let (sort_c0, sort_c1) = c0_c1_sort_exprs(&schema)?;
        let ordering = LexOrdering::from([sort_c0.clone(), sort_c1]);
        let filter = make_shared_topk_filter(2);
        let mut five = make_c0_c1_topk(
            0,
            Arc::clone(&schema),
            vec![sort_c0.clone()],
            ordering.clone(),
            Arc::clone(&filter),
        )?;
        let mut one = make_c0_c1_topk(
            1,
            Arc::clone(&schema),
            vec![sort_c0],
            ordering,
            Arc::clone(&filter),
        )?;

        five.insert_batch(make_c0_c1_batch(Arc::clone(&schema), &[(5, 0), (5, 1)])?)?;
        assert!(filter.read().shared_threshold.is_some());
        assert!(!five.finished);

        one.insert_batch(make_c0_c1_batch(Arc::clone(&schema), &[(1, 0)])?)?;
        assert!(!one.finished);
        assert_eq!(one.heap.inner.len(), 1);

        // The first batch must not stop this partition before its second row.
        one.insert_batch(make_c0_c1_batch(Arc::clone(&schema), &[(1, 1)])?)?;
        assert!(!one.finished);
        assert_eq!(one.heap.inner.len(), 2);

        // The better partition now has k rows, so the worse one may stop.
        five.insert_batch(make_c0_c1_batch(schema, &[(5, 2)])?)?;
        assert!(five.finished);
        assert_eq!(five.metrics.row_replacements.value(), 2);
        assert_eq!(collect_c0_c1_top2([five, one]).await?, vec![(1, 0), (1, 1)]);
        Ok(())
    }

    /// Tests that memory-based compaction triggers when a large batch
    /// has very few rows referenced by the top-k heap.
    #[tokio::test]
    async fn test_topk_memory_compaction() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));

        let sort_expr = PhysicalSortExpr {
            expr: col("a", schema.as_ref())?,
            options: SortOptions::default(),
        };

        let full_expr = LexOrdering::from([sort_expr.clone()]);
        let prefix = vec![sort_expr];

        let runtime = Arc::new(RuntimeEnv::default());
        let metrics = ExecutionPlanMetricsSet::new();

        let k = 5;
        let mut topk = TopK::try_new(
            0,
            Arc::clone(&schema),
            prefix,
            full_expr,
            k,
            8192,
            runtime,
            &metrics,
            Arc::new(RwLock::new(TopKDynamicFilters::new(Arc::new(
                DynamicFilterPhysicalExpr::new(vec![], lit(true)),
            )))),
        )?;

        // Insert a large batch (100,000 rows) with values 1..=100_000.
        // Only the smallest 5 values (1..=5) will end up in the heap.
        let large_values: Vec<i32> = (1..=100_000).collect();
        let array1: ArrayRef = Arc::new(Int32Array::from(large_values));
        let batch1 = RecordBatch::try_new(Arc::clone(&schema), vec![array1])?;
        topk.insert_batch(batch1)?;

        // After the first batch, store has 1 batch — compaction should
        // not trigger (guard: store.len() <= 1).
        assert_eq!(
            topk.heap.store.len(),
            1,
            "should have 1 batch before second insert"
        );

        // Insert a second batch whose values displace entries in the heap.
        // -1 and 0 are smaller than the current top-5 (1..=5), so they
        // produce 2 replacements. With replacements > 0, `insert_batch`
        // calls `insert_batch_entry` (briefly making store.len() == 2)
        // and then `maybe_compact`, which should collapse it back to 1.
        let array2: ArrayRef = Arc::new(Int32Array::from(vec![-1, 0]));
        let batch2 = RecordBatch::try_new(Arc::clone(&schema), vec![array2])?;
        let replacements_before = topk.metrics.row_replacements.value();
        topk.insert_batch(batch2)?;

        // Sanity check: batch2 was actually integrated. Without
        // replacements, `maybe_compact` is never called and the
        // store-length assertion below would pass vacuously.
        assert!(
            topk.metrics.row_replacements.value() > replacements_before,
            "batch2 must produce replacements so compaction is exercised"
        );

        // The compacted-estimate guard is `total_rows <= num_rows * 2`,
        // i.e. 100_002 <= 10, which is false, so compaction fires and
        // collapses the two stored batches back into one.
        assert_eq!(
            topk.heap.store.len(),
            1,
            "store should be compacted to 1 batch"
        );

        // Verify the emitted results are correct (top 5 ascending).
        let results: Vec<_> = topk.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+", "| a  |", "+----+", "| -1 |", "| 0  |", "| 1  |", "| 2  |",
                "| 3  |", "+----+",
            ],
            &results
        );

        Ok(())
    }

    /// Negative path: when stored rows are close to the heap size,
    /// compaction must NOT fire even with multiple batches present,
    /// because the savings would be marginal
    /// (guard: `total_rows <= num_rows * 2`).
    ///
    /// Uses a bit-packed `BooleanArray` so that future changes to the
    /// compaction heuristic that reintroduce a per-byte estimate
    /// (where integer truncation could misbehave on sub-byte types)
    /// are caught here.
    #[tokio::test]
    async fn test_topk_memory_compaction_skipped_when_marginal() -> Result<()> {
        let schema =
            Arc::new(Schema::new(vec![Field::new("a", DataType::Boolean, false)]));

        let sort_expr = PhysicalSortExpr {
            expr: col("a", schema.as_ref())?,
            options: SortOptions::default(),
        };
        let full_expr = LexOrdering::from([sort_expr.clone()]);
        let prefix = vec![sort_expr];

        let runtime = Arc::new(RuntimeEnv::default());
        let metrics = ExecutionPlanMetricsSet::new();

        let k = 10;
        let mut topk = TopK::try_new(
            0,
            Arc::clone(&schema),
            prefix,
            full_expr,
            k,
            8192,
            runtime,
            &metrics,
            Arc::new(RwLock::new(TopKDynamicFilters::new(Arc::new(
                DynamicFilterPhysicalExpr::new(vec![], lit(true)),
            )))),
        )?;

        // Two small batches; every row from both batches ends up referenced
        // by the heap, so total_rows == num_rows == 10.
        let batch1 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(BooleanArray::from(vec![false, false, true, true, true]))
                    as ArrayRef,
            ],
        )?;
        topk.insert_batch(batch1)?;

        let batch2 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(BooleanArray::from(vec![false, false, false, true, true]))
                    as ArrayRef,
            ],
        )?;
        topk.insert_batch(batch2)?;

        // Guard `total_rows <= num_rows * 2` should hold (10 <= 20),
        // so compaction is skipped and BOTH batches remain in the store.
        assert_eq!(
            topk.heap.store.len(),
            2,
            "store must keep 2 batches when savings would be marginal"
        );
        assert_eq!(topk.heap.inner.len(), 10, "heap should hold all 10 rows");

        // Output is still correct (5 falses then 5 trues ascending).
        let results: Vec<_> = topk.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+-------+",
                "| a     |",
                "+-------+",
                "| false |",
                "| false |",
                "| false |",
                "| false |",
                "| false |",
                "| true  |",
                "| true  |",
                "| true  |",
                "| true  |",
                "| true  |",
                "+-------+",
            ],
            &results
        );

        Ok(())
    }

    /// Builds a `(pk Int32, val Int32)` schema and a `PartitionedTopK`
    /// partitioned by `pk` with order `val ASC`. Helper for the
    /// `PartitionedTopK` tests below.
    fn build_partitioned_topk(k: usize) -> Result<(Arc<Schema>, PartitionedTopK)> {
        build_partitioned_topk_with_opts(k, SortOptions::default(), false)
    }

    /// Variant of [`build_partitioned_topk`] that lets the test pick the
    /// `val` column's `SortOptions` (direction, null ordering) and
    /// nullability. Used by tests that exercise the shared encoder
    /// across `ASC`/`DESC` and `NULLS FIRST/LAST` paths.
    fn build_partitioned_topk_with_opts(
        k: usize,
        val_sort_options: SortOptions,
        val_nullable: bool,
    ) -> Result<(Arc<Schema>, PartitionedTopK)> {
        build_pk_val_state(
            PartitionedTopK::try_new,
            k,
            val_sort_options,
            val_nullable,
            &Arc::new(RuntimeEnv::default()),
            None,
        )
    }

    /// Variant of [`build_partitioned_topk`] that runs against a caller-supplied
    /// [`RuntimeEnv`], so a test can bound the memory pool.
    fn build_partitioned_topk_with_runtime(
        k: usize,
        runtime: &Arc<RuntimeEnv>,
    ) -> Result<(Arc<Schema>, PartitionedTopK)> {
        build_pk_val_state(
            PartitionedTopK::try_new,
            k,
            SortOptions::default(),
            false,
            runtime,
            None,
        )
    }

    /// The signature all three policies' `try_new` share, so one builder can
    /// construct any of them.
    type StateCtor<T> = fn(
        usize,
        &SchemaRef,
        Vec<Arc<dyn PhysicalExpr>>,
        Vec<SortField>,
        LexOrdering,
        usize,
        usize,
        &Arc<RuntimeEnv>,
        &ExecutionPlanMetricsSet,
        Option<SchemaRef>,
    ) -> Result<T>;

    /// Builds a `(pk Int32, val Int32)` schema and a state built by `ctor`,
    /// partitioned by `pk ASC` and ordered by `val` under `val_sort_options`,
    /// with batch size 8. With a `ranking_field` the state appends it, as the
    /// exec would. Shared by every policy's builders.
    fn build_pk_val_state<T>(
        ctor: StateCtor<T>,
        k: usize,
        val_sort_options: SortOptions,
        val_nullable: bool,
        runtime: &Arc<RuntimeEnv>,
        ranking_field: Option<FieldRef>,
    ) -> Result<(Arc<Schema>, T)> {
        let schema = pk_val_schema(val_nullable);

        let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
        let pk_sort_expr = PhysicalSortExpr {
            expr: Arc::clone(&pk_expr),
            options: SortOptions::default(),
        };
        let val_sort_expr = PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: val_sort_options,
        };

        let ranked_schema = ranking_field
            .map(|field| partitioned_topk_output_schema(&schema, Some(&field)));
        let state = ctor(
            0,
            &schema,
            vec![pk_expr],
            build_sort_fields(&[pk_sort_expr], &schema)?,
            LexOrdering::from([val_sort_expr]),
            k,
            8, // batch_size
            runtime,
            &ExecutionPlanMetricsSet::new(),
            ranked_schema,
        )?;
        Ok((schema, state))
    }

    /// A state built by `ctor` with [`build_pk_val_state`]'s defaults that
    /// emits `ranking_field`.
    fn build_emitting<T>(
        ctor: StateCtor<T>,
        k: usize,
        ranking_field: FieldRef,
    ) -> Result<(Arc<Schema>, T)> {
        build_pk_val_state(
            ctor,
            k,
            SortOptions::default(),
            false,
            &Arc::new(RuntimeEnv::default()),
            Some(ranking_field),
        )
    }

    /// Partition-key nullability is a distinct concern from ORDER BY
    /// nullability: the key layer decides whether NULL keys collapse
    /// into one partition, and emit-time ordering decides where that
    /// partition lands relative to the non-NULL ones.
    fn build_partitioned_topk_nullable_pk(
        k: usize,
        pk_sort_options: SortOptions,
    ) -> Result<(Arc<Schema>, PartitionedTopK)> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("pk", DataType::Int32, true),
            Field::new("val", DataType::Int32, false),
        ]));

        let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
        let partition_ordering = [PhysicalSortExpr {
            expr: Arc::clone(&pk_expr),
            options: pk_sort_options,
        }];
        let order_expr = LexOrdering::from([PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: SortOptions::default(),
        }]);

        let state = PartitionedTopK::try_new(
            0,
            &schema,
            vec![pk_expr],
            build_sort_fields(&partition_ordering, &schema)?,
            order_expr,
            k,
            8, // batch_size
            &Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            None,
        )?;
        Ok((schema, state))
    }

    fn nullable_pk_batch(
        schema: &Arc<Schema>,
        pks: Vec<Option<i32>>,
        vals: Vec<i32>,
    ) -> Result<RecordBatch> {
        Ok(RecordBatch::try_new(
            Arc::clone(schema),
            vec![
                Arc::new(Int32Array::from(pks)),
                Arc::new(Int32Array::from(vals)),
            ],
        )?)
    }

    /// A NULL partition key is a partition like any other: every NULL-keyed
    /// row belongs to the *same* partition, and that partition gets its own
    /// K-row heap. With `NULLS LAST` on the partition key it emits after
    /// every non-NULL partition.
    #[tokio::test]
    async fn test_partitioned_topk_null_partition_key_nulls_last() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_nullable_pk(
            2,
            SortOptions {
                descending: false,
                nulls_first: false,
            },
        )?;

        // pk=NULL vals: 9, 3, 5 → top-2 ASC = [3, 5]   (one partition, not three)
        // pk=1    vals: 4, 2    → top-2      = [2, 4]
        // pk=2    vals: 8       → top-2      = [8]
        let batch = nullable_pk_batch(
            &schema,
            vec![None, Some(1), None, Some(2), None, Some(1)],
            vec![9, 4, 3, 8, 5, 2],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 2   |",
                "| 1  | 4   |",
                "| 2  | 8   |",
                "|    | 3   |",
                "|    | 5   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// Companion to [`test_partitioned_topk_null_partition_key_nulls_last`]
    /// with `NULLS FIRST` on the partition key: the same NULL partition must
    /// now emit *before* every non-NULL one. Also splits the NULL key across
    /// two batches to prove it interns to a stable group.
    #[tokio::test]
    async fn test_partitioned_topk_null_partition_key_nulls_first() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_nullable_pk(
            2,
            SortOptions {
                descending: false,
                nulls_first: true,
            },
        )?;

        // First batch sees pk=1 before any NULL, so the NULL partition is
        // interned second — emit must still place it first.
        state.insert_batch(&nullable_pk_batch(
            &schema,
            vec![Some(1), None, Some(1)],
            vec![4, 9, 2],
        )?)?;
        // Second batch must land in the *same* NULL partition and evict 9.
        state.insert_batch(&nullable_pk_batch(
            &schema,
            vec![None, None, Some(2)],
            vec![3, 5, 8],
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "|    | 3   |",
                "|    | 5   |",
                "| 1  | 2   |",
                "| 1  | 4   |",
                "| 2  | 8   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// A `DESC` partition key must emit partitions in descending key order.
    /// Group indices are assigned in first-seen order, so this pins the
    /// partition key's `SortOptions` really being folded into the encoding
    /// the emit-time sort reads, rather than defaulting to ascending.
    #[tokio::test]
    async fn test_partitioned_topk_desc_partition_key_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_nullable_pk(
            1,
            SortOptions {
                descending: true,
                nulls_first: false,
            },
        )?;

        let batch = nullable_pk_batch(
            &schema,
            vec![Some(1), Some(3), Some(2), Some(3)],
            vec![10, 30, 20, 31],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 3  | 30  |",
                "| 2  | 20  |",
                "| 1  | 10  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// A multi-column partition key is encoded as one concatenated byte
    /// string, so emit ordering becomes a lexicographic comparison of those
    /// bytes across both columns rather than of a single column's.
    #[tokio::test]
    async fn test_partitioned_topk_multi_column_partition_key() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("pk_a", DataType::Int32, false),
            Field::new("pk_b", DataType::Utf8, false),
            Field::new("val", DataType::Int32, false),
        ]));

        let pk_a: Arc<dyn PhysicalExpr> = col("pk_a", schema.as_ref())?;
        let pk_b: Arc<dyn PhysicalExpr> = col("pk_b", schema.as_ref())?;
        let partition_ordering = [
            PhysicalSortExpr {
                expr: Arc::clone(&pk_a),
                options: SortOptions::default(),
            },
            PhysicalSortExpr {
                expr: Arc::clone(&pk_b),
                options: SortOptions::default(),
            },
        ];
        let order_expr = LexOrdering::from([PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: SortOptions::default(),
        }]);

        let mut state = PartitionedTopK::try_new(
            0,
            &schema,
            vec![pk_a, pk_b],
            build_sort_fields(&partition_ordering, &schema)?,
            order_expr,
            1,
            8,
            &Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            None,
        )?;

        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(vec![2, 1, 2, 1, 1])),
                Arc::new(StringArray::from(vec!["b", "b", "a", "a", "a"])),
                Arc::new(Int32Array::from(vec![20, 15, 25, 11, 10])),
            ],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+------+------+-----+",
                "| pk_a | pk_b | val |",
                "+------+------+-----+",
                "| 1    | a    | 10  |",
                "| 1    | b    | 15  |",
                "| 2    | a    | 25  |",
                "| 2    | b    | 20  |",
                "+------+------+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `PartitionedTopK` must run under a memory pool sized from `K` and the
    /// partition count, not from the input.
    ///
    /// Retained rows reference batches in the shared store, so what stays
    /// pinned is data-dependent in a way that `K` alone does not bound — this
    /// is the test that holds it down. A store entry keeps only the rows that
    /// batch contributed and is freed when its last row is evicted, so pinning
    /// converges instead of tracking the input; feeding 16 fully-admitted
    /// batches and asserting the total stays flat is what pins that.
    ///
    /// Sibling of `test_partitioned_topk_rank_runs_under_bounded_memory_pool`
    /// for the `ROW_NUMBER` path, which had no bounded-pool coverage.
    #[tokio::test]
    async fn test_partitioned_topk_runs_under_bounded_memory_pool() -> Result<()> {
        const P: i32 = 256;
        const ROWS_PER_PARTITION: i32 = 32;
        const ROWS: i32 = P * ROWS_PER_PARTITION;
        const BATCHES: i32 = 16;
        const K: usize = 2;

        let schema = pk_val_schema(false);
        let pks: Vec<i32> = (0..ROWS).map(|i| i % P).collect();
        // Batch b's values all beat batch b-1's, so every row of every batch is
        // admitted and every admission evicts. That is the maximum churn this
        // design can be put under -- a gather of the whole batch 16 times over,
        // every one of which must be handed back to the allocator as the next
        // batch supersedes it -- and it is the case where pinning that tracked
        // the input rather than converging would be obvious.
        let vals = |b: i32| -> Vec<i32> {
            (0..ROWS)
                .map(|i| (BATCHES - b) * ROWS_PER_PARTITION + i / P)
                .collect()
        };

        // Derived from the data so no byte constant here goes stale. The
        // operator needs a little over 4x the batch, most of it the two
        // row-encoding scratch buffers (partition key, ORDER BY key) sized to
        // hold a whole batch plus the one gathered batch the store pins; 4x
        // fails, so this bound is tight rather than slack. Charging a whole
        // batch per partition, as a per-partition store would, needs ~P = 256x.
        let batch_bytes =
            get_record_batch_memory_size(&pk_val_batch(&schema, pks.clone(), vals(0))?);
        let limit = 5 * batch_bytes;
        let runtime = RuntimeEnvBuilder::new()
            .with_memory_pool(Arc::new(GreedyMemoryPool::new(limit)))
            .build_arc()?;

        let (schema, mut state) = build_partitioned_topk_with_runtime(K, &runtime)?;

        let mut after_first = 0;
        for b in 0..BATCHES {
            let batch = pk_val_batch(&schema, pks.clone(), vals(b))?;
            state.insert_batch(&batch).map_err(|e| {
                exec_datafusion_err!(
                    "batch {b} of {BATCHES} failed under a {limit}-byte pool: {e}"
                )
            })?;
            if b == 0 {
                after_first = state.size();
            }
        }

        // Flat, not merely under the limit. Every batch was fully admitted, so
        // a store that failed to release a superseded entry would grow linearly
        // in the batch count here; the 2x slack absorbs hash-map and buffer
        // capacity growth but not a batch's worth of pinned rows.
        assert!(
            state.size() <= after_first * 2,
            "retention grew from {after_first} to {} bytes across {BATCHES} \
             batches; it tracks the input rather than K per partition",
            state.size()
        );

        // A pool that was never pressed proves nothing, so pin down the output:
        // K rows per partition, drawn from the last batch, whose values are the
        // smallest seen.
        let expected: Vec<(i32, i32)> = (0..P)
            .flat_map(|pk| [(pk, ROWS_PER_PARTITION), (pk, ROWS_PER_PARTITION + 1)])
            .collect();
        assert_eq!(pk_val_rows(state.emit()?).await?, expected);
        Ok(())
    }

    /// The bytes `emit` leaves pinned must stay accounted for until the stream
    /// is dropped.
    ///
    /// Retained rows reference batches in the shared store, so those batches are
    /// still held after `emit` returns, for as long as the stream lives. An
    /// `emit` that dropped its reservation instead would report zero while
    /// holding all of it — the one direction of accounting error that lets a
    /// pool overcommit. Asserting both sides catches the opposite mistake too:
    /// carrying the reservation but never releasing it.
    #[tokio::test]
    async fn test_partitioned_topk_emit_keeps_pinned_bytes_reserved() -> Result<()> {
        use datafusion_execution::memory_pool::MemoryPool;

        let pool = Arc::new(GreedyMemoryPool::new(16 * 1024 * 1024));
        let runtime = RuntimeEnvBuilder::new()
            .with_memory_pool(Arc::clone(&pool) as Arc<dyn MemoryPool>)
            .build_arc()?;

        let (schema, mut state) = build_partitioned_topk_with_runtime(2, &runtime)?;
        let pks: Vec<i32> = (0..64).map(|i| i % 8).collect();
        let vals: Vec<i32> = (0..64).collect();
        state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
        assert!(pool.reserved() > 0, "insert_batch must reserve");

        let stream = state.emit()?;
        assert!(
            pool.reserved() > 0,
            "emit released its reservation while the store's batches are still \
             pinned by the stream it returned"
        );

        // Consumes the stream, so it is dropped by the time this returns.
        let results: Vec<RecordBatch> = stream.try_collect().await?;
        assert_eq!(
            pool.reserved(),
            0,
            "the reservation must be released once the stream is dropped"
        );

        let rows: usize = results.iter().map(|b| b.num_rows()).sum();
        assert_eq!(rows, 16, "K = 2 for each of 8 partitions");
        Ok(())
    }

    /// `PartitionedTopKRank` must not charge (or pin) a whole input batch
    /// once per partition key that batch touches.
    ///
    /// Regression: the heap used to be handed `batch.clone()` — the full
    /// input batch — rather than a gather of just that partition's rows,
    /// so a batch spanning P partitions was counted P times over. With 500
    /// partitions in one batch that reported ~516x the batch size.
    ///
    /// Measured against the input batch's own size rather than against the
    /// `ROW_NUMBER` state on the same input: the two operators hold their
    /// retained rows differently, so a ratio between them tracks changes to
    /// either one and this test is about `RANK` alone.
    #[tokio::test]
    async fn test_partitioned_topk_rank_size_is_not_per_partition_batch() -> Result<()> {
        // The over-count factor was exactly the number of partitions sharing
        // a batch, so P is what makes the bug visible at all.
        const P: i32 = 500;
        // 8 rows per partition: enough for every partition's k=2 heap to fill
        // and then evict, so the heaps hold real state rather than sitting
        // half-empty in the fill phase.
        const ROWS: i32 = 4000;

        // Distinct values throughout: no ties, so RANK retains exactly K per
        // partition and nothing is held by the tie list. k=2 is the smallest k
        // with a distinct fill phase before eviction begins.
        let pks: Vec<i32> = (0..ROWS).map(|i| i % P).collect();
        let vals: Vec<i32> = (0..ROWS).map(|i| i / P).collect();

        let (schema, mut rk) = build_partitioned_topk_rank(2)?;
        let batch = pk_val_batch(&schema, pks, vals)?;
        let batch_size = get_record_batch_memory_size(&batch);
        rk.insert_batch(&batch)?;
        let rk_size = rk.size();

        // Just under 19x the input batch measured here, against ~516x for the bug:
        // the per-partition scratch buffers and heap headers at P=500 dominate
        // what is retained, which is why the correct figure is a double-digit
        // multiple at all. A 100x bar sits ~5x clear of both, so it neither
        // flakes when the size calculation is legitimately adjusted nor misses a
        // reintroduced per-partition batch charge.
        assert!(
            rk_size <= batch_size * 100,
            "RANK reported {rk_size} bytes holding K=2 rows from each of {P} \
             partitions of a {batch_size}-byte batch; a per-partition batch \
             charge has crept back in"
        );
        Ok(())
    }

    /// A boundary tie must retain only the tied rows, not the batch they
    /// arrived in.
    ///
    /// Regression: `TieEntry` used to hold the source `RecordBatch` plus
    /// indices, so one tied row pinned — and was charged for — a whole
    /// input batch, for as long as the boundary held. Across a stream of
    /// batches that made retained memory grow with the *input* size rather
    /// than with `K + ties`.
    #[tokio::test]
    async fn test_partitioned_topk_rank_ties_do_not_pin_input_batches() -> Result<()> {
        // k=1 makes every retained row after the very first one a boundary
        // tie, which is the state under test.
        let (schema, mut rk) = build_partitioned_topk_rank(1)?;

        // Each batch carries exactly one row tied at the boundary and 999
        // rows that are strictly worse and must be dropped. The 1000:1 ratio
        // is the point: holding the tied row costs a few bytes, holding the
        // batch it arrived in costs ~8 KB, so the two outcomes cannot be
        // confused.
        let mut vals = vec![100; 1000];
        vals[0] = 7;
        let batch = pk_val_batch(&schema, vec![1; 1000], vals)?;

        rk.insert_batch(&batch)?;
        let after_first = rk.size();
        for _ in 0..7 {
            rk.insert_batch(&batch)?;
        }
        let after_eight = rk.size();

        // Seven more batches retain seven more single rows. Correct growth is
        // ~8 bytes per batch (~56 total, just the tie-list slots); the bug grew
        // by a whole ~8 KB batch each time (~56 KB total). A 2000-byte bar sits
        // between the two with more than an order of magnitude of clearance on
        // each side.
        let growth = after_eight - after_first;
        assert!(
            growth < 2000,
            "tie list grew {growth} bytes over 7 batches that contributed \
             1 row each; it is holding the source batches"
        );
        Ok(())
    }

    /// The reservation must clear a *bounded* memory pool, not merely
    /// report a plausible `size()`.
    ///
    /// The two tests above check what `size()` computes; this one checks
    /// how that number is actually spent — `try_resize` against a real
    /// pool, which is what returned `ResourcesExhausted` to the user.
    ///
    /// No byte constant is asserted. The limit is derived from the input
    /// at run time, because the property under test is a ratio: retention
    /// must be a small multiple of *one* input batch no matter how many
    /// batches stream through, where whole-batch retention was
    /// (partitions x batch) and needed ~P times as much. Only the ratio
    /// has to hold as the size accounting is legitimately adjusted.
    #[tokio::test]
    async fn test_partitioned_topk_rank_runs_under_bounded_memory_pool() -> Result<()> {
        // P is the whole point: the old code pinned and charged one copy of
        // each batch per partition that batch touched, so it needed ~P x the
        // batch where the fix needs a constant multiple of it.
        const P: i32 = 256;
        const ROWS_PER_PARTITION: i32 = 32;
        const ROWS: i32 = P * ROWS_PER_PARTITION;
        const BATCHES: i32 = 16;
        const K: usize = 2;

        let schema = pk_val_schema(false);
        let pks: Vec<i32> = (0..ROWS).map(|i| i % P).collect();
        // Batch b's values all beat batch b-1's, so every batch is admitted
        // by every partition and the batch it displaces must be released —
        // the case that separates "charged once per batch" from "charged
        // once per partition per batch". Within a batch a partition's
        // values are distinct, so nothing ties at the boundary and each
        // partition keeps exactly K rows throughout.
        let vals = |b: i32| -> Vec<i32> {
            (0..ROWS)
                .map(|i| (BATCHES - b) * ROWS_PER_PARTITION + i / P)
                .collect()
        };

        // A budget of 32 batches, derived from the data so no byte constant
        // here goes stale. The operator legitimately holds ~8x the batch
        // (row-encoding scratch for one batch, plus per-partition heap and
        // map overhead), so this clears it ~4x over; the old whole-batch
        // retention needed ~P = 256x the batch, which is 8x past the limit.
        let batch_bytes =
            get_record_batch_memory_size(&pk_val_batch(&schema, pks.clone(), vals(0))?);
        let limit = 32 * batch_bytes;
        let runtime = RuntimeEnvBuilder::new()
            .with_memory_pool(Arc::new(GreedyMemoryPool::new(limit)))
            .build_arc()?;

        let (schema, mut rk) = build_partitioned_topk_rank_with_runtime(K, &runtime)?;

        let mut after_first = 0;
        for b in 0..BATCHES {
            let batch = pk_val_batch(&schema, pks.clone(), vals(b))?;
            rk.insert_batch(&batch).map_err(|e| {
                exec_datafusion_err!(
                    "batch {b} of {BATCHES} failed under a {limit}-byte pool: {e}"
                )
            })?;
            if b == 0 {
                after_first = rk.size();
            }
        }

        // Flat, not merely under the limit: the last 15 batches must not
        // have added retention (in practice this is exactly equal). The 2x
        // slack absorbs map and tie-list capacity growth, but not a batch's
        // worth of pinned rows.
        assert!(
            rk.size() <= after_first * 2,
            "retention grew from {after_first} to {} bytes across {BATCHES} \
             batches; it tracks the input rather than a bounded window of it",
            rk.size()
        );

        // A pool that was never pressed proves nothing, so pin down what the
        // operator produced: K rows per partition, drawn from the last batch,
        // whose values are the smallest seen.
        let expected: Vec<(i32, i32)> = (0..P)
            .flat_map(|pk| [(pk, ROWS_PER_PARTITION), (pk, ROWS_PER_PARTITION + 1)])
            .collect();
        assert_eq!(sorted_pk_val(rk.emit()?).await?, expected);
        Ok(())
    }

    /// One deterministic pseudo-random input shape for the differential
    /// tests below: a `k`, and the `(pks, vals)` batches to feed in.
    ///
    /// Shapes are deliberately tiny. These bugs live in how ties, partitions
    /// and batch boundaries interleave, not in volume, so many small shapes
    /// cover far more of that space than a few large ones — and they keep the
    /// O(n^2) brute-force reference cheap.
    struct DiffShape {
        seed: u64,
        k: usize,
        n_partitions: i32,
        n_values: i32,
        batches: Vec<(Vec<i32>, Vec<i32>)>,
    }

    impl std::fmt::Display for DiffShape {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(
                f,
                "seed={} k={} partitions={} values={} batches={}",
                self.seed,
                self.k,
                self.n_partitions,
                self.n_values,
                self.batches.len()
            )
        }
    }

    impl DiffShape {
        /// `max_values` caps the ORDER BY value domain. Keep it near `k` so
        /// rows tie above, at, and below the boundary frequently rather than
        /// by chance; raise it for an operator that bounds *distinct* values
        /// and so needs more than `k` of them before it will evict anything.
        fn new(seed: u64, max_values: i32) -> Self {
            use rand::rngs::StdRng;
            use rand::{Rng, SeedableRng};

            let mut rng = StdRng::seed_from_u64(seed);
            let k = rng.random_range(1..5usize);
            let n_partitions = rng.random_range(1..4i32);
            let n_values = rng.random_range(1..max_values);
            let n_batches = rng.random_range(1..5usize);

            let batches = (0..n_batches)
                .map(|_| {
                    let rows = rng.random_range(1..12usize);
                    let pks = (0..rows)
                        .map(|_| rng.random_range(0..n_partitions))
                        .collect();
                    let vals = (0..rows).map(|_| rng.random_range(0..n_values)).collect();
                    (pks, vals)
                })
                .collect();

            Self {
                seed,
                k,
                n_partitions,
                n_values,
                batches,
            }
        }

        /// Every `(pk, val)` fed in, across all batches.
        fn all_rows(&self) -> Vec<(i32, i32)> {
            self.batches
                .iter()
                .flat_map(|(pks, vals)| pks.iter().copied().zip(vals.iter().copied()))
                .collect()
        }

        /// Brute-force reference for `ROW_NUMBER`: per partition, the `k`
        /// smallest values by the ORDER BY key.
        ///
        /// Deliberately not expressed through [`Self::expected`]. That ranks a
        /// row by how many rows precede it, so with `k = 2` and values
        /// `[5, 5, 5]` every row ranks 1 and a `<= k` filter keeps all three —
        /// `RANK` semantics, not `ROW_NUMBER`, which keeps exactly two.
        ///
        /// Comparing `(pk, val)` pairs makes *which* of a tied group is kept
        /// unobservable, so this reference stays deterministic despite
        /// `DiffShape` generating ties on purpose.
        ///
        /// Built in emit order rather than sorted at the end: the `BTreeMap`
        /// walks partitions ascending and each partition's values are sorted
        /// ascending, which is exactly `(partition_key, order_key)` for the
        /// ASC/ASC sort options `build_partitioned_topk` uses. That makes this
        /// usable with [`pk_val_rows`], so the differential test checks the
        /// emitted order and not just the set.
        fn expected_row_number(&self) -> Vec<(i32, i32)> {
            let mut by_pk: std::collections::BTreeMap<i32, Vec<i32>> =
                std::collections::BTreeMap::new();
            for (pk, val) in self.all_rows() {
                by_pk.entry(pk).or_default().push(val);
            }
            let mut kept: Vec<(i32, i32)> = Vec::new();
            for (pk, mut vals) in by_pk {
                vals.sort_unstable();
                kept.extend(vals.into_iter().take(self.k).map(|v| (pk, v)));
            }
            kept
        }

        /// Brute-force reference: the sorted rows a `<= k` filter keeps, given
        /// `rank_of(all_rows, pk, val)` for the ranking function under test.
        fn expected(
            &self,
            rank_of: impl Fn(&[(i32, i32)], i32, i32) -> usize,
        ) -> Vec<(i32, i32)> {
            let all = self.all_rows();
            let mut kept: Vec<(i32, i32)> = all
                .iter()
                .copied()
                .filter(|&(pk, val)| rank_of(&all, pk, val) <= self.k)
                .collect();
            kept.sort_unstable();
            kept
        }
    }

    /// Drain an operator's output into `(pk, val)` pairs **in emit order**.
    ///
    /// Preferred over [`sorted_pk_val`] wherever the expected rows can be
    /// written in `(partition_key, order_key)` order, because emitting them in
    /// the wrong order is a real failure this then catches. Sorting here would
    /// hide it: a reversed `emit` passes a sorted comparison on every shape.
    async fn pk_val_rows(stream: SendableRecordBatchStream) -> Result<Vec<(i32, i32)>> {
        let batches: Vec<RecordBatch> = stream.try_collect().await?;
        let mut rows: Vec<(i32, i32)> = Vec::new();
        for b in &batches {
            let pk = b.column(0).as_primitive::<Int32Type>();
            let val = b.column(1).as_primitive::<Int32Type>();
            for i in 0..b.num_rows() {
                rows.push((pk.value(i), val.value(i)));
            }
        }
        Ok(rows)
    }

    /// [`pk_val_rows`] sorted, ready to compare against
    /// [`DiffShape::expected`].
    ///
    /// Asserts the rows arrived already in `(pk ASC, val ASC)` order before
    /// sorting them. That order is load-bearing rather than cosmetic — it is
    /// what `PartitionedTopKExec::compute_properties` advertises, and so what
    /// lets the window above it run `mode=Sorted` with no `SortExec` — and
    /// the content comparison this feeds would otherwise sort it away.
    async fn sorted_pk_val(stream: SendableRecordBatchStream) -> Result<Vec<(i32, i32)>> {
        let mut rows = pk_val_rows(stream).await?;
        assert!(
            rows.windows(2).all(|w| w[0] <= w[1]),
            "emitted rows are not in (pk, val) order: {rows:?}"
        );
        rows.sort_unstable();
        Ok(rows)
    }

    /// Randomized differential test for the plain `ROW_NUMBER` path.
    ///
    /// `PartitionedTopKRank` and `PartitionedTopKDenseRank` each had one of
    /// these; `ROW_NUMBER` did not, which left its retained-row storage
    /// without a randomized net.
    ///
    /// Compares in emit order, via [`pk_val_rows`] rather than
    /// [`sorted_pk_val`]: `(partition_key, order_key)` ordering is the
    /// operator's output contract, and a sorted comparison cannot see it —
    /// reversing both the partition sort and the within-partition order in
    /// `emit` leaves a sorted version of this test green on all 64 seeds.
    #[tokio::test]
    async fn test_partitioned_topk_matches_bruteforce() -> Result<()> {
        for seed in 0..64u64 {
            let shape = DiffShape::new(seed, 6);
            let (schema, mut state) = build_partitioned_topk(shape.k)?;
            for (pks, vals) in &shape.batches {
                state.insert_batch(&pk_val_batch(&schema, pks.clone(), vals.clone())?)?;
            }

            assert_eq!(
                pk_val_rows(state.emit()?).await?,
                shape.expected_row_number(),
                "{shape}"
            );
        }
        Ok(())
    }

    /// A row can be admitted and then superseded by a better row from the
    /// *same* batch, before that batch has been registered in the store.
    ///
    /// This is the case the use count has to get right: the superseded row's
    /// use is dropped on the in-flight count rather than through `unuse`, which
    /// would panic on an id the store has never seen. Every such row still ends
    /// up in the gather, so the surviving slot's row index has to account for
    /// admissions that no longer survive.
    ///
    /// Interleaving two partitions is what makes a slot pointing at the wrong
    /// gathered row visible: crossing them yields `(0, 2)` / `(1, 1)` instead
    /// of `(0, 1)` / `(1, 2)`, which a single-partition case could not tell
    /// apart from correct behaviour.
    #[tokio::test]
    async fn test_partitioned_topk_payload_survives_supersession() -> Result<()> {
        // pk 0 admits 9, then 3 supersedes it, then 1 supersedes that.
        // pk 1 admits 8, then 2 supersedes it.
        let (schema, mut state) = build_partitioned_topk(1)?;
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![0, 1, 0, 1, 0],
            vec![9, 8, 3, 2, 1],
        )?)?;

        assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 1), (1, 2)]);

        // With K = 2 a supersession replaces only the worst slot, so the
        // other retained row must keep pointing at its own gathered row.
        let (schema, mut state) = build_partitioned_topk(2)?;
        state.insert_batch(&pk_val_batch(&schema, vec![0, 0, 0], vec![4, 7, 5])?)?;

        assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 4), (0, 5)]);
        Ok(())
    }

    /// The store must release a gathered batch the moment its last referencing
    /// slot is evicted, and must never register a batch nothing references.
    ///
    /// This is the property that makes pinning converge rather than track the
    /// input. The bounded-pool test above asserts the *consequence* (total size
    /// stays flat); this asserts the mechanism directly, because a leak that
    /// happened to be offset by a shrinking buffer elsewhere would satisfy a
    /// total-size bound while still holding batches forever.
    #[tokio::test]
    async fn test_partitioned_topk_store_releases_superseded_batches() -> Result<()> {
        const K: usize = 2;
        let (schema, mut state) = build_partitioned_topk(K)?;

        // Batch 0 fills the single partition's heap, so it is referenced and
        // must be pinned.
        state.insert_batch(&pk_val_batch(&schema, vec![0, 0], vec![50, 60])?)?;
        assert_eq!(state.core.store.len(), 1, "the batch every slot points at");
        let first_id = *state.core.store.batches.keys().next().expect("one entry");

        // Batch 1 is entirely worse, so nothing is admitted and nothing may be
        // registered — a store that registered unconditionally would grow here.
        state.insert_batch(&pk_val_batch(&schema, vec![0, 0], vec![70, 80])?)?;
        assert_eq!(
            state.core.store.len(),
            1,
            "a fully-rejected batch must not be registered"
        );

        // Batch 2 supersedes both retained rows, so batch 0 loses its last
        // reference and must be dropped as batch 2 takes its place.
        state.insert_batch(&pk_val_batch(&schema, vec![0, 0], vec![10, 20])?)?;
        assert_eq!(
            state.core.store.len(),
            1,
            "superseded batch 0 must be released, not accumulated"
        );
        assert!(
            !state.core.store.batches.contains_key(&first_id),
            "the released entry must be the superseded one"
        );

        // Partial supersession: one of the two retained rows is replaced, so
        // both the old and the new batch are legitimately referenced.
        state.insert_batch(&pk_val_batch(&schema, vec![0], vec![5])?)?;
        assert_eq!(
            state.core.store.len(),
            2,
            "a batch still holding one live row must stay pinned"
        );

        assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 5), (0, 10)]);
        Ok(())
    }

    /// Pinned rows must stay proportional to the rows the heaps hold, even when
    /// releasing superseded batches alone cannot manage it.
    ///
    /// The sibling test above covers the easy shape: every batch supersedes the
    /// last one whole, so every entry's use count reaches zero and the store
    /// converges to one entry on its own. This is the shape where it does not.
    /// `val = |batch - partition|` makes batch `j` the owner of partition `j`'s
    /// winner, so all `B` entries keep exactly one live row and each stays
    /// resident holding every row it admitted. Releasing is powerless here —
    /// nothing is ever fully superseded — and without compaction the store
    /// pins `B(B+1)/2` rows (131,328 at `B = 512`, half the whole input) to
    /// retain `B`. That is the unbounded case: over-retention grows with `B`.
    #[tokio::test]
    async fn test_partitioned_topk_store_compacts_when_survivors_spread() -> Result<()> {
        const B: i32 = 512;

        let (schema, mut state) = build_partitioned_topk(1)?;
        for j in 0..B {
            let pks: Vec<i32> = (0..B).collect();
            let vals: Vec<i32> = (0..B).map(|p| (j - p).abs()).collect();
            state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
        }

        // Every partition holds its K = 1 row, so the ratio's denominator is B.
        assert_eq!(state.core.live_slots, B as usize);
        let pinned: usize = state
            .core
            .store
            .batches
            .values()
            .map(|e| e.batch.num_rows())
            .sum();
        assert_eq!(
            pinned, state.core.store.total_rows,
            "store row count is exact"
        );
        // An invariant, not a measurement: compaction runs at the end of
        // every `insert_batch`, so on return the store either never tripped the
        // guard or was just rewritten down to `live_slots`. Expressed through
        // the constant so tuning it cannot leave this stale. Measured 977 here
        // against 131,328 unfixed, so the bar bites by two orders of magnitude
        // at this B and the gap widens with it.
        let bound = B as usize * STORE_COMPACTION_RATIO;
        assert!(
            pinned <= bound,
            "{pinned} rows pinned to retain {} — above the {bound}-row bound, so \
             retention tracks the input rather than the rows held",
            state.core.live_slots
        );

        // Compaction rewrote every slot's coordinates, so the rows it resolves
        // at emit are the check that it repointed them correctly: partition p's
        // single retained row is the one whose value is 0, contributed by batch
        // p — a slot left pointing at a pre-compaction coordinate would surface
        // some other partition's row here. Compared in emit order, so this also
        // covers the ordering of a compacted, multi-chunk emit; no other test
        // reaches that path at all.
        let expected: Vec<(i32, i32)> = (0..B).map(|pk| (pk, 0)).collect();
        assert_eq!(pk_val_rows(state.emit()?).await?, expected);
        Ok(())
    }

    /// A store holding a *single* entry must still be compacted when that entry
    /// is mostly dead rows.
    ///
    /// Regression: compaction used to bail on `store.len() <= 1`, on the
    /// reasoning that one entry cannot compact to anything smaller. It can. An
    /// entry holds every row *admitted* from its batch, and a row admitted and
    /// then superseded within that same pass stays in the gather with nothing
    /// pointing at it — so a single entry is bounded by the input batch, not by
    /// `live_slots`.
    ///
    /// Descending values in one batch is the worst case and not an exotic one:
    /// every row beats the current worst, so all of them are admitted and `K`
    /// survive. `store.len() == 1` is also the state right after every
    /// compaction and on the first batch, so the old guard was live for the
    /// whole of a single-batch query.
    #[tokio::test]
    async fn test_partitioned_topk_store_compacts_a_single_oversized_entry() -> Result<()>
    {
        const ROWS: i32 = 200;

        let (schema, mut state) = build_partitioned_topk(1)?;
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![0; ROWS as usize],
            (0..ROWS).map(|i| ROWS - i).collect(),
        )?)?;

        assert_eq!(state.core.live_slots, 1, "K = 1 in a single partition");
        assert_eq!(
            state.core.store.len(),
            1,
            "one input batch, one gathered entry"
        );
        // The bound the ratio promises, which the old guard exempted this shape
        // from entirely: 200 rows stayed pinned to retain 1.
        assert!(
            state.core.store.total_rows <= state.core.live_slots * STORE_COMPACTION_RATIO,
            "{} rows pinned to retain {}; a single entry escaped compaction",
            state.core.store.total_rows,
            state.core.live_slots
        );

        // Compaction repointed the surviving slot, so emit still resolves it.
        assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 1)]);
        Ok(())
    }

    /// Every invariant the shared store's bookkeeping rests on, checked against
    /// a full recount of the heaps.
    ///
    /// The running totals (`live_slots`, `store.total_rows`,
    /// `store.batches_size`, each entry's `uses`) are maintained incrementally
    /// precisely so that neither `size()` nor compaction's guard has to
    /// walk the partitions. Nothing else re-derives them, so a drift in any one
    /// is invisible: an over-counted `uses` leaks an entry forever, an
    /// under-counted one drops a batch rows still point at, and a wrong
    /// `live_slots` silently disables the pinning bound.
    fn assert_store_invariants(state: &PartitionedTopK, label: &str) {
        let slots: Vec<StoreRef> = state
            .core
            .partitions
            .values()
            .flat_map(PartitionHeap::store_rows)
            .collect();
        assert_store_matches_slots(
            &state.core.store,
            state.core.live_slots,
            &slots,
            label,
        );

        // 5. What the operator reported to the pool is what it computes now.
        assert_eq!(
            state.core.reservation.size(),
            state.size(),
            "{label}: the reservation does not match size()"
        );
    }

    /// Sections 1–4 of [`assert_store_invariants`], for any operator on the
    /// shared store: `slots` is every retained row's store coordinates, heap
    /// or tie.
    fn assert_store_matches_slots(
        store: &RecordBatchStore,
        live_slots: usize,
        slots: &[StoreRef],
        label: &str,
    ) {
        // 1. `live_slots` is the number of slots actually held.
        assert_eq!(
            slots.len(),
            live_slots,
            "{label}: live_slots disagrees with the slots held"
        );

        // 2. Every slot points at a live entry and a row inside it, and each
        //    entry's `uses` is exactly the number of slots pointing into it.
        let mut refs: HashMap<u32, usize> = HashMap::new();
        for slot in slots {
            let entry = store.get(slot.batch_id).unwrap_or_else(|| {
                panic!(
                    "{label}: slot points at batch {} which the store does not hold",
                    slot.batch_id
                )
            });
            // Out of range, emit's interleave would read out of bounds (or
            // silently pick a different row).
            assert!(
                (slot.row as usize) < entry.batch.num_rows(),
                "{label}: slot row {} is outside entry {} ({} rows)",
                slot.row,
                slot.batch_id,
                entry.batch.num_rows()
            );
            *refs.entry(slot.batch_id).or_default() += 1;
        }
        assert_eq!(
            refs.len(),
            store.len(),
            "{label}: the store holds entries nothing points at"
        );
        for (id, entry) in &store.batches {
            let expected = refs.get(id).copied().unwrap_or(0);
            assert_eq!(
                entry.uses, expected,
                "{label}: entry {id} has uses={} but {expected} slots point at it",
                entry.uses
            );
        }

        // 3. The store's two running totals are exact, not estimates.
        let rows: usize = store.batches.values().map(|e| e.batch.num_rows()).sum();
        assert_eq!(rows, store.total_rows, "{label}: store.total_rows drifted");
        let mut counter = RecordBatchMemoryCounter::new();
        let bytes: usize = store
            .batches
            .values()
            .map(|e| counter.count_batch(&e.batch))
            .sum();
        assert_eq!(
            bytes, store.batches_size,
            "{label}: store.batches_size drifted"
        );

        // 4. The bound compaction exists to enforce. Without it, what stays
        //    pinned tracks the *input* rather than `partitions × K`.
        assert!(
            store.total_rows <= live_slots * STORE_COMPACTION_RATIO,
            "{label}: {} rows pinned to retain {live_slots}",
            store.total_rows
        );
    }

    /// Feed shapes designed to break the store's bookkeeping, checking every
    /// invariant after every batch and the output against brute force at the
    /// end.
    ///
    /// The shapes matter more than the count. `K = 1` with one partition per
    /// batch is the sparse-survivor case that makes a live row pin a whole
    /// gathered entry; a descending run at `K = 1` admits every row and keeps
    /// one, so the gather is nearly all dead on arrival and the pre-assigned
    /// batch id churns down to `uses == 1`; an all-ties batch admits nothing
    /// after the first `k` rows, so `uses == 0` and the id must go back to the
    /// next batch unconsumed.
    #[tokio::test]
    async fn test_partitioned_topk_store_bookkeeping_holds_under_stress() -> Result<()> {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        struct Case {
            name: &'static str,
            k: usize,
            partitions: i32,
            values: i32,
            batches: usize,
            rows: usize,
            /// Sort each batch's values descending, so every row is an
            /// admission that the next row supersedes.
            descending: bool,
            /// Give each batch a single partition, so survivors spread one per
            /// gathered entry.
            one_partition_per_batch: bool,
        }

        let cases = [
            Case {
                name: "k1_one_partition_per_batch",
                k: 1,
                partitions: 64,
                values: 1_000,
                batches: 64,
                rows: 16,
                descending: false,
                one_partition_per_batch: true,
            },
            Case {
                name: "k1_descending_runs",
                k: 1,
                partitions: 3,
                values: 1_000,
                batches: 20,
                rows: 50,
                descending: true,
                one_partition_per_batch: false,
            },
            Case {
                name: "all_ties_uses_zero",
                k: 2,
                partitions: 1,
                values: 1,
                batches: 20,
                rows: 30,
                descending: false,
                one_partition_per_batch: false,
            },
            Case {
                name: "k_exceeds_partition_size",
                k: 40,
                partitions: 50,
                values: 1_000,
                batches: 30,
                rows: 10,
                descending: false,
                one_partition_per_batch: false,
            },
            Case {
                name: "wide_churn",
                k: 3,
                partitions: 12,
                values: 20,
                batches: 40,
                rows: 64,
                descending: false,
                one_partition_per_batch: false,
            },
        ];

        for case in cases {
            for seed in 0..4u64 {
                let mut rng = StdRng::seed_from_u64(seed);
                let (schema, mut state) = build_partitioned_topk(case.k)?;
                let mut all_rows: Vec<(i32, i32)> = Vec::new();

                for b in 0..case.batches {
                    let pks: Vec<i32> = if case.one_partition_per_batch {
                        vec![(b as i32) % case.partitions; case.rows]
                    } else {
                        (0..case.rows)
                            .map(|_| rng.random_range(0..case.partitions))
                            .collect()
                    };
                    let mut vals: Vec<i32> = (0..case.rows)
                        .map(|_| rng.random_range(0..case.values))
                        .collect();
                    if case.descending {
                        vals.sort_unstable_by(|a, b| b.cmp(a));
                    }
                    all_rows.extend(pks.iter().copied().zip(vals.iter().copied()));

                    state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
                    assert_store_invariants(
                        &state,
                        &format!("{} seed {seed} batch {b}", case.name),
                    );
                }

                // Brute force: per partition, the k smallest values, emitted in
                // (pk, val) ascending order.
                let mut expected: Vec<(i32, i32)> = Vec::new();
                let mut pks: Vec<i32> = all_rows.iter().map(|&(p, _)| p).collect();
                pks.sort_unstable();
                pks.dedup();
                for pk in pks {
                    let mut vals: Vec<i32> = all_rows
                        .iter()
                        .filter(|&&(p, _)| p == pk)
                        .map(|&(_, v)| v)
                        .collect();
                    vals.sort_unstable();
                    vals.truncate(case.k);
                    expected.extend(vals.into_iter().map(|v| (pk, v)));
                }

                assert_eq!(
                    pk_val_rows(state.emit()?).await?,
                    expected,
                    "{} seed {seed}",
                    case.name
                );
            }
        }
        Ok(())
    }

    /// A batch whose every admission is superseded before the pass ends must
    /// not consume the batch id `next_batch_id` handed the slots.
    ///
    /// `insert_batch` points slots at an id before the gather exists, and skips
    /// `register` entirely when `uses` falls back to 0. If the id were consumed
    /// anyway the sequence would gap harmlessly, but if `register` ran with
    /// `uses == 0` the store would keep an entry nothing references — and
    /// `RecordBatchStore::compact`'s `first_id` would then collide with it.
    #[tokio::test]
    async fn test_partitioned_topk_unused_gather_id_is_reused() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk(1)?;

        // Batch 0: one partition, one row. Consumes id 0.
        state.insert_batch(&pk_val_batch(&schema, vec![0], vec![5])?)?;
        assert_eq!(
            state.core.store.next_batch_id(),
            1,
            "batch 0 consumed its id"
        );

        // Batch 1: every value is worse than the retained 5, so nothing is
        // admitted at all — `uses` never rises and the id is untouched. No
        // compaction either: neither total_rows nor live_slots moved, and the
        // guard already held when the previous call returned.
        state.insert_batch(&pk_val_batch(&schema, vec![0, 0, 0], vec![7, 8, 9])?)?;
        assert_eq!(state.core.store.next_batch_id(), 1, "no admission, no id");
        assert_eq!(state.core.store.len(), 1);
        assert_store_invariants(&state, "after a batch with no admissions");

        // Batch 2: rows are admitted but each is superseded by a later row of
        // the *same* batch, and the first evicts the row from batch 0. The
        // gather therefore holds 3 rows for 1 live slot, which trips
        // compaction — so this consumes two ids, the gather's and the
        // compacted chunk's.
        state.insert_batch(&pk_val_batch(&schema, vec![0, 0, 0], vec![4, 3, 2])?)?;
        assert_store_invariants(&state, "after a self-superseding batch");
        assert_eq!(state.core.store.len(), 1, "batch 0's entry was released");
        assert_eq!(
            state.core.store.total_rows, 1,
            "compaction dropped the dead rows"
        );
        let after_compaction = state.core.store.next_batch_id();

        // Batch 3: admitted then superseded within the batch, ending worse than
        // the retained 2 — so `uses` returns to 0 and the id is handed back.
        state.insert_batch(&pk_val_batch(&schema, vec![0, 0], vec![3, 6])?)?;
        assert_eq!(
            state.core.store.next_batch_id(),
            after_compaction,
            "every admission was superseded, so the id must be reusable"
        );
        assert_store_invariants(&state, "after a fully superseded batch");

        assert_eq!(pk_val_rows(state.emit()?).await?, vec![(0, 2)]);
        Ok(())
    }

    /// `size()` must account for the ORDER BY keys the heaps hold by value.
    ///
    /// Every other term of `size()` is either a fixed struct, a `RowConverter`,
    /// or the store — all of which exist whatever the key width. `heaps_bytes`
    /// is the only term that grows with `partitions × K × key_width`, and with
    /// an `Int32` key it is a rounding error, so a test on the narrow schema
    /// cannot see it go missing. With a wide string key it is the dominant
    /// per-partition term: dropping the `heaps_bytes` fold leaves the operator
    /// under-reporting megabytes to the pool.
    #[tokio::test]
    async fn test_partitioned_topk_size_accounts_for_retained_keys() -> Result<()> {
        const PARTITIONS: usize = 200;
        const K: usize = 4;
        const KEY_WIDTH: usize = 512;

        let schema = Arc::new(Schema::new(vec![
            Field::new("pk", DataType::Int32, false),
            Field::new("val", DataType::Utf8, false),
        ]));
        let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
        let partition_ordering = [PhysicalSortExpr {
            expr: Arc::clone(&pk_expr),
            options: SortOptions::default(),
        }];
        let order_expr = LexOrdering::from([PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: SortOptions::default(),
        }]);
        let mut state = PartitionedTopK::try_new(
            0,
            &schema,
            vec![pk_expr],
            build_sort_fields(&partition_ordering, &schema)?,
            order_expr,
            K,
            8,
            &Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            None,
        )?;

        let empty = state.size();

        // Feed K rows for each partition, all retained, each key KEY_WIDTH wide.
        let mut pks: Vec<i32> = Vec::new();
        let mut vals: Vec<String> = Vec::new();
        for p in 0..PARTITIONS {
            for i in 0..K {
                pks.push(p as i32);
                vals.push(format!("{p:0>width$}{i}", width = KEY_WIDTH - 1));
            }
        }
        state.insert_batch(&RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(pks)),
                Arc::new(StringArray::from(vals)),
            ],
        )?)?;

        assert_eq!(
            state.core.live_slots,
            PARTITIONS * K,
            "every row should have been retained"
        );

        // The keys alone are this many bytes; `size()` has to have grown by at
        // least that much, on top of whatever the store and the map cost.
        let key_bytes = PARTITIONS * K * KEY_WIDTH;
        assert!(
            state.core.heaps_bytes >= key_bytes,
            "heaps_bytes is {} but the retained keys are at least {key_bytes} bytes",
            state.core.heaps_bytes
        );
        assert!(
            state.size() >= empty + key_bytes,
            "size() grew by {} for {key_bytes} bytes of retained keys",
            state.size() - empty
        );
        // And the interned partition keys are counted separately.
        assert!(
            state.core.index_bytes >= PARTITIONS,
            "index_bytes is {} for {PARTITIONS} interned keys",
            state.core.index_bytes
        );
        Ok(())
    }

    /// Randomized differential test for `PartitionedTopKDenseRank`.
    ///
    /// Same harness as [`test_partitioned_topk_rank_bookkeeping_tracks_recompute`],
    /// differing only in the ranking formula and a wider value domain:
    /// DENSE_RANK bounds *distinct* values, so a partition needs more than
    /// `k` of them before it evicts anything, and eviction is what the
    /// admission pre-filter guards. A pre-filter that wrongly rejects
    /// boundary-equal rows is caught by seed 6.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_matches_bruteforce() -> Result<()> {
        for seed in 0..64u64 {
            let shape = DiffShape::new(seed, 8);
            let (schema, mut state) = build_partitioned_topk_dense_rank(shape.k)?;
            for (pks, vals) in &shape.batches {
                state.insert_batch(&pk_val_batch(&schema, pks.clone(), vals.clone())?)?;
            }

            // DENSE_RANK: 1 + the number of *distinct* strictly smaller values.
            let expected = shape.expected(|rows, pk, val| {
                1 + rows
                    .iter()
                    .filter(|&&(p, v)| p == pk && v < val)
                    .map(|&(_, v)| v)
                    .collect::<std::collections::BTreeSet<_>>()
                    .len()
            });

            assert_eq!(sorted_pk_val(state.emit()?).await?, expected, "{shape}");
        }
        Ok(())
    }

    /// `DenseRankPartitionState::contents_bytes` is maintained
    /// incrementally at four mutation sites (append to an existing ob
    /// group, insert a new one with room, evict-then-insert, and the
    /// key/entry buffer growth each can trigger). Drift there would
    /// silently give the reservation a wrong total, so check it against a
    /// recompute over the same randomized workload the correctness
    /// differential test uses — its shapes are tuned to exercise
    /// eviction, which is the case with the most bookkeeping.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_contents_bytes_tracks_recompute()
    -> Result<()> {
        let mut saw_eviction = false;
        for seed in 0..64u64 {
            let shape = DiffShape::new(seed, 8);
            let (schema, mut state) = build_partitioned_topk_dense_rank(shape.k)?;
            for (pks, vals) in &shape.batches {
                state.insert_batch(&pk_val_batch(&schema, pks.clone(), vals.clone())?)?;
                // Check after every batch, not just at the end: a
                // compensating pair of errors within one batch would
                // survive an end-only assertion.
                for (pk, partition) in &state.states {
                    assert_eq!(
                        partition.contents_bytes,
                        partition.recompute_contents_bytes(),
                        "seed {seed}, partition {pk:?}: {shape}"
                    );
                }
            }
            saw_eviction |= state.metrics.row_replacements.value() > 0;
        }
        // Guards the guard: if the shapes stopped evicting, case C would
        // go unchecked and this test would still pass.
        assert!(saw_eviction, "workload never evicted a group");
        Ok(())
    }

    /// The `(pk Int32, val Int32)` schema every `PartitionedTopK*` test
    /// builds against. `val_nullable` is what the null-ordering tests vary.
    fn pk_val_schema(val_nullable: bool) -> Arc<Schema> {
        Arc::new(Schema::new(vec![
            Field::new("pk", DataType::Int32, false),
            Field::new("val", DataType::Int32, val_nullable),
        ]))
    }

    fn pk_val_batch(
        schema: &Arc<Schema>,
        pks: Vec<i32>,
        vals: Vec<i32>,
    ) -> Result<RecordBatch> {
        Ok(RecordBatch::try_new(
            Arc::clone(schema),
            vec![
                Arc::new(Int32Array::from(pks)),
                Arc::new(Int32Array::from(vals)),
            ],
        )?)
    }

    /// Variant of [`pk_val_batch`] that accepts nullable `val`s. Used by
    /// tests that exercise null-ordering through the shared encoder.
    fn nullable_pk_val_batch(
        schema: &Arc<Schema>,
        pks: Vec<i32>,
        vals: Vec<Option<i32>>,
    ) -> Result<RecordBatch> {
        Ok(RecordBatch::try_new(
            Arc::clone(schema),
            vec![
                Arc::new(Int32Array::from(pks)),
                Arc::new(Int32Array::from(vals)),
            ],
        )?)
    }

    /// Companion to [`test_topk_output_batches_metric_counts_emitted_batches`] for
    /// the partitioned emit path: rows from several per-partition heaps are
    /// interleaved into `batch_size` chunks, so the metric must count the
    /// emitted chunks rather than the per-partition heaps they came from.
    #[tokio::test]
    async fn test_partitioned_topk_output_batches_metric_counts_emitted_batches()
    -> Result<()> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("pk", DataType::Int32, false),
            Field::new("val", DataType::Int32, false),
        ]));
        let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
        let partition_ordering = vec![PhysicalSortExpr {
            expr: Arc::clone(&pk_expr),
            options: SortOptions::default(),
        }];
        let metrics = ExecutionPlanMetricsSet::new();
        // 3 per-partition heaps of 2 rows each, emitted as 2 batches of 3
        let order_ordering = [PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: SortOptions::default(),
        }];
        let mut state = PartitionedTopK::try_new(
            0,
            &schema,
            vec![pk_expr],
            build_sort_fields(&partition_ordering, &schema)?,
            LexOrdering::from(order_ordering.clone()),
            2,
            3, // batch_size
            &Arc::new(RuntimeEnv::default()),
            &metrics,
            None,
        )?;

        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 1, 2, 2, 3, 3],
            vec![10, 5, 20, 15, 30, 25],
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        let row_counts: Vec<usize> = results.iter().map(|b| b.num_rows()).collect();
        assert_eq!(row_counts, vec![3, 3]);
        assert_eq!(output_batches_and_rows(&metrics), (2, 6));

        Ok(())
    }

    /// With a `ranking_field`, `emit` appends the retained rows'
    /// `ROW_NUMBER()`: 1-based within each partition, restarting at every
    /// partition boundary, and independent of how the partitions' rows were
    /// interleaved on the way in.
    #[tokio::test]
    async fn test_partitioned_topk_emits_row_number_column() -> Result<()> {
        let rn_field = Arc::new(Field::new("rn", DataType::UInt64, false));
        let (schema, mut state) =
            build_emitting(PartitionedTopK::try_new, 3, Arc::clone(&rn_field))?;

        // pk=1 vals: 30, 10, 20, 40 → top-3 ASC = [10, 20, 30] (40 evicted)
        // pk=2 vals: 5              → top-3 ASC = [5]
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 2, 1, 1, 1],
            vec![30, 5, 10, 20, 40],
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_eq!(
            results[0].schema().field(2),
            rn_field.as_ref(),
            "the appended field is the one the caller asked for"
        );
        assert_batches_eq!(
            &[
                "+----+-----+----+",
                "| pk | val | rn |",
                "+----+-----+----+",
                "| 1  | 10  | 1  |",
                "| 1  | 20  | 2  |",
                "| 1  | 30  | 3  |",
                "| 2  | 5   | 1  |",
                "+----+-----+----+",
            ],
            &results
        );
        Ok(())
    }

    /// Input for the ranking-column chunk tests: partition 1 holds vals 1..=4
    /// three times each, partition 2 holds two 5s, split over two input
    /// batches. Every policy retains more rows than the builders' batch size
    /// of 8, so the ranks have to be sliced correctly across output chunks.
    fn ranking_chunk_batches(schema: &SchemaRef) -> Result<[RecordBatch; 2]> {
        Ok([
            pk_val_batch(schema, vec![1; 7], vec![1, 1, 1, 2, 2, 2, 3])?,
            pk_val_batch(schema, vec![1, 1, 1, 1, 1, 2, 2], vec![3, 3, 4, 4, 4, 5, 5])?,
        ])
    }

    /// `(val, rank)` for every emitted row, and how many batches carried them.
    fn vals_and_ranks(batches: &[RecordBatch]) -> (Vec<(i32, u64)>, usize) {
        let mut rows = Vec::new();
        for batch in batches {
            let vals = batch.column(1).as_primitive::<Int32Type>();
            let ranks = batch.column(2).as_primitive::<UInt64Type>();
            rows.extend(
                vals.values()
                    .iter()
                    .copied()
                    .zip(ranks.values().iter().copied()),
            );
        }
        (rows, batches.len())
    }

    /// `ROW_NUMBER()` keeps counting across an output chunk boundary, and
    /// restarts at the next partition.
    #[tokio::test]
    async fn test_partitioned_topk_row_number_column_spans_output_chunks() -> Result<()> {
        let rn = Arc::new(Field::new("rn", DataType::UInt64, false));
        let (schema, mut state) = build_emitting(PartitionedTopK::try_new, 10, rn)?;
        for batch in ranking_chunk_batches(&schema)? {
            state.insert_batch(&batch)?;
        }
        let results: Vec<_> = state.emit()?.try_collect().await?;
        let (rows, chunks) = vals_and_ranks(&results);
        assert_eq!(chunks, 2);
        assert_eq!(
            rows,
            vec![
                (1, 1),
                (1, 2),
                (1, 3),
                (2, 4),
                (2, 5),
                (2, 6),
                (3, 7),
                (3, 8),
                // second chunk
                (3, 9),
                (4, 10),
                (5, 1),
                (5, 2),
            ]
        );
        Ok(())
    }

    /// `RANK()` across an output chunk boundary: the second chunk opens inside
    /// the 3s and ends with the boundary ties, so heap ranks and tie ranks are
    /// both read past the first chunk.
    #[tokio::test]
    async fn test_partitioned_topk_rank_column_spans_output_chunks() -> Result<()> {
        let rk = Arc::new(Field::new("rk", DataType::UInt64, false));
        let (schema, mut state) = build_emitting(PartitionedTopKRank::try_new, 10, rk)?;
        for batch in ranking_chunk_batches(&schema)? {
            state.insert_batch(&batch)?;
        }
        let results: Vec<_> = state.emit()?.try_collect().await?;
        let (rows, chunks) = vals_and_ranks(&results);
        assert_eq!(chunks, 2);
        assert_eq!(
            rows,
            vec![
                (1, 1),
                (1, 1),
                (1, 1),
                (2, 4),
                (2, 4),
                (2, 4),
                (3, 7),
                (3, 7),
                // second chunk: the last 3, then the heap's 4 and its two ties
                (3, 7),
                (4, 10),
                (4, 10),
                (4, 10),
                (5, 1),
                (5, 1),
            ]
        );
        Ok(())
    }

    /// `DENSE_RANK()` across an output chunk boundary, which its emit flushes
    /// separately from the other two policies.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_column_spans_output_chunks() -> Result<()> {
        let dr = Arc::new(Field::new("dr", DataType::UInt64, false));
        let (schema, mut state) =
            build_emitting(PartitionedTopKDenseRank::try_new, 3, dr)?;
        for batch in ranking_chunk_batches(&schema)? {
            state.insert_batch(&batch)?;
        }
        let results: Vec<_> = state.emit()?.try_collect().await?;
        let (rows, chunks) = vals_and_ranks(&results);
        assert_eq!(chunks, 2);
        assert_eq!(
            rows,
            vec![
                (1, 1),
                (1, 1),
                (1, 1),
                (2, 2),
                (2, 2),
                (2, 2),
                (3, 3),
                (3, 3),
                // second chunk
                (3, 3),
                (5, 1),
                (5, 1),
            ]
        );
        Ok(())
    }

    /// Multiple distinct partition keys interleaved within a single
    /// input batch — grouping rows by partition key, per-partition heap eviction,
    /// and partition-key-ordered emit must all behave correctly.
    #[tokio::test]
    async fn test_partitioned_topk_multi_partition_within_batch() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk(2)?;

        // pk=1 vals: 10, 5, 8 → top-2 ASC = [5, 8]
        // pk=2 vals: 20, 15   → top-2 ASC = [15, 20]
        // pk=3 vals: 7        → top-2 ASC = [7]
        let batch =
            pk_val_batch(&schema, vec![1, 2, 1, 2, 1, 3], vec![10, 20, 5, 15, 8, 7])?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 8   |",
                "| 2  | 15  |",
                "| 2  | 20  |",
                "| 3  | 7   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// State must accumulate across `insert_batch` calls: a partition
    /// key seen in batch 1 should still own its heap when batch 2
    /// arrives, and a row in batch 2 that beats the existing K-th
    /// best should evict the loser.
    #[tokio::test]
    async fn test_partitioned_topk_cross_batch_eviction() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk(2)?;

        // Batch 1: pk=1 fills the heap with [50, 40].
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![50, 40])?)?;

        // Batch 2: pk=1 sees a smaller value (10) — it must evict 50.
        // pk=2 appears for the first time mid-stream.
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 2, 1],
            vec![10, 99, 60], // 60 > 40 stays on top, gets discarded
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 10  |",
                "| 1  | 40  |",
                "| 2  | 99  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// Empty input must produce an empty output stream, not panic.
    #[tokio::test]
    async fn test_partitioned_topk_empty_input() -> Result<()> {
        let (_schema, state) = build_partitioned_topk(3)?;
        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert!(results.is_empty(), "empty input → empty output");
        Ok(())
    }

    /// `fetch = 1` is a common case (rn = 1 filter). The heap should
    /// hold exactly one row per partition: the partition's minimum.
    #[tokio::test]
    async fn test_partitioned_topk_fetch_one() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk(1)?;
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 1, 2, 2, 3],
            vec![3, 1, 9, 4, 7],
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 1   |",
                "| 2  | 4   |",
                "| 3  | 7   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `ORDER BY val DESC` exercises the shared encoder's sort-direction
    /// handling: the row converter must flip the sort sign for `val` so
    /// that larger values compare smaller in row-encoded form. Each
    /// partition should keep its top-K *largest* values.
    #[tokio::test]
    async fn test_partitioned_topk_desc_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_with_opts(
            2,
            SortOptions {
                descending: true,
                nulls_first: false,
            },
            false,
        )?;

        // pk=1 vals: 10, 5, 8, 12 → top-2 DESC = [12, 10]
        // pk=2 vals: 20, 15, 25   → top-2 DESC = [25, 20]
        let batch = pk_val_batch(
            &schema,
            vec![1, 2, 1, 2, 1, 1, 2],
            vec![10, 20, 5, 15, 8, 12, 25],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 12  |",
                "| 1  | 10  |",
                "| 2  | 25  |",
                "| 2  | 20  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// NULL sort values exercise the shared encoder's null-ordering
    /// handling. With `ASC NULLS LAST`, NULLs sort *after* every
    /// non-NULL value, so a partition whose only non-NULL value beats
    /// a NULL must evict the NULL when `K = 1`. A partition that holds
    /// only NULLs must still emit them.
    #[tokio::test]
    async fn test_partitioned_topk_nulls_last_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_with_opts(
            1,
            SortOptions {
                descending: false,
                nulls_first: false,
            },
            true,
        )?;

        // pk=1 vals: NULL, 7, NULL → top-1 ASC NULLS LAST = [7]
        // pk=2 vals: NULL          → top-1                 = [NULL]
        // pk=3 vals: NULL, 4, 2    → top-1                 = [2]
        let batch = nullable_pk_val_batch(
            &schema,
            vec![1, 2, 1, 1, 3, 3, 3],
            vec![None, None, Some(7), None, None, Some(4), Some(2)],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 7   |",
                "| 2  |     |",
                "| 3  | 2   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `ASC NULLS FIRST` (the `SortOptions::default()`) sorts NULLs
    /// *before* every non-NULL value, so under `fetch = K` a partition's
    /// NULLs are kept preferentially over larger non-NULL values.
    #[tokio::test]
    async fn test_partitioned_topk_nulls_first_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_with_opts(
            2,
            SortOptions {
                descending: false,
                nulls_first: true,
            },
            true,
        )?;

        // pk=1 vals: NULL, 5, NULL, 8 → top-2 ASC NULLS FIRST = [NULL, NULL]
        // pk=2 vals: 7, NULL          → top-2                  = [NULL, 7]
        // pk=3 vals: 3, 1             → top-2                  = [1, 3]
        let batch = nullable_pk_val_batch(
            &schema,
            vec![1, 2, 1, 3, 1, 2, 1, 3],
            vec![
                None,
                Some(7),
                Some(5),
                Some(3),
                None,
                None,
                Some(8),
                Some(1),
            ],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  |     |",
                "| 1  |     |",
                "| 2  |     |",
                "| 2  | 7   |",
                "| 3  | 1   |",
                "| 3  | 3   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    // ====================================================================
    // PartitionedTopKRank operator tests
    //
    // These mirror the PartitionedTopK tests above plus three RANK-specific
    // cases for the Equal / boundary-shift / boundary-unchanged-eviction
    // arms in `PartitionedTopKRank::insert_batch`.
    // ====================================================================

    /// Builds a `(pk Int32, val Int32)` schema and a `PartitionedTopKRank`
    /// keyed on `pk ASC` (partition) and `val ASC` (ORDER BY).
    fn build_partitioned_topk_rank(
        k: usize,
    ) -> Result<(Arc<Schema>, PartitionedTopKRank)> {
        build_partitioned_topk_rank_with_opts(k, SortOptions::default(), false)
    }

    /// Variant of [`build_partitioned_topk_rank`] that lets the test pick
    /// the `val` column's `SortOptions` (direction, null ordering) and
    /// nullability.
    fn build_partitioned_topk_rank_with_opts(
        k: usize,
        val_sort_options: SortOptions,
        val_nullable: bool,
    ) -> Result<(Arc<Schema>, PartitionedTopKRank)> {
        build_pk_val_state(
            PartitionedTopKRank::try_new,
            k,
            val_sort_options,
            val_nullable,
            &Arc::new(RuntimeEnv::default()),
            None,
        )
    }

    /// Variant of [`build_partitioned_topk_rank`] that takes the
    /// [`RuntimeEnv`] to register the reservation against, so a test can
    /// bound the memory pool the operator draws from.
    fn build_partitioned_topk_rank_with_runtime(
        k: usize,
        runtime: &Arc<RuntimeEnv>,
    ) -> Result<(Arc<Schema>, PartitionedTopKRank)> {
        build_pk_val_state(
            PartitionedTopKRank::try_new,
            k,
            SortOptions::default(),
            false,
            runtime,
            None,
        )
    }

    /// Multiple distinct partition keys interleaved within a single
    /// input batch — grouping rows by partition key, per-partition heap eviction,
    /// and partition-key-ordered emit must all behave correctly. No
    /// ties: result should match a `ROW_NUMBER` top-K under the same K.
    #[tokio::test]
    async fn test_partitioned_topk_rank_multi_partition_within_batch() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(2)?;

        // pk=1 vals: 10, 5, 8 → top-2 ASC = [5, 8]
        // pk=2 vals: 20, 15   → top-2 ASC = [15, 20]
        // pk=3 vals: 7        → top-2 ASC = [7]
        let batch =
            pk_val_batch(&schema, vec![1, 2, 1, 2, 1, 3], vec![10, 20, 5, 15, 8, 7])?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 8   |",
                "| 2  | 15  |",
                "| 2  | 20  |",
                "| 3  | 7   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// State must accumulate across `insert_batch` calls. A row in
    /// batch 2 that's strictly better than the existing K-th must
    /// evict it; an evicted row whose bytes match the new boundary
    /// moves to the tie list, still pointing into the prior batch's entry.
    #[tokio::test]
    async fn test_partitioned_topk_rank_cross_batch_eviction() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(2)?;

        // Batch 1: pk=1 fills the heap with [50, 40].
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![50, 40])?)?;

        // Batch 2: pk=1 sees a smaller value (10) — it must evict 50;
        // 60 > 40 so it's dropped. pk=2 appears mid-stream.
        state.insert_batch(&pk_val_batch(&schema, vec![1, 2, 1], vec![10, 99, 60])?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 10  |",
                "| 1  | 40  |",
                "| 2  | 99  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// Empty input must produce an empty output stream, not panic.
    #[tokio::test]
    async fn test_partitioned_topk_rank_empty_input() -> Result<()> {
        let (_schema, state) = build_partitioned_topk_rank(3)?;
        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert!(results.is_empty(), "empty input → empty output");
        Ok(())
    }

    /// `fetch = 1` is a common case (rk = 1 filter) and exercises the
    /// boundary-defined-immediately path: after the first admission per
    /// partition the heap is full, so every subsequent row goes through
    /// full Equal/Greater/Less classification.
    #[tokio::test]
    async fn test_partitioned_topk_rank_fetch_one() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(1)?;
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 1, 2, 2, 3],
            vec![3, 1, 9, 4, 7],
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 1   |",
                "| 2  | 4   |",
                "| 3  | 7   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `ORDER BY val DESC` exercises the shared encoder's sort-direction
    /// handling: the row converter flips the sort sign for `val` so
    /// larger values compare smaller in row-encoded form. Each
    /// partition keeps its top-K *largest* values.
    #[tokio::test]
    async fn test_partitioned_topk_rank_desc_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank_with_opts(
            2,
            SortOptions {
                descending: true,
                nulls_first: false,
            },
            false,
        )?;

        // pk=1 vals: 10, 5, 8, 12 → top-2 DESC = [12, 10]
        // pk=2 vals: 20, 15, 25   → top-2 DESC = [25, 20]
        let batch = pk_val_batch(
            &schema,
            vec![1, 2, 1, 2, 1, 1, 2],
            vec![10, 20, 5, 15, 8, 12, 25],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 12  |",
                "| 1  | 10  |",
                "| 2  | 25  |",
                "| 2  | 20  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// NULL sort values exercise the shared encoder's null-ordering
    /// handling. With `ASC NULLS LAST`, NULLs sort *after* every
    /// non-NULL value, so a partition whose only non-NULL value beats
    /// a NULL must evict the NULL when `K = 1`. A partition that holds
    /// only NULLs must still emit them.
    #[tokio::test]
    async fn test_partitioned_topk_rank_nulls_last_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank_with_opts(
            1,
            SortOptions {
                descending: false,
                nulls_first: false,
            },
            true,
        )?;

        // pk=1 vals: NULL, 7, NULL → top-1 ASC NULLS LAST = [7]
        // pk=2 vals: NULL          → top-1                 = [NULL]
        // pk=3 vals: NULL, 4, 2    → top-1                 = [2]
        let batch = nullable_pk_val_batch(
            &schema,
            vec![1, 2, 1, 1, 3, 3, 3],
            vec![None, None, Some(7), None, None, Some(4), Some(2)],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 7   |",
                "| 2  |     |",
                "| 3  | 2   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `ASC NULLS FIRST` (the `SortOptions::default()`) sorts NULLs
    /// *before* every non-NULL value, so under `fetch = K` a partition's
    /// NULLs are kept preferentially over larger non-NULL values.
    #[tokio::test]
    async fn test_partitioned_topk_rank_nulls_first_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank_with_opts(
            2,
            SortOptions {
                descending: false,
                nulls_first: true,
            },
            true,
        )?;

        // pk=1 vals: NULL, 5, NULL, 8 → top-2 ASC NULLS FIRST = [NULL, NULL]
        // pk=2 vals: 7, NULL          → top-2                  = [NULL, 7]
        // pk=3 vals: 3, 1             → top-2                  = [1, 3]
        let batch = nullable_pk_val_batch(
            &schema,
            vec![1, 2, 1, 3, 1, 2, 1, 3],
            vec![
                None,
                Some(7),
                Some(5),
                Some(3),
                None,
                None,
                Some(8),
                Some(1),
            ],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  |     |",
                "| 1  |     |",
                "| 2  |     |",
                "| 2  | 7   |",
                "| 3  | 1   |",
                "| 3  | 3   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// RANK-specific: heap fills with K rows tied at the same OB value,
    /// then more rows at that same value arrive. They take the Equal arm
    /// (heap is full, its root's key equals the row's) and accumulate as ties, while
    /// strictly-greater rows are dropped. All retained rows have rank 1.
    #[tokio::test]
    async fn test_partitioned_topk_rank_boundary_ties_retained() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(2)?;

        // pk=1 vals: 5, 5, 10, 5
        //   - first two 5s fill the heap (max=None until heap reaches K=2)
        //   - third row 10 > 5 → drop (Greater)
        //   - fourth row 5 == 5 → push to ties (Equal)
        // Sorted RANKs: 5→1, 5→1, 5→1, 10→4. WHERE rk ≤ 2 keeps the three 5s.
        let batch = pk_val_batch(&schema, vec![1, 1, 1, 1], vec![5, 5, 10, 5])?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 5   |",
                "| 1  | 5   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// With a `ranking_field`, RANK's `emit` appends each retained row's
    /// `RANK()`. The interesting rows are the boundary ties, which are emitted
    /// *after* the heap's rows and must carry the rank of the first heap row
    /// holding the boundary key rather than their own position.
    #[tokio::test]
    async fn test_partitioned_topk_rank_emits_rank_column() -> Result<()> {
        let rk_field = Arc::new(Field::new("rk", DataType::UInt64, false));
        let (schema, mut state) =
            build_emitting(PartitionedTopKRank::try_new, 2, Arc::clone(&rk_field))?;

        // pk=1 vals 10, 20, 20: heap fills with [10, 20], the second 20 ties at
        //   the boundary. True RANKs: 10→1, 20→2, 20→2.
        // pk=2 vals 5, 5:       both tie at rank 1 inside the heap.
        // pk=3 vals 7, 7, 7:    the boundary key fills the whole heap and the
        //   third 7 ties at it, so the tie's rank is the boundary's first
        //   position (1), not the heap's length (2).
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 1, 1, 2, 2, 3, 3, 3],
            vec![10, 20, 20, 5, 5, 7, 7, 7],
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_eq!(results[0].schema().field(2), rk_field.as_ref());
        assert_batches_eq!(
            &[
                "+----+-----+----+",
                "| pk | val | rk |",
                "+----+-----+----+",
                "| 1  | 10  | 1  |",
                "| 1  | 20  | 2  |",
                "| 1  | 20  | 2  |",
                "| 2  | 5   | 1  |",
                "| 2  | 5   | 1  |",
                "| 3  | 7   | 1  |",
                "| 3  | 7   | 1  |",
                "| 3  | 7   | 1  |",
                "+----+-----+----+",
            ],
            &results
        );
        Ok(())
    }

    /// RANK's emitted column must agree with the window function it replaces
    /// when an eviction leaves the boundary where it was: the evicted row
    /// still ties with the new root, so it moves to the tie list, and its rank
    /// then comes from the boundary rather than from a heap position.
    #[tokio::test]
    async fn test_partitioned_topk_rank_emits_rank_after_boundary_moves() -> Result<()> {
        let rk_field = Arc::new(Field::new("rk", DataType::UInt64, false));
        let (schema, mut state) =
            build_emitting(PartitionedTopKRank::try_new, 2, Arc::clone(&rk_field))?;

        // Arrive as 20, 20, 10: the heap fills with [20, 20], then 10 evicts one
        // 20, whose bytes equal the new boundary (20) so it moves to the ties.
        // True RANKs over {10, 20, 20}: 10→1, 20→2, 20→2.
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![20, 20])?)?;
        state.insert_batch(&pk_val_batch(&schema, vec![1], vec![10])?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+----+",
                "| pk | val | rk |",
                "+----+-----+----+",
                "| 1  | 10  | 1  |",
                "| 1  | 20  | 2  |",
                "| 1  | 20  | 2  |",
                "+----+-----+----+",
            ],
            &results
        );
        Ok(())
    }

    /// Tie rows are emitted in the same `EmitState` chunks as heap rows, so
    /// they must be counted in `output_rows` once, not once as ties and again
    /// as part of the chunk that holds them.
    #[tokio::test]
    async fn test_partitioned_topk_rank_output_rows_counts_ties_once() -> Result<()> {
        let schema = pk_val_schema(false);
        let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
        let pk_sort_expr = PhysicalSortExpr {
            expr: Arc::clone(&pk_expr),
            options: SortOptions::default(),
        };
        let val_sort_expr = PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: SortOptions::default(),
        };
        let metrics = ExecutionPlanMetricsSet::new();
        let mut state = PartitionedTopKRank::try_new(
            0,
            &schema,
            vec![pk_expr],
            build_sort_fields(&[pk_sort_expr], &schema)?,
            LexOrdering::from([val_sort_expr]),
            2,
            8, // batch_size
            &Arc::new(RuntimeEnv::default()),
            &metrics,
            None,
        )?;

        // Two 5s fill the heap, the third 5 is retained as a tie.
        let batch = pk_val_batch(&schema, vec![1, 1, 1, 1], vec![5, 5, 10, 5])?;
        state.insert_batch(&batch)?;

        let results: Vec<RecordBatch> = state.emit()?.try_collect().await?;
        let emitted_rows: usize = results.iter().map(|b| b.num_rows()).sum();
        assert_eq!(emitted_rows, 3);
        assert_eq!(
            output_batches_and_rows(&metrics),
            (results.len(), emitted_rows)
        );
        Ok(())
    }

    /// RANK-specific: heap fills with K rows tied at value V, ties accumulate
    /// at V, then a strictly-better row arrives whose admission shifts the
    /// boundary strictly below V. The boundary-changed branch must release
    /// every tie, including those admitted earlier in the same batch —
    /// otherwise the now-rank-> K rows at value V would leak into output.
    #[tokio::test]
    async fn test_partitioned_topk_rank_boundary_shifts_clears_ties() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(2)?;

        // pk=1 vals: 10, 10, 10, 5, 3
        //   - first two 10s fill heap (max=10)
        //   - third 10 → Equal → ties=[row 2]
        //   - 5 < 10 → admit, evict 10 → heap={5,10}, max=10 (unchanged).
        //       The evicted 10 moves to ties: ties=[row 2, evicted].
        //   - 3 < 10 → admit, evict 10 → heap={3,5}, max=5 (CHANGED).
        //       Release the evicted 10 and every tie.
        // Sorted RANKs: 3→1, 5→2, 10→3, 10→3, 10→3. WHERE rk ≤ 2 → [3, 5].
        let batch = pk_val_batch(&schema, vec![1, 1, 1, 1, 1], vec![10, 10, 10, 5, 3])?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 3   |",
                "| 1  | 5   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `row_replacements` counts every admission, to the heap or to ties, as
    /// it does for `PartitionedTopK`. Nothing is evicted below, so the count
    /// is exactly the rows retained.
    #[tokio::test]
    async fn test_partitioned_topk_rank_row_replacements_counts_ties() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(2)?;

        // pk=1 vals: 10, 10, 10, 20, 10, 5
        //   - two 10s fill the heap (2 admissions)
        //   - 10 → Equal → tie (3); 20 → Greater → dropped; 10 → tie (4)
        //   - 5 < 10 → admit, evict 10, boundary unchanged → the evicted 10
        //       moves to ties (5)
        let batch =
            pk_val_batch(&schema, vec![1, 1, 1, 1, 1, 1], vec![10, 10, 10, 20, 10, 5])?;
        state.insert_batch(&batch)?;
        assert_eq!(state.core.metrics.row_replacements.value(), 5);

        let results: Vec<_> = state.emit()?.try_collect().await?;
        let emitted: usize = results.iter().map(RecordBatch::num_rows).sum();
        assert_eq!(emitted, 5);
        Ok(())
    }

    /// A boundary move frees the partition's tie list rather than clearing
    /// it, so a partition that once held many ties does not keep their
    /// capacity, and `ties_bytes` gives the bytes back.
    #[tokio::test]
    async fn test_partitioned_topk_rank_boundary_move_frees_tie_capacity() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(2)?;

        // pk=1 vals: 10 ×5, 5, 3
        //   - two 10s fill the heap, three more 10s are ties
        //   - 5 < 10 → evict 10, boundary still 10 → the evicted 10 is a tie
        //   - 3 < 10 → evict 10, boundary moves to 5 → every tie released
        let batch = pk_val_batch(&schema, vec![1; 7], vec![10, 10, 10, 10, 10, 5, 3])?;
        state.insert_batch(&batch)?;

        let partition = state
            .core
            .partitions
            .values()
            .next()
            .expect("one partition");
        assert!(partition.ties.is_empty());
        assert_eq!(partition.ties.capacity(), 0, "tie capacity must be freed");
        assert_eq!(state.ties_bytes, 0);
        assert_eq!(
            rank_recompute(&state),
            (state.core.heaps_bytes, 0, state.core.index_bytes)
        );
        Ok(())
    }

    /// A `PartitionedTopKRank` over `schema`, partitioned by `pk`, ordered by
    /// `val` ascending.
    fn build_partitioned_topk_rank_for(
        schema: &Arc<Schema>,
        k: usize,
        batch_size: usize,
    ) -> Result<PartitionedTopKRank> {
        let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
        let partition_sort_fields = build_sort_fields(
            &[PhysicalSortExpr {
                expr: Arc::clone(&pk_expr),
                options: SortOptions::default(),
            }],
            schema,
        )?;
        let order_expr = LexOrdering::from([PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: SortOptions::default(),
        }]);
        PartitionedTopKRank::try_new(
            0,
            schema,
            vec![pk_expr],
            partition_sort_fields,
            order_expr,
            k,
            batch_size,
            &Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            None,
        )
    }

    /// Input in descending order, so under `ORDER BY val ASC` every row after
    /// the heap fills beats the boundary and takes the eviction path that
    /// swaps key buffers with `evicted_key`. Keys vary in length, so the swap
    /// moves buffers of different capacities between the heap and
    /// `evicted_key`, and `heaps_bytes` must still match a recompute.
    #[tokio::test]
    async fn test_partitioned_topk_rank_sorted_input_evicts_every_row() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("pk", DataType::Int32, false),
            Field::new("val", DataType::Utf8, false),
        ]));
        let mut state = build_partitioned_topk_rank_for(&schema, 2, 8)?;

        // Two equal keys fill the heap, then strictly descending keys of
        // lengths 1, 6, 1, 6, 1, 9, 1. "y" evicts one "z…" and the boundary
        // stays at the other, so the evicted row moves to ties; every later
        // eviction moves the boundary and releases what is tied.
        let vals = [
            "zzzzzzzzz",
            "zzzzzzzzz",
            "y",
            "xxxxxx",
            "w",
            "cccccc",
            "c",
            "bbbbbbbbb",
            "a",
        ];
        for (i, chunk) in vals.chunks(3).enumerate() {
            let batch = RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(vec![1; chunk.len()])),
                    Arc::new(StringArray::from(chunk.to_vec())),
                ],
            )?;
            state.insert_batch(&batch)?;
            if i == 0 {
                let partition = state
                    .core
                    .partitions
                    .values()
                    .next()
                    .expect("one partition");
                assert_eq!(partition.ties.len(), 1, "\"y\" must leave a tie");
            }
            let (heaps, ties, index) = rank_recompute(&state);
            assert_eq!(state.core.heaps_bytes, heaps, "heaps_bytes");
            assert_eq!(state.ties_bytes, ties, "ties_bytes");
            assert_eq!(state.core.index_bytes, index, "index_bytes");
        }

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----------+",
                "| pk | val       |",
                "+----+-----------+",
                "| 1  | a         |",
                "| 1  | bbbbbbbbb |",
                "+----+-----------+",
            ],
            &results
        );
        Ok(())
    }

    /// `interleave_referenced` is `interleave_record_batch` restricted to the
    /// batches a chunk uses: the same rows come out, and `remap` is left
    /// clean for the next chunk. Every batch has its own dictionary, as when
    /// each input batch was decoded separately.
    #[test]
    fn test_interleave_referenced_matches_interleave_over_all() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![Field::new(
            "d",
            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
            false,
        )]));
        let batches: Vec<RecordBatch> = (0..4)
            .map(|b| {
                let mut builder = StringDictionaryBuilder::<Int32Type>::new();
                for row in 0..3 {
                    builder.append_value(format!("b{b}r{row}"));
                }
                RecordBatch::try_new(
                    Arc::clone(&schema),
                    vec![Arc::new(builder.finish())],
                )
            })
            .collect::<std::result::Result<_, _>>()?;
        let all: Vec<&RecordBatch> = batches.iter().collect();
        let as_strings = |batch: &RecordBatch| -> Result<Vec<String>> {
            let col = arrow::compute::cast(batch.column(0), &DataType::Utf8)?;
            Ok(col
                .as_string::<i32>()
                .iter()
                .map(|v| v.unwrap().to_string())
                .collect())
        };

        let mut remap = vec![usize::MAX; batches.len()];
        // Chunks touching one, two and all batches, out of order and revisiting
        // a batch the previous chunk used at a different local position.
        let chunks: [&[(usize, usize)]; 3] = [
            &[(2, 0), (2, 2)],
            &[(3, 1), (2, 1), (3, 0)],
            &[(1, 2), (0, 0), (3, 2), (2, 0), (1, 1)],
        ];
        for chunk in chunks {
            let got = interleave_referenced(&batches, chunk, &mut remap)?;
            let want = interleave_record_batch(&all, chunk)?;
            assert_eq!(as_strings(&got)?, as_strings(&want)?, "chunk {chunk:?}");
            assert!(remap.iter().all(|&r| r == usize::MAX), "remap left dirty");
        }
        Ok(())
    }

    /// The reviewer's emit shape on #25468, for RANK: input clustered by
    /// partition key, every retained row a tie so nothing is compacted, and a
    /// Dictionary payload with one dictionary per input batch. The store holds
    /// four batches while each 8-row chunk uses two, so every chunk exercises
    /// the remap from store positions to chunk-local ones.
    #[tokio::test]
    async fn test_partitioned_topk_rank_emit_dictionary_chunks_use_few_batches()
    -> Result<()> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("pk", DataType::Int32, false),
            Field::new("val", DataType::Int32, false),
            Field::new(
                "d",
                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
                false,
            ),
        ]));
        let mut state = build_partitioned_topk_rank_for(&schema, 2, 8)?;

        // Four batches, batch b holding partitions 2b and 2b+1, six rows each,
        // every row tied at val 0: all 48 rows are retained.
        for b in 0..4 {
            let mut pks = Vec::new();
            let mut builder = StringDictionaryBuilder::<Int32Type>::new();
            for pk in [2 * b, 2 * b + 1] {
                for row in 0..6 {
                    pks.push(pk);
                    builder.append_value(format!("p{pk}r{row}"));
                }
            }
            let batch = RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(pks)),
                    Arc::new(Int32Array::from(vec![0; 12])),
                    Arc::new(builder.finish()),
                ],
            )?;
            state.insert_batch(&batch)?;
        }
        assert_eq!(
            state.core.store.len(),
            4,
            "every input batch stays in the store"
        );

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_eq!(
            results
                .iter()
                .map(RecordBatch::num_rows)
                .collect::<Vec<_>>(),
            vec![8; 6]
        );
        // Tied rows emit in no particular order within a partition, so compare
        // per-partition sorted.
        let mut emitted: Vec<(i32, String)> = Vec::new();
        for batch in &results {
            let pks = batch.column(0).as_primitive::<Int32Type>();
            let d = arrow::compute::cast(batch.column(2), &DataType::Utf8)?;
            let d = d.as_string::<i32>();
            for i in 0..batch.num_rows() {
                emitted.push((pks.value(i), d.value(i).to_string()));
            }
        }
        let pks_in_order: Vec<i32> = emitted.iter().map(|(pk, _)| *pk).collect();
        assert!(pks_in_order.is_sorted(), "partitions emit in key order");
        emitted.sort();
        let expected: Vec<(i32, String)> = (0..8)
            .flat_map(|pk| (0..6).map(move |row| (pk, format!("p{pk}r{row}"))))
            .collect();
        assert_eq!(emitted, expected);
        Ok(())
    }

    /// RANK-specific: heap has multiple rows at boundary value V, then a
    /// strictly-better row arrives. The heap evicts one V, but its root
    /// is still V — boundary unchanged. The evicted V row must move to
    /// the tie list; without that branch a `rk <= K` query would silently
    /// lose a tied row.
    #[tokio::test]
    async fn test_partitioned_topk_rank_eviction_at_unchanged_boundary() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(2)?;

        // pk=1 vals: 10, 10, 5
        //   - first two 10s fill the heap (max=10)
        //   - 5 < 10 → admit, evict 10. New heap={5,10}, max=10 (unchanged).
        //       Push the evicted 10 to ties.
        // Sorted RANKs: 5→1, 10→2, 10→2. WHERE rk ≤ 2 → all 3 rows.
        let batch = pk_val_batch(&schema, vec![1, 1, 1], vec![10, 10, 5])?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 10  |",
                "| 1  | 10  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// The byte totals `PartitionedTopKRank::size` reads, recomputed from the
    /// partitions: `(heaps_bytes, ties_bytes, index_bytes)`. `heaps_bytes`
    /// includes `evicted_key`, which trades buffers with heap keys.
    fn rank_recompute(state: &PartitionedTopKRank) -> (usize, usize, usize) {
        let (mut heaps, mut ties, mut index) = (state.evicted_key.capacity(), 0, 0);
        for (pk, partition) in &state.core.partitions {
            index += pk.len();
            heaps += partition.heap.inner.capacity() * size_of::<PartitionSlot>()
                + partition
                    .heap
                    .slots()
                    .map(|slot| slot.key.capacity())
                    .sum::<usize>();
            ties += partition.ties.capacity() * size_of::<StoreRef>();
        }
        (heaps, ties, index)
    }

    /// Every retained row's store coordinates, heap and ties.
    fn rank_slots(state: &PartitionedTopKRank) -> Vec<StoreRef> {
        state
            .core
            .partitions
            .values()
            .flat_map(RankPartitionState::store_rows)
            .collect()
    }

    /// Randomized differential test for `PartitionedTopKRank`, checking the
    /// shared-store bookkeeping after every batch as well as the output.
    ///
    /// The retention rule is subtle — a K-bounded heap plus a boundary-tie
    /// list that must be discarded the moment the K-th-best ORDER BY value
    /// improves — and it turns on how partitions, ties and batch boundaries
    /// interleave. After every batch, [`assert_store_matches_slots`] checks
    /// that each retained row, heap or tie, holds exactly one use of the
    /// entry it points into, and the running totals `size()` reads are
    /// checked against a recompute. The use check is what catches a slot that
    /// moves to the tie list without its use, a tie released against the
    /// wrong entry, or an in-flight release that forgets the local count —
    /// each leaves the store either panicking later or pinning a batch
    /// forever, and none is visible in the emitted rows.
    #[tokio::test]
    async fn test_partitioned_topk_rank_bookkeeping_tracks_recompute() -> Result<()> {
        let (mut saw_ties, mut saw_compaction) = (false, false);
        for seed in 0..256u64 {
            let shape = DiffShape::new(seed, 6);
            let (schema, mut state) = build_partitioned_topk_rank(shape.k)?;
            for (pks, vals) in &shape.batches {
                let next_id = state.core.store.next_batch_id();
                state.insert_batch(&pk_val_batch(&schema, pks.clone(), vals.clone())?)?;
                // A batch takes at most one id; any more went to compaction.
                saw_compaction |= state.core.store.next_batch_id() > next_id + 1;
                saw_ties |= state.core.partitions.values().any(|p| !p.ties.is_empty());

                assert_store_matches_slots(
                    &state.core.store,
                    state.core.live_slots,
                    &rank_slots(&state),
                    &shape.to_string(),
                );
                let (heaps, ties, index) = rank_recompute(&state);
                assert_eq!(state.core.heaps_bytes, heaps, "heaps_bytes: {shape}");
                assert_eq!(state.ties_bytes, ties, "ties_bytes: {shape}");
                assert_eq!(state.core.index_bytes, index, "index_bytes: {shape}");
                assert_eq!(
                    state.core.reservation.size(),
                    state.size(),
                    "reservation vs size(): {shape}"
                );
            }

            let expected = shape.expected(|rows, pk, val| {
                1 + rows.iter().filter(|&&(p, v)| p == pk && v < val).count()
            });
            assert_eq!(sorted_pk_val(state.emit()?).await?, expected, "{shape}");
        }
        // Guards the guard: shapes that never tie or never compact would leave
        // the paths this is about unchecked.
        assert!(saw_ties, "no shape retained a tie");
        assert!(saw_compaction, "no shape compacted the store");
        Ok(())
    }

    /// Ties are store slots like heap rows, so they are subject to the same
    /// pinning as [`test_partitioned_topk_store_compacts_a_single_oversized_entry`]
    /// guards against for `ROW_NUMBER`: a batch's entry stays resident while
    /// any one of its rows is retained.
    ///
    /// Batch `j` gives every partition `p` a tie pair at `|j - p|`, so
    /// partition `p` keeps improving until batch `p` and is then fixed at a
    /// tie pair of zeros. Each batch's entry therefore keeps two live rows
    /// forever while its other admissions are superseded: without
    /// compaction the store would hold ~B² rows to retain 2B.
    #[tokio::test]
    async fn test_partitioned_topk_rank_store_bounded_when_ties_spread_thinly()
    -> Result<()> {
        const B: i32 = 64;
        let (schema, mut state) = build_partitioned_topk_rank(1)?;
        for j in 0..B {
            let pks: Vec<i32> = (0..B).flat_map(|p| [p, p]).collect();
            let vals: Vec<i32> = (0..B)
                .flat_map(|p| {
                    let v = (j - p).abs();
                    [v, v]
                })
                .collect();
            state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;
            assert!(
                state.core.store.total_rows
                    <= STORE_COMPACTION_RATIO * state.core.live_slots,
                "batch {j}: store holds {} rows for {} retained",
                state.core.store.total_rows,
                state.core.live_slots
            );
        }
        let expected: Vec<(i32, i32)> = (0..B).flat_map(|p| [(p, 0), (p, 0)]).collect();
        assert_eq!(pk_val_rows(state.emit()?).await?, expected);
        Ok(())
    }

    /// A boundary move releases every tie of the partition, which can come
    /// from earlier batches and from the batch in flight, in any
    /// interleaving: ties released by run must hand each use back to the
    /// right place, the store for an earlier batch and the local count for
    /// the in-flight one.
    #[tokio::test]
    async fn test_partitioned_topk_rank_boundary_move_releases_ties_across_batches()
    -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_rank(2)?;

        // Heap {10, 10} and ties [10, 10]: four slots into one store entry.
        state.insert_batch(&pk_val_batch(&schema, vec![1; 4], vec![10; 4])?)?;
        assert_eq!((state.core.store.len(), state.core.live_slots), (1, 4));

        // 10 ties, from this batch. 3 evicts a 10 but the root is still 10, so
        // the evicted row moves to the ties. 1 evicts the last 10 and the root
        // becomes 3, releasing the evicted row and every tie: runs of
        // [first, first, this, first] batch.
        state.insert_batch(&pk_val_batch(&schema, vec![1; 3], vec![10, 3, 1])?)?;

        // The first batch's entry is freed. This batch's gather holds all
        // three of its admissions, two of them still retained.
        assert_eq!((state.core.store.len(), state.core.live_slots), (1, 2));
        let entry = state.core.store.batches.values().next().expect("one entry");
        assert_eq!((entry.batch.num_rows(), entry.uses), (3, 2));

        assert_eq!(pk_val_rows(state.emit()?).await?, vec![(1, 1), (1, 3)]);
        Ok(())
    }

    /// Ties from every partition a batch touches share that batch's single
    /// store entry, so they are charged once.
    ///
    /// Regression for #23326: ties used to be materialized — and charged —
    /// once per partition, which with every row tied at `K = 1` across 4096
    /// partitions multiplied the reservation by the partition count.
    #[tokio::test]
    async fn test_partitioned_topk_rank_ties_share_one_store_entry() -> Result<()> {
        const P: i32 = 4096;
        let (schema, mut state) = build_partitioned_topk_rank(1)?;
        let batch =
            pk_val_batch(&schema, (0..4 * P).map(|i| i % P).collect(), vec![0; 16384])?;
        state.insert_batch(&batch)?;

        // Every row ties: one heap row plus three ties per partition.
        assert_eq!(state.core.live_slots, 4 * P as usize);
        assert_eq!(state.core.store.len(), 1);
        assert!(
            state.core.store.batches_size <= 2 * get_record_batch_memory_size(&batch),
            "store charges {} bytes for one {}-byte batch",
            state.core.store.batches_size,
            get_record_batch_memory_size(&batch)
        );
        Ok(())
    }

    // ====================================================================
    // PartitionedTopKDenseRank operator tests
    //
    // These mirror the RANK tests plus DENSE_RANK-specific cases: rows
    // sharing an ob key coalesce into one `GroupEntry`, unbounded
    // rows-per-distinct-key, and eviction removes the entire max group
    // when a strictly-smaller distinct ob arrives.
    // ====================================================================

    /// Builds a `(pk Int32, val Int32)` schema and a
    /// `PartitionedTopKDenseRank` keyed on `pk ASC` (partition) and
    /// `val ASC` (ORDER BY).
    fn build_partitioned_topk_dense_rank(
        k: usize,
    ) -> Result<(Arc<Schema>, PartitionedTopKDenseRank)> {
        build_partitioned_topk_dense_rank_with_opts(k, SortOptions::default(), false)
    }

    fn build_partitioned_topk_dense_rank_with_opts(
        k: usize,
        val_sort_options: SortOptions,
        val_nullable: bool,
    ) -> Result<(Arc<Schema>, PartitionedTopKDenseRank)> {
        build_pk_val_state(
            PartitionedTopKDenseRank::try_new,
            k,
            val_sort_options,
            val_nullable,
            &Arc::new(RuntimeEnv::default()),
            None,
        )
    }

    /// Single-batch DENSE_RANK top-2 across multiple partitions with
    /// distinct ob values only — should behave identically to a
    /// ROW_NUMBER top-2. Exercises per-partition grouping + emit order.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_multi_partition_within_batch() -> Result<()>
    {
        let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;

        // pk=1 vals: 10, 5, 8 → distinct-top-2 ASC = {5, 8}
        // pk=2 vals: 20, 15   → distinct-top-2 ASC = {15, 20}
        // pk=3 vals: 7        → distinct-top-2 ASC = {7}
        let batch =
            pk_val_batch(&schema, vec![1, 2, 1, 2, 1, 3], vec![10, 20, 5, 15, 8, 7])?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 8   |",
                "| 2  | 15  |",
                "| 2  | 20  |",
                "| 3  | 7   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// With a `ranking_field`, DENSE_RANK's `emit` appends each retained row's
    /// `DENSE_RANK()`: the 1-based index of its distinct ORDER BY value, so
    /// every row of a tied group shares one value and the counter does not skip
    /// over group sizes the way `RANK` does.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_emits_rank_column() -> Result<()> {
        let dr_field = Arc::new(Field::new("dr", DataType::UInt64, false));
        let (schema, mut state) =
            build_emitting(PartitionedTopKDenseRank::try_new, 2, Arc::clone(&dr_field))?;

        // pk=1 vals 10, 10, 20, 30: the 2 distinct-smallest are 10 and 20, so
        //   DENSE_RANKs are 10→1, 10→1, 20→2 and 30 is dropped. Note RANK would
        //   have given the 20 rank 3, not 2.
        // pk=2 vals 7, 7:          one distinct value, both dense rank 1.
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 1, 1, 1, 2, 2],
            vec![10, 10, 20, 30, 7, 7],
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_eq!(results[0].schema().field(2), dr_field.as_ref());
        assert_batches_eq!(
            &[
                "+----+-----+----+",
                "| pk | val | dr |",
                "+----+-----+----+",
                "| 1  | 10  | 1  |",
                "| 1  | 10  | 1  |",
                "| 1  | 20  | 2  |",
                "| 2  | 7   | 1  |",
                "| 2  | 7   | 1  |",
                "+----+-----+----+",
            ],
            &results
        );
        Ok(())
    }

    /// DENSE_RANK groups accumulate across batches, and a group's rows can come
    /// from several source batches — each gathered separately at emit time. The
    /// rank must be per *group*, not per gathered batch.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_emits_rank_across_batches() -> Result<()> {
        let dr_field = Arc::new(Field::new("dr", DataType::UInt64, false));
        let (schema, mut state) =
            build_emitting(PartitionedTopKDenseRank::try_new, 2, Arc::clone(&dr_field))?;

        // Both groups (10 and 20) collect a row from each of the two batches.
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![20, 10])?)?;
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![10, 20])?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+----+",
                "| pk | val | dr |",
                "+----+-----+----+",
                "| 1  | 10  | 1  |",
                "| 1  | 10  | 1  |",
                "| 1  | 20  | 2  |",
                "| 1  | 20  | 2  |",
                "+----+-----+----+",
            ],
            &results
        );
        Ok(())
    }

    /// DENSE_RANK-specific: heavy ties within a batch. All rows at each
    /// distinct ob value must be kept — within-call bucketing groups them
    /// into one `GroupEntry` per distinct ob.
    ///
    /// vals per partition (sorted logically):
    ///   pk=1: 1, 1, 1, 2, 2, 3, 3, 3, 4
    ///   distinct-top-2 = {1, 2} → all 5 rows at those values retained.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_heavy_ties_coalesced() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;

        let batch = pk_val_batch(
            &schema,
            vec![1, 1, 1, 1, 1, 1, 1, 1, 1],
            vec![1, 3, 1, 2, 3, 1, 2, 3, 4],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 1   |",
                "| 1  | 1   |",
                "| 1  | 1   |",
                "| 1  | 2   |",
                "| 1  | 2   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// Rows tied at the same ob across two source batches must both
    /// land under the same map key as separate `GroupEntry`s — one per
    /// source batch — but emit as a single contiguous run.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_cross_batch_same_key() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;

        // Batch 1: pk=1 with ob values {5, 5, 8}. groups after: {5→[..], 8→[..]}.
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1, 1], vec![5, 5, 8])?)?;

        // Batch 2: pk=1 with more 5s and an 8, plus a 20 that's dropped.
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1, 1], vec![5, 8, 20])?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 5   |",
                "| 1  | 5   |",
                "| 1  | 8   |",
                "| 1  | 8   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// Refactor guard: the full RANK-style path in one run — multi-partition
    /// per-batch grouping, within-batch bucketing of scattered same-ob rows,
    /// cross-batch append to an existing group, cross-batch new-key insert,
    /// and cross-batch eviction of a whole max group. Every `GroupEntry` is
    /// built from its own source batch (no cross-batch coalescing), so the
    /// retained rows must be exactly the K=2 smallest distinct ob values
    /// per partition with all their rows, regardless of arrival order.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_multi_batch_multi_partition() -> Result<()>
    {
        let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;

        // Batch 1 interleaves pk=1 and pk=2, with same-ob rows scattered:
        //   pk=1 vals: 10, 20, 10, 20, 10  → {10:[×3], 20:[×2]}
        //   pk=2 vals: 100, 100            → {100:[×2]}
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 2, 1, 1, 2, 1, 1],
            vec![10, 100, 20, 20, 100, 10, 10],
        )?)?;

        // Batch 2:
        //   pk=1 vals: 20, 5, 10 → append a 20, insert 5 (evicts the whole
        //              20 group), append a 10 → retained distinct {5, 10}.
        //   pk=2 vals: 50        → insert 5th... new key, room → {50, 100}.
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 2, 1, 1],
            vec![20, 50, 5, 10],
        )?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        // pk=1: val=5 (×1 from batch 2), val=10 (×3 batch 1 + ×1 batch 2 = ×4).
        //       All 20s dropped (evicted). pk=2: val=50 (×1), val=100 (×2).
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 10  |",
                "| 1  | 10  |",
                "| 1  | 10  |",
                "| 1  | 10  |",
                "| 2  | 50  |",
                "| 2  | 100 |",
                "| 2  | 100 |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `emit` rebuilds the `interleave` batch slice per chunk, so a
    /// Dictionary column must survive chunk boundaries that change which
    /// source batches are in the slice — including a boundary that falls
    /// *inside* one group entry (the four `v06` rows), whose batch must be
    /// re-registered in the next chunk's slice. `batch_size` is 8, so the
    /// 20 retained rows emit as 8 + 8 + 4, with the second chunk starting
    /// mid-entry and mixing both source batches.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_emit_dictionary_spans_chunks() -> Result<()>
    {
        let schema = Arc::new(Schema::new(vec![
            Field::new("pk", DataType::Int32, false),
            Field::new(
                "val",
                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
                false,
            ),
        ]));

        let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
        let partition_sort_fields = build_sort_fields(
            &[PhysicalSortExpr {
                expr: Arc::clone(&pk_expr),
                options: SortOptions::default(),
            }],
            &schema,
        )?;
        let order_expr = LexOrdering::from([PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: SortOptions::default(),
        }]);

        let mut state = PartitionedTopKDenseRank::try_new(
            0,
            &schema,
            vec![pk_expr],
            partition_sort_fields,
            order_expr,
            20, // k: large enough to retain every distinct value below
            8,  // batch_size
            &Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            None,
        )?;

        let dict_batch = |vals: &[&str]| -> Result<RecordBatch> {
            let mut builder = StringDictionaryBuilder::<Int32Type>::new();
            for v in vals {
                builder.append_value(v);
            }
            Ok(RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(vec![1; vals.len()])),
                    Arc::new(builder.finish()),
                ],
            )?)
        };

        // Two source batches (two distinct `batch_id`s), all under a single
        // partition key; `v06` is one entry of four rows at batch 1.
        state.insert_batch(&dict_batch(&[
            "v00", "v01", "v02", "v03", "v04", "v05", "v06", "v06", "v06", "v06",
        ])?)?;
        state.insert_batch(&dict_batch(&[
            "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19",
        ])?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_eq!(
            results.iter().map(|b| b.num_rows()).collect::<Vec<_>>(),
            vec![8, 8, 4]
        );
        let mut emitted = Vec::new();
        for b in &results {
            let val_col = b.column(1).as_dictionary::<Int32Type>();
            let dict_values = val_col.values().as_string::<i32>();
            for key in val_col.keys().values() {
                emitted.push(dict_values.value(*key as usize).to_string());
            }
        }
        let expected: Vec<String> = [
            "v00", "v01", "v02", "v03", "v04", "v05", "v06", "v06", "v06", "v06", "v10",
            "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        assert_eq!(emitted, expected, "rows must emit in ob-sorted order");
        Ok(())
    }

    /// DENSE_RANK-specific: eviction removes the entire max group when
    /// a strictly-smaller distinct ob arrives. Multiple rows at the
    /// evicted key all disappear.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_max_group_eviction() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;

        // Batch 1: pk=1 with {10, 10, 20, 20}. groups={10→[..], 20→[..]}, at K.
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 1, 1, 1],
            vec![10, 10, 20, 20],
        )?)?;

        // Batch 2: pk=1 with 5 — strictly smaller than max=20, evict entire
        // 20 group; now groups={10, 5}. Then a 30 comes in and is dropped.
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![5, 30])?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 10  |",
                "| 1  | 10  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// Empty input must produce an empty output stream, not panic.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_empty_input() -> Result<()> {
        let (_schema, state) = build_partitioned_topk_dense_rank(3)?;
        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert!(results.is_empty(), "empty input → empty output");
        Ok(())
    }

    /// `fetch = 1` retains only the smallest distinct ob per partition,
    /// with all rows at that value kept.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_fetch_one() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(1)?;

        // pk=1 vals: 5, 3, 5, 3, 7 → distinct-top-1 = {3} → both 3s kept.
        // pk=2 vals: 9, 4          → distinct-top-1 = {4} → single 4.
        let batch = pk_val_batch(
            &schema,
            vec![1, 1, 1, 2, 1, 2, 1],
            vec![5, 3, 5, 9, 3, 4, 7],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 3   |",
                "| 1  | 3   |",
                "| 2  | 4   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `K > distinct_ob_count` — nothing should be dropped.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_k_exceeds_distinct() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(10)?;

        // Only 3 distinct ob values under pk=1; all rows must be retained.
        let batch = pk_val_batch(&schema, vec![1, 1, 1, 1], vec![5, 3, 3, 7])?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 3   |",
                "| 1  | 3   |",
                "| 1  | 5   |",
                "| 1  | 7   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `ORDER BY val DESC` — the row-encoded key ordering must reflect
    /// the direction so the "distinct-K best" set is the K *largest*
    /// distinct ob values.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_desc_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank_with_opts(
            2,
            SortOptions {
                descending: true,
                nulls_first: false,
            },
            false,
        )?;

        // pk=1 vals: 10, 5, 8, 12, 10 → distinct-top-2 DESC = {12, 10}
        //   → keep both 10s and 12.
        let batch = pk_val_batch(&schema, vec![1, 1, 1, 1, 1], vec![10, 5, 8, 12, 10])?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 12  |",
                "| 1  | 10  |",
                "| 1  | 10  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// Cross-partition eviction independence — Case-C eviction in one
    /// partition must not affect another partition's state.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_partition_independence() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;

        // Batch 1: pk=1 fills {10, 20}; pk=2 fills {30, 40}.
        state.insert_batch(&pk_val_batch(
            &schema,
            vec![1, 1, 2, 2],
            vec![10, 20, 30, 40],
        )?)?;

        // Batch 2: pk=1 sees 5 (evicts 20). pk=2 sees 25 (evicts 40).
        // Each partition's Case-C branch is independent.
        state.insert_batch(&pk_val_batch(&schema, vec![1, 2], vec![5, 25])?)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 10  |",
                "| 2  | 25  |",
                "| 2  | 30  |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// NULL sort values exercise the shared encoder's null-ordering
    /// through the row-encoded key byte order. With `ASC NULLS
    /// LAST`, a NULL is the *largest* distinct ob, so a partition with
    /// >= K non-NULL distinct values evicts its NULLs, while a partition
    /// whose only distinct value is NULL still emits it.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_nulls_last_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank_with_opts(
            2,
            SortOptions {
                descending: false,
                nulls_first: false,
            },
            true,
        )?;

        // pk=1 vals: NULL, 10, 20, NULL → distinct-top-2 NULLS LAST = {10, 20}
        // pk=2 vals: NULL               → distinct-top-2            = {NULL}
        // pk=3 vals: 3, 3               → distinct-top-2            = {3}
        let batch = nullable_pk_val_batch(
            &schema,
            vec![1, 1, 1, 1, 2, 3, 3],
            vec![None, Some(10), Some(20), None, None, Some(3), Some(3)],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 10  |",
                "| 1  | 20  |",
                "| 2  |     |",
                "| 3  | 3   |",
                "| 3  | 3   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// `ASC NULLS FIRST` sorts NULLs *before* every non-NULL value, so a
    /// NULL is the smallest distinct ob and is kept preferentially. Every
    /// row at a retained distinct ob — including all tied NULLs — emits.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_nulls_first_ordering() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank_with_opts(
            2,
            SortOptions {
                descending: false,
                nulls_first: true,
            },
            true,
        )?;

        // pk=1 vals: NULL, 5, NULL, 8 → distinct-top-2 NULLS FIRST = {NULL, 5}
        // pk=2 vals: 7, NULL          → distinct-top-2             = {NULL, 7}
        // pk=3 vals: 3, 1             → distinct-top-2             = {1, 3}
        let batch = nullable_pk_val_batch(
            &schema,
            vec![1, 2, 1, 3, 1, 2, 1, 3],
            vec![
                None,
                Some(7),
                Some(5),
                Some(3),
                None,
                None,
                Some(8),
                Some(1),
            ],
        )?;
        state.insert_batch(&batch)?;

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  |     |",
                "| 1  |     |",
                "| 1  | 5   |",
                "| 2  |     |",
                "| 2  | 7   |",
                "| 3  | 1   |",
                "| 3  | 3   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// Total `GroupEntry` count across all partitions.
    fn dense_rank_entry_count(state: &PartitionedTopKDenseRank) -> usize {
        state
            .states
            .values()
            .flat_map(|s| s.groups.values())
            .map(|entries| entries.len())
            .sum()
    }

    /// One source batch feeding many retained groups must be charged
    /// once, not once per group.
    ///
    /// Dense-rank retains up to K distinct-ob groups per partition and
    /// each can draw rows from the same batch, so charging per entry
    /// inflates the reservation by (partitions × K) — here 6× — and can
    /// trip a spurious `ResourcesExhausted`.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_charges_batch_once() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(3)?;

        // pk=1 retains {1,2,3}, pk=2 retains {10,20,30}: 6 groups, all
        // from this one batch.
        let batch = pk_val_batch(
            &schema,
            vec![1, 1, 1, 1, 2, 2, 2, 2],
            vec![1, 2, 3, 4, 10, 20, 30, 40],
        )?;
        let batch_bytes = get_record_batch_memory_size(&batch);
        state.insert_batch(&batch)?;

        assert_eq!(dense_rank_entry_count(&state), 6);
        assert_eq!(state.store.len(), 1);
        assert_eq!(state.store.batches_size, batch_bytes);
        Ok(())
    }

    /// Evicting the last group referencing a batch must release the
    /// batch's bytes, or the reservation only ever grows.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_releases_evicted_batch() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;

        let first = pk_val_batch(&schema, vec![1, 1], vec![50, 60])?;
        state.insert_batch(&first)?;
        assert_eq!(state.store.len(), 1);

        // Both values beat {50, 60}, so every group from `first` is
        // evicted and only `second` remains charged.
        let second = pk_val_batch(&schema, vec![1, 1], vec![5, 6])?;
        let second_bytes = get_record_batch_memory_size(&second);
        state.insert_batch(&second)?;

        assert_eq!(state.store.len(), 1);
        assert_eq!(state.store.batches_size, second_bytes);

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 5   |",
                "| 1  | 6   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }

    /// The mirror of the above: a batch whose every run is rejected must
    /// not be charged at all.
    ///
    /// Nothing references it, so nothing would ever release it — charging
    /// it would pin both the bytes and the batch for the operator's
    /// lifetime.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_ignores_fully_rejected_batch() -> Result<()>
    {
        let (schema, mut state) = build_partitioned_topk_dense_rank(2)?;

        let first = pk_val_batch(&schema, vec![1, 1], vec![5, 6])?;
        let first_bytes = get_record_batch_memory_size(&first);
        state.insert_batch(&first)?;
        assert_eq!(state.store.len(), 1);

        // At K=2 with {5, 6} tracked, both values lose to the boundary, so
        // no `GroupEntry` points at `second`.
        state.insert_batch(&pk_val_batch(&schema, vec![1, 1], vec![50, 60])?)?;

        assert_eq!(dense_rank_entry_count(&state), 2);
        assert_eq!(state.store.len(), 1);
        assert_eq!(state.store.batches_size, first_bytes);
        Ok(())
    }

    /// `keys` must grow on demand rather than reserve K slots when a
    /// partition is first seen. `size()` charges `keys.capacity()`, so
    /// eager sizing reserves O(partitions * K) for slots that never hold
    /// a key — enough to fail a memory limit on a high-cardinality input
    /// whose partitions each keep a handful of distinct values.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_heap_grows_on_demand() -> Result<()> {
        const K: usize = 512;
        const PARTITIONS: usize = 64;
        let (schema, mut state) = build_partitioned_topk_dense_rank(K)?;

        // One row per partition: every partition holds exactly one
        // distinct ob value, K - 1 slots short of capacity.
        let pks: Vec<i32> = (0..PARTITIONS as i32).collect();
        let vals = pks.clone();
        state.insert_batch(&pk_val_batch(&schema, pks, vals)?)?;

        assert_eq!(state.states.len(), PARTITIONS);
        let heap_slots: usize = state.states.values().map(|s| s.keys.capacity()).sum();
        // Eager `with_capacity(K)` would reserve PARTITIONS * K = 32768.
        assert!(
            heap_slots <= PARTITIONS * 8,
            "reserved {heap_slots} heap slots to hold {PARTITIONS} keys"
        );
        Ok(())
    }

    /// The encoded partition keys owned by `states`, and the backing
    /// tables the drained scratch maps keep, are long-lived heap
    /// allocations `size()` must charge: they persist for the operator's
    /// life yet belong to no `GroupEntry`, so per-entry accounting can't
    /// see them. With numerous or wide partition keys the key bytes are
    /// the larger term.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_size_covers_keys_and_scratch() -> Result<()>
    {
        const PARTITIONS: usize = 64;
        const KEY_WIDTH: usize = 1024;

        let schema = Arc::new(Schema::new(vec![
            Field::new("pk", DataType::Utf8, false),
            Field::new("val", DataType::Int32, false),
        ]));
        let pk_expr: Arc<dyn PhysicalExpr> = col("pk", schema.as_ref())?;
        let partition_sort_fields = build_sort_fields(
            &[PhysicalSortExpr {
                expr: Arc::clone(&pk_expr),
                options: SortOptions::default(),
            }],
            &schema,
        )?;
        let order_expr = LexOrdering::from([PhysicalSortExpr {
            expr: col("val", schema.as_ref())?,
            options: SortOptions::default(),
        }]);
        let mut state = PartitionedTopKDenseRank::try_new(
            0,
            &schema,
            vec![pk_expr],
            partition_sort_fields,
            order_expr,
            4,
            8, // batch_size
            &Arc::new(RuntimeEnv::default()),
            &ExecutionPlanMetricsSet::new(),
            None,
        )?;

        // One row per partition, each with a wide key.
        let pks: Vec<String> = (0..PARTITIONS)
            .map(|i| format!("{}{i:04}", "p".repeat(KEY_WIDTH - 4)))
            .collect();
        let vals: Vec<i32> = (0..PARTITIONS as i32).collect();
        state.insert_batch(&RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(StringArray::from(pks)),
                Arc::new(Int32Array::from(vals)),
            ],
        )?)?;
        assert_eq!(state.states.len(), PARTITIONS);

        let key_bytes: usize = state.states.keys().map(|pk| pk.capacity()).sum();
        let scratch_bytes = state.partition_groups.capacity()
            * (size_of::<Vec<u8>>() + size_of::<Vec<u32>>())
            + state.ob_runs.capacity() * (size_of::<Vec<u8>>() + size_of::<Vec<u32>>());
        assert!(key_bytes >= PARTITIONS * KEY_WIDTH, "key bytes {key_bytes}");
        assert!(scratch_bytes > 0, "scratch tables never allocated");

        // Reconstruct the total from its parts. Both terms above have to
        // appear for this to balance, so dropping either from `size()`
        // fails here rather than being absorbed by the slack in some
        // other term.
        let expected = size_of::<PartitionedTopKDenseRank>()
            + state.row_converter.size()
            + state.partition_converter.size()
            + state.scratch_rows.size()
            + state.partition_scratch_rows.size()
            + key_bytes
            + state.states.values().map(|s| s.size()).sum::<usize>()
            + state.states.capacity()
                * (size_of::<Vec<u8>>() + size_of::<DenseRankPartitionState>())
            + scratch_bytes
            + state.store.size();
        assert_eq!(state.size(), expected);
        Ok(())
    }

    /// A group admitted and then evicted within the *same*
    /// `insert_batch` call: the batch is still pending (not yet handed to
    /// the store), so releasing it must decrement the in-flight use count
    /// rather than call `unuse` on an unregistered id.
    ///
    /// `ob_runs` drains in hash order, so with K=1 and many distinct
    /// values the minimum is almost never seen first and the run
    /// admit-then-evict path is taken repeatedly.
    #[tokio::test]
    async fn test_partitioned_topk_dense_rank_evicts_same_call_group() -> Result<()> {
        let (schema, mut state) = build_partitioned_topk_dense_rank(1)?;

        let pks = vec![1; 32];
        let vals: Vec<i32> = (0..32).rev().collect();
        let batch = pk_val_batch(&schema, pks, vals)?;
        let batch_bytes = get_record_batch_memory_size(&batch);
        state.insert_batch(&batch)?;

        assert_eq!(dense_rank_entry_count(&state), 1);
        assert_eq!(state.store.len(), 1);
        assert_eq!(state.store.batches_size, batch_bytes);

        let results: Vec<_> = state.emit()?.try_collect().await?;
        assert_batches_eq!(
            &[
                "+----+-----+",
                "| pk | val |",
                "+----+-----+",
                "| 1  | 0   |",
                "+----+-----+",
            ],
            &results
        );
        Ok(())
    }
}