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

//! Create a stream that do a multi level merge stream

use crate::metrics::BaselineMetrics;
use crate::{EmptyRecordBatchStream, SpillManager};
use arrow::array::RecordBatch;
use std::fmt::{Debug, Formatter};
use std::mem;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use arrow::datatypes::SchemaRef;
use datafusion_common::{Result, internal_err, resources_err};
use datafusion_execution::memory_pool::{MemoryReservation, MergeMemoryPool};

use crate::sorts::builder::try_grow_reservation_to_at_least;
use crate::sorts::sort::get_reserved_bytes_for_record_batch_size;
use crate::sorts::streaming_merge::{SortedSpillFile, StreamingMergeBuilder};
use crate::spill::gc_view_arrays;
use crate::spill::spill_manager::GetSlicedSize;
use crate::stream::{ObservedStream, RecordBatchStreamAdapter};
use datafusion_execution::{RecordBatchStream, SendableRecordBatchStream};
use datafusion_physical_expr_common::sort_expr::LexOrdering;
use futures::TryStreamExt;
use futures::{Stream, StreamExt};

/// Merges a stream of sorted cursors and record batches into a single sorted stream
///
/// This is a wrapper around [`SortPreservingMergeStream`](crate::sorts::merge::SortPreservingMergeStream)
/// that provide it the sorted streams/files to merge while making sure we can merge them in memory.
/// In case we can't merge all of them in a single pass we will spill the intermediate results to disk
/// and repeat the process.
///
/// ## High level Algorithm
/// 1. Get the maximum amount of sorted in-memory streams and spill files we can merge with the available memory
/// 2. Sort them to a sorted stream
/// 3. Do we have more spill files to merge?
///  - Yes: write that sorted stream to a spill file,
///    add that spill file back to the spill files to merge and
///    repeat the process
///
///  - No: return that sorted stream as the final output stream
///
/// ```text
/// Initial State: Multiple sorted streams + spill files
///      ┌───────────┐
///      │  Phase 1  │
///      └───────────┘
/// ┌──Can hold in memory─┐
/// │   ┌──────────────┐  │
/// │   │  In-memory   │
/// │   │sorted stream │──┼────────┐
/// │   │      1       │  │        │
///     └──────────────┘  │        │
/// │   ┌──────────────┐  │        │
/// │   │  In-memory   │           │
/// │   │sorted stream │──┼────────┤
/// │   │      2       │  │        │
///     └──────────────┘  │        │
/// │   ┌──────────────┐  │        │
/// │   │  In-memory   │           │
/// │   │sorted stream │──┼────────┤
/// │   │      3       │  │        │
///     └──────────────┘  │        │
/// │   ┌──────────────┐  │        │            ┌───────────┐
/// │   │ Sorted Spill │           │            │  Phase 2  │
/// │   │    file 1    │──┼────────┤            └───────────┘
/// │   └──────────────┘  │        │
///  ──── ──── ──── ──── ─┘        │       ┌──Can hold in memory─┐
///                                │       │                     │
///     ┌──────────────┐           │       │   ┌──────────────┐
///     │ Sorted Spill │           │       │   │ Sorted Spill │  │
///     │    file 2    │──────────────────────▶│    file 2    │──┼─────┐
///     └──────────────┘           │           └──────────────┘  │     │
///     ┌──────────────┐           │       │   ┌──────────────┐  │     │
///     │ Sorted Spill │           │       │   │ Sorted Spill │        │
///     │    file 3    │──────────────────────▶│    file 3    │──┼─────┤
///     └──────────────┘           │       │   └──────────────┘  │     │
///     ┌──────────────┐           │           ┌──────────────┐  │     │
///     │ Sorted Spill │           │       │   │ Sorted Spill │  │     │
///     │    file 4    │──────────────────────▶│    file 4    │────────┤          ┌───────────┐
///     └──────────────┘           │       │   └──────────────┘  │     │          │  Phase 3  │
///                                │       │                     │     │          └───────────┘
///                                │        ──── ──── ──── ──── ─┘     │     ┌──Can hold in memory─┐
///                                │                                   │     │                     │
///     ┌──────────────┐           │           ┌──────────────┐        │     │  ┌──────────────┐
///     │ Sorted Spill │           │           │ Sorted Spill │        │     │  │ Sorted Spill │   │
///     │    file 5    │──────────────────────▶│    file 5    │────────────────▶│    file 5    │───┼───┐
///     └──────────────┘           │           └──────────────┘        │     │  └──────────────┘   │   │
///                                │                                   │     │                     │   │
///                                │           ┌──────────────┐        │     │  ┌──────────────┐       │
///                                │           │ Sorted Spill │        │     │  │ Sorted Spill │   │   │       ┌── ─── ─── ─── ─── ─── ─── ──┐
///                                └──────────▶│    file 6    │────────────────▶│    file 6    │───┼───┼──────▶         Output Stream
///                                            └──────────────┘        │     │  └──────────────┘   │   │       └── ─── ─── ─── ─── ─── ─── ──┘
///                                                                    │     │                     │   │
///                                                                    │     │  ┌──────────────┐       │
///                                                                    │     │  │ Sorted Spill │   │   │
///                                                                    └───────▶│    file 7    │───┼───┘
///                                                                          │  └──────────────┘   │
///                                                                          │                     │
///                                                                          └─ ──── ──── ──── ────
/// ```
///
/// ## Memory Management Strategy
///
/// This multi-level merge make sure that we can handle any amount of data to sort as long as
/// we have enough memory to merge at least 2 streams at a time, even when individual record
/// batches are skewed (very wide).
///
/// 1. **Worst-Case Memory Reservation**: Reserves memory based on the largest
///    batch size encountered in each spill file to merge, ensuring sufficient memory is always
///    available during merge operations.
/// 2. **Adaptive Buffer Sizing**: Reduces buffer sizes when memory is constrained
/// 3. **Spill-to-Disk**: Spill to disk when we cannot merge all files in memory
/// 4. **Re-spilling Skewed Runs**: If even at the smallest read-buffer size we still cannot
///    reserve memory for the minimum of 2 streams - because a single run's largest batch is so
///    wide that two streams' worth of reservation exceeds the budget - the larger of the two
///    runs is re-spilled with each batch sliced in half. This shrinks its largest batch,
///    lowering the per-stream reservation, and the merge pass is retried. The re-spilled run
///    is tracked alongside a per-run batch-size limit equal to half the batch size it was
///    written with, so any later merge that includes it caps its output batch size to match -
///    otherwise the merged run could rebuild a full-size batch and reintroduce the skew.
///    Crucially the global merge batch size is *not* lowered, so re-spilling more than one run
///    does not compound the reduction. If a batch cannot be split any further (a single row
///    wider than the budget), the merge surfaces `ResourcesExhausted` instead of looping
///    forever.
pub(crate) struct MultiLevelMergeBuilder {
    spill_manager: SpillManager,
    schema: SchemaRef,
    /// Sorted runs still to be merged. Each run is paired with the batch-size limit a
    /// merge consuming it must cap its output at. Runs written at the full batch size
    /// carry `batch_size`. A run re-spilled smaller to resolve skew carries its halved
    /// limit (see [`Self::split_spill_file_in_half`]). Tracking it here keeps this limit
    /// out of the public [`SortedSpillFile`], so no external caller has to set it.
    sorted_spill_files: Vec<(SortedSpillFile, usize)>,
    sorted_streams: Vec<SendableRecordBatchStream>,
    expr: LexOrdering,
    metrics: BaselineMetrics,
    batch_size: usize,
    /// See [`StreamingMergeBuilder::with_max_batch_bytes`]
    max_batch_bytes: Option<usize>,
    reservation: MemoryReservation,
    /// Workspace retained across retries and intermediate spill passes.
    merge_pool: Option<Arc<MergeMemoryPool>>,
    /// Leave memory for the aggregate consuming the merged spill rows.
    reserve_replay_headroom: bool,
    /// Avoid merging more runs than needed before the final replay pass.
    size_intermediate_merges: bool,
    fetch: Option<usize>,
    enable_round_robin_tie_breaker: bool,
}

impl Debug for MultiLevelMergeBuilder {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "MultiLevelMergeBuilder")
    }
}

impl MultiLevelMergeBuilder {
    #[expect(clippy::too_many_arguments)]
    pub(crate) fn new(
        spill_manager: SpillManager,
        schema: SchemaRef,
        sorted_spill_files: Vec<SortedSpillFile>,
        sorted_streams: Vec<SendableRecordBatchStream>,
        expr: LexOrdering,
        metrics: BaselineMetrics,
        batch_size: usize,
        reservation: MemoryReservation,
        fetch: Option<usize>,
        enable_round_robin_tie_breaker: bool,
    ) -> Self {
        Self {
            spill_manager,
            schema,
            // Initial runs are written at the full batch size, so they impose no cap
            // on later merges - record `batch_size` as their (unconstrained) limit.
            sorted_spill_files: sorted_spill_files
                .into_iter()
                .map(|file| (file, batch_size))
                .collect(),
            sorted_streams,
            expr,
            metrics,
            batch_size,
            max_batch_bytes: None,
            reservation,
            merge_pool: None,
            reserve_replay_headroom: false,
            size_intermediate_merges: false,
            enable_round_robin_tie_breaker,
            fetch,
        }
    }

