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
//! `Drop`'s two branches that release the backend in place, without the reaper pool: a detached
//! handle, and an armed one whose kill was refused. Evidence of a foreign reap must stop tokio's
//! field-drop from reaping the child by pid, or it would reap whichever process took the pid.
//!
//! The evidence is forced: the peek through the child's handle answers `Foreign`. The child really
//! is an unreaped zombie, so a reap by pid that should not have run consumes the record the test
//! then finds gone.

use crate::os_process::child::{Foreign, PeekOutcome};
use crate::test_child::Console;
use crate::wait::exit_only::seams::{force_peek_once, force_peeks};

/// Watches one child from outside cosca and reaps it on the test's behalf.
struct Witness {
    #[cfg(target_os = "macos")]
    pid: u32,
    #[cfg(target_os = "linux")]
    pidfd: std::os::fd::OwnedFd,
}

impl Witness {
    /// `SIGKILL` through the pidfd (Linux), or by the pid of a child nothing else reaps (macOS).
    fn kill(&self) {
        #[cfg(target_os = "linux")]
        {
            use std::os::fd::AsFd;
            rustix::process::pidfd_send_signal(self.pidfd.as_fd(), rustix::process::Signal::KILL).expect("kill");
        }
        #[cfg(target_os = "macos")]
        // SAFETY: `pid` is this test's own child, which nothing reaps while the test runs.
        assert_eq!(unsafe { libc::kill(self.pid as libc::pid_t, libc::SIGKILL) }, 0);
    }

    fn new(pid: u32) -> Witness {
        Witness {
            #[cfg(target_os = "macos")]
            pid,
            #[cfg(target_os = "linux")]
            pidfd: rustix::process::pidfd_open(
                rustix::process::Pid::from_raw(pid as i32).expect("pid"),
                rustix::process::PidfdFlags::empty(),
            )
            .expect("pidfd_open"),
        }
    }

    /// Blocks until the child has exited, without consuming it.
    fn wait_exited(&self) {
        #[cfg(target_os = "linux")]
        {
            use std::os::fd::AsFd;
            let fd = self.pidfd.as_fd();
            let mut fds = [rustix::event::PollFd::new(&fd, rustix::event::PollFlags::IN)];
            crate::wait::poll_ready(&mut fds).expect("poll(pidfd)");
        }
        #[cfg(target_os = "macos")]
        {
            // SAFETY: an all-zero `siginfo_t` is valid, and `waitid` writes only into it.
            let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
            // SAFETY: waits for our own child's exit without consuming it.
            let rc = unsafe {
                libc::waitid(
                    libc::P_PID,
                    self.pid as libc::id_t,
                    &mut info,
                    libc::WEXITED | libc::WNOWAIT,
                )
            };
            assert_eq!(rc, 0, "waitid: {}", std::io::Error::last_os_error());
        }
    }

    /// Consumes the child's exit record. `Err` if something else already did.
    fn reap(&self) -> Result<(), std::io::Error> {
        #[cfg(target_os = "linux")]
        {
            use std::os::fd::AsFd;
            let record = rustix::process::waitid(
                rustix::process::WaitId::PidFd(self.pidfd.as_fd()),
                rustix::process::WaitIdOptions::EXITED,
            )?;
            assert!(record.is_some(), "an exited child has a record");
            Ok(())
        }
        #[cfg(target_os = "macos")]
        {
            let mut status = 0;
            // SAFETY: reaps this process's own exited child.
            let reaped = unsafe { libc::waitpid(self.pid as libc::pid_t, &mut status, 0) };
            if reaped == self.pid as libc::pid_t {
                Ok(())
            } else {
                Err(std::io::Error::last_os_error())
            }
        }
    }
}

/// A child that has exited and is not reaped, and the witness of it.
fn exited_unreaped(kill_on_drop: bool) -> (crate::tokio::Child, Witness) {
    let (stdin, writer) = crate::test_child::held_writer_stdin();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("set stdin");
    cmd.kill_on_drop(kill_on_drop);
    let child = cmd.spawn().expect("spawn");
    let witness = Witness::new(child.pid());
    drop(writer);
    witness.wait_exited();
    (child, witness)
}

