cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
use super::{
    ceil_millis, clears_tokio_timer_margin, deadline_at, deadline_from, instant_near_ceiling, read_probe, rearm_until,
    remaining, remaining_override_seam, test_clock, wait_clamp_seam, wait_ms_probe, win32_timeout_ms,
    TOKIO_TIMER_ROUNDING_MARGIN,
};
use std::time::{Duration, Instant};

#[skuld::test]
fn remaining_unbounded_is_none() {
    assert_eq!(remaining(None), None);
}

#[skuld::test]
fn remaining_past_deadline_saturates_to_zero() {
    let past = Instant::now().checked_sub(Duration::from_secs(1)).unwrap();
    assert_eq!(remaining(Some(past)), Some(Duration::ZERO));
}

/// A deadline within tokio's own ~1ms round-up margin of `Instant`'s ceiling must saturate to
/// unbounded, not reach a primitive whose own margin arithmetic overflows on it.
#[skuld::test]
fn deadline_from_saturates_when_the_result_is_too_close_to_instants_ceiling() {
    let now = Instant::now();
    // 500µs short of the true ceiling (found from `now`): comfortably more than the time this
    // test takes to reach `deadline_from`'s own `Instant::now()` call, so that call's own
    // `checked_add` still succeeds — landing well within the 1ms margin this exercises, not
    // overflowing outright before ever reaching it.
    let duration = instant_near_ceiling(now).saturating_duration_since(now) - Duration::from_micros(500);
    assert_eq!(deadline_from(duration), None);
}

/// Pins `remaining`'s ZERO boundary exactly, via the frozen test clock rather than a real one:
/// 250ms remaining a full 250ms before the deadline, exactly ZERO at the deadline itself (never
/// early), and still (just barely) above zero one nanosecond before it.
#[skuld::test]
fn remaining_pins_the_exact_zero_boundary() {
    let (_guard, t0) = test_clock::FrozenClockGuard::install();
    let at = t0 + Duration::from_millis(250);
    let deadline = Some(at);

    assert_eq!(remaining(deadline), Some(Duration::from_millis(250)));
    test_clock::advance(Duration::from_millis(250) - Duration::from_nanos(1));
    assert_eq!(remaining(deadline), Some(Duration::from_nanos(1)));
    test_clock::advance(Duration::from_nanos(1));
    assert_eq!(remaining(deadline), Some(Duration::ZERO));
}

// `ceil_millis`/`win32_timeout_ms` tests: pure and portable.

/// Mutant: `d.as_millis()` instead of ceiling -> 500us floors to 0.
#[skuld::test]
fn ceil_millis_rounds_up_sub_millisecond_remainders() {
    assert_eq!(ceil_millis(Duration::from_nanos(1)), 1);
    assert_eq!(ceil_millis(Duration::from_micros(500)), 1);
    assert_eq!(ceil_millis(Duration::from_micros(999)), 1);
    assert_eq!(ceil_millis(Duration::from_micros(1500)), 2);
    assert_eq!(ceil_millis(Duration::from_micros(2001)), 3);
}

/// A zero remainder stays a poll, not a wait.
///
/// Mutant: round zero up to 1 -> fails.
#[skuld::test]
fn ceil_millis_zero_stays_zero() {
    assert_eq!(ceil_millis(Duration::ZERO), 0);
}

/// Mutant: add a millisecond of slack -> whole milliseconds grow.
#[skuld::test]
fn ceil_millis_whole_milliseconds_are_unchanged() {
    assert_eq!(ceil_millis(Duration::from_millis(1)), 1);
    assert_eq!(ceil_millis(Duration::from_millis(7)), 7);
    assert_eq!(ceil_millis(Duration::from_secs(3)), 3_000);
}

/// Mutant: map `None` to a finite value -> an unbounded wait gets a deadline.
#[skuld::test]
fn win32_timeout_ms_unbounded_is_the_win32_infinite_sentinel() {
    assert_eq!(win32_timeout_ms(None), u32::MAX);
}

/// Mutant: truncate instead of ceiling -> 500us arms 0.
#[skuld::test]
fn win32_timeout_ms_ceils_rather_than_truncates() {
    assert_eq!(win32_timeout_ms(Some(Duration::from_micros(500))), 1);
    assert_eq!(win32_timeout_ms(Some(Duration::ZERO)), 0);
    assert_eq!(win32_timeout_ms(Some(Duration::from_millis(7))), 7);
}

/// A finite remainder never arms `INFINITE`, even at exactly `u32::MAX` ms.
///
/// Mutant: drop the clamp -> `u32::MAX` (the sentinel) instead of `u32::MAX - 1`.
#[skuld::test]
fn win32_timeout_ms_never_returns_the_infinite_sentinel_for_a_finite_remaining() {
    let ms = win32_timeout_ms(Some(Duration::from_millis(u64::from(u32::MAX))));
    assert_ne!(ms, u32::MAX);
    assert_eq!(ms, u32::MAX - 1);
}