    pub(super) fn with_merge_pool(mut self, pool: Option<Arc<MergeMemoryPool>>) -> Self {
        self.merge_pool = pool;
        self
    }

    /// Applies [`StreamingMergeBuilder::with_max_batch_bytes`] to every pass,
    /// including the passes whose output is spilled again.
    pub(super) fn with_max_batch_bytes(mut self, max_batch_bytes: Option<usize>) -> Self {
        self.max_batch_bytes = max_batch_bytes;
        self
    }

    /// Leave replay headroom while selecting merge buffers. Temporary splitting
    /// workspace can still use the full pool because replay has not started.
    pub(super) fn with_replay_headroom(mut self, reserve: bool) -> Self {
        self.reserve_replay_headroom = reserve;
        self
    }

    pub(super) fn with_intermediate_merge_sizing(
        mut self,
        min_spill_batch_rows: Option<usize>,
    ) -> Self {
        // Short inputs can produce larger batches when merged, reducing the next
        // pass's fan-in. Fetch can also leave intermediate runs with short batches.
        self.size_intermediate_merges = self.fetch.is_none()
            && min_spill_batch_rows.is_some_and(|rows| rows >= self.batch_size);
        self
    }

    pub(crate) fn create_spillable_merge_stream(self) -> SendableRecordBatchStream {
        Box::pin(RecordBatchStreamAdapter::new(
            Arc::clone(&self.schema),
            futures::stream::once(self.create_stream()).try_flatten(),
        ))
    }

    async fn create_stream(mut self) -> Result<SendableRecordBatchStream> {
        let mut allow_minimum_without_headroom = false;
        loop {
            let (mut stream, batch_size_limit) = match self
                .merge_sorted_runs_within_mem_limit(allow_minimum_without_headroom)?
            {
                MergeStep::Stream {
                    stream,
                    batch_size_limit,
                } => (stream, batch_size_limit),
                MergeStep::SplitThenRetry(index) => {
                    // Couldn't reserve memory for the minimum of 2 streams. Re-spill
                    // the larger of the two we're trying to merge with half its batch
                    // size so its largest batch shrinks, lowering the per-stream
                    // reservation, then retry. Makes the merge resilient to skewed
                    // (very wide) rows.
                    let retry_unsplittable =
                        self.reserve_replay_headroom && !allow_minimum_without_headroom;
                    if !self
                        .split_spill_file_in_half(index, retry_unsplittable)
                        .await?
                    {
                        // A single row may prevent leaving replay headroom while
                        // the minimum merge still fits the actual shared pool.
                        allow_minimum_without_headroom = true;
                    }
                    continue;
                }
            };
            allow_minimum_without_headroom = false;

            // TODO - add a threshold for number of files to disk even if empty and reading from disk so
            //        we can avoid the memory reservation

            // If no spill files are left, we can return the stream as this is the last sorted run
            // TODO - We can write to disk before reading it back to avoid having multiple streams in memory
            if self.sorted_spill_files.is_empty() {
                assert!(
                    self.sorted_streams.is_empty(),
                    "We should not have any sorted streams left"
                );

                // The final pass has its buffer budget and needs no future spill
                // workspace. Keep live reservations, but release the idle floor.
                if let Some(pool) = &self.merge_pool {
                    pool.release_unused();
                }

                return Ok(stream);
            }

            // Need to sort to a spill file
            let Some((spill_file, max_record_batch_memory, max_batch_rows)) = self
                .spill_manager
                .spill_record_batch_stream_and_return_max_batch_stats(
                    &mut stream,
                    "MultiLevelMergeBuilder intermediate spill",
                )
                .await?
            else {
                continue;
            };

            // Offset overflow can flush partial batches even without a fetch limit.
            // Keep sizing disabled once a run cannot fill its output batch limit.
            self.size_intermediate_merges &= max_batch_rows >= batch_size_limit;

            // Add the spill file paired with the batch-size limit of the merge that
            // produced it: if that merge consumed a shrunk (skew-resolved) run, its
            // output was capped and this intermediate run is likewise capped, so a
            // later pass that re-merges it won't rebuild an oversized batch.
            self.sorted_spill_files.push((
                SortedSpillFile {
                    file: spill_file,
                    max_record_batch_memory,
                },
                batch_size_limit,
            ));
        }
    }

    /// This tries to create a stream that merges the most sorted streams and sorted spill files
    /// as possible within the memory limit.
    fn merge_sorted_runs_within_mem_limit(
        &mut self,
        allow_minimum_without_headroom: bool,
    ) -> Result<MergeStep> {
        match (self.sorted_spill_files.len(), self.sorted_streams.len()) {
            // No data so empty batch
            (0, 0) => {
                let empty_stream =
                    Box::pin(EmptyRecordBatchStream::new(Arc::clone(&self.schema)));
                Ok(MergeStep::Stream {
                    stream: self.observe_output(empty_stream),
                    batch_size_limit: self.batch_size,
                })
            }

            // Only in-memory stream, return that
            (0, 1) => {
                let output_stream = self.sorted_streams.remove(0);
                Ok(MergeStep::Stream {
                    stream: self.observe_output(output_stream),
                    batch_size_limit: self.batch_size,
                })
            }

            // Only single sorted spill file so return it
            (1, 0) => {
                let (spill_file, batch_size) = self.sorted_spill_files.remove(0);

                // Not reserving any memory for this disk as we are not holding it in memory
                let output_stream = self
                    .spill_manager
                    .read_spill_as_stream(spill_file.file, None)?;

                Ok(MergeStep::Stream {
                    stream: self.observe_output(output_stream),
                    batch_size_limit: batch_size,
                })
            }

            // Only in memory streams, so merge them all in a single pass. In-memory
            // runs are never shrunk for skew, so this merge runs at the full batch
            // size and its output carries no limit.
            (0, _) => {
                let sorted_stream = mem::take(&mut self.sorted_streams);
                // No need to wrap with observed stream since merge sort will update the observed metrics
                Ok(MergeStep::Stream {
                    stream: self.create_new_merge_sort(
                        sorted_stream,
                        // If we have no sorted spill files left, this is the last run
                        true,
                        true,
                        self.batch_size,
                    )?,
                    batch_size_limit: self.batch_size,
                })
            }

            // Need to merge multiple streams
            (_, _) => {
                // Transfer any pre-reserved bytes (from sort_spill_reservation_bytes)
                // to the merge memory reservation. This prevents starvation when
                // concurrent sort partitions compete for pool memory: the pre-reserved
                // bytes cover spill file buffer reservations without additional pool
                // allocation.
                let mut memory_reservation = self.reservation.take();

                // Compute the minimum before taking the in-memory streams so that, if we
                // need to re-spill and retry, `self.sorted_streams` is left untouched.
                let minimum_number_of_required_streams =
                    2_usize.saturating_sub(self.sorted_streams.len());

                let (mut sorted_spill_files, buffer_size) = match self
                    .get_sorted_spill_files_to_merge(
                        2,
                        // we must have at least 2 streams to merge
                        minimum_number_of_required_streams,
                        &mut memory_reservation,
                        allow_minimum_without_headroom,
                    )? {
                    SpillFilesToMerge::Ready(sorted_spill_files, buffer_size) => {
                        (sorted_spill_files, buffer_size)
                    }
                    // Not enough memory to seat 2 streams. Re-spill the blocking file
                    // smaller and retry. `get_sorted_spill_files_to_merge` already freed
                    // the reservation and `self.sorted_streams` is untouched, so the
                    // retry starts clean.
                    SpillFilesToMerge::SplitThenRetry(index) => {
                        return Ok(MergeStep::SplitThenRetry(index));
                    }
                };

                if self.size_intermediate_merges
                    && self.sorted_streams.is_empty()
                    && !self.sorted_spill_files.is_empty()
                {
                    // The next admission starts with two read buffers per run.
                    // Fit both those buffers and any replay headroom in the
                    // existing grant: another partition may take every spare
                    // byte while this intermediate pass writes to disk.
                    let final_fan_in = sorted_spill_files.len() * buffer_size / 2;
                    let final_fan_in = if self.reserve_replay_headroom {
                        final_fan_in / 2
                    } else {
                        final_fan_in
                    };
                    let needed = self.sorted_spill_files.len() + sorted_spill_files.len()
                        - final_fan_in
                        + 1;
                    if needed < sorted_spill_files.len() {
                        let (first, first_limit) = &sorted_spill_files[0];
                        // A wider pending run or a smaller output batch limit can
                        // change the next pass's fan-in and add intermediate work.
                        // Apply this sizing heuristic only to uniform run budgets.
                        let uniform_runs = sorted_spill_files
                            .iter()
                            .chain(&self.sorted_spill_files)
                            .all(|(file, limit)| {
                                file.max_record_batch_memory
                                    == first.max_record_batch_memory
                                    && limit == first_limit
                            });
                        if uniform_runs {
                            let unused = sorted_spill_files.split_off(needed);
                            self.sorted_spill_files.splice(0..0, unused);
                            // Keep the grant through intermediate EOF and the
                            // spill write, then transfer it to the next admission.
                            // This does not reserve additional pool memory.
                            self.reservation = memory_reservation.take();
                        }
                    }
                }

                // Don't account for existing streams memory
                // as we are not holding the memory for them
                let mut sorted_streams = mem::take(&mut self.sorted_streams);

                let is_only_merging_memory_streams = sorted_spill_files.is_empty();

                // If no spill files were selected (e.g. all too large for
                // available memory but enough in-memory streams exist),
                // return the pre-reserved bytes to self.reservation so
                // create_new_merge_sort can transfer them to the merge
                // stream's BatchBuilder.
                if is_only_merging_memory_streams {
                    mem::swap(&mut self.reservation, &mut memory_reservation);
                }

                // Cap the merge output at the smallest limit among the runs we're
                // about to merge. Runs that were shrunk for skew carry a smaller limit,
                // if none do, every run carries `self.batch_size` and the merge runs at
                // the full batch size. The output stream is tagged with the same limit
                // (see the `MergeStep::Stream` returns below) so a re-spilled
                // intermediate run stays shrunk and won't rebuild an oversized batch on
                // a later pass.
                let mut output_batch_size = self.batch_size;
                for (spill, batch_size_limit) in sorted_spill_files {
                    let stream = self
                        .spill_manager
                        .clone()
                        .with_batch_read_buffer_capacity(buffer_size)
                        .read_spill_as_stream(
                            spill.file,
                            Some(spill.max_record_batch_memory),
                        )?;
                    output_batch_size = output_batch_size.min(batch_size_limit);
                    sorted_streams.push(stream);
                }
                let merge_sort_stream = self.create_new_merge_sort(
                    sorted_streams,
                    // If we have no sorted spill files left, this is the last run
                    self.sorted_spill_files.is_empty(),
                    is_only_merging_memory_streams,
                    output_batch_size,
                )?;

                // If we're only merging memory streams, we don't need to attach the memory reservation
                // as it's empty
                if is_only_merging_memory_streams {
                    assert_eq!(
                        memory_reservation.size(),
                        0,
                        "when only merging memory streams, we should not have any memory reservation and let the merge sort handle the memory"
                    );

                    Ok(MergeStep::Stream {
                        stream: merge_sort_stream,
                        batch_size_limit: output_batch_size,
                    })
                } else {
                    // Attach the memory reservation to the stream to make sure we have enough memory
                    // throughout the merge process as we bypassed the memory pool for the merge sort stream
                    Ok(MergeStep::Stream {
                        stream: Box::pin(StreamAttachedReservation::new(
                            merge_sort_stream,
                            memory_reservation,
                        )),
                        batch_size_limit: output_batch_size,
                    })
                }
            }
        }
    }

