concurrent-sharded-stack 0.3.1

Lock-free sharded stacks with epoch reclamation and optional intrusive node storage.
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
//! Lock-free intrusive stacks and their epoch reclamation contracts.
use crate::{CLOSED_TAG, PopError, PushError, current_thread_id};
use crossbeam_epoch::{self as epoch, Atomic, Shared};
use crossbeam_utils::CachePadded;
use intrusive_collections::singly_linked_list::{AtomicLinkOps, SinglyLinkedListOps};
use intrusive_collections::{Adapter, LinkOps, PointerOps, SinglyLinkedListAtomicLink};
use std::ptr::NonNull;
use std::sync::atomic::Ordering;

type Pointer<A> = <<A as Adapter>::PointerOps as PointerOps>::Pointer;
type Link<A> = <<A as Adapter>::LinkOps as ConcurrentLinkOps>::Link;

/// Link operations usable by concurrent Treiber-stack readers.
///
/// # Safety
/// All methods must be thread-safe and must not panic. `try_acquire` must
/// exclusively claim an unlinked link across *all* compatible collections,
/// synchronizing with its previous release. `release` relinquishes that claim.
/// `load_next` and `store_next` must access the same atomic next pointer without
/// creating exclusive references to the node. A relaxed access is sufficient:
/// the stack publishes initialization through a release head CAS and reads it
/// through an acquire head load. Operations must preserve pointer provenance.
/// `Link` must have alignment >= 2, and its address must stay fixed while owned.
/// For lock-free progress, implementations must not block or acquire locks.
///
/// These operations use `&self`; upstream `&mut self` methods alone do not
/// provide a concurrency contract. Only the singly-linked atomic implementation
/// is provided here; similarly named links for other collections may differ.
pub unsafe trait ConcurrentLinkOps:
    LinkOps<LinkPtr = NonNull<Self::Link>> + Send + Sync
{
    /// The embedded link, not the enclosing value.
    type Link: Send + Sync + 'static;
    /// Claims a live link not already owned by any collection.
    /// # Safety
    /// `link` must remain valid for the call.
    unsafe fn try_acquire(&self, link: NonNull<Self::Link>) -> bool;
    /// Releases a claimed link after all old readers have finished.
    /// # Safety
    /// Caller owns the claim and no reader may still access the old next pointer.
    unsafe fn release(&self, link: NonNull<Self::Link>);
    /// Reads a claimed link's next pointer.
    /// # Safety
    /// Caller must protect the link's lifetime, e.g. with an epoch guard.
    unsafe fn load_next(&self, link: NonNull<Self::Link>) -> Option<NonNull<Self::Link>>;
    /// Updates a claimed, unpublished link.
    /// # Safety
    /// No reader may access this link until the write has been published.
    unsafe fn store_next(&self, link: NonNull<Self::Link>, next: Option<NonNull<Self::Link>>);
}

// SAFETY: this specific upstream link stores next atomically, including the
// unlinked marker. Its operations object is stateless, so a local copy supplies
// the upstream &mut receiver without aliasing an operations object.
unsafe impl ConcurrentLinkOps for AtomicLinkOps {
    type Link = SinglyLinkedListAtomicLink;
    unsafe fn try_acquire(&self, link: NonNull<Self::Link>) -> bool {
        let mut ops = *self;
        unsafe { LinkOps::acquire_link(&mut ops, link) }
    }
    unsafe fn release(&self, link: NonNull<Self::Link>) {
        let mut ops = *self;
        unsafe { LinkOps::release_link(&mut ops, link) }
    }
    unsafe fn load_next(&self, link: NonNull<Self::Link>) -> Option<NonNull<Self::Link>> {
        unsafe { SinglyLinkedListOps::next(self, link) }
    }
    unsafe fn store_next(&self, link: NonNull<Self::Link>, next: Option<NonNull<Self::Link>>) {
        let mut ops = *self;
        unsafe { SinglyLinkedListOps::set_next(&mut ops, link, next) }
    }
}

