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

//! Planned-demand admission, FIFO waiters, and acquisition accounting.
//!
//! Aggregate coverage and reservation-local authority are independent state
//! machines. Aggregate coverage determines how an acquisition is charged to
//! the pool. Reservation-local authority determines whether one admitted work
//! item may make that acquisition.

use std::collections::VecDeque;
use std::fmt;
use std::task::Waker;
use std::time::{Duration, Instant};

use crate::runtime::sync::sync::atomic::{AtomicU64, Ordering};
use crate::runtime::sync::sync::{Arc, MutexGuard};

use super::{invariant_violation, CarrierCount, PoolInner};

/// Closed bit in [`ReservationOwnerState::packed`].
const RESERVATION_CLOSED: u64 = 1 << 63;

/// Direct owners and in-flight debits in [`ReservationOwnerState::packed`].
const DIRECT_OUTSTANDING_MASK: u64 = !RESERVATION_CLOSED;

/// Whether a repayment must reconsider reservation admission.
const RESERVATION_DRAIN_ARMED: u64 = 1;

/// Repayment epoch bit, toggled without changing the armed bit.
const RESERVATION_REPAYMENT_EPOCH: u64 = 2;

mod coverage;
use coverage::CoverageSnapshot;
pub(super) use coverage::{CoverageDebit, CoverageState, MAX_PACKED_CARRIERS};

mod waiter;
pub(crate) use waiter::ReserveFuture;
pub(super) use waiter::{ReservationPoll, WaitSlot, WaitState, Waiter};

/// Orders uncovered repayment against reservation-queue publication.
///
/// A reservation poll arms the signal while holding admission and before it
/// samples coverage. An uncovered return updates coverage first, then advances
/// the epoch. If the return observes an unarmed signal, a later poll acquires
/// that epoch before sampling coverage and cannot enqueue from a stale sample.
/// If the signal was already armed, the return takes admission and drains the
/// FIFO through the authoritative state.
pub(super) struct ReservationDrainSignal {
    /// Packed queue-presence bit and uncovered-repayment epoch.
    state: AtomicU64,
}

impl ReservationDrainSignal {
    /// Creates an unarmed signal before any repayment.
    pub(super) fn new() -> Self {
        Self {
            state: AtomicU64::new(0),
        }
    }

    /// Announces a reservation decision before its coverage sample.
    pub(super) fn arm(&self) {
        self.state
            .fetch_or(RESERVATION_DRAIN_ARMED, Ordering::AcqRel);
    }

    /// Publishes whether admission retains a queued reservation.
    ///
    /// The caller holds admission, so no other queue mutation can race this
    /// publication. A waiting poll that has not acquired admission yet will
    /// arm the signal before taking its own coverage sample.
    pub(super) fn publish_waiter_state(&self, waiters_present: bool) {
        if waiters_present {
            self.arm();
        } else {
            self.state
                .fetch_and(!RESERVATION_DRAIN_ARMED, Ordering::AcqRel);
        }
    }

    /// Advances repayment ordering and reports whether the FIFO needs a drain.
    pub(super) fn repayment_requires_drain(&self) -> bool {
        self.state
            .fetch_xor(RESERVATION_REPAYMENT_EPOCH, Ordering::AcqRel)
            & RESERVATION_DRAIN_ARMED
            != 0
    }

    /// Returns whether a queued poll may require repayment work.
    pub(super) fn is_armed(&self) -> bool {
        self.state.load(Ordering::Acquire) & RESERVATION_DRAIN_ARMED != 0
    }
}

/// Planned-demand state protected by the pool admission mutex.
pub(super) struct AdmissionState {
    /// Counters participating in grant and preparation decisions.
    pub(super) ledger: AdmissionLedger,
    /// Reservation requests and queue observations retained in strict arrival order.
    queue: ReservationQueue,
}

impl AdmissionState {
    /// Creates empty admission state with one immutable normal ceiling.
    pub(super) fn new(configured_capacity: CarrierCount) -> Self {
        Self {
            ledger: AdmissionLedger {
                configured_capacity,
                prepared_capacity: CarrierCount::ZERO,
                active_planned_demand: CarrierCount::ZERO,
            },
            queue: ReservationQueue::new(Instant::now()),
        }
    }

    /// Returns whether no reservation request is queued.
    pub(super) fn waiters_is_empty(&self) -> bool {
        self.queue.is_empty()
    }

    /// Returns the current reservation FIFO depth.
    pub(super) fn waiter_count(&self) -> usize {
        self.queue.len()
    }

    /// Returns the reservation request at the FIFO head.
    pub(super) fn front_waiter(&self) -> Option<&Waiter> {
        self.queue.front()
    }

    /// Appends one request after reserving its FIFO metadata.
    ///
    /// Returns whether the queue changed from empty to non-empty.
    pub(super) fn enqueue_waiter(
        &mut self,
        waiter: Waiter,
        now: Instant,
    ) -> Result<bool, std::collections::TryReserveError> {
        self.queue.enqueue(waiter, now)
    }

    /// Removes a reservation request and returns whether pressure cleared.
    pub(super) fn remove_waiter(&mut self, slot: &Arc<WaitSlot>, now: Instant) -> bool {
        self.queue.remove(slot, now)
    }

    /// Removes the FIFO head and returns whether pressure cleared.
    pub(super) fn pop_front_waiter(&mut self, now: Instant) -> (Option<Waiter>, bool) {
        self.queue.pop_front(now)
    }

