cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//! macOS: the sync `Child`'s public kill and terminate paths while the root's state is `Unpinned`
//! (launchd holds its zombie) or `Unknown` (the handle cannot vouch for it).
//!
//! The lone `kill` and `terminate` refuse an `Unpinned` root and send to an `Unknown` one through
//! its handle. The tree paths send by identity alone, as the drop does: nothing named by the root's
//! number (`killpg`, the walk from its pid, its kill by pid) runs; an fd marker still signals its
//! holders. Each case forces the state with a peek, and a positive control then signals the same
//! child once its state reads true, so a refusal that never lets go fails too.
//!
//! A test that counts the peeks left empties the table with `fake.peeks([])` before it ends: the
//! answer left over must not reach the drop.

use std::io::{BufRead as _, BufReader};

use crate::test_child::Console;
use std::time::Duration;

use crate::error::Error;
use crate::log_capture::warns_since;
use crate::os_process::child::{Foreign, PeekOutcome};
use crate::os_process::fake::FakeProcess;
use crate::send_log::{Capture, Via};
use crate::signal::Sig;
use crate::ContainMode;

/// A blocker whose spawn reports `elevation`: a child launched behind that elevation backend.
fn blocker(
    mode: ContainMode,
    elevation: Option<crate::elevation::ElevationReport>,
) -> (crate::Child, crate::PipeWriter) {
    let (stdin, writer) = crate::test_child::held_writer_stdin();
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("set stdin");
    cmd.contain_with(mode);
    cmd.set_elevation_report(elevation);
    (cmd.spawn().expect("spawn"), writer)
}

/// A blocker spawned with the marker's install made to fail, so the spawn degrades to the
/// mechanism the marker takes priority over.
fn degraded_blocker(
    mode: ContainMode,
    elevation: Option<crate::elevation::ElevationReport>,
) -> (crate::Child, crate::PipeWriter) {
    use crate::containment::fdmarker::fault::{lock_for_log_assertion, set_fault, Fault};
    // A failed install logs, and a sibling test scans the shared log for its own text.
    let _serialize = lock_for_log_assertion();
    set_fault(Some(Fault::Pipe));
    let spawned = blocker(mode, elevation);
    set_fault(None);
    spawned
}

/// A tree-walk child: its root is signalled by identity. (On macOS `TreeWalk` is only the
/// mechanism when the marker cannot be installed, which is made to happen here.)
pub(crate) fn walked_blocker() -> (crate::Child, crate::PipeWriter) {
    walked_blocker_reporting(None)
}

/// [`walked_blocker`] whose spawn reports `elevation`.
fn walked_blocker_reporting(elevation: Option<crate::elevation::ElevationReport>) -> (crate::Child, crate::PipeWriter) {
    let (child, writer) = degraded_blocker(ContainMode::TreeWalk, elevation);
    assert!(
        child.containment() == crate::containment::Containment::TreeWalk,
        "the test needs a tree walk"
    );
    (child, writer)
}

/// A session (fd-marker) child: its group is signalled with `killpg`.
pub(crate) fn session_blocker() -> (crate::Child, crate::PipeWriter) {
    let (child, writer) = blocker(ContainMode::Session, None);
    assert!(
        child.containment() == crate::containment::Containment::FdMarker,
        "the test needs an fd marker"
    );
    (child, writer)
}

/// A child whose group is its containment: a session leader's, the mechanism [`ContainMode::Session`]
/// degrades to without the marker (it reports [`Containment::Session`](crate::containment::Containment::Session),
/// not `ProcessGroup`).
pub(crate) fn group_blocker() -> (crate::Child, crate::PipeWriter) {
    let (child, writer) = degraded_blocker(ContainMode::Session, None);
    assert!(
        child.containment() == crate::containment::Containment::Session,
        "the test needs a session's process group"
    );
    (child, writer)
}

