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

//! Complete carrier acquisition and physical-first final return.
//!
//! Accounting is installed before bitmap ownership. A pending transaction
//! retains both until every carrier has become a guard or rollback has
//! returned all physical ownership before releasing its charges.

use std::fmt;

use super::admission::{
    AdmissionGuard, CoverageDebit, DirectDebitError, ReservationState, ReserveError,
};
use super::arena::{ArenaError, ClaimBatch};
use super::block::{
    BlockError, BlockSlot, CarrierAllocation, CarrierAllocationBatch, CarrierLocation,
};
use super::{invariant_violation, CarrierCount, OwnerReturnPermit, PoolInner};
use crate::runtime::sync::sync::Arc;

/// Failure to acquire a complete mutable carrier batch.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum AcquireError {
    /// The byte request was zero.
    InvalidSize,
    /// The reservation belongs to another pool.
    ForeignReservation,
    /// The reservation no longer permits carrier acquisition.
    ReservationClosed,
    /// The request exceeds the reservation's direct-acquisition authority.
    ReservationCapacityExceeded,
    /// Geometry or accounting cannot represent the request.
    CapacityOverflow,
    /// Physical storage could not be reserved or prepared.
    PhysicalAllocationFailed,
    /// Ownership metadata could not reserve the required capacity.
    MetadataAllocationFailed,
}

impl fmt::Display for AcquireError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidSize => f.write_str("acquisition size must be nonzero"),
            Self::ForeignReservation => f.write_str("reservation belongs to another buffer pool"),
            Self::ReservationClosed => f.write_str("reservation acquisition is closed"),
            Self::ReservationCapacityExceeded => {
                f.write_str("acquisition exceeds reservation capacity")
            }
            Self::CapacityOverflow => {
                f.write_str("acquisition exceeds buffer-pool accounting capacity")
            }
            Self::PhysicalAllocationFailed => f.write_str("physical buffer-pool allocation failed"),
            Self::MetadataAllocationFailed => {
                f.write_str("buffer-pool ownership metadata allocation failed")
            }
        }
    }
}

impl std::error::Error for AcquireError {}

/// Aggregate and optional direct charges not yet owned by carrier guards.
struct AcquisitionDebit {
    /// Pool whose aggregate accounting owns every remaining charge.
    pool: Arc<PoolInner>,
    /// Reservation whose direct authority owns every remaining charge.
    direct: Option<Arc<ReservationState>>,
    /// Charges not yet transferred to carrier guards.
    untransferred: CarrierCount,
    /// Uncovered contribution still owned by the provisional charges.
    aggregate: CoverageDebit,
}

impl AcquisitionDebit {
    /// Installs a complete accounting debit before physical acquisition.
    fn install(
        pool: &Arc<PoolInner>,
        direct: Option<Arc<ReservationState>>,
        count: CarrierCount,
    ) -> Result<Self, AcquireError> {
        if let Some(direct) = direct.as_ref() {
            direct
                .precheck_debit(count)
                .map_err(map_direct_debit_error)?;
        }

        let aggregate = match pool.try_debit_covered(count) {
            Ok(true) => Ok(CoverageDebit::covered()),
            Ok(false) => {
                let mut admission = AdmissionGuard::new(pool.admission.lock());
                PoolInner::debit_and_prepare_locked(pool, &mut admission, count)
            }
            Err(error) => Err(error),
        };
        let aggregate = match aggregate {
            Ok(aggregate) => aggregate,
            Err(error) => return Err(map_reserve_error(error)),
        };
        if let Some(direct) = direct.as_ref() {
            if let Err(error) = direct.try_debit(count) {
                PoolInner::rollback_acquisition_charges(pool, count, aggregate);
                return Err(map_direct_debit_error(error));
            }
        }

        Ok(Self {
            pool: Arc::clone(pool),
            direct,
            untransferred: count,
            aggregate,
        })
    }

    /// Transfers one physical allocation and its accounting provenance.
    fn transfer(&mut self, allocation: CarrierAllocation) -> Arc<CarrierGuard> {
        let Some(untransferred) = self.untransferred.checked_sub(CarrierCount::new(1)) else {
            invariant_violation("acquisition debit transferred too many charges");
        };
        let guard = Arc::new(CarrierGuard {
            pool: Some(Arc::clone(&self.pool)),
            allocation: Some(allocation),
            direct: self.direct.as_ref().map(Arc::clone),
        });
        self.untransferred = untransferred;
        self.aggregate.commit_one();
        guard
    }
}

impl Drop for AcquisitionDebit {
    fn drop(&mut self) {
        if self.untransferred == CarrierCount::ZERO {
            return;
        }
        if let Some(direct) = self.direct.as_ref() {
            direct.release(self.untransferred);
        }
        PoolInner::rollback_acquisition_charges(&self.pool, self.untransferred, self.aggregate);
    }
}

/// Physical and accounting ownership retained until acquisition commits.
struct PendingAcquisition {
    /// Completed carrier owners returned before the remaining transaction.
    guards: Vec<Arc<CarrierGuard>>,
    /// Provisional physical bits returned before accounting rollback.
    claim: Option<ClaimBatch>,
    /// Aggregate and direct charges released last.
    debit: Option<AcquisitionDebit>,
}

impl PendingAcquisition {
    /// Creates a pending transaction after its complete debit is installed.
    fn new(debit: AcquisitionDebit) -> Self {
        Self {
            guards: Vec::new(),
            claim: None,
            debit: Some(debit),
        }
    }

    /// Converts one complete physical batch into grouped carrier ownership.
    fn finish(mut self) -> Result<Vec<Arc<CarrierGuard>>, AcquireError> {
        let claim = self
            .claim
            .take()
            .unwrap_or_else(|| invariant_violation("pending acquisition lost its physical claim"));
        let allocations = claim.finish().map_err(map_arena_error)?;
        let pool = &self
            .debit
            .as_ref()
            .unwrap_or_else(|| invariant_violation("pending acquisition lost its accounting debit"))
            .pool;
        if allocation_failure_injected(pool) {
            return Err(AcquireError::MetadataAllocationFailed);
        }
        self.guards
            .try_reserve_exact(allocations.len())
            .map_err(|_| AcquireError::MetadataAllocationFailed)?;

        let debit = self.debit.as_mut().unwrap_or_else(|| {
            invariant_violation("pending acquisition lost its accounting debit")
        });
        for allocation in allocations {
            self.guards.push(debit.transfer(allocation));
        }
        if debit.untransferred != CarrierCount::ZERO {
            invariant_violation("complete acquisition left untransferred charges");
        }

        Ok(std::mem::take(&mut self.guards))
    }
}

