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

//! Bounded transfer-memory admission and fixed-size pooled storage.
//!
//! [`BufferPool`] grants planned demand in FIFO order, accounts carrier
//! ownership independently of reservation lifetime, and prepares backing in
//! whole blocks. Mutable acquisitions retain exclusive carrier ownership;
//! immutable segmented values may present adjacent carriers as one byte range
//! while preserving each carrier's independent return boundary.
//!
//! Current memory gauges are always available through [`BufferPool::metrics`].
//! Pressure and lifecycle counters are updated only when exceptional allocator
//! work occurs. Per-acquisition scan accounting and periodic snapshots are
//! opt-in so the normal success path does not pay for diagnostic atomics.

use std::task::Waker;

use crate::config::MemoryDiagnosticsConfig;
#[cfg(not(all(test, s3_tm_loom)))]
use crate::runtime::sync::sync::atomic::{AtomicUsize, Ordering};
use crate::runtime::sync::sync::{Arc, Mutex};

mod acquisition;
mod admission;
mod arena;
#[cfg(s3_tm_bench)]
pub(crate) mod bench_util;
mod block;
mod config;
#[cfg(not(all(test, s3_tm_loom)))]
mod diagnostics;
mod geometry;
mod maintenance;
mod metrics;
mod pooled_buf;
mod segmented_bytes;
#[cfg(any(test, s3_tm_fuzz))]
mod test_util;
#[cfg(all(test, not(s3_tm_loom)))]
mod tests;
mod virtual_memory;

use crate::config::MemoryBudgetConfig;
use acquisition::acquire_count;
pub(crate) use acquisition::AcquireError;
use admission::{
    wake_all, AdmissionGuard, AdmissionState, CoverageDebit, CoverageState, ReservationDrainSignal,
    ReservationPoll, WaitSlot, WaitState, Waiter, MAX_PACKED_CARRIERS,
};
pub(crate) use admission::{Reservation, ReserveError, ReserveFuture};
use arena::{Arena, ArenaError, ArenaOptions};
use block::BlockError;
pub(crate) use config::auto_capacity_bytes;
use config::PoolConfig;
pub use config::{BufferPoolBuildError, BufferPoolBuilder};
use geometry::{GeometryError, PoolGeometry};
use maintenance::MaintenanceCoordinator;
pub use metrics::MemoryMetrics;
use metrics::{MemoryDiagnostics, MemoryMetricState};
use pooled_buf::GrowthAuthority;
pub(crate) use pooled_buf::PooledBufMut;
pub use segmented_bytes::SegmentedBytes;

/// Executes one compact accounting and ownership fuzz sequence.
///
/// The target decodes public pool operations and checks every transition
/// against the shared reference model and quiescent audit.
#[cfg(s3_tm_fuzz)]
pub(crate) fn run_fuzz_input(data: &[u8]) {
    let _ = test_util::model_harness::run_fuzz_input(data);
}

/// Executes one large-geometry bitmap-placement fuzz sequence.
///
/// The target uses the shared reference model plus the independent free-word
/// oracle to verify contiguous-first placement and legal fragmented fallback.
#[cfg(s3_tm_fuzz)]
pub(crate) fn run_placement_fuzz_input(data: &[u8]) {
    let _ = test_util::model_harness::run_placement_fuzz_input(data);
}

#[cfg(all(test, not(s3_tm_loom)))]
pub(crate) use test_util::test_pool;
#[cfg(test)]
use test_util::TestHooks;

/// A cloneable handle to one admission, accounting, and storage domain.
///
/// Every clone shares the configured capacity, reservation queue, ownership
/// charges, prepared storage, maintenance state, and metrics. Constructing a
/// pool is lazy: no virtual ranges or physical memory are prepared until the
/// first admitted acquisition needs them.
#[derive(Clone)]
pub struct BufferPool {
    inner: Arc<PoolInner>,
}

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

impl BufferPool {
    /// Returns a builder for an empty shared memory pool.
    pub fn builder() -> BufferPoolBuilder {
        BufferPoolBuilder::default()
    }

