aws-s3-transfer 1.0.0

Transfer Manager for Amazon S3 - a high-performance data plane client for uploading and downloading objects and directories.
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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use std::io::IoSlice;

use bytes::Buf;

use crate::runtime::buffer_pool::{Reservation, SegmentedBytes};
use crate::runtime::sync::sync::atomic::{AtomicU64, Ordering};
use crate::runtime::sync::sync::Arc;

use super::recv_buffer::{
    DrainMode, FillOutcome, PagedRecvBuffer, RecvBufferConsumer, SegmentWrite, SlotHandle,
};
use super::sink::SinkWrite;
use super::ChunkMetadata;

/// Segment size for the paged buffer. Re-exported from `recv_buffer` for test access.
const SEG_SIZE: usize = super::recv_buffer::DEFAULT_SEG_SIZE;
use super::transfer::DownloadTransfer;

/// Wakeup signal wrapper. Under loom, tokio::sync::Notify is unavailable,
/// but the Notify doesn't participate in safety invariants — it's just a
/// hint to the consumer. A no-op stub is sufficient for loom tests.
#[cfg(not(all(test, s3_tm_loom)))]
use tokio::sync::Notify as WakeNotify;

#[cfg(all(test, s3_tm_loom))]
struct WakeNotify;

#[cfg(all(test, s3_tm_loom))]
impl WakeNotify {
    fn new() -> Self {
        Self
    }
    fn notify_one(&self) {}
    async fn notified(&self) {}
}

/// Borrowed read position over one contiguous run being written to disk.
///
/// The claimed receive-buffer slots retain ownership until the write
/// completes. This cursor presents their bytes without cloning owner metadata.
pub(crate) struct DiskWriteCursor<'a> {
    write: &'a SegmentWrite<ChunkOutput>,
    payload_index: usize,
    payload_offset: usize,
    remaining: usize,
}

impl<'a> DiskWriteCursor<'a> {
    /// Validates one claimed run and returns its object offset and read cursor.
    fn new(write: &'a SegmentWrite<ChunkOutput>) -> std::io::Result<(u64, Self)> {
        let mut object_offset = None;
        let mut expected_offset = None;
        let mut remaining = 0usize;

        for slot in write.payloads() {
            let chunk = slot.get().ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "claimed disk-write run contains an unfilled slot",
                )
            })?;
            let chunk_len = chunk.data.remaining();
            if chunk_len == 0 {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "claimed disk-write run contains an empty payload",
                ));
            }
            if let Some(expected) = expected_offset {
                if chunk.offset != expected {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "claimed disk-write run has noncontiguous object offsets",
                    ));
                }
            } else {
                object_offset = Some(chunk.offset);
            }

            let chunk_len_u64 = u64::try_from(chunk_len).map_err(|_| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "disk-write payload length exceeds object-offset representation",
                )
            })?;
            expected_offset = Some(chunk.offset.checked_add(chunk_len_u64).ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "disk-write object offset overflow",
                )
            })?);
            remaining = remaining.checked_add(chunk_len).ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "disk-write run length overflow",
                )
            })?;
        }

        let object_offset = object_offset.ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "claimed disk-write run contains no payloads",
            )
        })?;
        Ok((
            object_offset,
            Self {
                write,
                payload_index: 0,
                payload_offset: 0,
                remaining,
            },
        ))
    }

    fn current(&self) -> &SegmentedBytes {
        self.write.payloads()[self.payload_index]
            .get()
            .map(|chunk| &chunk.data)
            .expect("validated disk-write payload disappeared")
    }
}

impl Buf for DiskWriteCursor<'_> {
    fn remaining(&self) -> usize {
        self.remaining
    }

    fn chunk(&self) -> &[u8] {
        if self.remaining == 0 {
            return &[];
        }
        self.current().chunk_from(self.payload_offset)
    }

    fn chunks_vectored<'a>(&'a self, dst: &mut [IoSlice<'a>]) -> usize {
        let mut written = 0;
        for (index, slot) in self.write.payloads()[self.payload_index..]
            .iter()
            .enumerate()
        {
            if written == dst.len() {
                break;
            }
            let chunk = slot
                .get()
                .expect("validated disk-write payload disappeared");
            let offset = if index == 0 { self.payload_offset } else { 0 };
            written += chunk.data.chunks_vectored_from(offset, &mut dst[written..]);
        }
        written
    }

    fn advance(&mut self, mut count: usize) {
        assert!(
            count <= self.remaining,
            "advanced beyond download write run"
        );
        self.remaining -= count;
        while count != 0 {
            let current_len = self.current().remaining();
            let available = current_len
                .checked_sub(self.payload_offset)
                .expect("disk-write cursor exceeds its payload");
            let advanced = count.min(available);
            self.payload_offset += advanced;
            count -= advanced;
            if self.payload_offset == current_len {
                self.payload_index += 1;
                self.payload_offset = 0;
            }
        }
    }
}

/// Stream vs disk discrimination. Mutually exclusive per transfer.
#[derive(Debug)]
enum Mode {
    Stream,
    /// Positioned writes land at `chunk.offset - object_range_start` in the sink.
    Disk {
        sink: Box<dyn SinkWrite>,
        /// Start of the resolved S3 byte range for this transfer.
        object_range_start: std::sync::OnceLock<u64>,
        /// Bytes the sink has accepted across every drain. Only completed run
        /// writes are counted, so this never exceeds what reached the sink.
        written: AtomicU64,
    },
}

/// Destination work done by one drain call.
///
/// A run is counted only after the sink accepted all of it. A drain that fails
/// returns what it did before the failure in its [`DrainError`].
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Drained {
    /// Parts whose payloads were written and freed: the read-ahead occupancy
    /// the caller releases.
    pub(crate) parts: u64,
    /// Bytes the sink accepted.
    pub(crate) bytes: u64,
}

/// A drain that failed after writing `drained`: the runs the sink accepted before
/// the failing one, or, from `finalize`, the tail its terminal drain wrote.
#[derive(Debug)]
pub(crate) struct DrainError {
    pub(crate) drained: Drained,
    pub(crate) source: std::io::Error,
}

/// Producer handle to the download body buffer. Held at `self.inner.writer`
/// in the transfer. Clone shares all state via `Arc`.
#[derive(Clone)]
pub(crate) struct BodyWriter {
    buffer: PagedRecvBuffer<ChunkOutput>,
    notify: Arc<WakeNotify>,
    mode: Arc<Mode>,
}

impl std::fmt::Debug for BodyWriter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BodyWriter")
            .field("mode", &self.mode)
            .finish_non_exhaustive()
    }
}

/// A claimed slot in the body buffer, produced by [`BodyWriter::claim`].
/// Consuming [`fill`](Self::fill) publishes the payload and notifies the
/// consumer. Drop without fill still wakes the consumer and closes any
/// attached reservation.
pub(crate) struct BodySlot {
    handle: Option<SlotHandle<ChunkOutput>>,
    buffer: PagedRecvBuffer<ChunkOutput>,
    notify: Arc<WakeNotify>,
    /// Memory reservation held from claim through response collection. A
    /// successful fill closes acquisition authority; the immutable payload then
    /// owns every live carrier charge directly. `None` until
    /// [`BodySlot::attach_reservation`], and on paths that do not reserve
    /// (tests).
    reservation: Option<Reservation>,
}

