store-io-engine 0.6.0

The store-io engine: volumes, regions, barriers with flush sharing, receipts, provisioning and A/B slot objects over any store-io platform.
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! The flush domain's tests (D-047, D-124).

use super::*;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::mpsc;
use std::time::Duration;

use store_io_core::error::OsErrorSource;

const EIO: OsError = OsError {
    code: 5,
    source: OsErrorSource::Sim,
};

const LONG: Duration = Duration::from_secs(10);

/// Waits until `n` followers are parked: a follower registers under
/// the slot lock and releases it only by waiting, so seeing the count
/// under the lock proves they are waiting.
fn until_waiting(d: &Domain, n: u32) {
    let start = std::time::Instant::now();
    while d.waiting() < n {
        assert!(start.elapsed() < LONG, "never registered");
        std::thread::yield_now();
    }
}

/// A follower waiting behind a leader is woken when leadership is given
/// back (the leader notifies only when a follower is registered), and a
/// lone barrier registers nobody.
#[test]
fn test_a_waiting_follower_is_woken_when_the_leader_returns() {
    let d = Arc::new(Domain::new());
    assert!(d.hold_leadership());
    let need = d.ticket();
    let (tx, rx) = mpsc::channel();
    let follower = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let r = d.barrier(need, |_, _| Ok(()));
            let _sent = tx.send(r.is_ok());
        })
    };
    until_waiting(&d, 1);
    d.drop_leadership();
    assert_eq!(
        rx.recv_timeout(LONG),
        Ok(true),
        "the follower was never woken"
    );
    assert!(follower.join().is_ok(), "the follower panicked");
    assert_eq!(d.waiting(), 0);
    // A lone barrier leads and registers nobody.
    let need = d.ticket();
    assert!(d.barrier(need, |_, _| Ok(())).is_ok());
    assert_eq!(d.waiting(), 0);
}

/// A flush that panics poisons the domain and gives its slot back:
/// later barriers fail at once instead of waiting for a leader that is
/// gone.
#[test]
fn test_a_panicking_flush_poisons_and_releases_leadership() {
    let d = Domain::new();
    let need = d.ticket();
    let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _r = d.barrier(need, |_, _| panic!("the flush panicked"));
    }));
    assert!(r.is_err());
    assert!(
        d.poisoned().is_some(),
        "a flush of unknown outcome did not poison"
    );
    let need = d.ticket();
    assert!(matches!(
        d.barrier(need, |_, _| Ok(())),
        Err(Error::Poisoned { .. })
    ));
}

#[test]
fn test_lone_barrier_issues_exactly_one_flush() {
    let d = Domain::new();
    let mut calls = 0;
    let need = d.ticket();
    assert!(
        d.barrier(need, |_, _| {
            calls += 1;
            Ok(())
        })
        .is_ok()
    );
    assert_eq!(calls, 1);
    // The same need is now satisfied without another flush.
    assert!(d.barrier(need, |_, _| Err(Some(EIO))).is_ok());
    assert_eq!(
        d.stats(),
        DomainStats {
            flushes: 1,
            joined: 1,
            led: 1,
            already_durable: 0,
            peak_in_flight: 1,
            out_of_order: 0,
        }
    );
}

#[test]
fn test_ticket_taken_after_a_flush_needs_the_next_flush() {
    let d = Domain::new();
    assert!(d.barrier(d.ticket(), |_, _| Ok(())).is_ok());
    let mut calls = 0;
    assert!(
        d.barrier(d.ticket(), |_, _| {
            calls += 1;
            Ok(())
        })
        .is_ok()
    );
    assert_eq!(calls, 1, "a write completing after flush 1 needs flush 2");
}

#[test]
fn test_failed_flush_poisons_and_is_never_retried() {
    let d = Domain::new();
    let r = d.barrier(d.ticket(), |_, _| Err(Some(EIO)));
    assert!(matches!(
        r,
        Err(Error::DurabilityUnknown {
            op: Op::FlushData,
            ..
        })
    ));
    let mut calls = 0;
    let r = d.barrier(d.ticket(), |_, _| {
        calls += 1;
        Ok(())
    });
    assert!(matches!(r, Err(Error::Poisoned { .. })));
    assert_eq!(calls, 0, "a poisoned domain must never flush again");
}

