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
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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Mutable byte streams backed by exclusively owned pool carriers.
//!
//! Acquisition returns charged carrier guards without assigning byte-level
//! meaning to their storage. [`PooledBufMut`] arranges those carriers in logical
//! write order and implements the remaining ownership transitions:
//!
//! - [`BufMut`] exposes only uninitialized storage held exclusively by the
//!   mutable buffer.
//! - [`PooledBufMut::publish_prefix`] removes initialized bytes from mutable
//!   authority and transfers them to an immutable [`Bytes`] owner.
//! - [`PooledBufMut::freeze`] ends growth and transfers all remaining
//!   initialized bytes to [`SegmentedBytes`].
//!
//! Growth consumes retained writable capacity before acquiring more carriers.
//! A buffer never changes between reserved and unreserved growth.

use std::mem::MaybeUninit;
use std::ptr::NonNull;

use bytes::buf::UninitSlice;
use bytes::{BufMut, Bytes};
use smallvec::SmallVec;

use super::acquisition::{
    acquire_count, allocation_failure_injected, AcquireError, CarrierGuard, OwnerReturn,
};
use super::admission::ReservationState;
use super::block::CarrierLocation;
use super::geometry::GeometryError;
use super::segmented_bytes::SegmentedBytesBuilder;
use super::{invariant_violation, CarrierCount, PoolInner, SegmentedBytes};
use crate::runtime::sync::sync::Arc;

/// Carrier runs stored inline before metadata spills to the heap.
const INLINE_CARRIER_RUNS: usize = 4;

/// Contiguous physical runs in logical byte order.
type CarrierRuns = SmallVec<[CarrierRun; INLINE_CARRIER_RUNS]>;

/// One growable, exclusively writable stream of pooled bytes.
///
/// `len()` counts initialized bytes that remain owned by this mutable buffer.
/// `remaining_mut()` counts retained uninitialized capacity, and `capacity()`
/// is their sum. Publishing bytes reduces both `len()` and `capacity()` because
/// the immutable result takes ownership of that range.
///
/// The buffer implements [`BufMut`] but does not expose its initialized prefix
/// as one slice. Initialized bytes may cross carrier boundaries; callers use
/// [`Self::initialized_chunk`] and [`Self::publish_prefix`] to transfer one
/// contiguous prefix at a time, or [`Self::freeze`] to finish the complete
/// segmented value.
///
/// Growth reuses this buffer's retained writable tail before acquiring another
/// carrier. Freezing a partially initialized carrier discards mutable access
/// to its unused suffix, while the immutable prefix keeps the complete carrier
/// charged. Several partially filled buffers can therefore exhaust a
/// reservation's carrier allowance even when their initialized byte lengths
/// fit within the reservation. The allowance returns when each final immutable
/// owner drops.
pub(crate) struct PooledBufMut {
    /// Selects reserved or unreserved acquisition for every later growth.
    growth: GrowthAuthority,
    /// Preserves logical byte order across physical runs.
    runs: CarrierRuns,
    /// First carrier with uninitialized writable capacity.
    write_cursor: BufferCursor,
    /// First carrier with initialized unpublished bytes.
    publish_cursor: BufferCursor,
    /// Initialized bytes awaiting publication.
    initialized: usize,
    /// Initialized bytes plus uninitialized writable capacity.
    retained_capacity: usize,
}

impl PooledBufMut {
    /// Takes every carrier from one complete acquisition.
    ///
    /// Failure drops all guards and returns their physical and accounting
    /// ownership. No partial mutable buffer escapes.
    pub(super) fn try_new(
        growth: GrowthAuthority,
        guards: Vec<Arc<CarrierGuard>>,
    ) -> Result<Self, AcquireError> {
        let (runs, retained_capacity) = build_runs(growth.pool(), guards)?;
        let mut buffer = Self {
            growth,
            runs,
            write_cursor: BufferCursor::START,
            publish_cursor: BufferCursor::START,
            initialized: 0,
            retained_capacity,
        };
        buffer.reset_cursors();
        Ok(buffer)
    }

    /// Returns initialized and writable bytes retained by this buffer.
    ///
    /// This is `len() + remaining_mut()`, not the original allocation size.
    /// Publishing removes capacity from the mutable buffer.
    pub(crate) fn capacity(&self) -> usize {
        self.retained_capacity
    }

    /// Returns initialized bytes that have not been published.
    ///
    /// The bytes may span multiple carriers and therefore may not be
    /// contiguous in memory.
    pub(crate) fn len(&self) -> usize {
        self.initialized
    }

    /// Returns whether no initialized unpublished bytes remain.
    pub(crate) fn is_empty(&self) -> bool {
        self.initialized == 0
    }

    /// Returns the number of grouped runs for acquisition tests.
    ///
    /// Fuzzing uses this only as a placement witness. It does not expose block
    /// addresses or mutable ownership outside the pool.
    #[cfg(any(test, s3_tm_fuzz))]
    pub(in crate::runtime::buffer_pool) fn test_run_count(&self) -> usize {
        self.runs.len()
    }

    /// Returns one grouped run's complete carrier capacity.
    #[cfg(test)]
    pub(super) fn test_run_capacity(&self, index: usize) -> usize {
        self.runs[index]
            .carriers
            .iter()
            .map(|carrier| carrier.writable.len())
            .sum()
    }

