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
//! The armed async drop kills the root through its handle, reaps it, and drains and removes a
//! cgroup leaf before it returns. It waits on the dropping thread whatever the runtime, and warns
//! once if the wait passes 1 s.

use crate::error::ChildFate;
use crate::test_child::Console;
#[cfg(target_os = "linux")]
use crate::test_groups::{tracer_group, Group};
use crate::tokio::child::child_drop_tests::released_blocker;
use crate::tokio::child::Child;

/// A kill-on-drop root that only a kill or a closed stdin ends, in no containment.
fn blocker() -> (Child, crate::tokio::ChildStdin) {
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::null()).expect("set stdout");
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    (child, stdin)
}

/// Names the root for good while the test still holds it unreaped: a pidfd on Linux, the pid on
/// macOS, where nothing else in this process spawns between the drop and the look.
struct Root {
    #[cfg(target_os = "linux")]
    pidfd: std::os::fd::OwnedFd,
    #[cfg(target_os = "macos")]
    pid: u32,
}

impl Root {
    fn of(child: &Child) -> Root {
        let pid = child.pid();
        #[cfg(target_os = "linux")]
        {
            let pid = rustix::process::Pid::from_raw(pid as i32).expect("a positive pid");
            Root {
                pidfd: rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).expect("pidfd_open"),
            }
        }
        #[cfg(target_os = "macos")]
        Root { pid }
    }

    /// Whether the root has been reaped: a non-blocking, non-consuming `waitid` answers `ECHILD`.
    fn reaped(&self) -> bool {
        // SAFETY: an all-zero `siginfo_t` is valid, and `waitid` writes only into it.
        let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
        #[cfg(target_os = "linux")]
        let (idtype, id) = {
            use std::os::fd::AsRawFd as _;
            (libc::P_PIDFD, self.pidfd.as_raw_fd() as libc::id_t)
        };
        #[cfg(target_os = "macos")]
        let (idtype, id) = (libc::P_PID, self.pid as libc::id_t);
        loop {
            // SAFETY: `info` is a valid out-pointer; WNOWAIT consumes nothing.
            let rc = unsafe { libc::waitid(idtype, id, &mut info, libc::WEXITED | libc::WNOHANG | libc::WNOWAIT) };
            if rc == 0 {
                return false;
            }
            let e = std::io::Error::last_os_error();
            match e.raw_os_error() {
                Some(libc::ECHILD) => return true,
                Some(libc::EINTR) => {}
                _ => panic!("waitid on the root: {e}"),
            }
        }
    }
}

/// The root is reaped when the drop returns, and the teardown says it collected the exit. So does
/// the awaited teardown of a failed run-to-completion helper.
///
/// Mutant: no reap.
#[skuld::test]
async fn tokio_armed_drop_reaps_before_returning() {
    {
        let (child, teardown) = released_blocker();
        let root = Root::of(&child);
        drop(child);
        assert!(root.reaped(), "the armed drop must reap the root before it returns");
        teardown.assert_killed();
    }
    {
        let (mut child, teardown) = released_blocker();
        assert_eq!(
            child.tear_down_now(crate::containment::dispatch::TeardownCaller::Drop),
            ChildFate::Reaped
        );
        teardown.assert_killed();
    }
    let (mut child, teardown) = released_blocker();
    let root = Root::of(&child);
    assert_eq!(child.tear_down_awaiting().await, ChildFate::Reaped);
    assert!(
        root.reaped(),
        "the awaited teardown must reap the root before it returns"
    );
    teardown.assert_killed();
}

/// An awaited teardown that cannot watch the root's exit (the reactor refuses the registration)
/// reaps it as the drop does, on this thread, instead of forgetting a killed child that is ours.
///
/// Mutant: a failed watch forgets the root, which is left an unreaped zombie.
#[skuld::test]
async fn an_awaited_teardown_that_cannot_watch_the_exit_reaps_as_the_drop_does() {
    let (mut child, teardown) = released_blocker();
    let root = Root::of(&child);
    let _refused = super::fault::fail_reap_watch();
    assert_eq!(child.tear_down_awaiting().await, ChildFate::Reaped);
    assert!(root.reaped(), "the teardown must reap the root");
    teardown.assert_killed();
}