impl std::fmt::Debug for BodySlot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BodySlot")
            .field("seq", &self.handle.as_ref().map(|h| h.seq()))
            .finish_non_exhaustive()
    }
}

impl BodySlot {
    /// The sequence number for this slot.
    pub(crate) fn seq(&self) -> u64 {
        self.handle.as_ref().expect("slot already consumed").seq()
    }

    /// Returns the reservation attached before this slot was dispatched.
    ///
    /// Response attempts borrow this authority while copying transport-owned
    /// frames into pooled carriers. A failed attempt drops its carriers but
    /// leaves the reservation on the slot for the next attempt.
    pub(crate) fn reservation(&self) -> &Reservation {
        self.reservation
            .as_ref()
            .expect("body slot dispatched without a memory reservation")
    }

    /// Attach the memory reservation backing this chunk. It remains open while
    /// response attempts may acquire carriers and closes on successful fill.
    pub(crate) fn attach_reservation(&mut self, reservation: Reservation) {
        self.reservation = Some(reservation);
    }

    /// Publish a completed chunk into this slot. Wakes the stream consumer
    /// and returns the fill outcome (whether a segment was sealed). Immutable
    /// owners retain all acquired carriers, so no direct acquisition authority
    /// is needed after this point.
    pub(crate) fn fill(mut self, chunk: ChunkOutput) -> FillOutcome {
        let handle = self.handle.take().expect("slot already consumed");
        if let Some(reservation) = self.reservation.take() {
            reservation.close_acquisition();
        }
        let outcome = self.buffer.fill(handle, chunk);
        self.notify.notify_one();
        outcome
    }
}

impl Drop for BodySlot {
    fn drop(&mut self) {
        // If the handle is still present the slot was never filled. Notify to
        // prevent the consumer from sleeping forever waiting on this sequence.
        if self.handle.is_some() {
            self.notify.notify_one();
        }
    }
}

impl BodyWriter {
    pub(crate) fn has_sink(&self) -> bool {
        matches!(&*self.mode, Mode::Disk { .. })
    }

    /// Bytes the destination sink has accepted across every drain, including
    /// drains that went on to fail. Stream mode: 0.
    ///
    /// Counts only runs the sink fully accepted, so it never exceeds what
    /// reached the sink.
    #[cfg(test)]
    pub(crate) fn written(&self) -> u64 {
        match &*self.mode {
            Mode::Disk { written, .. } => written.load(Ordering::Acquire),
            Mode::Stream => 0,
        }
    }

    /// Claim the next slot. The read-ahead gate lives in poll_work (tracks
    /// `issued` under the state lock) — this is the unconditional claim.
    pub(crate) fn claim(&self) -> BodySlot {
        let handle = self.buffer.claim();
        BodySlot {
            handle: Some(handle),
            buffer: self.buffer.clone(),
            notify: self.notify.clone(),
            reservation: None,
        }
    }

    /// Disk mode: drain every batch-ready run to disk. Called on the `DrainReady`
    /// edge from execute tasks. A non-terminal drain claims only runs that reach the
    /// drain batch, coalescing each into one positioned write. Stream mode: no-op.
    ///
    /// Returns the parts freed and the bytes written across the runs drained by
    /// this call. The download layer releases that read-ahead occupancy under
    /// its state lock.
    ///
    /// A run that fails to write ends the drain with a [`DrainError`] carrying
    /// the runs written before it. A filled payload before
    /// [`prepare`](Self::prepare) fails the drain with nothing drained.
    pub(crate) fn drain(&self, mode: DrainMode) -> Result<Drained, DrainError> {
        let mut drained = Drained::default();
        if let Mode::Disk {
            sink,
            object_range_start,
            written,
        } = &*self.mode
        {
            let Some(object_range_start) = object_range_start.get().copied() else {
                // Cancellation can terminate a disk transfer before discovery
                // establishes its range. A fill before preparation violates the
                // transfer ordering and cannot be positioned safely.
                if self.buffer.has_undrained_fills() {
                    return Err(DrainError {
                        drained: Drained::default(),
                        source: std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "disk payload arrived before destination preparation",
                        ),
                    });
                }
                return Ok(drained);
            };
            while let Some(sw) = self.buffer.take_drain_run(mode) {
                let bytes = match write_run(sink.as_ref(), object_range_start, &sw) {
                    Ok(bytes) => bytes,
                    Err(source) => return Err(DrainError { drained, source }),
                };
                written.fetch_add(bytes, Ordering::Release);
                drained.bytes = drained.bytes.saturating_add(bytes);
                drained.parts = drained.parts.saturating_add(sw.complete());
            }
        }
        Ok(drained)
    }

    /// Flush every remaining filled run at a terminal transition, including a partial
    /// final segment below the drain batch.
    ///
    /// Success, failure, and cancellation all use this operation to release resident
    /// payload ownership. It does not establish the target's successful final shape.
    /// Fails as [`drain`](Self::drain) does.
    pub(crate) fn terminal_drain(&self) -> Result<Drained, DrainError> {
        if !matches!(&*self.mode, Mode::Disk { .. }) {
            return Ok(Drained::default());
        }
        let drained = self.drain(DrainMode::Eager)?;
        tracing::debug!(
            target: crate::telemetry::TARGET_TRANSFER_DOWNLOAD,
            terminal_parts = drained.parts,
            terminal_bytes = drained.bytes,
            "terminal drain complete; tail flushed to disk",
        );
        Ok(drained)
    }

    /// Flush terminal payloads and establish the successful disk target length.
    ///
    /// Returns what the terminal drain wrote. A failed terminal drain returns its
    /// [`DrainError`]. Fails with
    /// [`UnexpectedEof`](std::io::ErrorKind::UnexpectedEof), before the target
    /// is resized, if the sink has not accepted exactly `expected_download_len`
    /// bytes across every drain. A run claimed by a drain that has not finished
    /// writing is invisible to the terminal drain, so without this check its
    /// region would be published holding zeros or the file's previous bytes.
    /// That error, and a failed resize, carry what the terminal drain wrote.
    pub(crate) fn finalize(&self, expected_download_len: u64) -> Result<Drained, DrainError> {
        let drained = self.terminal_drain()?;
        if let Mode::Disk { sink, written, .. } = &*self.mode {
            let written = written.load(Ordering::Acquire);
            if written != expected_download_len {
                return Err(DrainError {
                    drained,
                    source: std::io::Error::new(
                        std::io::ErrorKind::UnexpectedEof,
                        format!(
                            "destination accepted {written} of {expected_download_len} expected bytes"
                        ),
                    ),
                });
            }
            sink.finalize(expected_download_len)
                .map_err(|source| DrainError { drained, source })?;
        }
        Ok(drained)
    }

    /// Whether a forced eager drain would free at least one resident part right now:
    /// the disk surface holds a contiguous filled run at some segment's claim cursor.
    /// Stream mode returns false: its consumer drives release, so it never pins
    /// carrier charges behind the drain batch. This gates memory-pressure relief.
    pub(crate) fn has_drainable_resident(&self) -> bool {
        matches!(&*self.mode, Mode::Disk { .. }) && self.buffer.has_drainable_prefix()
    }

    /// Flush the resident filled prefix to disk now, below the drain batch.
    /// Memory-pressure relief is distinct from terminal `finalize`, but uses
    /// the same eager take. Returns the parts freed, so the caller releases their
    /// read-ahead occupancy, and the bytes written. Not terminal: the transfer
    /// keeps issuing after this. Fails as [`drain`](Self::drain) does.
    pub(crate) fn flush_resident(&self) -> Result<Drained, DrainError> {
        self.drain(DrainMode::Eager)
    }

    /// Couple the drain batch to the read-ahead window: a window narrower than a
    /// segment drains in smaller runs so the block surface never waits for a run it
    /// cannot accumulate. Capped at the segment size (the coalescing target). Called
    /// at construction and whenever the window changes.
    pub(crate) fn sync_drain_batch(&self, window: u64) {
        let batch = std::cmp::min(SEG_SIZE as u64, window.max(1)) as usize;
        self.buffer.set_drain_batch(batch);
    }

    /// Wake the consumer (terminal transition).
    pub(crate) fn notify_consumer(&self) {
        self.notify.notify_one();
    }

    /// Fix the resolved object-range origin and prepare a disk target.
    pub(crate) fn prepare(
        &self,
        object_range_start: u64,
        expected_download_len: u64,
    ) -> std::io::Result<()> {
        if let Mode::Disk {
            sink,
            object_range_start: configured_start,
            ..
        } = &*self.mode
        {
            assert!(
                configured_start.set(object_range_start).is_ok(),
                "disk destination prepared more than once"
            );
            sink.prepare(expected_download_len)?;
        }
        Ok(())
    }
}