    /// Takes interval queue statistics without changing the FIFO.
    pub(super) fn take_queue_diagnostics(
        &mut self,
        now: Instant,
    ) -> ReservationQueueDiagnosticSample {
        self.queue.take_diagnostics(now)
    }

    /// Returns the cumulative requests that entered the FIFO.
    pub(super) fn reservation_enqueues_total(&self) -> u64 {
        self.queue.reservation_enqueues_total
    }

    /// Sets the cumulative enqueue count for saturation testing.
    #[cfg(test)]
    pub(super) fn set_reservation_enqueues_total_for_test(&mut self, total: u64) {
        self.queue.reservation_enqueues_total = total;
    }
}

/// Reservation FIFO and observations derived from its mutation order.
struct ReservationQueue {
    waiters: VecDeque<Waiter>,
    diagnostics: ReservationQueueDiagnostics,
    reservation_enqueues_total: u64,
}

impl ReservationQueue {
    /// Creates an empty queue and diagnostic interval.
    fn new(now: Instant) -> Self {
        Self {
            waiters: VecDeque::new(),
            diagnostics: ReservationQueueDiagnostics::new(now),
            reservation_enqueues_total: 0,
        }
    }

    fn is_empty(&self) -> bool {
        self.waiters.is_empty()
    }

    fn len(&self) -> usize {
        self.waiters.len()
    }

    fn front(&self) -> Option<&Waiter> {
        self.waiters.front()
    }

    /// Reserves metadata, appends one request, and records its queue transition.
    fn enqueue(
        &mut self,
        waiter: Waiter,
        now: Instant,
    ) -> Result<bool, std::collections::TryReserveError> {
        self.waiters.try_reserve(1)?;
        self.waiters.push_back(waiter);
        self.reservation_enqueues_total = self.reservation_enqueues_total.saturating_add(1);
        Ok(matches!(
            self.diagnostics.record_depth(self.waiters.len(), now),
            Some(ReservationQueueTransition::BecameNonempty)
        ))
    }

    /// Removes a linked request and reports the nonempty-to-empty edge.
    fn remove(&mut self, slot: &Arc<WaitSlot>, now: Instant) -> bool {
        let Some(index) = self
            .waiters
            .iter()
            .position(|waiter| Arc::ptr_eq(&waiter.slot, slot))
        else {
            return false;
        };
        self.waiters.remove(index);
        matches!(
            self.diagnostics.record_depth(self.waiters.len(), now),
            Some(ReservationQueueTransition::BecameEmpty)
        )
    }

    /// Removes the oldest request and reports the nonempty-to-empty edge.
    fn pop_front(&mut self, now: Instant) -> (Option<Waiter>, bool) {
        let waiter = self.waiters.pop_front();
        let cleared = waiter.is_some()
            && matches!(
                self.diagnostics.record_depth(self.waiters.len(), now),
                Some(ReservationQueueTransition::BecameEmpty)
            );
        (waiter, cleared)
    }

    fn take_diagnostics(&mut self, now: Instant) -> ReservationQueueDiagnosticSample {
        self.diagnostics.take(self.waiters.len(), now)
    }
}

/// A reservation FIFO crossing its empty boundary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ReservationQueueTransition {
    /// The FIFO changed from empty to non-empty.
    BecameNonempty,
    /// The FIFO changed from non-empty to empty.
    BecameEmpty,
}

/// Queue occupancy accumulated since the preceding diagnostic snapshot.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct ReservationQueueDiagnosticSample {
    /// Requests retained in FIFO order at the snapshot boundary.
    pub(super) current_depth: usize,
    /// Largest FIFO depth observed during the interval.
    pub(super) peak_depth: usize,
    /// Time during the interval for which the FIFO was non-empty.
    pub(super) nonempty_duration: Duration,
    /// Duration of the current uninterrupted non-empty interval.
    pub(super) continuous_nonempty_duration: Option<Duration>,
}

/// Queue timing and high-water state protected by admission serialization.
struct ReservationQueueDiagnostics {
    current_depth: usize,
    peak_depth: usize,
    nonempty_duration: Duration,
    became_nonempty_at: Option<Instant>,
    last_observed_at: Instant,
}

impl ReservationQueueDiagnostics {
    /// Creates an empty interval at pool construction.
    fn new(now: Instant) -> Self {
        Self {
            current_depth: 0,
            peak_depth: 0,
            nonempty_duration: Duration::ZERO,
            became_nonempty_at: None,
            last_observed_at: now,
        }
    }

    /// Accounts elapsed non-empty time before changing the observed depth.
    fn record_depth(&mut self, depth: usize, now: Instant) -> Option<ReservationQueueTransition> {
        self.accrue(now);
        let transition = match (self.current_depth == 0, depth == 0) {
            (true, false) => {
                self.became_nonempty_at = Some(now);
                Some(ReservationQueueTransition::BecameNonempty)
            }
            (false, true) => {
                self.became_nonempty_at = None;
                Some(ReservationQueueTransition::BecameEmpty)
            }
            _ => None,
        };
        self.current_depth = depth;
        self.peak_depth = self.peak_depth.max(depth);
        transition
    }

    /// Returns and resets interval statistics at one coherent queue depth.
    fn take(&mut self, depth: usize, now: Instant) -> ReservationQueueDiagnosticSample {
        let _ = self.record_depth(depth, now);
        let sample = ReservationQueueDiagnosticSample {
            current_depth: depth,
            peak_depth: self.peak_depth,
            nonempty_duration: self.nonempty_duration,
            continuous_nonempty_duration: self
                .became_nonempty_at
                .map(|started| now.saturating_duration_since(started)),
        };
        self.peak_depth = depth;
        self.nonempty_duration = Duration::ZERO;
        sample
    }

