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

//! Defines the spilling functions

pub(crate) mod in_progress_spill_file;
pub(crate) mod replayable_spill_input;
pub(crate) mod spill_manager;
pub mod spill_pool;
pub(crate) mod spilled_row_sizes;
use datafusion_execution::spill_file::{AsyncSpillWriter, SpillWriter};
// Moved for refactor, re-export to keep the public API stable
pub use datafusion_common::utils::memory::get_record_batch_memory_size;
// Re-export SpillManager for doctests only (hidden from public docs)
#[doc(hidden)]
pub use spill_manager::SpillManager;

use std::collections::{HashMap, VecDeque};
use std::pin::Pin;
use std::sync::{Arc, LazyLock};
use std::task::{Context, Poll};

use arrow::array::{
    Array, ArrayRef, AsArray, BinaryViewArray, BufferSpec, GenericByteViewArray,
    StringViewArray, layout, make_array,
};
use arrow::buffer::{Buffer, ScalarBuffer};
use arrow::datatypes::DataType;
use arrow::datatypes::{ByteViewType, Schema, SchemaRef};
use arrow::ipc::{
    MetadataVersion,
    reader::StreamDecoder,
    writer::{IpcWriteOptions, StreamEncoder},
};
use arrow::record_batch::RecordBatch;
use arrow_data::{ArrayDataBuilder, ByteView, MAX_INLINE_VIEW_LEN};
#[cfg(test)]
use arrow_ipc::writer::StreamWriter;
use arrow_ipc::{CompressionType, root_as_message};
use arrow_select::dictionary::garbage_collect_any_dictionary;

use datafusion_common::config::SpillCompression;
use datafusion_common::{Result, internal_datafusion_err};
use datafusion_execution::RecordBatchStream;
use datafusion_execution::spill_file::SpillFile;
use futures::Stream;
use log::debug;

/// Stream that reads spill files from a [`SpillFile`] backend as a stream of [`RecordBatch`]es.
/// Uses [`StreamDecoder`] to decode IPC bytes received from the backend's async byte stream.
/// Backends handle their own threading concerns internally - OS files use
/// `tokio::fs::File` which performs blocking IO per-syscall without holding a thread
/// for the file's lifetime, avoiding deadlocks when concurrent reads exceed thread pool limits.
struct SpillReaderStream {
    schema: SchemaRef,
    decoder: StreamDecoder,
    byte_stream: Pin<Box<dyn Stream<Item = Result<bytes::Bytes>> + Send>>,
    is_done: bool,

    /// Maximum memory size observed among spilling sorted record batches.
    /// This is used for validation purposes during reading each RecordBatch from spill.
    /// For context on why this value is recorded and validated,
    /// see `physical_plan/sort/multi_level_merge.rs`.
    max_record_batch_memory: Option<usize>,

    /// Holds leftover bytes from a chunk not yet consumed by `framer`
    current_buffer: Buffer,

    /// Assembles the chunks of `byte_stream` into exactly sized messages
    framer: MessageFramer,

    /// Framed message buffers not yet consumed by `decoder`
    pending: VecDeque<Buffer>,

    /// Keeps the file alive until the stream is dropped
    _spill_file: Arc<dyn SpillFile>,

    schema_validated: bool,
}

// Small margin allowed to accommodate slight memory accounting variation
const SPILL_BATCH_MEMORY_MARGIN: usize = 4096;

/// Reassembles an IPC stream read in arbitrary chunks into one exactly sized
/// allocation per message, so that the zero-copy [`StreamDecoder`] produces
/// batches whose buffers pin only their own message.
///
/// # Why
///
/// The decoder builds arrays on slices of whatever [`Buffer`] it is given,
/// and a slice keeps its whole backing allocation alive. Fed with the raw
/// chunks of the byte stream (128 KB for a file backed spill) that goes
/// wrong in two ways.
///
/// A message that fits inside a chunk pins the entire chunk. With ~5 KB
/// batches, one chunk holds ~27 of them, and each decoded batch retains, and
/// is accounted for, 128 KB:
///
/// ```text
/// chunk (128 KB allocation)
/// ┌──────┬──────┬──────┬─────┬───────┐
/// │ msg1 │ msg2 │ msg3 │ ... │ msg27 │
/// └──────┴──────┴──────┴─────┴───────┘
///    ▲
///    batch1's buffers slice here, yet keep all 128 KB alive
/// ```
///
/// A message that spans two chunks cannot be sliced, so the decoder gathers
/// it into a `Vec` grown by doubling, and the batch keeps the spare
/// capacity: a 256 KB body typically lands in a 512 KB allocation.
///
/// ```text
/// chunk N                      chunk N+1
/// ┌──────┬────────────────────┬──────────────┬────────┐
/// │ ...  │ msgK (first part)  │ msgK (rest)  │ msgK+1 │
/// └──────┴────────────────────┴──────────────┴────────┘
/// ```
///
/// Either way a batch uses several times the memory recorded for it at
/// spill time, breaking the `max_record_batch_memory` budgeting that the
/// multi-level merge relies on.
///
/// # How
///
/// Each message is copied out of the chunks into allocations sized from its
/// own headers: a head buffer (the length prefix and flatbuffer metadata,
/// whose `bodyLength` gives the body size) and, when non-empty, a body
/// buffer of exactly that size. The decoder then zero-copies from the body
/// buffer, so a batch pins exactly its own message:
///
/// ```text
/// body for msg1 (5 KB)      body for msgK (256 KB)
/// ┌──────┐                  ┌────────────────────┐
/// │ msg1 │ ◀── batch1       │ msgK               │ ◀── batchK
/// └──────┘                  └────────────────────┘
/// ```
///
/// This costs one copy per message, which the decoder already paid for
/// spanning messages, without the doubling reallocation. Measured on the
/// `spill_io` benchmark, the copy is not visible end to end for batches at
/// or above the 128 KB read chunk, where skipping the doubling gather makes
/// framing the faster of the two, and costs a few percent for batches small
/// enough that several share a chunk, which are exactly the batches whose
/// accounting it fixes.
struct MessageFramer {
    state: FramerState,
}

enum FramerState {
    /// Reading the 4 byte continuation marker or metadata length.
    Prefix {
        head: Vec<u8>,
        read: usize,
        continuation: bool,
    },
    /// Reading the flatbuffer metadata into `head`, which already holds the
    /// prefix and is allocated for `head_len` bytes.
    Metadata {
        head: Vec<u8>,
        metadata_start: usize,
        head_len: usize,
    },
    /// Reading the body into `body`, which is allocated for `body_len` bytes.
    Body {
        head: Vec<u8>,
        body: Vec<u8>,
        body_len: usize,
    },
    /// The end-of-stream marker was read.
    Finished,
}

impl MessageFramer {
    fn new() -> Self {
        Self {
            state: FramerState::prefix(),
        }
    }

    /// Consumes bytes from `input` until a message is complete or `input` is
    /// exhausted, returning the buffers of a completed message.
    fn push(&mut self, input: &mut Buffer) -> Result<Option<Vec<Buffer>>> {
        while !input.is_empty() {
            match &mut self.state {
                FramerState::Prefix {
                    head,
                    read,
                    continuation,
                } => {
                    let to_read = input.len().min(4 - *read);
                    head.extend_from_slice(&input[..to_read]);
                    input.advance(to_read);
                    *read += to_read;
                    if *read < 4 {
                        continue;
                    }
                    let word: [u8; 4] = head[head.len() - 4..].try_into().unwrap();
                    if !*continuation && word == CONTINUATION_MARKER {
                        *continuation = true;
                        *read = 0;
                        continue;
                    }
                    let metadata_len = u32::from_le_bytes(word) as usize;
                    let head = std::mem::take(head);
                    if metadata_len == 0 {
                        self.state = FramerState::Finished;
                        return Ok(Some(vec![Buffer::from_vec(head)]));
                    }
                    let metadata_start = head.len();
                    let head_len = metadata_start + metadata_len;
                    let mut sized = Vec::with_capacity(head_len);
                    sized.extend_from_slice(&head);
                    self.state = FramerState::Metadata {
                        head: sized,
                        metadata_start,
                        head_len,
                    };
                }
                FramerState::Metadata {
                    head,
                    metadata_start,
                    head_len,
                } => {
                    let to_read = input.len().min(*head_len - head.len());
                    head.extend_from_slice(&input[..to_read]);
                    input.advance(to_read);
                    if head.len() < *head_len {
                        continue;
                    }
                    let message =
                        root_as_message(&head[*metadata_start..]).map_err(|e| {
                            datafusion_common::exec_datafusion_err!(
                                "Invalid IPC message in spill file: {e}"
                            )
                        })?;
                    let body_len =
                        usize::try_from(message.bodyLength()).map_err(|_| {
                            datafusion_common::exec_datafusion_err!(
                                "Invalid IPC message body length in spill file: {}",
                                message.bodyLength()
                            )
                        })?;
                    let head = std::mem::take(head);
                    if body_len == 0 {
                        self.state = FramerState::prefix();
                        return Ok(Some(vec![Buffer::from_vec(head)]));
                    }
                    self.state = FramerState::Body {
                        head,
                        body: Vec::with_capacity(body_len),
                        body_len,
                    };
                }
                FramerState::Body {
                    head,
                    body,
                    body_len,
                } => {
                    let to_read = input.len().min(*body_len - body.len());
                    body.extend_from_slice(&input[..to_read]);
                    input.advance(to_read);
                    if body.len() < *body_len {
                        continue;
                    }
                    let (head, body) = (std::mem::take(head), std::mem::take(body));
                    self.state = FramerState::prefix();
                    return Ok(Some(vec![
                        Buffer::from_vec(head),
                        Buffer::from_vec(body),
                    ]));
                }
                FramerState::Finished => {
                    return datafusion_common::exec_err!(
                        "Unexpected bytes after the end of the IPC stream in spill file"
                    );
                }
            }
        }
        Ok(None)
    }

    /// Checks that the stream ended on a message boundary.
    ///
    /// This mirrors [`StreamDecoder::finish`]: a stream is complete either
    /// when the end-of-stream marker was read, or when it ends right after a
    /// message. Framing moves the partial bytes of a truncated file out of
    /// the decoder's own scratch space and into the framer, so without this
    /// check a truncated spill file would silently decode as a shorter
    /// stream instead of erroring.
    fn finish(&self) -> Result<()> {
        match &self.state {
            FramerState::Finished
            | FramerState::Prefix {
                read: 0,
                continuation: false,
                ..
            } => Ok(()),
            _ => datafusion_common::exec_err!(
                "Unexpected end of spill file: the IPC stream ends mid-message"
            ),
        }
    }
}

impl FramerState {
    fn prefix() -> Self {
        Self::Prefix {
            head: Vec::with_capacity(8),
            read: 0,
            continuation: false,
        }
    }
}

/// Marks a length prefix in the IPC stream format, see `arrow_ipc`.
const CONTINUATION_MARKER: [u8; 4] = [0xff; 4];