/// A session child whose root `cat` (held on its stdin, so only a signal ends it) holds one
/// descendant `cat`, a second marker holder on the same stdin, and that descendant's pid, read once
/// the root has started it. Nothing is written to the stdin, so neither exits on its own before the
/// writer drops, and the holders do not change under a sweep. The last element is the read end of a
/// pipe only the descendant holds, for [`assert_descendant_dies`]: it reaches EOF when the
/// descendant ends, whatever happens to the stdin.
pub(crate) fn session_tree() -> (crate::Child, crate::PipeWriter, u32, crate::PipeReader) {
    let (stdin, writer) = crate::test_child::held_writer_stdin();
    let mut cmd = crate::test_child::command(Console::Hidden);
    // A background job's stdin is `/dev/null` unless it is redirected (see `BLOCKER_ARGV`). The root closes 3
    // and 4 in a bare `exec` before `exec cat`: macOS's bash 3.2 saves the fds an `exec cmd N>&-` closes to 10
    // and up, and the command inherits them, so the root would keep the descendant's pipe open.
    cmd.args([
        "sh",
        "-c",
        "exec 3<&0; cat <&3 3<&- >/dev/null & echo $!; exec 3<&- 4>&-; exec cat",
    ]);
    cmd.stdin(stdin).expect("set stdin");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout");
    cmd.fd(4, crate::Stdio::pipe_out()).expect("set the descendant's pipe");
    cmd.contain_with(ContainMode::Session);
    let mut child = cmd.spawn().expect("spawn");
    let mut line = String::new();
    BufReader::new(child.stdout().expect("piped stdout"))
        .read_line(&mut line)
        .expect("the descendant's pid");
    let gone = child.fd_read_end(4.into()).expect("the descendant's pipe");
    (child, writer, line.trim().parse().expect("a pid"), gone)
}

/// Blocks until the [`session_tree`] descendant is gone: its pipe reaches EOF. Call it once the test
/// has shown the descendant was signalled and before releasing the stdin, so a signal that went
/// nowhere cannot pass by the stdin's EOF ending the descendant anyway.
pub(crate) fn assert_descendant_dies(mut gone: crate::PipeReader) {
    let mut rest = Vec::new();
    std::io::Read::read_to_end(&mut gone, &mut rest).expect("the descendant's pipe reaches EOF");
    assert!(rest.is_empty(), "unexpected output from the descendant: {rest:?}");
}

/// The two states the tree paths cannot send by number for.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Untrusted {
    /// launchd holds the root's zombie.
    Unpinned,
    /// The handle could not say.
    Unknown,
}

pub(crate) const BOTH: [Untrusted; 2] = [Untrusted::Unpinned, Untrusted::Unknown];

impl Untrusted {
    /// The next peek of `child`'s root reads as this state.
    pub(crate) fn script(self, child: &mut crate::Child) -> FakeProcess {
        child.proc.script_over(|f| f.peeks([self.result()]))
    }

    pub(crate) fn result(self) -> std::io::Result<PeekOutcome> {
        match self {
            Untrusted::Unpinned => Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
            Untrusted::Unknown => Err(std::io::Error::other("unreadable")),
        }
    }

    /// What a message about this state names.
    pub(crate) fn why(self) -> &'static str {
        match self {
            Untrusted::Unpinned => "launchd holds its zombie",
            Untrusted::Unknown => "RootState::Unknown",
        }
    }

    /// The `source` of a refusal for this state: none for `Unpinned`, whose refusal asked nothing of
    /// the OS, and the failed peek (`result`) for `Unknown`.
    pub(crate) fn cause(self) -> Cause {
        match self {
            Untrusted::Unpinned => Cause::None,
            Untrusted::Unknown => Cause::Unreadable,
        }
    }
}

/// What a refusal carries as its `source`.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Cause {
    /// Nothing.
    None,
    /// The failed peek `Untrusted::Unknown` scripts.
    Unreadable,
    /// The failure the test forces on the cooperative signal (`Forced::Containment`), carried below
    /// the sweep's refusal.
    ForcedTerm,
}

impl Cause {
    /// `source` is this cause, and the right one: the injected fault or the OS code, not just any error.
    #[track_caller]
    pub(crate) fn assert(self, source: &Option<std::sync::Arc<Error>>) {
        match (self, source) {
            (Cause::None, None) => {}
            (Cause::None, Some(cause)) => panic!("expected no source, got {cause:?}"),
            (_, None) => panic!("expected {self:?} as the source, got none"),
            (Cause::Unreadable, Some(cause)) => {
                let said = crate::error::said(&**cause);
                assert!(said.contains("unreadable"), "{said}");
            }
            (Cause::ForcedTerm, Some(cause)) => assert!(
                matches!(&**cause, Error::Containment { detail, .. } if detail.contains("forced term_group refusal")),
                "{cause:?}"
            ),
        }
    }
}