/// Spawns a blocker on `rt`, drops it there, and says whether the root was reaped by then.
fn dropped_and_reaped_on(rt: &::tokio::runtime::Runtime, local: bool) -> bool {
    let body = async {
        let (child, teardown) = released_blocker();
        let root = Root::of(&child);
        drop(child);
        let reaped = root.reaped();
        teardown.assert_killed();
        reaped
    };
    if local {
        ::tokio::task::LocalSet::new().block_on(rt, body)
    } else {
        rt.block_on(body)
    }
}

/// On a `current_thread` runtime the drop waits in place: tokio has no `block_in_place` there.
///
/// Mutant: an unconditional `block_in_place` (panics on this runtime).
#[skuld::test]
fn tokio_armed_drop_on_a_current_thread_runtime_reaps() {
    let rt = ::tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("current_thread runtime");
    assert!(dropped_and_reaped_on(&rt, false));
}

/// Inside a `LocalSet` on a multi-thread runtime the drop waits in place too: tokio panics in
/// `block_in_place` there, and offers no way to ask first.
///
/// Mutant: `block_in_place` whenever the runtime's flavour is multi-thread.
#[skuld::test]
fn tokio_armed_drop_in_a_local_set_on_a_multi_thread_runtime_reaps() {
    let rt = ::tokio::runtime::Builder::new_multi_thread()
        .worker_threads(1)
        .enable_all()
        .build()
        .expect("multi-thread runtime");
    assert!(dropped_and_reaped_on(&rt, true));
}

/// A contained tree whose member has not exited when the drop's tree kill lands: the drop waits for
/// the leaf to drain, then removes it. The member is the fake leaf's `populated 1`, which only the
/// drop's own drain wait releases (`set_before_drain_block`), so a drop that never waits finds it
/// still there.
///
/// Mutant: `release_without_waiting` on the armed arm (the leaf is left behind with a warn).
#[cfg(target_os = "linux")]
#[skuld::test]
async fn tokio_armed_drop_of_a_tree_with_a_dying_descendant_removes_the_leaf() {
    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    crate::tokio::test_runtime::assert_current_thread();
    let name = "cosca-armed-drop-dying-member";
    let (fake, leaf) = linux::fake_leaf(name, true);
    let events = fake.events.clone();
    let _release = leaf_fault::set_before_drain_block(move || FakeLeaf::set_populated(&events, false));
    let (child, teardown) = released_blocker();
    let (steps, levels) = linux::dropped(linux::contained_by(child, leaf), name);

    assert!(!fake.leaf.exists(), "the drained leaf must be removed: {steps:?}");
    assert_eq!(levels, Vec::<log::Level>::new(), "{steps:?}");
    teardown.assert_killed();
}

