cosca 0.8.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
//! One event, one warn: the sync `Child`'s drop and `finish_elevated` report an event once,
//! however many steps (the unsettled root, the refused kill, the failed reap) each had to say. Each
//! test forces the looks it counts on and asserts they were all made.

use crate::log_capture::warns_since;
use crate::test_child::Console;
#[cfg(target_os = "linux")]
use crate::test_groups::{setuid, Group};
use crate::ContainMode;

/// One scripted refusal of a kill: the `EPERM` the kernel answers a signal to another user's process.
fn refused() -> crate::os_process::fake::SignalAnswer {
    crate::os_process::fake::failed_signal(libc::EPERM)
}

/// The OS's words for the `EPERM` that [`refused`] answers: the warn names the refusal as the OS
/// gave it.
fn refusal() -> String {
    std::io::Error::from_raw_os_error(libc::EPERM).to_string()
}

fn contained_blocker(mode: ContainMode) -> (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.spawn().expect("spawn"), writer)
}

/// A child with no containment: nothing sweeps it before the root kill under test, on any platform
/// (a macOS fd marker's sweep kills the root, which holds the marker).
fn bare_blocker() -> (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.spawn().expect("spawn"), writer)
}

fn failed_write() -> Result<(), crate::error::Error> {
    Err(crate::error::Error::Elevation {
        kind: crate::error::ElevationErrorKind::AuthFailed,
        detail: "w".into(),
        source: None,
    })
}

/// An unknown root whose kill the OS refuses: the unknown state and the refusal are one event, so
/// one warn that names both. (macOS: a refused unique-id read on a setuid child spawned without
/// `.elevate()` is this case.)
///
/// Mutant: `tear_down` warns of the refusal on its own, besides the drop's.
#[skuld::test]
fn an_unknown_root_with_a_refused_kill_warns_once() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let mark = crate::log_capture::mark();
    let fake = child.proc.script_over(|f| {
        f.peeks([Err(std::io::Error::other("forced peek failure"))])
            .signals([refused()])
    });

    drop(child);
    drop(writer);

    fake.assert_peeks_exhausted();
    assert_eq!(fake.signal_calls(), [crate::signal::Sig::Kill], "the drop's kill");
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(
        warns[0].starts_with("Child::drop:")
            && warns[0].contains("RootState::Unknown")
            && warns[0].contains(&refusal()),
        "{warns:?}"
    );
}

/// The teardown of a root says what became of it under the caller's own name: a teardown after a
/// failed run leads its `debug` reap line with that name, not a drop's. Only the teardown's own
/// line is read: on macOS the reap's second look logs a line of its own at `debug`.
///
/// Mutant: `Child::tear_down` leads the clause with `TeardownCaller::Drop.label()`, whoever called.
#[skuld::test]
fn a_roots_reap_is_said_under_the_name_of_the_caller_that_tore_it_down() {
    use crate::containment::dispatch::TeardownCaller;

    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let pid = child.pid();
    let mark = crate::log_capture::mark();

    let torn = child.tear_down(
        TeardownCaller::FailedRun,
        crate::child::owned::teardown::Disposition::Leave,
    );

    assert_eq!(torn.fate, crate::error::ChildFate::Reaped);
    assert_eq!(
        crate::log_capture::records_since_on_current_thread(mark, "teardown of child"),
        [(
            log::Level::Debug,
            format!("teardown after a failed run: teardown of child {pid}: reaped it after the kill")
        )]
    );
    drop(writer);
}

/// A failed spawn's cleanup on an unknown root whose reap fails after the kill: the unknown state
/// and the failed reap are one event, so one warn that names both.
///
/// Mutant: the failed reap warns on its own, besides the unknown state's.
#[skuld::test]
fn finish_elevated_with_an_unknown_root_and_a_failed_reap_warns_once() {
    crate::log_capture::install();
    let _recorder = crate::containment::unix::fault::record_kill_group();
    let (mut child, writer) = contained_blocker(ContainMode::Session);
    let pid = child.pid();
    // Released once the cleanup's root kill returned, before its reap (the forced failure comes
    // after the reap, which records nothing): the root must be a zombie that died of `SIGKILL`.
    let _released = crate::child::spawn::fault::set_between_kill_and_wait(move || {
        drop(writer);
        crate::test_child::assert_zombie_sigkilled("the root", pid);
    });
    let mark = crate::log_capture::mark();
    let fake = child
        .proc
        .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
    crate::child::spawn::fault::set_force_reap_failure("cosca-unknown-reap-9d1c");

    let err = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");

    fake.assert_peeks_exhausted();
    assert!(
        crate::child::spawn::fault::take_force_reap_failure().is_none(),
        "the cleanup consumed the forced failure"
    );
    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(&format!("the elevated child pid {pid}: the wait failed")),
        "{warns:?}"
    );
}