impl SpillReaderStream {
    fn new(
        schema: SchemaRef,
        spill_file: Arc<dyn SpillFile>,
        max_record_batch_memory: Option<usize>,
    ) -> Result<Self> {
        let byte_stream = spill_file.read_stream()?;
        // DataFusion controls what it writes so it can trust its own IPC output,
        // matching the behavior of the previous StreamReader-based implementation.
        let decoder = unsafe { StreamDecoder::new().with_skip_validation(true) };
        Ok(Self {
            schema,
            decoder,
            byte_stream,
            max_record_batch_memory,
            is_done: false,
            current_buffer: Buffer::from(&[]),
            framer: MessageFramer::new(),
            pending: VecDeque::new(),
            _spill_file: spill_file,
            schema_validated: false,
        })
    }
}

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

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();

        if this.is_done {
            return Poll::Ready(None);
        }

        loop {
            // Decode the framed messages first
            if let Some(buffer) = this.pending.front_mut() {
                if buffer.is_empty() {
                    this.pending.pop_front();
                    continue;
                }
                match this.decoder.decode(buffer) {
                    Ok(Some(batch)) => {
                        // One-time schema validation on the first decoded batch.
                        // The IPC stream embeds the writer's schema in its header;
                        // StreamDecoder surfaces it via the first batch's schema.
                        // We check here rather than in new() because schema bytes
                        // only arrive after decoding the IPC header from the stream.
                        if !this.schema_validated {
                            this.schema_validated = true;
                            let actual = batch.schema();
                            if actual != this.schema {
                                this.is_done = true;
                                return Poll::Ready(Some(Err(
                                    datafusion_common::exec_datafusion_err!(
                                        "Spill file schema mismatch: expected {}, got {}. \
                     The caller must use the same SpillManager that created \
                     the spill file to read it.",
                                        this.schema,
                                        actual
                                    ),
                                )));
                            }
                        }
                        if let Some(max_record_batch_memory) =
                            this.max_record_batch_memory
                        {
                            let actual_size = get_record_batch_memory_size(&batch);
                            if actual_size
                                > max_record_batch_memory + SPILL_BATCH_MEMORY_MARGIN
                            {
                                debug!(
                                    "Record batch memory usage ({actual_size} bytes) exceeds the expected limit ({max_record_batch_memory} bytes) \n\
                                        by more than the allowed tolerance ({SPILL_BATCH_MEMORY_MARGIN} bytes).\n\
                                        This likely indicates a bug in memory accounting during spilling."
                                );
                            }
                        }
                        return Poll::Ready(Some(Ok(batch)));
                    }
                    Ok(None) => {
                        // A schema or dictionary message, or the buffer was
                        // only part of a message. Carry on with the next one.
                    }
                    Err(e) => {
                        this.is_done = true;
                        return Poll::Ready(Some(Err(e.into())));
                    }
                }
                continue;
            }

            // Then frame the next message out of the current chunk
            if !this.current_buffer.is_empty() {
                match this.framer.push(&mut this.current_buffer) {
                    Ok(Some(buffers)) => this.pending.extend(buffers),
                    Ok(None) => {}
                    Err(e) => {
                        this.is_done = true;
                        return Poll::Ready(Some(Err(e)));
                    }
                }
                continue;
            }

            // Finally fetch another chunk
            match futures::ready!(this.byte_stream.as_mut().poll_next(cx)) {
                Some(Ok(chunk)) => {
                    this.current_buffer = Buffer::from(chunk);
                }
                Some(Err(e)) => {
                    this.is_done = true;
                    return Poll::Ready(Some(Err(e)));
                }
                None => {
                    this.is_done = true;

                    // The framer holds the bytes of an incomplete trailing
                    // message, so it is the one that detects truncation.
                    if let Err(e) = this.framer.finish() {
                        return Poll::Ready(Some(Err(e)));
                    }
                    if let Err(e) = this.decoder.finish() {
                        return Poll::Ready(Some(Err(e.into())));
                    }
                    return Poll::Ready(None);
                }
            }
        }
    }
}

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

/// Write in Arrow IPC Stream format to an underlying `SpillWriter` backend.
/// Stream format also supports dictionary replacement.
struct IPCStreamWriter {
    writer: Box<dyn SpillWriter>,
    encoder: IPCStreamEncoder,
}

impl IPCStreamWriter {
    pub fn new(
        spill_writer: Box<dyn SpillWriter>,
        schema: &Schema,
        spill_compression: SpillCompression,
    ) -> Result<Self> {
        Ok(Self {
            writer: spill_writer,
            encoder: IPCStreamEncoder::new(schema, spill_compression)?,
        })
    }

    pub fn write(&mut self, batch: &RecordBatch) -> Result<(usize, usize)> {
        use std::io::Write;
        let (rows, bytes, buffers) = self.encoder.encode(batch)?;
        for buffer in buffers {
            self.writer.write_all(buffer.as_slice())?;
        }
        Ok((rows, bytes))
    }

    pub fn flush(&mut self) -> Result<()> {
        use std::io::Write;
        self.writer.flush()?;
        Ok(())
    }

    pub fn finish(&mut self) -> Result<usize> {
        use std::io::Write;
        let (bytes, buffers) = self.encoder.finish()?;
        for buffer in buffers {
            self.writer.write_all(buffer.as_slice())?;
        }
        self.writer.flush()?;
        self.writer.finish()?;
        Ok(bytes)
    }
}

/// Writes Arrow IPC Stream data through an [`AsyncSpillWriter`] interface.
struct AsyncIPCStreamWriter {
    writer: Option<Box<dyn AsyncSpillWriter>>,
    encoder: IPCStreamEncoder,
    abort_handle: Option<tokio::runtime::Handle>,
}

/// Bounds the number of detached cleanup tasks after query cancellation. If all
/// permits are occupied, the writer is dropped and the backend lifecycle policy
/// is the remaining cleanup mechanism.
const MAX_CONCURRENT_SPILL_ABORTS: usize = 8;
static SPILL_ABORT_PERMITS: LazyLock<Arc<tokio::sync::Semaphore>> =
    LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_SPILL_ABORTS)));

impl AsyncIPCStreamWriter {
    pub fn new(
        spill_writer: Box<dyn AsyncSpillWriter>,
        encoder: IPCStreamEncoder,
    ) -> Self {
        Self {
            writer: Some(spill_writer),
            encoder,
            abort_handle: tokio::runtime::Handle::try_current().ok(),
        }
    }

    pub async fn write(&mut self, batch: &RecordBatch) -> Result<(usize, usize)> {
        let (rows, bytes, buffers) = match self.encoder.encode(batch) {
            Ok(encoded) => encoded,
            Err(error) => {
                self.abort_after_error().await;
                return Err(error);
            }
        };
        for buffer in buffers {
            let result = self
                .writer
                .as_mut()
                .ok_or_else(|| {
                    internal_datafusion_err!("Spill writer is no longer active")
                })?
                .write_all(buffer_to_bytes(buffer))
                .await;
            if let Err(error) = result {
                self.abort_after_error().await;
                return Err(error);
            }
        }
        Ok((rows, bytes))
    }

    pub async fn finish(&mut self) -> Result<usize> {
        let (bytes, buffers) = match self.encoder.finish() {
            Ok(encoded) => encoded,
            Err(error) => {
                self.abort_after_error().await;
                return Err(error);
            }
        };
        for buffer in buffers {
            let result = self
                .writer
                .as_mut()
                .ok_or_else(|| {
                    internal_datafusion_err!("Spill writer is no longer active")
                })?
                .write_all(buffer_to_bytes(buffer))
                .await;
            if let Err(error) = result {
                self.abort_after_error().await;
                return Err(error);
            }
        }
        let result = self
            .writer
            .as_mut()
            .ok_or_else(|| internal_datafusion_err!("Spill writer is no longer active"))?
            .flush()
            .await;
        if let Err(error) = result {
            self.abort_after_error().await;
            return Err(error);
        }
        let result = self
            .writer
            .as_mut()
            .ok_or_else(|| internal_datafusion_err!("Spill writer is no longer active"))?
            .finish()
            .await;
        if let Err(error) = result {
            self.abort_after_error().await;
            return Err(error);
        }
        self.writer.take();
        Ok(bytes)
    }

    pub async fn abort(&mut self) -> Result<()> {
        let Some(writer) = self.writer.as_mut() else {
            return Ok(());
        };
        writer.abort().await?;
        self.writer = None;
        Ok(())
    }

    async fn abort_after_error(&mut self) {
        if let Err(error) = self.abort().await {
            debug!("Failed to abort spill writer: {error}");
        }
    }
}

impl Drop for AsyncIPCStreamWriter {
    fn drop(&mut self) {
        let Some(mut writer) = self.writer.take() else {
            return;
        };

        let Some(handle) = tokio::runtime::Handle::try_current()
            .ok()
            .or_else(|| self.abort_handle.take())
        else {
            debug!("Unable to abort dropped spill writer without a Tokio runtime");
            return;
        };

        let Ok(permit) = Arc::clone(&SPILL_ABORT_PERMITS).try_acquire_owned() else {
            debug!(
                "Skipping spill writer abort because the cleanup concurrency limit was reached"
            );
            return;
        };

        let _abort_task = handle.spawn(async move {
            // Backends bound their own abort latency; the runtime may not have
            // a time driver. See the AsyncSpillWriter::abort contract.
            if let Err(error) = writer.abort().await {
                debug!("Failed to abort dropped spill writer: {error}");
            }
            // Keep the permit until cleanup finishes.
            drop(permit);
        });
    }
}

/// Encodes Arrow IPC streams without performing I/O.
struct IPCStreamEncoder {
    encoder: Option<StreamEncoder>,
}

impl IPCStreamEncoder {
    /// Create a new encoder.
    ///
    /// # Codec contract
    ///
    /// `arrow-ipc` must be compiled with the `lz4` and `zstd` features
    /// (declared explicitly in `datafusion-physical-plan/Cargo.toml`). If
    /// those features are absent, `try_with_compression` will return an
    /// error at runtime for [`SpillCompression::Lz4Frame`] and
    /// [`SpillCompression::Zstd`] variants. The Cargo dependency keeps this
    /// contract local and build-visible during Cargo feature resolution,
    /// rather than relying solely on workspace-level feature unification;
    /// see #21917.
    fn new(schema: &Schema, spill_compression: SpillCompression) -> Result<Self> {
        let metadata_version = MetadataVersion::V5;
        // Depending on the schema, some array types such as StringViewArray require larger (16 byte in this case) alignment.
        // If the actual buffer layout after IPC read does not satisfy the alignment requirement,
        // Arrow ArrayBuilder will copy the buffer into a newly allocated, properly aligned buffer.
        // This copying may lead to memory blowup during IPC read due to duplicated buffers.
        // To avoid this, we compute the maximum required alignment based on the schema and configure the IPCStreamWriter accordingly.
        let alignment = get_max_alignment_for_schema(schema);
        let mut write_options =
            IpcWriteOptions::try_new(alignment, false, metadata_version)?;

        let compression_type = Option::<CompressionType>::from(spill_compression);
        write_options = write_options.try_with_compression(compression_type)?;

        let encoder = StreamEncoder::try_new_with_options(schema, write_options)?;
        Ok(Self {
            encoder: Some(encoder),
        })
    }

    fn encode(&mut self, batch: &RecordBatch) -> Result<(usize, usize, Vec<Buffer>)> {
        let buffers = self.encoder.as_mut().unwrap().encode(batch)?;
        let bytes = buffers.iter().map(Buffer::len).sum();
        Ok((batch.num_rows(), bytes, buffers))
    }

    fn finish(&mut self) -> Result<(usize, Vec<Buffer>)> {
        let buffers = self.encoder.take().unwrap().finish()?;
        let bytes = buffers.iter().map(Buffer::len).sum();
        Ok((bytes, buffers))
    }
}

struct ArrowBufferOwner(Buffer);

impl AsRef<[u8]> for ArrowBufferOwner {
    fn as_ref(&self) -> &[u8] {
        self.0.as_slice()
    }
}

fn buffer_to_bytes(buffer: Buffer) -> bytes::Bytes {
    bytes::Bytes::from_owner(ArrowBufferOwner(buffer))
}

// Returns the maximum byte alignment required by any field in the schema (>= 8), derived from Arrow buffer layouts.
fn get_max_alignment_for_schema(schema: &Schema) -> usize {
    let minimum_alignment = 8;
    let mut max_alignment = minimum_alignment;
    for field in schema.fields() {
        let layout = layout(field.data_type());
        let required_alignment = layout
            .buffers
            .iter()
            .map(|buffer_spec| {
                if let BufferSpec::FixedWidth { alignment, .. } = buffer_spec {
                    *alignment
                } else {
                    minimum_alignment
                }
            })
            .max()
            .unwrap_or(minimum_alignment);
        max_alignment = std::cmp::max(max_alignment, required_alignment);
    }
    max_alignment
}

/// Size of a single view structure in StringView/BinaryView arrays (in bytes).
/// Each view is 16 bytes: 4 bytes length + 4 bytes prefix + 8 bytes buffer ID/offset.
const VIEW_SIZE_BYTES: usize = 16;

/// Compacts view buffers and oversized dictionaries before spilling.
///
/// # Why GC is needed
///
/// StringView and BinaryView arrays can accumulate significant memory waste when sliced.
/// When a large array is sliced (e.g., taking first 100 rows of 1000), the view array
/// still references the original data buffers containing all 1000 rows of data.
///
/// For example, in the ClickBench benchmark (issue #19414), repeated slicing of StringView
/// arrays resulted in 820MB of spill files that could be reduced to just 33MB after GC -
/// a 96% reduction in size.
///
/// # How it works
///
/// The GC process:
/// 1. Identifies view arrays (StringView/BinaryView) in the batch
/// 2. Checks if their data buffers exceed a memory threshold
/// 3. If exceeded, calls the Arrow `gc()` method which creates new compact buffers
///    containing only the data referenced by the current views
/// 4. Returns a new batch with GC'd arrays (or original arrays if GC not needed)
///
/// Dictionary arrays with more values than keys are also compacted using Arrow's
/// dictionary garbage collector before visiting their children. This avoids spilling
/// whole value tables retained by sliced or merged dictionaries.
///
/// # When GC is triggered
///
/// View GC is only performed when data buffers exceed a threshold (currently 10KB).
/// This balances memory savings against the CPU overhead of garbage collection.
/// Small view buffers are passed through unchanged since the GC overhead would exceed
/// any memory savings.
///
/// # Performance considerations
///
/// - If no arrays need compaction, the original batch is cloned cheaply
/// - View GC is skipped for small buffers to avoid unnecessary CPU overhead
/// - Nested container types are traversed recursively so view arrays inside
///   `List`, `Map`, `Union`, `Dictionary`, and other child-bearing arrays are compacted too
/// - Traversal uses physical children, not logical reachability. For example,
///   unused ListView child entries can still retain dictionary values
/// - The Arrow `gc()` method itself is optimized and only copies referenced data
pub(crate) fn gc_view_arrays(batch: &RecordBatch) -> Result<RecordBatch> {
    gc_arrays_of_columns(batch, |_, _| true, false)
}

