shuttle 0.8.1

A library for testing concurrent Rust code
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
use shuttle::scheduler::PctScheduler;
use shuttle::sync::{mpsc::channel, RwLock};
use shuttle::{check, check_dfs, check_random, thread, Runner};
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, TryLockError};
use test_log::test;

#[test]
fn reader_concurrency() {
    let saw_concurrent_reads = Arc::new(AtomicBool::new(false));

    {
        let saw_concurrent_reads = Arc::clone(&saw_concurrent_reads);

        check_random(
            move || {
                let rwlock = Arc::new(RwLock::new(0usize));
                let readers = Arc::new(AtomicUsize::new(0));

                {
                    let rwlock = Arc::clone(&rwlock);
                    let readers = Arc::clone(&readers);
                    let saw_concurrent_reads = Arc::clone(&saw_concurrent_reads);

                    thread::spawn(move || {
                        let counter = rwlock.read().unwrap();
                        assert_eq!(*counter, 0);

                        readers.fetch_add(1, Ordering::SeqCst);

                        thread::yield_now();

                        if readers.load(Ordering::SeqCst) == 2 {
                            saw_concurrent_reads.store(true, Ordering::SeqCst);
                        }

                        readers.fetch_sub(1, Ordering::SeqCst);
                    });
                }

                let counter = rwlock.read().unwrap();
                assert_eq!(*counter, 0);

                readers.fetch_add(1, Ordering::SeqCst);

                thread::yield_now();

                if readers.load(Ordering::SeqCst) == 2 {
                    saw_concurrent_reads.store(true, Ordering::SeqCst);
                }

                readers.fetch_sub(1, Ordering::SeqCst);
            },
            100,
        );
    }

    assert!(saw_concurrent_reads.load(Ordering::SeqCst));
}

fn deadlock() {
    let lock1 = Arc::new(RwLock::new(0usize));
    let lock2 = Arc::new(RwLock::new(0usize));
    let lock1_clone = Arc::clone(&lock1);
    let lock2_clone = Arc::clone(&lock2);

    thread::spawn(move || {
        let _l1 = lock1_clone.read().unwrap();
        let _l2 = lock2_clone.read().unwrap();
    });

    let _l2 = lock2.write().unwrap();
    let _l1 = lock1.write().unwrap();
}

#[test]
#[should_panic(expected = "deadlock")]
fn deadlock_default() {
    // Round-robin should always fail this deadlock test
    check(deadlock);
}

#[test]
#[should_panic(expected = "deadlock")]
fn deadlock_random() {
    // 200 tries should be enough to find a deadlocking execution
    check_random(deadlock, 200);
}

#[test]
#[should_panic(expected = "deadlock")]
fn deadlock_pct() {
    // 200 tries should be enough to find a deadlocking execution
    let scheduler = PctScheduler::new(2, 100);
    let runner = Runner::new(scheduler, Default::default());
    runner.run(deadlock);
}

// Test case for a bug we found in Loom: https://github.com/tokio-rs/loom/pull/135
#[test]
fn rwlock_two_writers() {
    check_random(
        || {
            let lock = Arc::new(RwLock::new(1));
            let lock2 = lock.clone();

            thread::spawn(move || {
                let mut w = lock.write().unwrap();
                *w += 1;
                thread::yield_now();
            });

            thread::spawn(move || {
                let mut w = lock2.write().unwrap();
                *w += 1;
                thread::yield_now();
            });
        },
        100,
    );
}

// Check that multiple readers are allowed to read at a time
// This test should never deadlock.
#[test]
fn rwlock_allows_multiple_readers() {
    check_dfs(
        || {
            let lock1 = Arc::new(RwLock::new(1));
            let lock2 = lock1.clone();

            let (s1, r1) = channel::<usize>();
            let (s2, r2) = channel::<usize>();

            thread::spawn(move || {
                let w = lock1.read().unwrap();
                s1.send(*w).unwrap(); // Send value to other thread
                let r = r2.recv().unwrap(); // Wait for value from other thread
                assert_eq!(r, 1);
            });

            thread::spawn(move || {
                let w = lock2.read().unwrap();
                s2.send(*w).unwrap();
                let r = r1.recv().unwrap();
                assert_eq!(r, 1);
            });
        },
        None,
    );
}

// Ensure that a writer is never woken up when a reader is using the lock
fn two_readers_and_one_writer() {
    let lock1 = Arc::new(RwLock::new(1));

    // Spawn two readers, each tries to acquire both locks
    for _ in 0..2 {
        let rlock1 = lock1.clone();
        thread::spawn(move || {
            let r1 = rlock1.read().unwrap();
            thread::yield_now();
            assert!(*r1 > 0);
        });
    }

    // Writer runs on the main thread
    let mut w = lock1.write().unwrap();
    *w += 1;
}