#[test]
fn test_satisfied_barrier_keeps_its_result_after_later_poison() {
    let d = Domain::new();
    let need = d.ticket();
    assert!(d.barrier(need, |_, _| Ok(())).is_ok());
    let _ = d.barrier(d.ticket(), |_, _| Err(Some(EIO)));
    assert!(
        d.barrier(need, |_, _| Ok(())).is_ok(),
        "already-durable data stays durable"
    );
}

#[test]
fn test_explicit_poison_wakes_and_fails_followers() {
    let d = Arc::new(Domain::new());
    d.poison(FirstCause {
        op: None,
        raw: None,
    });
    assert!(matches!(
        d.barrier(d.ticket(), |_, _| Ok(())),
        Err(Error::Poisoned { .. })
    ));
}

/// Two slots: flush 2 finishes first, but a barrier needing it is not
/// satisfied until flush 1 (issued earlier, still running) has
/// succeeded too.
#[test]
fn test_a_later_flush_finishing_first_waits_for_the_earlier_one() {
    let d = Arc::new(Domain::with_slots(2));
    let (go, wait_go) = mpsc::channel::<()>();
    let (started, on_start) = mpsc::channel::<usize>();
    let first = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let need = d.ticket();
            d.barrier(need, |slot, _| {
                let _sent = started.send(slot);
                let _released = wait_go.recv_timeout(3 * LONG); // outlasts the test's waits
                Ok(())
            })
        })
    };
    assert_eq!(
        on_start.recv_timeout(LONG),
        Ok(1),
        "flush 1 on the highest slot"
    );
    // A write completed now needs flush 2, which leads on slot 0.
    let need = d.ticket();
    assert_eq!(need, 2);
    let (tx, rx) = mpsc::channel();
    let second = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let mut slot_used = None;
            let r = d.barrier(need, |slot, _| {
                slot_used = Some(slot);
                Ok(())
            });
            let _sent = tx.send((r.is_ok(), slot_used));
        })
    };
    until_waiting(&d, 1);
    assert_eq!(d.done.load(Ordering::SeqCst), 0, "flush 1 is unfinished");
    assert!(rx.try_recv().is_err(), "satisfied before flush 1 finished");
    let _sent = go.send(());
    assert_eq!(rx.recv_timeout(LONG), Ok((true, Some(0))));
    assert!(matches!(first.join(), Ok(Ok(()))));
    assert!(second.join().is_ok());
    assert_eq!(d.done.load(Ordering::SeqCst), 2);
}

/// Two slots: flush 2 succeeds, then flush 1 (issued earlier) fails: the
/// barrier waiting on flush 2 is poisoned, never satisfied.
#[test]
fn test_an_earlier_flush_failing_poisons_a_later_success() {
    let d = Arc::new(Domain::with_slots(2));
    let (go, wait_go) = mpsc::channel::<()>();
    let (started, on_start) = mpsc::channel::<()>();
    let first = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let need = d.ticket();
            d.barrier(need, |_, _| {
                let _sent = started.send(());
                let _released = wait_go.recv_timeout(3 * LONG); // outlasts the test's waits
                Err(Some(EIO))
            })
        })
    };
    assert_eq!(on_start.recv_timeout(LONG), Ok(()));
    let need = d.ticket();
    let second = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || d.barrier(need, |_, _| Ok(())))
    };
    until_waiting(&d, 1);
    let _sent = go.send(());
    assert!(matches!(
        first.join(),
        Ok(Err(Error::DurabilityUnknown { .. }))
    ));
    assert!(matches!(second.join(), Ok(Err(Error::Poisoned { .. }))));
    assert_eq!(d.done.load(Ordering::SeqCst), 0);
}

/// A barrier that can flush only through the main handle waits for slot
/// 0, even with another slot free.
#[test]
fn test_a_main_handle_barrier_leads_only_on_slot_zero() {
    let d = Arc::new(Domain::with_slots(2));
    let (go, wait_go) = mpsc::channel::<()>();
    let (inside, on_inside) = mpsc::channel::<()>();
    // Slot 0 held (a full flush of the main handle); slot 1 free.
    let full = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            d.exclusive_main(|| {
                let _sent = inside.send(());
                let _released = wait_go.recv_timeout(3 * LONG); // outlasts the test's waits
            });
        })
    };
    assert_eq!(on_inside.recv_timeout(LONG), Ok(()));
    let need = d.ticket();
    let (tx, rx) = mpsc::channel();
    let main = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let r = d.barrier_main(need, || Ok(()));
            let _sent = tx.send(r.is_ok());
        })
    };
    until_waiting(&d, 1);
    assert_eq!(d.stats().flushes, 0, "led on slot 1 while slot 0 was held");
    let _sent = go.send(());
    assert_eq!(rx.recv_timeout(LONG), Ok(true));
    assert!(full.join().is_ok());
    assert!(main.join().is_ok());
    assert_eq!(d.stats().flushes, 1);
}