    /// Returns the fixed writable allocation unit used by this pool.
    ///
    /// Reservations and acquisitions accept arbitrary byte counts and round
    /// them to this page-aligned unit.
    pub(crate) fn carrier_size(&self) -> usize {
        self.inner.geometry.carrier_size()
    }

    /// Constructs an empty pool from capacity policy and detected memory.
    ///
    /// Capacity and geometry are fixed before publication. Construction does
    /// not reserve virtual ranges, prepare backing, or start maintenance.
    pub(crate) fn from_capacity(
        capacity: MemoryBudgetConfig,
        detected_memory: Option<usize>,
        diagnostics: MemoryDiagnosticsConfig,
    ) -> Result<Self, BufferPoolBuildError> {
        let resolved = PoolConfig::resolve(capacity, detected_memory)?;
        let arena_options = ArenaOptions::new(
            resolved.optimistic_scan_words,
            diagnostics.enable_detailed_counters(),
        );
        Ok(Self::from_parts_with_arena_options(
            resolved.geometry,
            resolved.configured_capacity,
            diagnostics,
            arena_options,
        )
        .unwrap_or_else(|_| invariant_violation("validated pool configuration was rejected")))
    }

    /// Constructs a pool with explicit internal arena policy.
    fn from_parts_with_arena_options(
        geometry: PoolGeometry,
        configured_capacity: CarrierCount,
        diagnostics: MemoryDiagnosticsConfig,
        arena_options: ArenaOptions,
    ) -> Result<Self, ArenaError> {
        if configured_capacity == CarrierCount::ZERO {
            invariant_violation("configured capacity must be nonzero");
        }
        if configured_capacity > MAX_PACKED_CARRIERS {
            invariant_violation("configured capacity must fit packed accounting");
        }

        let configured_capacity_bytes = configured_capacity
            .get()
            .checked_mul(geometry.carrier_size())
            .unwrap_or_else(|| invariant_violation("configured byte capacity overflowed"));
        let optimistic_scan_words = arena_options.optimistic_scan_words();
        let inner = Arc::new(PoolInner::new(
            geometry,
            configured_capacity,
            diagnostics,
            arena_options,
        )?);
        inner.maintenance.start_periodic_diagnostics(&inner);
        tracing::debug!(
            target: crate::telemetry::TARGET_MEMORY,
            configured_capacity_bytes,
            page_size_bytes = geometry.page_size(),
            carrier_size_bytes = geometry.carrier_size(),
            block_size_bytes = geometry.block_size(),
            optimistic_scan_words,
            diagnostic_detail = diagnostics.detail_level(),
            diagnostic_snapshot_interval_ms =
                diagnostics.snapshot_interval().map(|interval| interval.as_millis()).unwrap_or(0),
            "constructed buffer pool"
        );
        Ok(Self { inner })
    }

    /// Attempts one immediate reservation grant.
    ///
    /// `Ok(None)` reports an older FIFO request or current admission pressure.
    /// A successful grant has already prepared storage through its complete
    /// admission floor. A request whose carrier-rounded envelope exceeds the
    /// configured pool capacity returns [`ReserveError::ExceedsCapacity`].
    pub(crate) fn try_reserve(&self, bytes: usize) -> Result<Option<Reservation>, ReserveError> {
        let envelope = self.reservation_envelope(bytes)?;
        PoolInner::try_reserve_count(&self.inner, envelope)
    }

    /// Creates a lazy, cancellation-safe reservation request.
    ///
    /// The first poll either returns an immediate result or enters the
    /// pool-wide FIFO. Invalid requests and physical preparation failures
    /// resolve through the future's `ReserveError`. A request larger than the
    /// configured pool capacity fails without entering the FIFO.
    pub(crate) fn reserve(&self, bytes: usize) -> ReserveFuture {
        ReserveFuture::new(self.clone(), bytes)
    }

    /// Returns one coherent sample of this pool's memory state.
    pub fn metrics(&self) -> MemoryMetrics {
        self.inner.memory_metrics()
    }

    /// Returns operational counters and a scanned lifecycle sample.
    pub(crate) fn diagnostics(&self) -> MemoryDiagnostics {
        MemoryDiagnostics::from_samples(
            self.inner.arena.diagnostics(),
            self.inner.arena.sample_lifecycle(),
            self.inner.maintenance.diagnostics(),
        )
    }