/// [`Untrusted::script`] for [`Untrusted::Unpinned`].
pub(crate) fn orphan(child: &mut crate::Child) -> FakeProcess {
    Untrusted::Unpinned.script(child)
}

/// The lone refusal: `Unassessable`, no source, naming launchd and the call that sent nothing.
#[track_caller]
pub(crate) fn assert_refused(err: &Error, op: &str) {
    assert_refused_caused_by(err, op, Cause::None);
}

/// [`assert_refused`], for a call whose earlier failure is the refusal's `source`.
#[track_caller]
pub(crate) fn assert_refused_caused_by(err: &Error, op: &str, cause: Cause) {
    match err {
        Error::Unassessable { detail, source } => {
            assert!(
                detail.contains("launchd")
                    && detail.contains(&format!("{op} sent nothing"))
                    && !detail.contains("(launchd"),
                "{detail}"
            );
            cause.assert(source);
        }
        other => panic!("expected Unassessable, got {other:?}"),
    }
}

/// The tree refusal: `Unassessable` with the state's own cause ([`Untrusted::cause`]), naming the
/// state, the call that sent nothing and that its signals are named by the root's number.
#[track_caller]
pub(crate) fn assert_tree_refused(err: &Error, op: &str, state: Untrusted) {
    assert_tree_refused_caused_by(err, op, state, state.cause());
}

/// [`assert_tree_refused`], for a call whose earlier failure is the refusal's `source`.
#[track_caller]
pub(crate) fn assert_tree_refused_caused_by(err: &Error, op: &str, state: Untrusted, cause: Cause) {
    match err {
        Error::Unassessable { detail, source } => {
            assert!(
                detail.contains(state.why())
                    && detail.contains(&format!("{op} sent nothing"))
                    && detail.contains("named by the root's number"),
                "{state:?}: {detail}"
            );
            cause.assert(source);
        }
        other => panic!("{state:?}: expected Unassessable, got {other:?}"),
    }
}

/// `err` is the `Unassessable` of an fd marker's kill that signalled only its holders, for a root in
/// `state`, with the state's own cause.
#[track_caller]
pub(crate) fn assert_holders_only(err: &Error, op: &str, state: Untrusted) {
    match err {
        Error::Unassessable { detail, source } => {
            assert!(
                detail.contains(state.why()) && detail.contains(&format!("{op} signalled the marker holders")),
                "{state:?}: {detail}"
            );
            state.cause().assert(source);
        }
        other => panic!("{state:?}: expected Unassessable, got {other:?}"),
    }
}

/// Nothing was sent to the root by pid or by identity.
#[track_caller]
pub(crate) fn assert_nothing_sent(sends: &Capture) {
    assert_eq!(sends.entries(), vec![], "nothing may be sent to a root we do not pin");
    assert_eq!(sends.by_identity(), vec![], "nothing may be sent by identity either");
}

/// The holders a sweep signalled, sorted.
#[track_caller]
pub(crate) fn sorted(mut pids: Vec<u32>) -> Vec<u32> {
    pids.sort_unstable();
    pids.dedup();
    pids
}

/// Every pid in `want` was sent signal `signo` by identity, as `sends` logged it: the log is written
/// after the `kill(2)`, so a holder the recorder names but no signal went to fails here.
#[track_caller]
pub(crate) fn assert_sent_by_identity(sends: &Capture, signo: i32, want: &[u32], what: impl std::fmt::Debug) {
    let sent: Vec<u32> = sends
        .by_identity()
        .into_iter()
        .filter(|&(_, sent)| sent == signo)
        .map(|(pid, _)| pid)
        .collect();
    for pid in want {
        assert!(
            sent.contains(pid),
            "{what:?}: signal {signo} never went to pid {pid}: {sent:?}"
        );
    }
}

// Lone kill and terminate =====

/// Mutant: `kill` sends without reading the root's state.
#[skuld::test]
fn kill_of_an_orphaned_root_sends_nothing() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    let fake = orphan(&mut child);

    let err = child
        .kill()
        .expect_err("a root this process does not pin is not killed");

    fake.assert_peeks_exhausted();
    assert_refused(&err, "kill");
    assert_nothing_sent(&sends);
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());

    child.kill().expect("an unreaped root is killed");
    assert_eq!(sends.entries(), vec![(pid, Sig::Kill, Via::Identity)]);
    drop(writer);
}