#[test]
fn rwlock_two_readers_and_one_writer_exhaustive() {
    check_dfs(two_readers_and_one_writer, None);
}

#[test]
fn rwlock_default() {
    struct Point(u32, u32);
    impl Default for Point {
        fn default() -> Self {
            Self(21, 42)
        }
    }

    check_dfs(
        || {
            let point: RwLock<Point> = Default::default();

            let r = point.read().unwrap();
            assert_eq!(r.0, 21);
            assert_eq!(r.1, 42);
        },
        None,
    );
}

#[test]
fn rwlock_into_inner() {
    check_dfs(
        || {
            let lock = Arc::new(RwLock::new(0u64));

            let threads = (0..2)
                .map(|_| {
                    let lock = lock.clone();
                    thread::spawn(move || {
                        *lock.write().unwrap() += 1;
                    })
                })
                .collect::<Vec<_>>();

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

            let lock = Arc::try_unwrap(lock).unwrap();
            assert_eq!(lock.into_inner().unwrap(), 2);
        },
        None,
    )
}

/// Two concurrent threads trying to do an atomic increment using `try_write`.
/// One `try_write` must succeed, while the other may or may not succeed.
/// Thus we expect to see final values 1 and 2.
#[test]
fn concurrent_try_increment() {
    let observed_values = Arc::new(std::sync::Mutex::new(HashSet::new()));
    let observed_values_clone = Arc::clone(&observed_values);

    check_dfs(
        move || {
            let lock = Arc::new(RwLock::new(0usize));

            let threads = (0..2)
                .map(|_| {
                    let lock = Arc::clone(&lock);
                    thread::spawn(move || {
                        match lock.try_write() {
                            Ok(mut guard) => {
                                *guard += 1;
                            }
                            Err(TryLockError::WouldBlock) => (),
                            Err(_) => panic!("unexpected TryLockError"),
                        };
                    })
                })
                .collect::<Vec<_>>();

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

            let value = Arc::try_unwrap(lock).unwrap().into_inner().unwrap();
            observed_values_clone.lock().unwrap().insert(value);
        },
        None,
    );

    let observed_values = Arc::try_unwrap(observed_values).unwrap().into_inner().unwrap();
    assert_eq!(observed_values, HashSet::from([1, 2]));
}

/// Run some threads that try to acquire the lock in both read and write modes, and check that any
/// execution allowed by our `RwLock` implementation is allowed by `std`.
#[test]
fn try_lock_implies_std() {
    check_random(
        move || {
            let lock = Arc::new(RwLock::new(()));
            let reference_lock = Arc::new(std::sync::RwLock::new(()));

            let threads = (0..3)
                .map(|_| {
                    let lock = Arc::clone(&lock);
                    let reference_lock = Arc::clone(&reference_lock);
                    thread::spawn(move || {
                        for _ in 0..3 {
                            {
                                let _r = lock.try_read();
                                if _r.is_ok() {
                                    assert!(reference_lock.try_read().is_ok());
                                }
                            }
                            {
                                let _w = lock.try_write();
                                if _w.is_ok() {
                                    assert!(reference_lock.try_write().is_ok());
                                }
                            }
                        }
                    })
                })
                .collect::<Vec<_>>();

            for thd in threads {
                thd.join().unwrap();
            }
        },
        5000,
    );
}

/// Run some threads that try to acquire the lock in both read and write modes, and check that any
/// execution allowed by `std` is allowed by our `RwLock` implementation. (This implication isn't
/// true in general -- see `double_try_read` -- but is true for this test).
#[test]
fn try_lock_implied_by_std() {
    check_random(
        move || {
            let lock = Arc::new(RwLock::new(()));
            let reference_lock = Arc::new(std::sync::RwLock::new(()));

            let threads = (0..3)
                .map(|_| {
                    let lock = Arc::clone(&lock);
                    let reference_lock = Arc::clone(&reference_lock);
                    thread::spawn(move || {
                        for _ in 0..5 {
                            {
                                let _r = reference_lock.try_read();
                                if _r.is_ok() {
                                    assert!(lock.try_read().is_ok());
                                }
                            }
                            {
                                let _w = reference_lock.try_write();
                                if _w.is_ok() {
                                    assert!(lock.try_write().is_ok());
                                }
                            }
                        }
                    })
                })
                .collect::<Vec<_>>();

            for thd in threads {
                thd.join().unwrap();
            }
        },
        5000,
    );
}