    /// Invalidates pending idle reclamation when managed work starts.
    pub(crate) fn record_managed_activity(&self) {
        self.inner.maintenance.record_activity();
    }

    /// Arms idle reclamation after the scheduler becomes globally idle.
    pub(crate) fn record_global_idle(&self) {
        self.inner.maintenance.record_idle(&self.inner);
    }

    /// Acquires at least `min_bytes` under one reservation.
    ///
    /// Capacity is rounded up to complete carriers. The reservation must
    /// belong to this pool, remain open, and retain enough direct-acquisition
    /// authority for the rounded request. Failure exposes no partial carrier
    /// ownership.
    pub(crate) fn acquire(
        &self,
        reservation: &Reservation,
        min_bytes: usize,
    ) -> Result<PooledBufMut, AcquireError> {
        let count = self.acquisition_count(min_bytes)?;
        let direct = reservation
            .acquisition_state()
            .ok_or(AcquireError::ReservationClosed)?;
        if !direct.belongs_to(&self.inner) {
            return Err(AcquireError::ForeignReservation);
        }
        let direct = Arc::clone(direct);
        let guards = acquire_count(&self.inner, Some(Arc::clone(&direct)), count)?;
        PooledBufMut::try_new(GrowthAuthority::reserved(direct), guards)
    }

    /// Acquires at least `min_bytes` without reservation-local authority.
    ///
    /// Capacity is rounded up to complete carriers. The request still
    /// participates in aggregate accounting and may prepare physical capacity
    /// or raise admission above its normal configured ceiling. Failure exposes
    /// no partial carrier ownership.
    pub(crate) fn acquire_unreserved(
        &self,
        min_bytes: usize,
    ) -> Result<PooledBufMut, AcquireError> {
        let count = self.acquisition_count(min_bytes)?;
        let guards = acquire_count(&self.inner, None, count)?;
        PooledBufMut::try_new(GrowthAuthority::unreserved(Arc::clone(&self.inner)), guards)
    }

    /// Converts one public byte request to its checked carrier envelope.
    fn reservation_envelope(&self, bytes: usize) -> Result<CarrierCount, ReserveError> {
        let envelope = self
            .inner
            .geometry
            .carriers_for_bytes(bytes)
            .map_err(map_reservation_geometry_error)?;
        if envelope > MAX_PACKED_CARRIERS {
            return Err(ReserveError::CapacityOverflow);
        }
        Ok(envelope)
    }

    /// Converts one acquisition request to its complete carrier count.
    fn acquisition_count(&self, min_bytes: usize) -> Result<CarrierCount, AcquireError> {
        self.inner
            .geometry
            .carriers_for_bytes(min_bytes)
            .map_err(|error| match error {
                GeometryError::ZeroByteRequest => AcquireError::InvalidSize,
                _ => AcquireError::CapacityOverflow,
            })
    }
}

/// Shared state retained by pool handles, reservations, and carrier owners.
struct PoolInner {
    /// Immutable page, block, carrier, and bitmap dimensions.
    geometry: PoolGeometry,
    /// Planned-demand policy and prepared-capacity serialization.
    admission: Mutex<AdmissionState>,
    /// Repayment ordering and the reservation FIFO's drain requirement.
    reservation_drain: ReservationDrainSignal,
    /// Whole-value returns currently publishing physical ownership.
    #[cfg(not(all(test, s3_tm_loom)))]
    active_owner_returns: AtomicUsize,
    /// Aggregate charges updated by carrier acquisition and final return.
    coverage: CoverageState,
    /// Stable virtual ranges and physical carrier ownership.
    arena: Arena,
    /// Lazy maintenance and optional diagnostic-reporting worker.
    maintenance: MaintenanceCoordinator,
    /// Per-pool failure injection and test-only observations.
    #[cfg(test)]
    test_hooks: TestHooks,
}