/// An adapter whose raw ownership can outlive a stack and cross epoch callbacks.
///
/// # Safety
/// Clones must refer to the same link in each value and have interchangeable
/// pointer operations: a pointer erased by one clone can be restored by any
/// other clone. Cloning and all adapter/pointer operations must not panic.
/// Conversions must not create exclusive references to values or their links
/// while the collection owns them. `into_raw` must preserve the allocation and
/// its address until the matching `from_raw`, even after the stack is dropped.
/// Outstanding shared owners must not move/free the node, mutate its link, or
/// access payload through exclusive references during that interval. Ordinary
/// `Box<T>` and `Arc<T>` adapters generated by `intrusive_adapter!` satisfy these
/// requirements when their link type satisfies `ConcurrentLinkOps`.
///
/// The stack separately requires `Pointer: Send + 'static`. Borrowed scoped
/// nodes cannot generally be retired into a global epoch collector.
/// Implementations must not block if lock-free core progress is required.
///
/// Adapters do not opt in implicitly:
/// ```compile_fail
/// use concurrent_sharded_stack::{IntrusiveShardedStack, intrusive_collections};
/// use intrusive_collections::{intrusive_adapter, SinglyLinkedListAtomicLink};
/// struct Node { link: SinglyLinkedListAtomicLink }
/// intrusive_adapter!(A = Box<Node>: Node { link => SinglyLinkedListAtomicLink });
/// let stack = IntrusiveShardedStack::new(A::new()); // Missing EpochAdapter.
/// ```
/// Non-atomic links are rejected even when the adapter opts in:
/// ```compile_fail
/// use concurrent_sharded_stack::{EpochAdapter, IntrusiveShardedStack, intrusive_collections};
/// use intrusive_collections::{intrusive_adapter, SinglyLinkedListLink};
/// struct Node { link: SinglyLinkedListLink }
/// intrusive_adapter!(A = Box<Node>: Node { link => SinglyLinkedListLink });
/// unsafe impl EpochAdapter for A {}
/// let stack = IntrusiveShardedStack::new(A::new()); // Missing ConcurrentLinkOps.
/// ```
pub unsafe trait EpochAdapter: Adapter + Clone + Send + Sync + 'static {}

/// A removed node whose link is still reserved until its epoch grace period.
///
/// This token provides no access to the value or link. Call [`defer`](Self::defer)
/// to receive the original pointer after old readers finish. Dropping the token
/// schedules destruction instead. Forgetting it leaks the node, like forgetting
/// an owning pointer. This token is not a pinned epoch guard.
pub struct Retired<A: EpochAdapter>
where
    A::LinkOps: ConcurrentLinkOps,
    Pointer<A>: Send + 'static,
{
    link: Option<NonNull<Link<A>>>,
    adapter: A,
}

// SAFETY: the token owns the erased Pointer (which is Send); it never exposes
// the value while epoch readers may exist. Adapter clones can restore it.
unsafe impl<A: EpochAdapter> Send for Retired<A>
where
    A::LinkOps: ConcurrentLinkOps,
    Pointer<A>: Send + 'static,
{
}

impl<A: EpochAdapter> Retired<A>
where
    A::LinkOps: ConcurrentLinkOps,
    Pointer<A>: Send + 'static,
{
    /// Schedules delivery on a collecting thread after the grace period.
    ///
    /// The callback may free or reinsert the returned pointer. It must be Send
    /// and 'static; panics propagate on the collecting thread. Delivery has no
    /// time bound and is not guaranteed at process exit. [`collect`] helps drive
    /// progress but does not synchronously wait for callbacks.
    ///
    /// Callbacks are batched in the **calling thread's** epoch cache. Call
    /// [`collect`] on that thread before waiting for delivery or becoming idle;
    /// collection on another thread cannot flush this cache. Thread exit also
    /// flushes it. Dropping a `Retired` uses the same batching policy.
    pub fn defer(self, callback: impl FnOnce(Pointer<A>) + Send + 'static) {
        let guard = epoch::pin();
        // SAFETY: this callback runs only after pre-existing readers unpin.
        guard.defer(move || callback(unsafe { self.reclaim() }));
        // Let epoch fill its local bag. Flushing every node allocates a whole
        // bag per callback and contends on the global reclamation queue.
    }

    // Caller guarantees all old readers of this node have finished.
    unsafe fn reclaim(mut self) -> Pointer<A> {
        let link = self.link.take().expect("retired node already consumed");
        unsafe {
            let value = self.adapter.get_value(link);
            self.adapter.link_ops().release(link);
            self.adapter.pointer_ops().from_raw(value)
        }
    }
}

impl<A: EpochAdapter> Drop for Retired<A>
where
    A::LinkOps: ConcurrentLinkOps,
    Pointer<A>: Send + 'static,
{
    fn drop(&mut self) {
        if let Some(link) = self.link.take() {
            Self {
                link: Some(link),
                adapter: self.adapter.clone(),
            }
            .defer(drop);
        }
    }
}