/// A root that a foreign tracer holds as a zombie cannot be reaped until the tracer lets go: the
/// drop warns once, naming the pid, and keeps waiting. The tracer lets go only once the drop sleeps
/// in its blocking `waitid`, and the drop then reaps the root.
///
/// Mutants: no warn; warn, then return without reaping.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn tokio_armed_drop_warns_once_when_the_reap_waits_past_1s(#[fixture(tracer_group)] _group: &Group) {
    use crate::test_support::foreign_tracer::{self, await_blocked_or_finished, Holder, REAP};

    crate::log_capture::install();
    let (child, stdin) = foreign_tracer::spawn_tokio_tracee().await;
    let pid = child.pid();
    let root = Root::of(&child);
    let mut tracer = foreign_tracer::spawn_helper(pid);
    let needle = format!("async child {pid}");
    let mark = crate::log_capture::mark();

    // Asserted only after the tracer lets go: a failure inside the scope would join a dropper the
    // tracer still blocks.
    let (holder, warns) = std::thread::scope(|s| {
        let (tid_tx, tid_rx) = std::sync::mpsc::channel();
        let dropper = s.spawn(move || {
            tid_tx
                .send(rustix::thread::gettid().as_raw_nonzero().get())
                .expect("report the tid");
            let _warn = super::fault::warn_slow_teardowns();
            // The hooks are this thread's: released once the drop's kill returned, so a kill that sent
            // nothing fails the assertion below instead of leaving the reap to wait on the root.
            let teardown = crate::child::spawn::fault::release_between_kill_and_wait(stdin);
            drop(child);
            teardown.assert_killed();
        });
        let tid = tid_rx.recv().expect("the dropper's tid");
        let holder = await_blocked_or_finished(tid);
        let warns: Vec<_> = crate::log_capture::records_since(mark, &needle)
            .into_iter()
            .filter(|text| text.contains("still waiting"))
            .collect();
        tracer.send(REAP);
        tracer.expect("reaped");
        dropper.join().expect("the dropper");
        (holder, warns)
    });

    assert_eq!(
        holder,
        Holder::Blocked,
        "the drop returned while the tracer still held the zombie"
    );
    assert_eq!(warns.len(), 1, "one warn before the blocking wait: {warns:?}");
    assert!(root.reaped(), "the drop reaps the root once the tracer lets go");
    assert_eq!(
        crate::log_capture::levels_since(mark, "still waiting"),
        [log::Level::Warn],
        "exactly one warn, at warn"
    );
}

/// An armed drop whose tree kill fails has nothing to bound the drain: it neither waits for it nor
/// says it is waiting, and writes no other `cgroup.kill`, though one after the leaf's first `rmdir`
/// would land. The leaf is left behind, and a warning names it. The writes fail until that `rmdir`; a
/// drain wait that blocks after it releases the member and records it.
///
/// Mutants: the drain is waited for after a failed kill (the drop says it is still waiting); the
/// failed kill is written again, by the drop or by the leaf's own drop, and lands.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn tokio_armed_drop_whose_tree_kill_fails_does_not_wait_for_the_drain() {
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    crate::tokio::test_runtime::assert_current_thread();
    let name = "cosca-armed-drop-failed-tree-kill";
    let (fake, leaf) = linux::fake_leaf(name, true);
    let (child, stdin) = blocker();
    let teardown = crate::child::spawn::fault::record_teardown_reaps();
    let failing = Rc::new(RefCell::new(Some(leaf_fault::fail_kill_writes_releasing_at_wait(
        move || drop(stdin),
    ))));
    let waited = Rc::new(Cell::new(false));
    let release = Rc::new(RefCell::new(None));
    let (path, events) = (fake.leaf.clone(), fake.events.clone());
    let (until_rmdir, armed_at_rmdir) = (Rc::clone(&failing), Rc::clone(&release));
    let (flag, drain_events) = (Rc::clone(&waited), fake.events.clone());
    leaf_fault::set_rmdir_hook(move |_| {
        if let Some(failing) = until_rmdir.borrow_mut().take() {
            drop(failing);
            let (flag, events) = (Rc::clone(&flag), drain_events.clone());
            *armed_at_rmdir.borrow_mut() = Some(leaf_fault::set_before_drain_block(move || {
                flag.set(true);
                FakeLeaf::set_populated(&events, false);
            }));
        }
        FakeLeaf::rmdir(&path, &events)
    });
    let root = Root::of(&child);
    let mark = crate::log_capture::mark();
    let (steps, levels) = linux::dropped(linux::contained_by(child, leaf), name);
    drop(failing.borrow_mut().take());

    assert!(root.reaped(), "the root's own kill landed, so it is reaped: {steps:?}");
    teardown.assert_killed();
    assert!(!waited.get(), "nothing may wait for the drain: {steps:?}");
    assert!(fake.leaf.exists(), "the undrained leaf is left behind: {steps:?}");
    assert_eq!(
        crate::log_capture::levels_since(mark, "still waiting"),
        Vec::<log::Level>::new(),
        "{steps:?}"
    );
    assert!(
        levels.contains(&log::Level::Warn),
        "the leaf left behind is named: {steps:?}"
    );
}