    fn create_new_merge_sort(
        &mut self,
        streams: Vec<SendableRecordBatchStream>,
        is_output: bool,
        all_in_memory: bool,
        output_batch_size: usize,
    ) -> Result<SendableRecordBatchStream> {
        let mut builder = StreamingMergeBuilder::new()
            .with_schema(Arc::clone(&self.schema))
            .with_expressions(&self.expr)
            .with_batch_size(output_batch_size)
            .with_fetch(self.fetch)
            .with_metrics(if is_output {
                // Only add the metrics to the last run
                self.metrics.clone()
            } else {
                self.metrics.intermediate()
            })
            .with_round_robin_tie_breaker(self.enable_round_robin_tie_breaker)
            .with_streams(streams)
            .with_max_batch_bytes(self.max_batch_bytes);

        if !all_in_memory {
            // Don't track memory used by this stream as we reserve that memory by worst case sceneries
            // (reserving memory for the biggest batch in each stream)
            // TODO - avoid this hack as this can be broken easily when `SortPreservingMergeStream`
            //        changes the implementation to use more/less memory
            builder = builder.with_bypass_mempool();
        } else {
            // If we are only merging in-memory streams, we need to use the memory reservation
            // because we don't know the maximum size of the batches in the streams.
            // Use take() to transfer any pre-reserved bytes so the merge can use them
            // as its initial budget without additional pool allocation.
            builder = builder.with_reservation(self.reservation.take());
        }

        builder.build()
    }

    /// Return the sorted spill files to use for the next phase, and the buffer size
    /// This will try to get as many spill files as possible to merge, and if we don't have enough streams
    /// it will try to reduce the buffer size until we have enough streams to merge
    /// otherwise it will return an error
    fn get_sorted_spill_files_to_merge(
        &mut self,
        buffer_len: usize,
        minimum_number_of_required_streams: usize,
        reservation: &mut MemoryReservation,
        allow_minimum_without_headroom: bool,
    ) -> Result<SpillFilesToMerge> {
        assert_ne!(buffer_len, 0, "Buffer length must be greater than 0");
        let mut number_of_spills_to_read_for_current_phase = 0;
        let configured_fan_in = self
            .spill_manager
            .env()
            .disk_manager
            .max_spill_merge_fan_in();
        let max_spill_files = effective_spill_merge_fan_in(configured_fan_in);
        // Track total memory needed for spill file buffers. When the
        // reservation has pre-reserved bytes (from sort_spill_reservation_bytes),
        // those bytes cover the first N spill files without additional pool
        // allocation, preventing starvation under memory pressure.
        let mut total_needed: usize = 0;
        let mut accepted_memory: usize = 0;

        for (spill, _) in &self.sorted_spill_files {
            if number_of_spills_to_read_for_current_phase >= max_spill_files
                || (allow_minimum_without_headroom
                    && number_of_spills_to_read_for_current_phase
                        >= minimum_number_of_required_streams)
            {
                break;
            }

            let per_spill = get_reserved_bytes_for_record_batch_size(
                spill.max_record_batch_memory,
                // Size will be the same as the sliced size, bc it is a spilled batch.
                spill.max_record_batch_memory,
            ) * buffer_len;
            total_needed += per_spill;

            // If a run cannot shrink, allow only the minimum merge without
            // replay headroom. Disable read-ahead and still ask the pool for
            // every byte used by the merge.
            let skip_headroom = allow_minimum_without_headroom
                && buffer_len == 1
                && number_of_spills_to_read_for_current_phase
                    < minimum_number_of_required_streams;
            let check_headroom = self.reserve_replay_headroom && !skip_headroom;
            let admission = if check_headroom {
                // Ask the pool for merge buffers plus equal replay space, then
                // return the spare bytes before exposing the merge stream.
                match total_needed.checked_mul(2) {
                    Some(with_headroom) => {
                        try_grow_reservation_to_at_least(reservation, with_headroom)
                    }
                    None => resources_err!("Spill merge headroom exceeds usize::MAX"),
                }
            } else {
                try_grow_reservation_to_at_least(reservation, total_needed)
            };
            match admission {
                Ok(_) => {
                    number_of_spills_to_read_for_current_phase += 1;
                    accepted_memory = total_needed;
                }
                // If we can't grow the reservation, we need to stop
                Err(err) => {
                    // We must have at least 2 streams to merge, so if we don't have enough memory
                    // fail
                    if minimum_number_of_required_streams
                        > number_of_spills_to_read_for_current_phase
                    {
                        // Free the memory we reserved for this merge as we either try again or fail
                        reservation.free();
                        if buffer_len > 1 {
                            // Try again with smaller buffer size, it will be slower but at least we can merge
                            return self.get_sorted_spill_files_to_merge(
                                buffer_len - 1,
                                minimum_number_of_required_streams,
                                reservation,
                                allow_minimum_without_headroom,
                            );
                        }

                        // buffer_len == 1 and we still can't seat the minimum of 2 streams.
                        if number_of_spills_to_read_for_current_phase == 0 {
                            if check_headroom {
                                // Replay has not started, so splitting may use the
                                // full pool to leave room for replay afterward.
                                return Ok(SpillFilesToMerge::SplitThenRetry(0));
                            }
                            // We couldn't even reserve a single stream - one record batch
                            // is larger than the whole merge budget. That's the lone-batch
                            // case, not the 2-stream merge skew we rescue here - surface it.
                            return Err(err);
                        }

                        // We seated one stream (index 0) but not the second (index 1, the
                        // batch that just failed to reserve). Those are by definition the
                        // only two streams we are trying to merge, so re-spill the larger
                        // of them with a smaller batch size and retry, the smaller max
                        // batch lowers the per-stream reservation enough to seat both.
                        let split_index = usize::from(
                            self.sorted_spill_files[1].0.max_record_batch_memory
                                > self.sorted_spill_files[0].0.max_record_batch_memory,
                        );
                        return Ok(SpillFilesToMerge::SplitThenRetry(split_index));
                    }

                    // We reached the maximum amount of memory we can use
                    // for this merge
                    break;
                }
            }
        }

        if self.reserve_replay_headroom {
            // `total_needed` may include a rejected candidate. Keep only the
            // buffers that were admitted, releasing temporary replay headroom.
            reservation.shrink(reservation.size() - accepted_memory);
        }

        let spills = self
            .sorted_spill_files
            .drain(..number_of_spills_to_read_for_current_phase)
            .collect::<Vec<_>>();

        Ok(SpillFilesToMerge::Ready(spills, buffer_len))
    }