impl Drop for PendingAcquisition {
    fn drop(&mut self) {
        self.guards.clear();
        drop(self.claim.take());
        drop(self.debit.take());
    }
}

/// One physical carrier and its aggregate accounting charge.
pub(super) struct CarrierGuard {
    /// Pool retained through final physical and accounting return.
    pool: Option<Arc<PoolInner>>,
    /// Single-owner physical return capability.
    allocation: Option<CarrierAllocation>,
    /// Optional reservation-local return provenance.
    direct: Option<Arc<ReservationState>>,
}

impl CarrierGuard {
    /// Returns the pool that owns this live carrier.
    fn pool(&self) -> &Arc<PoolInner> {
        self.pool
            .as_ref()
            .unwrap_or_else(|| invariant_violation("live carrier guard lost its pool"))
    }

    /// Returns the physical location used to group adjacent carriers.
    pub(super) fn location(&self) -> CarrierLocation {
        let allocation = self
            .allocation
            .as_ref()
            .unwrap_or_else(|| invariant_violation("live carrier guard lost its allocation"));
        allocation.location()
    }

    /// Returns the concrete slot that roots this carrier's pointer provenance.
    pub(super) fn slot(&self) -> &Arc<BlockSlot> {
        self.allocation
            .as_ref()
            .unwrap_or_else(|| invariant_violation("live carrier guard lost its allocation"))
            .slot()
    }

    /// Returns this carrier's byte capacity.
    pub(super) fn capacity(&self) -> usize {
        self.allocation
            .as_ref()
            .unwrap_or_else(|| invariant_violation("live carrier guard lost its allocation"))
            .capacity()
    }

    /// Returns the first byte of this exclusively owned carrier.
    pub(super) fn ptr(&self) -> std::ptr::NonNull<std::mem::MaybeUninit<u8>> {
        self.allocation
            .as_ref()
            .unwrap_or_else(|| invariant_violation("live carrier guard lost its allocation"))
            .ptr()
    }

    /// Enters pool-local whole-value return publication.
    pub(super) fn begin_owner_return(&self) -> OwnerReturnPermit {
        PoolInner::begin_owner_return(self.pool())
    }

    /// Transfers final return authority into a whole-value batch.
    pub(super) fn into_return(mut self) -> CarrierReturn {
        let pool = self
            .pool
            .take()
            .unwrap_or_else(|| invariant_violation("carrier guard lost aggregate ownership"));
        let allocation = self
            .allocation
            .take()
            .unwrap_or_else(|| invariant_violation("carrier guard lost physical ownership"));
        CarrierReturn {
            pool: Some(pool),
            allocation: Some(allocation),
            direct: self.direct.take(),
        }
    }
}

impl Drop for CarrierGuard {
    fn drop(&mut self) {
        let Some(pool) = self.pool.take() else {
            return;
        };
        let allocation = self
            .allocation
            .take()
            .unwrap_or_else(|| invariant_violation("carrier guard returned its allocation twice"));
        drop(allocation);
        if let Some(direct) = self.direct.as_ref() {
            direct.release(CarrierCount::new(1));
        }
        PoolInner::release_acquisition_charges(&pool, CarrierCount::new(1));
    }
}

/// Final physical and accounting return for one carrier.
pub(super) struct CarrierReturn {
    /// Pool retained until aggregate accounting is repaid.
    pool: Option<Arc<PoolInner>>,
    /// Physical ownership returned before any accounting publication.
    allocation: Option<CarrierAllocation>,
    /// Optional reservation-local owner count.
    direct: Option<Arc<ReservationState>>,
}

impl Drop for CarrierReturn {
    fn drop(&mut self) {
        let Some(pool) = self.pool.take() else {
            return;
        };
        let allocation = self
            .allocation
            .take()
            .unwrap_or_else(|| invariant_violation("carrier return lost physical ownership"));
        drop(allocation);
        if let Some(direct) = self.direct.take() {
            direct.release(CarrierCount::new(1));
        }
        PoolInner::release_acquisition_charges(&pool, CarrierCount::new(1));
    }
}

/// Homogeneous whole-value return with physical-first publication.
pub(super) struct CarrierReturnBatch {
    /// Physical word groups released before accounting on drop.
    physical: Option<CarrierAllocationBatch>,
    /// Shared pool for every owner in this batch.
    pool: Option<Arc<PoolInner>>,
    /// Shared direct reservation state, when present.
    direct: Option<Arc<ReservationState>>,
    /// Owners transferred into this batch.
    count: usize,
}

impl CarrierReturnBatch {
    /// Creates an empty batch for one guard's accounting provenance.
    pub(super) fn for_guard(guard: &CarrierGuard) -> Self {
        Self {
            physical: Some(CarrierAllocationBatch::new()),
            pool: Some(Arc::clone(guard.pool())),
            direct: guard.direct.as_ref().map(Arc::clone),
            count: 0,
        }
    }

    /// Returns whether `guard` has this batch's accounting provenance.
    pub(super) fn accepts(&self, guard: &CarrierGuard) -> bool {
        Arc::ptr_eq(
            self.pool
                .as_ref()
                .unwrap_or_else(|| invariant_violation("carrier batch lost aggregate ownership")),
            guard.pool(),
        ) && option_arc_ptr_eq(self.direct.as_ref(), guard.direct.as_ref())
    }

    /// Transfers one prevalidated homogeneous owner into this batch.
    pub(super) fn push(&mut self, mut returned: CarrierReturn) {
        let pool = returned
            .pool
            .take()
            .unwrap_or_else(|| invariant_violation("carrier batch lost aggregate ownership"));
        let direct = returned.direct.take();
        let current_pool = self
            .pool
            .as_ref()
            .unwrap_or_else(|| invariant_violation("carrier batch lost aggregate ownership"));
        if !Arc::ptr_eq(current_pool, &pool)
            || !option_arc_ptr_eq(self.direct.as_ref(), direct.as_ref())
        {
            invariant_violation("carrier batch mixed accounting owners");
        }

        let allocation = returned
            .allocation
            .as_mut()
            .unwrap_or_else(|| invariant_violation("carrier batch lost physical ownership"));
        self.physical
            .as_mut()
            .unwrap_or_else(|| invariant_violation("finished carrier batch accepted an owner"))
            .push(allocation);
        drop(returned.allocation.take());
        self.count = self
            .count
            .checked_add(1)
            .unwrap_or_else(|| invariant_violation("carrier return count overflowed"));
    }
}