/// The handle pins an `Unknown` root: our own unreaped child, killed by its pid only while the
/// pid's unique id is still the child's.
///
/// Mutant: `kill` refuses an `Unknown` root as it does an `Unpinned` one.
#[skuld::test]
fn kill_of_an_unknown_root_is_sent_through_its_handle() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    let sends = Capture::start();
    let fake = Untrusted::Unknown.script(&mut child);

    child.kill().expect("an unknown root is killed through its handle");

    fake.assert_peeks_exhausted();
    assert_eq!(sends.entries(), vec![(pid, Sig::Kill, Via::Identity)]);
    drop(writer);
}

/// Mutant: `terminate` signals the root without reading its state.
#[skuld::test]
fn terminate_of_an_orphaned_root_sends_nothing() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    let fake = orphan(&mut child);

    let err = child
        .terminate()
        .expect_err("a root this process does not pin is not signalled");

    fake.assert_peeks_exhausted();
    assert_refused(&err, "terminate");
    assert_nothing_sent(&sends);
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());

    child.terminate().expect("an unreaped root is signalled");
    assert_eq!(sends.by_identity(), vec![(pid, libc::SIGTERM)]);
    drop(writer);
}

/// Mutant: `terminate` refuses an `Unknown` root as it does an `Unpinned` one.
#[skuld::test]
fn terminate_of_an_unknown_root_is_sent_through_its_handle() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    let sends = Capture::start();
    let fake = Untrusted::Unknown.script(&mut child);

    child.terminate().expect("an unknown root is signalled");

    fake.assert_peeks_exhausted();
    assert_eq!(sends.by_identity(), vec![(pid, libc::SIGTERM)]);
    drop(writer);
}

// kill_tree =====

/// A tree-walk root is named by its number alone: nothing is sent, the answer says what was skipped.
///
/// Mutants: `kill_tree` walks without reading the root's state; it refuses only `Unpinned`.
#[skuld::test]
fn kill_tree_of_an_untrusted_walked_root_sends_nothing() {
    crate::log_capture::install();
    for state in BOTH {
        let (mut child, writer) = walked_blocker();
        let pid = child.pid();
        let sends = Capture::start();
        let walks = crate::containment::treewalk::fault::record_walks();
        let mark = crate::log_capture::mark();
        let fake = state.script(&mut child);

        let err = child
            .kill_tree()
            .expect_err("the walk names the tree by the root's number");

        fake.assert_peeks_exhausted();
        assert_tree_refused(&err, "kill_tree", state);
        assert_nothing_sent(&sends);
        assert_eq!(walks.walked(), Vec::<u32>::new(), "{state:?}");
        assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");

        child.kill_tree().expect("an unreaped root is killed with its tree");
        assert!(
            sends.by_identity().contains(&(pid, libc::SIGKILL)),
            "{state:?}: {:?}",
            sends.by_identity()
        );
        drop(writer);
    }
}

/// A process group is named by the root's number: no `killpg`.
///
/// Mutants: `kill_tree` fires `killpg` without reading the root's state; it refuses only `Unpinned`.
#[skuld::test]
fn kill_tree_of_an_untrusted_group_root_sends_no_killpg() {
    crate::log_capture::install();
    for state in BOTH {
        let groups = crate::containment::unix::fault::record_kill_group();
        let (mut child, writer) = group_blocker();
        let pid = child.pid();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        let fake = state.script(&mut child);

        let err = child.kill_tree().expect_err("the group is named by the root's number");

        fake.assert_peeks_exhausted();
        assert_tree_refused(&err, "kill_tree", state);
        assert_nothing_sent(&sends);
        assert_eq!(groups.killed(), Vec::<i32>::new(), "{state:?}");
        assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");

        child.kill_tree().expect("an unreaped root is killed with its group");
        assert_eq!(
            groups.killed(),
            vec![pid as i32],
            "{state:?}: the group call was reached"
        );
        drop(writer);
    }
}