/// Reservation pressure captured while admission state is coherent.
#[derive(Clone, Copy)]
struct ReservationQueueSample {
    /// Empty-boundary transition and any data specific to it.
    event: ReservationQueueEvent,
    /// Requests retained in FIFO order at this transition.
    queued_reservations: usize,
    /// Pool-lifetime requests that have entered the FIFO.
    reservation_enqueues_total: u64,
    /// Planned demand and uncovered ownership after this enqueue.
    admission_used: CarrierCount,
    /// Normal admission ceiling.
    configured_capacity: CarrierCount,
}

/// A reservation FIFO crossing its empty boundary.
#[derive(Clone, Copy)]
enum ReservationQueueEvent {
    /// The FIFO became non-empty for this request.
    BecameNonempty { requested: CarrierCount },
    /// The FIFO became empty.
    BecameEmpty,
}

/// FIFO work and an optional empty-boundary transition captured under admission.
struct ReservationDrain {
    wakers: Vec<Waker>,
    queue_sample: Option<ReservationQueueSample>,
}

impl PoolInner {
    /// Constructs an empty pool domain without reserving virtual ranges.
    fn new(
        geometry: PoolGeometry,
        configured_capacity: CarrierCount,
        diagnostics: MemoryDiagnosticsConfig,
        arena_options: ArenaOptions,
    ) -> Result<Self, ArenaError> {
        Ok(Self {
            geometry,
            admission: Mutex::new(AdmissionState::new(configured_capacity)),
            reservation_drain: ReservationDrainSignal::new(),
            #[cfg(not(all(test, s3_tm_loom)))]
            active_owner_returns: AtomicUsize::new(0),
            coverage: CoverageState::new(),
            arena: Arena::new(geometry, arena_options)?,
            maintenance: MaintenanceCoordinator::new(
                configured_capacity,
                geometry,
                diagnostics.snapshot_interval(),
            ),
            #[cfg(test)]
            test_hooks: TestHooks::new(),
        })
    }

    /// Returns one coherent admission and aggregate memory sample.
    fn memory_metrics(&self) -> MemoryMetrics {
        let admission = self.admission.lock();
        self.memory_metrics_locked(&admission)
    }

    /// Takes memory and reservation-queue state at one diagnostic boundary.
    fn diagnostic_memory_sample(
        &self,
        now: std::time::Instant,
    ) -> (MemoryMetrics, admission::ReservationQueueDiagnosticSample) {
        let mut admission = self.admission.lock();
        let queue = admission.take_queue_diagnostics(now);
        let metrics = self.memory_metrics_locked(&admission);
        (metrics, queue)
    }

    /// Builds public memory metrics while admission remains coherent.
    fn memory_metrics_locked(&self, admission: &AdmissionState) -> MemoryMetrics {
        let coverage = self.coverage.snapshot();
        admission.ledger.assert_invariants(coverage);

        let admission_used = admission
            .ledger
            .admission_used(coverage)
            .unwrap_or_else(|_| invariant_violation("completed admission exceeds packed capacity"));
        let covered_charges = admission
            .ledger
            .active_planned_demand
            .checked_sub(coverage.available)
            .unwrap_or_else(|| {
                invariant_violation("available coverage exceeds active planned demand")
            });
        let charged_capacity = covered_charges
            .checked_add(coverage.uncovered)
            .unwrap_or_else(|| invariant_violation("completed charges exceed packed capacity"));

        MemoryMetrics::from_carriers(
            self.geometry.carrier_size(),
            MemoryMetricState {
                configured_capacity: admission.ledger.configured_capacity,
                admission_used,
                active_planned_demand: admission.ledger.active_planned_demand,
                charged_capacity,
                prepared_capacity: admission.ledger.prepared_capacity,
                queued_reservations: admission.waiter_count(),
                reservation_enqueues_total: admission.reservation_enqueues_total(),
            },
        )
    }

    /// Attempts an aggregate debit without admission serialization.
    ///
    /// `Ok(false)` leaves accounting unchanged and requires the caller to use
    /// the serialized shortfall path.
    fn try_debit_covered(&self, count: CarrierCount) -> Result<bool, ReserveError> {
        self.coverage
            .try_debit_covered(count)
            .map_err(|_| ReserveError::CapacityOverflow)
    }