impl Drop for CarrierReturnBatch {
    fn drop(&mut self) {
        drop(self.physical.take());
        if self.count == 0 {
            return;
        }

        let count = CarrierCount::new(self.count);
        if let Some(direct) = self.direct.take() {
            direct.release(count);
        }
        let pool = self
            .pool
            .take()
            .unwrap_or_else(|| invariant_violation("carrier batch lost aggregate ownership"));
        PoolInner::release_acquisition_charges(&pool, count);
    }
}

/// One whole-value return of pooled carrier owners.
///
/// Registers the return with the pool for its lifetime so overlapping returns
/// can observe it. When a reservation is waiting or another whole-value return
/// overlaps, [`push`](Self::push) collects uniquely held owners that share the
/// first owner's accounting provenance into one batch. The batch releases
/// physical ownership and then publishes one aggregate return when this value
/// drops, so admission observes the complete return at once. Otherwise the
/// caller returns owners individually while this registration remains active.
pub(super) struct OwnerReturn {
    // Field order is drop order: the batch publishes while the permit is held.
    /// Collected owners, present only when batching is warranted.
    batch: Option<CarrierReturnBatch>,
    /// Pool registration for the duration of the return.
    _permit: OwnerReturnPermit,
}

impl OwnerReturn {
    /// Starts a whole-value return whose accounting provenance is `first`'s.
    pub(super) fn begin(first: &CarrierGuard) -> Self {
        let permit = first.begin_owner_return();
        let batch = permit
            .should_batch()
            .then(|| CarrierReturnBatch::for_guard(first));
        Self {
            batch,
            _permit: permit,
        }
    }

    /// Returns whether owners should be passed to [`push`](Self::push).
    ///
    /// When `false`, the caller drops its owners individually before this
    /// value drops.
    pub(super) fn is_batched(&self) -> bool {
        self.batch.is_some()
    }

    /// Adds one owner to the batch, or drops it when it cannot be batched.
    ///
    /// An owner still shared with another value, or with different accounting
    /// provenance, drops without joining the batch.
    pub(super) fn push(&mut self, owner: Arc<CarrierGuard>) {
        let Some(batch) = self.batch.as_mut() else {
            drop(owner);
            return;
        };
        if !batch.accepts(&owner) {
            drop(owner);
            return;
        }
        match Arc::try_unwrap(owner) {
            Ok(owner) => batch.push(owner.into_return()),
            Err(shared) => drop(shared),
        }
    }
}

/// Returns whether two optional owners name the same reservation state.
fn option_arc_ptr_eq<T>(left: Option<&Arc<T>>, right: Option<&Arc<T>>) -> bool {
    match (left, right) {
        (Some(left), Some(right)) => Arc::ptr_eq(left, right),
        (None, None) => true,
        _ => false,
    }
}

/// Installs accounting, acquires a complete physical batch, and groups it.
pub(super) fn acquire_count(
    pool: &Arc<PoolInner>,
    direct: Option<Arc<ReservationState>>,
    count: CarrierCount,
) -> Result<Vec<Arc<CarrierGuard>>, AcquireError> {
    let debit = AcquisitionDebit::install(pool, direct, count)?;
    #[cfg(test)]
    pool.test_hooks.record_acquisition_attempt();
    let mut pending = PendingAcquisition::new(debit);
    pending.claim = Some(
        pool.arena
            .claim_optimistic(count)
            .map_err(map_arena_error)?,
    );

    if !pending
        .claim
        .as_ref()
        .unwrap_or_else(|| invariant_violation("pending acquisition lost its claim"))
        .is_complete()
    {
        let fallback = {
            let mut admission = AdmissionGuard::new(pool.admission.lock());
            pool.arena.complete_claim_serialized(
                &mut admission,
                pending
                    .claim
                    .as_mut()
                    .unwrap_or_else(|| invariant_violation("pending acquisition lost its claim")),
            )
        };
        if let Err(error) = fallback {
            PoolInner::request_cleanup_after_arena_error(pool, &error);
            return Err(map_arena_error(error));
        }
    }

    pending.finish()
}

/// Returns whether test injection fails this metadata allocation boundary.
#[cfg(test)]
pub(super) fn allocation_failure_injected(pool: &PoolInner) -> bool {
    pool.test_hooks.take_acquisition_allocation_failure()
}

/// Removes the metadata failure-injection seam from production paths.
#[cfg(not(test))]
#[inline(always)]
pub(super) fn allocation_failure_injected(_pool: &PoolInner) -> bool {
    false
}

fn map_direct_debit_error(error: DirectDebitError) -> AcquireError {
    match error {
        DirectDebitError::Closed => AcquireError::ReservationClosed,
        DirectDebitError::CapacityExceeded => AcquireError::ReservationCapacityExceeded,
        DirectDebitError::CapacityOverflow => AcquireError::CapacityOverflow,
    }
}

fn map_reserve_error(error: ReserveError) -> AcquireError {
    match error {
        ReserveError::InvalidSize => AcquireError::InvalidSize,
        ReserveError::ExceedsCapacity => AcquireError::CapacityOverflow,
        ReserveError::PhysicalPreparationFailed => AcquireError::PhysicalAllocationFailed,
        ReserveError::MetadataAllocationFailed => AcquireError::MetadataAllocationFailed,
        ReserveError::CapacityOverflow => AcquireError::CapacityOverflow,
    }
}

fn map_arena_error(error: ArenaError) -> AcquireError {
    match error {
        ArenaError::Block(BlockError::PreparedCapacityOverflow)
        | ArenaError::SlotIdExhausted
        | ArenaError::RegistryCapacityOverflow
        | ArenaError::AddressOverflow { .. }
        | ArenaError::ScanSpaceOverflow { .. } => AcquireError::CapacityOverflow,
        ArenaError::Block(BlockError::Allocation(_)) | ArenaError::Allocation(_) => {
            AcquireError::MetadataAllocationFailed
        }
        ArenaError::Block(_)
        | ArenaError::InvalidScanBudget
        | ArenaError::InvalidClaimCount
        | ArenaError::IncompleteClaim { .. }
        | ArenaError::AddressOverlap { .. } => AcquireError::PhysicalAllocationFailed,
    }
}