    /// Adds elapsed non-empty time through `now`.
    fn accrue(&mut self, now: Instant) {
        let elapsed = now.saturating_duration_since(self.last_observed_at);
        if self.current_depth != 0 {
            self.nonempty_duration = self.nonempty_duration.saturating_add(elapsed);
        }
        self.last_observed_at = now;
    }
}

/// Proof that one operation owns admission serialization.
pub(super) struct AdmissionGuard<'a> {
    pub(super) inner: MutexGuard<'a, AdmissionState>,
}

impl<'a> AdmissionGuard<'a> {
    /// Wraps the mutex guard that establishes admission serialization.
    pub(super) fn new(inner: MutexGuard<'a, AdmissionState>) -> Self {
        Self { inner }
    }

    /// Returns prepared capacity.
    pub(super) fn prepared_capacity(&self) -> CarrierCount {
        self.inner.ledger.prepared_capacity
    }

    /// Returns exclusive prepared-capacity access under admission.
    pub(super) fn prepared_capacity_mut(&mut self) -> &mut CarrierCount {
        &mut self.inner.ledger.prepared_capacity
    }

    /// Returns whether one fresh request is immediately eligible.
    pub(super) fn can_grant(&self, coverage: CoverageSnapshot, envelope: CarrierCount) -> bool {
        self.inner.ledger.can_grant(coverage, envelope)
    }

    /// Rejects an envelope larger than the configured admission ceiling.
    pub(super) fn validate_envelope(&self, envelope: CarrierCount) -> Result<(), ReserveError> {
        self.inner.ledger.validate_envelope(envelope)
    }

    /// Computes and validates the post-grant admission floor.
    pub(super) fn grant_target(
        &self,
        coverage: CoverageSnapshot,
        envelope: CarrierCount,
    ) -> Result<CarrierCount, ReserveError> {
        self.inner.ledger.grant_target(coverage, envelope)
    }

    /// Publishes one prepared grant.
    pub(super) fn commit_grant(
        &mut self,
        coverage: &CoverageState,
        envelope: CarrierCount,
    ) -> Result<(), ReserveError> {
        self.inner.ledger.commit_grant(coverage, envelope)
    }

    /// Retires one open envelope without releasing its carrier owners.
    pub(super) fn close_envelope(
        &mut self,
        coverage: &CoverageState,
        envelope: CarrierCount,
        direct_outstanding: CarrierCount,
    ) {
        self.inner
            .ledger
            .close_envelope(coverage, envelope, direct_outstanding);
    }

    /// Returns the largest uncovered count compatible with packed admission.
    pub(super) fn maximum_uncovered(&self) -> CarrierCount {
        MAX_PACKED_CARRIERS
            .checked_sub(self.inner.ledger.active_planned_demand)
            .unwrap_or_else(|| {
                invariant_violation("active planned demand exceeds packed admission")
            })
    }

    /// Returns the floor required by the current admission state.
    pub(super) fn acquisition_floor(
        &self,
        coverage: &CoverageState,
    ) -> Result<CarrierCount, ReserveError> {
        self.inner.ledger.admission_used(coverage.snapshot())
    }

    /// Reverses an unexposed acquisition while admission remains held.
    pub(super) fn rollback_acquisition(
        &mut self,
        coverage: &CoverageState,
        count: CarrierCount,
        debit: CoverageDebit,
    ) {
        coverage.rollback_debit(count, debit, self.inner.ledger.active_planned_demand);
        self.inner.ledger.assert_invariants(coverage.snapshot());
    }
}

/// Carrier-granular values used to decide and back new admission.
pub(super) struct AdmissionLedger {
    /// Normal admission ceiling.
    pub(super) configured_capacity: CarrierCount,
    /// Capacity whose complete preparation steps have succeeded.
    pub(super) prepared_capacity: CarrierCount,
    /// Complete envelopes whose acquisition authority remains open.
    pub(super) active_planned_demand: CarrierCount,
}

impl AdmissionLedger {
    /// Returns active envelopes plus ownership outside their coverage.
    pub(super) fn admission_used(
        &self,
        coverage: CoverageSnapshot,
    ) -> Result<CarrierCount, ReserveError> {
        self.active_planned_demand
            .checked_add(coverage.uncovered)
            .filter(|count| *count <= MAX_PACKED_CARRIERS)
            .ok_or(ReserveError::CapacityOverflow)
    }

    /// Returns whether one envelope fits the current admission state.
    fn can_grant(&self, coverage: CoverageSnapshot, envelope: CarrierCount) -> bool {
        self.admission_used(coverage)
            .ok()
            .and_then(|used| used.checked_add(envelope))
            .is_some_and(|next| next <= self.configured_capacity)
    }

    /// Rejects an envelope that can never fit under normal admission.
    fn validate_envelope(&self, envelope: CarrierCount) -> Result<(), ReserveError> {
        // TODO(memory): Evaluate admitting one oversized FIFO-head reservation
        // when aggregate admission use is zero. Define retained-owner blocking,
        // serialization, memory-overage, and metrics semantics before relaxing
        // the configured-capacity ceiling.
        if envelope > self.configured_capacity {
            return Err(ReserveError::ExceedsCapacity);
        }
        Ok(())
    }