/// Write one claimed, contiguous payload run at its translated file position,
/// returning the run's length in bytes.
///
/// The cursor borrows payloads in place. `complete()` (called by the caller
/// after this returns) frees their owners.
fn write_run(
    sink: &dyn SinkWrite,
    object_range_start: u64,
    sw: &SegmentWrite<ChunkOutput>,
) -> std::io::Result<u64> {
    let (object_offset, mut cursor) = DiskWriteCursor::new(sw)?;
    let len = cursor.remaining() as u64;
    let file_pos = object_offset
        .checked_sub(object_range_start)
        .ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "disk-write payload begins before the requested object range",
            )
        })?;
    sink.write_all_at(&mut cursor, file_pos)?;
    Ok(len)
}

/// Consumer wrapper carrying the notify handle alongside the buffer consumer.
/// Handed from constructors to `Body::new`.
pub(crate) struct RecvBodyConsumer {
    consumer: RecvBufferConsumer<ChunkOutput>,
    notify: Arc<WakeNotify>,
}

impl std::fmt::Debug for RecvBodyConsumer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RecvBodyConsumer").finish_non_exhaustive()
    }
}

impl RecvBodyConsumer {
    /// Try to take the next sequential chunk without waiting.
    #[cfg(test)]
    pub(crate) fn try_take_next(&mut self) -> Option<ChunkOutput> {
        self.consumer.poll_next()
    }
}

/// Create a matched producer/consumer pair for download body delivery (stream mode).
///
/// Issuance backpressure is owned by the per-transfer [`ReadAhead`] controller, not
/// by a fixed buffer capacity — the buffer grows as needed.
///
/// [`ReadAhead`]: super::read_ahead::ReadAhead
pub(crate) fn new_recv_body() -> (BodyWriter, RecvBodyConsumer) {
    let (buffer, consumer) = PagedRecvBuffer::new_with_segment_size(SEG_SIZE);
    let notify = Arc::new(WakeNotify::new());
    let writer = BodyWriter {
        buffer,
        notify: notify.clone(),
        mode: Arc::new(Mode::Stream),
    };
    let slot_consumer = RecvBodyConsumer { consumer, notify };
    (writer, slot_consumer)
}

/// Create a producer/consumer pair writing to an arbitrary [`SinkWrite`] target.
/// Positioned writes land at `chunk.offset - object_range_start` in the sink.
///
/// Issuance backpressure is owned by the per-transfer [`ReadAhead`] controller.
///
/// [`ReadAhead`]: super::read_ahead::ReadAhead
pub(crate) fn new_recv_body_with_disk_mode(
    sink: Box<dyn SinkWrite>,
) -> (BodyWriter, RecvBodyConsumer) {
    let (buffer, consumer) = PagedRecvBuffer::new_with_segment_size(SEG_SIZE);
    let notify = Arc::new(WakeNotify::new());
    let resolved_range_start = std::sync::OnceLock::new();
    let writer = BodyWriter {
        buffer,
        notify: notify.clone(),
        mode: Arc::new(Mode::Disk {
            sink,
            object_range_start: resolved_range_start,
            written: AtomicU64::new(0),
        }),
    };
    let slot_consumer = RecvBodyConsumer { consumer, notify };
    (writer, slot_consumer)
}

/// Create a producer/consumer pair writing directly to `file` through a
/// [`FileSink`](super::sink::FileSink).
#[cfg(test)]
pub(crate) fn new_recv_body_with_sink(
    file: std::fs::File,
    owns_file: bool,
) -> (BodyWriter, RecvBodyConsumer) {
    new_recv_body_with_disk_mode(Box::new(super::sink::FileSink::new(file, owns_file)))
}

/// Stream of [ChunkOutput] representing an Amazon S3 Object's contents and metadata.
///
/// Wraps potentially multiple streams of binary data into a single coherent stream.
/// The data on this stream is sequenced into the correct order.
pub struct Body {
    consumer: RecvBufferConsumer<ChunkOutput>,
    notify: Arc<WakeNotify>,
    transfer: DownloadTransfer,
}

impl std::fmt::Debug for Body {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Body").finish_non_exhaustive()
    }
}

/// Contains body and metadata for each GetObject call made. This will be delivered sequentially
/// in-order.
#[derive(Clone)]
#[non_exhaustive]
pub struct ChunkOutput {
    // TODO(aws-sdk-rust#1159, design) - consider PartialOrd for ChunkResponse and hiding `seq` as internal only detail
    // the seq number
    pub(crate) seq: u64,
    /// Byte offset in the object where this chunk starts.
    pub(crate) offset: u64,
    /// The content associated with this ranged `GetObject` request.
    pub data: SegmentedBytes,
    /// The metadata associated with this particular ranged GetObject request. This contains all the
    /// metadata returned by the S3 GetObject operation.
    pub metadata: ChunkMetadata,
}

impl std::fmt::Debug for ChunkOutput {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ChunkOutput")
            .field("seq", &self.seq)
            .field("offset", &self.offset)
            .field("data_len", &self.data.remaining())
            .field("metadata", &self.metadata)
            .finish()
    }
}

impl Body {
    pub(crate) fn new(consumer: RecvBodyConsumer, transfer: DownloadTransfer) -> Self {
        Self {
            consumer: consumer.consumer,
            notify: consumer.notify,
            transfer,
        }
    }