#[cfg(all(test, not(s3_tm_loom)))]
mod tests {
    use std::sync::mpsc;
    use std::task::Poll;
    use std::time::Duration;

    use super::super::block::{BlockSlot, TrimBlocked};
    use super::super::test_util::{claiming_waker, poll_reserve, test_pool_with_scan as test_pool};
    use super::super::virtual_memory::VirtualMemoryOperation;
    use super::super::{PooledBufMut, Reservation};
    use super::*;

    #[test]
    fn test_metadata_failures_retain_their_error_classification() {
        assert_eq!(
            map_reserve_error(ReserveError::MetadataAllocationFailed),
            AcquireError::MetadataAllocationFailed
        );

        let arena_error = Vec::<u8>::new().try_reserve(usize::MAX).unwrap_err();
        assert_eq!(
            map_arena_error(ArenaError::Allocation(arena_error)),
            AcquireError::MetadataAllocationFailed
        );

        let block_error = Vec::<u8>::new().try_reserve(usize::MAX).unwrap_err();
        assert_eq!(
            map_arena_error(ArenaError::Block(BlockError::Allocation(block_error))),
            AcquireError::MetadataAllocationFailed
        );

        let preparation_error = Vec::<u8>::new().try_reserve(usize::MAX).unwrap_err();
        assert_eq!(
            super::super::map_preparation_error(ArenaError::Allocation(preparation_error)),
            ReserveError::MetadataAllocationFailed
        );
    }

    #[test]
    fn test_acquisition_rejects_zero_foreign_and_excess_requests() {
        let (first, carrier_size) = test_pool(1, 1, 1);
        let (second, _) = test_pool(1, 1, 1);
        let reservation = first
            .try_reserve(carrier_size)
            .unwrap()
            .expect("initial reservation");

        assert!(matches!(
            first.acquire_unreserved(0),
            Err(AcquireError::InvalidSize)
        ));
        assert!(matches!(
            second.acquire(&reservation, carrier_size),
            Err(AcquireError::ForeignReservation)
        ));
        assert!(matches!(
            first.acquire(&reservation, carrier_size * 2),
            Err(AcquireError::ReservationCapacityExceeded)
        ));
        assert_eq!(
            first.inner.test_accounting_state(),
            (
                CarrierCount::new(1),
                CarrierCount::new(1),
                CarrierCount::new(1),
                CarrierCount::ZERO,
                0,
            )
        );

        let direct = Arc::clone(reservation.acquisition_state().unwrap());
        reservation.close_acquisition();
        assert!(matches!(
            acquire_count(&first.inner, Some(direct), CarrierCount::new(1)),
            Err(AcquireError::ReservationClosed)
        ));
    }

    #[test]
    fn test_reserved_acquisition_returns_direct_and_aggregate_authority() {
        let (pool, carrier_size) = test_pool(2, 2, 1);
        let reservation = pool
            .try_reserve(carrier_size * 2)
            .unwrap()
            .expect("reservation");
        let direct = Arc::clone(reservation.acquisition_state().unwrap());

        let acquired = pool.acquire(&reservation, carrier_size + 1).unwrap();

        assert_eq!(acquired.capacity(), carrier_size * 2);
        assert_eq!(acquired.test_run_count(), 1);
        assert_eq!(direct.test_owner_state(), (false, CarrierCount::new(2)));
        assert_eq!(
            pool.inner.test_accounting_state(),
            (
                CarrierCount::new(2),
                CarrierCount::new(2),
                CarrierCount::ZERO,
                CarrierCount::ZERO,
                0,
            )
        );

        drop(acquired);
        assert_eq!(direct.test_owner_state(), (false, CarrierCount::ZERO));
        assert_eq!(pool.inner.test_accounting_state().2, CarrierCount::new(2));
        reservation.close_acquisition();
        assert_eq!(
            pool.inner.test_accounting_state(),
            (
                CarrierCount::new(2),
                CarrierCount::ZERO,
                CarrierCount::ZERO,
                CarrierCount::ZERO,
                0,
            )
        );
    }

    #[test]
    fn test_unreserved_shortfall_prepares_and_groups_complete_runs() {
        let (pool, carrier_size) = test_pool(2, 1, 1);

        let acquired = pool.acquire_unreserved(carrier_size * 3).unwrap();

        assert_eq!(acquired.capacity(), carrier_size * 3);
        assert_eq!(acquired.test_run_count(), 2);
        assert_eq!(acquired.test_run_capacity(0), carrier_size * 2);
        assert_eq!(acquired.test_run_capacity(1), carrier_size);
        assert_eq!(
            pool.inner.test_accounting_state(),
            (
                CarrierCount::new(4),
                CarrierCount::ZERO,
                CarrierCount::ZERO,
                CarrierCount::new(3),
                0,
            )
        );

        drop(acquired);
        assert_eq!(
            pool.inner.test_accounting_state(),
            (
                CarrierCount::new(4),
                CarrierCount::ZERO,
                CarrierCount::ZERO,
                CarrierCount::ZERO,
                0,
            )
        );
    }

    #[test]
    fn test_partial_optimistic_claim_completes_through_fallback() {
        let (pool, carrier_size) = test_pool(65, 65, 1);
        let reservation = pool
            .try_reserve(carrier_size * 65)
            .unwrap()
            .expect("reservation");

        let acquired = pool.acquire(&reservation, carrier_size * 65).unwrap();

        assert_eq!(acquired.capacity(), carrier_size * 65);
        assert_eq!(acquired.test_run_count(), 1);
        assert_eq!(pool.inner.arena.diagnostics().serialized_fallbacks, 1);
    }

    #[test]
    fn test_preparation_failure_restores_direct_and_aggregate_debits() {
        let (pool, carrier_size) = test_pool(1, 1, 1);
        let reservation = pool
            .try_reserve(carrier_size)
            .unwrap()
            .expect("reservation");
        let direct = Arc::clone(reservation.acquisition_state().unwrap());
        let occupying = pool.acquire_unreserved(carrier_size).unwrap();
        let failed_slot = pool.inner.arena.reserve_slot().unwrap();
        failed_slot.inject_failure_once(VirtualMemoryOperation::Prepare);

        assert!(matches!(
            pool.acquire(&reservation, carrier_size),
            Err(AcquireError::PhysicalAllocationFailed)
        ));
        assert_eq!(direct.test_owner_state(), (false, CarrierCount::ZERO));
        assert_eq!(
            pool.inner.test_accounting_state(),
            (
                CarrierCount::new(1),
                CarrierCount::new(1),
                CarrierCount::ZERO,
                CarrierCount::ZERO,
                0,
            )
        );

        let retry = pool.acquire(&reservation, carrier_size).unwrap();
        assert_eq!(retry.capacity(), carrier_size);
        drop(retry);
        drop(occupying);
    }

