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

//! Multi-producer, single-consumer submission queue with opportunistic batching.
//!
//! Multiple producers push items concurrently into a fixed-capacity backing array.
//! The last producer to complete a submission becomes the consumer and receives a
//! [`SubmissionGuard`] with contiguous access to the batch.
//!
//! Producers follow the [`enter`](SubmissionQueue::enter) / [`push`](Submission::push) /
//! [`submit`](Submission::submit) protocol. A `Mutex` + `Condvar` pair protects
//! submission state (a pending count and a flushing flag); the critical section
//! only increments or decrements integers. Slot claiming and writing is lock-free
//! (atomic `fetch_add` on the tail index).
//!
//! ```text
//!  Producer threads                            Consumer (last out)
//!  ┌──────────┐ ┌──────────┐ ┌──────────┐
//!  │ enter()  │ │ enter()  │ │ enter()  │
//!  │ push(w1) │ │ push(w2) │ │ push(w3) │
//!  │ submit() │ │ submit() │ │ submit() │──→ SubmissionGuard
//!  │ = None   │ │ = None   │ │ = Some   │    ┌─────────────────┐
//!  └──────────┘ └──────────┘ └──────────┘    │ [w1, w2, w3]    │
//!                                            │ as_slice()      │
//!                                            │ as_mut_slice()  │
//!                                            │ drain() → iter  │
//!                                            └─────────────────┘
//!
//!  ┌─────────────────────────────────────────────────────────┐
//!  │ Backing array (fixed capacity, reused across rounds)    │
//!  │ ┌────┬────┬────┬────┬────┬────┬────┬────┐               │
//!  │ │ w1 │ w2 │ w3 │    │    │    │    │    │               │
//!  │ └────┴────┴────┴────┴────┴────┴────┴────┘               │
//!  │   ▲                  ▲                                  │
//!  │   0              tail (atomic)                          │
//!  └─────────────────────────────────────────────────────────┘
//! ```

use std::mem::MaybeUninit;

use crossbeam_utils::CachePadded;

use super::cell::UnsafeCell;
use super::sync::atomic::{AtomicUsize, Ordering};
use super::sync::{Condvar, Mutex};

/// Multi-producer submission queue backed by a fixed-capacity array.
///
/// Producers call [`enter`](Self::enter) to join a round, [`push`](Submission::push)
/// to write items into the backing array, and [`submit`](Submission::submit) to
/// complete their participation. The last producer to submit receives a
/// [`SubmissionGuard`] with access to the batch. Capacity is fixed at construction.
pub(crate) struct SubmissionQueue<T> {
    slots: Box<[UnsafeCell<MaybeUninit<T>>]>,
    tail: CachePadded<AtomicUsize>,
    state: Mutex<State>,
    not_flushing: Condvar,
    capacity: usize,
}

struct State {
    pending: usize,
    flushing: bool,
}

// Number of currently-live `Submission` handles held by this thread
// across nested `SubmissionQueue::enter` calls.
//
// The first `enter()` on a thread takes the shared-state path (grabs
// the state lock, increments `pending`, blocks on `not_flushing` if a
// flush is in progress). Subsequent re-entrant `enter()` calls on the
// same thread skip that path and participate as nested producers — they
// can still `push` items, but they don't bump `pending` and won't
// deadlock waiting for a flush that the outer frame owns.
//
// The counter is per-thread because `pending` is a global count of
// distinct producers, not a count of `Submission` handles. A single
// thread that re-enters via scheduler recursion is still one producer
// from the queue's perspective.
//
// The `loom::thread_local!` variant under `cfg(s3_tm_loom)` is per-
// loom-thread; `std::thread_local!` would be shared across all loom-
// simulated threads (they run on a single OS thread) and mis-classify
// separate loom threads as nested re-entries.
#[cfg(not(all(test, s3_tm_loom)))]
std::thread_local! {
    static SUBMISSION_DEPTH: core::cell::Cell<u32> = const { core::cell::Cell::new(0) };
}

#[cfg(all(test, s3_tm_loom))]
loom::thread_local! {
    static SUBMISSION_DEPTH: core::cell::Cell<u32> = core::cell::Cell::new(0);
}

fn incr_depth() -> u32 {
    SUBMISSION_DEPTH.with(|c| {
        let depth = c.get();
        c.set(depth + 1);
        depth
    })
}

fn decr_depth() {
    SUBMISSION_DEPTH.with(|c| c.set(c.get() - 1));
}