/// Like [`gc_view_arrays`], but only compacts `columns`, and also removes the
/// dictionary values that no key of theirs references.
///
/// `take` and `slice` keep every value of a dictionary, so a few rows taken
/// from a large batch carry the values of all its rows.
pub(crate) fn gc_columns(batch: &RecordBatch, columns: &[usize]) -> Result<RecordBatch> {
    gc_arrays_of_columns(batch, |index, _| columns.contains(&index), true)
}

/// Like [`gc_view_arrays`], but only compacts nested columns, such as lists of
/// strings, and also removes the dictionary values that no key of theirs
/// references.
///
/// A batch built by `interleave`, such as the output of a sort-preserving
/// merge, references the whole data buffers of the batches it takes rows
/// from, and can hold all their dictionary values. An accumulator that keeps
/// the arrays it merges, such as `array_agg`, keeps them alive with each
/// group. Top-level columns are left as they are, since group keys and the
/// accumulators of top-level states typically copy the values they keep.
pub(crate) fn gc_nested_arrays(batch: &RecordBatch) -> Result<RecordBatch> {
    gc_arrays_of_columns(batch, |_, array| array.data_type().is_nested(), true)
}

/// Compacts the view arrays of the columns of `batch` that `include` selects
/// by index, and their dictionary arrays if `dictionaries` is set.
fn gc_arrays_of_columns(
    batch: &RecordBatch,
    include: impl Fn(usize, &ArrayRef) -> bool,
    dictionaries: bool,
) -> Result<RecordBatch> {
    let mut mutated = false;
    let mut new_columns: Vec<Arc<dyn Array>> = Vec::with_capacity(batch.num_columns());

    for (index, array) in batch.columns().iter().enumerate() {
        let (gc_array, array_mutated) = if include(index, array) {
            gc_array(array, dictionaries)?
        } else {
            (Arc::clone(array), false)
        };
        mutated |= array_mutated;
        new_columns.push(gc_array);
    }

    if mutated {
        Ok(RecordBatch::try_new(batch.schema(), new_columns)?)
    } else {
        Ok(batch.clone())
    }
}

/// Compacts the view arrays in `array`, and its dictionary arrays if
/// `dictionaries` is set. Also returns whether anything was compacted.
fn gc_array(array: &ArrayRef, dictionaries: bool) -> Result<(ArrayRef, bool)> {
    match array.data_type() {
        DataType::Utf8View => {
            let string_view = array
                .as_any()
                .downcast_ref::<StringViewArray>()
                .expect("Utf8View array should downcast to StringViewArray");
            Ok(match compact_view_array(string_view) {
                Some(compacted) => (Arc::new(compacted) as ArrayRef, true),
                None => (Arc::clone(array), false),
            })
        }
        DataType::BinaryView => {
            let binary_view = array
                .as_any()
                .downcast_ref::<BinaryViewArray>()
                .expect("BinaryView array should downcast to BinaryViewArray");
            Ok(match compact_view_array(binary_view) {
                Some(compacted) => (Arc::new(compacted) as ArrayRef, true),
                None => (Arc::clone(array), false),
            })
        }
        DataType::Dictionary(_, _) if dictionaries => {
            let dictionary = array.as_any_dictionary();
            let gc = garbage_collect_any_dictionary(dictionary)?;
            let gc = gc.as_any_dictionary();
            let shrunk = gc.values().len() < dictionary.values().len();
            let (values, values_mutated) = gc_array(gc.values(), dictionaries)?;
            if !shrunk && !values_mutated {
                return Ok((Arc::clone(array), false));
            }
            Ok((gc.with_values(values), true))
        }
        DataType::Dictionary(_, _)
            if array.as_any_dictionary().values().len() > array.len() =>
        {
            // Struct-valued merge dictionaries can concatenate whole value tables.
            // Prune the outer dictionary before compacting its retained children.
            let compacted = garbage_collect_any_dictionary(array.as_any_dictionary())?;
            let (compacted, _) = gc_array_children(&compacted, dictionaries)?;
            Ok((compacted, true))
        }
        _ => gc_array_children(array, dictionaries),
    }
}

/// Compacts a view array before spilling, or returns `None` to spill it as is.
///
/// The IPC writer writes every data buffer of an array in full, once per
/// entry, and `gc()` copies the bytes of every view separately. Neither
/// handles views that share bytes, as the views of a dictionary-encoded
/// Parquet column do: after `concat` the dictionary is listed once per input
/// batch, and `gc()` copies it once per row
/// (<https://github.com/apache/datafusion/issues/23564>).
///
/// Repeated buffer entries are merged first. `gc()` then runs only if it
/// writes less than the merged buffers hold, and runs on the original array
/// so that the views are rewritten at most once.
fn compact_view_array<T: ByteViewType>(
    array: &GenericByteViewArray<T>,
) -> Option<GenericByteViewArray<T>> {
    let buffers = array.data_buffers();
    if buffers.is_empty() {
        return None;
    }

    let (remap, unique) = dedup_buffer_entries(buffers);
    let unique_size: usize = unique.iter().map(|b| b.len()).sum();
    if should_gc_view_array(array, unique_size) {
        return Some(array.gc());
    }
    if unique.len() == buffers.len() {
        return None;
    }

    let views: Vec<u128> = array
        .views()
        .iter()
        .enumerate()
        .map(|(i, &raw)| {
            if array.is_null(i) {
                0
            } else if (raw as u32) <= MAX_INLINE_VIEW_LEN {
                raw
            } else {
                let view = ByteView::from(raw);
                ByteView {
                    buffer_index: remap[view.buffer_index as usize],
                    ..view
                }
                .as_u128()
            }
        })
        .collect();

    // SAFETY: every non-null, non-inline view points at the same bytes as
    // before, in an entry of `unique` that holds the same buffer, and inline
    // views are unchanged.
    Some(unsafe {
        GenericByteViewArray::new_unchecked(
            ScalarBuffer::from(views),
            unique.into(),
            array.nulls().cloned(),
        )
    })
}

/// Returns, for each entry of `buffers`, its index in a list without repeated
/// entries of the same buffer, and that list.
fn dedup_buffer_entries(buffers: &[Buffer]) -> (Vec<u32>, Vec<Buffer>) {
    let mut first_index: HashMap<(*const u8, usize), u32> =
        HashMap::with_capacity(buffers.len());
    let mut unique: Vec<Buffer> = Vec::with_capacity(buffers.len());
    let remap = buffers
        .iter()
        .map(|buffer| {
            *first_index
                .entry((buffer.as_ptr(), buffer.len()))
                .or_insert_with(|| {
                    unique.push(buffer.clone());
                    (unique.len() - 1) as u32
                })
        })
        .collect();
    (remap, unique)
}

fn gc_array_children(array: &ArrayRef, dictionaries: bool) -> Result<(ArrayRef, bool)> {
    let data = array.to_data();
    if data.child_data().is_empty() {
        return Ok((Arc::clone(array), false));
    }

    let mut mutated = false;
    let mut child_data = Vec::with_capacity(data.child_data().len());
    for child in data.child_data() {
        let child_array = make_array(child.clone());
        let (gc_child, child_mutated) = gc_array(&child_array, dictionaries)?;
        mutated |= child_mutated;
        child_data.push(gc_child.to_data());
    }

    if !mutated {
        return Ok((Arc::clone(array), false));
    }

    let rebuilt = ArrayDataBuilder::new(data.data_type().clone())
        .len(data.len())
        .offset(data.offset())
        .nulls(data.nulls().cloned())
        .buffers(data.buffers().to_vec())
        .child_data(child_data)
        .build()?;

    Ok((make_array(rebuilt), true))
}

/// Determines whether a view array should be garbage collected before spilling,
/// given `data_size`, the bytes its data buffers hold after
/// [`dedup_buffer_entries`].
///
/// Arrow's `gc()` always allocates new compact buffers (it is never a no-op), so
/// it is skipped when the data buffers are small. It is also skipped when it
/// would write more than the data buffers hold: `gc()` copies the bytes of
/// every view separately, so views that share bytes each get their own copy.
/// Both sizes come from the views and buffer lengths, without reading values.
fn should_gc_view_array<T: ByteViewType>(
    array: &GenericByteViewArray<T>,
    data_size: usize,
) -> bool {
    const MIN_BUFFER_SIZE_FOR_GC: usize = 10 * 1024; // 10KB threshold

    // `total_buffer_bytes_used` is the size of the data buffer `gc()` writes
    data_size > MIN_BUFFER_SIZE_FOR_GC && array.total_buffer_bytes_used() < data_size
}

#[cfg(test)]
fn data_buffers_size(array: &StringViewArray) -> usize {
    array.data_buffers().iter().map(|b| b.len()).sum()
}

#[cfg(test)]
fn calculate_string_view_waste_ratio(array: &StringViewArray) -> f64 {
    calculate_view_waste_ratio(array.len(), array.data_buffers(), |i| {
        if !array.is_null(i) {
            let value = array.value(i);
            if value.len() > MAX_INLINE_VIEW_LEN as usize {
                return value.len();
            }
        }
        0
    })
}

#[cfg(test)]
fn calculate_view_waste_ratio<F>(
    len: usize,
    data_buffers: &[Buffer],
    get_value_size: F,
) -> f64
where
    F: Fn(usize) -> usize,
{
    let total_buffer_size: usize = data_buffers.iter().map(|b| b.capacity()).sum();
    if total_buffer_size == 0 {
        return 0.0;
    }

    let mut actual_used_size = (0..len).map(get_value_size).sum::<usize>();
    actual_used_size += len * VIEW_SIZE_BYTES;

    let waste = total_buffer_size.saturating_sub(actual_used_size);
    waste as f64 / total_buffer_size as f64
}

#[cfg(test)]
mod tests {
    use super::in_progress_spill_file::InProgressSpillFile;
    use super::*;
    use crate::common::collect;
    use crate::metrics::ExecutionPlanMetricsSet;
    use crate::metrics::SpillMetrics;
    use crate::spill::spill_manager::SpillManager;
    use crate::test::build_table_i32;
    use arrow::array::{
        ArrayRef, DictionaryArray, Int32Array, ListArray, StringArray, StructArray,
    };
    use arrow::buffer::OffsetBuffer;
    use arrow::compute::cast;
    use arrow::datatypes::{DataType, Field, Int32Type};
    use arrow::ipc::reader::StreamReader;
    use datafusion_execution::runtime_env::RuntimeEnv;
    use futures::StreamExt as _;
    use std::io::Cursor;
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::time::Duration;
    use tokio::sync::Notify;

    struct YieldingAsyncWriter {
        data: Arc<Mutex<Vec<u8>>>,
        writes: Arc<AtomicUsize>,
        finished: Arc<AtomicBool>,
        aborted: Arc<AtomicBool>,
    }

    struct FailingAsyncWriter {
        aborted: Arc<AtomicBool>,
    }

    struct PendingFinishAsyncWriter {
        finish_started: Arc<Notify>,
        aborted: Arc<Notify>,
        abort_count: Arc<AtomicUsize>,
    }

    struct FailOnceAbortWriter {
        abort_count: Arc<AtomicUsize>,
        cleanup_done: Arc<Notify>,
    }

    #[async_trait::async_trait]
    impl AsyncSpillWriter for FailingAsyncWriter {
        async fn write_all(&mut self, _data: bytes::Bytes) -> Result<()> {
            datafusion_common::exec_err!("injected spill write failure")
        }

        async fn finish(&mut self) -> Result<()> {
            Ok(())
        }

        async fn abort(&mut self) -> Result<()> {
            self.aborted.store(true, Ordering::Relaxed);
            Ok(())
        }
    }

    #[async_trait::async_trait]
    impl AsyncSpillWriter for YieldingAsyncWriter {
        async fn write_all(&mut self, data: bytes::Bytes) -> Result<()> {
            tokio::task::yield_now().await;
            self.writes.fetch_add(1, Ordering::Relaxed);
            self.data.lock().unwrap().extend_from_slice(&data);
            Ok(())
        }