/// Makes the next peek through the child's handle see a foreign reap.
fn force_evidence() -> impl Sized {
    force_peek_once(Ok(PeekOutcome::Foreign(Foreign::Gone)))
}

/// Mutant: no forget in the bypass branches. tokio's in-drop `try_wait` then reaps the zombie, and
/// the test's own reap gets `ECHILD`.
#[skuld::test]
async fn tokio_bypass_drop_of_a_detached_child_after_a_foreign_reap_reaps_nothing() {
    let (mut child, witness) = exited_unreaped(true);
    child.detach().expect("detach");
    let _evidence = force_evidence();
    drop(child);
    witness.reap().expect("the drop must not have reaped the child by pid");
}

/// The failed-kill early return: the drop's first look misses the reap, its kill is refused, and
/// the look inside that branch sees it, so the drop forgets tokio's `Child` instead of `try_wait`ing
/// it by pid. The looks are forced in sequence: `Running`, then `Foreign`.
///
/// Mutants: no forget in the refused-kill branch (the zombie is reaped by pid: `ECHILD`); the
/// `is_reaped` check dropped there (a false "left running" warning).
#[skuld::test]
async fn tokio_bypass_drop_after_a_refused_kill_and_a_foreign_reap_reaps_nothing() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let (child, witness) = exited_unreaped(true);
    let _looks = force_peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Gone))]);
    let _refused = super::fault::force_kill_failure();
    let kills = super::drop_fault::record();

    drop(child);

    assert_eq!(kills.kills(), 1, "the drop reached its refused root kill");
    assert!(
        !crate::log_capture::contains_since(mark, "could not be terminated on drop"),
        "a forgotten child must not be reported as left running"
    );
    witness.reap().expect("the drop must not have reaped the child by pid");
}

/// `reap_now`'s refused-kill arm must not hand tokio's drop a child that is not shown ours: it
/// forgets it instead. A forced failure, a refused kill and forced evidence, for a child that
/// exited after the identity check. `evidence` arms the evidence inside the hook, where the
/// handshake's and the identity check's own peeks are done.
///
/// The forced failure is the attach's, except on macOS, where the attach cannot fail and the
/// identity check's (which finds the child gone before it peeks) reaches the same `reap_now`.
///
/// `torn_down`: the child is not shown gone, and Linux's pidfd pins it, so it is torn down through
/// the pidfd as well. Otherwise it is forgotten and nothing is done to it.
fn reap_now_after_a_refused_kill(evidence: fn() -> Box<dyn std::any::Any>, torn_down: bool) {
    use std::cell::RefCell;
    use std::rc::Rc;

    use crate::child::spawn::fault;

    let slot: Rc<RefCell<Option<Witness>>> = Rc::default();
    let armed: Rc<RefCell<Option<Box<dyn std::any::Any>>>> = Rc::default();
    let (point, force): (fault::SpawnPoint, fn(bool)) = if cfg!(target_os = "macos") {
        (fault::SpawnPoint::BeforeIdentity, fault::set_force_identity_vanished)
    } else {
        (fault::SpawnPoint::BeforeAttach, fault::set_force_attach_failure)
    };
    let _hook = fault::set_at(point, {
        let slot = Rc::clone(&slot);
        let armed = Rc::clone(&armed);
        move || {
            let witness = Witness::new(fault::spawn_pid());
            witness.wait_exited();
            // Armed here, not before `spawn()`: the handshake's own watch peek and the identity
            // check's run first and would consume it.
            *armed.borrow_mut() = Some(evidence());
            *slot.borrow_mut() = Some(witness);
        }
    });
    force(true);
    fault::set_force_kill_failure_leaving_child_alive_as("reap_now refused", std::io::ErrorKind::PermissionDenied);
    let reaps = fault::record_teardown_reaps();
    let backend_drops = super::fault::count_backend_drops();
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::stdio::Stdio::null()).expect("stdin");

    let err = cmd.spawn().err();

    force(false);
    drop(armed);
    assert!(err.is_some(), "the forced failure fails the spawn");
    assert!(
        crate::log_capture::contains_since(mark, "reap_now refused); the child "),
        "the warning must say why the forgotten child was forgotten, straight after the refused kill"
    );
    // The refused kill and the forget are one event: one warn, which carries the leak.
    let warns = crate::log_capture::warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("leaks"), "{warns:?}");
    assert_eq!(backend_drops.get(), 0, "tokio's Child must have been forgotten");
    let witness = slot.borrow_mut().take().expect("the hook ran");
    if torn_down {
        assert!(
            warns[0].contains("teardown of child"),
            "the warn carries the second teardown's clause: {warns:?}"
        );
        assert_eq!(
            reaps.recorded().len(),
            1,
            "the child was torn down through its pidfd: {:?}",
            reaps.recorded()
        );
        assert!(
            witness.reap().is_err(),
            "the teardown reaped the child through its pidfd"
        );
        return;
    }
    // A child shown gone gets no second teardown: no clause of one in the warn, and no reap recorded.
    assert!(
        !warns[0].contains("teardown of child"),
        "the warn carries no second teardown's clause: {warns:?}"
    );
    assert!(
        reaps.recorded().is_empty(),
        "nothing was torn down through its pidfd, so nothing was reaped by a teardown"
    );
    witness
        .reap()
        .expect("reap_now's refused-kill arm must not reap the child by pid");
}