// Safety: producers write to distinct slots (claimed via atomic fetch_add on
// tail). The flusher has exclusive access after all producers exit. T: Send is
// required because items cross thread boundaries.
unsafe impl<T: Send> Send for SubmissionQueue<T> {}
unsafe impl<T: Send> Sync for SubmissionQueue<T> {}

/// Participation in a submission round. Provides [`push`](Self::push) access to
/// the queue and is consumed by [`submit`](Self::submit) to complete the round.
///
/// A `Submission` may be either *primary* or *nested*. The first `enter()` on
/// a thread returns a primary handle that holds one unit of the queue's global
/// `pending` count. Subsequent re-entrant `enter()` calls on the same thread
/// return nested handles — they can push items but don't affect `pending`.
///
/// If dropped without calling `submit` (e.g. due to a panic), the destructor
/// correctly accounts for both primary and nested cases.
pub(crate) struct Submission<'a, T> {
    sq: &'a SubmissionQueue<T>,
    /// True when this handle came from a re-entrant `enter()` on the same
    /// thread and does not own a unit of `pending`.
    nested: bool,
}

/// Exclusive access to items from a completed submission. Provides slice access
/// for inspection or grouping and [`drain`](Self::drain) for consuming items.
///
/// On drop, any undrained items are dropped and the queue is reset for the next
/// round, unblocking producers parked in [`enter`](SubmissionQueue::enter).
pub(crate) struct SubmissionGuard<'a, T> {
    sq: &'a SubmissionQueue<T>,
    count: usize,
    next: usize,
}

impl<T> SubmissionQueue<T> {
    /// Create a queue with the given fixed capacity.
    ///
    /// # Panics
    ///
    /// Panics if `capacity` is zero.
    pub(crate) fn new(capacity: usize) -> Self {
        assert!(capacity > 0, "capacity must be non-zero");
        let slots: Box<[UnsafeCell<MaybeUninit<T>>]> = (0..capacity)
            .map(|_| UnsafeCell::new(MaybeUninit::uninit()))
            .collect();
        Self {
            slots,
            tail: CachePadded::new(AtomicUsize::new(0)),
            state: Mutex::new(State {
                pending: 0,
                flushing: false,
            }),
            not_flushing: Condvar::new(),
            capacity,
        }
    }

    /// Enter a submission round.
    ///
    /// For the first call on a given thread, this blocks while a flush is in
    /// progress and then increments the global `pending` count. For re-entrant
    /// calls on the same thread, it returns a nested handle immediately
    /// without blocking or bumping `pending` — the outer primary handle
    /// already owns this thread's contribution to the round.
    pub(crate) fn enter(&self) -> Submission<'_, T> {
        let depth = incr_depth();
        if depth > 0 {
            // Re-entrant on this thread — the outer primary handle already
            // holds the pending contribution; we just participate in pushes.
            return Submission {
                sq: self,
                nested: true,
            };
        }
        let mut state = self.state.lock();
        let mut parked = false;
        while state.flushing {
            if !parked {
                tracing::trace!(
                    target: crate::telemetry::TARGET_SCHEDULING,
                    phase = "enter_blocked",
                    pending = state.pending,
                    "enter blocked on flush in progress"
                );
                parked = true;
            }
            state = self.not_flushing.wait(state);
        }
        if parked {
            tracing::trace!(
                target: crate::telemetry::TARGET_SCHEDULING,
                phase = "enter_unblocked",
                pending = state.pending,
                "enter unblocked"
            );
        }
        state.pending += 1;
        Submission {
            sq: self,
            nested: false,
        }
    }

    /// Number of items the queue can hold per round.
    #[allow(dead_code)] // TODO: runtime observability
    pub(crate) fn capacity(&self) -> usize {
        self.capacity
    }
}

impl<'a, T> Submission<'a, T> {
    /// Push an item into the next available slot. Returns `Err(item)` if the
    /// queue is full.
    ///
    /// Slot claiming is lock-free — it uses an atomic `fetch_add` on the tail
    /// index.
    #[inline]
    pub(crate) fn push(&self, item: T) -> Result<(), T> {
        let idx = self.sq.tail.fetch_add(1, Ordering::Relaxed);
        if idx >= self.sq.capacity {
            self.sq.tail.fetch_sub(1, Ordering::Relaxed);
            return Err(item);
        }
        // Safety: this slot was uniquely claimed via atomic fetch_add.
        self.sq.slots[idx].with_mut(|ptr| unsafe { (*ptr).write(item) });
        Ok(())
    }