/// A failed spawn's cleanup on a `TreeWalk` child whose walk left only the root: the cleanup's own
/// kill of the root ends it, but the walk saw the root running, so the tree is not vouched for. The
/// cleanup says so once, in the error and the warn, and disarms the handle, so its drop does not say
/// it again. A walk that left a descendant is a failed kill: reported, and the handle stays armed to
/// try again. Not on macOS, where `TreeWalk` mode is an fd marker.
///
/// Mutants: the cleanup reports the walk's error before the root's kill; the handle stays armed over
/// an unvouched tree (its drop warns again).
#[cfg(target_os = "linux")]
#[skuld::test]
fn finish_elevated_reports_a_walk_that_left_only_the_root_as_unvouched_once() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::log_capture::install();
    for (left, failed) in [(LeftBehind::Root, false), (LeftBehind::Descendant, true)] {
        let (child, writer) = crate::test_child::held_treewalk_blocker_leaving(left);
        let mark = crate::log_capture::mark();
        let drop_looks = crate::graceful_hooks::watch_for_a_second_look();

        let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
        let error = crate::error::Error::from(failure);
        // A walk that left a descendant failed: its members are the cleanup. One that left only the
        // root is no failure, and has none.
        let cleanup = matches!(&error, crate::error::Error::MayHaveStarted { cleanup: Some(_), .. });
        assert_eq!(cleanup, failed, "{left:?}: {error:?}");
        if failed {
            let cleanup = crate::test_child::cleanup_of(&error);
            assert!(
                matches!(&**cleanup.first(), crate::error::Error::MembersLeft { .. }),
                "{left:?}: {cleanup:?}"
            );
        }
        let detail = crate::test_child::detail_of(&error);
        let (_, fate, _) = crate::test_child::expect_may_have_started_parts(error, writer);

        assert!(fate.not_running(), "{left:?}: {fate:?}");
        // A failed kill leaves the handle armed to try again: the look at the tree when it drops is the
        // armed drop's first act, whatever it then logs. No tree kill is made early over an unvouched tree.
        assert_eq!(drop_looks.seen(), failed, "{left:?}: armed only over a failed kill");
        assert!(detail.starts_with("the elevated child"), "{left:?}: {detail}");
        assert!(
            !detail.contains("its contained tree could not be killed"),
            "{left:?}: {detail}"
        );
        assert_eq!(
            detail.contains("could not be vouched for"),
            !failed,
            "{left:?}: {detail}"
        );
        let warns = warns_since(mark, "");
        let finish_elevated: Vec<_> = warns
            .iter()
            .filter(|warn| warn.starts_with("finish_elevated:"))
            .collect();
        assert_eq!(finish_elevated.len(), 1, "{left:?}: {warns:?}");
        // The cleanup's one warn, and no drop's after it.
        let unvouched = warns
            .iter()
            .filter(|warn| warn.contains("could not be vouched for"))
            .count();
        assert_eq!(unvouched, usize::from(!failed), "{left:?}: {warns:?}");
    }
}

/// A failed spawn's cleanup that hands the root back (its exit was not collected) over a walk that
/// left only the root: an unvouched tree is not a failed kill, so the cleanup makes no early tree
/// kill over it, says once that the tree could not be vouched for, and the handle is disarmed.
///
/// Mutants: the cleanup makes the drop's tree kill early over an unvouched tree and reports it
/// made early or failed too; the warn is not said, or said again by the drop.
#[cfg(target_os = "linux")]
#[skuld::test]
fn finish_elevated_makes_no_early_tree_kill_over_an_unvouched_tree_when_it_hands_the_root_back() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::log_capture::install();
    let (mut child, writer) = crate::test_child::held_treewalk_blocker_leaving(LeftBehind::Root);
    let teardowns = crate::child::owned::seams::record_root_teardowns();
    let mark = crate::log_capture::mark();
    let drop_looks = crate::graceful_hooks::watch_for_a_second_look();
    child.proc.script_over(|f| {
        f.signals([Ok(crate::signal::Sent::Delivered)])
            .reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let detail = crate::test_child::detail_of(&error);
    let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);

    assert!(detail.contains("could not be vouched for"), "{detail}");
    assert!(
        !detail.contains("made early") && !detail.contains("failed too"),
        "{detail}"
    );
    assert!(!drop_looks.seen(), "the handle is disarmed");
    assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
    let warns = warns_since(mark, "");
    let unvouched = warns
        .iter()
        .filter(|warn| warn.contains("could not be vouched for"))
        .count();
    assert_eq!(unvouched, 1, "{warns:?}");
    assert!(
        warns
            .iter()
            .all(|warn| !warn.contains("made early") && !warn.contains("failed too")),
        "{warns:?}"
    );
    handed_back.wait();
}