/// Mutant: ignore the clamp seam -> the 1s remainder arms 1000, not 5.
#[skuld::test]
fn win32_timeout_ms_honors_the_clamp_seam() {
    let guard = wait_clamp_seam::set(5);
    assert_eq!(win32_timeout_ms(Some(Duration::from_secs(1))), 5);
    drop(guard);
    assert_eq!(win32_timeout_ms(Some(Duration::from_millis(3))), 3);
}

/// The override applies to exactly one call.
///
/// Mutant: leave the override armed after `take` -> the second call sees 3, not 999.
#[skuld::test]
fn remaining_override_seam_is_consumed_exactly_once() {
    let guard = remaining_override_seam::set(Duration::from_millis(3));
    assert_eq!(win32_timeout_ms(Some(Duration::from_millis(999))), 3);
    assert_eq!(win32_timeout_ms(Some(Duration::from_millis(999))), 999);
    drop(guard);
}

/// An unconsumed override does not outlive its guard.
///
/// Mutant: make the guard's `Drop` a no-op -> the stale 3 leaks into the next call.
#[skuld::test]
fn remaining_override_seam_guard_clears_an_unconsumed_override_on_drop() {
    let guard = remaining_override_seam::set(Duration::from_millis(3));
    drop(guard);
    assert_eq!(win32_timeout_ms(Some(Duration::from_millis(999))), 999);
}

/// The probe pairs what a site asked for with what was armed.
///
/// Mutant: record the overridden duration as `requested` -> `requested` is 3ms, not 999ms.
#[skuld::test]
fn wait_ms_probe_records_the_requested_remaining_beside_the_armed_one() {
    wait_ms_probe::take();
    let _override = remaining_override_seam::set(Duration::from_millis(3));
    win32_timeout_ms(Some(Duration::from_millis(999)));
    let arms = wait_ms_probe::take();
    assert_eq!(arms.len(), 1);
    assert_eq!(arms[0].ms, 3);
    assert_eq!(arms[0].remaining, Duration::from_millis(3));
    assert_eq!(arms[0].requested, Duration::from_millis(999));
}

/// `ceiling - MARGIN` clears (adding the margin lands ON
/// the ceiling, representable); one nanosecond later does not.
#[skuld::test]
fn deadline_at_passes_through_up_to_the_margin_and_is_unbounded_past_it() {
    let now = Instant::now();
    let ceiling = instant_near_ceiling(now);
    let span = ceiling.saturating_duration_since(now);

    let edge = span - TOKIO_TIMER_ROUNDING_MARGIN;
    assert_eq!(deadline_at(now, edge), Some(now + edge));
    assert_eq!(deadline_at(now, edge + Duration::from_nanos(1)), None);
    assert_eq!(deadline_at(now, span), None);
    assert_eq!(
        deadline_at(now, span + Duration::from_nanos(1)),
        None,
        "overflow itself"
    );
    assert_eq!(deadline_at(now, Duration::MAX), None);
    assert_eq!(deadline_at(now, Duration::ZERO), Some(now));
    assert_eq!(
        deadline_at(now, Duration::from_secs(1)),
        Some(now + Duration::from_secs(1))
    );
}

#[skuld::test]
fn clears_tokio_timer_margin_is_true_exactly_up_to_the_margin() {
    let ceiling = instant_near_ceiling(Instant::now());
    assert!(clears_tokio_timer_margin(ceiling - TOKIO_TIMER_ROUNDING_MARGIN));
    assert!(!clears_tokio_timer_margin(
        ceiling - TOKIO_TIMER_ROUNDING_MARGIN + Duration::from_nanos(1)
    ));
}

/// `deadline_from` is `deadline_at` on the frozen clock.
#[skuld::test]
fn deadline_from_applies_deadline_at_on_the_test_clock() {
    let (_guard, t0) = test_clock::FrozenClockGuard::install();
    let span = instant_near_ceiling(t0).saturating_duration_since(t0);
    let edge = span - TOKIO_TIMER_ROUNDING_MARGIN;

    assert_eq!(deadline_from(edge), Some(t0 + edge));
    assert_eq!(deadline_from(edge + Duration::from_nanos(1)), None);
    assert_eq!(deadline_from(Duration::MAX), None);
}

// rearm_until =====

/// Each round after a real wait sees a frozen clock that has moved on, so a finite deadline ends.
///
/// Mutant: drop the `advance_by_elapsed_if_frozen` call -> the second round sees the same instant.
#[skuld::test]
fn rearm_until_advances_the_frozen_clock_by_each_round() {
    let (_clock, at) = test_clock::FrozenClockGuard::install();
    let deadline = Some(at + Duration::from_millis(30));
    let mut previous: Option<Instant> = None;
    let out = rearm_until(deadline, |remaining| {
        let seen = super::now();
        if let Some(previous) = previous {
            assert!(seen > previous, "the frozen clock did not advance across a real wait");
        }
        previous = Some(seen);
        std::thread::park_timeout(remaining.expect("finite deadline"));
        Ok::<Option<()>, ()>(None)
    });
    assert_eq!(out, Ok(None));
}

