cosca 0.6.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
//! The async `Child`'s backend answers [`RootState`] from its own handle, and tells its own reap
//! from a reap by someone else.

use crate::signal::RootState;
use crate::tokio::Command;

/// Every record at `warn` or above that this thread logged since `mark`.
pub(super) fn warns_since(mark: usize) -> Vec<String> {
    crate::log_capture::records_since_on_current_thread(mark, "")
        .into_iter()
        .filter(|(level, _)| *level <= log::Level::Warn)
        .map(|(_, text)| text)
        .collect()
}

/// This handle's own reap is `Reaped`, is not a reap by someone else, and nothing around it warns.
///
/// Mutant: `elsewhere` has no `id().is_some()` guard, so `forget_if_foreign` forgets tokio's own reap.
#[skuld::test]
async fn state_after_own_wait_is_reaped_without_a_warn() {
    crate::log_capture::install();
    let mut child = Command::new().args(["true"]).spawn().expect("spawn");
    child.wait().await.expect("wait");

    let mark = crate::log_capture::mark();
    let state = child.proc_mut().state();
    let forgot = child.proc_mut().forget_if_foreign();
    drop(child);

    assert!(matches!(state, RootState::Reaped), "{state:?}");
    assert_eq!(forgot, None, "this handle reaped the child itself");
    assert_eq!(warns_since(mark), Vec::<String>::new());
}

/// A `kill` after a completed `wait` is `Ok` and leaves the cached status for the next `wait`.
///
/// Mutant: `elsewhere` includes tokio's own reap, so the kill forgets tokio's `Child` and
/// the second `wait` answers `ECHILD`.
#[skuld::test]
async fn tokio_kill_after_a_completed_wait_keeps_the_cached_status() {
    crate::log_capture::install();
    let mut child = Command::new().args(["true"]).spawn().expect("spawn");
    let status = child.wait().await.expect("wait");

    let mark = crate::log_capture::mark();
    child.kill().expect("a kill after the child's own reap answers Ok");
    let again = child.wait().await.expect("the cached status survives the kill");

    assert_eq!(again, status);
    assert_eq!(warns_since(mark), Vec::<String>::new());
}

#[cfg(target_os = "linux")]
pub(super) fn session_blocker(kill_on_drop: bool) -> (crate::tokio::Child, std::io::PipeWriter) {
    let (stdin, writer) = crate::test_child::held_writer_stdin();
    let mut cmd = Command::new();
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("set stdin");
    cmd.contain_with(crate::ContainMode::Session);
    cmd.kill_on_drop(kill_on_drop);
    (cmd.spawn().expect("spawn"), writer)
}

#[cfg(target_os = "linux")]
pub(super) fn failed_peek(what: &str) -> std::io::Result<crate::wait::exit_only::Peek> {
    Err(std::io::Error::other(what.to_owned()))
}

/// A tokio drop whose root stays `Unknown` through both looks warns once, and the warn carries
/// what forgetting tokio's `Child` leaks. The drop makes exactly two looks (the read and the
/// second look), so exactly two peeks are forced.
///
/// Mutants: the skip warns; the second look warns; the forget warns; the warn omits the leak.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_tokio_drop_with_an_unknown_root_warns_once() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};

    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, _writer) = session_blocker(true);
    let pid = child.id().pid();
    let mark = crate::log_capture::mark();
    let _failed = force_peeks([failed_peek("forced"), failed_peek("forced")]);

    drop(child);

    assert_peeks_exhausted();
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "one warn for the event: {warns:?}");
    assert!(
        warns[0].contains("RootState::Unknown")
            && warns[0].contains(&format!("pgid {pid}"))
            && warns[0].contains("leaks"),
        "{warns:?}"
    );
}

/// An unknown root behind a live elevation front the drop leaves running is one event, so one
/// warn: it names the unknown state, the front and the leak.
///
/// Mutants: the drop warns of the front apart from the unknown root; the one warn omits the front.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_tokio_drop_with_an_unknown_root_behind_a_closed_front_gate_warns_once() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};
    use crate::wait::exit_only::Peek;

    crate::log_capture::install();
    let recorder = crate::containment::unix::fault::record_kill_group();
    let (mut child, _writer) = session_blocker(true);
    child.set_front(Some(crate::elevation::front::Front::Sudo));
    let mark = crate::log_capture::mark();
    // The read, then the gate's look at the front (it runs), then the second look.
    let _failed = force_peeks([
        failed_peek("forced"),
        Ok(Peek::Running),
        Ok(Peek::Running),
        failed_peek("forced"),
    ]);

    drop(child);

    assert_peeks_exhausted();
    assert_eq!(recorder.killed(), Vec::<i32>::new());
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "one warn for the event: {warns:?}");
    assert!(
        warns[0].contains("RootState::Unknown")
            && warns[0].contains("elevation front pid")
            && warns[0].contains("leaks"),
        "{warns:?}"
    );
}