    /// Returns the reservation containing the first retained carrier.
    #[cfg(all(
        test,
        not(miri),
        not(s3_tm_loom),
        not(s3_tm_tsan),
        any(
            target_os = "android",
            target_os = "freebsd",
            target_os = "linux",
            target_os = "macos",
            target_os = "windows"
        )
    ))]
    fn test_first_reservation_address_range(&self) -> std::ops::Range<usize> {
        self.runs[0].carriers[0]
            .guard
            .as_ref()
            .expect("test buffer retained no first-carrier guard")
            .slot()
            .reservation_address_range()
    }

    /// Returns the next contiguous initialized prefix.
    ///
    /// The result is empty exactly when [`Self::len`] is zero. A nonempty
    /// result never crosses a carrier boundary.
    pub(crate) fn initialized_chunk(&self) -> &[u8] {
        if self.initialized == 0 {
            return &[];
        }
        let carrier = self
            .carrier(self.publish_cursor)
            .filter(|carrier| carrier.initialized != 0)
            .unwrap_or_else(|| {
                invariant_violation("publication cursor does not name initialized bytes")
            });

        // SAFETY: `initialized` is the prefix written through this buffer's
        // exclusive range. The carrier guard keeps the mapping prepared.
        unsafe {
            std::slice::from_raw_parts(
                carrier.writable.ptr().as_ptr().cast::<u8>(),
                carrier.initialized,
            )
        }
    }

    /// Ensures that at least `min_writable` uninitialized bytes remain.
    ///
    /// Existing tail capacity is consumed before the shortfall is rounded to
    /// complete carriers. Only capacity retained by this buffer can satisfy
    /// the guarantee; unused tails discarded by other buffers are not shared.
    /// Failure leaves this buffer unchanged.
    pub(crate) fn reserve(&mut self, min_writable: usize) -> Result<(), AcquireError> {
        let remaining = self.remaining_mut();
        if min_writable <= remaining {
            return Ok(());
        }

        let shortfall = min_writable
            .checked_sub(remaining)
            .ok_or(AcquireError::CapacityOverflow)?;
        let count = self
            .growth
            .pool()
            .geometry
            .carriers_for_bytes(shortfall)
            .map_err(map_geometry_error)?;
        let guards = self.growth.acquire(count)?;
        let (staged, added_capacity) = build_runs(self.growth.pool(), guards)?;
        self.append_staged(staged, added_capacity)?;
        Ok(())
    }

    /// Publishes one contiguous initialized prefix without copying.
    ///
    /// # Panics
    ///
    /// Panics unless `count` is nonzero and no larger than
    /// `initialized_chunk().len()`.
    pub(crate) fn publish_prefix(&mut self, count: usize) -> Bytes {
        self.normalize_publish_cursor();
        let available = self.initialized_chunk().len();
        assert!(
            count != 0 && count <= available,
            "published prefix must be nonzero and within initialized_chunk"
        );

        let cursor = self.publish_cursor;
        let (range, guard) =
            {
                let carrier = self.carrier_mut(cursor).unwrap_or_else(|| {
                    invariant_violation("publication cursor is outside the buffer")
                });
                let range = carrier.writable.take_prefix(count);
                carrier.initialized = carrier.initialized.checked_sub(count).unwrap_or_else(|| {
                    invariant_violation("publication exceeds initialized bytes")
                });
                let guard =
                    if carrier.writable.is_empty() {
                        carrier.guard.take().unwrap_or_else(|| {
                            invariant_violation("exhausted writable carrier lost its guard")
                        })
                    } else {
                        Arc::clone(carrier.guard.as_ref().unwrap_or_else(|| {
                            invariant_violation("writable carrier lost its guard")
                        }))
                    };
                (range, guard)
            };

        self.initialized = self
            .initialized
            .checked_sub(count)
            .unwrap_or_else(|| invariant_violation("buffer initialization underflow"));
        self.retained_capacity = self
            .retained_capacity
            .checked_sub(count)
            .unwrap_or_else(|| invariant_violation("buffer capacity underflow"));
        self.normalize_publish_cursor();

        Bytes::from_owner(PooledWindow::new(guard, range))
    }

    /// Ends growth and transfers initialized unpublished ranges.
    ///
    /// Wholly unused carriers return immediately, together, as the buffer
    /// drops. An initialized prefix in a partially used carrier retains that
    /// carrier and discards its writable suffix. The operation does not copy
    /// initialized bytes.
    pub(crate) fn freeze(mut self) -> SegmentedBytes {
        let pool = Arc::clone(self.growth.pool());
        let mut builder = SegmentedBytesBuilder::for_pool(pool);

        for run in &mut self.runs {
            for carrier in &mut run.carriers {
                if carrier.initialized == 0 {
                    continue;
                }
                let initialized = carrier.initialized;
                let range = carrier.writable.take_prefix(initialized);
                carrier.initialized = 0;
                let guard = carrier
                    .guard
                    .take()
                    .unwrap_or_else(|| invariant_violation("initialized carrier lost its guard"));
                builder.push_pooled(range.ptr.cast::<u8>(), range.len, guard);
            }
        }

        builder.finish()
    }

    /// Appends one fully staged growth transaction.
    fn append_staged(
        &mut self,
        mut staged: CarrierRuns,
        added_capacity: usize,
    ) -> Result<(), AcquireError> {
        let retained_capacity = self
            .retained_capacity
            .checked_add(added_capacity)
            .ok_or(AcquireError::CapacityOverflow)?;
        if staged.is_empty() {
            invariant_violation("successful growth produced no carrier runs");
        }

        let merge_first = self
            .runs
            .last()
            .zip(staged.first())
            .is_some_and(|(current, incoming)| current.can_append_run(incoming));
        let appended_runs = staged.len() - usize::from(merge_first);

        if allocation_failure_injected(self.growth.pool()) {
            return Err(AcquireError::MetadataAllocationFailed);
        }
        self.runs
            .try_reserve(appended_runs)
            .map_err(|_| AcquireError::MetadataAllocationFailed)?;

        if merge_first {
            let incoming = staged.remove(0);
            let current = self
                .runs
                .last_mut()
                .unwrap_or_else(|| invariant_violation("merge target disappeared"));
            if allocation_failure_injected(self.growth.pool()) {
                return Err(AcquireError::MetadataAllocationFailed);
            }
            current
                .carriers
                .try_reserve(incoming.carriers.len())
                .map_err(|_| AcquireError::MetadataAllocationFailed)?;
            current.carriers.extend(incoming.carriers);
        }
        self.runs.extend(staged);
        self.retained_capacity = retained_capacity;
        self.reset_write_cursor();
        self.normalize_publish_cursor();
        Ok(())
    }

    /// Finds both cursors after initial construction.
    fn reset_cursors(&mut self) {
        self.reset_write_cursor();
        self.publish_cursor = self
            .first_cursor_matching(|carrier| carrier.initialized != 0)
            .unwrap_or_else(|| BufferCursor::end(self.runs.len()));
    }

    /// Finds the first writable carrier after run topology changes.
    fn reset_write_cursor(&mut self) {
        self.write_cursor = self
            .first_cursor_matching(|carrier| carrier.remaining_mut() != 0)
            .unwrap_or_else(|| BufferCursor::end(self.runs.len()));
    }

    /// Advances the write cursor past exhausted carrier entries.
    fn normalize_write_cursor(&mut self) {
        self.write_cursor = self
            .cursor_matching_from(self.write_cursor, |carrier| carrier.remaining_mut() != 0)
            .unwrap_or_else(|| BufferCursor::end(self.runs.len()));
    }

    /// Advances the publication cursor past entries with no initialized bytes.
    fn normalize_publish_cursor(&mut self) {
        self.publish_cursor = self
            .cursor_matching_from(self.publish_cursor, |carrier| carrier.initialized != 0)
            .unwrap_or_else(|| BufferCursor::end(self.runs.len()));
    }

    /// Returns the first carrier cursor satisfying `predicate`.
    fn first_cursor_matching(
        &self,
        predicate: impl Fn(&WritableCarrier) -> bool,
    ) -> Option<BufferCursor> {
        for (run, entry) in self.runs.iter().enumerate() {
            for (carrier, value) in entry.carriers.iter().enumerate() {
                if predicate(value) {
                    return Some(BufferCursor { run, carrier });
                }
            }
        }
        None
    }

    /// Returns the next carrier at or after `cursor` satisfying `predicate`.
    fn cursor_matching_from(
        &self,
        mut cursor: BufferCursor,
        predicate: impl Fn(&WritableCarrier) -> bool,
    ) -> Option<BufferCursor> {
        loop {
            let carrier = self.carrier(cursor)?;
            if predicate(carrier) {
                return Some(cursor);
            }
            cursor = self.next_cursor(cursor)?;
        }
    }

    /// Returns the carrier after `cursor`.
    fn next_cursor(&self, cursor: BufferCursor) -> Option<BufferCursor> {
        let run = self.runs.get(cursor.run)?;
        let carrier = cursor.carrier.checked_add(1)?;
        if carrier < run.carriers.len() {
            return Some(BufferCursor {
                run: cursor.run,
                carrier,
            });
        }
        let run = cursor.run.checked_add(1)?;
        (run < self.runs.len()).then_some(BufferCursor { run, carrier: 0 })
    }

    /// Returns the carrier at `cursor`.
    fn carrier(&self, cursor: BufferCursor) -> Option<&WritableCarrier> {
        self.runs
            .get(cursor.run)
            .and_then(|run| run.carriers.get(cursor.carrier))
    }

    /// Returns the mutable carrier at `cursor`.
    fn carrier_mut(&mut self, cursor: BufferCursor) -> Option<&mut WritableCarrier> {
        self.runs
            .get_mut(cursor.run)
            .and_then(|run| run.carriers.get_mut(cursor.carrier))
    }

    /// Marks `count` sequential writable bytes initialized.
    fn advance_initialized(&mut self, mut count: usize) {
        assert!(
            count <= self.remaining_mut(),
            "advanced beyond pooled writable capacity"
        );
        if count == 0 {
            return;
        }

        self.normalize_write_cursor();
        while count != 0 {
            let cursor = self.write_cursor;
            let publish_was_empty = self.initialized == 0;
            let (advanced, exhausted) = {
                let carrier = self.carrier_mut(cursor).unwrap_or_else(|| {
                    invariant_violation("writable cursor is outside the buffer")
                });
                let advanced = count.min(carrier.remaining_mut());
                if advanced == 0 {
                    invariant_violation("writable cursor names an exhausted carrier");
                }
                carrier.initialized = carrier
                    .initialized
                    .checked_add(advanced)
                    .unwrap_or_else(|| invariant_violation("carrier initialization overflow"));
                (advanced, carrier.remaining_mut() == 0)
            };
            if publish_was_empty {
                self.publish_cursor = cursor;
            }
            self.initialized = self
                .initialized
                .checked_add(advanced)
                .unwrap_or_else(|| invariant_violation("buffer initialization overflow"));
            count -= advanced;
            if exhausted {
                self.write_cursor = self
                    .next_cursor(cursor)
                    .unwrap_or_else(|| BufferCursor::end(self.runs.len()));
                self.normalize_write_cursor();
            }
        }
    }
}