        async fn finish(&mut self) -> Result<()> {
            self.finished.store(true, Ordering::Relaxed);
            Ok(())
        }

        async fn abort(&mut self) -> Result<()> {
            self.aborted.store(true, Ordering::Relaxed);
            Ok(())
        }
    }

    #[async_trait::async_trait]
    impl AsyncSpillWriter for PendingFinishAsyncWriter {
        async fn write_all(&mut self, _data: bytes::Bytes) -> Result<()> {
            Ok(())
        }

        async fn finish(&mut self) -> Result<()> {
            self.finish_started.notify_one();
            std::future::pending().await
        }

        async fn abort(&mut self) -> Result<()> {
            self.abort_count.fetch_add(1, Ordering::Relaxed);
            self.aborted.notify_one();
            Ok(())
        }
    }

    #[async_trait::async_trait]
    impl AsyncSpillWriter for FailOnceAbortWriter {
        async fn write_all(&mut self, _data: bytes::Bytes) -> Result<()> {
            Ok(())
        }

        async fn finish(&mut self) -> Result<()> {
            Ok(())
        }

        async fn abort(&mut self) -> Result<()> {
            if self.abort_count.fetch_add(1, Ordering::Relaxed) == 0 {
                return datafusion_common::exec_err!("injected spill abort failure");
            }
            self.cleanup_done.notify_one();
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_async_ipc_stream_writer() -> Result<()> {
        let batch1 = build_table_i32(
            ("a", &vec![0, 1, 2]),
            ("b", &vec![3, 4, 5]),
            ("c", &vec![6, 7, 8]),
        );
        let batch2 = build_table_i32(
            ("a", &vec![9, 10, 11]),
            ("b", &vec![12, 13, 14]),
            ("c", &vec![15, 16, 17]),
        );
        let schema = batch1.schema();
        let data = Arc::new(Mutex::new(Vec::new()));
        let writes = Arc::new(AtomicUsize::new(0));
        let finished = Arc::new(AtomicBool::new(false));
        let aborted = Arc::new(AtomicBool::new(false));

        let spill_writer = YieldingAsyncWriter {
            data: Arc::clone(&data),
            writes: Arc::clone(&writes),
            finished: Arc::clone(&finished),
            aborted: Arc::clone(&aborted),
        };
        let encoder =
            IPCStreamEncoder::new(schema.as_ref(), SpillCompression::Uncompressed)?;
        let mut writer = AsyncIPCStreamWriter::new(Box::new(spill_writer), encoder);

        let (_, first_bytes) = writer.write(&batch1).await?;
        let (_, second_bytes) = writer.write(&batch2).await?;
        let trailing_bytes = writer.finish().await?;

        assert!(finished.load(Ordering::Relaxed));
        assert!(writes.load(Ordering::Relaxed) > 2);
        drop(writer);
        assert!(!aborted.load(Ordering::Relaxed));

        let encoded = data.lock().unwrap().clone();
        assert_eq!(encoded.len(), first_bytes + second_bytes + trailing_bytes);
        let decoded = StreamReader::try_new(Cursor::new(encoded), None)?
            .collect::<arrow::error::Result<Vec<_>>>()?;
        assert_eq!(decoded, vec![batch1, batch2]);
        Ok(())
    }

    #[test]
    fn test_buffer_to_bytes_is_zero_copy() {
        let buffer = Buffer::from(vec![0_u8, 1, 2, 3]).slice_with_length(1, 2);
        let expected_ptr = buffer.as_ptr();
        let bytes = buffer_to_bytes(buffer);

        assert_eq!(bytes.as_ptr(), expected_ptr);
        assert_eq!(bytes.as_ref(), &[1, 2]);
    }

    #[tokio::test]
    async fn test_async_ipc_stream_writer_aborts_after_write_error() -> Result<()> {
        let batch = build_table_i32(
            ("a", &vec![0, 1, 2]),
            ("b", &vec![3, 4, 5]),
            ("c", &vec![6, 7, 8]),
        );
        let aborted = Arc::new(AtomicBool::new(false));
        let encoder = IPCStreamEncoder::new(
            batch.schema().as_ref(),
            SpillCompression::Uncompressed,
        )?;
        let mut writer = AsyncIPCStreamWriter::new(
            Box::new(FailingAsyncWriter {
                aborted: Arc::clone(&aborted),
            }),
            encoder,
        );

        let error = writer.write(&batch).await.unwrap_err();
        assert!(error.to_string().contains("injected spill write failure"));
        assert!(aborted.load(Ordering::Relaxed));
        Ok(())
    }

    #[tokio::test]
    async fn test_async_ipc_stream_writer_aborts_cancelled_finish() -> Result<()> {
        let batch = build_table_i32(
            ("a", &vec![0, 1, 2]),
            ("b", &vec![3, 4, 5]),
            ("c", &vec![6, 7, 8]),
        );
        let finish_started = Arc::new(Notify::new());
        let aborted = Arc::new(Notify::new());
        let abort_count = Arc::new(AtomicUsize::new(0));

        #[expect(clippy::disallowed_methods)] // spawn allowed only in tests
        let task = tokio::spawn({
            let finish_started = Arc::clone(&finish_started);
            let aborted = Arc::clone(&aborted);
            let abort_count = Arc::clone(&abort_count);
            async move {
                let encoder = IPCStreamEncoder::new(
                    batch.schema().as_ref(),
                    SpillCompression::Uncompressed,
                )?;
                let mut writer = AsyncIPCStreamWriter::new(
                    Box::new(PendingFinishAsyncWriter {
                        finish_started,
                        aborted,
                        abort_count,
                    }),
                    encoder,
                );
                writer.write(&batch).await?;
                writer.finish().await?;
                Result::<()>::Ok(())
            }
        });

        if tokio::time::timeout(Duration::from_secs(5), finish_started.notified())
            .await
            .is_err()
        {
            task.abort();
            let _ = task.await;
            panic!("spill finish did not start before the timeout");
        }
        task.abort();
        assert!(task.await.unwrap_err().is_cancelled());
        tokio::time::timeout(Duration::from_secs(1), aborted.notified())
            .await
            .expect("dropping a cancelled writer should abort its upload");
        assert_eq!(abort_count.load(Ordering::Relaxed), 1);
        Ok(())
    }

    #[tokio::test]
    async fn test_async_ipc_stream_writer_retries_failed_abort_on_drop() -> Result<()> {
        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
        let abort_count = Arc::new(AtomicUsize::new(0));
        let cleanup_done = Arc::new(Notify::new());
        let encoder = IPCStreamEncoder::new(&schema, SpillCompression::Uncompressed)?;
        let mut writer = AsyncIPCStreamWriter::new(
            Box::new(FailOnceAbortWriter {
                abort_count: Arc::clone(&abort_count),
                cleanup_done: Arc::clone(&cleanup_done),
            }),
            encoder,
        );

        assert!(writer.abort().await.is_err());
        assert_eq!(abort_count.load(Ordering::Relaxed), 1);
        drop(writer);

        tokio::time::timeout(Duration::from_secs(1), cleanup_done.notified())
            .await
            .expect("dropping a writer should retry an abort that returned an error");
        assert_eq!(abort_count.load(Ordering::Relaxed), 2);
        Ok(())
    }

    #[test]
    fn test_async_ipc_stream_writer_aborts_on_current_runtime() -> Result<()> {
        let batch = build_table_i32(
            ("a", &vec![0, 1, 2]),
            ("b", &vec![3, 4, 5]),
            ("c", &vec![6, 7, 8]),
        );
        let aborted = Arc::new(AtomicBool::new(false));
        let first_runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        let writer = {
            let _runtime_guard = first_runtime.enter();
            let spill_writer = YieldingAsyncWriter {
                data: Arc::new(Mutex::new(Vec::new())),
                writes: Arc::new(AtomicUsize::new(0)),
                finished: Arc::new(AtomicBool::new(false)),
                aborted: Arc::clone(&aborted),
            };
            let encoder = IPCStreamEncoder::new(
                batch.schema().as_ref(),
                SpillCompression::Uncompressed,
            )?;
            AsyncIPCStreamWriter::new(Box::new(spill_writer), encoder)
        };
        drop(first_runtime);

        let second_runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        second_runtime.block_on(async {
            drop(writer);
            tokio::time::timeout(Duration::from_secs(1), async {
                while !aborted.load(Ordering::Relaxed) {
                    tokio::task::yield_now().await;
                }
            })
            .await
            .expect("drop should abort on the current live runtime");
        });
        Ok(())
    }

    #[tokio::test]
    async fn test_batch_spill_and_read() -> Result<()> {
        let batch1 = build_table_i32(
            ("a2", &vec![0, 1, 2]),
            ("b2", &vec![3, 4, 5]),
            ("c2", &vec![4, 5, 6]),
        );

        let batch2 = build_table_i32(
            ("a2", &vec![10, 11, 12]),
            ("b2", &vec![13, 14, 15]),
            ("c2", &vec![14, 15, 16]),
        );

        let schema = batch1.schema();
        let num_rows = batch1.num_rows() + batch2.num_rows();

        // Construct SpillManager
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, Arc::clone(&schema));

        let spill_file = spill_manager
            .spill_record_batch_and_finish(&[batch1, batch2], "Test")?
            .unwrap();
        assert!(spill_file.path().unwrap().exists());
        let spilled_rows = spill_manager.metrics.spilled_rows.value();
        assert_eq!(spilled_rows, num_rows);

        let stream = spill_manager.read_spill_as_stream(spill_file, None)?;
        assert_eq!(stream.schema(), schema);

        let batches = collect(stream).await?;
        assert_eq!(batches.len(), 2);

        Ok(())
    }

    /// Reading a spill file back must not inflate the batches' memory
    /// footprint: the decoder is zero-copy, so without framing every small
    /// batch would keep a whole read chunk alive, see [`MessageFramer`].
    ///
    /// Regression test for
    /// <https://github.com/apache/datafusion/issues/17340>. Without framing
    /// these 50 batches read back at 131072 bytes each, against a 22992 byte
    /// maximum recorded at spill time, and the whole 345 KB stream is
    /// accounted for as 5.9 MB. Note that this is not a counting bug that a
    /// shared-buffer aware counter could net out: holding only 5 of the 50
    /// batches still pins every read chunk, so the memory really is retained.
    #[tokio::test]
    async fn test_read_back_does_not_inflate_batch_memory() -> Result<()> {
        use arrow::array::{ListArray, StringViewArray};
        use arrow::buffer::OffsetBuffer;

        let schema = Arc::new(Schema::new(vec![
            Field::new("i", DataType::Int32, false),
            Field::new("s", DataType::Utf8, false),
            Field::new("v", DataType::Utf8View, true),
            Field::new(
                "l",
                DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
                false,
            ),
        ]));

        // Small batches: many fit in one 128 KB read chunk.
        let batches: Vec<RecordBatch> = (0..50)
            .map(|b| {
                let n = 100;
                let ints = Int32Array::from_iter_values((0..n).map(|i| b * n + i));
                let strs = StringArray::from_iter_values(
                    (0..n).map(|i| format!("string value number {i}")),
                );
                let views = StringViewArray::from_iter((0..n).map(|i| {
                    (i % 3 != 0).then(|| format!("a longer view value {b}/{i}"))
                }));
                let values = Int32Array::from_iter_values(0..n * 2);
                let offsets =
                    OffsetBuffer::from_lengths(std::iter::repeat_n(2, n as usize));
                let list = ListArray::new(
                    Arc::new(Field::new("item", DataType::Int32, true)),
                    offsets,
                    Arc::new(values),
                    None,
                );
                RecordBatch::try_new(
                    Arc::clone(&schema),
                    vec![
                        Arc::new(ints),
                        Arc::new(strs),
                        Arc::new(views),
                        Arc::new(list),
                    ],
                )
                .unwrap()
            })
            .collect();

        let max_written = batches
            .iter()
            .map(get_record_batch_memory_size)
            .max()
            .unwrap();

        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, Arc::clone(&schema));
        let spill_file = spill_manager
            .spill_record_batch_and_finish(&batches, "Test")?
            .unwrap();

        let stream = spill_manager.read_spill_as_stream(spill_file, None)?;
        let read_back = collect(stream).await?;
        assert_eq!(read_back.len(), batches.len());

        for (written, read) in batches.iter().zip(&read_back) {
            assert_eq!(written, read);
            let size = get_record_batch_memory_size(read);
            assert!(
                size <= max_written + SPILL_BATCH_MEMORY_MARGIN,
                "read-back batch retains {size} bytes, written max was {max_written}"
            );
        }
        Ok(())
    }