/// A failed spawn's cleanup whose first tree kill left the root running (its own kill of the root was
/// refused) and whose root was reaped by someone else before the drop's tree kill, made early: that
/// kill finds no root to walk, and the one report says what the first walk found, that it saw the
/// root running, not that "something" was left. The handle is disarmed (the root is handed back).
///
/// Mutants: the kind of the unvouched tree is not the latest fact (the root seen running), so the
/// early tree kill's text names an earlier kill's leftovers instead; the handle stays armed, so its
/// drop says it again.
#[cfg(target_os = "linux")]
#[skuld::test]
fn finish_elevated_names_the_root_the_first_walk_saw_running_when_the_early_tree_kill_finds_it_gone() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::log_capture::install();
    let (mut child, writer) = crate::test_child::held_treewalk_blocker_leaving(LeftBehind::Root);
    let teardowns = crate::child::owned::seams::record_root_teardowns();
    let mark = crate::log_capture::mark();
    // The walk's send of the root's kill goes through this handle: it is answered first, and the
    // cleanup's own kill is the refused one.
    child.proc.script_over(|f| {
        f.signals([Ok(crate::signal::Sent::Delivered), refused()])
            .reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
    });
    // The first walk killed the root (its scripted send does not, so the root is ended here): someone
    // else reaps it before the early tree kill, which finds no root.
    let pid = child.pid();
    let _reaped = crate::child::spawn::fault::set_between_kill_and_wait(move || {
        // SAFETY: `pid` is this test's own child, not yet reaped.
        let killed = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
        assert_eq!(killed, 0, "{}", std::io::Error::last_os_error());
        crate::test_child::wait_until_zombie(pid);
        let mut status = 0;
        // SAFETY: `pid` is this test's own zombie child.
        let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
        assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let cleanup = crate::test_child::cleanup_of(&error);
    let detail = crate::test_child::detail_of(&error);
    let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);

    assert!(
        detail.starts_with("the elevated child could not be terminated"),
        "{detail}"
    );
    assert!(
        !detail.contains("its contained tree could not be killed") && !detail.contains("failed too"),
        "{detail}"
    );
    let found = "the root an earlier walk found running is gone";
    assert!(!detail.contains(found), "{detail}");
    assert!(
        cleanup
            .iter()
            .any(|failure| crate::error::said(&**failure).contains(found)),
        "the early tree kill's answer: {cleanup:?}"
    );
    assert!(!detail.contains("left something running"), "{detail}");
    assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
    let warns = warns_since(mark, "");
    let tree: Vec<_> = warns
        .iter()
        .filter(|warn| warn.starts_with("finish_elevated:"))
        .collect();
    assert_eq!(tree.len(), 1, "{warns:?}");
    assert!(tree[0].contains(found), "{warns:?}");
    // The root was reaped above, so there is nothing for the handed-back child to wait for.
    drop(handed_back);
}

/// A failed spawn's cleanup whose first tree kill left a member that refuses the kill, whose root
/// kill ended the root without collecting its exit (so it is handed back and the drop's tree kill is
/// made early), and whose early tree kill finds the member gone but its walk leaves the root, whose
/// own end the cleanup saw: the early tree kill ends unvouched, not failed. The cleanup's one report
/// says what the first attempt left and that the early tree kill could not vouch for the tree. Needs
/// the `setuid` group: the member is a setuid-root helper.
///
/// Mutant: an early tree kill that ends unvouched is dropped from the report (as a skipped one is).
#[cfg(target_os = "linux")]
#[skuld::test]
fn finish_elevated_reports_an_early_tree_kill_that_ends_unvouched_after_a_member_refused_the_first_kill(
    #[fixture(setuid)] _group: &Group,
) {
    use crate::containment::treewalk::fault::{force_incomplete_once, LeftBehind};
    crate::log_capture::install();
    let (mut child, writer) = crate::test_privilege::root_over_setuid_blockers(1, |cmd| {
        cmd.contain_with(ContainMode::TreeWalk);
    });
    let pid = child.pid();
    let member: u32 = std::fs::read_to_string(format!("/proc/{pid}/task/{pid}/children"))
        .expect("the root lists its children")
        .trim()
        .parse()
        .expect("the root has the one child");
    let teardowns = crate::child::owned::seams::record_root_teardowns();
    let mark = crate::log_capture::mark();
    child.proc.script_over(|f| {
        f.signals([Ok(crate::signal::Sent::Delivered)])
            .reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
    });
    // The first walk killed the root and was refused by the member. Let the member exit, and wait until
    // nothing names it, and make the early tree kill's walk leave the root, before that kill.
    let _released = crate::child::spawn::fault::set_between_kill_and_wait(move || {
        drop(writer);
        while std::path::Path::new(&format!("/proc/{member}")).exists() {
            std::thread::yield_now();
        }
        force_incomplete_once(LeftBehind::Root);
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let detail = crate::test_child::detail_of(&error);
    let (_, _, handed_back) = crate::test_child::expect_handed_back(error, ());

    assert!(!detail.contains("its contained tree could not be killed"), "{detail}");
    assert!(
        detail.contains("; on the drop's tree kill, made early, ") && detail.contains("could not be vouched for"),
        "the early tree kill's answer: {detail}"
    );
    assert!(!detail.contains("failed too"), "{detail}");
    assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
    let warns = warns_since(mark, "");
    let tree: Vec<_> = warns
        .iter()
        .filter(|warn| warn.starts_with("finish_elevated:"))
        .collect();
    assert_eq!(tree.len(), 1, "{warns:?}");
    assert!(
        tree[0].contains("; on the drop's tree kill, made early, ") && tree[0].contains("could not be vouched for"),
        "{warns:?}"
    );
    handed_back.wait();
}

/// A teardown whose walk left only the root, and whose root someone else had reaped when the
/// teardown's kill of it came, does not vouch for the tree: the walk saw the root running. The
/// teardown's own warn says so, and the tree is not marked killed.
///
/// Mutants: the root counts as ended only when this handle's own kill ended it (`Reaped`, `Killed`);
/// the tree is marked killed; the teardown is silent.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_walk_that_left_only_the_root_is_settled_by_a_root_someone_else_reaped() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::log_capture::install();
    let (mut child, writer) = crate::test_child::held_treewalk_blocker_leaving(LeftBehind::Root);
    let mark = crate::log_capture::mark();
    // The walk's send of the root's kill goes through this handle too: it is answered first, and the
    // teardown's own kill is the refused one.
    child.proc.script_over(|f| {
        f.signals([Ok(crate::signal::Sent::Delivered), refused()]).reaps([
            crate::os_process::fake::ReapAnswer::Foreign(crate::os_process::child::Foreign::Gone),
        ])
    });

    let torn = child.tear_down(
        crate::containment::dispatch::TeardownCaller::FailedRun,
        crate::child::owned::teardown::Disposition::Leave,
    );
    child.kill_on_drop = false;

    assert_eq!(torn.fate, crate::error::ChildFate::Gone);
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("could not be vouched for"), "{warns:?}");
    assert!(!warns[0].contains("members"), "{warns:?}");
    assert!(!child.tree.is_killed(), "the walk saw the root running");
    drop(writer);
}