/// Returns every carrier the buffer still owns as one whole-value return.
///
/// Carriers return together so a queued reservation observes the complete
/// return rather than a partial one. A carrier whose prefix was published
/// stays owned by that published value.
impl Drop for PooledBufMut {
    fn drop(&mut self) {
        let Some(first) = first_retained_guard(&self.runs) else {
            return;
        };
        let mut owner_return = OwnerReturn::begin(first);
        if !owner_return.is_batched() {
            // Return carriers before the registration ends so overlapping
            // returns observe this whole-value return as active.
            self.runs.clear();
            return;
        }
        for run in &mut self.runs {
            for carrier in &mut run.carriers {
                if let Some(guard) = carrier.guard.take() {
                    owner_return.push(guard);
                }
            }
        }
    }
}

/// Returns the first retained carrier guard when `runs` retain several.
fn first_retained_guard(runs: &CarrierRuns) -> Option<&CarrierGuard> {
    let mut guards = runs
        .iter()
        .flat_map(|run| &run.carriers)
        .filter_map(|carrier| carrier.guard.as_deref());
    let first = guards.next()?;
    guards.next().map(|_| first)
}

impl std::fmt::Debug for PooledBufMut {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PooledBufMut")
            .field("initialized", &self.initialized)
            .field("retained_capacity", &self.retained_capacity)
            .finish_non_exhaustive()
    }
}

// SAFETY: moving the buffer transfers every unique `ExclusiveRange`.
// Carrier and growth state is retained through synchronized shared ownership.
unsafe impl Send for PooledBufMut {}

// SAFETY: each `ExclusiveRange` is unique to this buffer, every pointer is
// retained by its carrier guard, and `advance_mut` exposes only initialized
// state transitions made by the caller.
unsafe impl BufMut for PooledBufMut {
    fn remaining_mut(&self) -> usize {
        self.retained_capacity
            .checked_sub(self.initialized)
            .unwrap_or_else(|| invariant_violation("initialized bytes exceed retained capacity"))
    }

    fn chunk_mut(&mut self) -> &mut UninitSlice {
        self.normalize_write_cursor();
        if self.remaining_mut() == 0 {
            // SAFETY: a dangling pointer is valid for a zero-length slice and
            // the returned borrow remains tied to `self`.
            return unsafe {
                UninitSlice::from_raw_parts_mut(NonNull::<u8>::dangling().as_ptr(), 0)
            };
        }
        let cursor = self.write_cursor;
        let carrier = self
            .carrier_mut(cursor)
            .unwrap_or_else(|| invariant_violation("buffer has no writable carrier"));
        let remaining = carrier.remaining_mut();
        if remaining == 0 {
            invariant_violation("writable cursor names an exhausted carrier");
        }
        // SAFETY: the returned range is the uninitialized suffix of one
        // exclusive carrier range and remains borrowed through `self`.
        unsafe {
            UninitSlice::from_raw_parts_mut(
                carrier
                    .writable
                    .ptr()
                    .as_ptr()
                    .add(carrier.initialized)
                    .cast::<u8>(),
                remaining,
            )
        }
    }

    unsafe fn advance_mut(&mut self, count: usize) {
        self.advance_initialized(count);
    }
}

/// Fixed acquisition authority for every growth of one mutable buffer.
///
/// Retaining the mode prevents a reserved buffer from escaping its envelope
/// through unreserved growth.
pub(super) enum GrowthAuthority {
    /// New carriers must debit this reservation.
    Reserved(Arc<ReservationState>),
    /// New carriers use aggregate pool authority only.
    Unreserved(Arc<PoolInner>),
}

impl GrowthAuthority {
    /// Creates reserved growth authority.
    pub(super) fn reserved(state: Arc<ReservationState>) -> Self {
        Self::Reserved(state)
    }

    /// Creates unreserved growth authority.
    pub(super) fn unreserved(pool: Arc<PoolInner>) -> Self {
        Self::Unreserved(pool)
    }

    /// Returns the shared pool.
    fn pool(&self) -> &Arc<PoolInner> {
        match self {
            Self::Reserved(state) => state.pool(),
            Self::Unreserved(pool) => pool,
        }
    }

    /// Acquires one complete carrier-rounded growth batch.
    fn acquire(&self, count: CarrierCount) -> Result<Vec<Arc<CarrierGuard>>, AcquireError> {
        match self {
            Self::Reserved(state) => acquire_count(state.pool(), Some(Arc::clone(state)), count),
            Self::Unreserved(pool) => acquire_count(pool, None, count),
        }
    }
}

/// Adjacent carriers within one stable block slot.
///
/// Runs preserve logical byte order and reduce the top-level metadata needed
/// for the common case where acquisition returns neighboring carriers. A run
/// groups cursors only; each carrier keeps its own guard and pointer, and
/// immutable coalescing performs a separate slot-identity check.
struct CarrierRun {
    /// Stable block slot containing the run.
    slot_id: u32,
    /// First carrier index within the slot.
    first_carrier: u32,
    /// Per-carrier mutable ownership in ascending address order.
    carriers: Vec<WritableCarrier>,
}

impl CarrierRun {
    /// Creates a run containing one carrier.
    fn try_new(pool: &PoolInner, guard: Arc<CarrierGuard>) -> Result<Self, AcquireError> {
        let location = guard.location();
        let mut carriers = Vec::new();
        if allocation_failure_injected(pool) {
            return Err(AcquireError::MetadataAllocationFailed);
        }
        carriers
            .try_reserve_exact(1)
            .map_err(|_| AcquireError::MetadataAllocationFailed)?;
        carriers.push(WritableCarrier::new(guard));
        Ok(Self {
            slot_id: location.slot_id(),
            first_carrier: location.carrier_index(),
            carriers,
        })
    }

    /// Returns whether `guard` immediately follows this run.
    fn can_append(&self, guard: &CarrierGuard) -> bool {
        let run_len = u32::try_from(self.carriers.len())
            .unwrap_or_else(|_| invariant_violation("carrier run length exceeds block geometry"));
        let next = self
            .first_carrier
            .checked_add(run_len)
            .unwrap_or_else(|| invariant_violation("carrier run end exceeds block geometry"));
        guard.location() == CarrierLocation::new(self.slot_id, next)
    }

    /// Returns whether `incoming` immediately follows this run.
    fn can_append_run(&self, incoming: &Self) -> bool {
        let run_len = u32::try_from(self.carriers.len())
            .unwrap_or_else(|_| invariant_violation("carrier run length exceeds block geometry"));
        self.slot_id == incoming.slot_id
            && self.first_carrier.checked_add(run_len) == Some(incoming.first_carrier)
    }