/// Model: a "write" completes at a moment; a flush covers every write
/// completed before the flush started. Each thread checks that a flush
/// it waited for started after its write completed, and that every
/// flush up to it finished first, with one slot and with four.
#[test]
fn test_concurrent_barriers_share_flushes_and_never_cover_late_writes() {
    for slots in [1, 4] {
        let d = Arc::new(Domain::with_slots(slots));
        let clock = Arc::new(AtomicUsize::new(0));
        // (flush number, started at, finished at)
        let flushes = Arc::new(Mutex::new(Vec::<(u64, usize, usize)>::new()));
        let handles: Vec<_> = (0..16)
            .map(|_| {
                let (d, clock, log) = (Arc::clone(&d), Arc::clone(&clock), Arc::clone(&flushes));
                std::thread::spawn(move || {
                    for _ in 0..200 {
                        let completed_at = clock.fetch_add(1, Ordering::SeqCst);
                        let need = d.ticket();
                        let r = d.barrier(need, |_, k| {
                            let started = clock.fetch_add(1, Ordering::SeqCst);
                            // A flush takes time, as a real one does, so
                            // the barriers overlap even on a loaded
                            // machine.
                            std::thread::sleep(Duration::from_micros(100));
                            let finished = clock.fetch_add(1, Ordering::SeqCst);
                            log.lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)
                                .push((k, started, finished));
                            Ok(())
                        });
                        assert!(r.is_ok());
                        let returned = clock.fetch_add(1, Ordering::SeqCst);
                        let log = log
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        let Some(&(_, started, _)) = log.iter().find(|f| f.0 == need) else {
                            panic!("flush {need} never ran");
                        };
                        assert!(
                            started > completed_at,
                            "covering flush started before the write completed"
                        );
                        for n in 1..=need {
                            let f = log.iter().find(|f| f.0 == n);
                            assert!(
                                f.is_some_and(|f| f.2 < returned),
                                "flush {n} unfinished when barrier {need} returned"
                            );
                        }
                    }
                })
            })
            .collect();
        for h in handles {
            assert!(h.join().is_ok());
        }
        let s = d.stats();
        assert_eq!(s.led as usize + s.joined as usize, 16 * 200);
        assert!(s.peak_in_flight <= slots as u64);
        assert!(
            slots == 1 || s.peak_in_flight > 1,
            "four slots never overlapped"
        );
        assert!(
            s.flushes < 16 * 200,
            "concurrent barriers must share flushes ({} flushes, {slots} slots)",
            s.flushes
        );
    }
}

/// A domain poisoned while a flush runs (a failed write elsewhere) keeps
/// that flush's success out: its barrier is poisoned, and `done` stays.
#[test]
fn test_a_flush_finishing_after_poison_satisfies_nothing() {
    let d = Domain::new();
    let need = d.ticket();
    let r = d.barrier(need, |_, _| {
        d.poison(FirstCause {
            op: Some(Op::Write),
            raw: None,
        });
        Ok(())
    });
    assert!(matches!(r, Err(Error::Poisoned { .. })), "{r:?}");
    assert_eq!(d.done.load(Ordering::SeqCst), 0);
}