    /// Returns the prepared-capacity floor required after one grant.
    fn grant_target(
        &self,
        coverage: CoverageSnapshot,
        envelope: CarrierCount,
    ) -> Result<CarrierCount, ReserveError> {
        self.admission_used(coverage)?
            .checked_add(envelope)
            .filter(|target| *target <= MAX_PACKED_CARRIERS)
            .ok_or(ReserveError::CapacityOverflow)
    }

    /// Adds one complete envelope after its floor has been prepared.
    fn commit_grant(
        &mut self,
        coverage: &CoverageState,
        envelope: CarrierCount,
    ) -> Result<(), ReserveError> {
        let snapshot = coverage.snapshot();
        let next_active = self
            .active_planned_demand
            .checked_add(envelope)
            .ok_or(ReserveError::CapacityOverflow)?;
        let next_admission_used = next_active
            .checked_add(snapshot.uncovered)
            .filter(|total| *total <= MAX_PACKED_CARRIERS)
            .ok_or(ReserveError::CapacityOverflow)?;
        if self.prepared_capacity < next_admission_used {
            invariant_violation(
                "reservation grant did not prepare its admission floor before publication",
            );
        }

        coverage
            .add_coverage(envelope)
            .map_err(|_| ReserveError::CapacityOverflow)?;
        self.active_planned_demand = next_active;
        self.assert_invariants(coverage.snapshot());
        Ok(())
    }

    /// Withdraws one envelope and reclassifies occupied coverage.
    fn close_envelope(
        &mut self,
        coverage: &CoverageState,
        envelope: CarrierCount,
        direct_outstanding: CarrierCount,
    ) {
        let Some(remaining_active) = self.active_planned_demand.checked_sub(envelope) else {
            invariant_violation("reservation close exceeds active planned demand");
        };
        self.active_planned_demand = remaining_active;
        coverage.remove_coverage(envelope, direct_outstanding, self.active_planned_demand);
        self.assert_invariants(coverage.snapshot());
    }

    /// Checks identities required after each serialized transition.
    pub(super) fn assert_invariants(&self, coverage: CoverageSnapshot) {
        let admission_used = self
            .admission_used(coverage)
            .unwrap_or_else(|_| invariant_violation("completed admission exceeds packed capacity"));
        if self.prepared_capacity < admission_used {
            invariant_violation("prepared capacity does not cover admission used");
        }
        if coverage.available > self.active_planned_demand {
            invariant_violation("available coverage exceeds active planned demand");
        }
    }
}

/// Failure to create a new reservation.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ReserveError {
    /// The byte request was zero.
    InvalidSize,
    /// The requested envelope exceeds the pool's configured capacity.
    ExceedsCapacity,
    /// Physical storage could not be prepared.
    PhysicalPreparationFailed,
    /// Queue or ownership metadata could not reserve the required capacity.
    MetadataAllocationFailed,
    /// The request or resulting accounting state is not representable.
    CapacityOverflow,
}

impl fmt::Display for ReserveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidSize => f.write_str("reservation size must be nonzero"),
            Self::ExceedsCapacity => {
                f.write_str("reservation exceeds configured buffer-pool capacity")
            }
            Self::PhysicalPreparationFailed => {
                f.write_str("physical buffer-pool preparation failed")
            }
            Self::MetadataAllocationFailed => f.write_str("buffer-pool metadata allocation failed"),
            Self::CapacityOverflow => {
                f.write_str("reservation exceeds buffer-pool accounting capacity")
            }
        }
    }
}

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

/// Non-cloneable acquisition authority for one admitted memory envelope.
///
/// Dropping the reservation closes it. Mutable buffers and immutable views
/// already acquired through it remain valid and keep their memory charged
/// until their final owners are dropped.
pub(crate) struct Reservation {
    state: Option<Arc<ReservationState>>,
}

/// Private reservation state retained by future direct carrier owners.
pub(super) struct ReservationState {
    /// Pool that granted the reservation.
    pool: Arc<PoolInner>,
    /// Complete admitted envelope.
    envelope: CarrierCount,
    /// Close state and direct owners or in-flight debits.
    owner_state: ReservationOwnerState,
}

impl Reservation {
    /// Creates one open reservation for an already published grant.
    pub(super) fn new(pool: Arc<PoolInner>, envelope: CarrierCount) -> Self {
        Self {
            state: Some(Arc::new(ReservationState {
                pool,
                envelope,
                owner_state: ReservationOwnerState::new(),
            })),
        }
    }

    /// Revokes new acquisition and retires this reservation's planned demand.
    ///
    /// Buffers acquired before this call keep their existing capacity, but
    /// attempts to grow them return
    /// [`AcquireError::ReservationClosed`](super::AcquireError::ReservationClosed).
    pub(crate) fn close_acquisition(mut self) {
        self.close();
    }

    fn close(&mut self) {
        if let Some(state) = self.state.take() {
            state.close_acquisition();
        }
    }

    /// Returns the private state retained by a direct acquisition.
    pub(super) fn acquisition_state(&self) -> Option<&Arc<ReservationState>> {
        self.state.as_ref()
    }
}

impl fmt::Debug for Reservation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Reservation")
            .field("open", &self.state.is_some())
            .finish_non_exhaustive()
    }
}

impl Drop for Reservation {
    fn drop(&mut self) {
        self.close();
    }
}

impl ReservationState {
    /// Returns the pool whose direct authority this state represents.
    pub(super) fn pool(&self) -> &Arc<PoolInner> {
        &self.pool
    }

    /// Returns whether this reservation belongs to `pool`.
    pub(super) fn belongs_to(&self, pool: &Arc<PoolInner>) -> bool {
        Arc::ptr_eq(&self.pool, pool)
    }