/// Evidence that the child was reaped elsewhere.
///
/// Mutant: no forget in `reap_now`'s refused-kill arm (tokio's drop reaps the zombie by pid).
#[skuld::test]
async fn reap_now_after_a_refused_kill_and_a_foreign_reap_reaps_nothing() {
    reap_now_after_a_refused_kill(
        || Box::new(force_peek_once(Ok(PeekOutcome::Foreign(Foreign::Gone)))),
        false,
    );
}

/// A failed look cannot show the child is ours, so the arm forgets it too; on Linux the pidfd still
/// pins the child, so it is torn down through it, as a child forgotten earlier is.
///
/// Mutants: a failed look counts as ours; on Linux a child forgotten in this call is left running.
#[skuld::test]
async fn reap_now_after_a_refused_kill_and_a_failed_look_forgets_the_child() {
    reap_now_after_a_refused_kill(
        || Box::new(force_peek_once(Err(std::io::Error::other("forced peek failure 6e2a")))),
        cfg!(target_os = "linux"),
    );
}

/// `try_wait` and `wait` on a child shown reaped elsewhere answer `ECHILD` and take nothing: tokio's
/// own are `waitpid`s by pid.
///
/// Mutants: `ProcSource::try_wait` or `wait` go to tokio without looking at the handle.
#[skuld::test]
async fn try_wait_after_a_foreign_reap_takes_nothing() {
    let (mut child, witness) = exited_unreaped(false);
    let _evidence = force_evidence();
    let err = child.try_wait().expect_err("a foreign-reaped child has no status");
    assert!(
        matches!(&err, crate::error::Error::Io(e) if e.raw_os_error() == Some(libc::ECHILD)),
        "{err:?}"
    );
    witness.reap().expect("try_wait must not have reaped the child by pid");
}

#[skuld::test]
async fn wait_after_a_foreign_reap_takes_nothing() {
    let (mut child, witness) = exited_unreaped(false);
    let _evidence = force_evidence();
    let err = child.wait().await.expect_err("a foreign-reaped child has no status");
    assert!(
        matches!(&err, crate::error::Error::Io(e) if e.raw_os_error() == Some(libc::ECHILD)),
        "{err:?}"
    );
    witness.reap().expect("wait must not have reaped the child by pid");
}