    /// Complete the submission.
    ///
    /// For a primary handle, decrements `pending`. If this was the last
    /// primary out, transitions the queue into the flushing phase and returns
    /// a [`SubmissionGuard`] granting exclusive access to the batch.
    ///
    /// For a nested handle, returns `None` immediately — the outer primary
    /// will perform the flush. Items pushed via the nested handle remain in
    /// the queue and are included in that flush.
    pub(crate) fn submit(self) -> Option<SubmissionGuard<'a, T>> {
        decr_depth();
        if self.nested {
            std::mem::forget(self);
            return None;
        }
        let sq = self.sq;
        std::mem::forget(self);
        let mut state = sq.state.lock();
        state.pending -= 1;
        if state.pending == 0 {
            state.flushing = true;
            drop(state);
            let count = sq.tail.swap(0, Ordering::Relaxed).min(sq.capacity);
            tracing::trace!(
                target: crate::telemetry::TARGET_SCHEDULING,
                phase = "flush_start",
                count,
                "submission flush starting",
            );
            Some(SubmissionGuard { sq, count, next: 0 })
        } else {
            // Deliberately not logging the no-flush path: it fires on every
            // submit under concurrent producers and drowns useful events.
            // The absence of `flush_start` over time is the diagnostic
            // signal (stuck flushing => no flush_start; stuck pending =>
            // flush_start fires but with unexpected `count` or never).
            None
        }
    }
}

impl<T> Drop for Submission<'_, T> {
    fn drop(&mut self) {
        decr_depth();
        if self.nested {
            // A nested handle owns no `pending` contribution and no slot
            // ownership. Items it pushed are claimed by the outer primary.
            return;
        }
        let mut state = self.sq.state.lock();
        state.pending -= 1;
        if state.pending == 0 && !state.flushing {
            let count = self
                .sq
                .tail
                .swap(0, Ordering::Relaxed)
                .min(self.sq.capacity);
            for i in 0..count {
                // Safety: slots 0..count were filled by producers and no
                // SubmissionGuard exists, so we have exclusive access.
                self.sq.slots[i].with_mut(|ptr| unsafe { (*ptr).assume_init_drop() });
            }
        }
    }
}

impl<T> SubmissionGuard<'_, T> {
    /// Number of items in this batch.
    #[allow(dead_code)] // TODO: runtime observability
    pub(crate) fn len(&self) -> usize {
        self.count - self.next
    }

    /// Whether the batch is empty.
    #[allow(dead_code)] // TODO: runtime observability
    pub(crate) fn is_empty(&self) -> bool {
        self.next >= self.count
    }

    /// View the remaining items as a shared slice.
    ///
    /// Safety relies on flushing being true (no producers are writing) and all
    /// slots in `next..count` being initialized.
    #[allow(dead_code)] // TODO: wire into runtime dispatch
    pub(crate) fn as_slice(&self) -> &[T] {
        // Safety: flushing is true so no producers are writing. All slots in
        // next..count were initialized by producers.
        //
        // We derive the pointer from the boxed slice (a single allocation),
        // not from an individual UnsafeCell, so the provenance covers the
        // entire range. UnsafeCell<MaybeUninit<T>> is #[repr(transparent)]
        // through both layers, so the cast is layout-correct.
        unsafe {
            let base = self.sq.slots.as_ptr().add(self.next) as *const T;
            std::slice::from_raw_parts(base, self.count - self.next)
        }
    }

    /// View the remaining items as a mutable slice.
    ///
    /// Safety relies on flushing being true (no producers are writing) and all
    /// slots in `next..count` being initialized.
    #[allow(dead_code)] // TODO: wire into runtime dispatch
    pub(crate) fn as_mut_slice(&mut self) -> &mut [T] {
        // Safety: same as as_slice, plus we have exclusive &mut access.
        unsafe {
            let base = self.sq.slots.as_ptr().add(self.next) as *mut T;
            std::slice::from_raw_parts_mut(base, self.count - self.next)
        }
    }

    /// Iterate over the submitted items, consuming each one.
    pub(crate) fn drain(&mut self) -> impl Iterator<Item = T> + '_ {
        (self.next..self.count).map(|i| {
            self.next = i + 1;
            // Safety: the flusher has exclusive access — all producers have
            // exited and flushing is true, blocking new entrants.
            self.sq.slots[i].with_mut(|ptr| unsafe { (*ptr).assume_init_read() })
        })
    }
}