/// Every round is armed with the frozen remaining, even when real time is ahead of the frozen
/// clock.
///
/// Mutant: derive the round's remaining from the real clock.
#[skuld::test]
fn rearm_until_hands_a_round_the_frozen_remaining() {
    let (_clock, at) = test_clock::FrozenClockGuard::install_lagging(Duration::from_secs(1));
    let deadline = Some(at + Duration::from_millis(50));
    let mut seen = None;
    let out = rearm_until(deadline, |remaining| {
        seen = Some(remaining);
        Ok::<_, ()>(Some(()))
    });
    assert_eq!(out, Ok(Some(())));
    assert_eq!(seen, Some(Some(Duration::from_millis(50))));
}

/// A deadline already past still runs one round, armed with zero, and reports its `None`.
///
/// Mutant: check `remaining` before the first round.
#[skuld::test]
fn rearm_until_polls_once_for_a_past_deadline() {
    let past = Instant::now().checked_sub(Duration::from_secs(1)).unwrap();
    let mut rounds = Vec::new();
    let out = rearm_until(Some(past), |remaining| {
        rounds.push(remaining);
        Ok::<Option<()>, ()>(None)
    });
    assert_eq!(out, Ok(None));
    assert_eq!(rounds, [Some(Duration::ZERO)]);
}

/// A round's error ends the loop at once, wherever in the loop it arrives.
///
/// Mutant: treat `Err` as `None` -> the third round runs and reports `Some`.
#[skuld::test]
fn rearm_until_stops_at_a_round_error() {
    let (_clock, at) = test_clock::FrozenClockGuard::install();
    let deadline = Some(at + Duration::from_secs(3600));
    let mut rounds = 0;
    let out = rearm_until(deadline, |_| {
        rounds += 1;
        match rounds {
            1 => Ok(None),
            2 => Err("boom"),
            _ => Ok(Some(())),
        }
    });
    assert_eq!(out, Err("boom"));
    assert_eq!(rounds, 2);
}

/// A probe records each `remaining` read with the deadline it was made against and its result,
/// interleaved in order with the marks a call site drops.
///
/// Mutant: skip `record` in `remaining_at` -> the log is empty.
#[skuld::test]
fn read_probe_records_reads_and_marks_in_order() {
    let (tx, rx) = std::sync::mpsc::channel();
    let (_clock, at) = test_clock::FrozenClockGuard::install();
    let deadline = Some(at + Duration::from_secs(5));
    let guard = read_probe::install(tx);
    read_probe::mark("before");
    remaining(deadline);
    remaining(None);
    drop(guard);
    let want = [
        read_probe::Event::Mark("before"),
        read_probe::Event::Read {
            deadline,
            remaining: Some(Duration::from_secs(5)),
        },
        read_probe::Event::Read {
            deadline: None,
            remaining: None,
        },
    ];
    assert_eq!(rx.try_iter().collect::<Vec<_>>(), want);
}

/// A probe does not outlive its guard, including when the guard is dropped by an unwind.
///
/// Mutant: make the guard's `Drop` a no-op -> the read after the panic is still recorded.
#[skuld::test]
fn read_probe_guard_uninstalls_on_drop_even_when_unwinding() {
    let (tx, rx) = std::sync::mpsc::channel();
    let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _guard = read_probe::install(tx);
        panic!("unwind with the probe installed");
    }));
    assert!(unwound.is_err());
    remaining(None);
    read_probe::mark("after");
    assert_eq!(rx.try_iter().count(), 0);
    assert!(read_probe::current().is_none());
}

/// A probe is per thread: another thread's reads are invisible until that thread installs the
/// handle [`read_probe::current`] hands out, which is how a `spawn_blocking` closure joins one.
///
/// Mutant: make `current` return `None` -> the installed thread's read goes unrecorded.
#[skuld::test]
fn read_probe_reaches_another_thread_only_through_current() {
    let (tx, rx) = std::sync::mpsc::channel();
    let _guard = read_probe::install(tx);
    std::thread::scope(|s| {
        s.spawn(|| remaining(None));
    });
    assert_eq!(rx.try_iter().count(), 0, "an uninstalled thread must not record");
    let carried = read_probe::current().expect("installed on this thread");
    std::thread::scope(|s| {
        s.spawn(move || {
            let _guard = read_probe::install(carried);
            remaining(None);
        });
    });
    assert_eq!(
        rx.try_iter().count(),
        1,
        "the installed thread records into the same log"
    );
}

// RoundCheck =====

/// Two rounds with no advance between them, under a frozen clock, are a stalled re-arm.
///
/// Mutant: drop the check in `RoundCheck::round` -> no panic.
#[skuld::test]
#[should_panic(expected = "no progress")]
fn round_check_panics_on_two_rounds_without_an_advance() {
    let (_clock, _at) = test_clock::FrozenClockGuard::install();
    let mut check = test_clock::RoundCheck::new("test");
    check.round();
    check.round();
}