    /// Appends one adjacent carrier.
    fn try_append(
        &mut self,
        pool: &PoolInner,
        guard: Arc<CarrierGuard>,
    ) -> Result<(), AcquireError> {
        if allocation_failure_injected(pool) {
            return Err(AcquireError::MetadataAllocationFailed);
        }
        self.carriers
            .try_reserve(1)
            .map_err(|_| AcquireError::MetadataAllocationFailed)?;
        self.carriers.push(WritableCarrier::new(guard));
        Ok(())
    }
}

/// Unique mutable authority over one carrier's unpublished suffix.
///
/// `initialized` divides `writable` into an initialized prefix followed by an
/// uninitialized suffix. Prefix publication advances `writable` and may leave
/// this positional entry empty so existing cursors remain stable.
struct WritableCarrier {
    /// Shared physical and accounting ownership while a range remains.
    guard: Option<Arc<CarrierGuard>>,
    /// Initialized prefix followed by uninitialized writable capacity.
    writable: ExclusiveRange,
    /// Initialized prefix length within `writable`.
    initialized: usize,
}

impl WritableCarrier {
    /// Creates a wholly uninitialized writable carrier.
    fn new(guard: Arc<CarrierGuard>) -> Self {
        let writable = ExclusiveRange::new(guard.ptr(), guard.capacity());
        Self {
            guard: Some(guard),
            writable,
            initialized: 0,
        }
    }

    /// Returns uninitialized writable bytes.
    fn remaining_mut(&self) -> usize {
        self.writable
            .len()
            .checked_sub(self.initialized)
            .unwrap_or_else(|| invariant_violation("carrier initialization exceeds its range"))
    }
}

/// Non-cloneable authority over one mutable byte range.
///
/// Construction requires a nonempty range. Prefix transfer may later consume
/// the complete range while its metadata entry remains positionally stable.
struct ExclusiveRange {
    ptr: NonNull<MaybeUninit<u8>>,
    len: usize,
}

impl ExclusiveRange {
    /// Creates authority over one complete carrier.
    fn new(ptr: NonNull<MaybeUninit<u8>>, len: usize) -> Self {
        if len == 0 {
            invariant_violation("exclusive range must be nonempty");
        }
        Self { ptr, len }
    }

    /// Returns the first byte.
    fn ptr(&self) -> NonNull<MaybeUninit<u8>> {
        self.ptr
    }

    /// Returns the range length.
    fn len(&self) -> usize {
        self.len
    }

    /// Returns whether prefix transfer consumed the complete range.
    fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Removes and returns one prefix, leaving a disjoint suffix.
    fn take_prefix(&mut self, count: usize) -> Self {
        assert!(count <= self.len, "split exceeds exclusive range");
        let prefix = Self {
            ptr: self.ptr,
            len: count,
        };
        // SAFETY: `count` lies within this range. The resulting pointer is
        // either within the same allocation or one byte past its end.
        self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().add(count)) };
        self.len -= count;
        prefix
    }
}

/// Run and carrier position inside one mutable buffer.
#[derive(Clone, Copy)]
#[cfg_attr(test, derive(Debug, PartialEq))]
struct BufferCursor {
    run: usize,
    carrier: usize,
}

impl BufferCursor {
    const START: Self = Self { run: 0, carrier: 0 };

    /// Creates a sentinel past the final run.
    fn end(run: usize) -> Self {
        Self { run, carrier: 0 }
    }
}

/// Immutable initialized view retained by one carrier guard.
///
/// `Bytes::from_owner` may clone or slice this owner. The final owner drop
/// releases the guard after every derived immutable view is gone.
struct PooledWindow {
    guard: Arc<CarrierGuard>,
    ptr: NonNull<u8>,
    len: usize,
}

impl PooledWindow {
    /// Consumes one exclusive initialized range.
    fn new(guard: Arc<CarrierGuard>, range: ExclusiveRange) -> Self {
        Self {
            guard,
            ptr: range.ptr.cast::<u8>(),
            len: range.len,
        }
    }
}

impl AsRef<[u8]> for PooledWindow {
    fn as_ref(&self) -> &[u8] {
        let _guard = &self.guard;
        // SAFETY: publication consumed mutable authority over this initialized
        // range, and `guard` retains the prepared carrier.
        unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
    }
}

// SAFETY: the pointer names immutable initialized storage retained by `guard`.
unsafe impl Send for PooledWindow {}

/// Groups one acquisition into adjacent physical runs.
fn build_runs(
    pool: &PoolInner,
    mut guards: Vec<Arc<CarrierGuard>>,
) -> Result<(CarrierRuns, usize), AcquireError> {
    if guards.is_empty() {
        invariant_violation("complete acquisition contains no carriers");
    }
    guards.sort_unstable_by_key(|guard| guard.location());

    let mut runs = CarrierRuns::new();
    let mut capacity = 0usize;
    for guard in guards {
        capacity = capacity
            .checked_add(guard.capacity())
            .ok_or(AcquireError::CapacityOverflow)?;
        if let Some(run) = runs.last_mut() {
            if run.can_append(&guard) {
                run.try_append(pool, guard)?;
                continue;
            }
        }
        if allocation_failure_injected(pool) {
            return Err(AcquireError::MetadataAllocationFailed);
        }
        runs.try_reserve(1)
            .map_err(|_| AcquireError::MetadataAllocationFailed)?;
        runs.push(CarrierRun::try_new(pool, guard)?);
    }
    Ok((runs, capacity))
}

/// Maps byte geometry failures into the acquisition API.
fn map_geometry_error(error: GeometryError) -> AcquireError {
    match error {
        GeometryError::ZeroByteRequest => AcquireError::InvalidSize,
        _ => AcquireError::CapacityOverflow,
    }
}

#[cfg(all(test, not(s3_tm_loom)))]
mod tests {
    use std::sync::Barrier;
    use std::thread;

    use bytes::{Buf, BufMut, BytesMut};

    use std::task::{Poll, Waker};

    use super::super::test_util::{poll_reserve, test_pool, write_pooled};
    use super::super::{BufferPool, ReserveFuture};
    use super::*;

    /// Reservation blocked until its paired buffer releases memory.
    struct WaitingReservation {
        pool: BufferPool,
        prepared_capacity_before_return: u64,
        future: ReserveFuture,
    }

    impl WaitingReservation {
        /// Verifies that the reservation was granted without preparing more memory.
        fn assert_granted_without_preparing_more(mut self) {
            let Poll::Ready(Ok(_reservation)) = poll_reserve(&mut self.future, Waker::noop())
            else {
                panic!("reservation was not granted after the buffer was released");
            };
            assert_eq!(
                self.pool.metrics().prepared_capacity_bytes(),
                self.prepared_capacity_before_return,
                "reservation was granted from a partial release and prepared more memory"
            );
        }
    }

    /// Creates a buffer and a reservation waiting for its memory.
    ///
    /// Existing prepared memory is sufficient after the full release. If
    /// admission acts on a partial release, it prepares more unnecessarily.
    fn buffer_with_waiting_reservation() -> (PooledBufMut, WaitingReservation) {
        let (pool, carrier_size) = test_pool(4, 6);
        let mutable = pool.acquire_unreserved(carrier_size * 4).unwrap();
        let prepared_capacity_before_return = pool.metrics().prepared_capacity_bytes();
        assert_eq!(prepared_capacity_before_return, (carrier_size * 4) as u64);
        let mut future = pool.reserve(carrier_size * 3);
        assert!(poll_reserve(&mut future, Waker::noop()).is_pending());
        (
            mutable,
            WaitingReservation {
                pool,
                prepared_capacity_before_return,
                future,
            },
        )
    }