    /// Installs one complete direct-acquisition debit.
    pub(super) fn try_debit(&self, count: CarrierCount) -> Result<(), DirectDebitError> {
        self.owner_state.try_debit(self.envelope, count)
    }

    /// Rejects an already impossible debit before aggregate preparation.
    ///
    /// This load does not reserve authority. The caller must still use
    /// [`Self::try_debit`] after publishing its aggregate charge.
    pub(super) fn precheck_debit(&self, count: CarrierCount) -> Result<(), DirectDebitError> {
        self.owner_state.precheck_debit(self.envelope, count)
    }

    /// Retires direct owners or an in-flight debit.
    pub(super) fn release(&self, count: CarrierCount) {
        self.owner_state.release(count);
    }

    /// Returns direct-owner state for composed acquisition tests.
    #[cfg(test)]
    pub(super) fn test_owner_state(&self) -> (bool, CarrierCount) {
        let snapshot = self.owner_state.snapshot();
        (snapshot.closed, snapshot.direct_outstanding)
    }

    /// Closes direct authority and withdraws this reservation's envelope.
    fn close_acquisition(&self) {
        let drained = {
            let mut admission = AdmissionGuard::new(self.pool.admission.lock());
            let Some(direct_outstanding) = self.owner_state.close() else {
                return;
            };
            admission.close_envelope(&self.pool.coverage, self.envelope, direct_outstanding);
            PoolInner::drain_fifo_locked(&self.pool, &mut admission, false)
        };
        if let Some(sample) = drained.queue_sample {
            self.pool.log_reservation_queue_transition(sample);
        }
        wake_all(drained.wakers);
    }
}

/// Wakes terminal reservation futures after every pool lock is released.
pub(super) fn wake_all(wakers: Vec<Waker>) {
    for waker in wakers {
        waker.wake();
    }
}

/// Why a reservation-local debit could not be installed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum DirectDebitError {
    /// The reservation no longer permits new carrier acquisition.
    Closed,
    /// The debit would exceed the admitted envelope.
    CapacityExceeded,
    /// The count cannot be represented in the packed owner state.
    CapacityOverflow,
}

/// One coherent reservation-owner sample.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ReservationOwnerSnapshot {
    /// Whether acquisition of new carriers is closed.
    closed: bool,
    /// Direct owners and in-flight debits.
    direct_outstanding: CarrierCount,
}

/// Reservation-local acquisition state.
///
/// The high bit records close. The remaining bits count direct carrier owners
/// and acquisition debits that have not yet become owners.
struct ReservationOwnerState {
    packed: AtomicU64,
}

impl ReservationOwnerState {
    /// Creates open authority with no direct owners.
    fn new() -> Self {
        Self {
            packed: AtomicU64::new(0),
        }
    }

    /// Rejects a debit that the current state already makes impossible.
    ///
    /// This load does not reserve authority and may race close or another
    /// debit. [`Self::try_debit`] performs the authoritative atomic update.
    fn precheck_debit(
        &self,
        envelope: CarrierCount,
        count: CarrierCount,
    ) -> Result<(), DirectDebitError> {
        let envelope =
            u64::try_from(envelope.get()).map_err(|_| DirectDebitError::CapacityOverflow)?;
        let count = u64::try_from(count.get()).map_err(|_| DirectDebitError::CapacityOverflow)?;
        if envelope > DIRECT_OUTSTANDING_MASK || count > DIRECT_OUTSTANDING_MASK {
            return Err(DirectDebitError::CapacityOverflow);
        }

        let current = self.packed.load(Ordering::Acquire);
        if current & RESERVATION_CLOSED != 0 {
            return Err(DirectDebitError::Closed);
        }
        (current & DIRECT_OUTSTANDING_MASK)
            .checked_add(count)
            .filter(|next| *next <= envelope)
            .map(|_| ())
            .ok_or(DirectDebitError::CapacityExceeded)
    }