    /// The workload from <https://github.com/apache/datafusion/issues/17340>,
    /// reduced to a single spilled run.
    ///
    /// `memory_limit::test_stringview_external_sort` sorts 200 batches of 1000
    /// random 100 byte strings under a 60 MB pool, producing around 10 spilled
    /// runs of about 20 batches each. This spills one such run and reads it
    /// back through the same [`SpillManager`] calls the external sorter and the
    /// multi-level merge use: the spill records the largest batch's memory size,
    /// and the merge reserves its budget from that number, so a batch that comes
    /// back bigger is memory the merge is using without having reserved it.
    ///
    /// Each batch here is around 167 KB, larger than the 128 KB read chunk, so
    /// every IPC message spans chunks. Without framing the decoder gathers such
    /// a message into a `Vec` grown by doubling and the batch keeps the spare
    /// capacity, so these batches read back at about 255 KB each against the
    /// ~167 KB recorded at spill time - half again the budget the merge
    /// reserved for them, which is the discrepancy the issue reports.
    #[tokio::test]
    async fn test_stringview_spill_read_back_memory_accounting() -> Result<()> {
        use arrow::array::StringViewArray;
        use rand::Rng;

        let schema = Arc::new(Schema::new(vec![
            Field::new("strings", DataType::Utf8View, false),
            Field::new("random_numbers", DataType::Int32, false),
        ]));

        // 100 random bytes per string, as in the issue's reproducer: long
        // enough that the views point into a data buffer rather than inlining,
        // and random so nothing dedupes.
        let mut rng = rand::rng();
        let batches: Vec<RecordBatch> = (0..20)
            .map(|_| {
                let strings: Vec<String> = (0..1000)
                    .map(|_| {
                        (0..100)
                            .map(|_| rng.random_range(0..=u8::MAX) as char)
                            .collect()
                    })
                    .collect();
                let numbers: Vec<i32> =
                    (0..1000).map(|_| rng.random_range(0..=1000)).collect();
                RecordBatch::try_new(
                    Arc::clone(&schema),
                    vec![
                        Arc::new(StringViewArray::from(strings)) as ArrayRef,
                        Arc::new(Int32Array::from(numbers)) as ArrayRef,
                    ],
                )
                .unwrap()
            })
            .collect();

        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, Arc::clone(&schema));

        // The same call the external sorter spills a sorted run with: the
        // returned size is what the merge budgets against.
        let (spill_file, max_record_batch_memory) = spill_manager
            .spill_record_batch_iter_and_return_max_batch_memory(
                batches
                    .iter()
                    .map(Ok::<_, datafusion_common::DataFusionError>),
                "Test",
            )?
            .unwrap();

        let stream = spill_manager
            .read_spill_as_stream(spill_file, Some(max_record_batch_memory))?;
        let read_back = collect(stream).await?;
        assert_eq!(read_back.len(), batches.len());