    #[test]
    fn test_freeze_returns_unused_carriers_before_queued_grant() {
        let (mutable, waiting) = buffer_with_waiting_reservation();
        let frozen = mutable.freeze();
        assert_eq!(frozen.remaining(), 0);
        waiting.assert_granted_without_preparing_more();
    }

    #[test]
    fn test_drop_returns_carriers_before_queued_grant() {
        let (mutable, waiting) = buffer_with_waiting_reservation();
        drop(mutable);
        waiting.assert_granted_without_preparing_more();
    }

    /// Checks the aggregate fields and cursors against per-carrier state.
    fn assert_buffer_invariants(buffer: &PooledBufMut) {
        let mut retained_capacity = 0usize;
        let mut initialized = 0usize;
        let mut writable = 0usize;

        for run in &buffer.runs {
            assert!(!run.carriers.is_empty());
            for (offset, carrier) in run.carriers.iter().enumerate() {
                assert!(carrier.initialized <= carrier.writable.len());
                assert_eq!(carrier.guard.is_some(), !carrier.writable.is_empty());

                if let Some(guard) = carrier.guard.as_ref() {
                    let offset = u32::try_from(offset).expect("test run exceeds u32");
                    let carrier_index = run
                        .first_carrier
                        .checked_add(offset)
                        .expect("test run exceeds block geometry");
                    assert_eq!(
                        guard.location(),
                        CarrierLocation::new(run.slot_id, carrier_index)
                    );
                }

                retained_capacity = retained_capacity
                    .checked_add(carrier.writable.len())
                    .expect("test capacity overflow");
                initialized = initialized
                    .checked_add(carrier.initialized)
                    .expect("test initialization overflow");
                writable = writable
                    .checked_add(carrier.remaining_mut())
                    .expect("test writable capacity overflow");
            }
        }

        assert_eq!(buffer.retained_capacity, retained_capacity);
        assert_eq!(buffer.initialized, initialized);
        assert_eq!(buffer.remaining_mut(), writable);
        assert_eq!(
            buffer.publish_cursor,
            buffer
                .first_cursor_matching(|carrier| carrier.initialized != 0)
                .unwrap_or_else(|| BufferCursor::end(buffer.runs.len()))
        );
        assert_eq!(
            buffer.write_cursor,
            buffer
                .first_cursor_matching(|carrier| carrier.remaining_mut() != 0)
                .unwrap_or_else(|| BufferCursor::end(buffer.runs.len()))
        );
    }

    #[test]
    fn test_mutable_initialization_crosses_carrier_boundaries() {
        let (pool, carrier_size) = test_pool(2, 2);
        let mut buffer = pool.acquire_unreserved(carrier_size + 1).unwrap();
        let input: Vec<u8> = (0..carrier_size + 1)
            .map(|index| (index % 251) as u8)
            .collect();

        write_pooled(&mut buffer, &input);

        assert_eq!(buffer.capacity(), carrier_size * 2);
        assert_eq!(buffer.len(), input.len());
        assert_eq!(buffer.remaining_mut(), carrier_size - 1);
        assert_eq!(buffer.initialized_chunk(), &input[..carrier_size]);
        assert_eq!(buffer.chunk_mut().len(), carrier_size - 1);
    }

    #[test]
    fn test_buf_mut_put_slice_crosses_carrier_boundaries() {
        let (pool, carrier_size) = test_pool(2, 2);
        let mut buffer = pool.acquire_unreserved(carrier_size + 3).unwrap();
        let input: Vec<u8> = (0..carrier_size + 3)
            .map(|index| (index.wrapping_mul(19) % 251) as u8)
            .collect();

        buffer.put_slice(&input);

        assert_eq!(buffer.len(), input.len());
        assert_eq!(buffer.remaining_mut(), carrier_size - 3);
        assert_eq!(buffer.initialized_chunk(), &input[..carrier_size]);
        let first = buffer.publish_prefix(carrier_size);
        assert_eq!(first, input[..carrier_size]);
        assert_eq!(buffer.initialized_chunk(), &input[carrier_size..]);
    }

    #[test]
    fn test_buf_mut_zero_and_exact_boundary_advance_select_next_carrier() {
        let (pool, carrier_size) = test_pool(2, 2);
        let mut buffer = pool.acquire_unreserved(carrier_size * 2).unwrap();

        let initial_len = buffer.chunk_mut().len();
        // SAFETY: advancing by zero initializes no bytes.
        unsafe { buffer.advance_mut(0) };
        assert_eq!(buffer.chunk_mut().len(), initial_len);

        let initialized = vec![0x5a; carrier_size];
        buffer.chunk_mut()[..carrier_size].copy_from_slice(&initialized);
        // SAFETY: the preceding fill initialized the complete first chunk.
        unsafe { buffer.advance_mut(carrier_size) };

        assert_eq!(buffer.len(), carrier_size);
        assert_eq!(buffer.chunk_mut().len(), carrier_size);
        assert_eq!(buffer.initialized_chunk(), initialized);
    }

    #[test]
    fn test_incremental_growth_reuses_one_buffers_writable_tail() {
        let (pool, carrier_size) = test_pool(4, 3);
        let total = carrier_size * 2 + 1;
        let reservation = pool
            .try_reserve(total)
            .unwrap()
            .expect("three-carrier reservation");
        let mut buffer = pool.acquire(&reservation, 1).unwrap();
        let increments = [
            carrier_size / 2,
            carrier_size / 2,
            carrier_size / 2,
            carrier_size / 2 + 1,
        ];

        let mut next = 0u8;
        for increment in increments {
            buffer.reserve(increment).unwrap();
            let bytes: Vec<u8> = (0..increment)
                .map(|_| {
                    let value = next;
                    next = next.wrapping_add(1);
                    value
                })
                .collect();
            write_pooled(&mut buffer, &bytes);
        }

        assert_eq!(buffer.len(), total);
        assert_eq!(buffer.capacity(), carrier_size * 3);
        assert_eq!(buffer.remaining_mut(), carrier_size - 1);
        assert_eq!(buffer.test_run_count(), 1);
    }

    #[test]
    fn test_reserve_zero_and_satisfied_tail_do_not_acquire() {
        let (pool, carrier_size) = test_pool(2, 2);
        let reservation = pool
            .try_reserve(carrier_size * 2)
            .unwrap()
            .expect("reservation");
        let mut buffer = pool.acquire(&reservation, 1).unwrap();
        write_pooled(&mut buffer, b"tail");
        let capacity = buffer.capacity();
        let metrics = pool.metrics();

        buffer.reserve(0).unwrap();
        buffer.reserve(buffer.remaining_mut()).unwrap();

        assert_eq!(buffer.capacity(), capacity);
        assert_eq!(pool.metrics().in_use_bytes(), metrics.in_use_bytes());
    }

    #[test]
    fn test_closed_reservation_allows_tail_use_but_rejects_growth() {
        let (pool, carrier_size) = test_pool(2, 2);
        let reservation = pool
            .try_reserve(carrier_size * 2)
            .unwrap()
            .expect("reservation");
        let mut buffer = pool.acquire(&reservation, 1).unwrap();
        reservation.close_acquisition();

        buffer.reserve(carrier_size).unwrap();
        let before = (buffer.capacity(), buffer.len(), buffer.remaining_mut());
        assert_eq!(
            buffer.reserve(carrier_size + 1),
            Err(AcquireError::ReservationClosed)
        );
        assert_eq!(
            (buffer.capacity(), buffer.len(), buffer.remaining_mut()),
            before
        );
    }