/// `try_wait` and `wait` on a child the handle cannot answer for (a failed look) say so with
/// `Unassessable`, not `ECHILD`: the child may be running. Nothing is reaped, and the child is not
/// forgotten, so a later call can still answer.
///
/// Mutants: the answer is `ECHILD`; the child is forgotten.
#[skuld::test]
async fn try_wait_and_wait_on_a_child_that_cannot_be_verified_say_so() {
    let (mut child, witness) = exited_unreaped(false);
    let backend_drops = super::fault::count_backend_drops();
    for use_wait in [false, true] {
        let _failed = force_peek_once(Err(std::io::Error::other("forced peek failure 8c4f")));
        let err = if use_wait {
            child.wait().await.map(Some)
        } else {
            child.try_wait()
        }
        .expect_err("an unverifiable child has no status to give");
        assert!(
            matches!(&err, crate::error::Error::Unassessable { detail, .. } if detail.contains("cannot be shown to be ours")),
            "{use_wait}: {err:?}"
        );
        assert!(
            !child.os.proc.as_ref().expect("backend").is_reaped(),
            "{use_wait}: not forgotten"
        );
    }
    witness.reap().expect("neither call may reap the child by pid");
    drop(backend_drops);
}

/// `finish_elevated`'s refused-kill arm forgets a child shown reaped elsewhere (`forget_if_foreign`,
/// as `Drop`'s and `reap_now`'s refused-kill arms do) before its `try_wait`, a `waitpid` by pid.
/// The looks are forced in sequence: `finish_elevated`'s first look sees `Running`, the look inside
/// the refused-kill arm sees `Foreign`.
#[skuld::test]
async fn finish_elevated_after_a_refused_kill_and_a_foreign_reap_reaps_nothing() {
    let (child, witness) = exited_unreaped(true);
    let _evidence = force_peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Gone))]);
    let _refused = super::fault::force_kill_failure();
    let err = crate::tokio::spawn::finish_elevated(
        child,
        Err(crate::error::Error::Io(std::io::Error::other("no password"))),
    )
    .expect_err("the password write failed")
    .expect_may_have_started_with();
    let (err, fate) = err;
    assert!(matches!(err, crate::error::Error::Elevation { .. }), "{err:?}");
    // The look found it reaped elsewhere: it is not running, and not reaped by cosca.
    assert_eq!(fate, crate::error::ChildFate::Gone);
    witness
        .reap()
        .expect("finish_elevated's refused-kill arm must not reap the child by pid");
}

/// A contained root reaped elsewhere: `Drop`'s tree teardown warns that it skips the group kill. A
/// logger that panics there unwinds out of the drop with tokio's `Child` held; the backend's own
/// drop must forget it, since its handle shows the root reaped, rather than hand it to tokio's
/// by-pid reap.
#[skuld::test]
async fn a_panicking_logger_in_the_tree_teardown_warn_does_not_reap_the_child_by_pid() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (stdin, writer) = crate::test_child::held_writer_stdin();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("set stdin");
    cmd.contain_with(crate::ContainMode::Session);
    let child = cmd.spawn().expect("spawn");
    let witness = Witness::new(child.pid());
    drop(writer);
    witness.wait_exited();
    witness
        .reap()
        .expect("the child is ours to reap: this is the foreign reap");
    let backend_drops = super::fault::count_backend_drops();
    let unwound = {
        let _panics = crate::log_capture::panic_on("the root is already reaped, so this drop does not");
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(child)))
    };
    assert!(unwound.is_err(), "the logger must have panicked out of the drop");
    assert_eq!(
        backend_drops.get(),
        0,
        "tokio's Child must have been forgotten, not dropped into a by-pid reap"
    );
}