/// Flushes this thread's deferred callbacks and helps advance global collection.
///
/// Call on each retiring thread before it waits or becomes idle, including after
/// dropping `Retired` tokens. Other threads cannot flush its local cache.
/// This is not a grace-period barrier. Call periodically while awaiting retired
/// nodes, releasing every epoch guard between calls. A stalled pinned thread
/// can indefinitely delay reclamation. Epoch metadata may allocate internally.
pub fn collect() {
    epoch::pin().flush();
}

/// A sharded Treiber stack using caller-provided links and epoch reclamation.
///
/// Requires the default-enabled `intrusive` feature. Push/pop do not allocate
/// wrapper nodes or take a shard lock. Epoch registration/deferred callbacks
/// may allocate; custom adapter operations and callbacks can also have costs.
/// Ordering, empty scans, and gradual close match `ConcurrentShardedStack`.
///
/// Pop returns a [`Retired`] token, **not** immediate ownership of the value.
/// Its link remains claimed until the grace period; this prevents reuse ABA.
///
/// ```
/// use concurrent_sharded_stack::{EpochAdapter, IntrusiveShardedStack, intrusive_collections};
/// use intrusive_collections::{intrusive_adapter, SinglyLinkedListAtomicLink};
/// #[derive(Debug)]
/// struct Entry { link: SinglyLinkedListAtomicLink, value: usize }
/// intrusive_adapter!(EntryAdapter = Box<Entry>: Entry { link => SinglyLinkedListAtomicLink });
/// // SAFETY: the generated adapter is stateless and Box keeps its node alive
/// // at a stable address until the matching pointer conversion.
/// unsafe impl EpochAdapter for EntryAdapter {}
/// let stack = IntrusiveShardedStack::with_concurrency(4, EntryAdapter::new());
/// stack.push(Box::new(Entry { link: SinglyLinkedListAtomicLink::new(), value: 42 })).unwrap();
/// stack.pop().unwrap().defer(|entry| {
///     assert_eq!(entry.value, 42);
///     assert!(!entry.link.is_linked());
/// });
/// ```
pub struct IntrusiveShardedStack<A: EpochAdapter>
where
    A::LinkOps: ConcurrentLinkOps,
    Pointer<A>: Send + 'static,
{
    shards: Box<[CachePadded<Atomic<Link<A>>>]>,
    adapter: A,
}

