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
//! Paged generational ids with shared allocation and freeing.
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt;
use core::iter::FusedIterator;
use core::ops::Range;
use super::atomic::{AtomicU32, Ordering};
use super::count::StripedLen;
use super::free_stack::{FreeStack, block_for};
use super::spine::Spine;
use crate::id_alloc::{Id, IdAllocator, MAX_INDICES, generation_of, live_version};
use crate::page::DEFAULT_PAGE;
// Include the last partial range of u32 page numbers, even for PAGE = 1.
// The design's 27 normal chunks cover only 2^32 - 32 pages.
#[cfg(not(loom))]
const CHUNKS: usize = 28;
#[cfg(loom)]
const CHUNKS: usize = 32;
#[derive(Default)]
struct Slot {
// Zero is never used for a fresh index, retired for an issued index.
version: AtomicU32,
next: AtomicU32,
}
struct Page {
slots: Box<[Slot]>,
}
/// A thread-safe, paged allocator of generational [`Id`]s.
///
/// Shared access can allocate, free, and check ids. Freed indices are reused
/// through tagged LIFO stacks, one per thread group (a thread with none
/// steals another's); their generations never wrap. As with
/// [`IdAllocator`], ids carry no allocator identity, and the stale-id
/// guarantee applies within one allocation history. Conversions preserve it.
///
/// Pages stay allocated until destruction. [`clear`](Self::clear) requires
/// exclusive access and preserves every index's generation history.
/// Allocation and freeing use CAS retry loops; liveness checks do not retry.
/// The free stack assumes fewer than 2^32 pops during any stalled operation.
pub struct ConcurrentIdAllocator<const PAGE: usize = DEFAULT_PAGE> {
pages: Spine<Page, CHUNKS>,
free: FreeStack,
len: StripedLen,
}
impl<const PAGE: usize> ConcurrentIdAllocator<PAGE> {
/// An empty allocator, without allocating memory.
///
/// # Panics
///
/// Panics if `PAGE` is zero or a page's slot storage exceeds `isize::MAX`.
pub fn new() -> Self {
assert!(
PAGE > 0 && PAGE <= isize::MAX as usize / core::mem::size_of::<Slot>(),
"ConcurrentIdAllocator: invalid page capacity"
);
Self {
pages: Spine::new(),
free: FreeStack::new(),
len: StripedLen::new(),
}
}
fn slot(&self, index: u32) -> Option<&Slot> {
self.pages
.get(index as usize / PAGE)
.map(|page| &page.slots[index as usize % PAGE])
}
fn ensure_slot(&self, index: u32) -> &Slot {
let page = self.pages.get_or_insert_with(index as usize / PAGE, || {
Box::new(Page {
slots: (0..PAGE).map(|_| Slot::default()).collect(),
})
});
&page.slots[index as usize % PAGE]
}
/// Issues an id, reusing a free index or reserving a fresh one.
///
/// # Panics
///
/// Panics when all [`MAX_INDICES`] indices are live or retired.
#[doc(alias = "alloc")]
pub fn allocate(&self) -> Id {
self.try_allocate().unwrap_or_else(|| {
panic!("ConcurrentIdAllocator: all {MAX_INDICES} indices are live or retired")
})
}
/// Like [`allocate`](Self::allocate), returning `None` on exhaustion.
/// A concurrent free may make room immediately after the stack is checked.
#[doc(alias = "try_alloc")]
pub fn try_allocate(&self) -> Option<Id> {
loop {
let (index, reused) = self.free.next_index(
|index| &self.slot(index).expect("free index has a page").next,
|| None,
MAX_INDICES,
block_for(PAGE),
)?;
let slot = self.ensure_slot(index);
// Acquire observes the previous owner's vacant version after pop.
// A fresh reservation uniquely owns its never-used zero version.
let previous = slot.version.load(Ordering::Acquire);
// The free stack is only a hint: owning an index means winning
// the version CAS below. If the stack's ABA tag ever wrapped
// (2^32 pops inside one stalled pop), it could hand out a live
// or retired index; that index is skipped here, so a wrap can
// leak indices but can never issue one id twice.
if previous % 2 == 1 || (reused && previous == 0) {
continue;
}
// Relaxed: accounting only. Increment before publication, so any
// free of this id is counted after it; undone if the claim is lost.
self.len.increment(index as usize / PAGE);
let version = previous + 1;
// Release publishes this generation; a successful free's Acquire
// observes the preceding count increment. Acquire on failure:
// another claimant won, so drop this candidate and retry.
if slot
.version
.compare_exchange(previous, version, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
return Some(Id::new(index, generation_of(version)));
}
self.len.decrement(index as usize / PAGE);
}
}
/// Frees a matching live id, returning whether this call won the free.
/// Stale, never-issued, and already-freed ids return `false`.
pub fn free(&self, id: Id) -> bool {
let Some(live) = live_version(id.generation()) else {
return false;
};
let Some(slot) = self.slot(id.index()) else {
return false;
};
let vacant = live.checked_add(1).unwrap_or(0);
// AcqRel observes publication (including accounting) and publishes
// invalidation. Exactly one CAS can win for this live generation.
// Acquire on failure observes the competing state transition.
if slot
.version
.compare_exchange(live, vacant, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return false;
}
// Relaxed: accounting only; decrement before push so a later owner
// cannot accumulate arbitrarily many pending decrements on this index.
self.len.decrement(id.index() as usize / PAGE);
if vacant != 0 {
self.free.push(id.index(), &slot.next);
}
true
}
/// Whether this generation is live at the instant its version is read.
#[doc(alias = "is_alive")]
pub fn is_live(&self, id: Id) -> bool {
let Some(live) = live_version(id.generation()) else {
return false;
};
// Acquire observes generation publication/invalidation. A slot's
// version never returns to an earlier live value in this history.
self.slot(id.index())
.is_some_and(|slot| slot.version.load(Ordering::Acquire) == live)
}
/// Returns the live id at `index` when the slot's version is read.
/// A concurrent free can invalidate the returned id immediately.
pub fn occupant(&self, index: u32) -> Option<Id> {
// Acquire observes publication of this generation or its invalidation.
let version = self.slot(index)?.version.load(Ordering::Acquire);
(version % 2 == 1).then(|| Id::new(index, generation_of(version)))
}
/// Scans for live ids in index order, up to the index bound read at creation.
///
/// This iterator takes no snapshot. Each slot is read once. Allocations
/// and frees during the scan may or may not be reflected, and a returned
/// id may already have been freed.
pub fn iter(&self) -> IdAllocIter<'_, PAGE> {
IdAllocIter {
allocator: self,
indices: 0..self.index_bound(),
}
}
/// Number of live ids; approximate while other threads allocate or free.
/// Exact when no operation is in flight. This is not a publication barrier.
///
/// It sums per-thread counters (per page group without `std`). While
/// operations are in flight it may combine counters read at different
/// moments and differ from every count the allocator held; it never
/// exceeds the number of insertions.
pub fn len(&self) -> usize {
self.len.get()
}
/// Whether no ids are live; approximate while other threads run.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// One past the highest reserved index, including reservations in flight.
/// This does not imply that every reserved index's page is installed yet.
///
/// Threads that contend for fresh indices reserve them in blocks of
/// about one page, so the bound may exceed the indices handed out by up
/// to one block per thread.
pub fn index_bound(&self) -> u32 {
self.free.index_bound()
}
/// Frees all live ids, preserving generations so stale ids stay dead.
/// Keeps pages and retired indices; requires exclusive access.
pub fn clear(&mut self) {
for index in 0..self.index_bound() {
// A reservation whose page allocation unwound has no page and
// never issued an id.
let Some(slot) = self.slot(index) else {
continue;
};
// Relaxed: exclusive access excludes all other version writers.
let version = slot.version.load(Ordering::Relaxed);
if version % 2 == 1 {
let freed = self.free(Id::new(index, generation_of(version)));
debug_assert!(freed);
}
}
}
/// Copies a weakly consistent snapshot into a plain [`IdAllocator`],
/// in O([`index_bound`](Self::index_bound)) time and space.
/// Allocations that happen-before the call are included if the id stays
/// live throughout it. Ids whose freeing happens-before the call stay
/// dead. The raw parts always validate; the lowest free index is reused first.
pub fn snapshot(&self) -> IdAllocator {
let (versions, free) = self.snapshot_parts();
IdAllocator::try_from_raw_parts(versions, free)
.expect("allocator snapshot has valid raw parts")
}
fn snapshot_parts(&self) -> (Vec<u32>, Vec<u32>) {
let bound = self.index_bound();
let unissued = self.free.unissued_shared();
let mut versions = Vec::with_capacity(bound as usize);
let mut free = Vec::new();
for index in 0..bound {
let version = self.slot(index).map_or(0, |slot| {
// Acquire observes the published version. Use this same
// observation for both the versions and the free list.
let version = slot.version.load(Ordering::Acquire);
if version == 0 && unissued.contains_shared(index) {
2
} else {
version
}
});
versions.push(version);
if version != 0 && version & 1 == 0 {
free.push(index);
}
}
free.reverse();
(versions, free)
}
/// Converts to the plain allocator, preserving ids, and LIFO reuse order
/// within each thread group's stack. Indices reserved in a block but
/// never handed out become free, with generation 1 spent.
/// Takes O(number of indices ever reserved) time and temporary storage.
pub fn into_inner(mut self) -> IdAllocator {
let bound = self.index_bound() as usize;
let mut unissued = self.free.unissued();
let mut spare = Vec::new();
// By index, not by installed page: a reservation whose page
// allocation unwound has no page and keeps version 0 (retired, as it
// cannot be told apart from a retired index). Block indices never
// handed out become vacancies with generation 1 spent.
let versions: Vec<u32> = (0..bound as u32)
.map(|index| {
// Relaxed: self is exclusively owned, with no operations in flight.
let version = self
.slot(index)
.map_or(0, |slot| slot.version.load(Ordering::Relaxed));
if unissued.contains(index) {
debug_assert_eq!(version, 0, "unissued index was used");
spare.push(index);
2
} else {
version
}
})
.collect();
// The plain allocator pops from the end: stack tops last, spare
// block indices first (lowest last among them).
let mut free = self
.free
.drain(|index| &self.slot(index).expect("free index has a page").next);
free.reverse();
spare.reverse();
spare.append(&mut free);
let free = spare;
IdAllocator::try_from_raw_parts(versions, free)
.expect("concurrent allocator maintains valid raw parts")
}
}
impl<const PAGE: usize> From<IdAllocator> for ConcurrentIdAllocator<PAGE> {
fn from(inner: IdAllocator) -> Self {
let mut result = Self::new();
let (versions, free) = inner.raw_parts();
for &version in versions {
let index = result
.free
.fresh(MAX_INDICES, block_for(PAGE))
.expect("valid index bound");
// Release publishes the imported generation, just as allocation does.
result
.ensure_slot(index)
.version
.store(version, Ordering::Release);
}
for &index in free {
let slot = result.slot(index).expect("imported index has a page");
result.free.push(index, &slot.next);
}
// Relaxed: result is not shared until the conversion returns.
result.len.set(inner.len());
result
}
}
/// Clones via [`ConcurrentIdAllocator::snapshot`], preserving generations.
impl<const PAGE: usize> Clone for ConcurrentIdAllocator<PAGE> {
fn clone(&self) -> Self {
Self::from(self.snapshot())
}
}
impl<const PAGE: usize> Default for ConcurrentIdAllocator<PAGE> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::*;
use crate::id_alloc::serde_impl::serialize_raw_parts;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
/// Serializes weakly consistent versions and their matching free list
/// in the plain [`IdAllocator`] format, with the same consistency as
/// [`ConcurrentIdAllocator::snapshot`]. The result always validates.
/// Takes O(index bound) time and temporary space.
impl<const PAGE: usize> Serialize for ConcurrentIdAllocator<PAGE> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let (versions, free) = self.snapshot_parts();
serialize_raw_parts(&versions, &free, serializer)
}
}
/// Validates the plain [`IdAllocator`] format and converts in O(index bound).
impl<'de, const PAGE: usize> Deserialize<'de> for ConcurrentIdAllocator<PAGE> {
fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
IdAllocator::deserialize(deserializer).map(Self::from)
}
}
}
impl<const PAGE: usize> fmt::Debug for ConcurrentIdAllocator<PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConcurrentIdAllocator")
.field("len", &self.len())
.field("index_bound", &self.index_bound())
.finish_non_exhaustive()
}
}
impl<'a, const PAGE: usize> IntoIterator for &'a ConcurrentIdAllocator<PAGE> {
type Item = Id;
type IntoIter = IdAllocIter<'a, PAGE>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// Weakly consistent iterator over live ids of a [`ConcurrentIdAllocator`].
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IdAllocIter<'a, const PAGE: usize = DEFAULT_PAGE> {
allocator: &'a ConcurrentIdAllocator<PAGE>,
indices: Range<u32>,
}
impl<const PAGE: usize> Iterator for IdAllocIter<'_, PAGE> {
type Item = Id;
fn next(&mut self) -> Option<Id> {
self.indices
.find_map(|index| self.allocator.occupant(index))
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.indices.len()))
}
}
impl<const PAGE: usize> DoubleEndedIterator for IdAllocIter<'_, PAGE> {
fn next_back(&mut self) -> Option<Id> {
self.indices
.by_ref()
.rev()
.find_map(|index| self.allocator.occupant(index))
}
}
impl<const PAGE: usize> FusedIterator for IdAllocIter<'_, PAGE> {}
impl<const PAGE: usize> fmt::Debug for IdAllocIter<'_, PAGE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IdAllocIter")
.field("indices", &self.indices)
.finish_non_exhaustive()
}
}
#[cfg(all(test, not(loom)))]
mod tests {
use super::*;
#[test]
fn unissued_block_tail_becomes_free_with_generation_one_spent() {
let ids: ConcurrentIdAllocator<4> = ConcurrentIdAllocator::new();
let a = ids.allocate();
let b = ids.allocate();
ids.free.force_blocks();
let c = ids.allocate();
assert_eq!((a.index(), b.index(), c.index()), (0, 1, 2));
assert_eq!(ids.index_bound(), 64);
assert!(ids.free(b));
let snapshot = ids.snapshot();
let (versions, free) = snapshot.raw_parts();
assert_eq!(&versions[..4], &[1, 2, 1, 2]);
assert!(versions[4..].iter().all(|&v| v == 0));
assert_eq!(free, &[3, 1]);
#[cfg(feature = "serde")]
{
let json = serde_json::to_string(&ids).unwrap();
let decoded: IdAllocator = serde_json::from_str(&json).unwrap();
assert_eq!(decoded.raw_parts(), snapshot.raw_parts());
}
let plain = ids.into_inner();
let (versions, free) = plain.raw_parts();
assert_eq!(&versions[..3], &[1, 2, 1]);
assert!(versions[3..].iter().all(|&v| v == 2));
assert_eq!(free.len(), 62);
assert_eq!(plain.retired_len(), 0);
assert!(!plain.is_alive(b) && plain.is_alive(a) && plain.is_alive(c));
let back = ConcurrentIdAllocator::<4>::from(plain);
for _ in 0..62 {
let id = back.allocate();
assert!(id.index() < 64 && id != b);
}
assert_eq!(back.index_bound(), 64);
}
#[test]
// Walks pages up to u32::MAX: over 9 hours under Miri, under a second natively.
#[cfg_attr(miri, ignore)]
fn the_last_indices_below_u32_max_are_issued_freed_and_reused() {
// Reservation resumes 3 below the limit: the last page is
// [2^32 - 4096, 2^32), and its top slot (index u32::MAX) is NONE.
let mut ids: ConcurrentIdAllocator<4096> = ConcurrentIdAllocator::new();
ids.free.set_next_fresh(MAX_INDICES - 3);
let got: Vec<Id> = (0..3).map(|_| ids.allocate()).collect();
let indices: Vec<u32> = got.iter().map(|id| id.index()).collect();
assert_eq!(indices, [MAX_INDICES - 3, MAX_INDICES - 2, MAX_INDICES - 1]);
assert_eq!(ids.try_allocate(), None);
assert_eq!(ids.index_bound(), MAX_INDICES);
assert!(!ids.is_live(Id::new(MAX_INDICES, got[0].generation())));
assert!(!ids.free(Id::new(MAX_INDICES, got[0].generation())));
// The top index goes back on a stack and comes out with a new
// generation; nothing else is issued.
assert!(ids.free(got[2]));
let again = ids.allocate();
assert_eq!(again.index(), MAX_INDICES - 1);
assert_ne!(again, got[2]);
assert!(ids.is_live(again) && !ids.is_live(got[2]));
assert_eq!(ids.try_allocate(), None);
assert_eq!(ids.len(), 3);
}
#[test]
fn a_live_index_on_the_free_stack_is_never_reissued() {
// Simulates the stack corruption an ABA tag wrap could cause: a
// live index sits on the free stack.
let ids: ConcurrentIdAllocator<2> = ConcurrentIdAllocator::new();
let a = ids.allocate();
let slot = ids.slot(a.index()).unwrap();
ids.free.push(a.index(), &slot.next);
let b = ids.allocate();
let c = ids.allocate();
assert!(ids.is_live(a) && ids.is_live(b) && ids.is_live(c));
assert_ne!(a.index(), b.index());
assert_ne!(a.index(), c.index());
assert_ne!(b.index(), c.index());
assert_eq!(ids.len(), 3);
}
}