/// An fd marker names its holders by identity, so the sweep still runs on them: the descendant is
/// killed, the root only while it may be (`Unknown`, not `Unpinned`), and the answer is
/// `Unassessable` all the same, as the kill skipped the rest. No `killpg`, no walk from the root's pid.
///
/// Mutants: the sweep is skipped; it signals the `Unpinned` root; it spares the `Unknown` root; it
/// fires `killpg` or walks from the root's pid; the answer is `Ok`.
#[skuld::test]
fn kill_tree_of_an_untrusted_session_root_kills_its_holders_only() {
    crate::log_capture::install();
    for state in BOTH {
        let groups = crate::containment::unix::fault::record_kill_group();
        let walks = crate::containment::treewalk::fault::record_walks();
        let holders = crate::containment::fdmarker::fault::record_holder_kills();
        let (mut child, writer, descendant, gone) = session_tree();
        let pid = child.pid();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        let fake = state.script(&mut child);

        let err = child
            .kill_tree()
            .expect_err("every holder was reached, but the kill skipped the rest of the tree");
        assert_holders_only(&err, "kill_tree", state);

        fake.assert_peeks_exhausted();
        assert_eq!(groups.killed(), Vec::<i32>::new(), "{state:?}");
        assert_eq!(walks.walked(), Vec::<u32>::new(), "{state:?}");
        assert_eq!(sends.entries(), vec![], "{state:?}: nothing by pid");
        let want = match state {
            Untrusted::Unpinned => vec![descendant],
            Untrusted::Unknown => sorted(vec![pid, descendant]),
        };
        assert_eq!(sorted(holders.killed()), want, "{state:?}");
        assert_sent_by_identity(&sends, libc::SIGKILL, &want, state);
        assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
        assert_descendant_dies(gone);
        drop(writer);
    }
}

/// A real control: a trusted session root is killed for real, not through the recorder. The stdin
/// is released after the kill, so a kill that never came ends the root with status 0 instead of
/// hanging the wait.
///
/// Mutant: `kill_tree` of a trusted root signals nothing.
#[skuld::test]
fn kill_tree_kills_a_trusted_session_root() {
    let (child, writer) = session_blocker();

    child.kill_tree().expect("a trusted root is killed with its group");

    drop(writer);
    crate::test_child::assert_killed("the session root", child.wait().expect("wait"));
}

// terminate_tree =====

/// Mutants: `terminate_tree` walks without reading the root's state; it refuses only `Unpinned`.
#[skuld::test]
fn terminate_tree_of_an_untrusted_walked_root_sends_nothing() {
    crate::log_capture::install();
    for state in BOTH {
        let (mut child, writer) = walked_blocker();
        let pid = child.pid();
        let sends = Capture::start();
        let walks = crate::containment::treewalk::fault::record_walks();
        let mark = crate::log_capture::mark();
        let fake = state.script(&mut child);

        let err = child
            .terminate_tree()
            .expect_err("the walk names the tree by the root's number");

        fake.assert_peeks_exhausted();
        assert_tree_refused(&err, "terminate_tree", state);
        assert_nothing_sent(&sends);
        assert_eq!(walks.walked(), Vec::<u32>::new(), "{state:?}");
        assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");

        child
            .terminate_tree()
            .expect("an unreaped root is signalled with its tree");
        assert!(
            sends.by_identity().contains(&(pid, libc::SIGTERM)),
            "{state:?}: {:?}",
            sends.by_identity()
        );
        drop(writer);
    }
}

/// Mutants: `terminate_tree` fires `killpg` without reading the root's state; it refuses only
/// `Unpinned`.
#[skuld::test]
fn terminate_tree_of_an_untrusted_group_root_sends_no_killpg() {
    crate::log_capture::install();
    for state in BOTH {
        let groups = crate::containment::unix::fault::record_term_group();
        let (mut child, writer) = group_blocker();
        let pid = child.pid();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        let fake = state.script(&mut child);

        let err = child
            .terminate_tree()
            .expect_err("the group is named by the root's number");

        fake.assert_peeks_exhausted();
        assert_tree_refused(&err, "terminate_tree", state);
        assert_nothing_sent(&sends);
        assert_eq!(groups.termed(), Vec::<i32>::new(), "{state:?}");
        assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");

        child
            .terminate_tree()
            .expect("an unreaped root is signalled with its group");
        assert_eq!(
            groups.termed(),
            vec![pid as i32],
            "{state:?}: the group call was reached"
        );
        drop(writer);
    }
}