impl<A: EpochAdapter> IntrusiveShardedStack<A>
where
    A::LinkOps: ConcurrentLinkOps,
    Pointer<A>: Send + 'static,
{
    /// Creates a stack using available parallelism as the shard-count hint.
    pub fn new(adapter: A) -> Self {
        let count = std::thread::available_parallelism()
            .map(|n| n.get().next_power_of_two())
            .unwrap_or(4);
        Self::with_concurrency(count, adapter)
    }
    /// Creates a nonzero power-of-two number of shards, otherwise panics.
    pub fn with_concurrency(shard_count: usize, adapter: A) -> Self {
        assert!(
            shard_count.is_power_of_two(),
            "shard_count must be a nonzero power of two"
        );
        assert!(
            std::mem::align_of::<Link<A>>() >= 2,
            "link alignment must leave a close tag bit"
        );
        Self {
            shards: (0..shard_count)
                .map(|_| CachePadded::new(Atomic::null()))
                .collect(),
            adapter,
        }
    }
    /// Pushes into the local shard. Closed rejection returns the original pointer.
    ///
    /// Panics if the selected link is already claimed (including retirement).
    pub fn push(&self, value: Pointer<A>) -> Result<(), PushError<Pointer<A>>> {
        let guard = &epoch::pin();
        let shard = &self.shards[self.current_shard_index()];
        if shard.load(Ordering::Acquire, guard).tag() == CLOSED_TAG {
            return Err(PushError::Closed(value));
        }
        let raw = self.adapter.pointer_ops().into_raw(value);
        // SAFETY: the erased pointer owns a stable live node; adapter methods do
        // not panic. Failure to acquire leaves the existing owner untouched.
        let link = unsafe { self.adapter.get_link(raw) };
        if !unsafe { self.adapter.link_ops().try_acquire(link) } {
            drop(unsafe { self.adapter.pointer_ops().from_raw(raw) });
            panic!("attempted to insert an object that is already linked or retired");
        }
        let node = Shared::from(link.as_ptr() as *const Link<A>);
        loop {
            let head = shard.load(Ordering::Acquire, guard);
            if head.tag() == CLOSED_TAG {
                // Not published: no readers can have seen this ownership cycle.
                unsafe {
                    self.adapter.link_ops().release(link);
                }
                return Err(PushError::Closed(unsafe {
                    self.adapter.pointer_ops().from_raw(raw)
                }));
            }
            unsafe {
                self.adapter
                    .link_ops()
                    .store_next(link, NonNull::new(head.as_raw() as *mut Link<A>));
            }
            if shard
                .compare_exchange_weak(head, node, Ordering::Release, Ordering::Relaxed, guard)
                .is_ok()
            {
                return Ok(());
            }
            std::hint::spin_loop();
        }
    }
    /// Removes a node, returning a token that delays access until readers finish.
    /// `Empty` is a retryable scan result; `Closed` means closed and drained,
    /// but does not mean all previously retired callbacks have run.
    pub fn pop(&self) -> Result<Retired<A>, PopError> {
        let adapter = self.adapter.clone();
        let guard = &epoch::pin();
        let mut all_closed = true;
        for mask in 0..self.shards.len() {
            let shard = &self.shards[self.current_shard_index() ^ mask];
            loop {
                let head = shard.load(Ordering::Acquire, guard);
                let Some(link) = NonNull::new(head.as_raw() as *mut Link<A>) else {
                    all_closed &= head.tag() == CLOSED_TAG;
                    break;
                };
                // SAFETY: pin protects this acquired link. Next is immutable
                // while published or retired; release/reuse waits for this guard.
                let next = unsafe { adapter.link_ops().load_next(link) };
                let next = next
                    .map_or(Shared::null(), |p| {
                        Shared::from(p.as_ptr() as *const Link<A>)
                    })
                    .with_tag(head.tag());
                if shard
                    .compare_exchange(head, next, Ordering::AcqRel, Ordering::Relaxed, guard)
                    .is_ok()
                {
                    return Ok(Retired {
                        link: Some(link),
                        adapter,
                    });
                }
                std::hint::spin_loop();
            }
        }
        Err(if all_closed {
            PopError::Closed
        } else {
            PopError::Empty
        })
    }
    /// Closes each shard; returns whether this call closed at least one shard.
    /// Existing nodes remain available to pop. Concurrent callers may both win.
    pub fn close(&self) -> bool {
        let guard = &epoch::pin();
        let mut changed = false;
        for shard in &self.shards {
            loop {
                let head = shard.load(Ordering::Acquire, guard);
                if head.tag() == CLOSED_TAG {
                    break;
                }
                if shard
                    .compare_exchange_weak(
                        head,
                        head.with_tag(CLOSED_TAG),
                        Ordering::AcqRel,
                        Ordering::Relaxed,
                        guard,
                    )
                    .is_ok()
                {
                    changed = true;
                    break;
                }
                std::hint::spin_loop();
            }
        }
        changed
    }
    /// Checks whether every shard is closed.
    pub fn is_closed(&self) -> bool {
        let guard = &epoch::pin();
        self.shards
            .iter()
            .all(|s| s.load(Ordering::Acquire, guard).tag() == CLOSED_TAG)
    }
    /// Returns the fixed number of shards.
    pub fn shard_count(&self) -> usize {
        self.shards.len()
    }
    fn current_shard_index(&self) -> usize {
        current_thread_id() & (self.shards.len() - 1)
    }
}

impl<A: EpochAdapter + Default> Default for IntrusiveShardedStack<A>
where
    A::LinkOps: ConcurrentLinkOps,
    Pointer<A>: Send + 'static,
{
    fn default() -> Self {
        Self::new(A::default())
    }
}

impl<A: EpochAdapter> Drop for IntrusiveShardedStack<A>
where
    A::LinkOps: ConcurrentLinkOps,
    Pointer<A>: Send + 'static,
{
    fn drop(&mut self) {
        let drain = || {
            // SAFETY: exclusive stack access means no stack operation can still
            // read its reachable nodes. Retired nodes are separately owned.
            let guard = unsafe { epoch::unprotected() };
            for shard in &self.shards {
                loop {
                    let head = shard.load(Ordering::Relaxed, guard);
                    let Some(link) = NonNull::new(head.as_raw() as *mut Link<A>) else {
                        break;
                    };
                    unsafe {
                        let next = self.adapter.link_ops().load_next(link);
                        shard.store(
                            next.map_or(Shared::null(), |p| {
                                Shared::from(p.as_ptr() as *const Link<A>)
                            }),
                            Ordering::Relaxed,
                        );
                        drop(
                            Retired {
                                link: Some(link),
                                adapter: self.adapter.clone(),
                            }
                            .reclaim(),
                        );
                    }
                }
            }
        };
        let cleanup = scopeguard::guard((), |_| drain());
        drain();
        scopeguard::ScopeGuard::into_inner(cleanup);
    }
}