    /// Installs one complete direct-acquisition debit.
    ///
    /// Close and debit linearize on the same atomic word. A successful debit
    /// remains valid if close follows it. A debit that observes close fails.
    fn try_debit(
        &self,
        envelope: CarrierCount,
        count: CarrierCount,
    ) -> Result<(), DirectDebitError> {
        let envelope =
            u64::try_from(envelope.get()).map_err(|_| DirectDebitError::CapacityOverflow)?;
        let count = u64::try_from(count.get()).map_err(|_| DirectDebitError::CapacityOverflow)?;
        if envelope > DIRECT_OUTSTANDING_MASK || count > DIRECT_OUTSTANDING_MASK {
            return Err(DirectDebitError::CapacityOverflow);
        }

        // TODO(msrv): `fetch_update` is deprecated from Rust 1.99 in favour of `try_update`,
        // which is stable from 1.95. Switch to `try_update` once the MSRV is 1.95 or later and the
        // loom atomics this module uses under `cfg(s3_tm_loom)` provide it (loom 0.7 has only
        // `fetch_update`).
        #[allow(deprecated)]
        let result = self
            .packed
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                if current & RESERVATION_CLOSED != 0 {
                    return None;
                }
                (current & DIRECT_OUTSTANDING_MASK)
                    .checked_add(count)
                    .filter(|next| *next <= envelope)
            });

        match result {
            Ok(_) => Ok(()),
            Err(current) if current & RESERVATION_CLOSED != 0 => Err(DirectDebitError::Closed),
            Err(_) => Err(DirectDebitError::CapacityExceeded),
        }
    }

    /// Closes direct acquisition and returns the outstanding count it observed.
    fn close(&self) -> Option<CarrierCount> {
        let previous = self.packed.fetch_or(RESERVATION_CLOSED, Ordering::AcqRel);
        if previous & RESERVATION_CLOSED != 0 {
            return None;
        }
        Some(CarrierCount::new(
            usize::try_from(previous & DIRECT_OUTSTANDING_MASK)
                .unwrap_or_else(|_| invariant_violation("direct owner count does not fit usize")),
        ))
    }

    /// Retires direct owners or rolls back an in-flight debit.
    ///
    /// Returns `true` when the reservation remains open. Release preserves the
    /// closed bit and cannot restore acquisition authority after close.
    fn release(&self, count: CarrierCount) -> bool {
        let count = u64::try_from(count.get()).unwrap_or_else(|_| {
            invariant_violation("direct release count does not fit owner state")
        });
        // TODO(msrv): `fetch_update` is deprecated from Rust 1.99 in favour of `try_update`,
        // which is stable from 1.95. Switch to `try_update` once the MSRV is 1.95 or later and the
        // loom atomics this module uses under `cfg(s3_tm_loom)` provide it (loom 0.7 has only
        // `fetch_update`).
        #[allow(deprecated)]
        let previous = self
            .packed
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                let outstanding = current & DIRECT_OUTSTANDING_MASK;
                outstanding
                    .checked_sub(count)
                    .map(|next| (current & RESERVATION_CLOSED) | next)
            })
            .unwrap_or_else(|_| {
                invariant_violation("direct release exceeds outstanding ownership")
            });
        previous & RESERVATION_CLOSED == 0
    }

    /// Loads one coherent owner-state sample.
    fn snapshot(&self) -> ReservationOwnerSnapshot {
        let packed = self.packed.load(Ordering::Acquire);
        ReservationOwnerSnapshot {
            closed: packed & RESERVATION_CLOSED != 0,
            direct_outstanding: CarrierCount::new(
                usize::try_from(packed & DIRECT_OUTSTANDING_MASK).unwrap_or_else(|_| {
                    invariant_violation("direct owner count does not fit usize")
                }),
            ),
        }
    }
}

#[cfg(all(test, not(s3_tm_loom)))]
mod tests {
    use super::super::test_util::test_pool;
    use super::super::virtual_memory::VirtualMemoryOperation;
    use super::super::BufferPool;
    use super::*;

    #[test]
    fn test_queue_diagnostics_report_depth_peak_and_nonempty_durations() {
        let start = Instant::now();
        let mut diagnostics = ReservationQueueDiagnostics::new(start);

        assert_eq!(
            diagnostics.record_depth(1, start + Duration::from_millis(10)),
            Some(ReservationQueueTransition::BecameNonempty)
        );
        assert_eq!(
            diagnostics.record_depth(4, start + Duration::from_millis(20)),
            None
        );
        assert_eq!(
            diagnostics.take(4, start + Duration::from_millis(30)),
            ReservationQueueDiagnosticSample {
                current_depth: 4,
                peak_depth: 4,
                nonempty_duration: Duration::from_millis(20),
                continuous_nonempty_duration: Some(Duration::from_millis(20)),
            }
        );

        assert_eq!(
            diagnostics.record_depth(0, start + Duration::from_millis(50)),
            Some(ReservationQueueTransition::BecameEmpty)
        );
        assert_eq!(
            diagnostics.take(0, start + Duration::from_millis(60)),
            ReservationQueueDiagnosticSample {
                current_depth: 0,
                peak_depth: 4,
                nonempty_duration: Duration::from_millis(20),
                continuous_nonempty_duration: None,
            }
        );
    }

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

        let reservation = pool.try_reserve(carrier_size).unwrap().unwrap();

        {
            let admission = pool.inner.admission.lock();
            let coverage = pool.inner.coverage.snapshot();
            assert_eq!(admission.ledger.prepared_capacity, CarrierCount::new(2));
            assert_eq!(admission.ledger.active_planned_demand, CarrierCount::new(1));
            assert_eq!(coverage.available, CarrierCount::new(1));
            assert_eq!(coverage.uncovered, CarrierCount::ZERO);
        }