    /// Publishes a shortfall debit and prepares through its admission floor.
    ///
    /// Failure reverses the aggregate debit before returning. The caller
    /// remains responsible for rolling back reservation-local authority.
    fn debit_and_prepare_locked(
        pool: &Arc<Self>,
        admission: &mut AdmissionGuard<'_>,
        count: CarrierCount,
    ) -> Result<CoverageDebit, ReserveError> {
        let debit = pool
            .coverage
            .debit(count, admission.maximum_uncovered())
            .map_err(|_| ReserveError::CapacityOverflow)?;

        let floor = match admission.acquisition_floor(&pool.coverage) {
            Ok(floor) => floor,
            Err(error) => {
                admission.rollback_acquisition(&pool.coverage, count, debit);
                return Err(error);
            }
        };
        if let Err(error) = pool.arena.prepare_to(admission, floor) {
            admission.rollback_acquisition(&pool.coverage, count, debit);
            Self::request_cleanup_after_arena_error(pool, &error);
            return Err(map_preparation_error(error));
        }
        Ok(debit)
    }

    /// Attempts one immediate grant without bypassing the FIFO.
    fn try_reserve_count(
        pool: &Arc<Self>,
        envelope: CarrierCount,
    ) -> Result<Option<Reservation>, ReserveError> {
        if envelope == CarrierCount::ZERO {
            return Err(ReserveError::InvalidSize);
        }
        if envelope > MAX_PACKED_CARRIERS {
            return Err(ReserveError::CapacityOverflow);
        }

        let mut admission = AdmissionGuard::new(pool.admission.lock());
        admission.validate_envelope(envelope)?;
        if !admission.inner.waiters_is_empty() {
            return Ok(None);
        }
        let coverage = pool.coverage.snapshot();
        if !admission.can_grant(coverage, envelope) {
            return Ok(None);
        }

        Self::prepare_and_grant_locked(pool, &mut admission, envelope).map(Some)
    }

    /// Grants one first-poll request or links it behind existing work.
    fn reserve_or_enqueue(
        pool: &Arc<Self>,
        envelope: CarrierCount,
        waker: Waker,
    ) -> Result<ReservationPoll, ReserveError> {
        #[cfg(test)]
        if let Some(error) = pool.test_hooks.take_reservation_failure() {
            return Err(error);
        }
        if envelope == CarrierCount::ZERO {
            return Err(ReserveError::InvalidSize);
        }
        if envelope > MAX_PACKED_CARRIERS {
            return Err(ReserveError::CapacityOverflow);
        }

        let mut admission = AdmissionGuard::new(pool.admission.lock());
        admission.validate_envelope(envelope)?;
        pool.reservation_drain.arm();
        let coverage = pool.coverage.snapshot();
        if admission.inner.waiters_is_empty() && admission.can_grant(coverage, envelope) {
            let result = Self::prepare_and_grant_locked(pool, &mut admission, envelope)
                .map(ReservationPoll::Ready);
            pool.reservation_drain
                .publish_waiter_state(!admission.inner.waiters_is_empty());
            return result;
        }

        let slot = Arc::new(WaitSlot::new(waker));
        #[cfg(test)]
        if pool.test_hooks.take_reservation_queue_allocation_failure() {
            pool.reservation_drain
                .publish_waiter_state(!admission.inner.waiters_is_empty());
            return Err(ReserveError::MetadataAllocationFailed);
        }
        let queue_became_nonempty = match admission.inner.enqueue_waiter(
            Waiter {
                envelope,
                slot: Arc::clone(&slot),
            },
            std::time::Instant::now(),
        ) {
            Ok(queue_became_nonempty) => queue_became_nonempty,
            Err(_) => {
                pool.reservation_drain
                    .publish_waiter_state(!admission.inner.waiters_is_empty());
                return Err(ReserveError::MetadataAllocationFailed);
            }
        };
        pool.reservation_drain
            .publish_waiter_state(!admission.inner.waiters_is_empty());
        let queue_sample = queue_became_nonempty
            .then(|| {
                Self::reservation_queue_sample(
                    &admission,
                    &pool.coverage,
                    ReservationQueueEvent::BecameNonempty {
                        requested: envelope,
                    },
                )
            })
            .flatten();
        drop(admission);
        if let Some(sample) = queue_sample {
            pool.log_reservation_queue_transition(sample);
        }
        Ok(ReservationPoll::Queued(slot))
    }