/// A drop whose own tree kill fails after the handle's `kill_tree()` landed still has a kill that
/// bounds the leaf's drain: it waits for the drain and removes the leaf, as the sync `Drop` does,
/// and warns of the failed write.
///
/// Mutant: the failed write alone decides to give the leaf up (the leaf is left behind, undrained).
#[cfg(target_os = "linux")]
#[skuld::test]
async fn tokio_armed_drop_whose_tree_kill_fails_after_a_landed_kill_waits_for_the_drain() {
    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    crate::tokio::test_runtime::assert_current_thread();
    let name = "cosca-armed-drop-failed-write-after-landed-kill";
    let (fake, leaf) = linux::fake_leaf(name, true);
    let events = fake.events.clone();
    // The member leaves only once the drain wait blocks: a drop that gives the leaf up leaves it.
    let _release = leaf_fault::set_before_drain_block(move || FakeLeaf::set_populated(&events, false));
    let (child, teardown) = released_blocker();
    let mut child = linux::contained_by(child, leaf);
    child.kill_tree().expect("the first kill lands");
    assert_eq!(fake.kill_written(), b"1", "the handle's kill landed");
    let _drop_kill_fails = leaf_fault::fail_next_kill_write();
    let mark = crate::log_capture::mark();
    let (steps, _) = linux::dropped(child, name);

    teardown.assert_killed();
    assert!(
        !fake.leaf.exists(),
        "the landed kill bounds the drain, so the leaf is removed: {steps:?}"
    );
    assert_eq!(
        crate::log_capture::levels_since(mark, "contained-tree teardown did not fully succeed"),
        [log::Level::Warn],
        "the drop's failed write is still warned of"
    );
}

/// The awaited teardown of a helper that failed after its spawn, whose tree kill fails, gives the
/// leaf up as the drop does: no second write, no wait for a drain nothing bounds, the leaf left
/// behind and the failed kill warned once. The root's own kill landed, so it is reaped.
///
/// Mutants: the failed kill is written again and lands (the leaf drains and is removed); the drain is
/// awaited anyway.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn an_awaited_teardown_whose_tree_kill_fails_gives_up_the_leaf_without_waiting() {
    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    crate::tokio::test_runtime::assert_current_thread();
    let name = "cosca-awaited-teardown-failed-tree-kill";
    let (fake, leaf) = linux::fake_leaf(name, true);
    let events = fake.events.clone();
    // A drain wait would empty the leaf: a teardown that waits fails the assertions instead of hanging.
    let _release = leaf_fault::set_before_drain_block(move || FakeLeaf::set_populated(&events, false));
    let _tree_kill_fails = leaf_fault::fail_next_kill_write();
    let (child, released) = released_blocker();
    let root = Root::of(&child);
    let mut child = linux::contained_by(child, leaf);
    let mark = crate::log_capture::mark();
    child.tear_down_awaiting().await;
    leaf_fault::take_rmdir_hook();
    released.assert_killed();

    assert!(root.reaped(), "the root's own kill landed, so it is reaped");
    assert_eq!(fake.kill_written(), b"", "the failed kill is not written again");
    assert!(
        fake.leaf.exists(),
        "the leaf the failed kill left running is left behind"
    );
    let warns = crate::log_capture::records_since(mark, "cgroup.kill failed");
    assert_eq!(warns.len(), 1, "the failed kill is warned once: {warns:?}");
}