/// An advance call between rounds is progress even when it advanced by zero.
///
/// Mutant: bump the generation only for a nonzero elapsed -> panics here.
#[skuld::test]
fn round_check_accepts_an_advance_of_zero_between_rounds() {
    let (_clock, _at) = test_clock::FrozenClockGuard::install();
    let mut check = test_clock::RoundCheck::new("test");
    check.round();
    test_clock::advance_by_elapsed_if_frozen(Duration::ZERO);
    check.round();
    test_clock::advance_by_elapsed_if_frozen(Duration::ZERO);
    check.round();
}

/// Two invocations share nothing: with no advance between the first's last round and the
/// second's first round, the second must not be judged against the first.
///
/// Mutant: compare against a thread-local last generation instead of the invocation's own ->
/// panics here.
#[skuld::test]
fn round_check_state_is_per_invocation() {
    let (_clock, _at) = test_clock::FrozenClockGuard::install();
    let mut first = test_clock::RoundCheck::new("first");
    first.round();
    let mut second = test_clock::RoundCheck::new("second");
    second.round();
}

/// `SkipAdvanceGuard` stops the advance while it lives and only then.
///
/// Mutant: make the guard's `Drop` a no-op -> the advance after the drop is still skipped.
#[skuld::test]
fn skip_advance_guard_resets_on_drop() {
    let (_clock, at) = test_clock::FrozenClockGuard::install();
    let skip = test_clock::SkipAdvanceGuard::install();
    test_clock::advance_by_elapsed_if_frozen(Duration::from_millis(10));
    assert_eq!(test_clock::now(), at, "the advance is skipped while the guard lives");
    drop(skip);
    test_clock::advance_by_elapsed_if_frozen(Duration::from_millis(10));
    assert_eq!(test_clock::now(), at + Duration::from_millis(10));
}

/// `ZeroElapsedGuard` pins the measured elapsed to zero while it lives and only then.
///
/// Mutant: make the guard's `Drop` a no-op -> the advance after the drop is still zero.
#[skuld::test]
fn zero_elapsed_guard_resets_on_drop() {
    let (_clock, at) = test_clock::FrozenClockGuard::install();
    let zero = test_clock::ZeroElapsedGuard::install();
    test_clock::advance_by_elapsed_if_frozen(Duration::from_millis(10));
    assert_eq!(
        test_clock::now(),
        at,
        "the elapsed is pinned to zero while the guard lives"
    );
    drop(zero);
    test_clock::advance_by_elapsed_if_frozen(Duration::from_millis(10));
    assert_eq!(test_clock::now(), at + Duration::from_millis(10));
}

/// Only the immediately previous round is compared: an advance before round two does not excuse
/// round three.
///
/// Mutant: compare against the first round's generation -> no panic.
#[skuld::test]
#[should_panic(expected = "no progress")]
fn round_check_compares_against_the_previous_round_only() {
    let (_clock, _at) = test_clock::FrozenClockGuard::install();
    let mut check = test_clock::RoundCheck::new("test");
    check.round();
    test_clock::advance_by_elapsed_if_frozen(Duration::ZERO);
    check.round();
    check.round();
}

/// An unfrozen clock advances on its own, so rounds without an advance are fine; and the clock is
/// unfrozen once its guard drops.
///
/// Mutant: ignore `is_frozen` -> panics here.
#[skuld::test]
fn round_check_ignores_an_unfrozen_clock() {
    {
        let (_clock, _at) = test_clock::FrozenClockGuard::install();
        assert!(test_clock::is_frozen());
    }
    assert!(!test_clock::is_frozen());
    let mut check = test_clock::RoundCheck::new("test");
    check.round();
    check.round();
}

/// Two whole waits under one frozen guard each run to completion through `rearm_until`. The
/// per-invocation state of the check itself is pinned by
/// `round_check_state_is_per_invocation`, which this end-to-end path cannot reach: every
/// `rearm_until` round is followed by an advance.
#[skuld::test]
fn two_sequential_waits_with_the_same_remaining_do_not_trip_the_check() {
    let (_clock, _at) = test_clock::FrozenClockGuard::install();
    // Unbounded: no `remaining` is needed here, and a finite deadline would let a preempted
    // round run it out and end the wait early.
    for _ in 0..2 {
        let mut rounds = 0;
        let out = rearm_until(None, |_| {
            rounds += 1;
            Ok::<_, ()>((rounds == 2).then_some(()))
        });
        assert_eq!(out, Ok(Some(())));
        assert_eq!(rounds, 2);
    }
}

/// The probe holds no progress state: repeated remainings, with or without a `take()` between,
/// are not its concern.
///
/// Mutant: make `wait_ms_probe::record` panic on a repeated remaining -> panics here.
#[skuld::test]
fn wait_ms_probe_does_not_judge_progress() {
    let (_clock, _at) = test_clock::FrozenClockGuard::install();
    wait_ms_probe::take();
    let r = Duration::from_millis(7);
    wait_ms_probe::record(7, r, r);
    wait_ms_probe::record(7, r, r);
    wait_ms_probe::take();
    wait_ms_probe::record(7, r, r);
    wait_ms_probe::take();
}