/// Mutants: the sweep is skipped; it signals the `Unpinned` root; it spares the `Unknown` root; it
/// fires `killpg` or walks from the root's pid.
#[skuld::test]
fn terminate_tree_of_an_untrusted_session_root_signals_its_holders_only() {
    crate::log_capture::install();
    for state in BOTH {
        let groups = crate::containment::unix::fault::record_term_group();
        let walks = crate::containment::treewalk::fault::record_walks();
        let holders = crate::containment::fdmarker::fault::record_holder_kills();
        let (mut child, writer, descendant, gone) = session_tree();
        let pid = child.pid();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        let fake = state.script(&mut child);

        child
            .terminate_tree()
            .expect("every holder was reached, so the tree was asked to stop");

        fake.assert_peeks_exhausted();
        assert_eq!(groups.termed(), Vec::<i32>::new(), "{state:?}");
        assert_eq!(walks.walked(), Vec::<u32>::new(), "{state:?}");
        assert_eq!(sends.entries(), vec![], "{state:?}: nothing by pid");
        let want = match state {
            Untrusted::Unpinned => vec![descendant],
            Untrusted::Unknown => sorted(vec![pid, descendant]),
        };
        assert_eq!(sorted(holders.killed()), want, "{state:?}");
        assert_sent_by_identity(&sends, libc::SIGTERM, &want, state);
        assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
        assert_descendant_dies(gone);
        drop(writer);
    }
}

/// A real control: a trusted session root is terminated for real, not through the recorder. The
/// stdin is released after the signal, so a signal that never came ends the root with status 0
/// instead of hanging the wait.
///
/// Mutant: `terminate_tree` signals nothing for a trusted session root.
#[skuld::test]
fn terminate_tree_terminates_a_trusted_session_root() {
    use std::os::unix::process::ExitStatusExt as _;
    let (child, writer) = session_blocker();

    child
        .terminate_tree()
        .expect("a trusted root is signalled with its group");

    drop(writer);
    assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGTERM));
}

// One look per decision =====

/// `terminate_tree` decides on one look at the root's state. That look reads `Running`, so the group
/// is signalled; the root's orphaning after it is not looked at again, by a check that would let it
/// through.
///
/// Mutant: the untrusted-root check and the reaped-root check each look, and the second look's
/// `Unpinned` is let through to the group signal.
#[skuld::test]
fn terminate_tree_decides_on_one_look_at_the_root() {
    let groups = crate::containment::unix::fault::record_term_group();
    let (mut child, writer) = group_blocker();
    let pid = child.pid();
    let fake = child
        .proc
        .script_over(|f| f.peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));

    child.terminate_tree().expect("a running root's group is signalled");

    assert_eq!(fake.peeks_left(), 1, "the decision looked at the root twice");
    drop(fake.peeks([]));
    assert_eq!(groups.termed(), vec![pid as i32]);
    drop(writer);
}

/// `kill_tree`'s twin of [`terminate_tree_decides_on_one_look_at_the_root`]: one look decides the
/// sweep, and the backstop's own look takes the second.
///
/// Mutant: as there.
#[skuld::test]
fn kill_tree_decides_on_one_look_at_the_root() {
    let groups = crate::containment::unix::fault::record_kill_group();
    let (mut child, writer) = group_blocker();
    let pid = child.pid();
    let fake = child.proc.script_over(|f| {
        f.peeks([
            Ok(PeekOutcome::Running),
            Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
            Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
        ])
    });

    child.kill_tree().expect("a running root's group is killed");

    assert_eq!(fake.peeks_left(), 1, "the decision looked at the root twice");
    drop(fake.peeks([]));
    assert_eq!(groups.killed(), vec![pid as i32]);
    drop(writer);
}

// The backstop =====

/// The tree kill reads the root's state again before its handle backstop. A root orphaned during
/// the sweep is an exited zombie launchd holds, so there is nothing for the backstop to kill: it is
/// skipped, and the sweep's answer stands.
///
/// Mutants: the backstop does not read the state again; it reads it and refuses.
#[skuld::test]
fn kill_tree_skips_its_backstop_for_a_root_orphaned_during_the_sweep() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    let fake = child
        .proc
        .script_over(|f| f.peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));

    child
        .kill_tree()
        .expect("the sweep killed the tree; the backstop has nothing to do");

    fake.assert_peeks_exhausted();
    // The walk kills the root through the handle, as the backstop would: one kill through it is the
    // walk's, and a second would be the backstop's.
    assert_eq!(
        sends.entries(),
        vec![(pid, Sig::Kill, Via::Identity)],
        "the backstop must send nothing after the walk's own kill of the root"
    );
    assert!(
        sends.by_identity().contains(&(pid, libc::SIGKILL)),
        "the sweep ran first"
    );
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
    drop(writer);
}