/// Behind one unfinished flush, at most `WINDOW` flushes are issued: the
/// successes kept above `done` fit their mask, so no later flush can be
/// mistaken for the unfinished one. When it finishes, every barrier is
/// satisfied.
#[test]
fn test_flushes_behind_an_unfinished_one_stay_within_the_window() {
    let d = Arc::new(Domain::with_slots(2));
    let (go, wait_go) = mpsc::channel::<()>();
    let (started, on_start) = mpsc::channel::<()>();
    let first = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let need = d.ticket();
            d.barrier(need, |_, _| {
                let _sent = started.send(());
                let _released = wait_go.recv_timeout(3 * LONG); // outlasts the test's waits
                Ok(())
            })
        })
    };
    assert_eq!(on_start.recv_timeout(LONG), Ok(()));
    let mut later = Vec::new();
    for i in 1..=70u64 {
        let d2 = Arc::clone(&d);
        later.push(std::thread::spawn(move || {
            let need = d2.ticket();
            (need, d2.barrier(need, |_, _| Ok(())))
        }));
        // Until it is parked: after its own flush, or behind the window.
        until_waiting(&d, i as u32);
    }
    // `issued - done` never reached past the window: flush 1 and 31 more.
    assert_eq!(d.stats().flushes, WINDOW, "issued past the window");
    // The next flush's barrier waits behind the window as the designate,
    // and is woken to lead it when flush 1 finishes.
    assert_eq!(d.lock().designate, Some(WINDOW + 1));
    let _sent = go.send(());
    assert!(matches!(first.join(), Ok(Ok(()))));
    for h in later {
        let (need, r) = h.join().unwrap_or((
            0,
            Err(Error::Poisoned {
                first: FirstCause {
                    op: None,
                    raw: None,
                },
            }),
        ));
        assert!(r.is_ok(), "barrier {need}: {r:?}");
        assert!(d.done.load(Ordering::SeqCst) >= need);
    }
}

/// A full flush of the main handle waits for slot 0 and holds it: a barrier
/// that needs a flush leads on another slot meanwhile, and slot 0 is free
/// again afterwards, even when the flush panics.
#[test]
fn test_exclusive_main_holds_slot_zero() {
    let d = Arc::new(Domain::with_slots(2));
    let (go, wait_go) = mpsc::channel::<()>();
    let (inside, on_inside) = mpsc::channel::<()>();
    let full = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            d.exclusive_main(|| {
                let _sent = inside.send(());
                let _released = wait_go.recv_timeout(3 * LONG); // outlasts the test's waits
            });
        })
    };
    assert_eq!(on_inside.recv_timeout(LONG), Ok(()));
    assert_eq!(d.lock().busy & 1, 1, "slot 0 not held");
    let mut slot_used = None;
    assert!(
        d.barrier(d.ticket(), |slot, _| {
            slot_used = Some(slot);
            Ok(())
        })
        .is_ok()
    );
    assert_eq!(slot_used, Some(1), "led on slot 0 while it was held");
    let _sent = go.send(());
    assert!(full.join().is_ok());
    // Checked without waiting, so slot 0 left held fails the test at once.
    assert_eq!(d.lock().busy & 1, 0, "slot 0 stayed held");
    let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        d.exclusive_main(|| panic!("the full flush panicked"));
    }));
    assert!(r.is_err());
    assert_eq!(d.lock().busy & 1, 0, "slot 0 stayed held after a panic");
    // On a thread, so slot 0 left held fails the test instead of hanging it.
    let (tx, rx) = mpsc::channel();
    let after = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let _sent = tx.send(d.barrier_main(d.ticket(), || Ok(())).is_ok());
        })
    };
    assert_eq!(rx.recv_timeout(LONG), Ok(true), "slot 0 stayed held");
    assert!(after.join().is_ok());
}

/// A full flush of the main handle waits while a data leader flushes on
/// slot 0, and runs once it has finished.
#[test]
fn test_exclusive_main_waits_for_a_data_flush_on_slot_zero() {
    let d = Arc::new(Domain::with_slots(2));
    // Two data leaders, flushing at once: the first on slot 1, the second
    // on slot 0.
    let mut leaders = Vec::new();
    let mut gos = Vec::new();
    for expect in [1usize, 0] {
        let (go, wait_go) = mpsc::channel::<()>();
        let (started, on_start) = mpsc::channel::<usize>();
        let d2 = Arc::clone(&d);
        leaders.push(std::thread::spawn(move || {
            let need = d2.ticket();
            d2.barrier(need, |slot, _| {
                let _sent = started.send(slot);
                let _released = wait_go.recv_timeout(3 * LONG); // outlasts the test's waits
                Ok(())
            })
        }));
        assert_eq!(on_start.recv_timeout(LONG), Ok(expect));
        gos.push(go);
    }
    let ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let (full_done, on_full) = mpsc::channel();
    let full = {
        let (d, ran) = (Arc::clone(&d), Arc::clone(&ran));
        std::thread::spawn(move || {
            d.exclusive_main(|| ran.store(true, Ordering::SeqCst));
            let _sent = full_done.send(());
        })
    };
    until_waiting(&d, 1);
    assert!(!ran.load(Ordering::SeqCst), "ran beside the slot-0 flush");
    for go in gos {
        let _sent = go.send(());
    }
    for l in leaders {
        assert!(matches!(l.join(), Ok(Ok(()))));
    }
    let r = on_full.recv_timeout(LONG);
    if r.is_err() {
        // Wake it before failing, so the test never hangs.
        d.notify();
    }
    assert_eq!(r, Ok(()), "the full flush was never woken");
    assert!(full.join().is_ok());
    assert!(ran.load(Ordering::SeqCst));
}