    #[test]
    fn test_failed_covered_acquisition_restores_prior_coverage_classification() {
        let (pool, carrier_size) = test_pool(2, 6, 1);
        let uncovered = pool.acquire_unreserved(carrier_size * 2).unwrap();
        let reservation = pool
            .try_reserve(carrier_size * 4)
            .unwrap()
            .expect("reservation");
        let before = pool.inner.test_accounting_state();
        assert_eq!(
            before,
            (
                CarrierCount::new(6),
                CarrierCount::new(4),
                CarrierCount::new(4),
                CarrierCount::new(2),
                0,
            )
        );
        pool.inject_acquisition_allocation_failure(1);

        assert!(matches!(
            pool.acquire(&reservation, carrier_size),
            Err(AcquireError::MetadataAllocationFailed)
        ));

        assert_eq!(pool.inner.test_accounting_state(), before);
        let retry = pool
            .acquire(&reservation, carrier_size)
            .expect("rollback preserved covered acquisition authority");
        drop(retry);
        drop(reservation);
        drop(uncovered);
    }

    #[test]
    fn test_covered_acquisition_does_not_enter_admission() {
        let (pool, carrier_size) = test_pool(1, 1, 1);
        let reservation = pool
            .try_reserve(carrier_size)
            .unwrap()
            .expect("reservation");
        let admission = pool.inner.admission.lock();
        let worker_pool = pool.clone();
        let (acquired_tx, acquired_rx) = mpsc::channel();
        let (release_tx, release_rx) = mpsc::channel();

        let worker = std::thread::spawn(move || {
            let acquired = worker_pool.acquire(&reservation, carrier_size);
            let result = match &acquired {
                Ok(runs) => Ok(runs.capacity()),
                Err(error) => Err(*error),
            };
            acquired_tx.send(result).unwrap();
            release_rx.recv().unwrap();
            drop(acquired);
            drop(reservation);
        });

        assert_eq!(
            acquired_rx
                .recv_timeout(Duration::from_secs(2))
                .expect("covered acquisition blocked on admission")
                .unwrap(),
            carrier_size
        );
        drop(admission);
        release_tx.send(()).unwrap();
        worker.join().unwrap();
    }

    #[test]
    fn test_pending_rollback_returns_bits_before_releasing_charges() {
        let (pool, _) = test_pool(2, 1, 1);
        let count = CarrierCount::new(2);
        let debit = AcquisitionDebit::install(&pool.inner, None, count).unwrap();
        let claim = pool.inner.arena.claim_optimistic(count).unwrap();
        assert!(claim.is_complete());
        let mut pending = PendingAcquisition::new(debit);
        pending.claim = Some(claim);

        drop(pending);

        assert_eq!(pool.inner.test_accounting_state().3, CarrierCount::ZERO);
        let reclaimed = pool.inner.arena.claim_optimistic(count).unwrap();
        assert!(reclaimed.is_complete());
        drop(reclaimed);
    }

    #[test]
    fn test_uncovered_return_skips_admission_when_fifo_is_empty() {
        let (pool, carrier_size) = test_pool(1, 1, 1);
        let reservation = pool
            .try_reserve(carrier_size)
            .unwrap()
            .expect("reservation");
        let acquired = pool.acquire(&reservation, carrier_size).unwrap();
        reservation.close_acquisition();

        drop(acquired);

        assert_eq!(pool.return_admission_entries(), 0);
        assert_eq!(pool.inner.test_accounting_state().3, CarrierCount::ZERO);
    }

    #[test]
    fn test_uncovered_return_drains_fifo_after_physical_return() {
        let (pool, carrier_size) = test_pool(1, 2, 1);
        let first = pool
            .try_reserve(carrier_size)
            .unwrap()
            .expect("first reservation");
        let first_acquired = pool.acquire(&first, carrier_size).unwrap();
        first.close_acquisition();

        let second = pool
            .try_reserve(carrier_size)
            .unwrap()
            .expect("second reservation");
        let second_acquired = pool.acquire(&second, carrier_size).unwrap();
        let (waker, wake_state) = claiming_waker(pool.clone());
        let mut queued = pool.reserve(carrier_size);
        assert!(poll_reserve(&mut queued, &waker).is_pending());

        drop(first_acquired);

        assert_eq!(pool.return_admission_entries(), 1);
        assert_eq!(wake_state.wakes(), 1);
        assert!(
            wake_state.claimed(),
            "waiter reentry ran before the returned physical bit was reusable"
        );
        let third = match poll_reserve(&mut queued, &waker) {
            Poll::Ready(Ok(reservation)) => reservation,
            Poll::Ready(Err(error)) => panic!("queued reservation failed: {error}"),
            Poll::Pending => panic!("uncovered repayment stranded an eligible waiter"),
        };
        drop(second_acquired);
        drop(second);
        drop(third);
    }

    #[test]
    fn test_return_and_close_orders_converge() {
        fn run(close_first: bool) -> (CarrierCount, CarrierCount, CarrierCount) {
            let (pool, carrier_size) = test_pool(1, 1, 1);
            let reservation = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("reservation");
            let acquired = pool.acquire(&reservation, carrier_size).unwrap();
            if close_first {
                reservation.close_acquisition();
                drop(acquired);
            } else {
                drop(acquired);
                reservation.close_acquisition();
            }
            let (_, active, available, uncovered, _) = pool.inner.test_accounting_state();
            (active, available, uncovered)
        }

        assert_eq!(
            run(false),
            (CarrierCount::ZERO, CarrierCount::ZERO, CarrierCount::ZERO)
        );
        assert_eq!(run(true), run(false));
    }