/// A leaf that has not drained when the drop's warn is due: the drop warns once, naming the root's
/// pid and the leaf, and keeps waiting until the leaf drains, then removes it. The root is reaped
/// before the drop, so the drain's is the only wait.
///
/// Mutants: no warn on the drain; a drop that waits only until the warn is due, then releases the
/// leaf without waiting (the member is never released, and the leaf is left behind).
#[cfg(target_os = "linux")]
#[skuld::test]
async fn tokio_armed_drop_warns_once_when_the_drain_is_slow() {
    use super::child_drop_tests::linux;

    crate::tokio::test_runtime::assert_current_thread();
    let name = "cosca-armed-drop-slow-drain";
    let child = reaped_blocker().await;
    let (fake, leaf) = linux::fake_leaf(name, true);
    let needle = format!("async child {}", child.pid());
    let mark = crate::log_capture::mark();
    let (warned_at_release, release) = release_from_the_blocking_wait(&fake, name, needle, mark);
    let _warn = super::fault::warn_slow_teardowns_after(std::time::Duration::ZERO);
    let (steps, _) = linux::dropped(linux::contained_by(child, leaf), name);
    drop(release.borrow_mut().take());

    assert_eq!(
        warned_at_release.get(),
        Some(1),
        "the drop must wait for the drain past its warn, with one warn naming the leaf by then: {steps:?}"
    );
    assert!(!fake.leaf.exists(), "the drained leaf is removed: {steps:?}");
    assert_eq!(
        crate::log_capture::levels_since(mark, "still waiting"),
        [log::Level::Warn],
        "exactly one warn"
    );
}

/// A run-to-completion helper that fails after its spawn awaits its teardown instead of blocking
/// the runtime thread: on a `current_thread` runtime another task runs while the teardown waits for
/// the leaf to drain, and it is that task that releases the leaf's member. The task is woken by the
/// drain wait about to block. A teardown that blocks reaches the leaf's own `rmdir` with the member
/// still there, and the `rmdir` releases it instead.
///
/// Mutant: the helper tears the child down as `Drop` does (`tear_down_now`), blocking the thread.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_run_to_completion_helper_awaits_its_teardown() {
    use std::cell::Cell;
    use std::rc::Rc;

    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let rt = ::tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("current_thread runtime");
    let name = "cosca-awaited-teardown";
    let (fake, leaf) = linux::fake_leaf(name, true);
    let released_by = Rc::new(Cell::new(None));
    let (path, events, by) = (fake.leaf.clone(), fake.events.clone(), Rc::clone(&released_by));
    leaf_fault::set_rmdir_hook(move |_| {
        if by.get().is_none() {
            by.set(Some("the leaf's rmdir"));
            FakeLeaf::set_populated(&events, false);
        }
        FakeLeaf::rmdir(&path, &events)
    });
    let (blocking_tx, blocking_rx) = ::tokio::sync::oneshot::channel();
    // Unsent only if the other task is gone, and then nothing releases the member but the `rmdir`.
    let _wake = leaf_fault::set_before_drain_block(move || {
        _ = blocking_tx.send(());
    });
    let (events, by) = (fake.events.clone(), Rc::clone(&released_by));
    let other_task = async move {
        if blocking_rx.await.is_ok() && by.get().is_none() {
            by.set(Some("another task"));
            FakeLeaf::set_populated(&events, false);
        }
    };
    let (error, teardown) = rt.block_on(async {
        let (child, teardown) = released_blocker();
        let mut child = linux::contained_by(child, leaf);
        let failed =
            crate::tokio::command::after_the_spawn(crate::error::Error::Io(std::io::Error::other("pump")), &mut child);
        (::tokio::join!(failed, other_task).0, teardown)
    });
    leaf_fault::take_rmdir_hook();
    teardown.assert_killed();

    assert_eq!(
        released_by.get(),
        Some("another task"),
        "the runtime must run another task while the teardown waits"
    );
    assert!(!fake.leaf.exists(), "the drained leaf is removed");
    match error {
        crate::error::Error::MayHaveStarted { fate, .. } => assert_eq!(fate, ChildFate::Reaped),
        other => panic!("expected MayHaveStarted, got {other:?}"),
    }
}

