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
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
use shuttle::current::{get_name_for_task, me};
use shuttle::sync::{Barrier, Condvar, Mutex};
use shuttle::{check_dfs, check_random, future, thread};
use std::collections::HashSet;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::Arc;
use test_log::test;

#[test]
fn thread_yield_point() {
    let success = Arc::new(AtomicU8::new(0));
    let success_clone = Arc::clone(&success);

    // We want to see executions that include both threads running first, otherwise we have
    // messed up the yieldpoints around spawn.
    check_random(
        move || {
            let flag = Arc::new(AtomicBool::new(false));
            let flag_clone = Arc::clone(&flag);

            thread::spawn(move || {
                flag_clone.store(true, Ordering::SeqCst);
            });

            if flag.load(Ordering::SeqCst) {
                success.fetch_or(0x1, Ordering::SeqCst);
            } else {
                success.fetch_or(0x2, Ordering::SeqCst);
            }
        },
        100,
    );

    assert_eq!(success_clone.load(Ordering::SeqCst), 0x3);
}

#[test]
fn thread_scope() {
    check_dfs(
        || {
            let mut trigger = false;
            thread::scope(|s| {
                s.spawn(|| {
                    trigger = true;
                });
            });
            assert!(trigger);
        },
        None,
    );
}

#[test]
fn thread_scope_multiple() {
    check_dfs(
        || {
            let mut data = vec![1, 2, 3, 4, 5, 6];

            thread::scope(|s| {
                let (left, right) = data.split_at_mut(3);

                s.spawn(|| {
                    for x in left {
                        *x *= 10;
                    }
                });

                s.spawn(|| {
                    for x in right {
                        *x += 100;
                    }
                });
            });

            assert_eq!(data, vec![10, 20, 30, 104, 105, 106]);
        },
        None,
    );
}

#[test]
fn thread_scope_join() {
    check_dfs(
        || {
            let num = Mutex::new(10);

            thread::scope(|s| {
                let handle = s.spawn(|| {
                    let mut num_guard = num.lock().unwrap();
                    *num_guard *= 10;
                    *num_guard
                });

                assert_eq!(handle.join().unwrap(), 100);

                let handle = s.spawn(|| {
                    let mut num_guard = num.lock().unwrap();
                    *num_guard += 10;
                    *num_guard
                });

                assert_eq!(handle.join().unwrap(), 110);
            });

            assert_eq!(*num.lock().unwrap(), 110);
        },
        None,
    );
}

#[test]
fn thread_join() {
    check_random(
        || {
            let lock = Arc::new(Mutex::new(false));
            let lock_clone = Arc::clone(&lock);
            let handle = thread::spawn(move || {
                *lock_clone.lock().unwrap() = true;
                1
            });
            let ret = handle.join();
            assert_eq!(ret.unwrap(), 1);
            assert!(*lock.lock().unwrap());
        },
        100,
    );
}

#[test]
fn thread_join_drop() {
    check_random(
        || {
            let lock = Arc::new(Mutex::new(false));
            let lock_clone = Arc::clone(&lock);
            let handle = thread::spawn(move || {
                *lock_clone.lock().unwrap() = true;
                1
            });
            drop(handle);
            *lock.lock().unwrap() = true;
        },
        100,
    );
}

#[test]
fn thread_builder_name() {
    check_random(
        || {
            let builder = thread::Builder::new().name("producer".into());
            let handle = builder
                .spawn(|| {
                    let name = String::from(get_name_for_task(me()).unwrap());
                    assert_eq!(name, "producer");
                    thread::yield_now();
                })
                .unwrap();
            assert_eq!(handle.thread().name().unwrap(), "producer");
        },
        100,
    );
}

#[test]
fn thread_identity() {
    check_dfs(
        || {
            let lock = std::sync::Arc::new(Mutex::new(None));
            let lock2 = lock.clone();

            let builder = thread::Builder::new().name("producer".into());
            let _handle = builder
                .spawn(move || {
                    let me = thread::current();
                    assert_eq!(me.name(), Some("producer"));
                    let id = me.id();

                    thread::yield_now();

                    let me = thread::current();
                    assert_eq!(me.name(), Some("producer"));
                    assert_eq!(me.id(), id);

                    *lock2.lock().unwrap() = Some(id);
                })
                .unwrap();

            let id = *lock.lock().unwrap();
            if let Some(id) = id {
                assert_ne!(id, thread::current().id());
            }
        },
        None,
    );
}

