kovan 0.1.12

High-performance wait-free memory reclamation for lock-free data structures. Bounded memory usage, predictable latency.
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
//! Stress tests for Kovan memory reclamation
//!
//! These tests push the system to its limits to find edge cases

#![allow(unused_unsafe)]

use kovan::{Atomic, RetiredNode, pin, retire};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;
use std::time::{Duration, Instant};

#[repr(C)]
struct StressNode {
    retired: RetiredNode,
    value: usize,
}

impl StressNode {
    fn new(value: usize) -> *mut Self {
        Box::into_raw(Box::new(Self {
            retired: RetiredNode::new(),
            value,
        }))
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn test_high_contention() {
    // Many threads hammering the same atomic
    const NUM_THREADS: usize = 16;
    const ITERATIONS: usize = 50000;

    let atomic = Arc::new(Atomic::new(StressNode::new(0)));
    let ops_count = Arc::new(AtomicUsize::new(0));
    let mut handles = vec![];

    let start = Instant::now();

    for tid in 0..NUM_THREADS {
        let atomic = atomic.clone();
        let ops_count = ops_count.clone();

        handles.push(thread::spawn(move || {
            for i in 0..ITERATIONS {
                let new_node = StressNode::new(tid * ITERATIONS + i);

                let guard = pin();
                let old = atomic.swap(
                    unsafe { kovan::Shared::from_raw(new_node) },
                    Ordering::Release,
                    &guard,
                );

                if !old.is_null() {
                    unsafe {
                        retire(old.as_raw());
                    }
                }

                ops_count.fetch_add(1, Ordering::Relaxed);
            }
        }));
    }

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

    let elapsed = start.elapsed();
    let total_ops = ops_count.load(Ordering::Relaxed);
    let throughput = total_ops as f64 / elapsed.as_secs_f64();

    println!("High contention test:");
    println!("  {} operations in {:?}", total_ops, elapsed);
    println!("  Throughput: {:.0} ops/sec", throughput);

    // Cleanup
    let guard = pin();
    let old = atomic.swap(
        unsafe { kovan::Shared::from_raw(std::ptr::null_mut()) },
        Ordering::Release,
        &guard,
    );
    if !old.is_null() {
        unsafe {
            retire(old.as_raw());
        }
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn test_read_heavy_workload() {
    // 95% reads, 5% writes
    const NUM_THREADS: usize = 8;
    const ITERATIONS: usize = 100000;
    const WRITE_RATIO: usize = 20; // 1 in 20 = 5%

    let atomic = Arc::new(Atomic::new(StressNode::new(0)));
    let mut handles = vec![];

    let start = Instant::now();

    for tid in 0..NUM_THREADS {
        let atomic = atomic.clone();

        handles.push(thread::spawn(move || {
            for i in 0..ITERATIONS {
                let guard = pin();

                if i % WRITE_RATIO == 0 {
                    // Write operation
                    let new_node = StressNode::new(tid * ITERATIONS + i);
                    let old = atomic.swap(
                        unsafe { kovan::Shared::from_raw(new_node) },
                        Ordering::Release,
                        &guard,
                    );

                    if !old.is_null() {
                        unsafe {
                            retire(old.as_raw());
                        }
                    }
                } else {
                    // Read operation
                    let ptr = atomic.load(Ordering::Acquire, &guard);
                    if let Some(node) = unsafe { ptr.as_ref() } {
                        let _ = node.value;
                    }
                }
            }
        }));
    }

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

    let elapsed = start.elapsed();
    let total_ops = NUM_THREADS * ITERATIONS;
    let throughput = total_ops as f64 / elapsed.as_secs_f64();

    println!("Read-heavy workload (95% reads):");
    println!("  {} operations in {:?}", total_ops, elapsed);
    println!("  Throughput: {:.0} ops/sec", throughput);

    // Cleanup
    let guard = pin();
    let old = atomic.swap(
        unsafe { kovan::Shared::from_raw(std::ptr::null_mut()) },
        Ordering::Release,
        &guard,
    );
    if !old.is_null() {
        unsafe {
            retire(old.as_raw());
        }
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn test_oversubscription() {
    // More threads than cores (2x oversubscription, matching paper's methodology)
    let num_cores = thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4);
    // 2x oversubscription as tested in the paper
    // We go beyond that and do 4x oversub here
    let num_threads = num_cores * 4;
    const ITERATIONS: usize = 10000;

    let atomic = Arc::new(Atomic::new(StressNode::new(0)));
    let mut handles = vec![];

    let start = Instant::now();

    for tid in 0..num_threads {
        let atomic = atomic.clone();

        handles.push(thread::spawn(move || {
            for i in 0..ITERATIONS {
                let new_node = StressNode::new(tid * ITERATIONS + i);

                let guard = pin();
                let old = atomic.swap(
                    unsafe { kovan::Shared::from_raw(new_node) },
                    Ordering::Release,
                    &guard,
                );

                if !old.is_null() {
                    unsafe {
                        retire(old.as_raw());
                    }
                }
            }
        }));
    }

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

    let elapsed = start.elapsed();
    let total_ops = num_threads * ITERATIONS;
    let throughput = total_ops as f64 / elapsed.as_secs_f64();

    println!(
        "Oversubscription test ({} threads on {} cores):",
        num_threads, num_cores
    );
    println!("  {} operations in {:?}", total_ops, elapsed);
    println!("  Throughput: {:.0} ops/sec", throughput);

    // Cleanup
    let guard = pin();
    let old = atomic.swap(
        unsafe { kovan::Shared::from_raw(std::ptr::null_mut()) },
        Ordering::Release,
        &guard,
    );
    if !old.is_null() {
        unsafe {
            retire(old.as_raw());
        }
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn test_rapid_guard_creation() {
    // Rapidly create and drop guards
    const NUM_THREADS: usize = 8;
    const ITERATIONS: usize = 100000;

    let mut handles = vec![];
    let start = Instant::now();

    for _ in 0..NUM_THREADS {
        handles.push(thread::spawn(move || {
            for _ in 0..ITERATIONS {
                let _guard = pin();
                // Immediately drop
            }
        }));
    }

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

    let elapsed = start.elapsed();
    let total_ops = NUM_THREADS * ITERATIONS;
    let throughput = total_ops as f64 / elapsed.as_secs_f64();

    println!("Rapid guard creation:");
    println!("  {} guards in {:?}", total_ops, elapsed);
    println!("  Throughput: {:.0} guards/sec", throughput);
}

#[test]
#[cfg_attr(miri, ignore)]
fn test_long_running_guards() {
    // Some threads hold guards for extended periods
    const NUM_LONG: usize = 2;
    const NUM_SHORT: usize = 6;
    const SHORT_ITERATIONS: usize = 10000;

    let atomic = Arc::new(Atomic::new(StressNode::new(0)));
    let mut handles = vec![];
    let done = Arc::new(AtomicBool::new(false));

    // Long-running guard threads
    for _ in 0..NUM_LONG {
        let atomic = atomic.clone();
        let done = done.clone();

        handles.push(thread::spawn(move || {
            let guard = pin();

            while !done.load(Ordering::Relaxed) {
                let ptr = atomic.load(Ordering::Acquire, &guard);
                if let Some(node) = unsafe { ptr.as_ref() } {
                    let _ = node.value;
                }
                thread::sleep(Duration::from_millis(10));
            }
        }));
    }

    // Short-lived operation threads
    for tid in 0..NUM_SHORT {
        let atomic = atomic.clone();

        handles.push(thread::spawn(move || {
            for i in 0..SHORT_ITERATIONS {
                let new_node = StressNode::new(tid * SHORT_ITERATIONS + i);

                let guard = pin();
                let old = atomic.swap(
                    unsafe { kovan::Shared::from_raw(new_node) },
                    Ordering::Release,
                    &guard,
                );

                if !old.is_null() {
                    unsafe {
                        retire(old.as_raw());
                    }
                }
            }
        }));
    }

    // Wait for short threads
    for handle in handles.drain(NUM_LONG..) {
        handle.join().unwrap();
    }

    // Signal long threads to stop
    done.store(true, Ordering::Relaxed);

    // Wait for long threads
    for handle in handles {
        handle.join().unwrap();
    }

    println!("Long-running guards test: PASS");

    // Cleanup
    let guard = pin();
    let old = atomic.swap(
        unsafe { kovan::Shared::from_raw(std::ptr::null_mut()) },
        Ordering::Release,
        &guard,
    );
    if !old.is_null() {
        unsafe {
            retire(old.as_raw());
        }
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn test_burst_workload() {
    // Alternating periods of high and low activity
    const NUM_THREADS: usize = 8;
    const BURSTS: usize = 10;
    const OPS_PER_BURST: usize = 10000;

    let atomic = Arc::new(Atomic::new(StressNode::new(0)));

    for burst in 0..BURSTS {
        let mut handles = vec![];

        for tid in 0..NUM_THREADS {
            let atomic = atomic.clone();

            handles.push(thread::spawn(move || {
                for i in 0..OPS_PER_BURST {
                    let new_node = StressNode::new(
                        burst * NUM_THREADS * OPS_PER_BURST + tid * OPS_PER_BURST + i,
                    );

                    let guard = pin();
                    let old = atomic.swap(
                        unsafe { kovan::Shared::from_raw(new_node) },
                        Ordering::Release,
                        &guard,
                    );

                    if !old.is_null() {
                        unsafe {
                            retire(old.as_raw());
                        }
                    }
                }
            }));
        }

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

        // Quiet period
        thread::sleep(Duration::from_millis(100));
    }

    println!("Burst workload test: PASS");

    // Cleanup
    let guard = pin();
    let old = atomic.swap(
        unsafe { kovan::Shared::from_raw(std::ptr::null_mut()) },
        Ordering::Release,
        &guard,
    );
    if !old.is_null() {
        unsafe {
            retire(old.as_raw());
        }
    }
}

/// Verify that >128 concurrent threads work (previously panicked with fixed MAX_THREADS=128).
#[test]
#[cfg_attr(miri, ignore)]
fn test_many_threads_beyond_old_limit() {
    let num_threads = 256;
    let shared = Arc::new(Atomic::new(StressNode::new(0)));
    let barrier = Arc::new(std::sync::Barrier::new(num_threads));

    let handles: Vec<_> = (0..num_threads)
        .map(|i| {
            let shared = shared.clone();
            let barrier = barrier.clone();
            thread::spawn(move || {
                barrier.wait();
                let guard = pin();
                let _ = shared.load(Ordering::Acquire, &guard);
                // Each thread does a store to exercise retirement
                let node = StressNode::new(i);
                let old = shared.swap(
                    unsafe { kovan::Shared::from_raw(node) },
                    Ordering::AcqRel,
                    &guard,
                );
                if !old.is_null() {
                    unsafe {
                        retire(old.as_raw());
                    }
                }
            })
        })
        .collect();

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