    /// Close the body, signaling no more chunks will be consumed.
    pub(crate) fn close(&mut self) {
        // No-op: dropping the consumer is sufficient for cleanup.
    }

    /// Pull the next chunk of data off the stream.
    ///
    /// Returns [None] when there is no more data.
    /// Chunks returned from a [Body] are guaranteed to be sequenced
    /// in the right order.
    ///
    /// On failure, returns `Some(Err(...))` with the error kind from the actual failure.
    /// Call `join()` on the handle to get the full error with source chain.
    pub async fn next(&mut self) -> Option<Result<ChunkOutput, crate::error::Error>> {
        loop {
            // Register interest BEFORE checking state (lost-wake safety).
            let notified = self.notify.notified();
            if let Some(chunk) = self.consumer.poll_next() {
                // Delivery freed one part's payload. Release that read-ahead occupancy
                // and wake the issuer under the state lock, so the release is ordered
                // against the gate's park (see `release_stream_occupancy`).
                self.transfer.release_stream_occupancy();
                return Some(Ok(chunk));
            }
            if !self.transfer.ctx().is_active() {
                // Terminal: drain then report.
                if let Some(chunk) = self.consumer.poll_next() {
                    self.transfer.release_stream_occupancy();
                    return Some(Ok(chunk));
                }
                return self.terminal_result();
            }
            notified.await;
        }
    }