/// Three concurrent threads, one doing an atomic increment by 1 using `write`, one trying to do an
/// atomic increment by 1 followed by trying to do an atomic increment by 2 using `try_write`, and a
/// third that peeks at the value using `try_read.` The `write` must succeed, while each `try_write`
/// may or may not succeed.
#[test]
fn concurrent_write_try_write_try_read() {
    let observed_values = Arc::new(std::sync::Mutex::new(HashSet::new()));
    let observed_values_clone = Arc::clone(&observed_values);

    check_dfs(
        move || {
            let lock = Arc::new(RwLock::new(0usize));

            let write_thread = {
                let lock = Arc::clone(&lock);
                thread::spawn(move || {
                    *lock.write().unwrap() += 1;
                })
            };
            let try_write_thread = {
                let lock = Arc::clone(&lock);
                thread::spawn(move || {
                    for n in 1..3 {
                        match lock.try_write() {
                            Ok(mut guard) => {
                                *guard += n;
                            }
                            Err(TryLockError::WouldBlock) => (),
                            Err(_) => panic!("unexpected TryLockError"),
                        };
                    }
                })
            };

            let read_value = match lock.try_read() {
                Ok(guard) => Some(*guard),
                Err(TryLockError::WouldBlock) => None,
                Err(_) => panic!("unexpected TryLockError"),
            };

            write_thread.join().unwrap();
            try_write_thread.join().unwrap();

            let final_value = Arc::try_unwrap(lock).unwrap().into_inner().unwrap();
            observed_values_clone.lock().unwrap().insert((final_value, read_value));
        },
        None,
    );

    let observed_values = Arc::try_unwrap(observed_values).unwrap().into_inner().unwrap();
    // The idea here is that the `try_read` can interleave anywhere between the (successful) writes,
    // but can also just fail.
    let expected_values = HashSet::from([
        // Both `try_write`s fail
        (1, None),
        (1, Some(0)),
        (1, Some(1)),
        // Second `try_write` fails
        (2, None),
        (2, Some(0)),
        (2, Some(1)),
        (2, Some(2)),
        // First `try_write` fails
        (3, None),
        (3, Some(0)),
        (3, Some(1)),
        // (3, Some(2)), // If first `try_write` failed, the value of the lock is never 2
        (3, Some(3)),
        // Both `try_write`s succeed
        (4, None),
        (4, Some(0)),
        (4, Some(1)),
        (4, Some(2)),
        (4, Some(3)),
        (4, Some(4)),
    ]);
    assert_eq!(observed_values, expected_values);
}

/// This behavior is _sometimes_ allowed in `std`, but advised against, as it can lead to deadlocks
/// on some platforms if the second `read` races with another thread's `write`. We conservatively
/// rule it out in all cases to better detect potential deadlocks.
#[test]
#[should_panic(expected = "tried to acquire a RwLock it already holds")]
fn double_read() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.read().unwrap();
            let _guard_2 = rwlock.read();
        },
        None,
    )
}

#[test]
#[should_panic(expected = "tried to acquire a RwLock it already holds")]
fn double_write() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.write().unwrap();
            let _guard_2 = rwlock.write();
        },
        None,
    )
}

#[test]
#[should_panic(expected = "tried to acquire a RwLock it already holds")]
fn read_upgrade() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.read().unwrap();
            let _guard_2 = rwlock.write();
        },
        None,
    )
}

#[test]
#[should_panic(expected = "tried to acquire a RwLock it already holds")]
fn write_downgrade() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.write().unwrap();
            let _guard_2 = rwlock.read();
        },
        None,
    )
}

/// This behavior isn't consistent with `std`, which seems to suggest that `try_read` succeeds if
/// the current thread already holds a read lock. We assume it always fails so that we can more
/// easily diagnose potential deadlocks, especially with async tasks that might migrate across
/// threads in real implementations.
#[test]
fn double_try_read() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.try_read().unwrap();
            assert!(matches!(rwlock.try_read(), Err(TryLockError::WouldBlock)));
        },
        None,
    )
}

/// As with `double_try_read`, this isn't consistent with `std`.
#[test]
fn read_try_read() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.read().unwrap();
            assert!(matches!(rwlock.try_read(), Err(TryLockError::WouldBlock)));
        },
        None,
    )
}

#[test]
fn double_try_write() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.try_write().unwrap();
            assert!(matches!(rwlock.try_write(), Err(TryLockError::WouldBlock)));
        },
        None,
    )
}

#[test]
fn write_try_write() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.write().unwrap();
            assert!(matches!(rwlock.try_write(), Err(TryLockError::WouldBlock)));
        },
        None,
    )
}

#[test]
fn try_read_upgrade() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.try_read().unwrap();
            assert!(matches!(rwlock.try_write(), Err(TryLockError::WouldBlock)));
        },
        None,
    )
}

#[test]
fn try_write_downgrade() {
    check_dfs(
        || {
            let rwlock = RwLock::new(());
            let _guard_1 = rwlock.try_write().unwrap();
            assert!(matches!(rwlock.try_read(), Err(TryLockError::WouldBlock)));
        },
        None,
    )
}