        drop(reservation);
        let admission = pool.inner.admission.lock();
        assert_eq!(admission.ledger.active_planned_demand, CarrierCount::ZERO);
        assert_eq!(admission.ledger.prepared_capacity, CarrierCount::new(2));
        assert_eq!(
            pool.inner.coverage.snapshot(),
            CoverageSnapshot {
                available: CarrierCount::ZERO,
                uncovered: CarrierCount::ZERO,
            }
        );
    }

    #[test]
    fn test_grant_cannot_publish_before_preparing_its_floor() {
        let mut admission = AdmissionState::new(CarrierCount::new(1));
        let coverage = CoverageState::new();

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            admission
                .ledger
                .commit_grant(&coverage, CarrierCount::new(1))
                .unwrap();
        }));

        assert!(result.is_err());
        assert_eq!(admission.ledger.active_planned_demand, CarrierCount::ZERO);
        assert_eq!(
            coverage.snapshot(),
            CoverageSnapshot {
                available: CarrierCount::ZERO,
                uncovered: CarrierCount::ZERO,
            }
        );
    }

    #[test]
    fn test_normal_grant_respects_configured_capacity() {
        let (pool, carrier_size) = test_pool(2, 2);
        let reservation = pool.try_reserve(carrier_size * 2).unwrap().unwrap();

        assert!(pool.try_reserve(carrier_size).unwrap().is_none());
        assert_eq!(pool.inner.arena.diagnostics().blocks_prepared, 1);

        drop(reservation);
    }

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

        assert!(matches!(
            pool.try_reserve(carrier_size * 2),
            Err(ReserveError::ExceedsCapacity)
        ));

        let admission = pool.inner.admission.lock();
        assert_eq!(admission.ledger.active_planned_demand, CarrierCount::ZERO);
        assert_eq!(admission.ledger.prepared_capacity, CarrierCount::ZERO);
        assert_eq!(
            pool.inner.coverage.snapshot(),
            CoverageSnapshot {
                available: CarrierCount::ZERO,
                uncovered: CarrierCount::ZERO,
            }
        );
    }

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

        for _ in 0..4 {
            assert!(pool.try_reserve(carrier_size).unwrap().is_none());
            let metrics = pool.metrics();
            assert_eq!(metrics.active_planned_demand_bytes(), 0);
            assert_eq!(metrics.admitted_bytes(), carrier_size as u64);
            assert_eq!(metrics.in_use_bytes(), carrier_size as u64);
            assert_eq!(metrics.admission_overage_bytes(), 0);
        }

        drop(retained);
        let next = pool
            .try_reserve(carrier_size)
            .unwrap()
            .expect("returned ownership restores admission");
        drop(next);
        let audit = pool.audit_quiescent();
        assert_eq!(audit.active_planned_demand, CarrierCount::ZERO);
        assert_eq!(audit.available_coverage, CarrierCount::ZERO);
        assert_eq!(audit.uncovered_charges, CarrierCount::ZERO);
        assert_eq!(audit.charged_capacity, CarrierCount::ZERO);
        assert_eq!(audit.live_carriers, CarrierCount::ZERO);
        assert_eq!(audit.queued_reservations, 0);
        assert_eq!(audit.cleanup_pending_blocks, 0);
        assert_eq!(audit.prepared_capacity, CarrierCount::new(1));
    }

    #[test]
    fn test_preparation_failure_publishes_no_grant() {
        let (pool, carrier_size) = test_pool(2, 4);
        let first = pool.inner.arena.reserve_slot().unwrap();
        let second = pool.inner.arena.reserve_slot().unwrap();
        second.inject_failure_once(VirtualMemoryOperation::Prepare);

        assert!(matches!(
            pool.try_reserve(carrier_size * 3),
            Err(ReserveError::PhysicalPreparationFailed)
        ));
        {
            let admission = pool.inner.admission.lock();
            assert_eq!(admission.ledger.prepared_capacity, CarrierCount::new(2));
            assert_eq!(admission.ledger.active_planned_demand, CarrierCount::ZERO);
            assert_eq!(
                pool.inner.coverage.snapshot(),
                CoverageSnapshot {
                    available: CarrierCount::ZERO,
                    uncovered: CarrierCount::ZERO,
                }
            );
        }

        let reservation = pool.try_reserve(carrier_size * 3).unwrap().unwrap();
        assert_eq!(
            pool.inner.admission.lock().ledger.prepared_capacity,
            CarrierCount::new(4)
        );
        drop(reservation);
        drop(first);
    }

    #[test]
    fn test_close_reclassifies_occupied_coverage() {
        let (pool, carrier_size) = test_pool(2, 2);
        let reservation = pool.try_reserve(carrier_size * 2).unwrap().unwrap();
        assert!(pool
            .inner
            .coverage
            .try_debit_covered(CarrierCount::new(1))
            .unwrap());

        reservation.close_acquisition();

        assert_eq!(
            pool.inner.coverage.snapshot(),
            CoverageSnapshot {
                available: CarrierCount::ZERO,
                uncovered: CarrierCount::new(1),
            }
        );
        assert_eq!(
            pool.inner.admission.lock().ledger.active_planned_demand,
            CarrierCount::ZERO
        );
        pool.inner.coverage.release(CarrierCount::new(1));
    }

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

        assert!(matches!(
            pool.try_reserve(0),
            Err(ReserveError::InvalidSize)
        ));
        if let Some(bytes) = (u32::MAX as usize)
            .checked_add(1)
            .and_then(|carriers| carriers.checked_mul(carrier_size))
        {
            assert!(matches!(
                pool.try_reserve(bytes),
                Err(ReserveError::CapacityOverflow)
            ));
        }
        assert_eq!(pool.inner.arena.diagnostics().blocks_prepared, 0);
    }

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

        assert_send_sync::<BufferPool>();
        assert_send_sync::<Reservation>();
        assert_send_sync::<ReservationState>();
    }

    #[test]
    fn test_close_is_idempotent() {
        let state = ReservationOwnerState::new();

        assert_eq!(state.close(), Some(CarrierCount::ZERO));
        assert_eq!(state.close(), None);
        assert_eq!(
            state.snapshot(),
            ReservationOwnerSnapshot {
                closed: true,
                direct_outstanding: CarrierCount::ZERO,
            }
        );
    }

    #[test]
    fn test_direct_debit_cannot_exceed_envelope() {
        let state = ReservationOwnerState::new();
        state
            .try_debit(CarrierCount::new(3), CarrierCount::new(2))
            .unwrap();

        assert_eq!(
            state.try_debit(CarrierCount::new(3), CarrierCount::new(2)),
            Err(DirectDebitError::CapacityExceeded)
        );
        assert_eq!(state.snapshot().direct_outstanding, CarrierCount::new(2));
    }

    #[test]
    fn test_release_after_close_does_not_reopen_reservation() {
        let state = ReservationOwnerState::new();
        state
            .try_debit(CarrierCount::new(2), CarrierCount::new(2))
            .unwrap();
        assert_eq!(state.close(), Some(CarrierCount::new(2)));

        assert!(!state.release(CarrierCount::new(2)));
        assert_eq!(
            state.snapshot(),
            ReservationOwnerSnapshot {
                closed: true,
                direct_outstanding: CarrierCount::ZERO,
            }
        );
        assert_eq!(
            state.try_debit(CarrierCount::new(2), CarrierCount::new(1)),
            Err(DirectDebitError::Closed)
        );
    }

    #[test]
    fn test_invalid_release_leaves_owner_state_unchanged() {
        let state = ReservationOwnerState::new();

        let result = std::panic::catch_unwind(|| state.release(CarrierCount::new(1)));

        assert!(result.is_err());
        assert_eq!(
            state.snapshot(),
            ReservationOwnerSnapshot {
                closed: false,
                direct_outstanding: CarrierCount::ZERO,
            }
        );
    }
}