        for (written, read) in batches.iter().zip(&read_back) {
            assert_eq!(written, read);
            let size = get_record_batch_memory_size(read);
            assert!(
                size <= max_record_batch_memory + SPILL_BATCH_MEMORY_MARGIN,
                "read-back batch retains {size} bytes, but the merge only \
                 reserved for {max_record_batch_memory} bytes"
            );
        }
        Ok(())
    }

    /// Frames an IPC stream delivered in chunks of `chunk_size` bytes and
    /// decodes it, checking that every batch is intact and that its buffers
    /// are backed by an allocation no larger than its own message body.
    fn frame_and_decode(ipc: &[u8], chunk_size: usize, expected: &[RecordBatch]) {
        let mut framer = MessageFramer::new();
        let mut decoder = StreamDecoder::new();
        let mut decoded = vec![];
        for chunk in ipc.chunks(chunk_size) {
            let mut input = Buffer::from(chunk);
            while !input.is_empty() {
                let Some(buffers) = framer.push(&mut input).unwrap() else {
                    continue;
                };
                let body_size = buffers.last().unwrap().len();
                for mut buffer in buffers {
                    while !buffer.is_empty() {
                        if let Some(batch) = decoder.decode(&mut buffer).unwrap() {
                            let retained = get_record_batch_memory_size(&batch);
                            assert!(
                                retained <= body_size,
                                "batch retains {retained} bytes for a {body_size} byte body"
                            );
                            decoded.push(batch);
                        }
                    }
                }
            }
        }
        decoder.finish().unwrap();
        assert!(matches!(framer.state, FramerState::Finished));
        assert_eq!(decoded, expected);
    }

    #[test]
    fn test_message_framer_across_chunk_boundaries() {
        let batches: Vec<RecordBatch> = (0..5)
            .map(|b| {
                let n = 10 * (b + 1);
                build_table_i32(
                    ("a", &(0..n).collect::<Vec<_>>()),
                    ("b", &(n..2 * n).collect::<Vec<_>>()),
                    ("c", &(2 * n..3 * n).collect::<Vec<_>>()),
                )
            })
            .collect();
        let schema = batches[0].schema();

        let mut ipc = vec![];
        let mut writer = StreamWriter::try_new(&mut ipc, &schema).unwrap();
        for batch in &batches {
            writer.write(batch).unwrap();
        }
        writer.finish().unwrap();

        for chunk_size in [1, 3, 7, 64, 1000, ipc.len()] {
            frame_and_decode(&ipc, chunk_size, &batches);
        }
    }

    /// Decodes `ipc` the way the reader did before framing, returning the
    /// number of batches or `Err` if the stream is not a complete one.
    fn decode_unframed(ipc: &[u8]) -> std::result::Result<usize, ()> {
        let mut decoder = StreamDecoder::new();
        let mut buffer = Buffer::from(ipc);
        let mut batches = 0;
        while !buffer.is_empty() {
            match decoder.decode(&mut buffer) {
                Ok(Some(_)) => batches += 1,
                Ok(None) => {}
                Err(_) => return Err(()),
            }
        }
        decoder.finish().map_err(|_| ())?;
        Ok(batches)
    }

    /// Same as [`decode_unframed`], but through the [`MessageFramer`].
    fn decode_framed(ipc: &[u8]) -> std::result::Result<usize, ()> {
        let mut framer = MessageFramer::new();
        let mut decoder = StreamDecoder::new();
        let mut input = Buffer::from(ipc);
        let mut batches = 0;
        while !input.is_empty() {
            let Some(buffers) = framer.push(&mut input).map_err(|_| ())? else {
                continue;
            };
            for mut buffer in buffers {
                while !buffer.is_empty() {
                    match decoder.decode(&mut buffer) {
                        Ok(Some(_)) => batches += 1,
                        Ok(None) => {}
                        Err(_) => return Err(()),
                    }
                }
            }
        }
        framer.finish().map_err(|_| ())?;
        decoder.finish().map_err(|_| ())?;
        Ok(batches)
    }

    /// Framing must not weaken the reader's detection of a corrupt or cut
    /// short spill file. The partial bytes of an incomplete trailing message
    /// end up in the [`MessageFramer`] instead of the decoder's own scratch
    /// space, so the framer has to report them, see [`MessageFramer::finish`].
    ///
    /// Truncated at every possible offset, framed decoding must accept and
    /// reject exactly what unframed decoding does.
    #[test]
    fn test_message_framer_reports_truncation_like_the_decoder() {
        let batches: Vec<RecordBatch> = (0..3)
            .map(|b| {
                build_table_i32(
                    ("a", &(0..50).map(|i| b * 50 + i).collect::<Vec<_>>()),
                    ("b", &(0..50).collect::<Vec<_>>()),
                    ("c", &(0..50).collect::<Vec<_>>()),
                )
            })
            .collect();

        let mut ipc = vec![];
        let mut writer = StreamWriter::try_new(&mut ipc, &batches[0].schema()).unwrap();
        for batch in &batches {
            writer.write(batch).unwrap();
        }
        writer.finish().unwrap();

        let mut complete = 0;
        for cut in 0..=ipc.len() {
            let truncated = &ipc[..cut];
            let framed = decode_framed(truncated);
            assert_eq!(
                framed,
                decode_unframed(truncated),
                "framed and unframed decoding disagree on a stream cut to {cut} bytes"
            );
            complete += usize::from(framed.is_ok());
        }
        // Cutting anywhere but on a message boundary must be an error, so
        // only the empty stream, the three batches and the end-of-stream
        // marker may decode cleanly.
        assert_eq!(complete, 5);
        assert_eq!(decode_framed(&ipc), Ok(batches.len()));
    }

    /// End-to-end: a spill file cut short mid-message must error rather than
    /// silently read back as a shorter stream.
    #[tokio::test]
    async fn test_truncated_spill_file_errors() -> Result<()> {
        let batch = build_table_i32(
            ("a", &(0..100).collect::<Vec<_>>()),
            ("b", &(100..200).collect::<Vec<_>>()),
            ("c", &(200..300).collect::<Vec<_>>()),
        );
        let schema = batch.schema();
        let batches = vec![batch.clone(), batch];

        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, Arc::clone(&schema));
        let spill_file = spill_manager
            .spill_record_batch_and_finish(&batches, "Test")?
            .unwrap();

        // Truncate the file mid-message: drop the 8 byte end-of-stream
        // marker plus part of the last batch's body.
        let path = spill_file.path().unwrap().to_path_buf();
        let len = std::fs::metadata(&path)?.len();
        let f = std::fs::OpenOptions::new().write(true).open(&path)?;
        f.set_len(len - 8 - 13)?;
        drop(f);

        let stream = spill_manager.read_spill_as_stream(spill_file, None)?;
        let result = collect(stream).await;
        assert!(
            result.is_err(),
            "truncated spill file should error, got Ok with {} batches",
            result.as_ref().map(|b| b.len()).unwrap_or(0)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_batch_spill_and_read_dictionary_arrays() -> Result<()> {
        // See https://github.com/apache/datafusion/issues/4658

        let batch1 = build_table_i32(
            ("a2", &vec![0, 1, 2]),
            ("b2", &vec![3, 4, 5]),
            ("c2", &vec![4, 5, 6]),
        );

        let batch2 = build_table_i32(
            ("a2", &vec![10, 11, 12]),
            ("b2", &vec![13, 14, 15]),
            ("c2", &vec![14, 15, 16]),
        );

        // Dictionary encode the arrays
        let dict_type =
            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Int32));
        let dict_schema = Arc::new(Schema::new(vec![
            Field::new("a2", dict_type.clone(), true),
            Field::new("b2", dict_type.clone(), true),
            Field::new("c2", dict_type.clone(), true),
        ]));

        let batch1 = RecordBatch::try_new(
            Arc::clone(&dict_schema),
            batch1
                .columns()
                .iter()
                .map(|array| cast(array, &dict_type))
                .collect::<Result<_, _>>()?,
        )?;

        let batch2 = RecordBatch::try_new(
            Arc::clone(&dict_schema),
            batch2
                .columns()
                .iter()
                .map(|array| cast(array, &dict_type))
                .collect::<Result<_, _>>()?,
        )?;

        // Construct SpillManager
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, Arc::clone(&dict_schema));

        let num_rows = batch1.num_rows() + batch2.num_rows();
        let spill_file = spill_manager
            .spill_record_batch_and_finish(&[batch1, batch2], "Test")?
            .unwrap();
        let spilled_rows = spill_manager.metrics.spilled_rows.value();
        assert_eq!(spilled_rows, num_rows);

        let stream = spill_manager.read_spill_as_stream(spill_file, None)?;
        assert_eq!(stream.schema(), dict_schema);
        let batches = collect(stream).await?;
        assert_eq!(batches.len(), 2);

        Ok(())
    }

    #[tokio::test]
    async fn test_batch_spill_by_size() -> Result<()> {
        let batch1 = build_table_i32(
            ("a2", &vec![0, 1, 2, 3]),
            ("b2", &vec![3, 4, 5, 6]),
            ("c2", &vec![4, 5, 6, 7]),
        );

        let schema = batch1.schema();
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, Arc::clone(&schema));

        let row_batches: Vec<RecordBatch> =
            (0..batch1.num_rows()).map(|i| batch1.slice(i, 1)).collect();
        let (spill_file, max_batch_mem) = spill_manager
            .spill_record_batch_iter_and_return_max_batch_memory(
                row_batches.iter().map(Ok),
                "Test Spill",
            )?
            .unwrap();
        assert!(spill_file.path().unwrap().exists());
        assert!(max_batch_mem > 0);

        let stream = spill_manager.read_spill_as_stream(spill_file, None)?;
        assert_eq!(stream.schema(), schema);

        let batches = collect(stream).await?;
        assert_eq!(batches.len(), 4);

        Ok(())
    }

    fn build_compressible_batch() -> RecordBatch {
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Utf8, false),
            Field::new("b", DataType::Int32, false),
            Field::new("c", DataType::Int32, true),
        ]));

        let a: ArrayRef = Arc::new(StringArray::from_iter_values(std::iter::repeat_n(
            "repeated", 100,
        )));
        let b: ArrayRef = Arc::new(Int32Array::from(vec![1; 100]));
        let c: ArrayRef = Arc::new(Int32Array::from(vec![2; 100]));

        RecordBatch::try_new(schema, vec![a, b, c]).unwrap()
    }

    async fn validate(
        spill_manager: &SpillManager,
        spill_file: Arc<dyn SpillFile>,
        num_rows: usize,
        schema: SchemaRef,
        batch_count: usize,
    ) -> Result<()> {
        let spilled_rows = spill_manager.metrics.spilled_rows.value();
        assert_eq!(spilled_rows, num_rows);

        let stream = spill_manager.read_spill_as_stream(spill_file, None)?;
        assert_eq!(stream.schema(), schema);

        let batches = collect(stream).await?;
        assert_eq!(batches.len(), batch_count);

        Ok(())
    }

    #[tokio::test]
    async fn test_spill_compression() -> Result<()> {
        let batch = build_compressible_batch();
        let num_rows = batch.num_rows();
        let schema = batch.schema();
        let batch_count = 1;
        let batches = [batch];

        // Construct SpillManager
        let env = Arc::new(RuntimeEnv::default());
        let uncompressed_metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let lz4_metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let zstd_metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let uncompressed_spill_manager = SpillManager::new(
            Arc::clone(&env),
            uncompressed_metrics,
            Arc::clone(&schema),
        );
        let lz4_spill_manager =
            SpillManager::new(Arc::clone(&env), lz4_metrics, Arc::clone(&schema))
                .with_compression_type(SpillCompression::Lz4Frame);
        let zstd_spill_manager =
            SpillManager::new(env, zstd_metrics, Arc::clone(&schema))
                .with_compression_type(SpillCompression::Zstd);
        let uncompressed_spill_file = uncompressed_spill_manager
            .spill_record_batch_and_finish(&batches, "Test")?
            .unwrap();
        let lz4_spill_file = lz4_spill_manager
            .spill_record_batch_and_finish(&batches, "Lz4_Test")?
            .unwrap();
        let zstd_spill_file = zstd_spill_manager
            .spill_record_batch_and_finish(&batches, "ZSTD_Test")?
            .unwrap();
        assert!(uncompressed_spill_file.path().unwrap().exists());
        assert!(lz4_spill_file.path().unwrap().exists());
        assert!(zstd_spill_file.path().unwrap().exists());

        let lz4_spill_size = std::fs::metadata(lz4_spill_file.path().unwrap())?.len();
        let zstd_spill_size = std::fs::metadata(zstd_spill_file.path().unwrap())?.len();
        let uncompressed_spill_size =
            std::fs::metadata(uncompressed_spill_file.path().unwrap())?.len();

        assert!(uncompressed_spill_size > lz4_spill_size);
        assert!(uncompressed_spill_size > zstd_spill_size);

        validate(
            &lz4_spill_manager,
            lz4_spill_file,
            num_rows,
            Arc::clone(&schema),
            batch_count,
        )
        .await?;
        validate(
            &zstd_spill_manager,
            zstd_spill_file,
            num_rows,
            Arc::clone(&schema),
            batch_count,
        )
        .await?;
        validate(
            &uncompressed_spill_manager,
            uncompressed_spill_file,
            num_rows,
            schema,
            batch_count,
        )
        .await?;
        Ok(())
    }

    // ==== Spill manager tests ====

    #[test]
    fn test_spill_manager_spill_record_batch_and_finish() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Utf8, false),
        ]));

        let spill_manager = SpillManager::new(env, metrics, Arc::clone(&schema));

        let batch = RecordBatch::try_new(
            schema,
            vec![
                Arc::new(Int32Array::from(vec![1, 2, 3])),
                Arc::new(StringArray::from(vec!["a", "b", "c"])),
            ],
        )?;

        let temp_file = spill_manager.spill_record_batch_and_finish(&[batch], "Test")?;
        assert!(temp_file.is_some());
        assert!(temp_file.unwrap().path().unwrap().exists());
        Ok(())
    }

    fn verify_metrics(
        in_progress_file: &InProgressSpillFile,
        expected_spill_file_count: usize,
        expected_spilled_bytes: usize,
        expected_spilled_rows: usize,
    ) -> Result<()> {
        let actual_spill_file_count = in_progress_file
            .spill_manager
            .metrics
            .spill_file_count
            .value();
        let actual_spilled_bytes =
            in_progress_file.spill_manager.metrics.spilled_bytes.value();
        let actual_spilled_rows =
            in_progress_file.spill_manager.metrics.spilled_rows.value();

        assert_eq!(
            actual_spill_file_count, expected_spill_file_count,
            "Spill file count mismatch"
        );
        assert_eq!(
            actual_spilled_bytes, expected_spilled_bytes,
            "Spilled bytes mismatch"
        );
        assert_eq!(
            actual_spilled_rows, expected_spilled_rows,
            "Spilled rows mismatch"
        );

        Ok(())
    }

    #[test]
    fn test_in_progress_spill_file_append_and_finish() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Utf8, false),
        ]));

        let spill_manager =
            Arc::new(SpillManager::new(env, metrics, Arc::clone(&schema)));
        let mut in_progress_file = spill_manager.create_in_progress_file("Test")?;

        let batch1 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(vec![1, 2, 3])),
                Arc::new(StringArray::from(vec!["a", "b", "c"])),
            ],
        )?;

        let batch2 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(vec![4, 5, 6])),
                Arc::new(StringArray::from(vec!["d", "e", "f"])),
            ],
        )?;
        // After appending each batch, spilled_rows and spilled_bytes should increase incrementally,
        // while spill_file_count remains 1 (since we're writing to the same file)
        in_progress_file.append_batch(&batch1)?;
        verify_metrics(&in_progress_file, 1, 424, 3)?;

        in_progress_file.append_batch(&batch2)?;
        verify_metrics(&in_progress_file, 1, 672, 6)?;

        let completed_file = in_progress_file.finish()?;
        assert!(completed_file.is_some());
        assert!(completed_file.unwrap().path().unwrap().exists());
        verify_metrics(&in_progress_file, 1, 680, 6)?;
        // Double finish produce error
        let result = in_progress_file.finish();
        assert!(result.is_err());

        Ok(())
    }

    // Test write no batches
    #[test]
    fn test_in_progress_spill_file_write_no_batches() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Utf8, false),
        ]));

        let spill_manager =
            Arc::new(SpillManager::new(env, metrics, Arc::clone(&schema)));

        // Test write empty batch with interface `InProgressSpillFile` and `append_batch()`
        let mut in_progress_file = spill_manager.create_in_progress_file("Test")?;
        let completed_file = in_progress_file.finish()?;
        assert!(completed_file.is_none());

        // Test write empty batch with interface `spill_record_batch_and_finish()`
        let completed_file = spill_manager.spill_record_batch_and_finish(&[], "Test")?;
        assert!(completed_file.is_none());

        // Test write empty batch with interface `spill_record_batch_iter_and_return_max_batch_memory()`
        let empty_batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(Vec::<Option<i32>>::new())),
                Arc::new(StringArray::from(Vec::<Option<&str>>::new())),
            ],
        )?;
        let completed_file = spill_manager
            .spill_record_batch_iter_and_return_max_batch_memory(
                std::iter::once(Ok(&empty_batch)),
                "Test",
            )?;
        assert!(completed_file.is_none());

        Ok(())
    }

    #[test]
    fn test_reading_more_spills_than_tokio_blocking_threads() -> Result<()> {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .max_blocking_threads(1)
            .build()
            .unwrap()
            .block_on(async {
                let batch = build_table_i32(
                    ("a2", &vec![0, 1, 2]),
                    ("b2", &vec![3, 4, 5]),
                    ("c2", &vec![4, 5, 6]),
                );

                let schema = batch.schema();

                // Construct SpillManager
                let env = Arc::new(RuntimeEnv::default());
                let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
                let spill_manager = SpillManager::new(env, metrics, Arc::clone(&schema));
                let batches: [_; 10] = std::array::from_fn(|_| batch.clone());

                let spill_file_1 = spill_manager
                    .spill_record_batch_and_finish(&batches, "Test1")?
                    .unwrap();
                let spill_file_2 = spill_manager
                    .spill_record_batch_and_finish(&batches, "Test2")?
                    .unwrap();

                let mut stream_1 =
                    spill_manager.read_spill_as_stream(spill_file_1, None)?;
                let mut stream_2 =
                    spill_manager.read_spill_as_stream(spill_file_2, None)?;
                stream_1.next().await;
                stream_2.next().await;

                Ok(())
            })
    }

    #[test]
    fn test_alignment_for_schema() -> Result<()> {
        let schema = Schema::new(vec![Field::new("strings", DataType::Utf8View, false)]);
        let alignment = get_max_alignment_for_schema(&schema);
        assert_eq!(alignment, 16);

        let schema = Schema::new(vec![
            Field::new("int32", DataType::Int32, false),
            Field::new("int64", DataType::Int64, false),
        ]);
        let alignment = get_max_alignment_for_schema(&schema);
        assert_eq!(alignment, 8);
        Ok(())
    }
    #[tokio::test]
    async fn test_real_time_spill_metrics() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Utf8, false),
        ]));

        let spill_manager = Arc::new(SpillManager::new(
            Arc::clone(&env),
            metrics.clone(),
            Arc::clone(&schema),
        ));
        let mut in_progress_file = spill_manager.create_in_progress_file("Test")?;

        let batch1 = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int32Array::from(vec![1, 2, 3])),
                Arc::new(StringArray::from(vec!["a", "b", "c"])),
            ],
        )?;

        // Before any batch, metrics should be 0
        assert_eq!(metrics.spilled_bytes.value(), 0);
        assert_eq!(metrics.spill_file_count.value(), 0);

        // Append first batch
        in_progress_file.append_batch(&batch1)?;

        // Metrics should be updated immediately (at least schema and first batch)
        let bytes_after_batch1 = metrics.spilled_bytes.value();
        assert_eq!(bytes_after_batch1, 424);
        assert_eq!(metrics.spill_file_count.value(), 1);

        // Check global progress
        let progress = env.spilling_progress();
        assert_eq!(progress.current_bytes, bytes_after_batch1 as u64);
        assert_eq!(progress.active_files_count, 1);

        // Append another batch
        in_progress_file.append_batch(&batch1)?;
        let bytes_after_batch2 = metrics.spilled_bytes.value();
        assert!(bytes_after_batch2 > bytes_after_batch1);

        // Check global progress again
        let progress = env.spilling_progress();
        assert_eq!(progress.current_bytes, bytes_after_batch2 as u64);

        // Finish the file
        let spilled_file = in_progress_file.finish()?;
        let final_bytes = metrics.spilled_bytes.value();
        assert!(final_bytes > bytes_after_batch2);

        // Even after finish, file is still "active" until dropped
        let progress = env.spilling_progress();
        assert!(progress.current_bytes > 0);
        assert_eq!(progress.active_files_count, 1);

        drop(spilled_file);
        assert_eq!(env.spilling_progress().active_files_count, 0);
        assert_eq!(env.spilling_progress().current_bytes, 0);

        Ok(())
    }

    #[test]
    fn test_gc_string_view_before_spill() -> Result<()> {
        use arrow::array::StringViewArray;

        let strings: Vec<String> = (0..200)
            .map(|i| {
                if i % 2 == 0 {
                    "short_string".to_string()
                } else {
                    "this_is_a_much_longer_string_that_will_not_be_inlined".to_string()
                }
            })
            .collect();

        let string_array = StringViewArray::from(strings);
        let schema = Arc::new(Schema::new(vec![Field::new(
            "strings",
            DataType::Utf8View,
            false,
        )]));

        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(string_array) as ArrayRef],
        )?;
        let sliced_batch = batch.slice(0, 20);
        let gc_batch = gc_view_arrays(&sliced_batch)?;

        assert_eq!(gc_batch.num_rows(), sliced_batch.num_rows());
        assert_eq!(gc_batch.num_columns(), sliced_batch.num_columns());

        Ok(())
    }

    #[test]
    fn test_gc_binary_view_before_spill() -> Result<()> {
        use arrow::array::BinaryViewArray;

        let binaries: Vec<Vec<u8>> = (0..200)
            .map(|i| {
                if i % 2 == 0 {
                    vec![1, 2, 3, 4]
                } else {
                    vec![1; 50]
                }
            })
            .collect();

        let binary_array =
            BinaryViewArray::from_iter(binaries.iter().map(|b| Some(b.as_slice())));
        let schema = Arc::new(Schema::new(vec![Field::new(
            "binaries",
            DataType::BinaryView,
            false,
        )]));

        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(binary_array) as ArrayRef],
        )?;
        let sliced_batch = batch.slice(0, 20);
        let gc_batch = gc_view_arrays(&sliced_batch)?;

        assert_eq!(gc_batch.num_rows(), sliced_batch.num_rows());
        assert_eq!(gc_batch.num_columns(), sliced_batch.num_columns());

        Ok(())
    }

    #[test]
    fn test_gc_skips_small_arrays() -> Result<()> {
        use arrow::array::StringViewArray;

        let strings: Vec<String> = (0..10).map(|i| format!("string_{i}")).collect();

        let string_array = StringViewArray::from(strings);
        let array_ref: ArrayRef = Arc::new(string_array);

        let schema = Arc::new(Schema::new(vec![Field::new(
            "strings",
            DataType::Utf8View,
            false,
        )]));

        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![array_ref])?;

        // GC should return the original batch for small arrays
        let array = batch
            .column(0)
            .as_any()
            .downcast_ref::<StringViewArray>()
            .unwrap();
        let should_gc = should_gc_view_array(array, data_buffers_size(array));
        let gc_batch = gc_view_arrays(&batch)?;

        assert!(!should_gc);
        assert_eq!(gc_batch.num_rows(), batch.num_rows());
        assert!(Arc::ptr_eq(batch.column(0), gc_batch.column(0)));

        Ok(())
    }

    #[test]
    fn test_gc_with_mixed_columns() -> Result<()> {
        use arrow::array::{Int32Array, StringViewArray};

        let strings: Vec<String> = (0..200)
            .map(|i| format!("long_string_for_gc_testing_{i}"))
            .collect();

        let string_array = StringViewArray::from(strings);
        let int_array = Int32Array::from((0..200).collect::<Vec<i32>>());

        let schema = Arc::new(Schema::new(vec![
            Field::new("strings", DataType::Utf8View, false),
            Field::new("ints", DataType::Int32, false),
        ]));

        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(string_array) as ArrayRef,
                Arc::new(int_array) as ArrayRef,
            ],
        )?;

        let sliced_batch = batch.slice(0, 50);
        let gc_batch = gc_view_arrays(&sliced_batch)?;

        assert_eq!(gc_batch.num_columns(), 2);
        assert_eq!(gc_batch.num_rows(), 50);

        Ok(())
    }

    #[test]
    fn test_verify_gc_triggers_for_sliced_arrays() -> Result<()> {
        let strings: Vec<String> = (0..200)
            .map(|i| {
                format!(
                    "http://example.com/very/long/path/that/exceeds/inline/threshold/{i}"
                )
            })
            .collect();

        let string_array = StringViewArray::from(strings);
        let schema = Arc::new(Schema::new(vec![Field::new(
            "url",
            DataType::Utf8View,
            false,
        )]));

        let batch = RecordBatch::try_new(
            schema,
            vec![Arc::new(string_array.clone()) as ArrayRef],
        )?;

        let sliced = batch.slice(0, 20);

        let sliced_array = sliced
            .column(0)
            .as_any()
            .downcast_ref::<StringViewArray>()
            .unwrap();
        let should_gc =
            should_gc_view_array(sliced_array, data_buffers_size(sliced_array));
        let waste_ratio = calculate_string_view_waste_ratio(sliced_array);

        assert!(
            waste_ratio > 0.8,
            "Waste ratio should be > 0.8 for sliced array"
        );
        assert!(
            should_gc,
            "GC should trigger for sliced array with high waste"
        );

        Ok(())
    }

    #[test]
    fn test_reproduce_issue_19414_string_view_spill_without_gc() -> Result<()> {
        use arrow::array::StringViewArray;
        use std::fs;

        let num_rows = 1000;
        let mut strings = Vec::with_capacity(num_rows);

        for i in 0..num_rows {
            let url = match i % 5 {
                0 => format!(
                    "http://irr.ru/index.php?showalbum/login-leniya7777294,938303130/{i}"
                ),
                1 => format!("http://komme%2F27.0.1453.116/very/long/path/{i}"),
                2 => format!("https://produkty%2Fproduct/category/item/{i}"),
                3 => format!(
                    "http://irr.ru/index.php?showalbum/login-kapusta-advert2668/{i}"
                ),
                4 => format!(
                    "http://irr.ru/index.php?showalbum/login-kapustic/product/{i}"
                ),
                _ => unreachable!(),
            };
            strings.push(url);
        }

        let string_array = StringViewArray::from(strings);
        let schema = Arc::new(Schema::new(vec![Field::new(
            "URL",
            DataType::Utf8View,
            false,
        )]));

        let original_batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(string_array.clone()) as ArrayRef],
        )?;

        let total_buffer_size: usize = string_array
            .data_buffers()
            .iter()
            .map(|buffer| buffer.capacity())
            .sum();

        let mut sliced_batches = Vec::new();
        let slice_size = 100;

        for i in (0..num_rows).step_by(slice_size) {
            let len = std::cmp::min(slice_size, num_rows - i);
            let sliced = original_batch.slice(i, len);
            sliced_batches.push(sliced);
        }

        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, schema);

        let mut in_progress_file = spill_manager.create_in_progress_file("Test GC")?;

        for batch in &sliced_batches {
            in_progress_file.append_batch(batch)?;
        }

        let spill_file = in_progress_file.finish()?.unwrap();
        let file_size = fs::metadata(spill_file.path().unwrap())?.len() as usize;

        let theoretical_without_gc = total_buffer_size * sliced_batches.len();
        let reduction_percent = ((theoretical_without_gc - file_size) as f64
            / theoretical_without_gc as f64)
            * 100.0;

        assert!(
            reduction_percent > 80.0,
            "GC should reduce spill file size by >80%, got {reduction_percent:.1}%"
        );

        Ok(())
    }

    #[test]
    fn test_spill_with_and_without_gc_comparison() -> Result<()> {
        let num_rows = 400;
        let strings: Vec<String> = (0..num_rows)
            .map(|i| {
                format!(
                    "http://example.com/this/is/a/long/url/path/that/wont/be/inlined/{i}"
                )
            })
            .collect();

        let string_array = StringViewArray::from(strings);
        let schema = Arc::new(Schema::new(vec![Field::new(
            "url",
            DataType::Utf8View,
            false,
        )]));

        let batch =
            RecordBatch::try_new(schema, vec![Arc::new(string_array) as ArrayRef])?;

        let sliced_batch = batch.slice(0, 40);

        let array_without_gc = sliced_batch
            .column(0)
            .as_any()
            .downcast_ref::<StringViewArray>()
            .unwrap();
        let size_without_gc: usize = array_without_gc
            .data_buffers()
            .iter()
            .map(|buffer| buffer.capacity())
            .sum();

        let gc_batch = gc_view_arrays(&sliced_batch)?;
        let array_with_gc = gc_batch
            .column(0)
            .as_any()
            .downcast_ref::<StringViewArray>()
            .unwrap();
        let size_with_gc: usize = array_with_gc
            .data_buffers()
            .iter()
            .map(|buffer| buffer.capacity())
            .sum();

        let reduction_percent =
            ((size_without_gc - size_with_gc) as f64 / size_without_gc as f64) * 100.0;

        assert!(
            reduction_percent > 85.0,
            "Expected >85% reduction for 10% slice, got {reduction_percent:.1}%"
        );

        Ok(())
    }

    /// `len` distinct 63 byte values in a single data buffer
    fn dictionary_array(len: u32) -> Result<StringViewArray> {
        use arrow::array::AsArray;

        let values = StringArray::from_iter_values(
            (0..len).map(|i| format!("container-id-{i:0>50}")),
        );
        // Casting to Utf8View keeps the values in the one existing buffer
        let dictionary = cast(&values, &DataType::Utf8View)?;
        let dictionary = dictionary.as_string_view().clone();
        assert_eq!(dictionary.data_buffers().len(), 1);
        Ok(dictionary)
    }

    /// Arrays that each hold views into one shared dictionary buffer, as the
    /// Parquet reader produces for a dictionary-encoded column, combined with
    /// `concat` as a sort combines its buffered batches. The rows cycle through
    /// the dictionary (<https://github.com/apache/datafusion/issues/23564>).
    fn shared_dictionary_views(
        dictionary_len: u32,
        inputs: u32,
        rows_per_input: u32,
    ) -> Result<(StringViewArray, StringViewArray)> {
        use arrow::array::{AsArray, UInt32Array};
        use arrow::compute::{concat, take};

        let dictionary = dictionary_array(dictionary_len)?;
        let arrays = (0..inputs)
            .map(|input| {
                let indices = UInt32Array::from_iter_values(
                    (0..rows_per_input)
                        .map(|row| (input * rows_per_input + row) % dictionary_len),
                );
                take(&dictionary, &indices, None)
            })
            .collect::<std::result::Result<Vec<_>, _>>()?;
        let arrays: Vec<&dyn Array> = arrays.iter().map(|a| a.as_ref()).collect();
        let merged = concat(&arrays)?;
        Ok((dictionary, merged.as_string_view().clone()))
    }

    #[test]
    fn test_gc_keeps_shared_dictionary_buffer() -> Result<()> {
        let (dictionary, merged) = shared_dictionary_views(1000, 8, 1024)?;
        // `concat` lists the dictionary once per input
        assert_eq!(merged.data_buffers().len(), 8);
        // `gc()` would copy 8192 values of 63 bytes, 8x the dictionary
        assert!(merged.total_buffer_bytes_used() > data_buffers_size(&dictionary));

        let compacted = compact_view_array(&merged).expect("buffer entries repeat");
        assert_eq!(compacted.data_buffers().len(), 1);
        assert_eq!(
            compacted.data_buffers()[0].as_ptr(),
            dictionary.data_buffers()[0].as_ptr()
        );
        assert_eq!(compacted, merged);

        Ok(())
    }

    #[test]
    fn test_gc_small_slice_of_shared_buffer() -> Result<()> {
        // 8 inputs of 4 rows each reference a 63 KB dictionary: `gc()` writes
        // 32 values, far less than the dictionary
        let (dictionary, merged) = shared_dictionary_views(1000, 8, 4)?;
        assert_eq!(merged.data_buffers().len(), 8);

        let compacted = compact_view_array(&merged).expect("gc() is smaller");
        assert_eq!(compacted.data_buffers().len(), 1);
        assert_eq!(data_buffers_size(&compacted), 32 * 63);
        assert_ne!(
            compacted.data_buffers()[0].as_ptr(),
            dictionary.data_buffers()[0].as_ptr()
        );
        assert_eq!(compacted, merged);

        Ok(())
    }

    #[test]
    fn test_gc_shared_buffer_with_nulls() -> Result<()> {
        use arrow::array::{AsArray, BooleanArray};
        use arrow::compute::nullif;

        let (_, merged) = shared_dictionary_views(1000, 8, 1024)?;
        let mask = BooleanArray::from_iter((0..merged.len()).map(|i| Some(i % 7 == 0)));
        let with_nulls = nullif(&merged, &mask)?;
        let with_nulls = with_nulls.as_string_view();

        let compacted = compact_view_array(with_nulls).expect("buffer entries repeat");
        assert_eq!(compacted.data_buffers().len(), 1);
        assert_eq!(compacted.null_count(), with_nulls.null_count());
        assert_eq!(&compacted, with_nulls);

        Ok(())
    }

    #[test]
    fn test_gc_skips_array_that_shares_one_buffer() -> Result<()> {
        use arrow::array::{AsArray, UInt32Array};
        use arrow::compute::take;

        // 10,000 views into one 63 KB dictionary: `gc()` would write 630 KB
        let dictionary = dictionary_array(1000)?;
        let indices = UInt32Array::from_iter_values((0..10_000).map(|i| i % 1000));
        let shared = take(&dictionary, &indices, None)?;
        let schema = Arc::new(Schema::new(vec![Field::new(
            "label",
            DataType::Utf8View,
            false,
        )]));
        let batch = RecordBatch::try_new(schema, vec![Arc::clone(&shared)])?;

        assert!(compact_view_array(shared.as_string_view()).is_none());
        let gc_batch = gc_view_arrays(&batch)?;
        assert!(Arc::ptr_eq(batch.column(0), gc_batch.column(0)));

        Ok(())
    }

    #[test]
    fn test_spill_shared_dictionary_writes_it_once() -> Result<()> {
        let (dictionary, merged) = shared_dictionary_views(1000, 8, 1024)?;
        let schema = Arc::new(Schema::new(vec![Field::new(
            "label",
            DataType::Utf8View,
            false,
        )]));
        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(merged)])?;

        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, schema);
        let mut in_progress_file = spill_manager.create_in_progress_file("Test GC")?;
        in_progress_file.append_batch(&batch)?;
        let spill_file = in_progress_file.finish()?.unwrap();
        let file_size = std::fs::metadata(spill_file.path().unwrap())?.len() as usize;

        // The views and one copy of the dictionary, not 8192 copied values
        let views_size = batch.num_rows() * VIEW_SIZE_BYTES;
        let dictionary_size = data_buffers_size(&dictionary);
        assert!(
            file_size < views_size + 2 * dictionary_size,
            "spill file is {file_size} bytes, views {views_size}, dictionary {dictionary_size}"
        );

        Ok(())
    }

    #[test]
    fn test_gc_recurses_into_nested_view_arrays() -> Result<()> {
        use arrow::array::{DictionaryArray, Int32Array};
        use arrow::buffer::Buffer;

        let strings: Vec<String> = (0..200)
            .map(|i| format!("http://example.com/nested/path/that/is/not/inlined/{i}"))
            .collect();
        let string_values = Arc::new(StringViewArray::from(strings)) as ArrayRef;

        let list_data = ArrayDataBuilder::new(DataType::List(Arc::new(
            Field::new_list_field(DataType::Utf8View, true),
        )))
        .len(20)
        .buffers(vec![Buffer::from_iter((0..=20).map(|i| i * 5_i32))])
        .child_data(vec![string_values.slice(0, 100).to_data()])
        .build()?;
        let list_array = make_array(list_data);

        let keys = Int32Array::from_iter_values(0..20);
        let dictionary = DictionaryArray::new(keys, string_values.slice(0, 20));
        let dictionary_array = Arc::new(dictionary) as ArrayRef;

        let schema = Arc::new(Schema::new(vec![
            Field::new(
                "list_strings",
                DataType::List(Arc::new(Field::new_list_field(DataType::Utf8View, true))),
                false,
            ),
            Field::new(
                "dictionary_strings",
                DataType::Dictionary(
                    Box::new(DataType::Int32),
                    Box::new(DataType::Utf8View),
                ),
                false,
            ),
        ]));
        let batch = RecordBatch::try_new(schema, vec![list_array, dictionary_array])?;
        let gc_batch = gc_view_arrays(&batch)?;

        let gc_list_values = gc_batch.column(0).to_data().child_data()[0].clone();
        let gc_list_values = make_array(gc_list_values);
        let gc_list_values = gc_list_values
            .as_any()
            .downcast_ref::<StringViewArray>()
            .unwrap();
        assert!(
            calculate_string_view_waste_ratio(gc_list_values) < 0.2,
            "GC should compact nested List child views"
        );

        let gc_dictionary_values = gc_batch.column(1).to_data().child_data()[0].clone();
        let gc_dictionary_values = make_array(gc_dictionary_values);
        let gc_dictionary_values = gc_dictionary_values
            .as_any()
            .downcast_ref::<StringViewArray>()
            .unwrap();
        assert!(
            calculate_string_view_waste_ratio(gc_dictionary_values) < 0.2,
            "GC should compact nested Dictionary values"
        );

        Ok(())
    }

    #[test]
    fn test_gc_nested_arrays_skips_top_level_columns() -> Result<()> {
        use arrow::buffer::Buffer;

        let strings: Vec<String> = (0..400)
            .map(|i| format!("http://example.com/nested/path/that/is/not/inlined/{i}"))
            .collect();
        let string_values = Arc::new(StringViewArray::from(strings)) as ArrayRef;

        // Both columns hold 20 of the strings, but reference the data of all 400
        let top_level = string_values.slice(0, 20);
        let list_data = ArrayDataBuilder::new(DataType::List(Arc::new(
            Field::new_list_field(DataType::Utf8View, true),
        )))
        .len(20)
        .buffers(vec![Buffer::from_iter(0..=20_i32)])
        .child_data(vec![string_values.slice(20, 20).to_data()])
        .build()?;
        let list_array = make_array(list_data);

        let schema = Arc::new(Schema::new(vec![
            Field::new("strings", DataType::Utf8View, false),
            Field::new(
                "list_strings",
                DataType::List(Arc::new(Field::new_list_field(DataType::Utf8View, true))),
                false,
            ),
        ]));
        let batch =
            RecordBatch::try_new(schema, vec![Arc::clone(&top_level), list_array])?;

        // `gc_view_arrays` compacts the top-level column, `gc_nested_arrays` does not
        assert!(!Arc::ptr_eq(gc_view_arrays(&batch)?.column(0), &top_level));
        let gc_batch = gc_nested_arrays(&batch)?;
        assert!(Arc::ptr_eq(gc_batch.column(0), &top_level));

        let gc_list_values =
            make_array(gc_batch.column(1).to_data().child_data()[0].clone());
        let gc_list_values = gc_list_values
            .as_any()
            .downcast_ref::<StringViewArray>()
            .unwrap();
        assert!(
            calculate_string_view_waste_ratio(gc_list_values) < 0.2,
            "GC should compact nested List child views"
        );

        Ok(())
    }

    #[test]
    fn test_gc_columns_compacts_dictionaries() -> Result<()> {
        use arrow::array::{DictionaryArray, ListArray};
        use arrow::buffer::OffsetBuffer;
        use arrow::datatypes::Int32Type;

        // Every column references a few of the same 100 values
        let values: ArrayRef = Arc::new(StringArray::from_iter_values(
            (0..100).map(|i| format!("value {i}")),
        ));
        let dictionary = |keys: Vec<i32>| {
            DictionaryArray::new(Int32Array::from(keys), Arc::clone(&values))
        };
        let decode = |array: &ArrayRef| -> Vec<String> {
            let dictionary = array.as_dictionary::<Int32Type>();
            let strings = dictionary.downcast_dict::<StringArray>().unwrap();
            strings
                .into_iter()
                .map(|s| s.unwrap().to_string())
                .collect()
        };
        let list = ListArray::new(
            Arc::new(Field::new_list_field(
                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
                true,
            )),
            OffsetBuffer::from_lengths([2, 1]),
            Arc::new(dictionary(vec![7, 3, 7])),
            None,
        );
        let batch = RecordBatch::try_from_iter(vec![
            ("compacted", Arc::new(dictionary(vec![5, 9])) as ArrayRef),
            ("other", Arc::new(dictionary(vec![1, 2])) as ArrayRef),
            ("list", Arc::new(list) as ArrayRef),
        ])?;

        // `gc_view_arrays` prunes only dictionaries with more values than keys,
        // so it leaves one whose keys reference every value as it is
        let dense = RecordBatch::try_from_iter(vec![(
            "dense",
            Arc::new(DictionaryArray::new(
                Int32Array::from(vec![0, 1, 0]),
                Arc::new(StringArray::from(vec!["a", "b"])) as ArrayRef,
            )) as ArrayRef,
        )])?;
        let gc_dense = gc_view_arrays(&dense)?;
        assert!(Arc::ptr_eq(dense.column(0), gc_dense.column(0)));

        // `gc_columns` keeps only the values that the given columns reference
        let gc_batch = gc_columns(&batch, &[0, 2])?;
        let compacted = gc_batch.column(0);
        assert_eq!(compacted.as_any_dictionary().values().len(), 2);
        assert_eq!(decode(compacted), ["value 5", "value 9"]);
        assert!(Arc::ptr_eq(gc_batch.column(1), batch.column(1)));
        let list_values = gc_batch.column(2).as_list::<i32>().values();
        assert_eq!(list_values.as_any_dictionary().values().len(), 2);
        assert_eq!(decode(list_values), ["value 7", "value 3", "value 7"]);

        // `gc_nested_arrays` compacts only the nested column
        let gc_batch = gc_nested_arrays(&batch)?;
        assert!(Arc::ptr_eq(gc_batch.column(0), batch.column(0)));
        let list_values = gc_batch.column(2).as_list::<i32>().values();
        assert_eq!(list_values.as_any_dictionary().values().len(), 2);

        Ok(())
    }

    #[rstest::rstest]
    #[case(SpillCompression::Uncompressed)]
    #[case(SpillCompression::Lz4Frame)]
    #[case(SpillCompression::Zstd)]
    #[tokio::test]
    async fn test_spill_prunes_unused_nested_dictionary_values(
        #[case] compression: SpillCompression,
    ) -> Result<()> {
        let values = Arc::new(StructArray::from(vec![
            (
                Arc::new(Field::new("id", DataType::Int32, false)),
                Arc::new(Int32Array::from_iter_values(0..1024)) as ArrayRef,
            ),
            (
                Arc::new(Field::new("name", DataType::Utf8View, false)),
                Arc::new(StringViewArray::from_iter_values(
                    (0..1024).map(|id| format!("{id}:{}", "x".repeat(256))),
                )) as ArrayRef,
            ),
        ])) as ArrayRef;
        let batch = |keys, values| -> Result<RecordBatch> {
            let dictionary = DictionaryArray::<Int32Type>::try_new(keys, values)?;
            let list = ListArray::new(
                Arc::new(Field::new_list_field(dictionary.data_type().clone(), true)),
                OffsetBuffer::new(vec![0_i32, 1, 3, 4].into()),
                Arc::new(dictionary),
                None,
            );
            Ok(RecordBatch::try_from_iter([(
                "stacktrace",
                Arc::new(list) as ArrayRef,
            )])?)
        };
        let input = batch(
            Int32Array::from(vec![Some(1023), None, Some(17), Some(1023)]),
            Arc::clone(&values),
        )?;
        let expected = batch(
            Int32Array::from(vec![Some(1), None, Some(0), Some(1)]),
            arrow::compute::take(&values, &Int32Array::from(vec![17, 1023]), None)?,
        )?;
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let manager =
            SpillManager::new(Arc::new(RuntimeEnv::default()), metrics, input.schema())
                .with_compression_type(compression);
        let file = manager
            .spill_record_batch_and_finish(&[input], "nested dictionary GC")?
            .unwrap();
        let size = file.size().unwrap();
        assert!(
            size < 16 * 1024,
            "unused dictionary values spilled: {size} bytes"
        );
        let actual = collect(manager.read_spill_as_stream(file, None)?).await?;
        assert_eq!(actual, vec![expected]);
        Ok(())
    }

    #[tokio::test]
    async fn test_spill_file_size_gc_verification_string_view() -> Result<()> {
        use arrow::array::StringViewArray;
        use std::fs;

        // 1. Setup bloated data (large buffers)
        let num_rows = 1000;
        let string_array: StringViewArray = (0..num_rows)
            .map(|i| Some(format!("this_is_a_long_string_to_ensure_it_is_not_inlined_and_causes_waste_{i}")))
            .collect();
        let schema = Arc::new(Schema::new(vec![Field::new(
            "s",
            DataType::Utf8View,
            false,
        )]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(string_array.clone()) as ArrayRef],
        )?;

        // 2. Slice it heavily (1% of the data)
        let sliced_batch = batch.slice(0, 10);

        // 3. Spill to disk using SpillManager
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, schema);
        let spill_file = spill_manager
            .spill_record_batch_and_finish(&[sliced_batch], "TestGC")?
            .unwrap();

        // 4. Check file size on disk
        let file_size = fs::metadata(spill_file.path().unwrap())?.len();

        // The original buffer size is around 70KB.
        // Without GC, the spill file would be > 70KB.
        // With GC, it should be much smaller (only 10 rows of ~70 bytes each + metadata).
        assert!(
            file_size < 10 * 1024,
            "Spill file is too large ({file_size} bytes)! GC might not be working."
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_spill_file_size_gc_verification_binary_view() -> Result<()> {
        use arrow::array::BinaryViewArray;
        use std::fs;

        // 1. Setup bloated data (large buffers)
        let num_rows = 1000;
        let binary_array: BinaryViewArray =
            (0..num_rows).map(|i| Some(vec![i as u8; 100])).collect();
        let schema = Arc::new(Schema::new(vec![Field::new(
            "b",
            DataType::BinaryView,
            false,
        )]));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(binary_array.clone()) as ArrayRef],
        )?;

        // 2. Slice it heavily (1% of the data)
        let sliced_batch = batch.slice(0, 10);

        // 3. Spill to disk using SpillManager
        let env = Arc::new(RuntimeEnv::default());
        let metrics = SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let spill_manager = SpillManager::new(env, metrics, schema);
        let spill_file = spill_manager
            .spill_record_batch_and_finish(&[sliced_batch], "TestGCBinary")?
            .unwrap();

        // 4. Check file size on disk
        let file_size = fs::metadata(spill_file.path().unwrap())?.len();

        // Original buffer is 100KB.
        // With GC, it should be much smaller.
        assert!(
            file_size < 10 * 1024,
            "Spill file is too large ({file_size} bytes)! GC might not be working."
        );

        Ok(())
    }
}