/// On one slot, a full flush waiting for slot 0 has it before a leader that
/// arrives while it waits: with slot 0 free but the full flush not yet
/// woken, the new barrier leaves the slot to it instead of leading.
#[test]
fn test_a_waiting_full_flush_goes_before_new_leaders() {
    let d = Arc::new(Domain::new());
    let order = Arc::new(Mutex::new(Vec::<&str>::new()));
    let push = |order: &Mutex<Vec<&'static str>>, what| {
        order
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .push(what);
    };
    assert!(d.hold_leadership());
    let (full_done, on_full) = mpsc::channel();
    let (go, wait_go) = mpsc::channel::<()>();
    let full = {
        let (d, order) = (Arc::clone(&d), Arc::clone(&order));
        std::thread::spawn(move || {
            d.exclusive_main(|| {
                push(&order, "full");
                let _released = wait_go.recv_timeout(3 * LONG); // outlasts the test's waits
            });
            let _sent = full_done.send(());
        })
    };
    until_waiting(&d, 1);
    // Slot 0 free again, nobody woken yet: the state the rule is for.
    d.lock().busy = 0;
    let (data_done, on_data) = mpsc::channel();
    let data = {
        let (d, order) = (Arc::clone(&d), Arc::clone(&order));
        std::thread::spawn(move || {
            let r = d.barrier(d.ticket(), |_, _| {
                push(&order, "data");
                Ok(())
            });
            let _sent = data_done.send(r.is_ok());
        })
    };
    // (A sleeper leaves only when a waker moved its word, so the full flush
    // cannot run before the data barrier parks: D-126.)
    until_waiting(&d, 2);
    assert_eq!(
        d.stats().flushes,
        0,
        "led on the slot a full flush waits for"
    );
    d.notify();
    // The full flush now holds slot 0; the data barrier parks behind it, so
    // releasing it always has exactly one waiter to wake.
    until_waiting(&d, 1);
    let _sent = go.send(());
    let (f, r) = (on_full.recv_timeout(LONG), on_data.recv_timeout(LONG));
    if f.is_err() || r.is_err() {
        // Free whatever is stuck before failing, so the test never hangs.
        d.poison(FirstCause {
            op: None,
            raw: None,
        });
        d.drop_leadership();
    }
    assert_eq!((f, r), (Ok(()), Ok(true)));
    assert!(full.join().is_ok());
    assert!(data.join().is_ok());
    let order = order
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone();
    assert_eq!(order, ["full", "data"]);
}

/// Counts its wakes, checking each comes with the domain's slot lock free.
struct CountWakes {
    domain: std::sync::Weak<Domain>,
    wakes: std::sync::atomic::AtomicUsize,
}

impl PoisonWaker for CountWakes {
    fn poisoned(&self) {
        if let Some(d) = self.domain.upgrade() {
            assert!(d.state.try_lock().is_ok(), "woken under the slot lock");
        }
        let _n = self.wakes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    }
}