    /// Re-spill the spill file at `index` with half its batch size, putting it back
    /// at the same position. We read the file back and re-spill it through the normal
    /// spill API (which owns batch layout), slicing every batch in two, which halves
    /// the largest written batch and so lowers the per-stream merge reservation enough
    /// for the next attempt to seat both streams. One stream's worth of memory is
    /// reserved for the duration and freed afterwards. Makes the merge resilient to skew.
    ///
    /// Instead of halving the *global* merge batch size (which would compound when more
    /// than one run is re-spilled), the shrunk run records its own smaller batch-size
    /// limit (tracked alongside the run in `sorted_spill_files`), so only merges that
    /// actually consume it pay the reduced batch size.
    ///
    /// Returns whether the largest batch shrank. If `retry_unsplittable` is true,
    /// restore an unchanged run for one minimum-merge admission attempt.
    async fn split_spill_file_in_half(
        &mut self,
        index: usize,
        retry_unsplittable: bool,
    ) -> Result<bool> {
        log::debug!(
            "2 spilled streams could not be loaded into memory for merge \
        (requires 2x of the largest batch from both), re-spilling the larger of the two with half \
        the batch size to reduce memory needs for the next merge attempt. the shrunk run carries \
        a halved batch-size limit so only merges consuming it use the smaller batch size"
        );

        // Extract the target in O(1) instead of `remove(index)`, which would shift
        // every following spill file. Swap it to the back and pop it; the matching
        // swap after re-spilling restores the original order, so the vec ends up
        // exactly as it started, just with the target file shrunk.
        // `old_batch_size` is the batch size this run was written with (the full merge
        // batch size unless it was already shrunk once). Halving it caps the next merge
        // that reads this run so the merged output can't rebuild a full-size batch.
        let last = self.sorted_spill_files.len() - 1;
        self.sorted_spill_files.swap(index, last);
        let (mut target, old_batch_size) = self
            .sorted_spill_files
            .pop()
            .expect("index is in bounds, so the vec is non-empty");
        let old_max = target.max_record_batch_memory;
        let mut max_batch_rows = old_batch_size;

        // Reserve enough to hold a single stream of this file while we re-spill it.
        let reservation = self.reservation.new_empty();
        reservation
            .try_grow(get_reserved_bytes_for_record_batch_size(old_max, old_max))?;

        if self.reserve_replay_headroom {
            // A maximum-sized singleton cannot shrink. Find it without writing
            // another file: the original runs may already fill the disk quota.
            // Use an unbuffered reader so no background read outlives this guard.
            let mut source = self.spill_manager.read_spill_as_stream_unbuffered(
                Arc::clone(&target.file),
                Some(old_max),
            )?;
            let mut all_singletons = true;
            let mut max_is_singleton = false;
            let mut decoded_max = 0;
            max_batch_rows = 0;
            while let Some(batch) = source.next().await {
                let batch = batch?;
                max_batch_rows = max_batch_rows.max(batch.num_rows());
                all_singletons &= batch.num_rows() == 1;
                decoded_max = decoded_max.max(batch.get_sliced_size()?);
                if batch.num_rows() == 1
                    && gc_view_arrays(&batch)?.get_sliced_size()? >= old_max
                {
                    max_is_singleton = true;
                    break;
                }
            }
            // IPC can discard spare view-buffer capacity included in `old_max`.
            // A complete scan can correct that estimate without rewriting the
            // file. Use decoded buffers without GC, as the merge retains them.
            let shrank = !max_is_singleton && decoded_max < old_max;
            if shrank || all_singletons || max_is_singleton {
                if !shrank && !retry_unsplittable {
                    return resources_err!(
                        "Cannot merge sorted runs: a single record batch of {old_max} bytes \
                         exceeds the available merge memory and cannot be split further"
                    );
                }
                if shrank {
                    target.max_record_batch_memory = decoded_max;
                }
                let batch_size_limit = if all_singletons || max_is_singleton {
                    1
                } else {
                    old_batch_size.min(max_batch_rows).max(1)
                };
                self.sorted_spill_files.push((target, batch_size_limit));
                self.sorted_spill_files.swap(index, last);
                return Ok(shrank);
            }
        }

        let source = self
            .spill_manager
            .read_spill_as_stream(target.file, Some(old_max))?;
        // Re-spill with half the batch size: slice every batch in two. The spill
        // writer owns the batch layout, we only change how many rows per batch.
        let mut halved: SendableRecordBatchStream =
            Box::pin(RecordBatchStreamAdapter::new(
                Arc::clone(&self.schema),
                source.flat_map(|batch| {
                    futures::stream::iter(match batch {
                        Ok(batch) => split_batch_in_half(batch)
                            .into_iter()
                            .map(Ok)
                            .collect::<Vec<_>>(),
                        Err(e) => vec![Err(e)],
                    })
                }),
            ));

        let result = self
            .spill_manager
            .spill_record_batch_stream_and_return_max_batch_stats(
                &mut halved,
                "MultiLevelMergeBuilder split skewed spill",
            )
            .await?;

        reservation.free();

        let Some((file, new_max, new_max_batch_rows)) = result else {
            return internal_err!("re-spilling a skewed spill file produced no data");
        };

        // If halving cannot reduce the largest batch, only a requested retry
        // against the actual pool can make progress. The caller permits that
        // retry once before surfacing this error.
        let shrank = new_max < old_max;
        if !shrank && !retry_unsplittable {
            return resources_err!(
                "Cannot merge sorted runs: a single record batch of {old_max} bytes \
                 exceeds the available merge memory and cannot be split further"
            );
        }

        // Record the halved batch size as a *per-run* limit rather than lowering the
        // global batch size. Merges that don't touch this run keep the full batch
        // size. a merge that reads it caps its output at this limit so the merged run
        // can't rebuild a full-size batch and reintroduce the skew. Actual batches
        // can be shorter than the configured limit; use their size so the merge
        // cannot accumulate extra split batches outside its reservation.
        let new_batch_size_limit = if shrank {
            (old_batch_size / 2).min(max_batch_rows.div_ceil(2)).max(1)
        } else {
            // Skipping headroom only covers indivisible input rows, not a
            // larger output batch formed by concatenating those rows.
            1
        };
        self.size_intermediate_merges &= new_max_batch_rows >= new_batch_size_limit;

        // Push the re-spilled (smaller) file and swap it back into `index`, undoing
        // the swap-to-back above so the order is preserved.
        self.sorted_spill_files.push((
            SortedSpillFile {
                file,
                max_record_batch_memory: new_max,
            },
            new_batch_size_limit,
        ));
        let last = self.sorted_spill_files.len() - 1;
        self.sorted_spill_files.swap(index, last);

        Ok(shrank)
    }

    fn observe_output(
        &self,
        stream: SendableRecordBatchStream,
    ) -> SendableRecordBatchStream {
        Box::pin(ObservedStream::new(stream, self.metrics.clone(), None))
    }
}

/// Outcome of trying to reserve memory for one multi-level merge pass.
enum SpillFilesToMerge {
    /// Enough memory: the spill files to read this pass (each paired with its
    /// batch-size limit) and the read-ahead buffer size.
    Ready(Vec<(SortedSpillFile, usize)>, usize),
    /// Could not seat the minimum of 2 streams. Re-spill the spill file at this index
    /// with a smaller (halved) batch size, then retry the pass.
    SplitThenRetry(usize),
}

/// What one iteration of the multi-level merge loop should do next.
enum MergeStep {
    /// A merged stream is ready to be consumed (and possibly spilled back).
    Stream {
        stream: SendableRecordBatchStream,
        /// The batch-size limit to stamp on the run if this stream is re-spilled as an
        /// intermediate result: the batch size its merge ran at. It equals the full
        /// merge batch size unless the merge consumed a skew-resolved run, in which
        /// case it is that run's smaller limit so the re-spilled result stays capped
        /// and can't rebuild an oversized batch.
        batch_size_limit: usize,
    },
    /// Re-spill the spill file at this index smaller, then retry the merge step.
    SplitThenRetry(usize),
}

/// Slice `batch` into two row-halves so a re-spill writes batches half the size.
fn split_batch_in_half(batch: RecordBatch) -> Vec<RecordBatch> {
    let num_rows = batch.num_rows();
    if num_rows <= 1 {
        return vec![batch];
    }
    let mid = num_rows / 2;
    vec![batch.slice(0, mid), batch.slice(mid, num_rows - mid)]
}

fn effective_spill_merge_fan_in(configured_fan_in: usize) -> usize {
    if configured_fan_in == 0 {
        usize::MAX
    } else {
        configured_fan_in.max(2)
    }
}

