concurrent-sharded-stack 0.2.1

A lock-free concurrent stack that shards a Treiber stack per thread and reclaims memory with epoch-based GC.
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
//! A lock-free concurrent stack that shards a classic Treiber stack across
//! multiple per-thread shards and reclaims memory with epoch-based GC.
//!
//! See [`ConcurrentShardedStack`] for the main entry point. Compared to a
//! single Treiber stack, sharding spreads CAS contention across independent
//! cache-line-padded shards, at the cost of only providing LIFO ordering
//! *within* a shard rather than globally.
//!
//! # Example
//!
//! ```
//! use concurrent_sharded_stack::{ConcurrentShardedStack, PopError};
//!
//! let stack = ConcurrentShardedStack::with_concurrency(4);
//! stack.push(1).unwrap();
//! stack.push(2).unwrap();
//!
//! assert_eq!(stack.pop().unwrap(), 2);
//! assert_eq!(stack.pop().unwrap(), 1);
//! assert_eq!(stack.pop(), Err(PopError::Empty));
//! ```

use crossbeam_epoch::{self as epoch, Atomic, Guard, Owned};
use crossbeam_utils::CachePadded;
use std::cell::Cell;
use std::fmt;
use std::hint::spin_loop;
use std::mem::ManuallyDrop;
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

static NEXT_THREAD_ID: AtomicUsize = AtomicUsize::new(0);

const CLOSED_TAG: usize = 1;

thread_local! {
    static THREAD_ID: Cell<usize> = Cell::new(
        NEXT_THREAD_ID.fetch_add(1, Ordering::Relaxed)
    );
}

fn current_thread_id() -> usize {
    THREAD_ID.with(Cell::get)
}

#[derive(Debug, PartialEq, Eq)]
pub enum PushError<T> {
    /// The stack has been closed.
    Closed(T),
}

impl<T> PushError<T> {
    pub fn into_inner(self) -> T {
        match self {
            PushError::Closed(v) => v,
        }
    }
}

impl<T> fmt::Display for PushError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PushError::Closed(_) => write!(f, "stack is closed"),
        }
    }
}

impl<T: fmt::Debug> std::error::Error for PushError<T> {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PopError {
    Empty,
    Closed,
}

impl fmt::Display for PopError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PopError::Empty => write!(f, "stack is empty"),
            PopError::Closed => write!(f, "stack is closed"),
        }
    }
}

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

struct Node<T> {
    value: ManuallyDrop<T>,
    next: Atomic<Node<T>>,
}

impl<T> Node<T> {
    fn new(value: T) -> Self {
        Self {
            value: ManuallyDrop::new(value),
            next: Atomic::null(),
        }
    }
}

enum ShardPopResult<T> {
    Popped(T),
    Empty,
    EmptyAndClosed,
}

/// Concurrent sharded Treiber stack.
pub struct ConcurrentShardedStack<T> {
    shards: Box<[CachePadded<Atomic<Node<T>>>]>,
    shard_index_mask: usize,
}

unsafe impl<T: Send> Send for ConcurrentShardedStack<T> {}
unsafe impl<T: Send> Sync for ConcurrentShardedStack<T> {}

impl<T> Default for ConcurrentShardedStack<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> ConcurrentShardedStack<T> {
    /// Creates a stack using `available_parallelism()` as concurrency hint.
    pub fn new() -> Self {
        let concurrency = thread::available_parallelism()
            .map(|n| n.get().next_power_of_two())
            .unwrap_or(4);

        Self::with_concurrency(concurrency)
    }

    /// Creates a stack with exact shard count.
    ///
    /// Panics if:
    ///
    /// - `shard_count == 0`
    /// - `shard_count` is not power of two
    pub fn with_concurrency(shard_count: usize) -> Self {
        assert!(shard_count > 0, "shard_count must be non-zero");

        assert!(
            shard_count.is_power_of_two(),
            "shard_count must be a power of two"
        );

        let mut shards = Vec::with_capacity(shard_count);

        for _ in 0..shard_count {
            shards.push(CachePadded::new(Atomic::null()));
        }

        Self {
            shards: shards.into_boxed_slice(),
            shard_index_mask: shard_count - 1,
        }
    }