/// A failed spawn's cleanup whose root kill is refused, and whose root still runs, hands the root
/// back in the error and disarms the handle: the caller owns the root now, and the handle's drop does
/// not retry the kill. The cleanup's one warn is the refusal.
///
/// Mutants: the cleanup leaves the handle armed (the drop retries) and drops the root; the root is
/// not handed back.
#[skuld::test]
fn finish_elevated_hands_back_a_root_whose_kill_was_refused() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let teardowns = crate::child::owned::seams::record_root_teardowns();
    let mark = crate::log_capture::mark();
    let fake = child.proc.script_over(|f| f.signals([refused()]));

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let (_, fate, handed_back) = crate::test_child::expect_handed_back(failure.into(), writer);

    assert!(matches!(fate, crate::error::ChildFate::Running { .. }), "{fate:?}");
    assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
    assert_eq!(fake.signal_calls().len(), 1, "the cleanup's kill alone");
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains(&refusal()), "{warns:?}");
    let status = handed_back.wait();
    assert!(status.success(), "the root exits on EOF: {status:?}");
}

/// A failed spawn's cleanup whose root kill is refused and whose look then fails: the root is
/// uncollected and the caller's, so it is handed back and the handle disarmed, though its fate is
/// `Unknown`.
///
/// Mutant: only a `Running` fate hands back (the handle's drop then retries and leaks the root).
#[skuld::test]
fn finish_elevated_hands_back_a_root_whose_kill_was_refused_and_look_failed() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let teardowns = crate::child::owned::seams::record_root_teardowns();
    child.proc.script_over(|f| {
        f.signals([refused()])
            .reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let (_, fate, handed_back) = crate::test_child::expect_handed_back(failure.into(), writer);

    assert_eq!(fate, crate::error::ChildFate::Unknown);
    assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
    let status = handed_back.wait();
    assert!(status.success(), "the root exits on EOF: {status:?}");
}

/// A root whose kill was refused and whose look failed: the look's failure is in the cleanup's one
/// warn and in the error's detail, as the refusal is.
///
/// Mutant: the cleanup keeps the fate of the look and drops its error.
#[skuld::test]
fn finish_elevated_names_the_failure_of_the_look_after_a_refused_kill() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let mark = crate::log_capture::mark();
    child.proc.script_over(|f| {
        f.signals([refused()])
            .reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let cleanup = crate::test_child::cleanup_of(&error);
    let said = crate::test_child::detail_of(&error);
    let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);

    let failed_look = std::io::Error::from(std::io::ErrorKind::Other).to_string();
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(
        warns[0].contains(&format!("the wait failed: {}", crate::error::io_said(&failed_look))),
        "{warns:?}"
    );
    assert!(said.contains("the wait failed"), "{said}");
    assert!(!said.contains(&failed_look) && !said.contains(&refusal()), "{said}");
    let codes: Vec<_> = cleanup
        .iter()
        .map(|failure| crate::error::first_os_code(&**failure))
        .collect();
    assert_eq!(codes, [Some(libc::EPERM), None], "{cleanup:?}");
    assert!(
        matches!(&**cleanup.iter().nth(1).expect("the failed look"), crate::error::Error::Io(e) if e.kind() == std::io::ErrorKind::Other),
        "{cleanup:?}"
    );
    handed_back.wait();
}

/// A root someone else reaped between the delivered kill and its reap is not the cleanup's to hand
/// back: the error carries no child, and the handle is disarmed.
///
/// Mutant: a failed wait hands the root back whatever failed it.
#[skuld::test]
fn finish_elevated_hands_back_nothing_when_the_root_was_reaped_elsewhere_after_the_kill() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let teardowns = crate::child::owned::seams::record_root_teardowns();
    child.proc.script_over(|f| {
        f.signals([Ok(crate::signal::Sent::Delivered)])
            .reaps([crate::os_process::fake::ReapAnswer::Foreign(
                crate::os_process::child::Foreign::Gone,
            )])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(failure.into(), writer);

    assert_eq!(fate, crate::error::ChildFate::Killed);
    assert!(handed_back.is_none(), "a root reaped elsewhere is not handed back");
    assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
}

/// A root whose reap someone else made after the kill is not a failed kill or reap: the cleanup says
/// so at `debug` (principle 5) and warns of nothing.
///
/// Mutant: the cleanup lists the foreign reap among the leftovers, which the one warn reports.
#[skuld::test]
fn finish_elevated_logs_a_root_reaped_elsewhere_after_the_kill_at_debug() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let mark = crate::log_capture::mark();
    child.proc.script_over(|f| {
        f.signals([Ok(crate::signal::Sent::Delivered)])
            .reaps([crate::os_process::fake::ReapAnswer::Foreign(
                crate::os_process::child::Foreign::Gone,
            )])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let (_, _, handed_back) = crate::test_child::expect_may_have_started_parts(failure.into(), writer);

    assert!(handed_back.is_none());
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
    let debug = crate::log_capture::records_since_on_current_thread(mark, "reaped by someone else");
    assert!(
        debug.len() == 1 && debug[0].0 == log::Level::Debug,
        "one debug record names the foreign reap: {debug:?}"
    );
}

/// A root whose kill was refused and which someone else had reaped when the look came: nothing is
/// handed back, `debug` says so, and the refusal stays in the debug line and in the error.
///
/// Mutant: the refusal's note is replaced by the wording of the foreign reap, which has no
/// refusal in it.
#[skuld::test]
fn finish_elevated_keeps_the_refusal_when_the_look_finds_the_root_reaped_elsewhere() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let mark = crate::log_capture::mark();
    child.proc.script_over(|f| {
        f.signals([refused()])
            .reaps([crate::os_process::fake::ReapAnswer::Foreign(
                crate::os_process::child::Foreign::Gone,
            )])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let cleanup = crate::test_child::cleanup_of(&error);
    let detail = crate::test_child::detail_of(&error);
    let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, writer);

    assert_eq!(fate, crate::error::ChildFate::Gone);
    assert!(handed_back.is_none());
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
    assert!(
        detail.contains("could not be terminated: reaped by someone else"),
        "{detail}"
    );
    assert_eq!(
        crate::error::first_os_code(&**cleanup.first()),
        Some(libc::EPERM),
        "{cleanup:?}"
    );
    let debug = crate::log_capture::records_since_on_current_thread(mark, "reaped by someone else");
    assert!(
        debug.len() == 1 && debug[0].0 == log::Level::Debug && debug[0].1.contains(&refusal()),
        "{debug:?}"
    );
}

/// A root whose kill was refused and whose zombie launchd held when the look came (macOS): the one
/// warn and the error's note both say it is not ours to reap, and both keep the refusal.
///
/// Mutants: the launchd line replaces the refusal in the warn; or in the error's note.
#[skuld::test]
fn finish_elevated_keeps_the_refusal_when_the_look_finds_launchd_holding_the_root() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let mark = crate::log_capture::mark();
    child.proc.script_over(|f| {
        f.signals([refused()])
            .reaps([crate::os_process::fake::ReapAnswer::Foreign(
                crate::os_process::child::Foreign::Orphaned,
            )])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let cleanup = crate::test_child::cleanup_of(&error);
    let detail = crate::test_child::detail_of(&error);
    let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, writer);

    assert_eq!(fate, crate::error::ChildFate::Gone);
    assert!(handed_back.is_none());
    assert_eq!(
        crate::error::first_os_code(&**cleanup.first()),
        Some(libc::EPERM),
        "{cleanup:?}"
    );
    let clause = "could not be terminated: not ours to reap (launchd";
    let reported = format!(
        "could not be terminated ({}): not ours to reap (launchd",
        crate::error::io_said(refusal())
    );
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains(&reported), "{warns:?}");
    assert!(detail.contains(clause), "{detail}");
}

/// A root a delivered kill reached whose zombie launchd held when the wait came (macOS): the one
/// warn says it is not ours to reap, led by the root's name, and the root is `Killed`.
///
/// Mutant: the launchd line is not led by the root's name.
#[skuld::test]
fn finish_elevated_names_the_root_when_launchd_holds_it_after_a_delivered_kill() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let pid = child.pid();
    let mark = crate::log_capture::mark();
    child.proc.script_over(|f| {
        f.signals([Ok(crate::signal::Sent::Delivered)])
            .reaps([crate::os_process::fake::ReapAnswer::Foreign(
                crate::os_process::child::Foreign::Orphaned,
            )])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let detail = crate::test_child::detail_of(&error);
    let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(error, writer);

    assert_eq!(fate, crate::error::ChildFate::Killed);
    assert!(handed_back.is_none());
    let clause = format!("the elevated child pid {pid}: not ours to reap (launchd");
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains(&clause), "{warns:?}");
    assert!(detail.contains(&clause), "{detail}");
}

/// A failed spawn's cleanup whose reap fails after a delivered kill: the root is not shown
/// collected, so it is handed back and the handle is disarmed, and the handle's drop does not retry.
///
/// Mutant: the cleanup leaves the handle armed and drops the root (a retry that fails leaks it).
#[skuld::test]
fn finish_elevated_hands_back_a_root_whose_reap_failed_after_a_delivered_kill() {
    crate::log_capture::install();
    let (mut child, writer) = bare_blocker();
    let teardowns = crate::child::owned::seams::record_root_teardowns();
    let mark = crate::log_capture::mark();
    // The kill is scripted as delivered and sends nothing: the root exits when released, below.
    let fake = child.proc.script_over(|f| {
        f.signals([Ok(crate::signal::Sent::Delivered)])
            .reaps([crate::os_process::fake::ReapAnswer::Err(std::io::ErrorKind::Other)])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let (_, fate, handed_back) = crate::test_child::expect_handed_back(failure.into(), writer);

    assert_eq!(fate, crate::error::ChildFate::Killed);
    assert_eq!(teardowns.count(), 0, "the handle is disarmed: its drop does not retry");
    assert_eq!(fake.signal_calls().len(), 1, "the cleanup's kill alone");
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(
        warns[0].contains("the elevated child pid")
            && warns[0].contains(": the wait failed: ")
            && warns[0].ends_with("handed back to the caller in the error"),
        "{warns:?}"
    );
    let status = handed_back.wait();
    assert!(status.success(), "the root exits on EOF: {status:?}");
}

/// A child in a stand-in cgroup leaf whose first `cgroup.kill` write fails (a write to a directory),
/// with the write end of its stdin, the leaf's path and its `cgroup.kill`. The leaf's own `Drop` is
/// disarmed, so only the handle's drop may make the tree kill again. The directory is returned to outlive them.
#[cfg(target_os = "linux")]
fn child_in_a_leaf_whose_kill_fails() -> (
    crate::Child,
    crate::PipeWriter,
    std::path::PathBuf,
    std::path::PathBuf,
    tempfile::TempDir,
) {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-retry-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    std::fs::write(leaf_path.join("occupant"), "").expect("keep the leaf unremovable");
    let kill_file = leaf_path.join("cgroup.kill");
    std::fs::create_dir(&kill_file).expect("make cgroup.kill a directory");
    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 = crate::child::spawn::spawn_uncommitted(&mut cmd, crate::child::spawn::policy::SpawnPolicy::SYNC)
        .expect("spawn");
    child.tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(
        crate::containment::cgroup::test_support::entered_leaf_at(leaf_path.clone()),
    ));
    child.tree.disarm().expect("disarm");
    (child, writer, leaf_path, kill_file, dir)
}

/// A tree kill that fails in a cleanup that then kills the root: the tree is not settled, so the
/// handle stays armed, and its drop writes the kill again. The drop's kill fails again with what the
/// cleanup already warned of, so the drop's record is `debug`, and the cleanup's is the one warn.
///
/// Mutant: the drop's report warns again of what the cleanup warned of.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_retry_that_only_repeats_the_cleanups_warn_is_debug() {
    use crate::child::spawn::fault;

    crate::log_capture::install();
    let (child, writer, leaf_path, _kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
    // The root is released once killed: a kill that sent nothing exits 0.
    let reaps = fault::record_teardown_reaps();
    let _hook = fault::set_between_kill_and_wait(move || drop(writer));
    let mark = crate::log_capture::mark();

    let err = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    drop(err);

    reaps.assert_killed();
    let marker = crate::child::spawn::teardown_warn_marker(&leaf_path);
    assert_eq!(
        crate::log_capture::levels_since(mark, &marker),
        [log::Level::Warn],
        "the cleanup's warn is the only one"
    );
    let drop_records = crate::log_capture::records_since_on_current_thread(mark, "Child::drop:");
    assert!(
        drop_records
            .iter()
            .any(|(level, text)| *level == log::Level::Debug && text.contains("contained-tree teardown")),
        "the drop made its tree kill and said so at debug: {drop_records:?}"
    );
}

/// A tree kill that fails once, in a cleanup that then kills the root: the tree is not settled, so
/// the handle stays armed and its drop writes the kill again, now that it can succeed. The failed
/// kill is the one warn.
///
/// Mutant: the cleanup disarms the handle whatever became of the tree.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_tree_kill_is_followed_by_the_drops_own_tree_kill() {
    use crate::child::spawn::fault;

    crate::log_capture::install();
    let (child, writer, leaf_path, kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
    // The failure ends once the root is killed: the drop's tree kill finds a file it can write. The
    // root is released there too: a kill that sent nothing exits 0.
    let reaps = fault::record_teardown_reaps();
    let healed = kill_file.clone();
    let _hook = fault::set_between_kill_and_wait(move || {
        std::fs::remove_dir(&healed).expect("remove the directory");
        std::fs::write(&healed, b"").expect("create cgroup.kill");
        drop(writer);
    });
    let mark = crate::log_capture::mark();

    let err = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");

    assert_eq!(
        std::fs::read(&kill_file).expect("read cgroup.kill"),
        crate::containment::cgroup::KILL_PAYLOAD,
        "the handle's drop must make its tree kill ({err:?})"
    );
    assert_eq!(
        crate::log_capture::levels_since(mark, &crate::child::spawn::teardown_warn_marker(&leaf_path)),
        [log::Level::Warn],
        "the failed kill is reported once, and the drop's tree kill adds nothing"
    );
    reaps.assert_killed();
}

/// A tree kill that fails in a cleanup whose root kill is refused: the root is handed back and the
/// handle disarmed, so no drop makes the tree kill. The cleanup makes the drop's tree kill, early,
/// before it hands the root back.
///
/// Mutant: the cleanup hands the root back without making the drop's tree kill after a failed one.
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_drops_tree_kill_is_made_early_when_a_failed_one_precedes_a_handed_back_root() {
    use crate::child::spawn::fault;

    crate::log_capture::install();
    let (mut child, writer, _leaf_path, kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
    child.proc.script_over(|f| f.signals([refused()]));
    // The failure ends once the root's kill is refused: the early tree kill finds a file it can write.
    let healed = kill_file.clone();
    let _hook = fault::set_between_kill_and_wait(move || {
        std::fs::remove_dir(&healed).expect("remove the directory");
        std::fs::write(&healed, b"").expect("create cgroup.kill");
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let (_, fate, handed_back) = crate::test_child::expect_handed_back(failure.into(), writer);

    assert!(matches!(fate, crate::error::ChildFate::Running { .. }), "{fate:?}");
    assert_eq!(
        std::fs::read(&kill_file).expect("read cgroup.kill"),
        crate::containment::cgroup::KILL_PAYLOAD,
        "the cleanup must make the drop's tree kill"
    );
    handed_back.wait();
}

/// The drop's tree kill, made early, that killed the tree is not reported as a failed teardown: the
/// one warn says the early kill was needed and names the first failure, and the error does not say
/// the tree was not killed.
///
/// Mutant: the warn keeps the first failure's text, or the error keeps its note.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_tree_kill_that_worked_when_made_early_is_reported_as_such_not_as_a_failure() {
    use crate::child::spawn::fault;

    crate::log_capture::install();
    let (mut child, writer, leaf_path, kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
    child.proc.script_over(|f| f.signals([refused()]));
    let healed = kill_file.clone();
    let _hook = fault::set_between_kill_and_wait(move || {
        std::fs::remove_dir(&healed).expect("remove the directory");
        std::fs::write(&healed, b"").expect("create cgroup.kill");
    });
    let mark = crate::log_capture::mark();

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let detail = crate::test_child::detail_of(&error);
    let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);

    let first = std::io::Error::from_raw_os_error(libc::EISDIR).to_string();
    let warns = warns_since(mark, "");
    let warn = warns
        .iter()
        .find(|warn| warn.contains(&leaf_path.display().to_string()))
        .unwrap_or_else(|| panic!("no warn names the tree: {warns:?}"));
    assert!(
        warn.contains("needed the drop's tree kill, made early") && warn.contains(&first),
        "the warn says the early tree kill was needed, after: {first}: {warn}"
    );
    assert!(
        !warn.contains(crate::child::spawn::TREE_TEARDOWN_WARN),
        "the tree was killed: {warn}"
    );
    assert!(
        detail.starts_with("the elevated child could not be terminated") && !detail.contains("could not be killed"),
        "the error blames no tree: {detail}"
    );
    handed_back.wait();
}

/// The drop's tree kill, made early, that fails too puts its error in the one warn and in the error,
/// after the first's.
///
/// Mutant: the early kill's error is dropped.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_tree_kill_that_failed_when_made_early_too_names_both_failures() {
    crate::log_capture::install();
    let (mut child, writer, leaf_path, _kill_file, _dir) = child_in_a_leaf_whose_kill_fails();
    child.proc.script_over(|f| f.signals([refused()]));
    // The first write fails with `EIO`, the early tree kill's with `EISDIR` (`cgroup.kill` is a
    // directory).
    let _first = crate::containment::cgroup::fault::fail_next_kill_write();
    let mark = crate::log_capture::mark();

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let cleanup = crate::test_child::cleanup_of(&error);
    let detail = crate::test_child::detail_of(&error);
    let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);

    let first = std::io::Error::from_raw_os_error(libc::EIO).to_string();
    let early = std::io::Error::from_raw_os_error(libc::EISDIR).to_string();
    let warns = warns_since(mark, "");
    let warn = warns
        .iter()
        .find(|warn| warn.contains(&leaf_path.display().to_string()))
        .unwrap_or_else(|| panic!("no warn names the tree: {warns:?}"));
    // The warn says the early kill through `Report`. A failed `cgroup.kill` is a `Containment`
    // over the OS error, which `Report` prints whole.
    let report = format!(
        "the drop's tree kill, made early, failed too (process containment failed: the kernel refused the \
         write of {}/cgroup.kill: {})",
        leaf_path.display(),
        crate::error::io_said(&early)
    );
    assert!(
        detail.starts_with("the elevated child could not be terminated"),
        "{detail}"
    );
    assert!(
        !detail.contains("failed too") && !detail.contains("its contained tree could not be killed"),
        "{detail}"
    );
    assert!(
        !detail.contains(&first) && !detail.contains(&early),
        "a failure is in the text: {detail}"
    );
    let codes: Vec<_> = cleanup
        .iter()
        .map(|failure| crate::error::first_os_code(&**failure))
        .collect();
    assert_eq!(
        codes,
        [Some(libc::EIO), Some(libc::EPERM), Some(libc::EISDIR)],
        "the first tree kill's failure, the root's refusal, the early one's: {cleanup:?}"
    );
    assert!(warn.contains(&first), "the first failure: {warn}");
    assert!(warn.contains(&report), "the early kill's Report: {warn}");
    handed_back.wait();
}

/// A tree kill skipped because the root's state is unknown, and a root whose kill is refused and
/// which is handed back: the early tree kill skips again and kills nothing, so the error still says
/// the tree was not killed. The tree is a process group named by the root's number, which an unknown
/// root skips where the root's pidfd cannot name it (below Linux 6.9, refused here). A `TreeWalk` does
/// not skip on Linux: its walk proves its root itself.
///
/// Linux only: a macOS root holds its fd marker whatever the mode, and the skipped kill still sweeps
/// the marker's holders by identity, so the root is dead before its refused kill and nothing is
/// handed back.
///
/// Mutant: the early kill's `Ok` clears the note whether or not it killed the tree.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_skipped_tree_kill_keeps_its_note_when_the_root_is_handed_back() {
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::log_capture::install();
    let (mut child, writer) = contained_blocker(ContainMode::Session);
    child.proc.script_over(|f| {
        f.peeks([Err(std::io::Error::other("forced peek failure"))])
            .signals([refused()])
    });

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let detail = crate::test_child::detail_of(&error);
    let (_, _, handed_back) = crate::test_child::expect_handed_back(error, writer);

    assert!(
        detail.contains("its contained tree was not killed"),
        "nothing killed the tree: {detail}"
    );
    handed_back.wait();
}

/// A tree kill skipped because the root's state is unknown has not killed the tree: a failed spawn's
/// cleanup leaves the handle armed, so its drop tries again. A killed root does not change that.
///
/// Mutant: a skipped kill marks the tree killed, which disarms the handle.
#[skuld::test]
fn finish_elevated_leaves_the_handle_armed_after_a_skipped_tree_kill() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::log_capture::install();
    let (mut child, writer) = contained_blocker(ContainMode::Session);
    child
        .proc
        .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
    let mark = crate::log_capture::mark();

    let failure = crate::child::spawn::finish_elevated(child, failed_write()).expect_err("the spawn fails");
    let error = crate::error::Error::from(failure);
    let detail = crate::test_child::detail_of(&error);
    let (_, _, _) = crate::test_child::expect_may_have_started_parts(error, writer);

    assert!(
        detail.contains("its contained tree was not killed"),
        "nothing killed the tree: {detail}"
    );
    // An armed handle's drop looks at the tree again, at `debug` at least; a disarmed one says nothing.
    let drops = crate::log_capture::records_since_on_current_thread(mark, "Child::drop:");
    assert!(!drops.is_empty(), "the handle was disarmed by a kill that did not run");
}

/// A drop that skipped the tree kill (the root's state is unknown) has not killed the tree, so it
/// does not mark it.
///
/// Mutant: `settle` marks the tree killed for a kill that was skipped.
#[skuld::test]
fn a_teardown_that_skipped_the_tree_kill_does_not_mark_the_tree_killed() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::log_capture::install();
    let (mut child, writer) = contained_blocker(ContainMode::Session);
    child
        .proc
        .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));

    let torn = child.tear_down(
        crate::containment::dispatch::TeardownCaller::FailedRun,
        crate::child::owned::teardown::Disposition::Leave,
    );

    assert!(torn.fate.not_running(), "{:?}", torn.fate);
    assert!(!child.tree.is_killed(), "a skipped kill does not mark the tree killed");
    drop(writer);
}