/// Every way a domain is poisoned wakes its poison wakers, after the slot
/// lock is released: an explicit poison, a failed flush, a panicking one.
/// A waker forgotten is not woken.
#[test]
fn test_every_poisoning_wakes_the_poison_wakers() {
    type Poisoning = fn(&Domain);
    let ways: [Poisoning; 3] = [
        |d| {
            d.poison(FirstCause {
                op: None,
                raw: None,
            });
        },
        |d| {
            let r = d.barrier(d.ticket(), |_, _| Err(None));
            assert!(matches!(r, Err(Error::DurabilityUnknown { .. })));
        },
        |d| {
            let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                let _r = d.barrier(d.ticket(), |_, _| panic!("the flush panicked"));
            }));
            assert!(r.is_err());
        },
    ];
    for poison in ways {
        let d = Arc::new(Domain::new());
        let w = Arc::new(CountWakes {
            domain: Arc::downgrade(&d),
            wakes: std::sync::atomic::AtomicUsize::new(0),
        });
        let gone = Arc::new(CountWakes {
            domain: Arc::downgrade(&d),
            wakes: std::sync::atomic::AtomicUsize::new(0),
        });
        let _key = d.on_poison(Arc::clone(&w) as Arc<dyn PoisonWaker>);
        let forgotten = d.on_poison(Arc::clone(&gone) as Arc<dyn PoisonWaker>);
        d.forget_poison_waker(forgotten);
        poison(&d);
        assert!(d.poisoned().is_some());
        assert_eq!(w.wakes.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(gone.wakes.load(std::sync::atomic::Ordering::SeqCst), 0);
    }
}

/// Only a commit-class barrier's entry marks the device's commits active
/// (PLANNING R5.4): a background barrier, leading or joining, never does.
#[test]
fn test_only_a_commit_class_barrier_marks_activity() {
    let r: &'static crate::qos::Registry = Box::leak(Box::new(crate::qos::Registry::new()));
    let at = 1_000_000_000;
    let qos = r.join(
        0,
        &crate::qos::Placement::Keyed {
            identity: store_io_core::identity::DeviceIdentity {
                devices: vec![store_io_core::identity::DeviceId::node(
                    store_io_core::identity::DeviceNode::Sim { device: 1 },
                )],
                complete: true,
            },
            members: Vec::new(),
            fs_device: None,
        },
        crate::qos::QosOptions::default(),
        at,
    );
    let d = Domain::with_slots(1).with_activity(Arc::clone(&qos), Arc::new(move || at), None);
    let need = d.ticket();
    assert!(
        d.barrier_classed(need, IoClass::Background, |_, _| Ok(()))
            .is_ok()
    );
    assert!(
        !qos.active(at),
        "a background barrier marked commits active"
    );
    let need = d.ticket();
    assert!(
        d.barrier_classed(need, IoClass::Commit, |_, _| Ok(()))
            .is_ok()
    );
    assert!(qos.active(at));
}

/// A domain whose store is in a device group of its own, auto-tuned or
/// not, its clock a word the test sets.
fn tuning_domain(autotune: bool) -> (Arc<Domain>, Arc<crate::qos::Qos>, Arc<AtomicU64>) {
    let r: &'static crate::qos::Registry = Box::leak(Box::new(crate::qos::Registry::new()));
    let now = Arc::new(AtomicU64::new(1_000));
    let qos = r.join(
        0,
        &crate::qos::Placement::Keyed {
            identity: store_io_core::identity::DeviceIdentity {
                devices: vec![store_io_core::identity::DeviceId::node(
                    store_io_core::identity::DeviceNode::Sim { device: 1 },
                )],
                complete: true,
            },
            members: Vec::new(),
            fs_device: None,
        },
        crate::qos::QosOptions {
            autotune,
            ..crate::qos::QosOptions::default()
        },
        1_000,
    );
    let clock = Arc::clone(&now);
    let d = Domain::with_slots(1).with_activity(
        Arc::clone(&qos),
        Arc::new(move || clock.load(Ordering::SeqCst)),
        None,
    );
    (Arc::new(d), qos, now)
}

/// Auto-tuning's sample of a commit that leads its flush: from its entry
/// (or, through a flush thread, from the batch's earliest arrival) to the
/// flush's completion; none at all with auto-tuning off.
#[test]
fn test_a_commit_leader_is_timed_from_its_entry_to_its_flush() {
    let (d, qos, now) = tuning_domain(true);
    now.store(1_000, Ordering::SeqCst);
    let need = d.ticket();
    let clock = Arc::clone(&now);
    assert!(
        d.barrier_classed(need, IoClass::Commit, |_, _| {
            clock.store(1_250, Ordering::SeqCst);
            Ok(())
        })
        .is_ok()
    );
    // A flush thread's batch: timed from its earliest arrival, 900.
    let need = d.ticket();
    let clock = Arc::clone(&now);
    assert!(
        d.barrier_classed_from(need, IoClass::Commit, Some(900), |_, _| {
            clock.store(1_400, Ordering::SeqCst);
            Ok(())
        })
        .is_ok()
    );
    // A background barrier with no commit waiting: no sample.
    let need = d.ticket();
    assert!(
        d.barrier_classed(need, IoClass::Background, |_, _| Ok(()))
            .is_ok()
    );
    assert_eq!(qos.samples_written(), [250, 500]);
    assert_eq!(d.earliest.load(Ordering::SeqCst), u64::MAX);
    let (off, q, _now) = tuning_domain(false);
    let need = off.ticket();
    assert!(
        off.barrier_classed(need, IoClass::Commit, |_, _| Ok(()))
            .is_ok()
    );
    assert!(q.samples_written().is_empty(), "auto-tuning off: no sample");
}