    /// Pushes a value into the stack.
    ///
    /// Returns `Err(PushError::Closed(value))` if the stack is already closed.
    pub fn push(&self, value: T) -> Result<(), PushError<T>> {
        let shard_index = self.current_shard_index();
        let shard = &self.shards[shard_index];

        let guard = &epoch::pin();
        let mut node = Owned::new(Node::new(value));

        loop {
            let head = shard.load(Ordering::Acquire, guard);

            if head.tag() == CLOSED_TAG {
                let node = node.into_box();
                let value = unsafe { ptr::read(&*node.value) };
                return Err(PushError::Closed(value));
            }

            node.next.store(head, Ordering::Relaxed);

            match shard.compare_exchange_weak(
                head,
                node,
                Ordering::Release,
                Ordering::Relaxed,
                guard,
            ) {
                Ok(_) => return Ok(()),
                Err(err) => {
                    node = err.new;
                    spin_loop();
                }
            }
        }
    }

    /// Pops a value from the stack non-blocking.
    ///
    /// Scan order:
    ///
    /// - first scan the current thread's own shard;
    /// - then scan the shard whose last binary bit differs;
    /// - then scan shards whose next binary bit differs;
    /// - continue widening the differing-bit window until all shards are scanned.
    ///
    /// For example, with 8 shards and local shard `start`, the XOR masks are:
    ///
    /// ```text
    /// 0,
    /// 1,
    /// 2, 3,
    /// 4, 5, 6, 7
    /// ```
    ///
    /// So the actual scan order is:
    ///
    /// ```text
    /// start,
    /// start ^ 1,
    /// start ^ 2, start ^ 3,
    /// start ^ 4, start ^ 5, start ^ 6, start ^ 7
    /// ```
    ///
    /// Returns `Err(PopError::Empty)` if no element is found and at least one
    /// shard is still observed open.
    ///
    /// Returns `Err(PopError::Closed)` if no element is found and every shard
    /// is observed closed.
    pub fn pop(&self) -> Result<T, PopError> {
        let guard = &epoch::pin();
        let start = self.current_shard_index();
        let shard_count = self.shards.len();

        let mut all_closed = true;

        for mask in 0..shard_count {
            let index = start ^ mask;

            match self.pop_one(index, guard) {
                ShardPopResult::Popped(value) => return Ok(value),
                ShardPopResult::Empty => {
                    all_closed = false;
                }
                ShardPopResult::EmptyAndClosed => {}
            }
        }

        if all_closed {
            Err(PopError::Closed)
        } else {
            Err(PopError::Empty)
        }
    }

    /// Closes the stack. Existing elements can still be popped.
    pub fn close(&self) -> bool {
        let guard = &epoch::pin();
        let mut changed = false;

        for shard in self.shards.iter() {
            loop {
                let head = shard.load(Ordering::Acquire, guard);

                if head.tag() == CLOSED_TAG {
                    break;
                }

                match shard.compare_exchange_weak(
                    head,
                    head.with_tag(CLOSED_TAG),
                    Ordering::AcqRel,
                    Ordering::Relaxed,
                    guard,
                ) {
                    Ok(_) => {
                        changed = true;
                        break;
                    }
                    Err(_) => spin_loop(),
                }
            }
        }

        changed
    }

    /// Checks if the stack is closed.
    pub fn is_closed(&self) -> bool {
        let guard = &epoch::pin();
        self.all_shards_closed(guard)
    }

    pub fn shard_count(&self) -> usize {
        self.shards.len()
    }

    fn current_shard_index(&self) -> usize {
        current_thread_id() & self.shard_index_mask
    }