/// An `Unknown` root at the backstop is still our unreaped child, killed through its handle as the
/// lone `kill` does.
///
/// Mutant: the backstop is skipped for an `Unknown` root too.
#[skuld::test]
fn kill_tree_keeps_its_backstop_for_an_unknown_root() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    let sends = Capture::start();
    let fake = child
        .proc
        .script_over(|f| f.peeks([Ok(PeekOutcome::Running), Err(std::io::Error::other("unreadable"))]));

    child.kill_tree().expect("the backstop kills through the handle");

    fake.assert_peeks_exhausted();
    // The walk's own kill of the root and the backstop's go through the same handle: the second kill
    // through it is the backstop's.
    assert_eq!(
        sends.entries(),
        vec![(pid, Sig::Kill, Via::Identity), (pid, Sig::Kill, Via::Identity)]
    );
    drop(writer);
}

// Guard order =====

/// An uncontained child has no tree: that answer is permanent and about the mechanism, so it
/// outranks the root's state, which is not even read.
///
/// Mutant: a tree path reads the root's state before checking that the child is contained.
#[skuld::test]
fn an_uncontained_child_hears_why_it_has_no_tree_not_why_its_root_is_unpinned() {
    let (stdin, writer) = crate::test_child::held_writer_stdin();
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(stdin).expect("set stdin");
    let mut child = cmd.spawn().expect("spawn");
    let fake = child
        .proc
        .script_over(|f| f.peeks([Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));

    for (op, result) in [
        ("kill_tree", child.kill_tree()),
        ("terminate_tree", child.terminate_tree()),
        (
            "graceful_shutdown_tree",
            child.graceful_shutdown_tree(Duration::ZERO).map(drop),
        ),
    ] {
        assert!(
            matches!(result, Err(Error::Unsupported { .. })),
            "{op}: expected the containment error, got {result:?}"
        );
    }
    assert_eq!(fake.peeks_left(), 1, "the root's state was read");
    drop(fake.peeks([]));
    drop(writer);
}

/// A front that may not be signalled is refused whatever the root's state: the refusal is
/// permanent and says nothing of the pid, while an unpinned root is a state the caller can do
/// nothing about either way. The state is not even read.
///
/// Mutant: a path reads the root's state before the front's gate.
#[skuld::test]
fn a_closed_front_gate_outranks_an_unpinned_root() {
    use crate::elevation::{Backend, ElevatedVia};
    for op in ["kill", "terminate", "kill_tree"] {
        // `sudo` relays a `SIGTERM`, so only `osascript` closes the terminate gate.
        let (mut child, writer) =
            walked_blocker_reporting(Some(crate::elevation::elevation_tests::report(if op == "terminate" {
                ElevatedVia::MacosOsascript
            } else {
                ElevatedVia::Wrapped(Backend::Sudo)
            })));
        // The gate looks at the front (twice for a kill, once for a terminate), and the state, read
        // wrongly first, would take the front's `Running` and let the gate see the `Orphaned`
        // one: an exited front, which is signalled.
        let peeks = if op == "terminate" {
            vec![Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))]
        } else {
            vec![
                Ok(PeekOutcome::Running),
                Ok(PeekOutcome::Running),
                Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
            ]
        };
        let fake = child.proc.script_over(|f| f.peeks(peeks));

        let err = match op {
            "kill" => child.kill(),
            "terminate" => child.terminate(),
            _ => child.kill_tree(),
        }
        .expect_err("the front is not signalled");

        assert!(
            matches!(
                err,
                Error::Elevation {
                    kind: crate::error::ElevationErrorKind::Unkillable,
                    ..
                }
            ),
            "{op}: {err:?}"
        );
        assert_eq!(
            fake.peeks_left(),
            1,
            "{op}: the root's state was read before the gate, or the gate was not"
        );
        drop(fake.peeks([]));
        drop(writer);
    }
}