/// A live child of ours, armed drop, kill refused (EPERM-like). `signal_on_drop` peeks (`Running`:
/// ours), `try_wait`s, then warns "could not be terminated on drop". A logger that panics there
/// unwinds out of `Drop` before it releases the backend, and the backend's own drop must still hand
/// a child its handle shows ours to tokio's drop and its orphan queue.
#[skuld::test]
async fn a_panicking_refused_kill_warn_in_drop_does_not_strand_or_reap_by_pid() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (stdin, writer) = crate::test_child::held_writer_stdin();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("set stdin");
    cmd.kill_on_drop(true);
    let child = cmd.spawn().expect("spawn");
    let witness = Witness::new(child.pid());
    let _refused = super::fault::force_kill_failure();
    let drops = super::fault::count_backend_drops();
    let unwound = {
        let _panics = crate::log_capture::panic_on("could not be terminated on drop");
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(child)))
    };
    assert!(unwound.is_err(), "the logger must have panicked out of the drop");
    let released = drops.get();
    // Clean up regardless: end the child and reap it ourselves.
    drop(writer);
    witness.wait_exited();
    let reaped_by_us = witness.reap().is_ok();
    assert_eq!(
        released, 1,
        "a child shown ours must reach tokio's drop (reaped_by_us={reaped_by_us})"
    );
}

/// As above, but stdin is a pipe that was never taken. The unwind must close this
/// process's end of it, or a child reading stdin to EOF never exits. The end is recorded by its
/// descriptor, which stays closed in this single-threaded test.
#[skuld::test]
async fn an_unwind_out_of_drop_closes_the_untaken_stdin_pipe() {
    crate::tokio::test_runtime::assert_current_thread();
    use std::os::fd::AsRawFd;
    crate::log_capture::install();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::stdio::Stdio::pipe_in()).expect("set stdin");
    cmd.kill_on_drop(true);
    let child = cmd.spawn().expect("spawn");
    let witness = Witness::new(child.pid());
    let Some(crate::pipe::ParentEnd::Writer(stdin)) = child.os.pipes.get(&crate::stdio::Fd::STDIN) else {
        panic!("piped stdin");
    };
    let fd = stdin.as_raw_fd();
    let is_open = || {
        // SAFETY: `fcntl(F_GETFD)` reads a flag and changes nothing.
        unsafe { libc::fcntl(fd, libc::F_GETFD) != -1 }
    };
    assert!(is_open(), "before: this process holds the write end");
    let _refused = super::fault::force_kill_failure();
    let unwound = {
        let _panics = crate::log_capture::panic_on("could not be terminated on drop");
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(child)))
    };
    assert!(unwound.is_err(), "the logger must have panicked out of the drop");
    let still_open = is_open();
    // The child is ours and, on macOS, was forgotten: end it and reap it.
    witness.kill();
    witness.wait_exited();
    drop(witness.reap()); // tokio's orphan queue may have reaped it first
    assert!(
        !still_open,
        "after the unwind this process still holds the stdin write end"
    );
}

/// The spawn's identity check peeks through the child's pidfd. A peek that fails cannot show the
/// child ours, but the pidfd pins it whatever the peek said: the spawn keeps the child with no
/// identity, warns of nothing (the failed check is logged at debug), and leaves tokio's `Child` in
/// the backend, so the child is waited for and killed through its handle like any other.
///
/// Mutants: the failed check warns, drops the error, or is never logged; the spawn forgets tokio's `Child`
/// (`forgets()` is 1) or drops it (`backend_drops` is 1); the spawn still fails.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_failed_identity_peek_keeps_the_tokio_child_without_an_identity() {
    use std::cell::RefCell;
    use std::rc::Rc;

    use crate::child::spawn::fault;

    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let armed: Rc<RefCell<Option<Box<dyn std::any::Any>>>> = Rc::default();
    let _hook = fault::set_at(fault::SpawnPoint::BeforeIdentity, {
        let armed = Rc::clone(&armed);
        move || {
            // Armed here, not before `spawn()`: the handshake's own peeks run first.
            *armed.borrow_mut() = Some(Box::new(force_peeks([Err(std::io::Error::other(
                "forced identity-check failure 91c4",
            ))])));
        }
    });
    let forgets = super::drop_fault::record();
    let backend_drops = super::fault::count_backend_drops();
    let mark = crate::log_capture::mark();
    let (stdin, _reaps) = crate::child::spawn::fault::teardown_blocker_stdin();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("stdin");

    let spawned = cmd.spawn();

    drop(armed);
    let mut child = spawned.expect("a failed identity peek keeps the child");
    assert_eq!(child.id(), None, "the read failed, so the child has no identity");
    assert_eq!(
        crate::log_capture::warns_since(mark, ""),
        Vec::<String>::new(),
        "a kept child warns of nothing"
    );
    assert_eq!(
        crate::log_capture::levels_since(mark, "forced identity-check failure 91c4"),
        [log::Level::Debug],
        "the failed check is logged once, at debug, naming its own error"
    );
    assert_eq!(forgets.forgets(), 0, "tokio's Child must stay in the backend");
    assert_eq!(backend_drops.get(), 0, "tokio's Child must not have been dropped");
    child.kill().expect("a kept child is killed through its handle");
    let status = child.wait().await.expect("a kept child is waited on");
    assert_eq!(
        std::os::unix::process::ExitStatusExt::signal(&status),
        Some(libc::SIGKILL),
        "the kill ended the child"
    );
}