    /// Pops from one shard.
    ///
    /// This function loops until the shard produces a definite result:
    ///
    /// - popped one value;
    /// - or the shard is observed empty.
    ///
    /// CAS failures are retried indefinitely for this shard. There is no fixed
    /// retry budget anymore.
    ///
    /// Returns:
    ///
    /// - `value: Some(T)` if a value was popped;
    /// - `value: None` if this shard is currently empty;
    /// - `closed` indicates whether this shard was observed closed.
    fn pop_one(&self, index: usize, guard: &Guard) -> ShardPopResult<T> {
        let shard = &self.shards[index];

        loop {
            let head = shard.load(Ordering::Acquire, guard);
            let closed = head.tag() == CLOSED_TAG;

            if head.is_null() {
                return if closed {
                    ShardPopResult::EmptyAndClosed
                } else {
                    ShardPopResult::Empty
                };
            }

            let head_ref = unsafe { head.deref() };

            // `head` was published by a Release CAS that we synchronized with
            // via the Acquire load above, so the node's fields are visible.
            let next = head_ref.next.load(Ordering::Relaxed, guard);

            // Preserve the CLOSED tag when popping from a closed shard.
            let new_head = next.with_tag(head.tag());

            match shard.compare_exchange(head, new_head, Ordering::AcqRel, Ordering::Relaxed, guard)
            {
                Ok(_) => {
                    // Move the value out of the popped node. The node itself
                    // is reclaimed later by epoch GC; because `value` is inside
                    // `ManuallyDrop<T>`, deferred destruction will not drop it again.
                    let value = unsafe { ptr::read(&*head_ref.value) };

                    unsafe {
                        guard.defer_destroy(head.with_tag(0));
                    }

                    return ShardPopResult::Popped(value);
                }
                Err(_) => {
                    spin_loop();
                }
            }
        }
    }

    fn all_shards_closed(&self, guard: &Guard) -> bool {
        self.shards
            .iter()
            .all(|shard| shard.load(Ordering::Acquire, guard).tag() == CLOSED_TAG)
    }
}