#[cfg(all(test, s3_tm_loom))]
mod loom_tests {
    use super::super::test_util::test_single_carrier_pool as test_pool;
    use crate::runtime::sync::sync::Arc;
    use crate::runtime::sync::thread;

    use super::*;

    #[test]
    fn test_concurrent_immediate_grants_respect_normal_capacity() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(1);

            let first_pool = pool.clone();
            let first = thread::spawn(move || first_pool.try_reserve(carrier_size).unwrap());
            let second_pool = pool.clone();
            let second = thread::spawn(move || second_pool.try_reserve(carrier_size).unwrap());

            let first = first.join().unwrap();
            let second = second.join().unwrap();
            assert_eq!(
                usize::from(first.is_some()) + usize::from(second.is_some()),
                1
            );
            drop(first);
            drop(second);
            assert_eq!(
                pool.inner.admission.lock().ledger.active_planned_demand,
                CarrierCount::ZERO
            );
        });
    }

    #[test]
    fn test_concurrent_oversized_requests_do_not_enter_admission() {
        loom::model(|| {
            let (pool, carrier_size) = test_pool(1);

            let first_pool = pool.clone();
            let first = thread::spawn(move || first_pool.try_reserve(carrier_size * 2));
            let second_pool = pool.clone();
            let second = thread::spawn(move || second_pool.try_reserve(carrier_size * 2));

            let first = first.join().unwrap();
            let second = second.join().unwrap();
            assert!(matches!(first, Err(ReserveError::ExceedsCapacity)));
            assert!(matches!(second, Err(ReserveError::ExceedsCapacity)));
            let admission = pool.inner.admission.lock();
            assert_eq!(admission.ledger.active_planned_demand, CarrierCount::ZERO);
            assert_eq!(admission.ledger.prepared_capacity, CarrierCount::ZERO);
            assert!(admission.waiters_is_empty());
        });
    }

    #[test]
    fn test_direct_debit_racing_close_has_one_linearization() {
        loom::model(|| {
            let state = Arc::new(ReservationOwnerState::new());

            let debiting = Arc::clone(&state);
            let debit = thread::spawn(move || {
                debiting.try_debit(CarrierCount::new(1), CarrierCount::new(1))
            });
            let closing = Arc::clone(&state);
            let close = thread::spawn(move || closing.close());

            let debit = debit.join().unwrap();
            let closed_outstanding = close.join().unwrap();
            let snapshot = state.snapshot();
            assert!(snapshot.closed);
            match debit {
                Ok(()) => {
                    assert_eq!(closed_outstanding, Some(CarrierCount::new(1)));
                    assert_eq!(snapshot.direct_outstanding, CarrierCount::new(1));
                }
                Err(DirectDebitError::Closed) => {
                    assert_eq!(closed_outstanding, Some(CarrierCount::ZERO));
                    assert_eq!(snapshot.direct_outstanding, CarrierCount::ZERO);
                }
                Err(error) => panic!("unexpected debit error: {error:?}"),
            }
        });
    }

    #[test]
    fn test_concurrent_direct_debits_consume_authority_once() {
        loom::model(|| {
            let state = Arc::new(ReservationOwnerState::new());

            let first_state = Arc::clone(&state);
            let first = thread::spawn(move || {
                first_state.try_debit(CarrierCount::new(1), CarrierCount::new(1))
            });
            let second_state = Arc::clone(&state);
            let second = thread::spawn(move || {
                second_state.try_debit(CarrierCount::new(1), CarrierCount::new(1))
            });

            let successes = usize::from(first.join().unwrap().is_ok())
                + usize::from(second.join().unwrap().is_ok());
            assert_eq!(successes, 1);
            assert_eq!(state.snapshot().direct_outstanding, CarrierCount::new(1));
        });
    }

    #[test]
    fn test_release_racing_close_cannot_reopen_reservation() {
        loom::model(|| {
            let state = Arc::new(ReservationOwnerState::new());
            state
                .try_debit(CarrierCount::new(1), CarrierCount::new(1))
                .unwrap();

            let releasing = Arc::clone(&state);
            let release = thread::spawn(move || releasing.release(CarrierCount::new(1)));
            let closing = Arc::clone(&state);
            let close = thread::spawn(move || closing.close());

            release.join().unwrap();
            close.join().unwrap();
            assert_eq!(
                state.snapshot(),
                ReservationOwnerSnapshot {
                    closed: true,
                    direct_outstanding: CarrierCount::ZERO,
                }
            );
        });
    }
}