    /// Removes one cancelled queue link and reconsiders the exposed head.
    fn cancel_waiter(pool: &Arc<Self>, slot: &Arc<WaitSlot>) -> Vec<Waker> {
        let mut admission = AdmissionGuard::new(pool.admission.lock());
        let queue_became_empty = admission
            .inner
            .remove_waiter(slot, std::time::Instant::now());
        let drained = Self::drain_fifo_locked(pool, &mut admission, queue_became_empty);
        drop(admission);
        if let Some(sample) = drained.queue_sample {
            pool.log_reservation_queue_transition(sample);
        }
        drained.wakers
    }

    /// Prepares and publishes one grant while admission is serialized.
    fn prepare_and_grant_locked(
        pool: &Arc<Self>,
        admission: &mut AdmissionGuard<'_>,
        envelope: CarrierCount,
    ) -> Result<Reservation, ReserveError> {
        let coverage = pool.coverage.snapshot();
        let target = admission.grant_target(coverage, envelope)?;
        if let Err(error) = pool.arena.prepare_to(admission, target) {
            Self::request_cleanup_after_arena_error(pool, &error);
            return Err(map_preparation_error(error));
        }
        admission.commit_grant(&pool.coverage, envelope)?;
        Ok(Reservation::new(Arc::clone(pool), envelope))
    }

    /// Transfers every eligible FIFO head and returns wakers for post-unlock use.
    fn drain_fifo_locked(
        pool: &Arc<Self>,
        admission: &mut AdmissionGuard<'_>,
        mut queue_became_empty: bool,
    ) -> ReservationDrain {
        let mut wakers = Vec::new();
        while let Some(front) = admission.inner.front_waiter() {
            let envelope = front.envelope;
            let slot = Arc::clone(&front.slot);
            let mut slot_state = slot.state.lock();

            match &*slot_state {
                WaitState::Taken => {
                    let (_, cleared) = admission.inner.pop_front_waiter(std::time::Instant::now());
                    queue_became_empty |= cleared;
                    continue;
                }
                WaitState::Queued { .. } => {}
                WaitState::Granted(_) | WaitState::Failed(_) => {
                    invariant_violation("terminal reservation result remained linked in the FIFO");
                }
            }

            let coverage = pool.coverage.snapshot();
            if !admission.can_grant(coverage, envelope) {
                break;
            }

            let result = Self::prepare_and_grant_locked(pool, admission, envelope);
            let previous = std::mem::replace(&mut *slot_state, WaitState::Taken);
            let WaitState::Queued { waker } = previous else {
                invariant_violation("reservation head changed while its slot lock was held");
            };
            *slot_state = match result {
                Ok(reservation) => WaitState::Granted(reservation),
                Err(error) => WaitState::Failed(error),
            };

            let (removed, cleared) = admission.inner.pop_front_waiter(std::time::Instant::now());
            queue_became_empty |= cleared;
            let Some(removed) = removed else {
                invariant_violation("reservation head disappeared while admission was held");
            };
            if !Arc::ptr_eq(&removed.slot, &slot) {
                invariant_violation("FIFO head changed while admission was held");
            }
            wakers.push(waker);
        }
        pool.reservation_drain
            .publish_waiter_state(!admission.inner.waiters_is_empty());
        let queue_sample = queue_became_empty
            .then(|| {
                Self::reservation_queue_sample(
                    admission,
                    &pool.coverage,
                    ReservationQueueEvent::BecameEmpty,
                )
            })
            .flatten();
        ReservationDrain {
            wakers,
            queue_sample,
        }
    }

    /// Retires aggregate charges and reconsiders work exposed by repayment.
    ///
    /// Physical ownership and direct provenance are returned before this
    /// boundary. Coverage-only returns stay lock-free. Repayment of uncovered
    /// charges enters admission only when a reservation poll may be queued and
    /// invokes wakers only after unlocking.
    fn release_acquisition_charges(pool: &Arc<Self>, count: CarrierCount) {
        let returned = pool.coverage.release(count);
        Self::drain_after_coverage_return(pool, returned.uncovered_removed);
    }