    fn terminal_result(&self) -> Option<Result<ChunkOutput, crate::error::Error>> {
        if self.transfer.ctx().is_cancelled() {
            Some(Err(crate::error::from_kind(
                crate::error::ErrorKind::OperationCancelled,
            )("download cancelled")))
        } else if self.transfer.ctx().is_failed() {
            let kind = self
                .transfer
                .ctx()
                .error_kind()
                .unwrap_or(crate::error::ErrorKind::ChildOperationFailed);
            Some(Err(crate::error::from_kind(kind)("transfer failed")))
        } else {
            None // normal completion
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::memory::SegmentedBytes;
    use crate::operation::download::transfer::DownloadTransfer;
    use crate::types::ByteSize;
    use crate::{error, operation::download::body::ChunkOutput};
    use bytes::{BufMut, Bytes};
    use std::sync::Arc;

    use super::{new_recv_body, Body, BodyWriter};

    fn chunk_resp(seq: u64, data: SegmentedBytes) -> ChunkOutput {
        ChunkOutput {
            seq,
            offset: 0,
            data,
            metadata: Default::default(),
        }
    }

    fn test_body() -> (Body, DownloadTransfer, BodyWriter) {
        use crate::operation::download::DownloadInput;
        use crate::transfer::TransferContext;
        use crate::types::BucketType;

        let s3_client = aws_sdk_s3::Client::from_conf(
            aws_sdk_s3::Config::builder()
                .with_test_defaults()
                .region(aws_sdk_s3::config::Region::new("us-west-2"))
                .build(),
        );
        let config = crate::Config::builder()
            .sdk_client(s3_client)
            .build()
            .expect("valid config");
        let tm = crate::Client::new(config);
        let input = DownloadInput::builder()
            .bucket("test")
            .key("test")
            .build()
            .unwrap();
        let (ctx, _) = TransferContext::new(tm.handle.clone());
        let (writer, consumer) = new_recv_body();
        let transfer = DownloadTransfer::new(ctx, BucketType::Standard, input, writer.clone());
        (Body::new(consumer, transfer.clone()), transfer, writer)
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_body_next() {
        let (mut body, transfer, writer) = test_body();
        let ctx_clone = transfer.clone();
        tokio::spawn(async move {
            // Claim 3 seqs, fill out of order
            let s0 = writer.claim();
            let s1 = writer.claim();
            let s2 = writer.claim();

            // Fill out of order: 2, 0, 1
            let seq2 = s2.seq();
            s2.fill(chunk_resp(
                seq2,
                SegmentedBytes::from(Bytes::from("chunk 2")),
            ));

            let seq0 = s0.seq();
            s0.fill(chunk_resp(
                seq0,
                SegmentedBytes::from(Bytes::from("chunk 0")),
            ));

            let seq1 = s1.seq();
            s1.fill(chunk_resp(
                seq1,
                SegmentedBytes::from(Bytes::from("chunk 1")),
            ));

            ctx_clone.ctx().set_completed();
        });

        let mut received = Vec::new();
        while let Some(chunk) = body.next().await {
            let chunk = chunk.expect("chunk ok");
            let data = String::from_utf8(chunk.data.into_contiguous().to_vec()).unwrap();
            received.push(data);
        }

        // Delivered in order despite out-of-order fill
        let expected: Vec<String> = [0, 1, 2].iter().map(|i| format!("chunk {i}")).collect();
        assert_eq!(expected, received);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_body_next_on_failed_transfer() {
        let (mut body, transfer, writer) = test_body();

        // Fill one chunk
        let s0 = writer.claim();
        let seq0 = s0.seq();
        s0.fill(chunk_resp(
            seq0,
            SegmentedBytes::from(Bytes::from("chunk 0")),
        ));

        // Fail the transfer
        transfer.ctx().set_failed(error::Error::new(
            error::ErrorKind::ChildOperationFailed,
            "simulated failure",
        ));

        // First call returns the buffered chunk
        let chunk = body.next().await.unwrap().unwrap();
        assert_eq!(chunk.seq, 0);

        // Second call sees failed status, returns error
        let err = body.next().await.unwrap().unwrap_err();
        assert!(matches!(err.kind(), error::ErrorKind::ChildOperationFailed));
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_body_next_on_cancelled_transfer() {
        let (mut body, transfer, _writer) = test_body();

        // Cancel the transfer
        transfer.ctx().set_cancelled();

        // next() should return cancellation error
        let err = body.next().await.unwrap().unwrap_err();
        assert!(matches!(err.kind(), error::ErrorKind::OperationCancelled));
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn test_body_next_unblocks_on_cancel() {
        let (mut body, transfer, _writer) = test_body();

        // Sync point: consumer signals it's about to wait
        let waiting = Arc::new(tokio::sync::Notify::new());
        let waiting_clone = waiting.clone();

        let cancel_transfer = transfer.clone();
        let consumer = tokio::spawn(async move {
            // Signal we're about to enter next() (which will park on notified)
            waiting_clone.notify_one();
            body.next().await
        });

        // Wait until consumer is about to park
        waiting.notified().await;
        // Yield to let consumer actually reach notified().await
        tokio::task::yield_now().await;

        // Now cancel and wake
        cancel_transfer.ctx().set_cancelled();
        cancel_transfer.writer().notify_consumer();

        let result = consumer.await.unwrap();
        let err = result.unwrap().unwrap_err();
        assert!(matches!(err.kind(), error::ErrorKind::OperationCancelled));
    }

    // --- Disk driver tests ---

    use super::{
        new_recv_body_with_disk_mode, new_recv_body_with_sink, BodyWriter as Writer,
        DiskWriteCursor, DrainMode, Drained, RecvBodyConsumer, Reservation,
    };
    use crate::operation::download::sink::{SinkFactory, SinkWrite};
    use crate::operation::download::test_util::sink::{
        Action, Match, Op, ScriptedSinkFactory, WriteScript,
    };
    use bytes::Buf as _;
    use std::collections::BTreeMap;
    use std::sync::Mutex as StdMutex;

    fn chunk_at(seq: u64, offset: u64, data: &[u8]) -> ChunkOutput {
        ChunkOutput {
            seq,
            offset,
            data: SegmentedBytes::from(Bytes::copy_from_slice(data)),
            metadata: Default::default(),
        }
    }

    #[test]
    fn disk_write_cursor_vectors_and_advances_across_chunk_boundaries() {
        let (writer, _consumer, _sink) = new_recv_body_with_capture(0);
        writer.claim().fill(chunk_at(0, 0, b"ab"));
        writer.claim().fill(chunk_at(1, 2, b"cdef"));
        let write = writer
            .buffer
            .take_drain_run(DrainMode::Eager)
            .expect("two filled payloads");
        {
            let (object_offset, mut cursor) = DiskWriteCursor::new(&write).unwrap();

            let mut slices = [std::io::IoSlice::new(&[]); 4];
            let count = cursor.chunks_vectored(&mut slices);
            assert_eq!(object_offset, 0);
            assert_eq!(count, 2);
            assert_eq!(slices[0].as_ref(), b"ab");
            assert_eq!(slices[1].as_ref(), b"cdef");

            cursor.advance(3);
            assert_eq!(cursor.remaining(), 3);
            assert_eq!(cursor.chunk(), b"def");
        }
        assert_eq!(write.complete(), 2);
    }

    /// In-memory [`SinkWrite`] that records every positioned write, for asserting the
    /// drain orchestration (offset translation, run coalescing, ordering under
    /// concurrency) without a real file. Reconstructs the destination by laying each
    /// write down at its position, so overlapping or misordered writes surface as
    /// wrong bytes.
    #[derive(Debug, Default)]
    struct CaptureSink {
        // pos -> bytes written there (most recent wins, as a real file would).
        writes: StdMutex<BTreeMap<u64, Vec<u8>>>,
    }

    impl CaptureSink {
        /// Materialize the written bytes into a contiguous buffer, panicking on a gap
        /// (an unwritten position below the high-water mark) so a missed write is loud.
        fn assembled(&self) -> Vec<u8> {
            let writes = self.writes.lock().unwrap();
            let mut out = Vec::new();
            for (&pos, bytes) in writes.iter() {
                assert_eq!(pos as usize, out.len(), "gap or overlap at pos {pos}");
                out.extend_from_slice(bytes);
            }
            out
        }

        fn write_count(&self) -> usize {
            self.writes.lock().unwrap().len()
        }
    }

    impl SinkWrite for CaptureSink {
        fn write_all_at(&self, buf: &mut DiskWriteCursor<'_>, pos: u64) -> std::io::Result<()> {
            let mut bytes = vec![0u8; buf.remaining()];
            buf.copy_to_slice(&mut bytes);
            self.writes.lock().unwrap().insert(pos, bytes);
            Ok(())
        }
    }

    fn new_recv_body_with_capture(
        object_range_start: u64,
    ) -> (Writer, RecvBodyConsumer, Arc<CaptureSink>) {
        let sink = Arc::new(CaptureSink::default());
        // The Mode holds a Box<dyn SinkWrite>; share state via an Arc the test also
        // holds. A thin forwarder lets the Box and the test handle point at one sink.
        #[derive(Debug)]
        struct Shared(Arc<CaptureSink>);
        impl SinkWrite for Shared {
            fn write_all_at(&self, buf: &mut DiskWriteCursor<'_>, pos: u64) -> std::io::Result<()> {
                self.0.write_all_at(buf, pos)
            }
        }
        let (writer, consumer) = new_recv_body_with_disk_mode(Box::new(Shared(sink.clone())));
        writer.prepare(object_range_start, 0).unwrap();
        (writer, consumer, sink)
    }

    fn new_test_recv_body_with_sink(
        file: std::fs::File,
        object_range_start: u64,
    ) -> (Writer, RecvBodyConsumer) {
        let (writer, consumer) = new_recv_body_with_sink(file, false);
        writer.prepare(object_range_start, 0).unwrap();
        (writer, consumer)
    }

    /// Cancellation can terminally drain a disk transfer before discovery has
    /// resolved its object range. No payload exists at that point.
    #[test]
    fn disk_terminal_drain_before_prepare_is_empty() {
        let file = tempfile::tempfile().unwrap();
        let (writer, _consumer) = new_recv_body_with_sink(file, false);

        assert_eq!(writer.terminal_drain().unwrap(), Drained::default());
    }

    /// A filled payload before destination preparation has no safe file
    /// position and must not be discarded as an empty cancellation.
    #[test]
    fn disk_terminal_drain_before_prepare_rejects_payload() {
        let file = tempfile::tempfile().unwrap();
        let (writer, _consumer) = new_recv_body_with_sink(file, false);
        writer.claim().fill(chunk_at(0, 0, b"payload"));

        let error = writer
            .terminal_drain()
            .expect_err("unpositioned payload must fail");
        assert_eq!(error.source.kind(), std::io::ErrorKind::InvalidData);
        assert_eq!(error.drained, Drained::default());
    }

    /// `has_drainable_resident` gates memory-pressure draining. It is true only on the
    /// disk surface with a filled run at the cursor: stream mode returns false (the
    /// consumer drives release there, so an eager drain would be a no-op that spins),
    /// and a resident run only exists once a slot at the cursor is filled.
    #[test]
    fn has_drainable_resident_only_on_disk_with_a_filled_run() {
        // Stream mode: even with a filled slot, never drainable-resident.
        let (stream_writer, _consumer) = new_recv_body();
        stream_writer.claim().fill(chunk_at(0, 0, b"streamed"));
        assert!(
            !stream_writer.has_drainable_resident(),
            "stream mode has no drainable-resident run (consumer drives release)"
        );

        // Disk mode: empty → false; filled at the cursor → true.
        let (disk_writer, _consumer, _sink) = new_recv_body_with_capture(0);
        assert!(
            !disk_writer.has_drainable_resident(),
            "disk mode with nothing filled is not drainable-resident"
        );
        disk_writer.claim().fill(chunk_at(0, 0, b"resident"));
        assert!(
            disk_writer.has_drainable_resident(),
            "disk mode with a filled run at the cursor is drainable-resident"
        );
    }

    #[test]
    fn disk_submits_one_contiguous_run_as_one_positioned_write() {
        let (writer, _consumer, sink) = new_recv_body_with_capture(100);
        writer.claim().fill(chunk_at(0, 100, b"ab"));
        writer.claim().fill(chunk_at(1, 102, b"cdef"));

        assert_eq!(
            writer.terminal_drain().unwrap(),
            Drained { parts: 2, bytes: 6 }
        );
        assert_eq!(sink.write_count(), 1);
        assert_eq!(sink.assembled(), b"abcdef");
    }

    #[test]
    fn disk_rejects_gaps_and_overlaps_within_a_claimed_run() {
        for second_offset in [1, 3] {
            let (writer, _consumer, sink) = new_recv_body_with_capture(0);
            writer.claim().fill(chunk_at(0, 0, b"ab"));
            writer.claim().fill(chunk_at(1, second_offset, b"cd"));

            let error = writer
                .terminal_drain()
                .expect_err("offsets are not contiguous");
            assert_eq!(error.source.kind(), std::io::ErrorKind::InvalidData);
            assert_eq!(sink.write_count(), 0);
        }
    }

    #[test]
    fn disk_rejects_an_empty_claimed_payload() {
        let (writer, _consumer, sink) = new_recv_body_with_capture(0);
        writer.claim().fill(chunk_at(0, 0, b""));

        let error = writer.terminal_drain().expect_err("disk payload is empty");
        assert_eq!(error.source.kind(), std::io::ErrorKind::InvalidData);
        assert_eq!(sink.write_count(), 0);
    }

    #[test]
    fn disk_writes_full_segment() {
        use super::SEG_SIZE;
        const CHUNK_LEN: usize = 4;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        let file = std::fs::File::create(&path).unwrap();
        let (writer, _consumer) = new_test_recv_body_with_sink(file, 0);

        let mut expected = Vec::with_capacity(SEG_SIZE * CHUNK_LEN);
        for i in 0..SEG_SIZE as u64 {
            let slot = writer.claim();
            let data = [i as u8; CHUNK_LEN];
            let offset = i * CHUNK_LEN as u64;
            expected.extend_from_slice(&data);
            slot.fill(chunk_at(i, offset, &data));
        }

        writer.drain(DrainMode::Batched).unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), expected);
    }

    #[test]
    fn disk_eof_partial_tail() {
        use super::SEG_SIZE;
        const CHUNK_LEN: usize = 2;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        let file = std::fs::File::create(&path).unwrap();
        let (writer, _consumer) = new_test_recv_body_with_sink(file, 0);

        let partial = SEG_SIZE / 2;
        let mut expected = Vec::with_capacity(partial * CHUNK_LEN);
        for i in 0..partial as u64 {
            let slot = writer.claim();
            let data = [i as u8; CHUNK_LEN];
            let offset = i * CHUNK_LEN as u64;
            expected.extend_from_slice(&data);
            slot.fill(chunk_at(i, offset, &data));
        }

        writer.finalize(expected.len() as u64).unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), expected);
    }

    #[test]
    fn disk_finalize_removes_an_existing_file_tail() {
        const ORIGINAL: &[u8] = b"old contents with a stale tail";
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        std::fs::write(&path, ORIGINAL).unwrap();
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&path)
            .unwrap();
        let (writer, _consumer) = new_recv_body_with_sink(file, false);
        writer.prepare(0, 3).unwrap();
        assert_eq!(
            std::fs::metadata(&path).unwrap().len(),
            ORIGINAL.len() as u64,
            "preparing a caller-owned file must not resize it"
        );

        writer.claim().fill(chunk_at(0, 0, b"new"));
        writer.terminal_drain().unwrap();
        assert_eq!(
            std::fs::metadata(&path).unwrap().len(),
            ORIGINAL.len() as u64,
            "terminal cleanup must not establish the successful length"
        );

        writer.finalize(3).unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), b"new");
    }

    /// A disk body writer over the existing file at `path`, opened for reading
    /// and writing, whose destination operations go through `script`.
    fn scripted_writer_over(
        path: &std::path::Path,
        script: &Arc<WriteScript>,
    ) -> (Writer, RecvBodyConsumer) {
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .unwrap();
        new_recv_body_with_disk_mode(
            ScriptedSinkFactory(Arc::clone(script))
                .create(file, false)
                .unwrap(),
        )
    }

    /// A drain that fails part-way returns the runs it wrote before the failing
    /// one. An eager drain takes the head run of each of three receive-buffer
    /// segments, and the destination rejects the third.
    #[test]
    fn failed_drain_returns_the_runs_written_before_it() {
        use super::SEG_SIZE;
        const RUN_LEN: u64 = 4;
        let script = Arc::new(WriteScript::default()).on(
            Match::NthWrite(3),
            Action::Fail(std::io::ErrorKind::StorageFull),
        );
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        std::fs::File::create(&path).unwrap();
        let (writer, _consumer) = scripted_writer_over(&path, &script);
        writer.prepare(0, 3 * RUN_LEN).unwrap();

        // Fill only the first slot of each segment, so the drain takes three
        // separate runs, in order.
        let seg = SEG_SIZE as u64;
        for seq in 0..=2 * seg {
            let slot = writer.claim();
            if seq % seg == 0 {
                let run = seq / seg;
                slot.fill(chunk_at(
                    seq,
                    run * RUN_LEN,
                    &[run as u8 + 1; RUN_LEN as usize],
                ));
            }
        }

        let error = writer
            .drain(DrainMode::Eager)
            .expect_err("the third write is scripted to fail");
        assert_eq!(error.source.kind(), std::io::ErrorKind::StorageFull);
        assert_eq!(error.drained, Drained { parts: 2, bytes: 8 });
        assert_eq!(writer.written(), 8);
    }

    /// A resize that fails after every byte was written fails finalization
    /// with the resize's error and leaves the destination's length in place.
    #[test]
    fn disk_finalize_propagates_resize_failure() {
        let script = Arc::new(WriteScript::default()).on(
            Match::Finalize,
            Action::Fail(std::io::ErrorKind::PermissionDenied),
        );
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        std::fs::write(&path, b"existing").unwrap();
        let (writer, _consumer) = scripted_writer_over(&path, &script);
        writer.prepare(0, 3).unwrap();
        writer.claim().fill(chunk_at(0, 0, b"new"));
        writer.drain(DrainMode::Eager).unwrap();
        assert_eq!(writer.written(), 3, "the whole object was written");

        let error = writer
            .finalize(3)
            .expect_err("the resize is scripted to fail");
        assert_eq!(error.source.kind(), std::io::ErrorKind::PermissionDenied);
        let contents = std::fs::read(&path).unwrap();
        assert_eq!(contents.len(), 8, "a failed resize keeps the length");
        assert_eq!(&contents[..3], b"new");
    }

    /// A run claimed by a drain that has not finished writing it leaves the
    /// destination short. Finalization must fail before the resize that would
    /// publish the hole, leaving the caller's previous bytes and length in
    /// place.
    #[test]
    fn disk_finalize_rejects_a_short_destination_without_resizing() {
        const ORIGINAL: &[u8] = b"previous contents";
        const HOLD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
        let script = Arc::new(WriteScript::default()).on(Match::NthWrite(1), Action::Hold);
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        std::fs::write(&path, ORIGINAL).unwrap();
        let (writer, _consumer) = scripted_writer_over(&path, &script);
        writer.prepare(0, 4).unwrap();
        writer.claim().fill(chunk_at(0, 0, b"ab"));

        std::thread::scope(|scope| {
            let drain = scope.spawn(|| writer.drain(DrainMode::Eager));
            let held = script.wait_held(HOLD_TIMEOUT);
            assert_eq!(held.op(), Op::Write { pos: 0, len: 2 });

            writer.claim().fill(chunk_at(1, 2, b"cd"));
            let error = writer
                .finalize(4)
                .expect_err("two of four bytes reached the destination");
            assert_eq!(error.source.kind(), std::io::ErrorKind::UnexpectedEof);
            assert!(
                error.source.to_string().contains("2 of 4"),
                "the error names both byte counts: {}",
                error.source
            );
            let contents = std::fs::read(&path).unwrap();
            assert_eq!(
                contents.len(),
                ORIGINAL.len(),
                "a short destination must not be resized"
            );
            assert_eq!(&contents[..4], b"prcd");

            held.release();
            drain.join().unwrap().unwrap();
        });
    }

    #[test]
    fn disk_finalize_truncates_an_empty_download() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        std::fs::write(&path, b"existing").unwrap();
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&path)
            .unwrap();
        let (writer, _consumer) = new_recv_body_with_sink(file, false);
        writer.prepare(0, 0).unwrap();
        assert_eq!(std::fs::metadata(&path).unwrap().len(), 8);

        writer.finalize(0).unwrap();
        assert!(std::fs::read(&path).unwrap().is_empty());
    }

    #[test]
    fn disk_finalize_drains_full_and_tail() {
        use super::SEG_SIZE;
        const CHUNK_LEN: usize = 2;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        let file = std::fs::File::create(&path).unwrap();
        let (writer, _consumer) = new_test_recv_body_with_sink(file, 0);

        let total = SEG_SIZE + 2;
        let mut expected = Vec::with_capacity(total * CHUNK_LEN);
        for i in 0..total as u64 {
            let slot = writer.claim();
            let data = [i as u8; CHUNK_LEN];
            let offset = i * CHUNK_LEN as u64;
            expected.extend_from_slice(&data);
            slot.fill(chunk_at(i, offset, &data));
        }

        writer.finalize(expected.len() as u64).unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), expected);
    }

    #[test]
    fn disk_offset_translation() {
        use super::SEG_SIZE;
        const CHUNK_LEN: usize = 2;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        let file = std::fs::File::create(&path).unwrap();
        let (writer, _consumer) = new_test_recv_body_with_sink(file, 1000);

        let n = SEG_SIZE;
        let mut expected = Vec::with_capacity(n * CHUNK_LEN);
        for i in 0..n as u64 {
            let slot = writer.claim();
            let data = [i as u8; CHUNK_LEN];
            let offset = 1000 + i * CHUNK_LEN as u64;
            expected.extend_from_slice(&data);
            slot.fill(chunk_at(i, offset, &data));
        }

        writer.drain(DrainMode::Batched).unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), expected);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn disk_concurrent_fill() {
        use super::SEG_SIZE;
        const CHUNK_LEN: usize = 4;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        let file = std::fs::File::create(&path).unwrap();
        let (writer, _consumer) = new_test_recv_body_with_sink(file, 0);

        let n = SEG_SIZE;
        let mut handles = Vec::new();
        for _ in 0..n {
            let slot = writer.claim();
            handles.push(tokio::spawn(async move {
                tokio::task::yield_now().await;
                let seq = slot.seq();
                let offset = seq * CHUNK_LEN as u64;
                let data = [seq as u8; CHUNK_LEN];
                slot.fill(chunk_at(seq, offset, &data));
            }));
        }

        for h in handles {
            h.await.unwrap();
        }

        writer.finalize((n * CHUNK_LEN) as u64).unwrap();

        let contents = std::fs::read(&path).unwrap();
        for seq in 0..n as u64 {
            let offset = seq as usize * CHUNK_LEN;
            assert_eq!(
                &contents[offset..offset + CHUNK_LEN],
                &[seq as u8; CHUNK_LEN],
                "mismatch at seq {seq}"
            );
        }
    }

    /// Draining runs on the disk path must report freed parts to release read-ahead
    /// occupancy.
    ///
    /// The issuance gate bounds `issued - released`, where `released` is the sum of the
    /// freed counts `drain` reports. On the disk path the consumer is `drain`, which
    /// writes and frees runs. If draining does not report freed parts, a download larger
    /// than the read-ahead window wedges: the gate latches shut at the window and never
    /// reopens even though the buffer has drained to empty. This drives that path
    /// directly — no network, no large object — and asserts every part is reported freed.
    #[test]
    fn disk_drain_releases_read_ahead_occupancy() {
        use super::SEG_SIZE;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        let file = std::fs::File::create(&path).unwrap();
        let (writer, _consumer) = new_test_recv_body_with_sink(file, 0);

        // Fill two full segments, draining on the DrainReady edge after each fill — the
        // disk path's steady-state loop. Bounded iteration, so a regression fails fast.
        let total = (2 * SEG_SIZE) as u64;
        let mut freed_total = 0u64;
        for i in 0..total {
            let slot = writer.claim();
            let outcome = slot.fill(chunk_at(i, i, &[i as u8]));
            // Drain on the batch edge, as execute_get_range does.
            if outcome == super::FillOutcome::DrainReady {
                freed_total += writer.drain(DrainMode::Batched).unwrap().parts;
            }
        }
        // A terminal drain flushes any sub-batch tail so the total accounts for every part.
        freed_total += writer.terminal_drain().unwrap().parts;

        // Resident occupancy is `issued - released` = total - freed_total. Every part has
        // been written to disk and its memory freed, so it must be 0 — otherwise the gate
        // would still count drained parts against the window.
        let occupancy = total - freed_total;
        assert_eq!(
            occupancy, 0,
            "all {total} parts drained to disk, but the drains reported only \
             {freed_total} freed; issuance cannot reopen past the window"
        );
    }

    /// Concurrent, out-of-order fills across several segments must drain to the correct
    /// positions: many parts are claimed in order, then filled and drained from many
    /// threads in a shuffled order, each thread mirroring the execute path (fill, then
    /// drain on the `DrainReady` edge). A non-zero `object_range_start` also exercises
    /// offset translation. The capture sink reconstructs the object; any misordered or
    /// misplaced positioned write surfaces as wrong bytes or a gap.
    ///
    /// This is the property the disk path depends on but that an in-order producer
    /// never exercises: parts arrive and drain out of order, yet positioned writes (no
    /// recomputed checksum) must still reassemble the object byte-for-byte.
    #[test]
    fn disk_concurrent_out_of_order_drain_reassembles() {
        use super::SEG_SIZE;

        // Several segments' worth, with a partial final segment, so the run includes
        // full-segment drains, cross-segment coalescing, and a terminal partial tail.
        let parts = 3 * SEG_SIZE + 5;
        let part_len = 64usize;
        let range_start = 4096u64; // non-zero base: exercises offset translation

        // Deterministic per-part bytes, so the assembled object is checkable.
        let part_bytes = |seq: usize| -> Vec<u8> {
            (0..part_len)
                .map(|b| (seq as u8).wrapping_add(b as u8))
                .collect()
        };
        let mut expected = Vec::with_capacity(parts * part_len);
        for seq in 0..parts {
            expected.extend_from_slice(&part_bytes(seq));
        }

        let (writer, _consumer, sink) = new_recv_body_with_capture(range_start);

        // Claim all slots up front (claim is serialized; seq assignment is in order).
        let slots: Vec<_> = (0..parts).map(|_| writer.claim()).collect();

        // A fixed shuffle of fill order (deterministic — no rng): odd indices first,
        // then even, so later segments seal before earlier ones complete.
        let mut order: Vec<usize> = (0..parts).filter(|i| i % 2 == 1).collect();
        order.extend((0..parts).filter(|i| i % 2 == 0));

        // Map seq -> slot, consumed as each thread fills.
        let mut by_seq: std::collections::HashMap<usize, super::BodySlot> =
            slots.into_iter().map(|s| (s.seq() as usize, s)).collect();

        let writer = Arc::new(writer);
        // Sum every drain's freed count across threads, the way the download layer
        // accumulates `released` under its state lock.
        let freed_total = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let n_threads = 4;
        let chunks: Vec<Vec<usize>> = (0..n_threads)
            .map(|t| order.iter().copied().skip(t).step_by(n_threads).collect())
            .collect();

        std::thread::scope(|scope| {
            for thread_seqs in &chunks {
                // Move this thread's slots in.
                let mut my_slots = Vec::new();
                for &seq in thread_seqs {
                    my_slots.push((seq, by_seq.remove(&seq).expect("slot for seq")));
                }
                let writer = writer.clone();
                let freed_total = freed_total.clone();
                scope.spawn(move || {
                    for (seq, slot) in my_slots {
                        let offset = range_start + (seq as u64) * (part_len as u64);
                        let outcome = slot.fill(chunk_at(seq as u64, offset, &part_bytes(seq)));
                        // Mirror execute_get_range: drain on the batch edge.
                        if outcome == super::FillOutcome::DrainReady {
                            let freed = writer.drain(DrainMode::Batched).unwrap().parts;
                            freed_total.fetch_add(freed, std::sync::atomic::Ordering::Relaxed);
                        }
                    }
                });
            }
        });
        assert!(by_seq.is_empty(), "every slot dispatched to a thread");

        // Terminal drain flushes the partial final segment and any straggler runs.
        freed_total.fetch_add(
            writer.terminal_drain().unwrap().parts,
            std::sync::atomic::Ordering::Relaxed,
        );

        // Every part written and freed.
        assert_eq!(
            freed_total.load(std::sync::atomic::Ordering::Relaxed),
            parts as u64,
            "all parts drained"
        );
        // The positioned writes reassemble the object exactly.
        assert_eq!(
            sink.assembled(),
            expected,
            "out-of-order concurrent drain must reassemble the object byte-for-byte"
        );
    }

    // --- Admission and payload ownership tests ---
    //
    // Fill closes acquisition authority. The resulting charge follows immutable
    // ownership: to final consumer drop on the stream surface, or through the
    // positioned write on the disk surface.

    use crate::config::MemoryBudgetConfig;
    use crate::memory::BufferPool;

    fn test_reservation_pool() -> (BufferPool, usize) {
        let pool = BufferPool::from_capacity(
            MemoryBudgetConfig::Limit(ByteSize::new(1024 * 1024)),
            None,
            crate::config::MemoryDiagnosticsConfig::default(),
        )
        .expect("test pool");
        let carrier_size = pool.carrier_size();
        (pool, carrier_size)
    }

    fn pooled_data(pool: &BufferPool, reservation: &Reservation, data: &[u8]) -> SegmentedBytes {
        let mut buffer = pool
            .acquire(reservation, data.len())
            .expect("reserved pooled buffer");
        buffer.put_slice(data);
        buffer.freeze()
    }

    #[test]
    fn test_stream_fill_closes_reservation_while_payload_retains_charge() {
        let (pool, chunk_bytes) = test_reservation_pool();
        let (writer, mut consumer) = new_recv_body();

        let reservation = pool
            .try_reserve(chunk_bytes)
            .unwrap()
            .expect("has capacity");
        let data = pooled_data(&pool, &reservation, b"hello");
        let mut slot = writer.claim();
        slot.attach_reservation(reservation);
        assert_eq!(
            pool.metrics().active_planned_demand_bytes(),
            chunk_bytes as u64
        );
        slot.fill(chunk_resp(0, data));

        let metrics = pool.metrics();
        assert_eq!(metrics.active_planned_demand_bytes(), 0);
        assert_eq!(metrics.in_use_bytes(), chunk_bytes as u64);
        assert_eq!(metrics.admitted_bytes(), chunk_bytes as u64);

        let chunk = consumer.try_take_next().expect("chunk delivered");
        assert_eq!(chunk.data.clone().into_contiguous().as_ref(), b"hello");
        assert_eq!(pool.metrics().in_use_bytes(), chunk_bytes as u64);

        drop(chunk);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
        assert_eq!(pool.metrics().admitted_bytes(), 0);
    }

    #[test]
    fn test_stream_charge_holds_until_last_chunk_clone_drops() {
        let (pool, chunk_bytes) = test_reservation_pool();
        let (writer, mut consumer) = new_recv_body();

        let reservation = pool
            .try_reserve(chunk_bytes)
            .unwrap()
            .expect("has capacity");
        let data = pooled_data(&pool, &reservation, b"shared");
        let mut slot = writer.claim();
        slot.attach_reservation(reservation);
        slot.fill(chunk_resp(0, data));

        let chunk = consumer.try_take_next().expect("chunk delivered");
        let clone = chunk.clone();
        assert_eq!(pool.metrics().active_planned_demand_bytes(), 0);
        assert_eq!(
            pool.metrics().in_use_bytes(),
            chunk_bytes as u64,
            "one physical buffer, charged once"
        );

        drop(chunk);
        assert_eq!(
            pool.metrics().in_use_bytes(),
            chunk_bytes as u64,
            "a surviving clone still holds the resident bytes"
        );

        drop(clone);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
        assert_eq!(pool.metrics().admitted_bytes(), 0);
    }

    #[test]
    fn test_disk_payload_charge_returns_on_drain() {
        let (pool, chunk_bytes) = test_reservation_pool();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("out");
        let file = std::fs::File::create(&path).unwrap();
        let (writer, _consumer) = new_test_recv_body_with_sink(file, 0);

        let reservation = pool
            .try_reserve(chunk_bytes)
            .unwrap()
            .expect("has capacity");
        let data = pooled_data(&pool, &reservation, b"flushed");
        let mut slot = writer.claim();
        slot.attach_reservation(reservation);
        slot.fill(ChunkOutput {
            seq: 0,
            offset: 0,
            data,
            metadata: Default::default(),
        });

        assert_eq!(pool.metrics().active_planned_demand_bytes(), 0);
        assert_eq!(pool.metrics().in_use_bytes(), chunk_bytes as u64);

        writer.terminal_drain().unwrap();
        assert_eq!(pool.metrics().in_use_bytes(), 0);
        assert_eq!(pool.metrics().admitted_bytes(), 0);
        assert_eq!(&std::fs::read(&path).unwrap()[..7], b"flushed");
    }
}