/// A remaining injected by the override seam, and a round that took no clock ticks, are not a
/// stalled loop: the loop advanced. The zero-elapsed seam forces every round's measured elapsed
/// to zero, so the frozen clock stays put and no deadline can be reached however long a round is
/// preempted.
///
/// Mutant: judge progress by the `remaining` values (equal `Some` remainings in consecutive
/// rounds are no progress) -> the zero-elapsed rounds repeat the same remaining and panic.
#[skuld::test]
fn the_override_seam_and_a_zero_elapsed_round_do_not_trip_the_check() {
    let (_clock, at) = test_clock::FrozenClockGuard::install();
    let _zero = test_clock::ZeroElapsedGuard::install();
    let deadline = Some(at + Duration::from_millis(5));
    let _override = remaining_override_seam::set(Duration::from_micros(500));
    wait_ms_probe::take();
    let mut seen = Vec::new();
    let mut rounds = 0;
    let out = rearm_until(deadline, |remaining| {
        seen.push(remaining);
        win32_timeout_ms(remaining);
        rounds += 1;
        Ok::<_, ()>((rounds == 3).then_some(()))
    });
    assert_eq!(out, Ok(Some(())));
    assert_eq!(
        test_clock::now(),
        at,
        "a zero-elapsed round leaves the frozen clock where it was"
    );
    assert_eq!(
        seen,
        vec![Some(Duration::from_millis(5)); 3],
        "the rounds saw the same remaining, and still made progress"
    );
    wait_ms_probe::take();
}

/// `rearm_until` with its advance dropped fails at the second round.
///
/// Mutant: drop the `advance_by_elapsed_if_frozen` call in `rearm_until` -> same panic, without
/// the seam. Mutant: drop `rearm_until`'s `check.round()` -> the second round runs and fails the
/// test with a different message, instead of the loop spinning forever.
#[skuld::test]
#[should_panic(expected = "no progress")]
fn rearm_until_panics_when_its_advance_is_dropped() {
    let (_clock, at) = test_clock::FrozenClockGuard::install();
    let _skip = test_clock::SkipAdvanceGuard::install();
    let deadline = Some(at + Duration::from_secs(3600));
    let mut rounds = 0;
    rearm_until(deadline, |_| {
        rounds += 1;
        assert!(rounds < 2, "the check let a second round run");
        Ok::<Option<()>, ()>(None)
    })
    .ok();
}

/// `wait_until` with its frozen-clock advance dropped fails at the second round.
///
/// Mutant: drop the `advance_by_elapsed_if_frozen` call in `rearm_until` -> same panic, without
/// the seam. Mutant: drop `rearm_until`'s `check.round()` -> the second round fails the test with
/// a different message, instead of the loop spinning forever.
#[cfg(windows)]
#[skuld::test]
#[should_panic(expected = "no progress")]
fn wait_until_panics_when_its_advance_is_dropped() {
    use windows::Win32::Foundation::WAIT_TIMEOUT;

    let (_clock, at) = test_clock::FrozenClockGuard::install();
    let _skip = test_clock::SkipAdvanceGuard::install();
    let deadline = Some(at + Duration::from_secs(3600));
    let mut waits = 0;
    super::wait_until(deadline, |_ms| {
        waits += 1;
        assert!(waits < 2, "the check let a second round run");
        WAIT_TIMEOUT
    });
}

/// The env var that arms [`fixture_round_check_violation_while_panicking`].
const ROUND_CHECK_ABORT_MARKER: &str = "COSCA_FIXTURE_ROUND_CHECK_ABORT";

/// The child half of [`round_check_exits_when_it_fires_while_panicking`]: inert in an ordinary
/// suite run. Stalls a [`test_clock::RoundCheck`] in a `Drop` that runs while its own panic
/// unwinds.
#[skuld::test]
fn fixture_round_check_violation_while_panicking() {
    struct StalledInDrop;
    impl Drop for StalledInDrop {
        fn drop(&mut self) {
            let mut check = test_clock::RoundCheck::new("drop path");
            check.round();
            check.round();
        }
    }
    if !crate::test_child::is_marked_fixture_reexec(ROUND_CHECK_ABORT_MARKER) {
        return; // picked up by an ordinary suite run: deliberately inert
    }
    let (_clock, _at) = test_clock::FrozenClockGuard::install();
    let _stalled = StalledInDrop;
    panic!("the fixture's own failure");
}