/// A helper's teardown dropped while it awaits the reap finishes as the drop would, on the dropping
/// thread: it reaps the root, emits the drop's report (here, of the tree kill that failed), and
/// gives up the leaf the failed kill left running, without a second write or a wait for its drain.
/// The teardown really was awaiting the reap when it was dropped.
///
/// Mutants: the dropped teardown leaves what it holds to the fields' own drops (no report); the
/// teardown reaps by blocking, as the drop does (it never reaches the awaited reap); the failed
/// kill is written again.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_dropped_awaited_teardown_finishes_as_the_drop_would() {
    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let rt = ::tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("current_thread runtime");
    let name = "cosca-dropped-awaited-teardown";
    let (fake, leaf) = linux::fake_leaf(name, true);
    let events = fake.events.clone();
    let _release = leaf_fault::set_before_drain_block(move || FakeLeaf::set_populated(&events, false));
    let _tree_kill_fails = leaf_fault::fail_next_kill_write();
    let pending = super::fault::pend_awaited_reap();
    let mark = crate::log_capture::mark();
    let (root, released) = rt.block_on(async {
        let (child, released) = released_blocker();
        let root = Root::of(&child);
        let mut child = linux::contained_by(child, leaf);
        let mut teardown = std::pin::pin!(child.tear_down_awaiting());
        ::tokio::select! {
            biased;
            _ = &mut teardown => panic!("the awaited reap never completes"),
            () = std::future::ready(()) => {}
        }
        (root, released)
    });
    leaf_fault::take_rmdir_hook();
    released.assert_killed();

    assert!(pending.taken(), "the teardown must have been awaiting the reap");
    assert_eq!(
        crate::log_capture::levels_since(mark, "contained-tree teardown did not fully succeed"),
        [log::Level::Warn],
        "the dropped teardown must still emit the drop's report"
    );
    assert!(root.reaped(), "the dropped teardown must reap the root");
    assert_eq!(fake.kill_written(), b"", "the failed kill is not written again");
    assert!(
        fake.leaf.exists(),
        "the leaf the failed kill left running is left behind"
    );
    let warns = crate::log_capture::records_since(mark, "cgroup.kill failed");
    assert_eq!(warns.len(), 1, "the failed kill is warned once: {warns:?}");
}

/// A helper's teardown dropped while it awaits the drain leaves the leaf to a wait on the dropping
/// thread, as the drop does, with the drop's one warn once that wait is slow.
///
/// Mutant: the dropped teardown leaves the leaf to its own drop, which blocks with no warn.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_teardown_dropped_during_the_drain_warns_once() {
    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;

    let rt = ::tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("current_thread runtime");
    let name = "cosca-teardown-dropped-in-drain";
    let (fake, leaf) = linux::fake_leaf(name, true);
    let mark = crate::log_capture::mark();
    let _warn = super::fault::warn_slow_teardowns_after(std::time::Duration::ZERO);
    let (draining_tx, draining_rx) = ::tokio::sync::oneshot::channel();
    // The awaited drain is about to wait: the test drops the teardown then.
    let _draining = leaf_fault::set_before_drain_block(move || {
        _ = draining_tx.send(());
    });
    let (fate, warned_at_release, release, killed) = rt.block_on(async {
        let (child, killed) = released_blocker();
        let needle = format!("async child {}", child.pid());
        let (warned_at_release, release) = release_from_the_blocking_wait(&fake, name, needle, mark);
        let mut child = linux::contained_by(child, leaf);
        let teardown = child.tear_down_awaiting();
        let fate = ::tokio::select! {
            biased;
            fate = teardown => Some(fate),
            _ = draining_rx => None,
        };
        (fate, warned_at_release, release, killed)
    });
    leaf_fault::take_rmdir_hook();
    drop(release.borrow_mut().take());
    killed.assert_killed();

    assert_eq!(fate, None, "the teardown must still be awaiting the drain");
    assert_eq!(
        warned_at_release.get(),
        Some(1),
        "the dropped teardown must wait for the drain past its warn, with one warn naming the leaf by then"
    );
    assert!(!fake.leaf.exists(), "the drained leaf is removed");
    assert_eq!(
        crate::log_capture::levels_since(mark, "still waiting"),
        [log::Level::Warn],
        "exactly one warn"
    );
}