impl<T> Drop for SubmissionGuard<'_, T> {
    fn drop(&mut self) {
        for i in self.next..self.count {
            self.sq.slots[i].with_mut(|ptr| unsafe { (*ptr).assume_init_drop() });
        }
        let mut state = self.sq.state.lock();
        state.flushing = false;
        self.sq.not_flushing.notify_all();
        tracing::trace!(
            target: crate::telemetry::TARGET_SCHEDULING,
            phase = "flush_end",
            "submission flush complete",
        );
    }
}

impl<T> Drop for SubmissionQueue<T> {
    fn drop(&mut self) {
        let count = self.tail.load(Ordering::Relaxed).min(self.capacity);
        for i in 0..count {
            self.slots[i].with_mut(|ptr| unsafe { (*ptr).assume_init_drop() });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::Arc;

    #[derive(Debug, Clone)]
    struct DropCounter(Arc<AtomicUsize>);
    impl Drop for DropCounter {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::Relaxed);
        }
    }
    fn drop_counter() -> (DropCounter, Arc<AtomicUsize>) {
        let count = Arc::new(AtomicUsize::new(0));
        (DropCounter(Arc::clone(&count)), count)
    }

    #[test]
    fn single_producer() {
        let q = SubmissionQueue::new(8);
        let s = q.enter();
        for i in [0, 10, 20] {
            s.push(i).unwrap();
        }
        let mut guard = s.submit().expect("single producer is last out");
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items, vec![0, 10, 20]);
    }

    #[test]
    fn submit_resets_for_next_round() {
        let q = SubmissionQueue::new(8);

        let s = q.enter();
        s.push(10).unwrap();
        s.push(20).unwrap();
        let mut guard = s.submit().unwrap();
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items, vec![10, 20]);
        drop(guard);

        let s = q.enter();
        s.push(30).unwrap();
        let mut guard = s.submit().unwrap();
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items, vec![30]);
    }

    #[test]
    fn push_returns_err_when_full() {
        let q = SubmissionQueue::<i32>::new(2);
        let s = q.enter();
        s.push(1).unwrap();
        s.push(2).unwrap();
        assert_eq!(s.push(3), Err(3));
        let mut guard = s.submit().unwrap();
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items, vec![1, 2]);
    }

    #[test]
    fn empty_round() {
        let q = SubmissionQueue::<i32>::new(8);
        let s = q.enter();
        let mut guard = s.submit().unwrap();
        assert!(guard.is_empty());
        assert_eq!(guard.len(), 0);
        assert_eq!(guard.drain().count(), 0);
    }

    #[test]
    fn multi_producer_all_items_flushed() {
        let q = Arc::new(SubmissionQueue::new(64));
        let flushed = Arc::new(AtomicUsize::new(0));

        let threads: Vec<_> = (0..8)
            .map(|i| {
                let q = Arc::clone(&q);
                let flushed = Arc::clone(&flushed);
                std::thread::spawn(move || {
                    let s = q.enter();
                    s.push(i).unwrap();
                    if let Some(mut guard) = s.submit() {
                        flushed.fetch_add(guard.drain().count(), Ordering::Relaxed);
                    }
                })
            })
            .collect();

        for t in threads {
            t.join().unwrap();
        }
        assert_eq!(flushed.load(Ordering::Relaxed), 8);
    }

    #[test]
    fn stress_multi_round() {
        const ROUNDS: usize = 1000;
        const PRODUCERS: usize = 8;

        let total = Arc::new(AtomicUsize::new(0));

        for _ in 0..ROUNDS {
            let q = Arc::new(SubmissionQueue::new(PRODUCERS * 2));
            let total = Arc::clone(&total);

            let threads: Vec<_> = (0..PRODUCERS)
                .map(|i| {
                    let q = Arc::clone(&q);
                    let total = Arc::clone(&total);
                    std::thread::spawn(move || {
                        let s = q.enter();
                        s.push(i).unwrap();
                        if let Some(mut guard) = s.submit() {
                            total.fetch_add(guard.drain().count(), Ordering::Relaxed);
                        }
                    })
                })
                .collect();

            for t in threads {
                t.join().unwrap();
            }
        }

        assert_eq!(total.load(Ordering::Relaxed), ROUNDS * PRODUCERS);
    }

    #[test]
    fn enter_parks_during_flush() {
        let q = Arc::new(SubmissionQueue::new(8));
        let flushing = Arc::new(AtomicBool::new(false));

        let q2 = Arc::clone(&q);
        let flushing2 = Arc::clone(&flushing);
        let flusher = std::thread::spawn(move || {
            let s = q2.enter();
            s.push(1).unwrap();
            let guard = s.submit().unwrap();
            flushing2.store(true, Ordering::Release);
            std::thread::sleep(std::time::Duration::from_millis(50));
            drop(guard);
        });

        while !flushing.load(Ordering::Acquire) {
            std::thread::yield_now();
        }

        let start = std::time::Instant::now();
        let s = q.enter();
        let waited = start.elapsed();
        assert!(waited.as_millis() >= 10, "enter should have blocked");
        s.submit();

        flusher.join().unwrap();
    }

    #[test]
    fn drop_unflushed_items() {
        let (dc, drops) = drop_counter();
        {
            let q = SubmissionQueue::new(8);
            let s = q.enter();
            s.push(dc.clone()).unwrap();
            s.push(dc.clone()).unwrap();
            s.push(dc).unwrap();
            let _guard = s.submit().unwrap();
        }
        assert_eq!(drops.load(Ordering::Relaxed), 3);
    }

    #[test]
    fn drain_then_drop_no_double_free() {
        let (dc, drops) = drop_counter();
        {
            let q = SubmissionQueue::new(8);
            let s = q.enter();
            s.push(dc.clone()).unwrap();
            s.push(dc).unwrap();
            let mut guard = s.submit().unwrap();
            let items: Vec<_> = guard.drain().collect();
            drop(items);
            assert_eq!(drops.load(Ordering::Relaxed), 2);
            drop(guard);
        }
        assert_eq!(drops.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn submission_drop_without_submit() {
        let (dc, drops) = drop_counter();
        let q = SubmissionQueue::new(8);
        {
            let s = q.enter();
            s.push(dc.clone()).unwrap();
            // drop Submission without submit — simulates panic path
        }
        assert_eq!(drops.load(Ordering::Relaxed), 1);

        // Queue is usable for a new round.
        let s = q.enter();
        s.push(dc).unwrap();
        let mut guard = s.submit().unwrap();
        assert_eq!(guard.drain().count(), 1);
    }

    #[test]
    fn batch_slice_access() {
        let q = SubmissionQueue::new(8);
        let s = q.enter();
        s.push(10).unwrap();
        s.push(20).unwrap();
        s.push(30).unwrap();
        let mut guard = s.submit().unwrap();
        assert_eq!(guard.as_slice(), &[10, 20, 30]);
        guard.as_mut_slice().reverse();
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items, vec![30, 20, 10]);
    }

    #[test]
    fn multiple_pushes_per_producer() {
        let q = SubmissionQueue::new(8);
        let s = q.enter();
        for i in 0..5 {
            s.push(i).unwrap();
        }
        let mut guard = s.submit().unwrap();
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items, vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn concurrent_push_and_flush_interleaving() {
        let q = Arc::new(SubmissionQueue::new(64));
        let total = Arc::new(AtomicUsize::new(0));
        let flushing = Arc::new(AtomicBool::new(false));

        // Thread A: enter, push, submit, hold guard for 50ms
        let q_a = Arc::clone(&q);
        let total_a = Arc::clone(&total);
        let flushing_a = Arc::clone(&flushing);
        let a = std::thread::spawn(move || {
            let s = q_a.enter();
            s.push(1).unwrap();
            let mut guard = s.submit().unwrap();
            flushing_a.store(true, Ordering::Release);
            std::thread::sleep(std::time::Duration::from_millis(50));
            total_a.fetch_add(guard.drain().count(), Ordering::Relaxed);
            drop(guard);
        });

        // Wait for A to hold the guard
        while !flushing.load(Ordering::Acquire) {
            std::thread::yield_now();
        }

        // Threads B and C: enter (will park), push, submit
        let mut handles = vec![];
        for _ in 0..2 {
            let q = Arc::clone(&q);
            let total = Arc::clone(&total);
            handles.push(std::thread::spawn(move || {
                let s = q.enter();
                s.push(1).unwrap();
                if let Some(mut guard) = s.submit() {
                    total.fetch_add(guard.drain().count(), Ordering::Relaxed);
                }
            }));
        }

        a.join().unwrap();
        for h in handles {
            h.join().unwrap();
        }

        assert_eq!(total.load(Ordering::Relaxed), 3);
    }

    #[test]
    fn reentrant_enter_does_not_deadlock() {
        // A single thread entering twice must not deadlock on `pending`.
        // The primary handle holds the `pending` contribution; the nested
        // handle is a no-op from the queue's perspective.
        let q: SubmissionQueue<i32> = SubmissionQueue::new(8);

        let outer = q.enter();
        outer.push(1).unwrap();

        // Nested enter on the same thread.
        let inner = q.enter();
        inner.push(2).unwrap();
        assert!(
            inner.submit().is_none(),
            "nested submit never returns a guard"
        );

        // Outer sees both items in its flush.
        let mut guard = outer.submit().expect("primary should flush");
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items.len(), 2);
        assert!(items.contains(&1));
        assert!(items.contains(&2));
    }

    #[test]
    fn reentrant_enter_does_not_bump_pending() {
        // Verify `pending` stays at 1 through re-entrant enter/submit cycles.
        let q: SubmissionQueue<i32> = SubmissionQueue::new(4);

        let outer = q.enter();
        assert_eq!(q.state.lock().pending, 1);

        let inner = q.enter();
        assert_eq!(
            q.state.lock().pending,
            1,
            "nested enter must not bump pending"
        );

        inner.submit();
        assert_eq!(
            q.state.lock().pending,
            1,
            "nested submit must not touch pending"
        );

        outer.submit();
        assert_eq!(q.state.lock().pending, 0);
    }

    #[test]
    fn nested_submission_drop_is_safe() {
        // Dropping a nested submission without calling submit must not
        // decrement pending or clean up slots.
        let q: SubmissionQueue<i32> = SubmissionQueue::new(4);
        let outer = q.enter();
        outer.push(10).unwrap();

        {
            let inner = q.enter();
            inner.push(20).unwrap();
            // inner drops here without submit
        }

        assert_eq!(
            q.state.lock().pending,
            1,
            "nested drop must not change pending"
        );

        let mut guard = outer.submit().expect("outer should flush");
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items.len(), 2, "both items should reach the flush");
    }

    #[test]
    fn cross_thread_entries_still_independent() {
        // Thread-local depth must not affect other threads. Backpressure
        // semantics for distinct threads remain as before.
        let q = Arc::new(SubmissionQueue::<i32>::new(8));

        let q2 = Arc::clone(&q);
        let outer = q.enter();
        assert_eq!(q.state.lock().pending, 1);

        let handle = std::thread::spawn(move || {
            let s = q2.enter();
            assert_eq!(
                q2.state.lock().pending,
                2,
                "different thread must bump pending"
            );
            s.push(1).unwrap();
            s.submit();
        });
        handle.join().unwrap();

        assert_eq!(q.state.lock().pending, 1);
        outer.submit();
    }

    #[test]
    fn reentrant_enter_during_push_overflow() {
        // The outer frame fills the queue; a nested enter on the same thread
        // cannot push more, mirroring the behaviour the outer would see.
        let q: SubmissionQueue<i32> = SubmissionQueue::new(2);

        let outer = q.enter();
        outer.push(1).unwrap();
        outer.push(2).unwrap();
        // Outer has filled the queue.

        let inner = q.enter();
        assert!(
            inner.push(3).is_err(),
            "queue is full, nested push should fail just like outer"
        );
        inner.submit();

        let mut guard = outer.submit().expect("outer flushes");
        let items: Vec<_> = guard.drain().collect();
        assert_eq!(items.len(), 2);
    }
}