/// A violation found while the thread is already panicking (a Drop path) cannot panic again, and
/// must not be stored where nothing reads it or a spin could go on: it ends the process with the
/// message on stderr and `VIOLATION_EXIT_CODE`, and no crash report.
///
/// Mutant: store the violation and return -> the child exits with the test's own failure (101).
/// Mutant: panic regardless of `thread::panicking()` -> the double panic aborts, and the exit
/// code differs whatever the environment.
#[skuld::test]
fn round_check_exits_when_it_fires_while_panicking() {
    let output = crate::test_child::run_fixture_output(
        crate::test_child::fixture_path!(fixture_round_check_violation_while_panicking),
        ROUND_CHECK_ABORT_MARKER,
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains(crate::test_child::FIXTURE_GATE_PASSED_LINE),
        "the fixture never passed its gate, so nothing ran:\n{stderr}"
    );
    assert!(
        !matches!(output.status.code(), Some(0 | 101)),
        "the exit code must differ from a pass and from libtest's failure: {:?}\n{stderr}",
        output.status
    );
    assert_eq!(
        output.status.code(),
        Some(test_clock::VIOLATION_EXIT_CODE),
        "the process must exit with the violation code, not abort or fail as a test: {:?}\n{stderr}",
        output.status
    );
    assert!(
        stderr.contains("drop path") && stderr.contains("no progress"),
        "the exit names its site and cause on stderr:\n{stderr}"
    );
}

#[cfg(target_os = "linux")]
mod pidfd_exit_visible {
    use std::os::fd::AsFd as _;
    use std::time::{Duration, Instant};

    use super::super::{pidfd_exit_visible_by, PidfdExit};
    use crate::test_groups::{tracer_group, Group};
    use crate::test_support::foreign_tracer::{self, EXIT};

    fn blocker() -> std::process::Child {
        let mut cmd = crate::test_child::held_std_blocker(std::process::Stdio::null());
        foreign_tracer::allow_any_tracer(&mut cmd);
        crate::test_spawn::spawn(&mut cmd).expect("spawn the blocker")
    }

    /// Mutant: answer `true` for a running child, or `false` for a zombie; or return before the
    /// deadline.
    #[skuld::test]
    fn pidfd_exit_visible_by_is_true_for_a_zombie_and_false_at_the_deadline_for_a_running_child() {
        let mut child = blocker();
        let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
        let until = Instant::now() + Duration::from_millis(30);
        assert!(!pidfd_exit_visible_by(pidfd.as_fd(), until));
        assert!(
            Instant::now() >= until,
            "a running child is reported before the deadline"
        );
        child.kill().expect("kill");
        crate::test_child::wait_until_zombie(child.id());
        let far = Instant::now() + Duration::from_secs(3600);
        assert!(pidfd_exit_visible_by(pidfd.as_fd(), far));
        child.wait().expect("reap");
    }

    /// A pidfd poll that fails is not an answer: the peeks decide until the deadline, so a running
    /// child is still `false` at it, and no block is armed. Runs in a re-exec'd process with
    /// `RLIMIT_NOFILE` at 0, which makes the kernel refuse every `poll(2)` with `EINVAL`.
    ///
    /// Mutant: answer `true` at once after a failed poll; or look at the child with a block again.
    #[skuld::test]
    fn a_failed_poll_leaves_the_peek_to_decide_until_the_deadline() {
        crate::test_child::run_fixture(crate::test_child::fixture_path!(
            fixture_a_failed_poll_leaves_the_peek_to_decide
        ));
    }