impl<T> Drop for ConcurrentShardedStack<T> {
    fn drop(&mut self) {
        let guard = &epoch::pin();

        for shard in self.shards.iter() {
            let mut current = shard.load(Ordering::Relaxed, guard);

            while !current.is_null() {
                unsafe {
                    let raw = current.as_raw() as *mut Node<T>;
                    let next = (*raw).next.load(Ordering::Relaxed, guard);

                    let mut node = Box::from_raw(raw);

                    // The value was never popped, so we are responsible for
                    // dropping it here. It lives inside a `ManuallyDrop<T>`.
                    ManuallyDrop::drop(&mut node.value);

                    drop(node);

                    current = next;
                }
            }
        }
    }
}

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

    #[derive(Debug)]
    struct DropCounter {
        counter: Arc<AtomicUsize>,
    }

    impl DropCounter {
        fn new(counter: Arc<AtomicUsize>) -> Self {
            Self { counter }
        }
    }

    impl Drop for DropCounter {
        fn drop(&mut self) {
            self.counter.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn new_requires_power_of_two() {
        let s = ConcurrentShardedStack::<usize>::with_concurrency(4);
        assert_eq!(s.shard_count(), 4);
    }

    #[test]
    #[should_panic]
    fn new_panics_if_not_power_of_two() {
        let _ = ConcurrentShardedStack::<usize>::with_concurrency(3);
    }

    #[test]
    fn push_pop_single_thread() {
        let s = ConcurrentShardedStack::with_concurrency(4);

        s.push(1).unwrap();
        s.push(2).unwrap();
        s.push(3).unwrap();

        assert_eq!(s.pop().unwrap(), 3);
        assert_eq!(s.pop().unwrap(), 2);
        assert_eq!(s.pop().unwrap(), 1);

        assert_eq!(s.pop(), Err(PopError::Empty));
    }

    #[test]
    fn close_works() {
        let s = ConcurrentShardedStack::with_concurrency(4);

        assert!(s.push(1).is_ok());

        assert!(s.close());
        assert!(!s.close());

        assert_eq!(s.push(2), Err(PushError::Closed(2)));

        assert_eq!(s.pop().unwrap(), 1);
        assert_eq!(s.pop(), Err(PopError::Closed));
    }

    #[test]
    fn multi_thread_push_pop() {
        let s = Arc::new(ConcurrentShardedStack::with_concurrency(8));

        let threads = 8;
        // Miri executes far slower, so use a much smaller workload there.
        #[cfg(miri)]
        let per_thread = 200;
        #[cfg(not(miri))]
        let per_thread = 10_000;

        let mut handles = Vec::new();

        for t in 0..threads {
            let s = Arc::clone(&s);

            handles.push(std::thread::spawn(move || {
                for i in 0..per_thread {
                    s.push(t * per_thread + i).unwrap();
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        let mut handles = Vec::new();

        for _ in 0..threads {
            let s = Arc::clone(&s);

            handles.push(std::thread::spawn(move || {
                let mut count = 0usize;

                loop {
                    match s.pop() {
                        Ok(_) => count += 1,
                        Err(PopError::Empty) => break,
                        Err(PopError::Closed) => break,
                    }
                }

                count
            }));
        }

        let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();

        assert_eq!(total, threads * per_thread);
    }

    #[test]
    fn close_after_drain_returns_closed() {
        let s = ConcurrentShardedStack::with_concurrency(4);

        for i in 0..100 {
            s.push(i).unwrap();
        }

        assert!(s.close());

        let mut count = 0;

        loop {
            match s.pop() {
                Ok(_) => count += 1,
                Err(PopError::Empty) => continue,
                Err(PopError::Closed) => break,
            }
        }

        assert_eq!(count, 100);
    }

    #[test]
    fn popped_values_are_dropped_exactly_once() {
        let counter = Arc::new(AtomicUsize::new(0));
        let s = ConcurrentShardedStack::with_concurrency(4);

        for _ in 0..50 {
            s.push(DropCounter::new(Arc::clone(&counter))).unwrap();
        }

        // Pop everything; each popped value should be dropped exactly once when
        // it goes out of scope here.
        let mut popped = 0;
        while let Ok(value) = s.pop() {
            drop(value);
            popped += 1;
        }

        assert_eq!(popped, 50);

        // Force any deferred reclamation to run. Even after reclamation, the
        // count must stay at exactly 50 (no double-drop from `defer_destroy`).
        drop(s);
        epoch::pin().flush();

        assert_eq!(counter.load(Ordering::Relaxed), 50);
    }

    #[test]
    fn remaining_values_are_dropped_when_stack_is_dropped() {
        let counter = Arc::new(AtomicUsize::new(0));

        {
            let s = ConcurrentShardedStack::with_concurrency(4);
            for _ in 0..30 {
                s.push(DropCounter::new(Arc::clone(&counter))).unwrap();
            }
            // Drop the stack without popping; all 30 values must be dropped once.
        }

        assert_eq!(counter.load(Ordering::Relaxed), 30);
    }

    #[test]
    fn partially_drained_stack_drops_each_value_once() {
        let counter = Arc::new(AtomicUsize::new(0));

        {
            let s = ConcurrentShardedStack::with_concurrency(4);
            for _ in 0..40 {
                s.push(DropCounter::new(Arc::clone(&counter))).unwrap();
            }

            for _ in 0..15 {
                let _ = s.pop().unwrap();
            }
            // 15 dropped via pop, 25 remain to be dropped by the stack's Drop.
        }

        epoch::pin().flush();
        assert_eq!(counter.load(Ordering::Relaxed), 40);
    }

    #[test]
    fn concurrent_drop_counter_no_double_free() {
        let counter = Arc::new(AtomicUsize::new(0));
        let s = Arc::new(ConcurrentShardedStack::with_concurrency(4));

        let threads = 4;
        #[cfg(miri)]
        let per_thread = 50;
        #[cfg(not(miri))]
        let per_thread = 200;

        let mut handles = Vec::new();
        for _ in 0..threads {
            let s = Arc::clone(&s);
            let counter = Arc::clone(&counter);
            handles.push(std::thread::spawn(move || {
                for _ in 0..per_thread {
                    s.push(DropCounter::new(Arc::clone(&counter))).unwrap();
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }

        let mut handles = Vec::new();
        for _ in 0..threads {
            let s = Arc::clone(&s);
            handles.push(std::thread::spawn(move || {
                let mut popped = 0;
                while let Ok(value) = s.pop() {
                    drop(value);
                    popped += 1;
                }
                popped
            }));
        }

        let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
        assert_eq!(total, threads * per_thread);

        drop(s);
        epoch::pin().flush();
        assert_eq!(counter.load(Ordering::Relaxed), threads * per_thread);
    }

    /// Wait until `cond` returns true, or panic with `label` after `timeout`.
    /// Used by the loss-detection tests to turn "popper hangs forever because
    /// an element is invisible" into an explicit, debuggable failure rather
    /// than a CI timeout.
    fn wait_until<F: Fn() -> bool>(timeout: Duration, label: &str, cond: F) {
        let start = Instant::now();
        while !cond() {
            if start.elapsed() > timeout {
                panic!("{label}: condition not met within {timeout:?}");
            }
            std::thread::sleep(Duration::from_millis(5));
        }
    }

    /// Pure-pusher / pure-popper split with **no** `close()`. Pushers map to a
    /// disjoint set of shards from poppers, so the shards that hold the
    /// pushed elements have no "local owner" that will ever pop them — every
    /// element has to be reached by a popper whose local shard differs from
    /// the pusher's, i.e. via the cross-shard scan in [`Self::pop`].
    ///
    /// This is the workload that exercises the worst case of the sharded
    /// scan: there is no fast path to the elements (no popper-thread ever
    /// hits its own shard for these pushes), and poppers must keep walking
    /// the full XOR-mask order until the elements are drained. The test
    /// asserts every pushed element is observed by some popper within a
    /// generous timeout; otherwise it fails loudly.
    ///
    /// Skipped under Miri: this is a hardware-race stress test (busy-spin
    /// poppers, no `close()`, watchdog measured in wall-clock seconds), and
    /// Miri's deterministic cooperative scheduler neither exposes the race
    /// window this is designed to catch nor finishes the workload in any
    /// reasonable wall-clock budget. UB and data-race coverage for this
    /// shape is handled by `no_element_loss_after_close_asymmetric`.
    #[cfg_attr(miri, ignore)]
    #[test]
    fn no_element_loss_open_asymmetric() {
        // Miri is too slow to hit this race repeatedly; keep workload tiny.
        #[cfg(miri)]
        let (n_pushers, n_poppers, per_pusher, rounds) = (2, 2, 200, 1);
        #[cfg(not(miri))]
        let (n_pushers, n_poppers, per_pusher, rounds) = (4, 12, 50_000, 4);

        for round in 0..rounds {
            let s = Arc::new(ConcurrentShardedStack::<usize>::with_concurrency(16));
            let popped = Arc::new(AtomicUsize::new(0));
            let pushed = Arc::new(AtomicUsize::new(0));
            let stop = Arc::new(AtomicBool::new(false));
            let total = n_pushers * per_pusher;

            let mut handles = Vec::new();
            for t in 0..n_pushers {
                let s = Arc::clone(&s);
                let pushed = Arc::clone(&pushed);
                handles.push(std::thread::spawn(move || {
                    for i in 0..per_pusher {
                        s.push(t * per_pusher + i).unwrap();
                        pushed.fetch_add(1, Ordering::Relaxed);
                    }
                }));
            }

            for _ in 0..n_poppers {
                let s = Arc::clone(&s);
                let popped = Arc::clone(&popped);
                let stop = Arc::clone(&stop);
                handles.push(std::thread::spawn(move || {
                    while !stop.load(Ordering::Relaxed) {
                        match s.pop() {
                            Ok(_) => {
                                popped.fetch_add(1, Ordering::Relaxed);
                            }
                            Err(PopError::Empty) => std::hint::spin_loop(),
                            Err(PopError::Closed) => break,
                        }
                    }
                }));
            }

            // 30 s is enormous for this workload (<100 ms in practice); only
            // a real loss should ever exceed it.
            wait_until(Duration::from_secs(30), "popper drain (open)", || {
                popped.load(Ordering::Relaxed) >= total
            });
            stop.store(true, Ordering::Relaxed);

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

            let final_pushed = pushed.load(Ordering::Relaxed);
            let final_popped = popped.load(Ordering::Relaxed);
            assert_eq!(
                final_popped, final_pushed,
                "round {round}: popped {final_popped} != pushed {final_pushed}",
            );
        }
    }

    /// Same asymmetric split, but with the producer side `close()`ing the
    /// stack once it has pushed everything. The post-`close()` drain must
    /// catch every in-flight element: with no `close()`, a popper can race
    /// indefinitely against pushers and keep observing `Empty` between
    /// pushes, so closing turns the open-ended scan into a finite one.
    #[test]
    fn no_element_loss_after_close_asymmetric() {
        #[cfg(miri)]
        let (n_pushers, n_poppers, per_pusher, rounds) = (2, 2, 200, 1);
        #[cfg(not(miri))]
        let (n_pushers, n_poppers, per_pusher, rounds) = (4, 12, 50_000, 4);

        for round in 0..rounds {
            let s = Arc::new(ConcurrentShardedStack::<usize>::with_concurrency(16));
            let popped = Arc::new(AtomicUsize::new(0));
            let total = n_pushers * per_pusher;

            let mut handles = Vec::new();
            for t in 0..n_pushers {
                let s = Arc::clone(&s);
                handles.push(std::thread::spawn(move || {
                    for i in 0..per_pusher {
                        s.push(t * per_pusher + i).unwrap();
                    }
                }));
            }

            for _ in 0..n_poppers {
                let s = Arc::clone(&s);
                let popped = Arc::clone(&popped);
                handles.push(std::thread::spawn(move || {
                    loop {
                        match s.pop() {
                            Ok(_) => {
                                popped.fetch_add(1, Ordering::Relaxed);
                            }
                            Err(PopError::Empty) => std::hint::spin_loop(),
                            Err(PopError::Closed) => break,
                        }
                    }
                }));
            }

            // Wait for pushers to finish, then close. Poppers continue
            // draining until they observe Closed.
            let pusher_handles: Vec<_> = handles.drain(..n_pushers).collect();
            for h in pusher_handles {
                h.join().unwrap();
            }
            s.close();

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

            assert_eq!(
                popped.load(Ordering::Relaxed),
                total,
                "round {round}: drain after close lost elements",
            );
        }
    }

    /// Lopsided shard count: many shards, few threads. Most shards are owned
    /// by nobody, so a popper only reaches the elements pushed there via the
    /// cross-shard scan in [`Self::pop`] (its own local shard is empty for
    /// those pushers). Catches loss via the cross-shard scan path.
    #[test]
    fn no_element_loss_few_threads_many_shards() {
        #[cfg(miri)]
        let (n_pushers, n_poppers, per_pusher, shards) = (2, 1, 100, 8);
        #[cfg(not(miri))]
        let (n_pushers, n_poppers, per_pusher, shards) = (2, 1, 100_000, 32);

        let s = Arc::new(ConcurrentShardedStack::<usize>::with_concurrency(shards));
        let popped = Arc::new(AtomicUsize::new(0));
        let total = n_pushers * per_pusher;

        let mut handles = Vec::new();
        for _ in 0..n_pushers {
            let s = Arc::clone(&s);
            handles.push(std::thread::spawn(move || {
                for i in 0..per_pusher {
                    s.push(i).unwrap();
                }
            }));
        }

        for _ in 0..n_poppers {
            let s = Arc::clone(&s);
            let popped = Arc::clone(&popped);
            handles.push(std::thread::spawn(move || {
                let start = Instant::now();
                while popped.load(Ordering::Relaxed) < total {
                    match s.pop() {
                        Ok(_) => {
                            popped.fetch_add(1, Ordering::Relaxed);
                        }
                        Err(PopError::Empty) => std::hint::spin_loop(),
                        Err(PopError::Closed) => break,
                    }
                    if start.elapsed() > Duration::from_secs(30) {
                        panic!(
                            "popper stuck: popped {} of {}",
                            popped.load(Ordering::Relaxed),
                            total,
                        );
                    }
                }
            }));
        }

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