    #[test]
    fn test_close_preserves_other_reservation_coverage_under_normal_ceiling() {
        let (pool, carrier_size) = test_pool(4, 8, 1);
        let first = pool
            .try_reserve(carrier_size * 3)
            .unwrap()
            .expect("first reservation");
        let first_acquired = pool.acquire(&first, carrier_size * 3).unwrap();
        let second = pool
            .try_reserve(carrier_size * 3)
            .unwrap()
            .expect("second reservation");

        first.close_acquisition();

        let closed = pool.metrics();
        assert_eq!(
            closed.active_planned_demand_bytes(),
            (carrier_size * 3) as u64
        );
        assert_eq!(closed.in_use_bytes(), (carrier_size * 3) as u64);
        assert_eq!(closed.admitted_bytes(), (carrier_size * 6) as u64);
        assert!(
            pool.try_reserve(carrier_size * 4).unwrap().is_none(),
            "close made another reservation's coverage available for a new grant"
        );

        let second_acquired = pool.acquire(&second, carrier_size * 3).unwrap();
        assert!(first_acquired.capacity() + second_acquired.capacity() <= carrier_size * 8);

        drop(first_acquired);
        let third = pool
            .try_reserve(carrier_size * 4)
            .unwrap()
            .expect("returned ownership restores normal headroom");
        let third_acquired = pool.acquire(&third, carrier_size * 4).unwrap();
        assert!(second_acquired.capacity() + third_acquired.capacity() <= carrier_size * 8);

        drop(second_acquired);
        drop(second);
        drop(third_acquired);
        drop(third);
    }

    #[test]
    fn test_reserved_composition_preserves_normal_capacity() {
        const CONFIGURED_CARRIERS: usize = 4;
        const RESERVATION_SLOTS: usize = 4;
        const SEQUENCES: u64 = 32;
        const STEPS: usize = 48;

        struct Actor {
            reservation: Option<Reservation>,
            envelope: usize,
            outstanding: usize,
            used: bool,
        }

        struct Owner {
            actor: usize,
            carriers: usize,
            runs: PooledBufMut,
        }

        fn next(state: &mut u64) -> usize {
            *state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            (*state >> 32) as usize
        }

        for sequence in 0..SEQUENCES {
            let (pool, carrier_size) = test_pool(CONFIGURED_CARRIERS, CONFIGURED_CARRIERS, 1);
            let mut state = sequence + 1;
            let mut actors: Vec<Actor> = (0..RESERVATION_SLOTS)
                .map(|_| Actor {
                    reservation: None,
                    envelope: 0,
                    outstanding: 0,
                    used: false,
                })
                .collect();
            let mut owners = Vec::<Owner>::new();

            for _ in 0..STEPS {
                match next(&mut state) % 4 {
                    0 => {
                        let Some(actor) = actors.iter_mut().find(|actor| !actor.used) else {
                            continue;
                        };
                        let envelope = 1 + next(&mut state) % (CONFIGURED_CARRIERS - 1);
                        if let Some(reservation) =
                            pool.try_reserve(envelope * carrier_size).unwrap()
                        {
                            actor.reservation = Some(reservation);
                            actor.envelope = envelope;
                            actor.used = true;
                        }
                    }
                    1 => {
                        let candidates: Vec<usize> = actors
                            .iter()
                            .enumerate()
                            .filter_map(|(index, actor)| {
                                (actor.reservation.is_some() && actor.outstanding < actor.envelope)
                                    .then_some(index)
                            })
                            .collect();
                        if candidates.is_empty() {
                            continue;
                        }
                        let actor_index = candidates[next(&mut state) % candidates.len()];
                        let actor = &mut actors[actor_index];
                        let remaining = actor.envelope - actor.outstanding;
                        let carriers = 1 + next(&mut state) % remaining;
                        let runs = pool
                            .acquire(actor.reservation.as_ref().unwrap(), carriers * carrier_size)
                            .unwrap();
                        actor.outstanding += carriers;
                        owners.push(Owner {
                            actor: actor_index,
                            carriers,
                            runs,
                        });
                    }
                    2 => {
                        let open: Vec<usize> = actors
                            .iter()
                            .enumerate()
                            .filter_map(|(index, actor)| actor.reservation.as_ref().map(|_| index))
                            .collect();
                        if let Some(index) = open.get(next(&mut state) % open.len().max(1)) {
                            actors[*index]
                                .reservation
                                .take()
                                .unwrap()
                                .close_acquisition();
                        }
                    }
                    _ => {
                        if owners.is_empty() {
                            continue;
                        }
                        let index = next(&mut state) % owners.len();
                        let owner = owners.swap_remove(index);
                        actors[owner.actor].outstanding -= owner.carriers;
                        drop(owner.runs);
                    }
                }

                let live: usize = owners.iter().map(|owner| owner.carriers).sum();
                let active: usize = actors
                    .iter()
                    .filter_map(|actor| actor.reservation.as_ref().map(|_| actor.envelope))
                    .sum();
                let metrics = pool.metrics();
                assert!(
                    live <= CONFIGURED_CARRIERS,
                    "sequence {sequence} retained {live} carriers above the normal ceiling"
                );
                assert_eq!(
                    metrics.in_use_bytes(),
                    (live * carrier_size) as u64,
                    "sequence {sequence} lost or duplicated a carrier charge"
                );
                assert_eq!(
                    metrics.active_planned_demand_bytes(),
                    (active * carrier_size) as u64,
                    "sequence {sequence} diverged from its open envelopes"
                );
            }

            for actor in &mut actors {
                drop(actor.reservation.take());
            }
            drop(owners);
            let metrics = pool.metrics();
            assert_eq!(metrics.active_planned_demand_bytes(), 0);
            assert_eq!(metrics.in_use_bytes(), 0);
            assert_eq!(metrics.admitted_bytes(), 0);
        }
    }

    #[test]
    fn test_carrier_owner_retains_pool_until_final_return() {
        let (pool, carrier_size) = test_pool(1, 1, 1);
        let weak = Arc::downgrade(&pool.inner);
        let acquired = pool.acquire_unreserved(carrier_size).unwrap();

        drop(pool);
        assert!(weak.upgrade().is_some());
        drop(acquired);
        assert!(weak.upgrade().is_none());
    }

    #[test]
    fn test_acquisition_ownership_is_send_and_sync() {
        fn assert_send<T: Send>() {}
        fn assert_send_sync<T: Send + Sync>() {}

        assert_send::<PooledBufMut>();
        assert_send_sync::<CarrierGuard>();
    }