/// One forget policy, and a quiet one: a root the view shows reaped is forgotten on that evidence;
/// any other only if a second look cannot show it ours, and the second look's answer is carried. A
/// root still shown ours, or already forgotten, is not forgotten, and nothing is logged.
///
/// Mutants: `forget_for` logs; forgets a trusted root without a second look; drops the second
/// look's answer; reports a leak for a backend that was already forgotten.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn forget_for_forgets_quietly_on_evidence_and_carries_the_second_look() {
    use crate::containment::dispatch::RootView;
    use crate::containment::DropView;
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peek_once};

    crate::log_capture::install();
    let view = |root| DropView {
        root_pid: 1,
        root,
        tree_killed: false,
    };

    let (mut child, _writer) = session_blocker(false);
    let mark = crate::log_capture::mark();
    let looks = force_peek_once(failed_peek("forced"));
    let forgot = child
        .proc_mut()
        .forget_for(&view(RootView::Unknown(std::io::Error::other("first look"))))
        .expect("an unsettled root the second look cannot show ours is forgotten");
    assert_peeks_exhausted();
    drop(looks);
    assert!(matches!(forgot.now, Some(RootState::Unknown(_))), "{forgot:?}");
    assert_eq!(warns_since(mark), Vec::<String>::new());
    // The backend is forgotten now: a second forget has nothing to forget, and leaks nothing.
    assert!(child.proc_mut().forget_for(&view(RootView::Reaped)).is_none());
    assert_eq!(
        child.proc_mut().forget_foreign(),
        None,
        "a forget that never happened leaks nothing"
    );
    assert_eq!(warns_since(mark), Vec::<String>::new());

    let (mut child, _writer) = session_blocker(false);
    let mark = crate::log_capture::mark();
    let looks = force_peek_once(failed_peek("forced"));
    let forgot = child
        .proc_mut()
        .forget_for(&view(RootView::Trusted))
        .expect("a trusted root the second look cannot show ours is forgotten");
    assert_peeks_exhausted();
    drop(looks);
    assert!(matches!(forgot.now, Some(RootState::Unknown(_))), "{forgot:?}");
    assert_eq!(warns_since(mark), Vec::<String>::new());

    let (mut child, _writer) = session_blocker(false);
    let mark = crate::log_capture::mark();
    let forgot = child
        .proc_mut()
        .forget_for(&view(RootView::Reaped))
        .expect("a root the view shows reaped is forgotten on that evidence");
    assert!(forgot.now.is_none(), "{forgot:?}");
    assert_eq!(warns_since(mark), Vec::<String>::new());

    let (mut child, _writer) = session_blocker(false);
    assert!(child.proc_mut().forget_for(&view(RootView::Trusted)).is_none());
    assert!(child
        .proc_mut()
        .forget_for(&view(RootView::Unknown(std::io::Error::other("x"))))
        .is_none());
}

/// A refused root kill with an unknown root forgets tokio's `Child` once, under the same one warn.
///
/// Mutant: the failed-kill path forgets with its own warn, besides the drop's.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_tokio_drop_whose_kill_fails_on_an_unknown_root_warns_once() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};

    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, _writer) = session_blocker(true);
    let mark = crate::log_capture::mark();
    let _failed = force_peeks([failed_peek("forced"), failed_peek("forced")]);
    let _kill = crate::tokio::child::fault::force_kill_failure();

    drop(child);

    assert_peeks_exhausted();
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(
        warns[0].contains("RootState::Unknown") && warns[0].contains("leaks"),
        "{warns:?}"
    );
}

/// An `Unknown` seen only on the second look is logged with its error.
///
/// Mutant: the second look is quiet.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn an_unknown_seen_only_on_the_second_look_names_its_error() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};
    use crate::wait::exit_only::Peek;

    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, _writer) = session_blocker(true);
    let mark = crate::log_capture::mark();
    let _failed = force_peeks([Ok(Peek::Running), failed_peek("second look failure 91")]);

    drop(child);

    assert_peeks_exhausted();
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("second look failure 91"), "{warns:?}");
}