    #[test]
    fn test_reservation_exhaustion_preserves_existing_buffer() {
        let (pool, carrier_size) = test_pool(1, 1);
        let reservation = pool
            .try_reserve(carrier_size)
            .unwrap()
            .expect("reservation");
        let mut buffer = pool.acquire(&reservation, 1).unwrap();
        let input = vec![0x5a; carrier_size];
        write_pooled(&mut buffer, &input);
        let before = (buffer.capacity(), buffer.len(), buffer.remaining_mut());

        assert_eq!(
            buffer.reserve(1),
            Err(AcquireError::ReservationCapacityExceeded)
        );
        assert_eq!(
            (buffer.capacity(), buffer.len(), buffer.remaining_mut()),
            before
        );
        assert_eq!(buffer.initialized_chunk(), input.as_slice());
    }

    #[test]
    fn test_growth_metadata_failure_preserves_bytes_cursors_and_authority() {
        for boundary in 1.. {
            let (pool, carrier_size) = test_pool(2, 2);
            let reservation = pool
                .try_reserve(carrier_size * 2)
                .unwrap()
                .expect("reservation");
            let mut buffer = pool.acquire(&reservation, 1).unwrap();
            write_pooled(&mut buffer, b"abc");
            pool.inject_acquisition_allocation_failure(boundary);

            let result = buffer.reserve(carrier_size);
            if pool.acquisition_allocation_failure_pending() {
                assert!(result.is_ok(), "boundary {boundary} was not reached");
                break;
            }
            assert_eq!(result, Err(AcquireError::MetadataAllocationFailed));
            assert_eq!(buffer.capacity(), carrier_size);
            assert_eq!(buffer.len(), 3);
            assert_eq!(buffer.remaining_mut(), carrier_size - 3);
            assert_eq!(buffer.initialized_chunk(), b"abc");
            assert_eq!(pool.metrics().in_use_bytes(), carrier_size as u64);

            buffer
                .reserve(carrier_size)
                .expect("rollback restored direct authority");
            assert_eq!(buffer.capacity(), carrier_size * 2);
        }
    }

    #[test]
    fn test_exhausted_buffer_returns_empty_mutable_chunk() {
        let (pool, carrier_size) = test_pool(1, 1);
        let mut buffer = pool.acquire_unreserved(carrier_size).unwrap();
        write_pooled(&mut buffer, &vec![0; carrier_size]);

        assert_eq!(buffer.remaining_mut(), 0);
        assert_eq!(buffer.chunk_mut().len(), 0);
    }

    #[test]
    fn test_rounding_is_per_buffer_instead_of_per_growth_call() {
        let (stream_pool, carrier_size) = test_pool(2, 2);
        let increment = carrier_size / 2 + 1;
        let total = increment * 3;
        assert!(total <= carrier_size * 2);
        let stream_reservation = stream_pool
            .try_reserve(total)
            .unwrap()
            .expect("two-carrier stream reservation");
        let mut stream = stream_pool.acquire(&stream_reservation, increment).unwrap();
        write_pooled(&mut stream, &vec![0; increment]);
        for _ in 0..2 {
            stream.reserve(increment).unwrap();
            write_pooled(&mut stream, &vec![0; increment]);
        }
        assert_eq!(stream.capacity(), carrier_size * 2);

        let (split_pool, _) = test_pool(2, 2);
        let split_reservation = split_pool
            .try_reserve(total)
            .unwrap()
            .expect("two-carrier split reservation");
        let first = split_pool.acquire(&split_reservation, increment).unwrap();
        let second = split_pool.acquire(&split_reservation, increment).unwrap();
        assert!(matches!(
            split_pool.acquire(&split_reservation, increment),
            Err(AcquireError::ReservationCapacityExceeded)
        ));
        drop((first, second));
    }