struct StreamAttachedReservation {
    stream: SendableRecordBatchStream,
    reservation: MemoryReservation,
}

impl StreamAttachedReservation {
    fn new(stream: SendableRecordBatchStream, reservation: MemoryReservation) -> Self {
        Self {
            stream,
            reservation,
        }
    }
}

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

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

        match res {
            Poll::Ready(res) => {
                match res {
                    Some(Ok(batch)) => Poll::Ready(Some(Ok(batch))),
                    Some(Err(err)) => {
                        // Had an error so drop the data
                        self.reservation.free();
                        Poll::Ready(Some(Err(err)))
                    }
                    None => {
                        // Stream is done so free the memory
                        self.reservation.free();

                        Poll::Ready(None)
                    }
                }
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

impl RecordBatchStream for StreamAttachedReservation {
    fn schema(&self) -> SchemaRef {
        self.stream.schema()
    }
}

#[cfg(test)]
#[path = "multi_level_merge/intermediate_sizing_tests.rs"]
mod intermediate_sizing_tests;

#[cfg(test)]
mod tests {
    use super::*;

    use crate::expressions::PhysicalSortExpr;
    use arrow::array::{AsArray, Int64Array};
    use arrow::compute::concat_batches;
    use arrow::datatypes::{DataType, Field, Int64Type, Schema};
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };
    use datafusion_execution::runtime_env::{RuntimeEnv, RuntimeEnvBuilder};
    use datafusion_physical_expr::expressions::{Column, col};
    use datafusion_physical_expr_common::metrics::{
        ExecutionPlanMetricsSet, SpillMetrics,
    };

    pub(super) fn test_schema() -> SchemaRef {
        Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, false)]))
    }

    pub(super) fn build_spill_manager(
        env: &Arc<RuntimeEnv>,
        schema: &SchemaRef,
    ) -> SpillManager {
        SpillManager::new(
            Arc::clone(env),
            SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
            Arc::clone(schema),
        )
    }

    /// Spill `values` (which must already be sorted) as a single sorted run and
    /// return it as a `SortedSpillFile` carrying its recorded largest-batch memory.
    pub(super) fn make_sorted_spill_file(
        spill_manager: &SpillManager,
        schema: &SchemaRef,
        values: Vec<i64>,
    ) -> SortedSpillFile {
        let batch = RecordBatch::try_new(
            Arc::clone(schema),
            vec![Arc::new(Int64Array::from(values))],
        )
        .unwrap();
        let batches: Vec<Result<RecordBatch>> = vec![Ok(batch)];
        let (file, max_record_batch_memory) = spill_manager
            .spill_record_batch_iter_and_return_max_batch_memory(
                batches.into_iter(),
                "test input run",
            )
            .unwrap()
            .expect("spill should produce a file");
        SortedSpillFile {
            file,
            max_record_batch_memory,
        }
    }

    pub(super) fn build_merge_builder(
        spill_manager: SpillManager,
        schema: SchemaRef,
        sorted_spill_files: Vec<SortedSpillFile>,
        pool: &Arc<dyn MemoryPool>,
        batch_size: usize,
    ) -> MultiLevelMergeBuilder {
        let reservation = MemoryConsumer::new("test merge").register(pool);
        let expr: LexOrdering =
            [PhysicalSortExpr::new_default(Arc::new(Column::new("x", 0)))].into();
        MultiLevelMergeBuilder::new(
            spill_manager,
            schema,
            sorted_spill_files,
            vec![],
            expr,
            BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
            batch_size,
            reservation,
            None,
            false,
        )
    }

    #[rstest::rstest]
    #[case::full_batches(8, 128, 6)]
    #[case::replay_headroom_limits_sizing(9, 128, 7)]
    #[case::unchanged_selection(13, 128, 7)]
    #[case::short_batches(9, 64, 7)]
    #[tokio::test]
    async fn intermediate_merge_sizing_preserves_final_output(
        #[values(false, true)] size_intermediate_merges: bool,
        #[case] runs: usize,
        #[case] rows: usize,
        #[case] sized_intermediate_inputs: usize,
    ) -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);
        let spilled_rows = spill_manager.metrics.spilled_rows.clone();
        let files: Vec<_> = (0..runs)
            .map(|run| {
                make_sorted_spill_file(
                    &spill_manager,
                    &schema,
                    (0..rows).map(|row| (row * runs + run) as i64).collect(),
                )
            })
            .collect();
        let batch_memory = files[0].max_record_batch_memory;
        // Ordinary admission seats seven inputs with read-ahead and equal replay
        // headroom. The retained buffer grant can admit three final inputs plus
        // their replay headroom, so eight runs need six merged inputs. Nine or
        // thirteen runs require all seven and exercise the unchanged selection.
        // Short input batches can grow when merged, so they must keep the original
        // selection to avoid adding a pass with the larger output batch budget.
        let pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(8 * 7 * batch_memory));
        let mut builder =
            build_merge_builder(spill_manager, Arc::clone(&schema), files, &pool, 128)
                .with_replay_headroom(true);
        if size_intermediate_merges {
            builder = builder.with_intermediate_merge_sizing(Some(rows));
        }
        let stream = builder.create_spillable_merge_stream();
        let batches: Vec<RecordBatch> = stream.try_collect().await?;
        let merged = concat_batches(&schema, &batches)?;
        let expected = Int64Array::from_iter_values(0..(runs * rows) as i64);
        assert_eq!(merged.column(0).as_primitive::<Int64Type>(), &expected);
        let intermediate_inputs = if size_intermediate_merges {
            sized_intermediate_inputs
        } else {
            7
        };
        assert_eq!(spilled_rows.value(), (runs + intermediate_inputs) * rows);
        assert_eq!(pool.reserved(), 0);
        assert_eq!(env.disk_manager.spilling_progress().active_files_count, 0);
        assert_eq!(env.disk_manager.used_disk_space(), 0);
        Ok(())
    }

    #[rstest::rstest]
    #[tokio::test]
    async fn intermediate_merge_sizing_preserves_heterogeneous_runs(
        #[values(false, true)] size_intermediate_merges: bool,
    ) -> Result<()> {
        use arrow::array::StringArray;
        use arrow::buffer::{Buffer, OffsetBuffer};

        let env = Arc::new(RuntimeEnv::default());
        let schema = Arc::new(Schema::new(vec![
            Field::new("x", DataType::Int64, false),
            Field::new("payload", DataType::Utf8, false),
        ]));
        let spill_manager = build_spill_manager(&env, &schema);
        let spilled_rows = spill_manager.metrics.spilled_rows.clone();
        let rows = 128;
        let mut files = Vec::new();
        for run in 0..8 {
            let width = if run == 6 { 256 } else { 16 };
            let payload = StringArray::new(
                OffsetBuffer::new(
                    (0..=rows)
                        .map(|row| (row * width) as i32)
                        .collect::<Vec<_>>()
                        .into(),
                ),
                Buffer::from(vec![b'x'; rows * width]),
                None,
            );
            let batch = RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int64Array::from_iter_values(
                        (run * rows..(run + 1) * rows).map(|value| value as i64),
                    )),
                    Arc::new(payload),
                ],
            )?;
            let (file, max_record_batch_memory) = spill_manager
                .spill_record_batch_iter_and_return_max_batch_memory(
                    std::iter::once(Ok(batch)),
                    "heterogeneous input run",
                )?
                .unwrap();
            files.push(SortedSpillFile {
                file,
                max_record_batch_memory,
            });
        }
        let small = files[0].max_record_batch_memory;
        let wide = files[6].max_record_batch_memory;
        // Admit six small inputs first, then the wide input and one small input.
        // Trimming the first merge to three wrongly assumes its fan-in will also
        // fit the wider suffix, adding a later rewrite of the small runs.
        let pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(8 * (wide + small + small / 2)));
        let builder =
            build_merge_builder(spill_manager, Arc::clone(&schema), files, &pool, rows)
                .with_replay_headroom(true)
                .with_intermediate_merge_sizing(size_intermediate_merges.then_some(rows));
        let batches: Vec<RecordBatch> = builder
            .create_spillable_merge_stream()
            .try_collect()
            .await?;
        let merged = concat_batches(&schema, &batches)?;
        let expected = Int64Array::from_iter_values(0..(8 * rows) as i64);
        assert_eq!(merged.column(0).as_primitive::<Int64Type>(), &expected);
        let small_payload = "x".repeat(16);
        let wide_payload = "x".repeat(256);
        let expected_payload = StringArray::from_iter_values((0..8).flat_map(|run| {
            std::iter::repeat_n(
                if run == 6 {
                    &wide_payload
                } else {
                    &small_payload
                },
                rows,
            )
        }));
        assert_eq!(merged.column(1).as_string::<i32>(), &expected_payload);
        assert_eq!(spilled_rows.value(), 16 * rows);
        assert_eq!(pool.reserved(), 0);
        assert_eq!(env.disk_manager.spilling_progress().active_files_count, 0);
        assert_eq!(env.disk_manager.used_disk_space(), 0);
        Ok(())
    }

    /// Two sorted runs whose largest batches are too big to both
    /// be seated in the merge budget at once are re-spilled (halved) until they
    /// fit, and the merge then completes with fully sorted, complete output.
    #[tokio::test]
    async fn skewed_runs_reuse_retained_workspace_across_retries() -> Result<()> {
        // These budgets require one and two re-spills, respectively.
        for (budget_halves, expected_splits) in [(7, 1), (5, 2)] {
            let capacity = 1024 * 1024;
            let parent: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(capacity));
            let env = RuntimeEnvBuilder::new()
                .with_memory_pool(Arc::clone(&parent))
                .build_arc()?;
            let schema = test_schema();
            let spill_manager = build_spill_manager(&env, &schema);
            let spill_count = spill_manager.metrics.spill_file_count.clone();
            let n: i64 = 16384;
            let f0 = make_sorted_spill_file(&spill_manager, &schema, (0..n).collect());
            let f1 = make_sorted_spill_file(&spill_manager, &schema, (0..n).collect());
            let m = f0.max_record_batch_memory.max(f1.max_record_batch_memory);
            let workspace = m * budget_halves / 2;
            assert!(workspace < capacity);
            let merge_pool = Arc::new(MergeMemoryPool::new(
                Arc::clone(&parent),
                MemoryConsumer::new("merge workspace"),
            ));
            let pool: Arc<dyn MemoryPool> =
                Arc::clone(&merge_pool) as Arc<dyn MemoryPool>;
            let batch_size = 8192;
            let mut builder = build_merge_builder(
                spill_manager,
                Arc::clone(&schema),
                vec![f0, f1],
                &pool,
                batch_size,
            )
            .with_merge_pool(Some(Arc::clone(&merge_pool)));
            builder.reservation.try_grow(workspace)?;
            merge_pool.retain(workspace);
            let contender = MemoryConsumer::new("contender").register(&parent);
            contender.try_grow(capacity - workspace)?;

            // Drive each retry so its freed child reservation cannot silently
            // release the workspace and reacquire it from the parent pool.
            for _ in 0..expected_splits {
                let MergeStep::SplitThenRetry(index) =
                    builder.merge_sorted_runs_within_mem_limit(false)?
                else {
                    panic!("the merge must re-spill a skewed run");
                };
                assert_eq!(parent.reserved(), capacity);
                assert!(contender.try_grow(1).is_err());
                builder.split_spill_file_in_half(index, false).await?;
                assert_eq!(parent.reserved(), capacity);
                assert!(contender.try_grow(1).is_err());
            }

            let final_bytes: usize = builder
                .sorted_spill_files
                .iter()
                .map(|(file, _)| {
                    get_reserved_bytes_for_record_batch_size(
                        file.max_record_batch_memory,
                        file.max_record_batch_memory,
                    )
                })
                .sum();
            assert!(final_bytes < workspace && workspace < 2 * final_bytes);

            let mut stream = builder.create_spillable_merge_stream();
            let first = stream.try_next().await?.expect("nonempty merge");
            assert_eq!(spill_count.value(), 2 + expected_splits);
            assert_eq!(merge_pool.reserved(), final_bytes);
            assert_eq!(parent.reserved(), contender.size() + final_bytes);

            let mut batches = vec![first];
            while let Some(batch) = stream.try_next().await? {
                batches.push(batch);
            }
            assert_eq!(
                batches.iter().map(|batch| batch.num_rows()).max(),
                Some(batch_size / 2),
                "splitting both runs must halve, not quarter, the output batch size"
            );
            let merged = concat_batches(&schema, &batches)?;
            let expected =
                Int64Array::from_iter_values((0..n).flat_map(|value| [value, value]));
            assert_eq!(merged.column(0).as_primitive::<Int64Type>(), &expected);

            // The pool stays alive: EOF must release live bytes and the idle floor.
            assert_eq!(merge_pool.reserved(), 0);
            assert_eq!(parent.reserved(), contender.size());
            drop(stream);
            assert_eq!(env.disk_manager.spilling_progress().active_files_count, 0);
            assert_eq!(env.disk_manager.used_disk_space(), 0);
            drop(contender);
            assert_eq!(parent.reserved(), 0);
        }
        Ok(())
    }

    #[tokio::test]
    async fn skewed_runs_are_respilled_so_the_merge_fits() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);

        let n: i64 = 16384;
        let f0 = make_sorted_spill_file(&spill_manager, &schema, (0..n).collect());
        let f1 = make_sorted_spill_file(&spill_manager, &schema, (0..n).collect());
        let m = f0.max_record_batch_memory.max(f1.max_record_batch_memory);

        // Seating two streams needs ~4*m (2*m each), which does NOT fit, but the
        // budget is large enough once a run is halved. The rescue keeps halving
        // the blocking run until two streams fit (here, after one halving).
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(m * 7 / 2));

        let builder = build_merge_builder(
            spill_manager,
            Arc::clone(&schema),
            vec![f0, f1],
            &pool,
            8192,
        );
        let stream = builder.create_spillable_merge_stream();
        let batches: Vec<RecordBatch> = stream.try_collect().await?;

        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(
            total_rows,
            (2 * n) as usize,
            "the merge must emit every input row"
        );

        let merged = concat_batches(&schema, &batches)?;
        let col = merged.column(0).as_primitive::<Int64Type>();
        for i in 1..col.len() {
            assert!(
                col.value(i - 1) <= col.value(i),
                "merge output must be sorted: {} > {} at {i}",
                col.value(i - 1),
                col.value(i),
            );
        }

        Ok(())
    }

    /// A run can fit the pool during splitting but leave no room for replay.
    /// Splitting must shrink the merge buffers to half the available memory.
    #[rstest::rstest]
    #[tokio::test]
    async fn replay_headroom_splits_an_oversized_first_run(
        #[values(128, 129, 4096)] rows: i64,
    ) -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);
        let first = make_sorted_spill_file(&spill_manager, &schema, (0..rows).collect());
        let second =
            make_sorted_spill_file(&spill_manager, &schema, (rows..2 * rows).collect());
        let merge_limit = first.max_record_batch_memory;
        // One original run fills the pool. Splitting may use that space before
        // replay starts, but the final merge must leave half the pool for replay.
        let pool_size = 2 * merge_limit;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(pool_size));
        let builder = build_merge_builder(
            spill_manager,
            Arc::clone(&schema),
            vec![first, second],
            &pool,
            8192,
        )
        .with_replay_headroom(true);
        let mut stream = builder.create_spillable_merge_stream();
        let mut batches = vec![];
        while let Some(batch) = stream.next().await {
            let batch = batch?;
            // Short input runs must not rebuild a larger output batch than
            // the attached merge reservation can hold.
            assert!(
                crate::spill::get_record_batch_memory_size(&batch) <= pool.reserved()
            );
            batches.push(batch);
            assert!(pool.reserved() <= merge_limit);
        }
        let merged = concat_batches(&schema, &batches)?;
        let values = merged.column(0).as_primitive::<Int64Type>();
        assert_eq!(values.len(), (2 * rows) as usize);
        for (expected, value) in values.values().iter().enumerate() {
            assert_eq!(*value, expected as i64);
        }
        drop(stream);
        assert_eq!(pool.reserved(), 0);
        assert_eq!(env.disk_manager.spilling_progress().current_bytes, 0);
        assert_eq!(env.disk_manager.spilling_progress().active_files_count, 0);
        Ok(())
    }

    #[tokio::test]
    async fn replay_headroom_allows_only_an_indivisible_minimum() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);
        let spills = (0..3)
            .map(|value| make_sorted_spill_file(&spill_manager, &schema, vec![value]))
            .collect::<Vec<_>>();
        let batch_memory = spills[0].max_record_batch_memory;
        let pool_size = 6 * batch_memory;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(pool_size));
        let mut builder =
            build_merge_builder(spill_manager, Arc::clone(&schema), spills, &pool, 8192)
                .with_replay_headroom(true);

        assert!(!builder.split_spill_file_in_half(0, true).await?);
        assert_eq!(builder.sorted_spill_files.len(), 3);
        // Actual batches contain one row even though the nominal size is 8192.
        assert_eq!(builder.sorted_spill_files[0].1, 1);
        let mut reservation = builder.reservation.new_empty();
        let SpillFilesToMerge::Ready(spills, buffer_len) =
            builder.get_sorted_spill_files_to_merge(2, 2, &mut reservation, true)?
        else {
            panic!("minimum merge should fit the pool");
        };
        assert_eq!(buffer_len, 1);
        assert_eq!(spills.len(), 2);
        assert_eq!(builder.sorted_spill_files.len(), 1);
        assert_eq!(reservation.size(), 4 * batch_memory);
        builder.sorted_spill_files.splice(0..0, spills);
        reservation.free();

        let mut stream = builder.create_spillable_merge_stream();
        let mut values = Vec::new();
        while let Some(batch) = stream.next().await {
            let batch = batch?;
            assert_eq!(batch.num_rows(), 1);
            values.push(batch.column(0).as_primitive::<Int64Type>().value(0));
        }
        assert_eq!(values, vec![0, 1, 2]);
        drop(stream);
        assert_eq!(pool.reserved(), 0);
        assert_eq!(env.disk_manager.spilling_progress().current_bytes, 0);
        assert_eq!(env.disk_manager.spilling_progress().active_files_count, 0);
        Ok(())
    }

    #[test]
    fn replay_headroom_is_released_after_rejected_candidate() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);
        let spills = (0..3)
            .map(|value| make_sorted_spill_file(&spill_manager, &schema, vec![value]))
            .collect::<Vec<_>>();
        let batch_memory = spills[0].max_record_batch_memory;
        let pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(10 * batch_memory));
        let mut builder = build_merge_builder(spill_manager, schema, spills, &pool, 1)
            .with_replay_headroom(true);
        let mut reservation = builder.reservation.new_empty();
        let SpillFilesToMerge::Ready(spills, buffer_len) =
            builder.get_sorted_spill_files_to_merge(1, 2, &mut reservation, false)?
        else {
            panic!("two streams and replay headroom should fit the pool");
        };
        assert_eq!(buffer_len, 1);
        assert_eq!(spills.len(), 2);
        assert_eq!(builder.sorted_spill_files.len(), 1);
        // The third candidate failed its 12-batch reservation. Release the
        // successful probe's spare four batches, retaining only two inputs.
        assert_eq!(reservation.size(), 4 * batch_memory);
        let replay = builder.reservation.new_empty();
        replay.try_grow(6 * batch_memory)?;
        assert_eq!(pool.reserved(), 10 * batch_memory);
        drop((replay, reservation, spills, builder));
        assert_eq!(pool.reserved(), 0);
        assert_eq!(env.disk_manager.spilling_progress().current_bytes, 0);
        assert_eq!(env.disk_manager.spilling_progress().active_files_count, 0);
        Ok(())
    }

    #[tokio::test]
    async fn replay_headroom_still_enforces_the_actual_pool() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);
        let first = make_sorted_spill_file(&spill_manager, &schema, vec![1]);
        let second = make_sorted_spill_file(&spill_manager, &schema, vec![2]);
        let batch_memory = first.max_record_batch_memory;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(3 * batch_memory));
        let builder =
            build_merge_builder(spill_manager, schema, vec![first, second], &pool, 8192)
                .with_replay_headroom(true);
        let mut stream = builder.create_spillable_merge_stream();
        let error = stream.next().await.unwrap().unwrap_err();
        assert!(error.to_string().contains("cannot be split further"));
        drop(stream);
        assert_eq!(pool.reserved(), 0);
        assert_eq!(env.disk_manager.spilling_progress().current_bytes, 0);
        assert_eq!(env.disk_manager.spilling_progress().active_files_count, 0);
        Ok(())
    }

    #[rstest::rstest]
    #[case(1, false, DataType::Utf8)]
    #[case(8192, true, DataType::Utf8)]
    #[case(8192, true, DataType::Utf8View)]
    #[tokio::test]
    async fn indivisible_spill_merge_needs_no_extra_disk_space(
        #[case] batch_size: usize,
        #[case] mixed_batches: bool,
        #[case] data_type: DataType,
    ) -> Result<()> {
        use arrow::array::{ArrayRef, StringArray, StringViewArray};

        const KEY_BYTES: usize = 300_000;
        const POOL_BYTES: usize = 2 * 1024 * 1024;
        let schema = Arc::new(Schema::new(vec![Field::new("x", data_type, false)]));
        let make_runs = |manager: &SpillManager| -> Result<Vec<SortedSpillFile>> {
            (0..2)
                .map(|run| {
                    let batches = (0..8).map(|batch| {
                        // A small two-row batch before the large singleton
                        // prevents treating the first batch as representative.
                        let keys = if mixed_batches && batch == 0 {
                            vec![format!("{run:04}"), format!("{:04}", run + 2)]
                        } else {
                            let key = run + 2 * (batch + usize::from(mixed_batches));
                            vec![format!("{key:04}{}", "x".repeat(KEY_BYTES - 4))]
                        };
                        let values: ArrayRef = match schema.field(0).data_type() {
                            DataType::Utf8 => Arc::new(StringArray::from(keys)),
                            DataType::Utf8View => Arc::new(StringViewArray::from(keys)),
                            _ => unreachable!(),
                        };
                        RecordBatch::try_new(Arc::clone(&schema), vec![values])
                            .map_err(Into::into)
                    });
                    let (file, max_record_batch_memory) = manager
                        .spill_record_batch_iter_and_return_max_batch_memory(
                            batches,
                            "indivisible input run",
                        )?
                        .unwrap();
                    Ok(SortedSpillFile {
                        file,
                        max_record_batch_memory,
                    })
                })
                .collect()
        };

        // Calibrate the quota to exactly the original IPC files, with no room
        // for even a replacement header. Keep several batches in each run so
        // read-ahead cannot retire the original before the unnecessary write.
        let calibration = Arc::new(RuntimeEnv::default());
        let runs = make_runs(&build_spill_manager(&calibration, &schema))?;
        let quota = runs.iter().map(|run| run.file.size().unwrap()).sum();
        drop(runs);
        let env = RuntimeEnvBuilder::new()
            .with_max_temp_directory_size(quota)
            .build_arc()?;
        let manager = build_spill_manager(&env, &schema);
        let runs = make_runs(&manager)?;
        assert_eq!(env.disk_manager.spilling_progress().current_bytes, quota);
        assert!(4 * runs[0].max_record_batch_memory > POOL_BYTES / 2);
        assert!(4 * runs[0].max_record_batch_memory <= POOL_BYTES);
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(POOL_BYTES));
        let builder = build_merge_builder(manager, schema, runs, &pool, batch_size)
            .with_replay_headroom(true);
        let mut stream = builder.create_spillable_merge_stream();
        let mut expected = 0;
        while let Some(batch) = stream.next().await {
            let batch = batch?;
            assert_eq!(batch.num_rows(), 1);
            let values = arrow::compute::cast(batch.column(0), &DataType::Utf8)?;
            let key = values.as_string::<i32>().value(0);
            assert_eq!(key[..4].parse::<usize>().unwrap(), expected);
            expected += 1;
        }
        assert_eq!(expected, if mixed_batches { 18 } else { 16 });
        drop(stream);
        assert_eq!(pool.reserved(), 0);
        let progress = env.disk_manager.spilling_progress();
        assert_eq!(progress.current_bytes, 0);
        assert_eq!(progress.active_files_count, 0);
        Ok(())
    }

    #[rstest::rstest]
    #[tokio::test]
    async fn small_view_spill_merge_needs_no_extra_disk_space(
        #[values(3, 6)] pool_batches: usize,
        #[values(false, true)] mixed_batches: bool,
    ) -> Result<()> {
        use arrow::array::StringViewBuilder;

        let schema = Arc::new(Schema::new(vec![Field::new(
            "x",
            DataType::Utf8View,
            false,
        )]));
        let make_runs = |manager: &SpillManager| -> Result<Vec<SortedSpillFile>> {
            (0..2)
                .map(|run| {
                    let batches = (0..8).map(|batch| {
                        // A non-inline value retains the builder's 8 KiB block,
                        // but IPC stores only its used bytes. Small view buffers
                        // are below the spill writer's compaction threshold.
                        let key = format!("{:04}xxxxxxxxx", run + 2 * batch);
                        let mut values = StringViewBuilder::with_capacity(1)
                            .with_fixed_block_size(8192);
                        values.append_value(key);
                        // A larger final batch requires scanning the entire run
                        // before replacing its maximum decoded size.
                        if mixed_batches && batch == 7 {
                            values.append_value(format!(
                                "{:04}xxxxxxxxx",
                                run + 2 * (batch + 1)
                            ));
                        }
                        RecordBatch::try_new(
                            Arc::clone(&schema),
                            vec![Arc::new(values.finish())],
                        )
                        .map_err(Into::into)
                    });
                    let (file, max_record_batch_memory) = manager
                        .spill_record_batch_iter_and_return_max_batch_memory(
                            batches,
                            "small view singleton run",
                        )?
                        .unwrap();
                    Ok(SortedSpillFile {
                        file,
                        max_record_batch_memory,
                    })
                })
                .collect()
        };

        // Fill the quota with the original runs. Multiple batches prevent
        // read-ahead from retiring a run before an unnecessary replacement write.
        let calibration = Arc::new(RuntimeEnv::default());
        let runs = make_runs(&build_spill_manager(&calibration, &schema))?;
        let quota = runs.iter().map(|run| run.file.size().unwrap()).sum();
        drop(runs);
        let env = RuntimeEnvBuilder::new()
            .with_max_temp_directory_size(quota)
            .build_arc()?;
        let manager = build_spill_manager(&env, &schema);
        let runs = make_runs(&manager)?;
        assert_eq!(env.disk_manager.spilling_progress().current_bytes, quota);
        let stored_max = runs[0].max_record_batch_memory;
        let mut source = manager.read_spill_as_stream_unbuffered(
            Arc::clone(&runs[0].file),
            Some(stored_max),
        )?;
        let batch = source.next().await.unwrap()?;
        assert_eq!(batch.num_rows(), 1);
        assert!(gc_view_arrays(&batch)?.get_sliced_size()? < stored_max);
        drop((source, batch));

        // The stale estimate needs four batches for the minimum merge. Test
        // limits below and above that estimate: both can fit the decoded rows.
        let pool_bytes = pool_batches * stored_max;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(pool_bytes));
        let builder = build_merge_builder(manager, schema, runs, &pool, 8192)
            .with_replay_headroom(true);
        let mut stream = builder.create_spillable_merge_stream();
        let mut expected = 0;
        while let Some(batch) = stream.next().await {
            let batch = batch?;
            if mixed_batches {
                assert!(batch.num_rows() <= 2);
            } else {
                assert_eq!(batch.num_rows(), 1);
            }
            for key in batch.column(0).as_string_view().iter() {
                assert_eq!(key.unwrap(), format!("{expected:04}xxxxxxxxx"));
                expected += 1;
            }
        }
        assert_eq!(expected, if mixed_batches { 18 } else { 16 });
        drop(stream);
        assert_eq!(pool.reserved(), 0);
        let progress = env.disk_manager.spilling_progress();
        assert_eq!(progress.current_bytes, 0);
        assert_eq!(progress.active_files_count, 0);
        Ok(())
    }

    /// Tests the `new_max >= old_max` guard: a single-row run cannot be split
    /// any smaller, so re-spilling it does not shrink the largest batch and the
    /// rescue surfaces `ResourcesExhausted` rather than looping forever.
    #[tokio::test]
    async fn respilling_an_unsplittable_run_surfaces_resources_exhausted() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);

        // A one-row run: `split_batch_in_half` returns it unchanged, so the
        // re-spilled file's largest batch cannot drop below the original.
        let f0 = make_sorted_spill_file(&spill_manager, &schema, vec![42]);

        // Ample budget so the only possible failure is the un-splittable guard,
        // not the single-stream reservation itself.
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1024 * 1024));
        let mut builder =
            build_merge_builder(spill_manager, schema, vec![f0], &pool, 1024);

        let err = builder
            .split_spill_file_in_half(0, false)
            .await
            .expect_err("re-spilling a one-row run cannot shrink it");
        assert!(
            err.to_string().contains("cannot be split further"),
            "expected the un-splittable guard error, got: {err}"
        );

        Ok(())
    }

    /// Proves the re-spill also halves the merge output batch size: after one
    /// re-spill the merged run is emitted in 4096-row batches (not the original
    /// 8192), so it cannot rebuild a full-size batch and reintroduce the skew.
    #[tokio::test]
    async fn respill_halves_the_merge_output_batch_size() -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);

        let n: i64 = 16384;
        let f0 = make_sorted_spill_file(&spill_manager, &schema, (0..n).collect());
        let f1 = make_sorted_spill_file(&spill_manager, &schema, (0..n).collect());
        let m = f0.max_record_batch_memory.max(f1.max_record_batch_memory);

        // 3.5*m forces exactly one re-spill (split one run, then both fit), which
        // halves the merge output batch size.
        let initial_batch_size = 8192;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(m * 7 / 2));

        let builder = build_merge_builder(
            spill_manager,
            Arc::clone(&schema),
            vec![f0, f1],
            &pool,
            initial_batch_size,
        );
        let stream = builder.create_spillable_merge_stream();
        let batches: Vec<RecordBatch> = stream.try_collect().await?;

        // All rows are still present.
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, (2 * n) as usize);

        // The largest emitted batch is the halved size, not the original 8192: the
        // shrunk run carries a halved batch-size limit, and the final pass consumes
        // it, so the merge output is capped there. Without the per-run limit the merge
        // would rebuild 8192-row batches.
        let expected_batch_size = initial_batch_size / 2;
        let max_batch_rows = batches.iter().map(|b| b.num_rows()).max().unwrap_or(0);
        assert_eq!(
            max_batch_rows, expected_batch_size,
            "after one re-spill the merge must emit {expected_batch_size}-row \
             batches, got a largest batch of {max_batch_rows} rows"
        );

        Ok(())
    }

    /// Same as [`respill_halves_the_merge_output_batch_size`], but under a budget tight
    /// enough that *both* runs must be re-spilled before the merge fits - the scenario
    /// where the batch-size reduction could compound. Because the reduction is tracked
    /// per-run (each run capped at half) rather than by halving the global batch size on
    /// every split, the merged output is emitted in 4096-row batches - half, not a
    /// quarter. A global-halving implementation would have halved once per re-spill and
    /// emitted 2048-row batches.
    #[tokio::test]
    async fn respilling_two_skewed_runs_halves_the_output_without_compounding()
    -> Result<()> {
        let env = Arc::new(RuntimeEnv::default());
        let schema = test_schema();
        let spill_manager = build_spill_manager(&env, &schema);

        let n: i64 = 16384;
        let f0 = make_sorted_spill_file(&spill_manager, &schema, (0..n).collect());
        let f1 = make_sorted_spill_file(&spill_manager, &schema, (0..n).collect());
        let m = f0.max_record_batch_memory.max(f1.max_record_batch_memory);

        // 2.5*m is tight enough that even after halving one run the two still don't
        // fit, so *both* runs are re-spilled once before the merge succeeds. (3.5*m,
        // as in the single-split test, would let the pair fit after one split.) This
        // is exactly the scenario where a compounding, global-halving implementation
        // would drive the output batch size down to a quarter.
        let initial_batch_size = 8192;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(m * 5 / 2));

        let builder = build_merge_builder(
            spill_manager,
            Arc::clone(&schema),
            vec![f0, f1],
            &pool,
            initial_batch_size,
        );
        let stream = builder.create_spillable_merge_stream();
        let batches: Vec<RecordBatch> = stream.try_collect().await?;

        // All rows are still present.
        let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
        assert_eq!(total_rows, (2 * n) as usize);

        // Each run was re-spilled once, so each is capped at half the original batch
        // size and the merge caps its output at that half - NOT a quarter. A global
        // halving-per-split implementation would have emitted 2048-row batches here.
        let expected_batch_size = initial_batch_size / 2;
        let max_batch_rows = batches.iter().map(|b| b.num_rows()).max().unwrap_or(0);
        assert_eq!(
            max_batch_rows, expected_batch_size,
            "two re-spills must halve (not quarter) the output: expected \
             {expected_batch_size}-row batches, got a largest batch of \
             {max_batch_rows} rows"
        );

        Ok(())
    }

    #[test]
    fn spill_merge_fan_in_is_unlimited_by_default() {
        assert_eq!(effective_spill_merge_fan_in(0), usize::MAX);
    }

    #[test]
    fn spill_merge_fan_in_preserves_merge_progress() {
        assert_eq!(effective_spill_merge_fan_in(1), 2);
        assert_eq!(effective_spill_merge_fan_in(2), 2);
        assert_eq!(effective_spill_merge_fan_in(8), 8);
    }

    #[test]
    fn spill_merge_phase_respects_configured_fan_in() -> Result<()> {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
        let runtime = RuntimeEnvBuilder::new()
            .with_max_spill_merge_fan_in(2)
            .build_arc()?;
        let spill_manager = SpillManager::new(
            Arc::clone(&runtime),
            SpillMetrics::new(&ExecutionPlanMetricsSet::new(), 0),
            Arc::clone(&schema),
        );
        let sorted_spill_files = (0..4)
            .map(|idx| {
                Ok(SortedSpillFile {
                    file: runtime
                        .disk_manager
                        .create_tmp_file(&format!("spill fan-in test {idx}"))?,
                    max_record_batch_memory: 1,
                })
            })
            .collect::<Result<Vec<_>>>()?;
        let expr = LexOrdering::new([PhysicalSortExpr::new_default(col("a", &schema)?)])
            .unwrap();
        let reservation =
            MemoryConsumer::new("spill_merge_phase_respects_configured_fan_in")
                .register(&runtime.memory_pool);
        let metrics = BaselineMetrics::new(&ExecutionPlanMetricsSet::new(), 0);
        let mut builder = MultiLevelMergeBuilder::new(
            spill_manager,
            schema,
            sorted_spill_files,
            vec![],
            expr,
            metrics,
            1024,
            reservation,
            None,
            false,
        );
        let mut merge_reservation = MemoryConsumer::new("spill_merge_fan_in_phase")
            .register(&runtime.memory_pool);

        let (spills, buffer_len) = match builder.get_sorted_spill_files_to_merge(
            1,
            2,
            &mut merge_reservation,
            false,
        )? {
            SpillFilesToMerge::Ready(spills, buffer_len) => (spills, buffer_len),
            SpillFilesToMerge::SplitThenRetry(index) => {
                panic!("expected ready spill files, got retry for index {index}")
            }
        };

        assert_eq!(spills.len(), 2);
        assert_eq!(buffer_len, 1);
        assert_eq!(builder.sorted_spill_files.len(), 2);

        Ok(())
    }
}