/// A disarmed drop kills nothing, so its warn does not speak of a skipped kill.
///
/// Mutant: the warn always says "so it does not".
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_disarmed_drop_with_an_unknown_root_does_not_claim_a_skipped_kill() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};

    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, _writer) = session_blocker(false);
    let mark = crate::log_capture::mark();
    let _failed = force_peeks([failed_peek("forced"), failed_peek("forced")]);

    drop(child);

    assert_peeks_exhausted();
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(!warns[0].contains("does not"), "{warns:?}");
}

/// A failed spawn's cleanup whose root kill is refused, on an `Unknown` root: tokio's `Child` is
/// forgotten once, under the one warn, which carries the leak.
///
/// Mutant: the refused-kill arm forgets with its own warn, besides the cleanup's.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn finish_elevated_with_an_unknown_root_and_a_refused_kill_warns_once() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};

    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, _writer) = session_blocker(true);
    let mark = crate::log_capture::mark();
    let _failed = force_peeks([failed_peek("forced"), failed_peek("forced")]);
    let _kill = crate::tokio::child::fault::force_kill_failure();

    let err = crate::tokio::spawn::finish_elevated(child, Err(crate::error::Error::Io(std::io::Error::other("w"))))
        .expect_err("the spawn fails");

    assert_peeks_exhausted();
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?} ({err:?})");
    assert!(
        warns[0].starts_with("finish_elevated:")
            && warns[0].contains("RootState::Unknown")
            && warns[0].contains("leaks"),
        "{warns:?}"
    );
}

/// A failed spawn's cleanup whose wait finds the child reaped behind its back, on an `Unknown`
/// root: tokio's `Child` is forgotten once, under the one warn, which carries the leak.
///
/// Mutants: the wait's forget warns on its own; the cleanup forgets with `forget_foreign`.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn finish_elevated_with_an_unknown_root_and_a_foreign_reap_during_the_wait_warns_once() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};

    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, _writer) = session_blocker(true);
    let pid = child.id().pid();
    let mark = crate::log_capture::mark();
    let _failed = force_peeks([failed_peek("forced")]);
    let _reap = crate::child::spawn::fault::set_between_kill_and_wait(move || {
        super::child_reap_tests::reap_behind_the_owner(pid);
    });

    let err = crate::tokio::spawn::finish_elevated(child, Err(crate::error::Error::Io(std::io::Error::other("w"))))
        .expect_err("the spawn fails");

    assert_peeks_exhausted();
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?} ({err:?})");
    assert!(
        warns[0].starts_with("finish_elevated:")
            && warns[0].contains("RootState::Unknown")
            && warns[0].contains("leaks"),
        "{warns:?}"
    );
}

/// A failed spawn's cleanup whose wait finds a trusted root reaped behind its back: tokio's `Child`
/// is forgotten once, under one warn that names the foreign reap and carries the leak.
///
/// Mutants: the wait's forget logs nothing and the cleanup's warn omits it; the wait's forget warns
/// on its own, besides the cleanup's.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn finish_elevated_with_a_trusted_root_and_a_foreign_reap_during_the_wait_warns_once() {
    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, _writer) = session_blocker(true);
    let pid = child.id().pid();
    let mark = crate::log_capture::mark();
    let _reap = crate::child::spawn::fault::set_between_kill_and_wait(move || {
        super::child_reap_tests::reap_behind_the_owner(pid);
    });

    let err = crate::tokio::spawn::finish_elevated(child, Err(crate::error::Error::Io(std::io::Error::other("w"))))
        .expect_err("the spawn fails");

    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?} ({err:?})");
    assert!(
        warns[0].starts_with("finish_elevated:")
            && warns[0].contains("reaped by someone else")
            && warns[0].contains("leaks"),
        "{warns:?}"
    );
}

/// The same for a root already gone when the kill is sent (`Sent::Gone`): the cleanup forgets
/// tokio's `Child` and carries the leak in its own warn, not the handle's drop's.
///
/// Mutants: the `Gone` arm leaves the forget to the drop of the handle; the kill's own forget warns.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn finish_elevated_with_an_unknown_root_that_is_already_gone_warns_once() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};

    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, writer) = session_blocker(true);
    drop(writer);
    super::child_reap_tests::reap_behind_the_owner(child.id().pid());
    let mark = crate::log_capture::mark();
    // The number still reads as the root, as after a same-tick reuse.
    let _number = crate::child::fault::force_next_root_read(crate::identity::Resolved::Found(child.id()));
    let _failed = force_peeks([failed_peek("forced"), failed_peek("forced")]);

    let err = crate::tokio::spawn::finish_elevated(child, Err(crate::error::Error::Io(std::io::Error::other("w"))))
        .expect_err("the spawn fails");

    assert_peeks_exhausted();
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?} ({err:?})");
    assert!(
        warns[0].starts_with("finish_elevated:") && warns[0].contains("leaks"),
        "{warns:?}"
    );
}