/// Thread local tests
///
/// The first three are based on Loom's thread local tests:
/// https://github.com/tokio-rs/loom/blob/562211da5978f729e5728667566636c34c9cbc8b/tests/thread_local.rs
mod thread_local {
    use super::*;
    use shuttle::thread::LocalKey;
    use std::cell::RefCell;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use test_log::test;

    #[test]
    fn basic() {
        shuttle::thread_local! {
            static THREAD_LOCAL: RefCell<usize> = RefCell::new(1);
        }

        fn do_test(n: usize) {
            THREAD_LOCAL.with(|local| {
                assert_eq!(*local.borrow(), 1);
            });
            THREAD_LOCAL.with(|local| {
                assert_eq!(*local.borrow(), 1);
                *local.borrow_mut() = n;
                assert_eq!(*local.borrow(), n);
            });
            THREAD_LOCAL.with(|local| {
                assert_eq!(*local.borrow(), n);
            });
        }

        check_dfs(
            || {
                let t1 = thread::spawn(|| do_test(2));

                let t2 = thread::spawn(|| do_test(3));

                do_test(4);

                t1.join().unwrap();
                t2.join().unwrap();
            },
            None,
        );
    }

    #[test]
    fn nested_with() {
        shuttle::thread_local! {
            static LOCAL1: RefCell<usize> = RefCell::new(1);
            static LOCAL2: RefCell<usize> = RefCell::new(2);
        }

        check_dfs(
            || {
                LOCAL1.with(|local1| *local1.borrow_mut() = LOCAL2.with(|local2| *local2.borrow()));
                LOCAL1.with(|local1| assert_eq!(*local1.borrow(), 2));
            },
            None,
        );
    }

    struct CountDrops {
        drops: &'static AtomicUsize,
        dummy: bool,
    }

    impl Drop for CountDrops {
        fn drop(&mut self) {
            self.drops.fetch_add(1, Ordering::Release);
        }
    }

    impl CountDrops {
        fn new(drops: &'static AtomicUsize) -> Self {
            Self { drops, dummy: true }
        }
    }