/// A teardown whose kill is refused (`EPERM`, as a setuid child answers) while the child is still
/// ours must not hand tokio's `Child` to its drop: tokio would reap it later with `waitpid(pid)`
/// from its orphan queue, when the number may name another process. tokio's `Child` is forgotten
/// and the child is torn down again through its pidfd (another kill, then a reap through the pidfd).
/// The seam refuses only the first kill, so that teardown's kill lands and its reap is recorded.
///
/// Mutants: the refused arm releases tokio's `Child` (`backend_drops` is 1, no teardown reap is
/// recorded); the arm forgets it and does nothing else (no teardown reap is recorded); the forget
/// warns with the foreign-reap text; the refused kill and the forget warn separately.
///
/// This is `reap_now`'s refused-kill arm (a forced attach failure).
#[cfg(target_os = "linux")]
#[skuld::test]
async fn reap_now_after_a_refused_kill_on_a_live_child_reaps_through_the_pidfd() {
    use std::cell::RefCell;
    use std::rc::Rc;

    use crate::child::spawn::fault;

    crate::tokio::test_runtime::assert_current_thread();
    let slot: Rc<RefCell<Option<Witness>>> = Rc::default();
    let _hook = fault::set_at(fault::SpawnPoint::BeforeIdentity, {
        let slot = Rc::clone(&slot);
        move || *slot.borrow_mut() = Some(Witness::new(fault::spawn_pid()))
    });
    fault::set_force_attach_failure(true);
    fault::set_force_kill_failure_leaving_child_alive_as("teardown refused", std::io::ErrorKind::PermissionDenied);
    let forgets = super::drop_fault::record();
    let backend_drops = super::fault::count_backend_drops();
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    // Released once the pidfd teardown's (landing) kill returned.
    let (stdin, reaps) = fault::teardown_blocker_stdin();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("stdin");

    let err = cmd.spawn().err();

    fault::set_force_attach_failure(false);
    assert!(err.is_some(), "the forced failure fails the spawn");
    assert!(
        crate::log_capture::contains_since(mark, "teardown refused); forgetting tokio's handle for it leaks"),
        "the warn must say the kill was refused, then what became of the forget"
    );
    // The refused kill and the forget are one event: one warn, which carries the leak.
    let warns = crate::log_capture::warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("leaks"), "{warns:?}");
    assert!(
        !crate::log_capture::contains_since(mark, "was reaped by someone else"),
        "the child was not reaped by someone else"
    );
    assert_eq!(forgets.forgets(), 1, "tokio's Child must have been forgotten");
    assert_eq!(
        backend_drops.get(),
        0,
        "tokio's Child must not have been released to its drop"
    );
    let recorded = reaps.recorded();
    assert_eq!(
        recorded.len(),
        1,
        "the pidfd teardown must have reaped the child: {recorded:?}"
    );
    assert_eq!(
        std::os::unix::process::ExitStatusExt::signal(&recorded[0].1),
        Some(libc::SIGKILL)
    );
    let witness = slot.borrow_mut().take().expect("the hook ran");
    assert!(witness.reap().is_err(), "the child is reaped already");
}