/// When the second look shows the child reaped by someone else, the warn says so rather than
/// "could not say whether it was reaped".
///
/// Mutant: the warn names only the first look.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn a_second_look_that_shows_a_foreign_reap_is_named() {
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};
    use crate::wait::exit_only::{Foreign, Peek};

    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (child, _writer) = session_blocker(true);
    let mark = crate::log_capture::mark();
    let _looks = force_peeks([failed_peek("forced"), Ok(Peek::Foreign(Foreign::Gone))]);

    drop(child);

    assert_peeks_exhausted();
    let warns = warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("reaped by someone else"), "{warns:?}");
}

#[cfg(target_os = "macos")]
mod macos {
    use super::*;
    use crate::send_log::{Capture, Via};
    use crate::signal::Sig;
    use crate::wait::exit_only::seams::{assert_peeks_exhausted, force_peeks};
    use crate::wait::exit_only::{Foreign, Peek};

    fn walked_blocker() -> (crate::tokio::Child, std::io::PipeWriter) {
        let (stdin, writer) = crate::test_child::held_writer_stdin();
        let mut cmd = Command::new();
        cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
        cmd.stdin(stdin).expect("set stdin");
        cmd.contain_with(crate::ContainMode::TreeWalk);
        (cmd.spawn().expect("spawn"), writer)
    }

    /// A root launchd holds is not pinned by this process: nothing is sent to it, tokio's `Child`
    /// is forgotten, and the one warn names the leak.
    ///
    /// Mutant: `Unpinned` is `Unknown` (the drop kills by pid).
    #[skuld::test]
    async fn an_orphaned_root_is_not_signalled_and_warns_once() {
        crate::log_capture::install();
        let (child, writer) = walked_blocker();
        let pid = child.id().pid();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        let orphaned = || Ok(Peek::Foreign(Foreign::Orphaned));
        let _orphaned = force_peeks([orphaned(), orphaned()]);

        drop(child);
        assert_peeks_exhausted();
        assert!(
            crate::test_child::is_unreaped_child(pid),
            "the root was waited on: this process does not pin it"
        );
        // The test's own child ended and collected, since the drop left it alone.
        drop(writer);
        crate::test_child::wait_until_zombie(pid);
        // SAFETY: `pid` is this test's own zombie child.
        unsafe { libc::waitpid(pid as libc::pid_t, std::ptr::null_mut(), 0) };

        assert_peeks_exhausted();

        assert_eq!(sends.entries(), vec![], "nothing may be sent to a root we do not pin");
        let warns = warns_since(mark);
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(warns[0].contains("launchd") && warns[0].contains("leaks"), "{warns:?}");
    }

    /// An unpinned root cannot be waited on, and the error does not pretend a failed call caused it:
    /// it names launchd and carries no source.
    ///
    /// Mutant: the gate answers `Unassessable` with a synthetic `io::Error` as its source.
    #[skuld::test]
    async fn waiting_on_an_orphaned_root_is_unassessable_without_a_source() {
        crate::log_capture::install();
        let (mut child, _writer) = walked_blocker();
        let _orphaned = force_peeks([Ok(Peek::Foreign(Foreign::Orphaned))]);

        let err = child
            .try_wait()
            .expect_err("a root this process does not pin cannot be waited on");

        assert_peeks_exhausted();
        assert!(
            matches!(&err, crate::error::Error::Unassessable { detail, source: None } if detail.contains("launchd")),
            "{err:?}"
        );
    }