#[cfg(all(test, s3_tm_loom))]
mod loom_tests {
    use super::super::sync::atomic::AtomicUsize as LoomAtomicUsize;
    use super::super::sync::Arc;
    use super::super::thread;
    use super::*;

    #[test]
    fn two_producers_both_flushed() {
        loom::model(|| {
            let q = Arc::new(SubmissionQueue::new(4));
            let total = Arc::new(LoomAtomicUsize::new(0));

            let q2 = Arc::clone(&q);
            let t2 = Arc::clone(&total);
            let h = thread::spawn(move || {
                let s = q2.enter();
                s.push(1).unwrap();
                if let Some(mut guard) = s.submit() {
                    t2.fetch_add(guard.drain().count(), Ordering::Relaxed);
                }
            });

            let s = q.enter();
            s.push(2).unwrap();
            if let Some(mut guard) = s.submit() {
                total.fetch_add(guard.drain().count(), Ordering::Relaxed);
            }

            h.join().unwrap();
            assert_eq!(total.load(Ordering::Relaxed), 2);
        });
    }

    #[test]
    fn enter_blocks_during_flush() {
        loom::model(|| {
            let q = Arc::new(SubmissionQueue::new(4));

            // Thread 1: enter, push, submit, drain, drop guard
            let q2 = Arc::clone(&q);
            let h = thread::spawn(move || {
                let s = q2.enter();
                s.push(10).unwrap();
                if let Some(mut guard) = s.submit() {
                    let _: Vec<_> = guard.drain().collect();
                    // guard dropped here, unblocking enter()
                }
            });

            // Thread 2: enter (may block if thread 1 holds guard), push, submit
            let s = q.enter();
            s.push(20).unwrap();
            if let Some(mut guard) = s.submit() {
                let _: Vec<_> = guard.drain().collect();
            }

            h.join().unwrap();
        });
    }