    /// Reverses charges that never became carrier owners.
    fn rollback_acquisition_charges(pool: &Arc<Self>, count: CarrierCount, debit: CoverageDebit) {
        let drained = {
            let mut admission = AdmissionGuard::new(pool.admission.lock());
            let returned = pool.coverage.rollback_debit(
                count,
                debit,
                admission.inner.ledger.active_planned_demand,
            );
            let drained = (returned.uncovered_removed != CarrierCount::ZERO)
                .then(|| Self::drain_fifo_locked(pool, &mut admission, false));
            admission
                .inner
                .ledger
                .assert_invariants(pool.coverage.snapshot());
            drained
        };
        if let Some(drained) = drained {
            if let Some(sample) = drained.queue_sample {
                pool.log_reservation_queue_transition(sample);
            }
            wake_all(drained.wakers);
        }
    }

    /// Reconsiders reservation admission after uncovered pressure decreases.
    fn drain_after_coverage_return(pool: &Arc<Self>, uncovered_removed: CarrierCount) {
        if uncovered_removed == CarrierCount::ZERO
            || !pool.reservation_drain.repayment_requires_drain()
        {
            return;
        }

        #[cfg(test)]
        pool.test_hooks.record_return_admission_entry();
        let drained = {
            let mut admission = AdmissionGuard::new(pool.admission.lock());
            let drained = Self::drain_fifo_locked(pool, &mut admission, false);
            admission
                .inner
                .ledger
                .assert_invariants(pool.coverage.snapshot());
            drained
        };
        if let Some(sample) = drained.queue_sample {
            pool.log_reservation_queue_transition(sample);
        }
        wake_all(drained.wakers);
    }

    /// Marks one whole-value return and selects its physical publication mode.
    fn begin_owner_return(pool: &Arc<Self>) -> OwnerReturnPermit {
        // Overlap detection selects between two equivalent return strategies.
        // Modeling it multiplies every multi-owner drop in unrelated Loom
        // tests; the queue-driven batch path retains modeled synchronization.
        #[cfg(not(all(test, s3_tm_loom)))]
        let previous = pool.active_owner_returns.fetch_add(1, Ordering::AcqRel);
        #[cfg(not(all(test, s3_tm_loom)))]
        let overlapping = previous != 0;
        #[cfg(all(test, s3_tm_loom))]
        let overlapping = false;
        OwnerReturnPermit {
            pool: Arc::clone(pool),
            batch: overlapping || pool.reservation_drain.is_armed(),
        }
    }

    /// Schedules recovery when block preparation leaves a slot nonclaimable.
    fn request_cleanup_after_arena_error(pool: &Arc<Self>, error: &ArenaError) {
        if !error.cleanup_required() {
            return;
        }
        tracing::warn!(
            target: crate::telemetry::TARGET_MEMORY,
            error = %error,
            "buffer-pool preparation failed; mapping cleanup was scheduled"
        );
        pool.maintenance.request_cleanup(pool);
    }

    /// Captures one reservation-queue transition while admission is coherent.
    fn reservation_queue_sample(
        admission: &AdmissionGuard<'_>,
        coverage: &CoverageState,
        event: ReservationQueueEvent,
    ) -> Option<ReservationQueueSample> {
        let admission_used = admission
            .inner
            .ledger
            .admission_used(coverage.snapshot())
            .ok()?;
        Some(ReservationQueueSample {
            event,
            queued_reservations: admission.inner.waiter_count(),
            reservation_enqueues_total: admission.inner.reservation_enqueues_total(),
            admission_used,
            configured_capacity: admission.inner.ledger.configured_capacity,
        })
    }