    #[skuld::test]
    fn fixture_a_failed_poll_leaves_the_peek_to_decide() {
        if !crate::test_child::is_fixture_reexec() {
            return;
        }
        let mut child = blocker();
        let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
        let mut before = libc::rlimit {
            rlim_cur: 0,
            rlim_max: 0,
        };
        // SAFETY: `before` is a valid out-pointer.
        assert_eq!(unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut before) }, 0);
        let none = libc::rlimit {
            rlim_cur: 0,
            rlim_max: before.rlim_max,
        };
        // SAFETY: lowers this fixture process's own soft limit; it is put back below.
        assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &none) }, 0);
        assert!(
            crate::os_process::poll::is_readable(pidfd.as_fd()).is_err(),
            "the precondition: poll fails"
        );
        // Assert via the on_blocking hook: the probe record also holds recheck pauses.
        let blocking = crate::wait::block_probe::on_blocking(|| panic!("a block after a failed poll"));
        let until = Instant::now() + Duration::from_millis(30);
        assert!(!pidfd_exit_visible_by(pidfd.as_fd(), until));
        assert!(Instant::now() >= until, "reported before the deadline");
        drop(blocking);
        // SAFETY: puts back the limit read above.
        assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &before) }, 0);
        child.kill().expect("kill");
        crate::test_child::wait_until_zombie(child.id());
        let far = Instant::now() + Duration::from_secs(3600);
        assert!(pidfd_exit_visible_by(pidfd.as_fd(), far));
        child.wait().expect("reap");
    }

    /// A child someone else reaped is visible at once, even past the deadline: the look is the one
    /// the deadline cannot cut short.
    ///
    /// Mutant: a foreign reap is read as a running child (the look rechecks and answers `false`).
    #[skuld::test]
    fn a_child_reaped_by_someone_else_is_visible_at_once() {
        let mut child = blocker();
        let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
        child.kill().expect("kill");
        child.wait().expect("reap");
        assert!(pidfd_exit_visible_by(pidfd.as_fd(), Instant::now()));
    }

    /// A peek that fails is left to the wait that follows, so the answer is `true` at once, even
    /// past the deadline, for a child that runs.
    ///
    /// Mutant: a failed peek is read as a running child (the look rechecks and answers `false`).
    #[skuld::test]
    fn a_peek_that_fails_is_visible_at_once() {
        use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peek_once};

        let mut child = blocker();
        let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
        let forced = force_peek_once(Err(std::io::Error::other("forced peek failure")));
        assert!(pidfd_exit_visible_by(pidfd.as_fd(), Instant::now()));
        assert_peeks_exhausted();
        drop(forced);
        child.kill().expect("kill");
        child.wait().expect("reap");
    }

    /// A zombie a foreign tracer holds turns the pidfd readable and shows no exit to a peek: it is
    /// not visible until the tracer lets go, and the peek is repeated until then.
    ///
    /// Mutant: a readable pidfd is taken as the exit; a peek that finds nothing ends the look; or the
    /// look blocks on the readable pidfd, which returns at once, instead of pausing.
    #[skuld::test]
    fn a_zombie_a_tracer_holds_is_visible_only_once_the_tracer_lets_go(#[fixture(tracer_group)] _group: &Group) {
        use crate::os_process::drive::{Step, Waitable as _};

        let mut child = blocker();
        let pidfd = crate::containment::cgroup::test_support::pidfd_of(child.id());
        let mut tracer = foreign_tracer::spawn_helper(child.id());
        child.kill().expect("kill");
        assert!(
            crate::os_process::poll::poll_readable(pidfd.as_fd(), None).expect("poll"),
            "the pidfd turns readable at the zombie"
        );
        assert!(
            matches!(PidfdExit::new(pidfd.as_fd()).look().expect("look"), Step::Recheck),
            "a readable pidfd with no visible exit is looked at again, not blocked on"
        );
        let until = Instant::now() + Duration::from_millis(30);
        assert!(
            !pidfd_exit_visible_by(pidfd.as_fd(), until),
            "the tracer still holds it"
        );
        assert!(Instant::now() >= until, "reported before the deadline");
        tracer.send(EXIT);
        tracer.finish();
        let far = Instant::now() + Duration::from_secs(3600);
        assert!(pidfd_exit_visible_by(pidfd.as_fd(), far), "the tracer let go");
        child.wait().expect("reap");
    }
}

// `any_ready_now` and `poll_ready` =====

#[cfg(unix)]
mod poll {
    use std::io::Write as _;

    use rustix::event::{PollFd, PollFlags};
    use rustix::io::Errno;

    use crate::test_own_process::{own_process, test_path};
    use crate::wait::{any_ready_now, poll_ready};

    /// More descriptors than any `poll(2)` takes: Linux's limit is `RLIMIT_NOFILE`, lowered by
    /// [`lower_the_descriptor_limit`], macOS's is `OPEN_MAX` (10240).
    const OVERSIZE: usize = 10_241;