    #[test]
    fn capacity_exhaustion() {
        loom::model(|| {
            let q = Arc::new(SubmissionQueue::new(1));

            let q2 = Arc::clone(&q);
            let h = thread::spawn(move || {
                let s = q2.enter();
                let _ = s.push(1);
                if let Some(mut guard) = s.submit() {
                    let _: Vec<_> = guard.drain().collect();
                }
            });

            let s = q.enter();
            let _ = s.push(2);
            if let Some(mut guard) = s.submit() {
                let _: Vec<_> = guard.drain().collect();
            }

            h.join().unwrap();
        });
    }

    #[test]
    fn drop_without_submit() {
        loom::model(|| {
            let q = Arc::new(SubmissionQueue::new(4));

            let q2 = Arc::clone(&q);
            let h = thread::spawn(move || {
                let s = q2.enter();
                s.push(1).unwrap();
                // drop without submit — exercises the panic/cleanup path
            });

            h.join().unwrap();

            let s = q.enter();
            s.push(2).unwrap();
            let mut guard = s.submit().unwrap();
            let items: Vec<_> = guard.drain().collect();
            assert_eq!(items, vec![2]);
        });
    }

    #[test]
    fn partial_drain_then_drop() {
        loom::model(|| {
            let q = Arc::new(SubmissionQueue::new(4));
            let total = Arc::new(LoomAtomicUsize::new(0));

            let q2 = Arc::clone(&q);
            let t2 = Arc::clone(&total);
            let h = thread::spawn(move || {
                let s = q2.enter();
                s.push(10).unwrap();
                s.push(20).unwrap();
                if let Some(mut guard) = s.submit() {
                    // Drain only one item, drop guard with remainder
                    if let Some(_val) = guard.drain().next() {
                        t2.fetch_add(1, Ordering::Relaxed);
                    }
                    // guard drops here — remaining items must be dropped exactly once
                }
            });

            let s = q.enter();
            s.push(30).unwrap();
            if let Some(mut guard) = s.submit() {
                total.fetch_add(guard.drain().count(), Ordering::Relaxed);
            }

            h.join().unwrap();
            // All 3 items accounted for (drained or dropped)
            assert!(total.load(Ordering::Relaxed) >= 1);
        });
    }

    #[test]
    fn three_producers_multiple_pushes() {
        loom::model(|| {
            let q = Arc::new(SubmissionQueue::new(8));
            let total = Arc::new(LoomAtomicUsize::new(0));

            let mut handles = Vec::new();
            for _ in 0..2 {
                let q = Arc::clone(&q);
                let total = Arc::clone(&total);
                handles.push(thread::spawn(move || {
                    let s = q.enter();
                    s.push(1).unwrap();
                    s.push(2).unwrap();
                    if let Some(mut guard) = s.submit() {
                        total.fetch_add(guard.drain().count(), Ordering::Relaxed);
                    }
                }));
            }

            let s = q.enter();
            s.push(3).unwrap();
            s.push(4).unwrap();
            if let Some(mut guard) = s.submit() {
                total.fetch_add(guard.drain().count(), Ordering::Relaxed);
            }

            for h in handles {
                h.join().unwrap();
            }
            assert_eq!(total.load(Ordering::Relaxed), 6);
        });
    }
}