/// A handle that could not say, when the root's number shows it reaped: the doubt is not dropped
/// silently. The `debug` record names the caller and the handle's error.
///
/// Mutant: `DropView::read` discards the handle's `Unknown` once the number shows the reap.
#[skuld::test]
fn a_handle_that_could_not_say_is_logged_when_the_number_shows_the_reap() {
    crate::log_capture::install();
    let (mut child, _writer) = contained_blocker(ContainMode::Session);
    let mark = crate::log_capture::mark();
    let _number = crate::child::fault::force_next_root_read(crate::identity::Resolved::Gone);
    let fake = child
        .proc
        .script_over(|f| f.peeks([Err(std::io::Error::other("handle doubt 6e2"))]));

    let view = crate::containment::DropView::read(
        crate::containment::dispatch::TeardownCaller::FailedRun,
        child.pid(),
        child.id,
        || child.proc.state(),
        &child.tree,
    );

    fake.assert_peeks_exhausted();
    assert!(
        matches!(view.root, crate::signal::RootState::Reaped { .. }),
        "{:?}",
        view.root
    );
    let records = crate::log_capture::records_since_on_current_thread(mark, "handle doubt 6e2");
    assert_eq!(records.len(), 1, "{records:?}");
    assert!(
        records[0].0 == log::Level::Debug && records[0].1.starts_with("teardown after a failed run:"),
        "{records:?}"
    );
}