/// A flush a background barrier leads while a commit waits for it is
/// timed from that commit's entry; the flush before it, issued before the
/// commit arrived, is timed for nobody.
#[test]
fn test_a_background_led_flush_is_timed_from_the_commit_it_covers() {
    let (d, qos, now) = tuning_domain(true);
    let (go, wait_go) = mpsc::channel::<()>();
    let (started, on_start) = mpsc::channel::<()>();
    // Flush 1, a background barrier's, held.
    let first = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let need = d.ticket();
            d.barrier_classed(need, IoClass::Background, |_, _| {
                let _sent = started.send(());
                let _released = wait_go.recv_timeout(3 * LONG);
                Ok(())
            })
        })
    };
    assert_eq!(on_start.recv_timeout(LONG), Ok(()));
    // A background barrier needing flush 2 waits as its designate; its
    // flush completes at 1,000.
    let lead = {
        let (d, clock) = (Arc::clone(&d), Arc::clone(&now));
        std::thread::spawn(move || {
            let need = d.ticket();
            d.barrier_classed(need, IoClass::Background, |_, _| {
                clock.store(1_000, Ordering::SeqCst);
                Ok(())
            })
        })
    };
    until_waiting(&d, 1);
    assert_eq!(d.lock().designate, Some(2));
    // A commit at 300 needing flush 2 waits behind it.
    now.store(300, Ordering::SeqCst);
    let commit = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            let need = d.ticket();
            d.barrier_classed(need, IoClass::Commit, |_, _| Ok(()))
        })
    };
    until_waiting(&d, 2);
    assert_eq!(d.earliest.load(Ordering::SeqCst), 300);
    let _sent = go.send(());
    for h in [first, lead, commit] {
        assert!(matches!(h.join(), Ok(Ok(()))));
    }
    assert_eq!(
        qos.samples_written(),
        [700],
        "flush 2 from the commit's 300 to 1,000"
    );
    assert_eq!(
        d.earliest.load(Ordering::SeqCst),
        u64::MAX,
        "taken by its leader"
    );
}

/// A commit that joins a flush already issued is that flush's: its entry
/// never times a later flush a background barrier leads alone.
#[test]
fn test_a_commit_joining_an_issued_flush_times_no_later_one() {
    let (d, qos, now) = tuning_domain(true);
    let (go, wait_go) = mpsc::channel::<()>();
    let (started, on_start) = mpsc::channel::<()>();
    let need = d.ticket();
    // Flush 1, a background barrier's, held; a commit at 300 needing only
    // flush 1 joins it (no flush to wait for that is not issued).
    let first = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || {
            d.barrier_classed(need, IoClass::Background, |_, _| {
                let _sent = started.send(());
                let _released = wait_go.recv_timeout(3 * LONG);
                Ok(())
            })
        })
    };
    assert_eq!(on_start.recv_timeout(LONG), Ok(()));
    now.store(300, Ordering::SeqCst);
    let joiner = {
        let d = Arc::clone(&d);
        std::thread::spawn(move || d.barrier_classed(need, IoClass::Commit, |_, _| Ok(())))
    };
    until_waiting(&d, 1);
    assert_eq!(d.earliest.load(Ordering::SeqCst), u64::MAX);
    let _sent = go.send(());
    for h in [first, joiner] {
        assert!(matches!(h.join(), Ok(Ok(()))));
    }
    // A background barrier alone on flush 2: nobody's.
    now.store(900, Ordering::SeqCst);
    let need = d.ticket();
    assert!(
        d.barrier_classed(need, IoClass::Background, |_, _| Ok(()))
            .is_ok()
    );
    assert!(
        qos.samples_written().is_empty(),
        "{:?}",
        qos.samples_written()
    );
}