/// A helper's teardown whose drain cannot be watched hands the leaf to a wait on this thread, as
/// the drop does, with the drop's one warn once that wait is slow.
///
/// Mutant: a failed drain watch is ignored and the leaf is dropped at once, so its own drop blocks
/// with no warn.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_teardown_whose_drain_watch_fails_warns_once() {
    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;

    let rt = ::tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("current_thread runtime");
    let name = "cosca-teardown-drain-watch-fails";
    let (fake, leaf) = linux::fake_leaf(name, true);
    let mark = crate::log_capture::mark();
    let _warn = super::fault::warn_slow_teardowns_after(std::time::Duration::ZERO);
    let _watch_fails = super::fault::fail_drain_watch();
    let (fate, warned_at_release, release, killed) = rt.block_on(async {
        let (child, killed) = released_blocker();
        let needle = format!("async child {}", child.pid());
        let (warned_at_release, release) = release_from_the_blocking_wait(&fake, name, needle, mark);
        let mut child = linux::contained_by(child, leaf);
        (child.tear_down_awaiting().await, warned_at_release, release, killed)
    });
    leaf_fault::take_rmdir_hook();
    drop(release.borrow_mut().take());
    killed.assert_killed();

    assert_eq!(fate, ChildFate::Reaped);
    assert_eq!(
        warned_at_release.get(),
        Some(1),
        "the teardown must wait for the drain past its warn, with one warn naming the leaf by then"
    );
    assert!(!fake.leaf.exists(), "the drained leaf is removed");
    assert_eq!(
        crate::log_capture::levels_since(mark, "still waiting"),
        [log::Level::Warn],
        "exactly one warn"
    );
}

/// A blocker whose root has exited and been reaped: an armed drop of it waits only for the drain.
#[cfg(target_os = "linux")]
async fn reaped_blocker() -> Child {
    let (mut child, stdin) = blocker();
    drop(stdin);
    child.wait().await.expect("the blocker exits once its stdin closes");
    child
}

/// The fake leaf's member is released only from a drain wait that blocks after the leaf's first
/// `rmdir`, so after any look that decides a warn. The release records how many warns naming
/// `needle` and the leaf `name` were out by then. Answers that record, and the release's guard, to
/// drop once the teardown is over.
#[cfg(target_os = "linux")]
#[allow(clippy::type_complexity, reason = "a test helper's two shared cells")]
fn release_from_the_blocking_wait(
    fake: &crate::containment::cgroup::test_support::FakeLeaf,
    name: &'static str,
    needle: String,
    mark: usize,
) -> (
    std::rc::Rc<std::cell::Cell<Option<usize>>>,
    std::rc::Rc<std::cell::RefCell<Option<crate::oneshot_hook::Armed>>>,
) {
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    use crate::containment::cgroup::fault as leaf_fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let warned_at_release = Rc::new(Cell::new(None));
    let release: Rc<RefCell<Option<crate::oneshot_hook::Armed>>> = Rc::default();
    let (path, events) = (fake.leaf.clone(), fake.events.clone());
    let (seen, armed) = (Rc::clone(&warned_at_release), Rc::clone(&release));
    leaf_fault::set_rmdir_hook(move |_| {
        if armed.borrow().is_none() {
            let (seen, events, needle) = (Rc::clone(&seen), events.clone(), needle.clone());
            *armed.borrow_mut() = Some(leaf_fault::set_before_drain_block(move || {
                let warns = crate::log_capture::records_since(mark, &needle)
                    .into_iter()
                    .filter(|text| text.contains("still waiting") && text.contains(name))
                    .count();
                seen.set(Some(warns));
                FakeLeaf::set_populated(&events, false);
            }));
        }
        FakeLeaf::rmdir(&path, &events)
    });
    (warned_at_release, release)
}