    /// Logs one reservation FIFO empty-boundary transition.
    fn log_reservation_queue_transition(&self, sample: ReservationQueueSample) {
        if !tracing::enabled!(
            target: crate::telemetry::TARGET_MEMORY,
            tracing::Level::DEBUG
        ) {
            return;
        }

        match sample.event {
            ReservationQueueEvent::BecameNonempty { requested } => tracing::debug!(
                target: crate::telemetry::TARGET_MEMORY,
                requested_bytes = self.carriers_to_bytes(requested),
                queued_reservations = sample.queued_reservations,
                reservation_enqueues_total = sample.reservation_enqueues_total,
                admission_used_bytes = self.carriers_to_bytes(sample.admission_used),
                configured_capacity_bytes = self.carriers_to_bytes(sample.configured_capacity),
                "buffer-pool reservation queue became non-empty"
            ),
            ReservationQueueEvent::BecameEmpty => tracing::debug!(
                target: crate::telemetry::TARGET_MEMORY,
                queued_reservations = sample.queued_reservations,
                reservation_enqueues_total = sample.reservation_enqueues_total,
                admission_used_bytes = self.carriers_to_bytes(sample.admission_used),
                configured_capacity_bytes = self.carriers_to_bytes(sample.configured_capacity),
                "buffer-pool reservation queue became empty"
            ),
        }
    }

    /// Converts one checked carrier count to its byte representation.
    fn carriers_to_bytes(&self, count: CarrierCount) -> u64 {
        let count = u64::try_from(count.get()).unwrap_or(u64::MAX);
        let carrier_size = u64::try_from(self.geometry.carrier_size()).unwrap_or(u64::MAX);
        count.saturating_mul(carrier_size)
    }
}

/// One whole-value return participating in pool-local contention detection.
///
/// The permit owns the pool independently of any carrier guard. Drop paths can
/// therefore drain their mutable owner collections while the permit remains
/// live and still retire the active-return count afterward.
pub(super) struct OwnerReturnPermit {
    /// Pool whose active-return count this permit decrements on drop.
    pool: Arc<PoolInner>,
    /// Whether this return should use the batched physical path.
    batch: bool,
}

impl OwnerReturnPermit {
    /// Returns whether contention or queued admission warrants batching.
    pub(super) fn should_batch(&self) -> bool {
        self.batch
    }
}

impl Drop for OwnerReturnPermit {
    fn drop(&mut self) {
        #[cfg(not(all(test, s3_tm_loom)))]
        {
            let previous = self
                .pool
                .active_owner_returns
                .fetch_sub(1, Ordering::AcqRel);
            if previous == 0 {
                invariant_violation("owner-return permit underflowed");
            }
        }
    }
}

impl Drop for PoolInner {
    fn drop(&mut self) {
        self.maintenance.shutdown();
    }
}

fn map_reservation_geometry_error(error: GeometryError) -> ReserveError {
    match error {
        GeometryError::ZeroByteRequest => ReserveError::InvalidSize,
        _ => invariant_violation("checked geometry rejected byte-to-carrier conversion"),
    }
}

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

/// A count of fixed-size carriers.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
struct CarrierCount(usize);

impl CarrierCount {
    /// No carriers.
    const ZERO: Self = Self(0);

    /// Wraps a carrier count.
    const fn new(value: usize) -> Self {
        Self(value)
    }

    /// Returns the underlying count.
    fn get(self) -> usize {
        self.0
    }

    /// Adds two counts, returning `None` on overflow.
    fn checked_add(self, other: Self) -> Option<Self> {
        self.0.checked_add(other.0).map(Self)
    }

    /// Subtracts two counts, returning `None` on underflow.
    fn checked_sub(self, other: Self) -> Option<Self> {
        self.0.checked_sub(other.0).map(Self)
    }

    /// Converts this count to the packed accounting lane width.
    fn try_as_u32(self) -> Option<u32> {
        u32::try_from(self.0).ok()
    }
}

/// Stops execution after an internal buffer-pool invariant fails.
#[cold]
#[track_caller]
fn invariant_violation(message: &'static str) -> ! {
    tracing::error!(
        target: crate::telemetry::TARGET_MEMORY,
        reason = message,
        "buffer-pool invariant violated; aborting"
    );

    #[cfg(test)]
    panic!("buffer-pool invariant violated: {message}");

    #[cfg(not(test))]
    {
        let _ = message;
        std::process::abort()
    }
}