    #[test]
    fn test_metadata_allocation_failure_rolls_back_every_commit_boundary() {
        for boundary in 1..=4 {
            let (pool, carrier_size) = test_pool(2, 2, 1);
            let reservation = pool
                .try_reserve(carrier_size * 2)
                .unwrap()
                .expect("reservation");
            let direct = Arc::clone(reservation.acquisition_state().unwrap());
            pool.inject_acquisition_allocation_failure(boundary);

            assert!(
                matches!(
                    pool.acquire(&reservation, carrier_size * 2),
                    Err(AcquireError::MetadataAllocationFailed)
                ),
                "metadata boundary {boundary} did not fail"
            );
            assert_eq!(
                direct.test_owner_state(),
                (false, CarrierCount::ZERO),
                "metadata boundary {boundary} leaked direct authority"
            );
            let metrics = pool.metrics();
            assert_eq!(
                metrics.in_use_bytes(),
                0,
                "metadata boundary {boundary} leaked aggregate charges"
            );
            assert_eq!(
                metrics.active_planned_demand_bytes(),
                (carrier_size * 2) as u64
            );

            let retry = pool
                .acquire(&reservation, carrier_size * 2)
                .expect("pool remains usable after metadata failure");
            drop(retry);
            drop(reservation);
        }
    }

    #[test]
    fn test_in_flight_shortfall_charge_preserves_trim_floor() {
        let (pool, _) = test_pool(2, 1, 1);
        let debit = AcquisitionDebit::install(&pool.inner, None, CarrierCount::new(1)).unwrap();
        let candidate = pool
            .inner
            .arena
            .select_trim_candidate()
            .expect("prepared free block");

        {
            let mut admission = AdmissionGuard::new(pool.inner.admission.lock());
            let floor = admission.acquisition_floor(&pool.inner.coverage).unwrap();
            assert!(matches!(
                BlockSlot::start_trim(&candidate, admission.prepared_capacity_mut(), floor,),
                Err(TrimBlocked::FloorViolation)
            ));
        }

        drop(debit);
        let cleanup = {
            let mut admission = AdmissionGuard::new(pool.inner.admission.lock());
            let floor = admission.acquisition_floor(&pool.inner.coverage).unwrap();
            BlockSlot::start_trim(&candidate, admission.prepared_capacity_mut(), floor)
                .expect("returned charge permits trim")
        };
        cleanup.finish().unwrap();
        assert_eq!(pool.metrics().prepared_capacity_bytes(), 0);
    }
}

#[cfg(all(test, s3_tm_loom))]
mod loom_tests {
    use std::task::Poll;

    use super::super::block::{BlockSlot, TrimBlocked};
    use super::super::test_util::{
        counting_waker, poll_reserve, test_single_carrier_pool as test_pool,
    };
    use super::*;
    use crate::runtime::sync::sync::atomic::Ordering;
    use crate::runtime::sync::sync::Arc;
    use crate::runtime::sync::thread;

    #[test]
    fn test_final_return_racing_close_converges() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(1);
            let reservation = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("reservation");
            let acquired = pool.acquire(&reservation, carrier_size).unwrap();

            let closing = thread::spawn(move || reservation.close_acquisition());
            let returning = thread::spawn(move || drop(acquired));
            closing.join().unwrap();
            returning.join().unwrap();