    #[test]
    fn test_interleaved_publication_growth_and_freeze_preserve_multirun_state() {
        let (pool, carrier_size) = test_pool(1, 3);
        let first_input: Vec<u8> = (0..carrier_size + 3)
            .map(|index| (index.wrapping_mul(17) % 251) as u8)
            .collect();
        let second_input: Vec<u8> = (0..carrier_size + 2)
            .map(|index| (index.wrapping_mul(29) % 251) as u8)
            .collect();
        let mut buffer = pool.acquire_unreserved(first_input.len()).unwrap();
        assert_eq!(buffer.test_run_count(), 2);
        assert_buffer_invariants(&buffer);

        write_pooled(&mut buffer, &first_input);
        assert_buffer_invariants(&buffer);
        let first = buffer.publish_prefix(carrier_size);
        assert_buffer_invariants(&buffer);
        let second_prefix = buffer.publish_prefix(2);
        assert_buffer_invariants(&buffer);

        buffer.reserve(carrier_size + 2).unwrap();
        assert_eq!(buffer.test_run_count(), 3);
        assert_buffer_invariants(&buffer);
        write_pooled(&mut buffer, &second_input);
        assert_buffer_invariants(&buffer);
        let second_rest = buffer.publish_prefix(carrier_size - 2);
        assert_buffer_invariants(&buffer);
        let frozen = buffer.freeze().into_contiguous();

        let mut output = BytesMut::with_capacity(first_input.len() + second_input.len());
        output.extend_from_slice(&first);
        output.extend_from_slice(&second_prefix);
        output.extend_from_slice(&second_rest);
        output.extend_from_slice(&frozen);
        let mut expected = first_input;
        expected.extend_from_slice(&second_input);
        assert_eq!(output, expected.as_slice());

        assert_eq!(pool.metrics().in_use_bytes(), (carrier_size * 3) as u64);
        drop(first);
        assert_eq!(pool.metrics().in_use_bytes(), (carrier_size * 2) as u64);
        drop(second_prefix);
        assert_eq!(pool.metrics().in_use_bytes(), (carrier_size * 2) as u64);
        drop(second_rest);
        assert_eq!(pool.metrics().in_use_bytes(), carrier_size as u64);
        drop(frozen);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_carrier_runs_spill_preserves_mutable_stream() {
        let run_count = INLINE_CARRIER_RUNS + 1;
        let (pool, carrier_size) = test_pool(1, run_count);
        let input: Vec<u8> = (0..carrier_size * run_count)
            .map(|index| (index.wrapping_mul(37) % 251) as u8)
            .collect();
        let mut buffer = pool.acquire_unreserved(input.len()).unwrap();

        assert_eq!(buffer.test_run_count(), run_count);
        assert!(buffer.runs.spilled());
        assert_buffer_invariants(&buffer);
        write_pooled(&mut buffer, &input);
        assert_buffer_invariants(&buffer);

        let frozen = buffer.freeze().into_contiguous();

        assert_eq!(frozen, input);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_dropping_empty_mutable_buffer_returns_every_carrier() {
        let (pool, carrier_size) = test_pool(1, 2);
        let buffer = pool.acquire_unreserved(carrier_size * 2).unwrap();
        assert_eq!(pool.metrics().in_use_bytes(), (carrier_size * 2) as u64);

        drop(buffer);

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

    // `usize::MAX` rounds to a carrier count that overflows the packed-lane
    // limit (`u32::MAX`) only on 64-bit; on 32-bit it rounds to ~2^20 carriers,
    // below the gate, and the acquisition path then scans whole-pool state.
    // The overflow rejection path only has a meaningful fast gate on 64-bit.
    #[cfg(target_pointer_width = "64")]
    #[test]
    fn test_reserve_overflow_preserves_existing_buffer() {
        let (pool, carrier_size) = test_pool(1, 1);
        let mut buffer = pool.acquire_unreserved(carrier_size).unwrap();
        write_pooled(&mut buffer, b"existing");
        let before = (buffer.capacity(), buffer.len(), buffer.remaining_mut());

        assert_eq!(
            buffer.reserve(usize::MAX),
            Err(AcquireError::CapacityOverflow)
        );

        assert_eq!(
            (buffer.capacity(), buffer.len(), buffer.remaining_mut()),
            before
        );
        assert_eq!(buffer.initialized_chunk(), b"existing");
        assert_buffer_invariants(&buffer);
    }

    #[test]
    fn test_publish_prefix_leaves_a_disjoint_mutable_suffix() {
        let (pool, carrier_size) = test_pool(1, 1);
        let mut buffer = pool.acquire_unreserved(carrier_size).unwrap();
        write_pooled(&mut buffer, b"abcdef");

        let first = buffer.publish_prefix(3);
        assert_eq!(first, b"abc"[..]);
        assert_eq!(buffer.len(), 3);
        assert_eq!(buffer.capacity(), carrier_size - 3);
        assert_eq!(buffer.initialized_chunk(), b"def");

        write_pooled(&mut buffer, b"XYZ");
        assert_eq!(first, b"abc"[..]);
        assert_eq!(buffer.initialized_chunk(), b"defXYZ");
        let second = buffer.publish_prefix(6);
        assert_eq!(second, b"defXYZ"[..]);
    }

    #[test]
    fn test_published_prefix_read_races_retained_suffix_write() {
        let (pool, carrier_size) = test_pool(1, 1);
        let prefix_len = carrier_size.min(64);
        let prefix = vec![0x5a; prefix_len];
        let mut buffer = pool.acquire_unreserved(carrier_size).unwrap();
        write_pooled(&mut buffer, &prefix);
        let published = buffer.publish_prefix(prefix_len);
        let suffix = vec![0xa5; buffer.remaining_mut()];
        let reader_expected = prefix.clone();
        let writer_input = suffix.clone();
        let start = Arc::new(Barrier::new(2));

        let reader_start = Arc::clone(&start);
        let reading = thread::spawn(move || {
            reader_start.wait();
            for _ in 0..8 {
                assert_eq!(published, reader_expected);
            }
            published
        });

        let writer_start = Arc::clone(&start);
        let writing = thread::spawn(move || {
            writer_start.wait();
            write_pooled(&mut buffer, &writer_input);
            buffer
        });

        let published = reading.join().unwrap();
        let buffer = writing.join().unwrap();
        assert_eq!(published, prefix);
        assert_eq!(buffer.initialized_chunk(), suffix);

        let frozen = buffer.freeze();
        assert_eq!(frozen.chunk(), suffix);
        drop(published);
        drop(frozen);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[cfg(all(
        not(miri),
        any(
            target_os = "android",
            target_os = "freebsd",
            target_os = "linux",
            target_os = "macos",
            target_os = "windows"
        )
    ))]
    mod guard_page_tests {
        //! Native mapping-boundary tests for pooled mutable buffers.
        //!
        //! Guarded fixtures reserve one inaccessible page on each side of the
        //! range managed by a block:
        //!
        //! ```text
        //! reservation base             block base                  reservation end
        //!       | guard page | one-carrier block range | guard page |
        //!       | inaccessible | prepared as one unit  | inaccessible |
        //! ```
        //!
        //! A block contains one carrier in these fixtures. A one-byte carrier
        //! underflow or overflow therefore lands directly in a guard page,
        //! while normal block preparation never changes either guard.
        //!
        //! The lifecycle test uses two guarded blocks and exercises ordinary
        //! acquisition, writing, prefix publication, freeze, owner return, and
        //! the global audit. The fault test launches this test binary as a
        //! child for each boundary write. The child is expected to fault, so
        //! the parent can verify the native signal without terminating the
        //! complete test process.

        #[cfg(not(s3_tm_tsan))]
        use std::io::Write;
        #[cfg(not(s3_tm_tsan))]
        use std::process::Command;

        #[cfg(all(unix, not(s3_tm_tsan)))]
        use std::os::unix::process::ExitStatusExt;

        use super::super::super::test_util::{test_guarded_pool, write_pooled};
        use super::super::super::CarrierCount;
        use super::*;

        #[cfg(not(s3_tm_tsan))]
        const PROBE_ENV: &str = "AWS_S3_TM_GUARD_PAGE_PROBE";
        #[cfg(not(s3_tm_tsan))]
        const PROBE_TEST: &str = concat!(
            "runtime::buffer_pool::pooled_buf::tests::guard_page_tests::",
            "test_guard_pages_reject_out_of_bounds_writes"
        );
        #[cfg(not(s3_tm_tsan))]
        const READY_MARKER: &str = "S3_TM_GUARD_PROBE_READY";
        #[cfg(not(s3_tm_tsan))]
        const SURVIVED_MARKER: &str = "S3_TM_GUARD_PROBE_SURVIVED";

        /// Exercises the ordinary mutable-to-immutable lifecycle across guarded blocks.
        #[test]
        fn test_guarded_blocks_preserve_buffer_lifecycle() {
            let (pool, carrier_size) = test_guarded_pool(1, 2);
            let input: Vec<u8> = (0..carrier_size * 2)
                .map(|index| (index.wrapping_mul(17) % 251) as u8)
                .collect();
            let mut buffer = pool.acquire_unreserved(input.len()).unwrap();
            write_pooled(&mut buffer, &input);

            let first = buffer.publish_prefix(carrier_size);
            let second = buffer.freeze();
            assert_eq!(first, input[..carrier_size]);
            assert_eq!(second.chunk(), &input[carrier_size..]);

            drop(first);
            drop(second);
            let audit = pool.audit_quiescent();
            assert_eq!(audit.charged_capacity, CarrierCount::ZERO);
            assert_eq!(audit.live_carriers, CarrierCount::ZERO);
        }

        /// Verifies that writes immediately outside a block fault in child processes.
        #[cfg(not(s3_tm_tsan))]
        #[test]
        fn test_guard_pages_reject_out_of_bounds_writes() {
            if let Some(probe) = std::env::var_os(PROBE_ENV) {
                run_guard_page_probe(
                    probe
                        .to_str()
                        .unwrap_or_else(|| panic!("{PROBE_ENV} is not valid UTF-8")),
                );
                return;
            }

            assert_guard_page_fault("underflow");
            assert_guard_page_fault("overflow");
        }

        /// Runs one faulting probe in a child test process.
        #[cfg(not(s3_tm_tsan))]
        fn assert_guard_page_fault(probe: &str) {
            let output = Command::new(std::env::current_exe().expect("current test executable"))
                .arg("--exact")
                .arg(PROBE_TEST)
                .arg("--nocapture")
                .env(PROBE_ENV, probe)
                .output()
                .expect("guard-page child process");
            let status = output.status;
            let stderr = String::from_utf8_lossy(&output.stderr);

            assert!(
                !status.success(),
                "{probe} unexpectedly remained accessible\n{stderr}"
            );
            assert!(
                stderr.contains(READY_MARKER),
                "{probe} failed before reaching the guard write: {status:?}\n{stderr}"
            );
            assert!(
                !stderr.contains(SURVIVED_MARKER),
                "{probe} guard write completed: {status:?}\n{stderr}"
            );

            #[cfg(all(unix, not(s3_tm_asan)))]
            {
                let signal = status.signal();
                assert!(
                    signal == Some(libc::SIGSEGV) || signal == Some(libc::SIGBUS),
                    "{probe} failed without a guard-page signal: {status:?}"
                );
            }

            #[cfg(all(target_os = "windows", not(s3_tm_asan)))]
            assert_eq!(
                status.code(),
                Some(0xC000_0005u32 as i32),
                "{probe} failed without an access violation: {status:?}\n{stderr}"
            );

            // Native ASan may intercept the protection fault and convert it
            // into a nonzero process exit before the OS signal is observable.
            // Require sanitizer evidence so an unrelated child panic cannot
            // satisfy the expected-fault assertion.
            #[cfg(s3_tm_asan)]
            {
                #[cfg(unix)]
                let native_fault =
                    matches!(status.signal(), Some(libc::SIGSEGV) | Some(libc::SIGBUS));
                #[cfg(not(unix))]
                let native_fault = false;
                let sanitizer_fault = stderr.contains("AddressSanitizer:DEADLYSIGNAL")
                    && (stderr.contains("SEGV") || stderr.contains("BUS"));
                assert!(
                    native_fault || sanitizer_fault,
                    "{probe} failed without a native fault or ASan report: {status:?}\n{stderr}"
                );
            }
        }

        /// Writes one byte immediately outside a guarded one-carrier block.
        #[cfg(not(s3_tm_tsan))]
        fn run_guard_page_probe(probe: &str) {
            let (pool, carrier_size) = test_guarded_pool(1, 1);
            let mut buffer = pool.acquire_unreserved(carrier_size).unwrap();
            let ptr = buffer.chunk_mut().as_mut_ptr();
            let reservation = buffer.test_first_reservation_address_range();
            let fault = match probe {
                "underflow" => ptr.wrapping_sub(1),
                // SAFETY: the one-past pointer remains within the complete
                // guarded virtual reservation.
                "overflow" => unsafe { ptr.add(carrier_size) },
                other => panic!("unknown guard-page probe {other}"),
            };
            assert!(
                reservation.contains(&fault.addr()),
                "{probe} address is outside the guarded reservation"
            );
            eprintln!("{READY_MARKER}:{probe}");
            std::io::stderr()
                .flush()
                .expect("flush guard-page readiness marker");
            // SAFETY: the child process deliberately verifies that this
            // inaccessible address terminates execution.
            unsafe { fault.write_volatile(0x5a) };
            eprintln!("{SURVIVED_MARKER}:{probe}");
        }
    }

    #[test]
    fn test_growth_skips_a_fully_published_carrier_entry() {
        let (pool, carrier_size) = test_pool(1, 2);
        let mut buffer = pool.acquire_unreserved(carrier_size).unwrap();
        buffer.put_slice(&vec![0x11; carrier_size]);
        let published = buffer.publish_prefix(carrier_size);

        assert!(buffer.is_empty());
        assert_eq!(buffer.capacity(), 0);
        buffer.reserve(1).unwrap();
        assert_buffer_invariants(&buffer);
        buffer.put_slice(b"next");
        let frozen = buffer.freeze();

        assert_eq!(published, vec![0x11; carrier_size]);
        assert_eq!(frozen.chunk(), b"next");
    }

    #[test]
    fn test_publication_stops_at_each_carrier_boundary() {
        let (pool, carrier_size) = test_pool(2, 2);
        let mut buffer = pool.acquire_unreserved(carrier_size + 3).unwrap();
        let input: Vec<u8> = (0..carrier_size + 3)
            .map(|index| (index % 251) as u8)
            .collect();
        write_pooled(&mut buffer, &input);

        assert_eq!(buffer.initialized_chunk().len(), carrier_size);
        let first = buffer.publish_prefix(carrier_size);
        assert_eq!(first, input[..carrier_size]);
        assert_eq!(buffer.initialized_chunk(), &input[carrier_size..]);
        assert_eq!(buffer.capacity(), carrier_size);
        assert_eq!(pool.metrics().in_use_bytes(), (carrier_size * 2) as u64);

        drop(first);
        assert_eq!(pool.metrics().in_use_bytes(), carrier_size as u64);
        let second = buffer.publish_prefix(3);
        drop(buffer);
        assert_eq!(pool.metrics().in_use_bytes(), carrier_size as u64);
        drop(second);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_published_clones_and_slices_share_one_carrier_return() {
        let (pool, carrier_size) = test_pool(1, 1);
        let mut buffer = pool.acquire_unreserved(carrier_size).unwrap();
        write_pooled(&mut buffer, b"immutable");
        let published = buffer.publish_prefix(9);
        let clone = published.clone();
        let slice = published.slice(2..7);
        drop(buffer);

        assert_eq!(pool.metrics().in_use_bytes(), carrier_size as u64);
        drop(published);
        drop(clone);
        assert_eq!(slice, b"mutab"[..]);
        assert_eq!(pool.metrics().in_use_bytes(), carrier_size as u64);
        drop(slice);
        assert_eq!(pool.metrics().in_use_bytes(), 0);
    }

    #[test]
    fn test_published_owner_holds_direct_authority_until_final_drop() {
        let (pool, carrier_size) = test_pool(2, 2);
        let reservation = pool
            .try_reserve(carrier_size * 2)
            .unwrap()
            .expect("reservation");
        let mut buffer = pool.acquire(&reservation, carrier_size).unwrap();
        write_pooled(&mut buffer, &vec![0x11; carrier_size]);
        let published = buffer.publish_prefix(carrier_size);

        buffer.reserve(1).unwrap();
        write_pooled(&mut buffer, &vec![0x22; carrier_size]);
        assert_eq!(
            buffer.reserve(1),
            Err(AcquireError::ReservationCapacityExceeded)
        );

        drop(published);
        buffer
            .reserve(1)
            .expect("final immutable drop restored direct authority");
    }

    #[test]
    fn test_publication_and_freeze_preserve_bytes_across_representative_lengths() {
        for carriers in 1..=3 {
            let (pool, carrier_size) = test_pool(3, 3);
            let lengths = [
                1,
                carrier_size - 1,
                carrier_size,
                carrier_size + 1,
                carrier_size * carriers - 1,
            ];
            for length in lengths {
                if length == 0 || length > carrier_size * 3 {
                    continue;
                }
                let input: Vec<u8> = (0..length)
                    .map(|index| (index.wrapping_mul(17) % 251) as u8)
                    .collect();
                let mut buffer = pool.acquire_unreserved(length).unwrap();
                write_pooled(&mut buffer, &input);
                let publish_target = length / 2;
                let mut published = 0;
                let mut views = Vec::new();
                while published < publish_target {
                    let count = (publish_target - published)
                        .min(buffer.initialized_chunk().len())
                        .min(97);
                    views.push(buffer.publish_prefix(count));
                    published += count;
                }
                let mut frozen = buffer.freeze();
                let mut output = BytesMut::with_capacity(length);
                for view in views {
                    output.extend_from_slice(&view);
                }
                while frozen.has_remaining() {
                    let count = frozen.chunk().len();
                    output.extend_from_slice(frozen.chunk());
                    frozen.advance(count);
                }
                assert_eq!(output.as_ref(), input.as_slice(), "length {length}");
                assert_eq!(pool.metrics().in_use_bytes(), 0);
            }
        }
    }

    #[test]
    #[should_panic(expected = "publication cursor does not name initialized bytes")]
    fn test_initialized_chunk_rejects_a_stale_publication_cursor() {
        let (pool, carrier_size) = test_pool(2, 2);
        let mut buffer = pool.acquire_unreserved(carrier_size + 1).unwrap();
        write_pooled(&mut buffer, &vec![0x5a; carrier_size + 1]);
        let _first = buffer.publish_prefix(carrier_size);
        buffer.publish_cursor = BufferCursor::START;

        let _ = buffer.initialized_chunk();
    }

    #[test]
    #[should_panic(expected = "published prefix must be nonzero")]
    fn test_publish_prefix_rejects_zero() {
        let (pool, _) = test_pool(1, 1);
        let mut buffer = pool.acquire_unreserved(1).unwrap();
        write_pooled(&mut buffer, b"x");
        let _ = buffer.publish_prefix(0);
    }

    #[test]
    #[should_panic(expected = "published prefix must be nonzero")]
    fn test_publish_prefix_rejects_cross_carrier_count() {
        let (pool, carrier_size) = test_pool(2, 2);
        let mut buffer = pool.acquire_unreserved(carrier_size + 1).unwrap();
        write_pooled(&mut buffer, &vec![0; carrier_size + 1]);
        let _ = buffer.publish_prefix(carrier_size + 1);
    }
}