    #[test]
    fn drop() {
        static DROPS: AtomicUsize = AtomicUsize::new(0);

        shuttle::thread_local! {
            static DROPPED_LOCAL: CountDrops = CountDrops::new(&DROPS);
        }

        check_dfs(
            || {
                // Reset the drop counter. We don't count drops with a fresh AtomicUsize within the test
                // because we want to be able to check the drop counter *after* the last thread exits.
                // If this is the first iteration, drops will be 0, otherwise it should be 3 (set by the
                // previous iteration of the test).
                let drops = DROPS.swap(0, Ordering::SeqCst);
                assert!(drops == 0 || drops == 3);

                let thd = thread::spawn(|| {
                    // force access to the thread local so that it's initialized.
                    DROPPED_LOCAL.with(|local| assert!(local.dummy));
                    assert_eq!(DROPS.load(Ordering::SeqCst), 0);
                });
                thd.join().unwrap();

                // When the first spawned thread completed, its copy of the thread local should have
                // been dropped.
                assert_eq!(DROPS.load(Ordering::SeqCst), 1);

                let thd = thread::spawn(|| {
                    // force access to the thread local so that it's initialized.
                    DROPPED_LOCAL.with(|local| assert!(local.dummy));
                    assert_eq!(DROPS.load(Ordering::SeqCst), 1);
                });
                thd.join().unwrap();

                // When the second spawned thread completed, its copy of the thread local should have
                // been dropped as well.
                assert_eq!(DROPS.load(Ordering::SeqCst), 2);

                // force access to the thread local so that it's initialized.
                DROPPED_LOCAL.with(|local| assert!(local.dummy));
            },
            None,
        );

        // Finally, when the test's "main thread" completes, its copy of the local should also be
        // dropped. Because we reset the `DROPS` static to 0 at the start of each iteration, we know
        // the correct value here regardless of how many iterations run.
        assert_eq!(DROPS.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn drop_main_thread() {
        static DROPS: AtomicUsize = AtomicUsize::new(0);
        shuttle::thread_local! {
            static DROPPED_LOCAL: CountDrops = CountDrops::new(&DROPS);
        }
        let seen_drop_counters = Arc::new(std::sync::Mutex::new(HashSet::new()));
        let seen_drop_counters_clone = seen_drop_counters.clone();

        check_dfs(
            move || {
                DROPS.store(0, Ordering::SeqCst);
                let seen_drop_counters = seen_drop_counters.clone();
                let _thd = thread::spawn(move || {
                    // force access to the thread local so that it's initialized
                    DROPPED_LOCAL.with(|local| assert!(local.dummy));
                    // record the current drop counter
                    seen_drop_counters.lock().unwrap().insert(DROPS.load(Ordering::SeqCst));
                });

                // force access to the thread local so that it's initialized
                DROPPED_LOCAL.with(|local| assert!(local.dummy));
            },
            None,
        );

        // We should have seen both orderings. In particular, it should be possible for the main
        // thread to drop its thread local before the spawned thread.
        assert_eq!(
            Arc::try_unwrap(seen_drop_counters_clone).unwrap().into_inner().unwrap(),
            HashSet::from([0, 1])
        );
    }

    // Like `drop`, but the destructor for one thread local initializes another thread local, and so
    // both destructors must be run (which Loom doesn't do)
    #[test]
    fn drop_init() {
        struct TouchOnDrop(CountDrops, &'static LocalKey<CountDrops>);

        impl Drop for TouchOnDrop {
            fn drop(&mut self) {
                self.1.with(|local| assert!(local.dummy));
            }
        }

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

        shuttle::thread_local! {
            static LOCAL1: CountDrops = CountDrops::new(&DROPS);
            static LOCAL2: TouchOnDrop = TouchOnDrop(CountDrops::new(&DROPS), &LOCAL1);
        }

        check_dfs(
            || {
                let drops = DROPS.swap(0, Ordering::SeqCst);
                // Same story as the `drop` test above, but the main thread only initializes LOCAL1
                // and not LOCAL2, so its destructors only trigger one drop.
                assert!(drops == 0 || drops == 3);

                let thd = thread::spawn(|| {
                    // force access to LOCAL2 so that it's initialized.
                    LOCAL2.with(|local| assert!(local.0.dummy));
                    assert_eq!(DROPS.load(Ordering::SeqCst), 0);
                });
                thd.join().unwrap();

                // When the first spawned thread completed, its copy of LOCAL2 should drop, and
                // LOCAL2's dtor initializes LOCAL1, which then also needs to be dropped. So we
                // should have run two CountDrops dtors by this point.
                assert_eq!(DROPS.load(Ordering::SeqCst), 2);

                // force access to LOCAL1 so that it's initialized.
                LOCAL1.with(|local| assert!(local.dummy));
            },
            None,
        );

        // The main thread only initializes LOCAL1 and not LOCAL2, so it only triggers one more drop
        assert_eq!(DROPS.load(Ordering::SeqCst), 3);
    }

    // Runs some synchronization code in the Drop handler
    #[test]
    fn drop_lock() {
        // Slightly funky type: the RefCell gives interior mutability, the Option allows us to
        // initialize the static before the lock is constructed.
        struct LockOnDrop(RefCell<Option<Arc<Mutex<usize>>>>);

        impl Drop for LockOnDrop {
            fn drop(&mut self) {
                *self.0.borrow_mut().as_ref().unwrap().lock().unwrap() += 1;
            }
        }

        shuttle::thread_local! {
            static LOCAL: LockOnDrop = LockOnDrop(RefCell::new(None));
        }

        check_dfs(
            || {
                let lock = Arc::new(Mutex::new(0));

                let thd = {
                    let lock = Arc::clone(&lock);
                    thread::spawn(move || {
                        // initialize LOCAL with the lock
                        LOCAL.with(|local| *local.0.borrow_mut() = Some(lock.clone()));
                        assert_eq!(*lock.lock().unwrap(), 0);
                    })
                };
                thd.join().unwrap();

                // When the first spawned thread completed, its copy of LOCAL should drop, and bump
                // the lock counter by 1.
                assert_eq!(*lock.lock().unwrap(), 1);
            },
            None,
        );
    }

    // Like `nested_with` but just testing the const variant of the `thread_local` macro
    #[test]
    fn const_nested_with() {
        shuttle::thread_local! {
            static LOCAL1: RefCell<usize> = const { RefCell::new(1) };
            static LOCAL2: RefCell<usize> = const { RefCell::new(2) };
        }

        check_dfs(
            || {
                LOCAL1.with(|local1| *local1.borrow_mut() = LOCAL2.with(|local2| *local2.borrow()));
            },
            None,
        );
    }

    #[test]
    fn multiple_accesses() {
        shuttle::thread_local! {
            static LOCAL: RefCell<usize> = RefCell::new(0);
        }

        fn increment() {
            LOCAL.with(|local| {
                *local.borrow_mut() += 1;
            });
        }

        fn check() {
            LOCAL.with(|local| {
                assert_eq!(*local.borrow(), 1);
            });
        }

        check_dfs(
            || {
                increment();
                check();
            },
            None,
        )
    }

    /// Thread-local destructors weren't being run for the main thread
    /// https://github.com/awslabs/shuttle/issues/86
    #[test]
    fn regression_86() {
        use core::cell::Cell;
        use shuttle::sync::*;
        let mu: &'static mut Mutex<usize> = Box::leak(Box::new(Mutex::new(0))); // a static_local here instead also works
        shuttle::thread_local! {
            static STASH: Cell<Option<MutexGuard<'_, usize>>> = Cell::new(None);
        }
        shuttle::check_random(
            || {
                shuttle::thread::spawn(|| {
                    STASH.with(|s| s.set(Some(mu.lock().unwrap())));
                });
                STASH.with(|s| s.set(Some(mu.lock().unwrap())));
            },
            100,
        );
    }
}

/// Test the common usage of park where a thread calls park in a loop waiting for a flag to be set.
#[test]
fn thread_park() {
    check_dfs(
        || {
            let shared_state = Arc::new(AtomicU8::new(0));
            let wakeup = Arc::new(AtomicBool::new(false));
            let thd = {
                let shared_state = Arc::clone(&shared_state);
                let wakeup = Arc::clone(&wakeup);
                thread::spawn(move || {
                    while !wakeup.load(Ordering::SeqCst) {
                        thread::park();
                    }
                    assert_eq!(shared_state.load(Ordering::SeqCst), 42);
                })
            };

            shared_state.store(42, Ordering::SeqCst);

            wakeup.store(true, Ordering::SeqCst);
            thd.thread().unpark();
            thd.join().unwrap();
        },
        Some(150), // We can't exhaust all orderings because of the infinite loop in the thread.
    )
}

// Test that shuttle explores schedulings where parked threads can be spuriously woken up.
// Threads should not rely on using park to accomplish synchronization.
#[test]
#[should_panic(expected = "spurious")]
fn thread_park_spuriously_wakeup() {
    check_dfs(
        || {
            let flag = Arc::new(AtomicBool::new(false));
            let thd = {
                let flag = Arc::clone(&flag);
                thread::spawn(move || {
                    thread::park();
                    assert!(flag.load(Ordering::SeqCst), "may not be true due to spurious wakeup");
                })
            };

            flag.store(true, Ordering::SeqCst);
            thd.thread().unpark();
            thd.join().unwrap();
        },
        None,
    )
}

// Test that Shuttle will detect a deadlock and panic if all threads are blocked in `park`, even
// though `park` can spuriously wake, since spurious wakeups aren't guaranteed and programs should
// not rely on them in order to make forward progress.
#[test]
#[should_panic(expected = "deadlock")]
fn thread_park_deadlock() {
    check_dfs(
        || {
            let thd = thread::spawn(thread::park);
            thread::park();
            thd.join().unwrap();
        },
        None,
    )
}

// From the docs: "Because the token is initially absent, `unpark` followed by `park` will result in
// the second call returning immediately"
#[test]
fn thread_unpark_park() {
    check_dfs(
        || {
            thread::current().unpark();
            thread::park();
        },
        None,
    )
}

// Test that `unpark` is not cumulative: multiple calls to `unpark` will still only unblock the very
// next call to `park`.
#[test]
#[should_panic(expected = "deadlock")]
fn thread_unpark_not_cumulative() {
    check_dfs(
        || {
            thread::current().unpark();
            thread::current().unpark();
            thread::park();
            thread::park();
        },
        None,
    )
}

// Unparking a thread should not unconditionally unblock it (e.g., if it's blocked waiting on a lock
// rather than parked)
#[test]
fn thread_unpark_unblock() {
    check_dfs(
        || {
            let lock = Arc::new(Mutex::new(false));
            let condvar = Arc::new(Condvar::new());

            let reader = {
                let lock = Arc::clone(&lock);
                let condvar = Arc::clone(&condvar);
                thread::spawn(move || {
                    let mut guard = lock.lock().unwrap();
                    while !*guard {
                        guard = condvar.wait(guard).unwrap();
                    }
                })
            };

            let _writer = {
                let lock = Arc::clone(&lock);
                let condvar = Arc::clone(&condvar);
                thread::spawn(move || {
                    let mut guard = lock.lock().unwrap();
                    *guard = true;
                    condvar.notify_one();
                })
            };

            reader.thread().unpark();
        },
        None,
    )
}

// Calling `unpark` on a thread that has already been unparked should be a no-op
#[test]
fn thread_double_unpark() {
    let seen_unparks = Arc::new(std::sync::Mutex::new(HashSet::new()));
    let seen_unparks_clone = Arc::clone(&seen_unparks);

    check_dfs(
        move || {
            let unpark_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
            let parkee = {
                let seen_unparks = Arc::clone(&seen_unparks);
                let unpark_count = Arc::clone(&unpark_count);
                thread::spawn(move || {
                    thread::park();
                    let unpark_count = unpark_count.load(Ordering::SeqCst);
                    seen_unparks.lock().unwrap().insert(unpark_count);
                    // If this is 1 we know `unpark` will be uncalled again, so this won't deadlock
                    if unpark_count == 1 {
                        thread::park();
                    }
                })
            };

            unpark_count.fetch_add(1, Ordering::SeqCst);
            parkee.thread().unpark();
            unpark_count.fetch_add(1, Ordering::SeqCst);
            parkee.thread().unpark();
        },
        None,
    );

    let seen_unparks = Arc::try_unwrap(seen_unparks_clone).unwrap().into_inner().unwrap();
    // It's possible for a thread to see 0 unparks, if it spuriously wakes up from a call to `park`.
    assert_eq!(seen_unparks, HashSet::from([0, 1, 2]));
}

// Test that `unpark` won't unblock a thread for reasons other than `park`, even if the blocked
// thread had called `park` before (and possible spuriously woke up).
#[test]
fn thread_unpark_after_spurious_wakeup() {
    check_dfs(
        || {
            let shared_state = Arc::new(AtomicU8::new(0));
            let barrier = Arc::new(Barrier::new(2));

            let thd = {
                let shared_state = Arc::clone(&shared_state);
                let barrier = Arc::clone(&barrier);
                thread::spawn(move || {
                    // Call `park`, which could possibly spuriously wake up.
                    thread::park();

                    // Wait on the barrier. If the main thread calls `unpark` after we've spuriously
                    // woken up from the `park` and starting waiting on the barrier, that shouldn't
                    // unblock this thread.
                    barrier.wait();
                    shared_state.store(1, Ordering::SeqCst);
                })
            };

            // It shouldn't be possible for this `unpark` to allow the thread to bypass waiting
            // on the barrier.
            thd.thread().unpark();
            assert_eq!(shared_state.load(Ordering::SeqCst), 0);

            barrier.wait();
            thd.join().unwrap();

            assert_eq!(shared_state.load(Ordering::SeqCst), 1);
        },
        None,
    )
}

#[test]
fn spawn_local_sanity() {
    check_dfs(
        || {
            let rc = Rc::new(0);
            shuttle::future::block_on(future::spawn_local(async { drop(rc) })).unwrap()
        },
        None,
    );
}