    /// A root launchd holds, behind a live elevation front: the front is left running and the root
    /// is not pinned, which is one event, so one warn that names both.
    ///
    /// Mutants: the drop warns of the front apart from the unpinned root; the one warn omits the
    /// front.
    #[skuld::test]
    async fn an_orphaned_root_behind_a_closed_front_gate_warns_once() {
        crate::log_capture::install();
        let (mut child, writer) = walked_blocker();
        let pid = child.id().pid();
        child.set_front(Some(crate::elevation::front::Front::Sudo));
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        // The read, the gate's look at the front (it runs), then the second look.
        let orphaned = || Ok(Peek::Foreign(Foreign::Orphaned));
        let _looks = force_peeks([orphaned(), Ok(Peek::Running), Ok(Peek::Running), orphaned()]);

        drop(child);

        assert_peeks_exhausted();
        assert_eq!(sends.entries(), vec![]);
        let warns = warns_since(mark);
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(
            warns[0].contains("launchd") && warns[0].contains("elevation front pid") && warns[0].contains("leaks"),
            "{warns:?}"
        );
        drop(writer);
        crate::test_child::wait_until_zombie(pid);
        // SAFETY: `pid` is this test's own zombie child.
        unsafe { libc::waitpid(pid as libc::pid_t, std::ptr::null_mut(), 0) };
    }

    /// Any other root we cannot get an answer for is still our unreaped child: still killed through
    /// its handle.
    ///
    /// Mutant: every `Unknown` leaves the root alone.
    #[skuld::test]
    async fn an_unknown_root_we_pin_is_still_killed_through_its_handle() {
        crate::log_capture::install();
        let (child, _writer) = walked_blocker();
        let pid = child.id().pid();
        let sends = Capture::start();
        let _failed = force_peeks([Err(std::io::Error::other("forced peek failure"))]);

        drop(child);

        assert_peeks_exhausted();

        assert_eq!(sends.entries(), vec![(pid, Sig::Kill, Via::Pid)]);
    }

    fn session_blocker() -> (crate::tokio::Child, std::io::PipeWriter) {
        let (stdin, writer) = crate::test_child::held_writer_stdin();
        let mut cmd = Command::new();
        cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
        cmd.stdin(stdin).expect("set stdin");
        cmd.contain_with(crate::ContainMode::Session);
        (cmd.spawn().expect("spawn"), writer)
    }

    /// Mutants: the holders-only sweep does not exclude the unpinned root; the sweep signals no
    /// holder at all (the control fails).
    #[skuld::test]
    async fn an_orphaned_root_in_a_session_tree_is_not_signalled_by_the_sweep() {
        crate::log_capture::install();
        let _groups = crate::containment::unix::fault::record_kill_group();
        let holders = crate::containment::fdmarker::fault::record_holder_kills();
        // Control: a root that is a marker holder is swept when the handle says it is reaped, so
        // the assertion below is not vacuous.
        let (control, _control_writer) = session_blocker();
        let control_pid = control.id().pid();
        let gone = force_peeks([Ok(Peek::Foreign(Foreign::Gone))]);
        drop(control);
        drop(gone);
        assert!(holders.killed().contains(&control_pid), "{:?}", holders.killed());

        let (child, _writer) = session_blocker();
        let pid = child.id().pid();
        let sends = Capture::start();
        let orphaned = || Ok(Peek::Foreign(Foreign::Orphaned));
        let _orphaned = force_peeks([orphaned(), orphaned()]);

        drop(child);

        assert_peeks_exhausted();

        assert_eq!(sends.entries(), vec![]);
        assert!(
            !holders.killed().contains(&pid),
            "swept the root: {:?}",
            holders.killed()
        );
    }

    /// Mutants: `finish_elevated` signals and waits on the root regardless; it leaves the forget and
    /// warn to the handle's drop.
    #[skuld::test]
    async fn finish_elevated_leaves_an_orphaned_root_alone() {
        crate::log_capture::install();
        let (child, _writer) = walked_blocker();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        // The cleanup's first look, then the second look of its own `forget_for`.
        let orphaned = || Ok(Peek::Foreign(Foreign::Orphaned));
        let _orphaned = force_peeks([orphaned(), orphaned()]);

        let (err, fate) =
            crate::tokio::spawn::finish_elevated(child, Err(crate::error::Error::Io(std::io::Error::other("w"))))
                .expect_err("the spawn fails")
                .expect_may_have_started_with();

        assert_peeks_exhausted();

        assert_eq!(sends.entries(), vec![]);
        assert!(err.to_string().contains("left alone"), "{err}");
        assert_eq!(
            fate,
            crate::error::ChildFate::Gone,
            "a launchd-held zombie, sent nothing, is gone"
        );
        let warns = warns_since(mark);
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(warns[0].contains("launchd") && warns[0].contains("leaks"), "{warns:?}");
    }
}