/// An armed drop whose leaf's drain pump cannot start (a thread limit) still warns once its drain
/// wait passes the threshold, and still waits for the drain: the wait that blocks decides the warn.
///
/// Mutant: the warn is decided by a look through the pump, whose failure skips it.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn tokio_armed_drop_whose_drain_pump_cannot_start_warns_once() {
    use super::child_drop_tests::linux;
    use crate::containment::cgroup::fault as leaf_fault;

    crate::tokio::test_runtime::assert_current_thread();
    let name = "cosca-armed-drop-pump-refused";
    let child = reaped_blocker().await;
    let (fake, leaf) = linux::fake_leaf(name, true);
    let needle = format!("async child {}", child.pid());
    let mark = crate::log_capture::mark();
    let (warned_at_release, release) = release_from_the_blocking_wait(&fake, name, needle, mark);
    let _warn = super::fault::warn_slow_teardowns_after(std::time::Duration::ZERO);
    let _no_pump = leaf_fault::fail_pump_starts();
    let (steps, _) = linux::dropped(linux::contained_by(child, leaf), name);
    drop(release.borrow_mut().take());

    assert_eq!(
        warned_at_release.get(),
        Some(1),
        "one warn naming the leaf, out before its member was released: {steps:?}"
    );
    assert!(!fake.leaf.exists(), "the drained leaf is removed: {steps:?}");
}

/// macOS: a root whose exit the drop's look does not see by the threshold gets the drop's one warn,
/// naming its pid, and the drop then waits for it and reaps it. A test here can have no foreign
/// tracer, so the threshold is zero and the look's two peeks are forced to find the root running.
///
/// Mutant: the drop's reap has no warn.
#[cfg(target_os = "macos")]
#[skuld::test]
async fn macos_tokio_armed_drop_warns_once_when_the_reap_is_slow() {
    use std::cell::RefCell;
    use std::rc::Rc;

    use crate::os_process::child::PeekOutcome;
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks, Forced};

    crate::log_capture::install();
    let (child, _stdin) = blocker();
    let pid = child.pid();
    let root = Root::of(&child);
    let mark = crate::log_capture::mark();
    let forced: Rc<RefCell<Option<Forced>>> = Rc::default();
    let _look = super::fault::set_before_reap_look({
        let forced = Rc::clone(&forced);
        move || *forced.borrow_mut() = Some(force_peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Running)]))
    });
    let _warn = super::fault::warn_slow_teardowns_after(std::time::Duration::ZERO);
    drop(child);
    assert_peeks_exhausted();
    drop(forced.borrow_mut().take());

    let warns: Vec<_> = crate::log_capture::records_since(mark, &format!("async child {pid}"))
        .into_iter()
        .filter(|text| text.contains("still waiting"))
        .collect();
    assert_eq!(warns.len(), 1, "one warn, and the wait goes on: {warns:?}");
    assert!(root.reaped(), "the drop reaps the root past its warn");
}

/// A test warns about a slow teardown only with a guard (a verdict must not depend on elapsed time),
/// and `warn_slow_teardowns` sets the threshold production uses, 1 s; another guard sets its own.
///
/// Mutants: a test without a guard gets a threshold; the production threshold is not 1 s.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_test_warns_past_the_production_threshold_only_with_a_guard() {
    assert_eq!(super::slow_teardown_after(), None);
    {
        let _production = super::fault::warn_slow_teardowns();
        assert_eq!(super::slow_teardown_after(), Some(std::time::Duration::from_secs(1)));
    }
    {
        let _zero = super::fault::warn_slow_teardowns_after(std::time::Duration::ZERO);
        assert_eq!(super::slow_teardown_after(), Some(std::time::Duration::ZERO));
    }
    assert_eq!(super::slow_teardown_after(), None);
}