    /// Process-wide: only a test that runs in a process of its own may call it.
    fn lower_the_descriptor_limit() {
        let limit = libc::rlimit {
            rlim_cur: 16,
            rlim_max: 16,
        };
        // SAFETY: lowers this process's own descriptor limit; the pointer is to a live local.
        let set = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) };
        assert_eq!(set, 0, "lower RLIMIT_NOFILE");
    }

    /// Mutant: `Ok(ready) => return Ok(false)`.
    #[skuld::test]
    fn any_ready_now_is_true_for_a_readable_descriptor() {
        let (rx, mut tx) = std::io::pipe().unwrap();
        tx.write_all(&[1]).unwrap();
        let mut fds = [PollFd::new(&rx, PollFlags::IN)];
        assert_eq!(any_ready_now(&mut fds), Ok(true));
        assert!(
            fds[0].revents().contains(PollFlags::IN),
            "the events found are in the slice"
        );
    }

    /// Mutant: `Ok(ready) => return Ok(ready >= 0)` or `Ok(true)`.
    #[skuld::test]
    fn any_ready_now_is_false_when_nothing_is_ready() {
        let (rx, _tx) = std::io::pipe().unwrap();
        let mut fds = [PollFd::new(&rx, PollFlags::IN)];
        assert_eq!(any_ready_now(&mut fds), Ok(false));
        assert!(fds[0].revents().is_empty());
    }

    /// A failed poll is an error, never "nothing ready".
    ///
    /// Mutant: `Err(e) => return Err(e)` becomes `Err(_) => return Ok(false)`.
    #[skuld::test]
    fn any_ready_now_reports_a_failed_poll_as_an_error() {
        let Some(_done) = own_process(
            test_path!(any_ready_now_reports_a_failed_poll_as_an_error),
            crate::test_spawn::spawn,
        ) else {
            return;
        };
        let (rx, _tx) = std::io::pipe().unwrap();
        let mut fds: Vec<_> = (0..OVERSIZE).map(|_| PollFd::new(&rx, PollFlags::IN)).collect();
        lower_the_descriptor_limit();
        assert_eq!(any_ready_now(&mut fds), Err(Errno::INVAL));
    }

    /// Mutant: `Ok(_) => return Ok(())` becomes `Ok(_) => continue`, which blocks for good here.
    #[skuld::test]
    fn poll_ready_returns_once_a_descriptor_is_ready() {
        let (rx, mut tx) = std::io::pipe().unwrap();
        tx.write_all(&[1]).unwrap();
        let mut fds = [PollFd::new(&rx, PollFlags::IN)];
        assert_eq!(poll_ready(&mut fds), Ok(()));
        assert!(
            fds[0].revents().contains(PollFlags::IN),
            "the events found are in the slice"
        );
    }

    /// A failed poll is an error, not a return that looks like readiness.
    ///
    /// Mutant: `Err(e) => return Err(e)` becomes `Err(_) => return Ok(())`.
    #[skuld::test]
    fn poll_ready_reports_a_failed_poll_as_an_error() {
        let Some(_done) = own_process(
            test_path!(poll_ready_reports_a_failed_poll_as_an_error),
            crate::test_spawn::spawn,
        ) else {
            return;
        };
        let (rx, _tx) = std::io::pipe().unwrap();
        let mut fds: Vec<_> = (0..OVERSIZE).map(|_| PollFd::new(&rx, PollFlags::IN)).collect();
        lower_the_descriptor_limit();
        assert_eq!(poll_ready(&mut fds), Err(Errno::INVAL));
    }

    /// A signal that lands while `poll_ready` is blocked in `poll(2)` interrupts it, and it blocks
    /// again: it returns only once the descriptor is ready. The polling thread is signalled only
    /// after the kernel shows it inside the poll, so the signal cannot land before or after it.
    /// Runs in a process of its own: a signal's disposition is process-wide.
    ///
    /// Mutant: `Err(Errno::INTR) => continue` is dropped, so the `EINTR` is returned.
    #[cfg(target_os = "linux")]
    #[skuld::test]
    fn poll_ready_retries_an_interrupted_poll() {
        use std::os::unix::thread::JoinHandleExt as _;
        use std::sync::atomic::{AtomicUsize, Ordering};

        use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};

        static HANDLED: AtomicUsize = AtomicUsize::new(0);
        extern "C" fn count(_: libc::c_int) {
            HANDLED.fetch_add(1, Ordering::SeqCst);
        }

        // Whether thread `tid` is blocked in `poll(2)` or `ppoll(2)`, as the kernel reports it.
        fn blocked_in_poll(tid: u32) -> bool {
            let path = format!("/proc/self/task/{tid}/syscall");
            let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
            let Some(Ok(number)) = text.split_whitespace().next().map(str::parse::<libc::c_long>) else {
                return false; // `running`
            };
            #[cfg(target_arch = "x86_64")]
            let polls = [libc::SYS_poll, libc::SYS_ppoll];
            #[cfg(not(target_arch = "x86_64"))]
            let polls = [libc::SYS_ppoll];
            polls.contains(&number)
        }

        let Some(_done) = own_process(
            test_path!(poll_ready_retries_an_interrupted_poll),
            crate::test_spawn::spawn,
        ) else {
            return;
        };
        // No `SA_RESTART`: the interrupted `poll` reports `EINTR`.
        let action = SigAction::new(SigHandler::Handler(count), SaFlags::empty(), SigSet::empty());
        // SAFETY: `count` only touches an atomic, so it is async-signal-safe.
        unsafe { sigaction(Signal::SIGUSR2, &action) }.expect("install the handler");

        let (rx, mut tx) = std::io::pipe().unwrap();
        let (tid_tx, tid_rx) = std::sync::mpsc::channel();
        let poller = std::thread::spawn(move || {
            tid_tx
                .send(rustix::thread::gettid().as_raw_nonzero().get() as u32)
                .unwrap();
            poll_ready(&mut [PollFd::new(&rx, PollFlags::IN)])
        });
        let tid = tid_rx.recv().unwrap();
        while !blocked_in_poll(tid) {
            std::thread::yield_now();
        }
        // SAFETY: the thread is still running, so its `pthread_t` is valid.
        let sent = unsafe { libc::pthread_kill(poller.as_pthread_t(), libc::SIGUSR2) };
        assert_eq!(sent, 0, "signal the polling thread");
        while HANDLED.load(Ordering::SeqCst) == 0 {
            std::thread::yield_now();
        }
        tx.write_all(&[1]).unwrap();
        assert_eq!(
            poller.join().unwrap(),
            Ok(()),
            "the interrupted poll was retried, not returned"
        );
    }
}