            let (_, active, available, uncovered, _) = pool.inner.test_accounting_state();
            assert_eq!(active, CarrierCount::ZERO);
            assert_eq!(available, CarrierCount::ZERO);
            assert_eq!(uncovered, CarrierCount::ZERO);
        });
    }

    #[test]
    fn test_close_cannot_free_another_reservations_coverage_for_grant() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(2);
            let first = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("first reservation");
            let first_acquired = pool.acquire(&first, carrier_size).unwrap();
            let second = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("second reservation");

            let closing = thread::spawn(move || first.close_acquisition());
            let granting_pool = pool.clone();
            let granting = thread::spawn(move || granting_pool.try_reserve(carrier_size).unwrap());

            closing.join().unwrap();
            assert!(
                granting.join().unwrap().is_none(),
                "close admitted work against another reservation's coverage"
            );
            let (_, active, available, uncovered, _) = pool.inner.test_accounting_state();
            assert_eq!(active, CarrierCount::new(1));
            assert_eq!(available, CarrierCount::new(1));
            assert_eq!(uncovered, CarrierCount::new(1));

            drop(first_acquired);
            drop(second);
        });
    }

    #[test]
    fn test_concurrent_acquisitions_consume_direct_authority_once() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(1);
            let reservation = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("reservation");
            let direct = Arc::clone(reservation.acquisition_state().unwrap());

            let first_pool = Arc::clone(&pool.inner);
            let first_direct = Arc::clone(&direct);
            let first = thread::spawn(move || {
                acquire_count(&first_pool, Some(first_direct), CarrierCount::new(1))
            });
            let second_pool = Arc::clone(&pool.inner);
            let second = thread::spawn(move || {
                acquire_count(&second_pool, Some(direct), CarrierCount::new(1))
            });

            let first = first.join().unwrap();
            let second = second.join().unwrap();
            assert_eq!(usize::from(first.is_ok()) + usize::from(second.is_ok()), 1);
            assert!(
                matches!(first, Err(AcquireError::ReservationCapacityExceeded))
                    || matches!(second, Err(AcquireError::ReservationCapacityExceeded))
            );
            drop(first);
            drop(second);
            drop(reservation);
            let (_, active, available, uncovered, _) = pool.inner.test_accounting_state();
            assert_eq!(active, CarrierCount::ZERO);
            assert_eq!(available, CarrierCount::ZERO);
            assert_eq!(uncovered, CarrierCount::ZERO);
        });
    }

    #[test]
    fn test_final_return_racing_waiter_enqueue_cannot_strand_grant() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(2);
            let returned = pool.acquire_unreserved(carrier_size).unwrap();
            let holder = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("reservation within configured capacity");
            let (waker, wake_count) = counting_waker();
            let mut future = pool.reserve(carrier_size);

            let returning = thread::spawn(move || drop(returned));
            let first_poll = poll_reserve(&mut future, &waker);
            returning.join().unwrap();
            let granted = match first_poll {
                Poll::Ready(Ok(reservation)) => reservation,
                Poll::Ready(Err(error)) => panic!("reservation failed: {error}"),
                Poll::Pending => match poll_reserve(&mut future, &waker) {
                    Poll::Ready(Ok(reservation)) => reservation,
                    Poll::Ready(Err(error)) => panic!("reservation failed: {error}"),
                    Poll::Pending => panic!("return stranded an eligible waiter"),
                },
            };

            assert!(wake_count.load(Ordering::Acquire) <= 1);
            drop(holder);
            drop(granted);
            let (_, active, available, uncovered, waiters) = pool.inner.test_accounting_state();
            assert_eq!(active, CarrierCount::ZERO);
            assert_eq!(available, CarrierCount::ZERO);
            assert_eq!(uncovered, CarrierCount::ZERO);
            assert_eq!(waiters, 0);
        });
    }

    #[test]
    fn test_close_racing_direct_debit_rollback_cannot_reopen_authority() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(1);
            let reservation = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("reservation");
            let direct = Arc::clone(reservation.acquisition_state().unwrap());

            let debiting_pool = Arc::clone(&pool.inner);
            let debiting_direct = Arc::clone(&direct);
            let debiting = thread::spawn(move || {
                AcquisitionDebit::install(
                    &debiting_pool,
                    Some(debiting_direct),
                    CarrierCount::new(1),
                )
            });
            let closing = thread::spawn(move || reservation.close_acquisition());
            let debit = debiting.join().unwrap();
            closing.join().unwrap();

            match debit {
                Ok(debit) => {
                    assert_eq!(direct.test_owner_state(), (true, CarrierCount::new(1)));
                    let (_, active, available, uncovered, _) = pool.inner.test_accounting_state();
                    assert_eq!(active, CarrierCount::ZERO);
                    assert_eq!(available, CarrierCount::ZERO);
                    assert_eq!(uncovered, CarrierCount::new(1));
                    drop(debit);
                }
                Err(AcquireError::ReservationClosed) => {
                    assert_eq!(direct.test_owner_state(), (true, CarrierCount::ZERO));
                }
                Err(error) => panic!("unexpected acquisition debit error: {error}"),
            }

            assert_eq!(direct.test_owner_state(), (true, CarrierCount::ZERO));
            let (_, active, available, uncovered, _) = pool.inner.test_accounting_state();
            assert_eq!(active, CarrierCount::ZERO);
            assert_eq!(available, CarrierCount::ZERO);
            assert_eq!(uncovered, CarrierCount::ZERO);
        });
    }

    #[test]
    fn test_shortfall_rollback_racing_waiter_enqueue_cannot_strand_grant() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(2);
            let debit = AcquisitionDebit::install(&pool.inner, None, CarrierCount::new(1)).unwrap();
            let holder = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("reservation within configured capacity");
            let (waker, wake_count) = counting_waker();
            let mut future = pool.reserve(carrier_size);

            let rolling_back = thread::spawn(move || drop(debit));
            let first_poll = poll_reserve(&mut future, &waker);
            rolling_back.join().unwrap();
            let granted = match first_poll {
                Poll::Ready(Ok(reservation)) => reservation,
                Poll::Ready(Err(error)) => panic!("reservation failed: {error}"),
                Poll::Pending => match poll_reserve(&mut future, &waker) {
                    Poll::Ready(Ok(reservation)) => reservation,
                    Poll::Ready(Err(error)) => panic!("reservation failed: {error}"),
                    Poll::Pending => panic!("rollback stranded an eligible waiter"),
                },
            };

            assert!(wake_count.load(Ordering::Acquire) <= 1);
            drop(holder);
            drop(granted);
            let (_, active, available, uncovered, waiters) = pool.inner.test_accounting_state();
            assert_eq!(active, CarrierCount::ZERO);
            assert_eq!(available, CarrierCount::ZERO);
            assert_eq!(uncovered, CarrierCount::ZERO);
            assert_eq!(waiters, 0);
        });
    }

    #[test]
    fn test_manager_local_teardown_preserves_escaped_owner_and_shared_pool() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(2);
            let manager_pool = pool.clone();
            let reservation = manager_pool
                .try_reserve(carrier_size * 2)
                .unwrap()
                .expect("manager reservation");
            let escaped = manager_pool.acquire(&reservation, carrier_size).unwrap();
            let (waker, _) = counting_waker();
            let mut queued = manager_pool.reserve(carrier_size);
            assert!(poll_reserve(&mut queued, &waker).is_pending());
            drop(manager_pool);

            let cancelling = thread::spawn(move || drop(queued));
            let closing = thread::spawn(move || reservation.close_acquisition());
            cancelling.join().unwrap();
            closing.join().unwrap();

            let retained = pool.metrics();
            assert_eq!(retained.active_planned_demand_bytes(), 0);
            assert_eq!(retained.in_use_bytes(), carrier_size as u64);
            assert_eq!(retained.waiting_requests(), 0);

            let shared = pool
                .try_reserve(carrier_size)
                .unwrap()
                .expect("shared pool remains operational");
            drop(shared);
            drop(escaped);
            let released = pool.metrics();
            assert_eq!(released.admitted_bytes(), 0);
            assert_eq!(released.in_use_bytes(), 0);
        });
    }

    #[test]
    fn test_published_shortfall_floor_blocks_trim_during_unlocked_claim() {
        loom::model(|| {
            let (pool, _) = test_pool(1);
            let debit = AcquisitionDebit::install(&pool.inner, None, CarrierCount::new(1)).unwrap();
            let candidate = pool
                .inner
                .arena
                .select_trim_candidate()
                .expect("prepared free block");

            let claiming_pool = pool.clone();
            let claiming = thread::spawn(move || {
                claiming_pool
                    .inner
                    .arena
                    .claim_optimistic(CarrierCount::new(1))
                    .unwrap()
            });
            let trimming_pool = pool.clone();
            let trimming = thread::spawn(move || {
                let mut admission = AdmissionGuard::new(trimming_pool.inner.admission.lock());
                let floor = admission
                    .acquisition_floor(&trimming_pool.inner.coverage)
                    .unwrap();
                assert!(matches!(
                    BlockSlot::start_trim(&candidate, admission.prepared_capacity_mut(), floor,),
                    Err(TrimBlocked::FloorViolation)
                ));
            });

            let claim = claiming.join().unwrap();
            trimming.join().unwrap();
            assert!(claim.is_complete());
            drop(claim);
            drop(debit);
            assert_eq!(pool.metrics().admitted_bytes(), 0);
        });
    }
}