/// The kill decides on the look the report is worded from: a handle that could not say, whose
/// number shows the reap, is `Reaped` to the mechanism too, not the handle's raw `Unknown`.
///
/// Mutant: `DropView::look` answers the handle's own state, before the number's evidence.
#[skuld::test]
fn the_look_a_kill_decides_on_is_the_one_the_report_is_worded_from() {
    let (mut child, _writer) = contained_blocker(ContainMode::Session);
    let _number = crate::child::fault::force_next_root_read(crate::identity::Resolved::Gone);
    let fake = child
        .proc
        .script_over(|f| f.peeks([Err(std::io::Error::other("handle doubt 7a1"))]));

    let view = crate::containment::DropView::read(
        crate::containment::dispatch::TeardownCaller::Drop,
        child.pid(),
        child.id,
        || child.proc.state(),
        &child.tree,
    );

    fake.assert_peeks_exhausted();
    assert!(view.leaves_root_alone());
    assert!(
        matches!(view.look(), crate::signal::RootState::Reaped { .. }),
        "{:?}",
        view.look()
    );
}

/// A trusted root's number is never untrusted, so nothing asks why: the answer would be a lie. A
/// debug build asserts it.
///
/// Mutant: the `Trusted` arm answers "already reaped".
#[cfg(debug_assertions)] // the contract is a debug assertion: release has none to trigger
#[skuld::test]
fn asking_why_a_trusted_root_is_untrusted_is_a_contract_breach() {
    let view = crate::containment::DropView {
        caller: crate::containment::dispatch::TeardownCaller::Drop,
        root_pid: 1,
        root: crate::signal::RootState::Unreaped,
        tree_killed: false,
    };

    let asked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| view.why_number_untrusted()));

    assert!(asked.is_err(), "a trusted root has no untrusted number to explain");
}