cosca 0.7.0

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

use crate::child::spawn::fault::{release_between_kill_and_wait, TeardownBlocker};
use crate::containment::treewalk::fault::record_walks;
use crate::containment::unix::fault::{record_kill_group, record_term_group};
use crate::send_log::Capture;
use crate::signal::Sig;
use crate::test_child::Console;
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, Group};
use crate::tokio::child::drop_fault;
use crate::tokio::Command;
use crate::{ContainMode, Containment};

/// Every record of the drop's warn starts with this. It is the sync drop's wording verbatim.
const WARN: &str = "Child::drop: the root is already reaped";

/// What `ContainMode::Session` resolves to here: macOS puts every mode but `TreeWalk` behind an fd
/// marker that also carries the group; elsewhere it is a bare process group.
#[cfg(target_os = "macos")]
const SESSION_CONTAINMENT: Containment = Containment::FdMarker;
#[cfg(not(target_os = "macos"))]
const SESSION_CONTAINMENT: Containment = Containment::Session;

fn session(argv: &[&str]) -> Command {
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(argv.iter().copied());
    cmd.contain_with(ContainMode::Session);
    cmd
}

/// A session-contained [`BLOCKER_ARGV`](crate::test_child::BLOCKER_ARGV) command with piped stdin.
/// A test that kills it takes the writer and drops it only after the kill: dropping the writer is
/// the only way for the blocker to end on its own (status 0), so a `kill` that sent nothing fails the
/// assertion on how the root ended, instead of leaving a wait unbounded.
fn session_blocker_cmd() -> Command {
    let mut cmd = session(crate::test_child::BLOCKER_ARGV);
    cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
    cmd
}

/// What the drop did to a [`session_blocker_cmd`] root `pid`, once the drop has run: `teardown`
/// released its stdin once the drop's kill returned, so a root nothing killed exited `0` and the drop
/// reaped it. The reap must show the drop's kill, and `sends` (logged after the syscall) must hold
/// the `SIGKILL` to `pid`.
#[track_caller]
fn assert_the_drop_killed(teardown: &TeardownBlocker, sends: &Capture, pid: u32) {
    teardown.assert_killed();
    assert!(
        sends.sent(pid, Sig::Kill),
        "the drop must send the root SIGKILL: {:?}",
        sends.entries()
    );
}

fn drop_warns_since(mark: usize) -> Vec<(log::Level, String)> {
    crate::log_capture::records_since_on_current_thread(mark, WARN)
}

/// Mutants: the drop still calls `hard_kill`; `root_reaped` is always false; no warn; the warn
/// without the pgid.
#[skuld::test]
async fn dropping_a_waited_on_process_group_child_sends_no_killpg_and_warns_with_the_pgid() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let root = drop_fault::record();
    let mut child = session(&["true"]).spawn().expect("spawn");
    assert_eq!(child.containment(), SESSION_CONTAINMENT);
    let pid = child.pid();
    child.wait().await.expect("reap the root");

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(
        recorder.killed(),
        Vec::<i32>::new(),
        "a reaped root's number may name another group: no killpg"
    );
    assert_eq!(
        (root.kills(), root.forgets()),
        (0, 0),
        "tokio reaped it; nothing is left to do"
    );
    let warns = drop_warns_since(mark);
    assert_eq!(warns.len(), 1, "exactly one warn, got {warns:?}");
    let (level, text) = &warns[0];
    assert_eq!(*level, log::Level::Warn);
    assert!(text.contains(&format!("pgid {pid}")), "the warn names the pgid: {text}");
    assert!(
        text.contains("kill_tree()") && text.contains("wait()"),
        "the warn says how to end descendants: {text}"
    );
}

/// The warn is for the skip only. Mutant: the reaped test is inverted or dropped, so a running
/// root is skipped too.
#[skuld::test]
async fn dropping_a_running_process_group_child_still_kills_the_group_and_does_not_warn() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let root = drop_fault::record();
    let mut child = session_blocker_cmd().spawn().expect("spawn");
    let teardown = release_between_kill_and_wait(child.stdin().expect("stdin pipe"));
    let pid = child.pid();

    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    drop(child);

    recorder.assert_killed_only(pid as i32);
    assert_eq!((root.kills(), root.forgets()), (1, 0));
    assert_eq!(drop_warns_since(mark), []);
    assert_the_drop_killed(&teardown, &sends, pid);
}

/// A root that exited but is not reaped is a zombie: it still pins its group number, so the group
/// kill is safe. Mutant: reaped judged with `try_wait`, which reaps the zombie and then skips.
#[skuld::test]
async fn dropping_an_exited_but_unreaped_process_group_child_still_kills_the_group() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let mut child = session_blocker_cmd().spawn().expect("spawn");
    let stdin = child.stdin().expect("stdin pipe");
    let pid = child.pid();
    child.kill().expect("kill the root");
    drop(stdin);
    crate::test_child::assert_zombie_sigkilled("the root", pid);

    let mark = crate::log_capture::mark();
    drop(child);

    recorder.assert_killed_only(pid as i32);
    assert_eq!(drop_warns_since(mark), []);
}

/// A `TreeWalk` names its tree by ppid edges from the root's number, which after the reap belong to
/// whoever reused it: the drop walks nothing and warns naming the root. Mutant: the reaped
/// `TreeWalk` still walks.
#[skuld::test]
async fn dropping_a_waited_on_tree_walk_child_walks_nothing_and_warns_with_the_root_pid() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let walks = record_walks();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(["true"]);
    cmd.contain_with(ContainMode::TreeWalk);
    let mut child = cmd.spawn().expect("spawn");
    let pid = child.pid();
    child.wait().await.expect("reap the root");

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(
        walks.walked(),
        Vec::<u32>::new(),
        "a reaped root's number names no tree"
    );
    let warns = drop_warns_since(mark);
    assert_eq!(warns.len(), 1, "exactly one warn, got {warns:?}");
    assert_eq!(warns[0].0, log::Level::Warn);
    assert!(
        warns[0].1.contains(&format!("root pid {pid}")),
        "the warn names the root: {warns:?}"
    );
}

/// Positive control for the recorder above: a running `TreeWalk` root is walked, and nothing is
/// warned.
#[skuld::test]
async fn dropping_a_running_tree_walk_child_walks_from_its_pid_and_does_not_warn() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let walks = record_walks();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
    cmd.contain_with(ContainMode::TreeWalk);
    let mut child = cmd.spawn().expect("spawn");
    let teardown = release_between_kill_and_wait(child.stdin().expect("stdin pipe"));
    let pid = child.pid();

    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    drop(child);

    // A macOS fd marker walks on every pass of its sweep, so more than once is fine.
    let walked = walks.walked();
    assert!(!walked.is_empty() && walked.iter().all(|w| *w == pid), "{walked:?}");
    assert_eq!(drop_warns_since(mark), []);
    assert_the_drop_killed(&teardown, &sends, pid);
}

/// A root reaped by someone else is invisible to tokio's own state (it stays `Running` until
/// polled), so the drop reads the root's number too, as the sync drop does. Mutant: tokio's drop
/// takes only its own state.
#[skuld::test]
async fn dropping_a_foreign_reaped_process_group_child_sends_no_killpg() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let root = drop_fault::record();
    let child = foreign_reaped(session_blocker_cmd());

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(recorder.killed(), Vec::<i32>::new());
    assert_eq!(
        (root.kills(), root.forgets()),
        (0, 1),
        "the number may belong to another child by now: no kill, and tokio's `Child` is forgotten so \
         its own drop cannot reap by pid"
    );
    // The drop also forgot tokio's `Child`, so the one warn leads with that and carries the skip.
    let warns =
        crate::log_capture::records_since_on_current_thread(mark, "the root is already reaped, so this drop does not");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].1.contains("leaks"), "{warns:?}");
}

/// A spawned blocker whose root something else (the application's own `waitpid`) has reaped,
/// while the handle still reads it as running.
fn foreign_reaped(mut cmd: Command) -> crate::tokio::Child {
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("stdin pipe");
    let pid = child.pid();
    child.kill().expect("kill the root");
    drop(stdin);
    crate::test_child::assert_zombie_sigkilled("the root", pid);
    let mut status = 0;
    // SAFETY: `pid` is this test's own zombie child. This plays the application that reaps it.
    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());
    child
}

/// A disarmed drop signals nothing, but tokio's own `Child` drop still `try_wait`s the root's
/// number, so a foreign reap must forget it there too. Mutant: the foreign-reap check runs only
/// under `kill_on_drop`.
#[skuld::test]
async fn a_detached_drop_after_a_foreign_reap_forgets_tokios_child() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let root = drop_fault::record();
    let backend_drops = crate::tokio::child::fault::count_backend_drops();
    let mut child = foreign_reaped(session_blocker_cmd());
    child.detach().expect("detach");
    drop(child);
    assert_eq!(
        (root.kills(), root.forgets(), backend_drops.get()),
        (0, 1, 0),
        "a detached drop must not run tokio's `Child` drop, which reaps by the reused number"
    );
}

/// The same through the command's opt-out. Mutant: as above.
#[skuld::test]
async fn a_kill_on_drop_false_drop_after_a_foreign_reap_forgets_tokios_child() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let root = drop_fault::record();
    let backend_drops = crate::tokio::child::fault::count_backend_drops();
    let mut cmd = session_blocker_cmd();
    cmd.kill_on_drop(false);
    let child = foreign_reaped(cmd);
    drop(child);
    assert_eq!((root.kills(), root.forgets(), backend_drops.get()), (0, 1, 0));
}

/// The skip is quiet once this handle has already hard-killed the tree. Mutant: the tree-killed
/// flag is ignored.
#[skuld::test]
async fn drop_after_kill_tree_and_wait_skips_at_debug_and_does_not_warn() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let mut child = session(&["true"]).spawn().expect("spawn");
    let pid = child.pid();
    child.kill_tree().expect("kill_tree");
    child.wait().await.expect("reap the root");
    recorder.assert_killed_only(pid as i32);
    let sent = recorder.killed();

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(recorder.killed(), sent, "the drop sends no further killpg");
    assert_skipped_at_debug(mark);
}

/// `graceful_shutdown_tree` sweeps with `kill_tree` and reaps the root, so its drop is quiet too.
///
/// The root's stdin is released via `release_at` after `terminate_tree` returns; a `terminate_tree`
/// that sent nothing yields status 0 and fails the status assertion.
#[skuld::test]
async fn drop_after_graceful_shutdown_tree_skips_at_debug_and_does_not_warn() {
    use std::os::unix::process::ExitStatusExt as _;
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let mut child = session_blocker_cmd().spawn().expect("spawn");
    let stdin = child.stdin().expect("stdin pipe");
    let pid = child.pid();
    let _release = crate::graceful_hooks::release_at(crate::graceful_hooks::HookPoint::AfterTerminate, stdin);
    let status = child
        .graceful_shutdown_tree(std::time::Duration::from_secs(60))
        .await
        .expect("graceful_shutdown_tree");
    assert_eq!(
        status.signal(),
        Some(libc::SIGTERM),
        "the root dies to the group's SIGTERM: {status:?}"
    );
    recorder.assert_killed_only(pid as i32);

    let mark = crate::log_capture::mark();
    drop(child);

    assert_skipped_at_debug(mark);
}

/// A failed elevated spawn's cleanup kills the tree, then kills the root, waits for its exit and
/// collects it, so that `Reaped` is true of the fate it reports. The handle then drops with its root
/// reaped and its tree already killed: the drop skips the group kill, at `debug`, and warns of
/// nothing. Mutant: a skip decided on anything but the reaped root.
#[skuld::test]
async fn a_failed_elevated_spawns_cleanup_drops_its_handle_without_a_warn() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let mut child = session_blocker_cmd().spawn().expect("spawn");
    // Released once the cleanup's root kill returned, before its reap.
    let stdin = child.stdin().expect("piped stdin");
    let teardown = crate::child::spawn::fault::release_between_kill_and_wait(stdin);
    let pid = child.pid();

    let mark = crate::log_capture::mark();
    let (err, fate) = crate::tokio::spawn::finish_elevated(
        child,
        Err(crate::error::Error::Io(std::io::Error::other("no password"))),
    )
    .expect_err("the password write failed")
    .expect_may_have_started_with();

    assert!(matches!(err, crate::error::Error::Elevation { .. }), "{err:?}");
    assert_eq!(
        fate,
        crate::error::ChildFate::Reaped,
        "the group's kill and the root's reap"
    );
    recorder.assert_killed_only(pid as i32);
    teardown.assert_killed();
    // The cleanup disarmed the handle (tree and root settled), so its drop reads nothing and logs
    // nothing: not a warn, and not a skip record either.
    assert_eq!(drop_warns_since(mark), []);
}

/// A blocker root, killed and then waited for, so that only `wait()` marks tokio's state.
async fn waited_on_blocker_root() -> crate::tokio::Child {
    let mut child = session_blocker_cmd().spawn().expect("spawn");
    let stdin = child.stdin().expect("stdin pipe");
    child.kill().expect("kill the root");
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().await.expect("reap the root"));
    child
}

/// Tokio's own reaped state is enough when the number's read is refused (`Unknown`). Mutant: the
/// drop takes only the number's read.
#[skuld::test]
async fn dropping_a_waited_on_child_whose_number_reads_unknown_still_sends_no_killpg() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let root = drop_fault::record();
    let child = waited_on_blocker_root().await;
    let _unknown = crate::child::fault::force_next_root_read(crate::identity::Resolved::Unknown);

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(recorder.killed(), Vec::<i32>::new());
    assert_eq!((root.kills(), root.forgets()), (0, 0));
    assert_eq!(drop_warns_since(mark).len(), 1);
}

/// With tokio's state not reaped, an `Unknown` read means "not known to be reaped": the drop kills.
/// Mutant: `Unknown` is treated as reaped.
#[skuld::test]
async fn dropping_an_unreaped_child_whose_number_reads_unknown_kills_and_logs_the_failed_read() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let root = drop_fault::record();
    let mut child = session_blocker_cmd().spawn().expect("spawn");
    let teardown = release_between_kill_and_wait(child.stdin().expect("stdin pipe"));
    let pid = child.pid();
    let _unknown = crate::child::fault::force_next_root_read(crate::identity::Resolved::Unknown);

    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    drop(child);

    recorder.assert_killed_only(pid as i32);
    assert_eq!((root.kills(), root.forgets()), (1, 0));
    assert_eq!(drop_warns_since(mark), []);
    let reads = crate::log_capture::records_since_on_current_thread(mark, "could not be read");
    assert_eq!(reads.len(), 1, "{reads:?}");
    assert_eq!(reads[0].0, log::Level::Debug);
    assert_the_drop_killed(&teardown, &sends, pid);
}

/// A `kill_tree` that failed may have left members running, so the drop still warns. Mutant: the
/// tree-killed flag is set on the attempt.
#[skuld::test]
async fn drop_after_a_failed_kill_tree_and_wait_still_warns() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    recorder.fail_with_unassessable();
    let mut child = session(&["true"]).spawn().expect("spawn");
    child.kill_tree().expect_err("the forced refusal");
    child.wait().await.expect("reap the root");

    let mark = crate::log_capture::mark();
    drop(child);

    let records = drop_warns_since(mark);
    assert_eq!(records.len(), 1, "{records:?}");
    assert_eq!(records[0].0, log::Level::Warn);
}

/// A `terminate_tree` is a request, not a kill, so a root reaped after it still leaves the drop
/// unable to vouch for the group, and it warns (below Linux 6.9 and on macOS; on 6.9+ the pidfd
/// finds the group empty, see `drop_group_exact_tests`). The `SIGTERM` is recorded, not sent, and
/// the root exits by itself. Mutants: `terminate_tree` sets the tree-killed flag; `terminate_tree`
/// sends nothing.
#[skuld::test]
async fn drop_after_terminate_tree_and_wait_still_warns() {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let termed = record_term_group();
    let mut child = session(&["true"]).spawn().expect("spawn");
    let pid = child.pid();
    child.terminate_tree().expect("terminate_tree");
    assert_eq!(
        termed.termed(),
        vec![pid as i32],
        "terminate_tree signals the group once"
    );
    child.wait().await.expect("reap the root");

    let mark = crate::log_capture::mark();
    drop(child);

    let records = drop_warns_since(mark);
    assert_eq!(records.len(), 1, "{records:?}");
    assert_eq!(records[0].0, log::Level::Warn);
}

/// A drop whose walk leaves a descendant reports it once, after the root's kill. Mutant: the walk's
/// per-member warn is kept beside the drop's. Not on macOS, where `TreeWalk` mode is an fd marker.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn a_drop_whose_walk_leaves_a_descendant_warns_once_and_kills_the_root() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::Descendant);
    let teardown = release_between_kill_and_wait(stdin);
    let pid = child.pid();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    drop(child);

    assert_the_drop_killed(&teardown, &sends, pid);
    let records = crate::log_capture::records_since_on_current_thread(mark, "was not killed");
    assert_eq!(records.len(), 1, "{records:?}");
    assert_eq!(records[0].0, log::Level::Warn);
    let drop_records = crate::log_capture::warns_since(mark, "Child::drop");
    assert_eq!(drop_records.len(), 1, "one report of the event: {drop_records:?}");
}

/// A walk that left a descendant and the root, then the root's kill by the handle: the report names
/// the descendant alone, for `kill_tree` and for the drop. The root is dead, so a line about it would
/// be stale. Mutant: the walk warns of every member it left, the root included, before the root's kill.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn kill_tree_and_drop_after_a_walk_that_left_a_descendant_and_the_root_name_the_descendant_alone() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (mut child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::RootAndDescendant);
    let root = child.pid();
    let descendant = root.wrapping_add(1);
    let mark = crate::log_capture::mark();

    let err = child.kill_tree().expect_err("a descendant was left");

    assert!(
        matches!(err, crate::error::Error::MemberNotKilled { pid, .. } if pid == descendant),
        "{err:?}"
    );
    let stale = crate::log_capture::records_since_on_current_thread(mark, &format!("pid {root} was not killed"));
    assert_eq!(stale, [], "the root was killed by the handle");
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().await.expect("reap the root"));

    // The drop of that child: armed by the unsettled tree, it reports the descendant once.
    let (child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::RootAndDescendant);
    let teardown = release_between_kill_and_wait(stdin);
    let root = child.pid();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    drop(child);

    assert_the_drop_killed(&teardown, &sends, root);
    let warns = crate::log_capture::warns_since(mark, "");
    assert_eq!(warns.len(), 1, "one report of the event: {warns:?}");
    let text = &warns[0];
    assert!(
        text.contains(&format!("pid {} was not killed", root.wrapping_add(1))),
        "{text}"
    );
    assert!(!text.contains(&format!("pid {root} was not killed")), "{text}");
}

/// A drop whose walk leaves only the root, which the drop's own kill of the root then ends, warns
/// once that the tree could not be vouched for (the sync twin is in `child::drop_reaped_tests`).
/// Mutants: the drop reports the walk's error before the root's kill; the drop is silent.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn a_drop_whose_walk_leaves_only_the_root_warns_it_could_not_vouch_for_the_tree() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::Root);
    let teardown = release_between_kill_and_wait(stdin);
    let pid = child.pid();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    drop(child);

    assert_the_drop_killed(&teardown, &sends, pid);
    let warns = crate::log_capture::warns_since(mark, "Child::drop");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("could not be vouched for"), "{warns:?}");
    assert!(!warns[0].contains("members"), "{warns:?}");
}

/// The handle remembers a member a walk left (the sync twin is in `child::drop_reaped_tests`): a
/// second `kill_tree` reports it again instead of settling the tree as killed.
///
/// Mutant: a walk that finds less settles the tree as killed.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn a_second_kill_tree_after_a_walk_left_a_member_reports_it_again_and_does_not_mark_the_tree() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    let (mut child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::Descendant);
    let first = child.kill_tree().expect_err("the walk left a member");
    let second = child
        .kill_tree()
        .expect_err("the member the first walk left is not shown killed");
    let pid_of = |error: &crate::error::Error| match error {
        crate::error::Error::MemberNotKilled { pid, .. } => *pid,
        other => panic!("expected MemberNotKilled, got {other:?}"),
    };
    assert_eq!(pid_of(&second), pid_of(&first), "{first:?}, {second:?}");
    assert!(!child.tree_killed(), "a member was left");
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().await.expect("reap the root"));
}

/// The drop is the second reader of what a walk left: after a `kill_tree` that left a member, its
/// walk from the unreaped root finds nothing, and it still warns of the member, once.
///
/// Mutant: the drop's walk settles the tree as killed and warns nothing.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn a_drop_after_a_kill_tree_that_left_a_member_warns_of_it() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (mut child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::Descendant);
    child.kill_tree().expect_err("the walk left a member");

    let mark = crate::log_capture::mark();
    drop(child);

    let records = crate::log_capture::records_since_on_current_thread(mark, "was not killed");
    assert_eq!(records.len(), 1, "{records:?}");
    assert_eq!(records[0].0, log::Level::Warn);
    drop(stdin);
}

/// The handle's memory of a member outlives the root's reap (the sync twin is in
/// `child::drop_reaped_tests`): a `kill_tree` after `wait` answers with the member an earlier one
/// left, not with the gone root.
///
/// Mutant: the held members are retried only when the new kill ran.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn a_kill_tree_after_wait_reports_the_member_an_earlier_kill_left() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    let (mut child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::Descendant);
    let first = child.kill_tree().expect_err("the walk left a member");
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().await.expect("reap the root"));

    let second = child
        .kill_tree()
        .expect_err("the root is gone, and the member is not shown killed");

    let pid_of = |error: &crate::error::Error| match error {
        crate::error::Error::MemberNotKilled { pid, .. } => *pid,
        other => panic!("expected MemberNotKilled, got {other:?}"),
    };
    assert_eq!(pid_of(&second), pid_of(&first), "{first:?}, {second:?}");
    assert!(!child.tree_killed(), "a member was left");
}

/// The drop after `wait` is the same reader: it still warns of the member a `kill_tree` left, once.
///
/// Mutant: the drop's reaped path does not retry the held members.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn a_drop_after_a_kill_tree_that_left_a_member_and_a_wait_warns_of_it() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (mut child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::Descendant);
    child.kill_tree().expect_err("the walk left a member");
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().await.expect("reap the root"));

    let mark = crate::log_capture::mark();
    drop(child);

    let records = crate::log_capture::records_since_on_current_thread(mark, "was not killed");
    assert_eq!(records.len(), 1, "{records:?}");
    assert_eq!(records[0].0, log::Level::Warn);
}

/// A walk that saw the root running and left it, whose backstop then killed it, is `Ok` for the
/// caller but leaves the tree unvouched, so the drop's skip warns that the tree could not be vouched
/// for, and speaks of no members. Mutant: the tree is marked killed.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn drop_after_a_walk_that_left_only_the_root_and_a_backstop_kill_warns_of_an_unvouched_tree() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (mut child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::Root);
    child.kill_tree().expect("the backstop killed the only member left");
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().await.expect("reap the root"));

    let mark = crate::log_capture::mark();
    drop(child);

    let warns = drop_warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert_eq!(warns[0].0, log::Level::Warn, "{warns:?}");
    assert!(warns[0].1.contains("could not be vouched for"), "{warns:?}");
    assert!(!warns[0].1.contains("members"), "{warns:?}");
}

/// A `kill_tree` on a `TreeWalk` whose root this handle reaped finds no root to walk from, so it kills
/// nothing: it is `Unassessable`, and does not mark the tree killed, so the drop still says it skips
/// the walk. The sync twin is in `child::drop_reaped_tests`.
///
/// Mutants: a walk that found no root counts as a kill that ran; it answers `Ok`.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn kill_tree_on_a_tree_walk_whose_root_is_reaped_is_unassessable_and_does_not_mark_the_tree_killed() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (mut child, stdin) = crate::test_child::held_treewalk_blocker_async();
    drop(stdin);
    child.wait().await.expect("reap the root");

    let err = child
        .kill_tree()
        .expect_err("a root that is gone leaves no tree to walk: nothing was killed");
    assert!(matches!(err, crate::error::Error::Unassessable { .. }), "{err:?}");

    assert!(!child.tree_killed(), "a walk that found no root killed nothing");
    let mark = crate::log_capture::mark();
    drop(child);
    let records = drop_warns_since(mark);
    assert_eq!(records.len(), 1, "{records:?}");
    assert_eq!(records[0].0, log::Level::Warn, "{records:?}");
}

/// The same for a `TreeWalk` whose walk left a descendant, which is an `Err` of its own variant.
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn drop_after_an_incomplete_tree_walk_kill_and_wait_still_warns() {
    use crate::containment::treewalk::fault::LeftBehind;
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let (mut child, stdin) = crate::test_child::held_treewalk_blocker_leaving_async(LeftBehind::Descendant);
    let left = child
        .kill_tree()
        .expect_err("a tree walk that left a member is an error");
    assert!(matches!(left, crate::error::Error::MemberNotKilled { .. }), "{left:?}");
    // Released after the kill so a no-op kill fails the assertion, not the wait.
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().await.expect("reap the root"));

    let mark = crate::log_capture::mark();
    drop(child);

    let records = drop_warns_since(mark);
    assert_eq!(records.len(), 1, "{records:?}");
    assert_eq!(records[0].0, log::Level::Warn);
}

// The integration tests' cgroup helpers, compiled from their real source by `test_groups`.
#[cfg(target_os = "linux")]
pub(super) use crate::test_groups::cgroup_leaf as cgroup_common;

/// A cgroup names its tree without the root's number, so the reaped root does not stop the drop's
/// kill. The cgroup lane's counterpart of the sync test of the same name. Mutant: the skip applied to every mechanism, which logs the warn here.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_drop_after_wait_still_kills_the_tree_and_does_not_warn(#[fixture(cgroup)] _group: &Group) {
    crate::tokio::test_runtime::assert_current_thread();
    use ::tokio::io::AsyncReadExt as _;

    crate::log_capture::install();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    // The `cat` is in a shell that prints `eof` if the `cat` ends by itself, as it does on EOF. A
    // `cat` a kill ended exits by a signal, so the `&&` prints no `eof`.
    cmd.args([
        "sh",
        "-c",
        "exec 3<&0; { cat <&3 3<&- && echo eof; } & echo started; exit 0",
    ]);
    cmd.contain_with(ContainMode::Strongest);
    cmd.stdin(crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.stdout(crate::Stdio::pipe_out()).expect("stdout pipe");
    cmd.stderr(crate::Stdio::pipe_out()).expect("stderr pipe");
    let mut child = cmd.spawn().expect("spawn");
    assert_eq!(child.containment(), Containment::CgroupV2);
    // The drop is under test, so it stays the killer.
    let leaf = match &child.os.attached {
        crate::containment::Attached::Cgroup(leaf) => leaf.path().to_path_buf(),
        other => panic!("a cgroup child holds its leaf, got {other:?}"),
    };
    let _leaf_cleanup = cgroup_common::LeafGuard::new(leaf.clone());
    let mut started = [0u8; 8];
    let mut stdout = child.stdout().expect("stdout pipe");
    stdout.read_exact(&mut started).await.expect("read `started`");
    let stdin = child.stdin().expect("stdin pipe");
    let mut stderr = child.stderr().expect("stderr pipe");
    child.wait().await.expect("reap the root");
    // Released as the kill returns; see [`KillRelease`].
    let release = crate::child::front_cgroup_tests::release_after_cgroup_kill(stdin);

    let mark = crate::log_capture::mark();
    drop(child);

    release.assert_killed();
    assert_eq!(drop_warns_since(mark), []);
    let mut rest = Vec::new();
    stderr
        .read_to_end(&mut rest)
        .await
        .expect("the cgroup kill ended the cat, closing stderr");
    let mut said = Vec::new();
    stdout
        .read_to_end(&mut said)
        .await
        .expect("every holder of stdout is gone");
    crate::child::front_cgroup_tests::assert_nothing_ended_by_itself(&said);
    // The drop waited for the leaf to drain, then removed it.
    assert!(
        !leaf.exists(),
        "the drop must remove the drained leaf: {}",
        leaf.display()
    );
}

/// The async twin of the sync `cgroup_drop_of_an_exited_unreaped_root_kills_its_orphaned_descendant`:
/// the root has exited and nothing has reaped it, and the drop's `cgroup.kill` ends the `cat` it
/// left in the leaf. Mutant: the drop's `cgroup.kill` write sends nothing.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_drop_of_an_exited_unreaped_root_kills_its_orphaned_descendant(#[fixture(cgroup)] _group: &Group) {
    crate::tokio::test_runtime::assert_current_thread();
    use ::tokio::io::AsyncReadExt as _;

    crate::log_capture::install();
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args([
        "sh",
        "-c",
        "exec 3<&0; { cat <&3 3<&- && echo eof; } & echo started; exit 0",
    ]);
    cmd.contain_with(ContainMode::Strongest);
    cmd.stdin(crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.stdout(crate::Stdio::pipe_out()).expect("stdout pipe");
    cmd.stderr(crate::Stdio::pipe_out()).expect("stderr pipe");
    let mut child = cmd.spawn().expect("spawn");
    assert_eq!(child.containment(), Containment::CgroupV2);
    let leaf = match &child.os.attached {
        crate::containment::Attached::Cgroup(leaf) => leaf.path().to_path_buf(),
        other => panic!("a cgroup child holds its leaf, got {other:?}"),
    };
    let _leaf_cleanup = cgroup_common::LeafGuard::new(leaf.clone());
    let mut started = [0u8; 8];
    let mut stdout = child.stdout().expect("stdout pipe");
    stdout.read_exact(&mut started).await.expect("read `started`");
    let stdin = child.stdin().expect("stdin pipe");
    let mut stderr = child.stderr().expect("stderr pipe");
    crate::test_child::wait_until_zombie(child.pid());
    // Released as the kill returns; see [`KillRelease`].
    let release = crate::child::front_cgroup_tests::release_after_cgroup_kill(stdin);

    let mark = crate::log_capture::mark();
    drop(child);

    release.assert_killed();
    assert_eq!(drop_warns_since(mark), []);
    let mut rest = Vec::new();
    stderr
        .read_to_end(&mut rest)
        .await
        .expect("the cgroup kill ended the cat, closing stderr");
    let mut said = Vec::new();
    stdout
        .read_to_end(&mut said)
        .await
        .expect("every holder of stdout is gone");
    crate::child::front_cgroup_tests::assert_nothing_ended_by_itself(&said);
    assert!(
        !leaf.exists(),
        "the drop must remove the drained leaf: {}",
        leaf.display()
    );
}

/// The drop alone is the killer, with the root still alive: no `kill_tree`, no wait. The root dies
/// of `SIGKILL`, and so does the `cat` it left in the leaf (a real grandchild, in a shell that says
/// `eof` if it ends by itself), and a member the test placed in the leaf. The leaf's `cgroup.kill`,
/// which the drop writes before it waits for the leaf to drain, does it, and the drop then removes
/// the leaf.
///
/// The test's holders (the root's stdin and the member's) are released as the write returns, or
/// when the drain wait is about to block, so a write that sent nothing ends the tree by itself
/// and `assert_killed` fails.
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_async_drop_alone_kills_the_members_and_removes_the_leaf(#[fixture(cgroup)] _group: &Group) {
    crate::tokio::test_runtime::assert_current_thread();
    use ::tokio::io::AsyncReadExt as _;

    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args([
        "sh",
        "-c",
        "exec 3<&0; { cat <&3 3<&- && echo eof; } & echo started; wait",
    ]);
    cmd.contain_with(ContainMode::Strongest);
    cmd.kill_on_drop(true);
    cmd.stdin(crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.stdout(crate::Stdio::pipe_out()).expect("stdout pipe");
    let mut child = cmd.spawn().expect("spawn");
    assert_eq!(child.containment(), Containment::CgroupV2);
    let leaf = match &child.os.attached {
        crate::containment::Attached::Cgroup(leaf) => leaf.path().to_path_buf(),
        other => panic!("a cgroup child holds its leaf, got {other:?}"),
    };
    let _leaf_cleanup = cgroup_common::LeafGuard::new(leaf.clone());
    let mut started = [0u8; 8];
    let mut stdout = child.stdout().expect("stdout pipe");
    stdout.read_exact(&mut started).await.expect("read `started`");
    assert_eq!(
        &started,
        b"started
"
    );
    let stdin = child.stdin().expect("stdin pipe");

    // A member of the test's own, blocked on its stdin and placed in the leaf.
    let mut member = crate::test_spawn::spawn(
        std::process::Command::new("cat")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null()),
    )
    .expect("spawn a member");
    let member_stdin = member.stdin.take().expect("the member's piped stdin");
    std::fs::write(leaf.join("cgroup.procs"), member.id().to_string()).expect("place the member in the leaf");
    assert_eq!(
        crate::child::front_cgroup_tests::cgroup_dir_of(member.id()),
        leaf.to_str().expect("a utf-8 path"),
        "the member must be in the tree's leaf"
    );
    let release = crate::child::front_cgroup_tests::release_after_cgroup_kill((stdin, member_stdin));
    release.observe(member.id());
    release.observe(child.pid());

    drop(child);

    release.assert_killed();
    member.wait().expect("reap the member");
    let mut said = Vec::new();
    stdout
        .read_to_end(&mut said)
        .await
        .expect("the root and the cat it left are gone");
    crate::child::front_cgroup_tests::assert_nothing_ended_by_itself(&said);
    assert!(
        !leaf.exists(),
        "the drop must drain and remove the leaf: {}",
        leaf.display()
    );
}

/// Exactly one record of the drop's skip since `mark`, at `debug`.
#[track_caller]
fn assert_skipped_at_debug(mark: usize) {
    let records = drop_warns_since(mark);
    assert_eq!(records.len(), 1, "exactly one skip record, got {records:?}");
    assert_eq!(records[0].0, log::Level::Debug, "{records:?}");
}

/// A macOS fd marker names its marker holders by identity, so after a reap the drop still sweeps
/// them and skips every channel that names the root's number: the `killpg`, the ppid walk and the
/// root's own kill. Mutants: the sweep skipped too; the `killpg` or the walk still run.
#[cfg(target_os = "macos")]
#[skuld::test]
async fn fd_marker_drop_after_wait_sweeps_the_marker_holders_but_names_nothing_by_the_roots_number() {
    crate::tokio::test_runtime::assert_current_thread();
    use ::tokio::io::AsyncReadExt as _;

    crate::log_capture::install();
    let recorder = record_kill_group();
    let walks = record_walks();
    let sweeps = crate::containment::fdmarker::fault::record_holder_kills();
    // `exec 3<&0` because `sh` points a background job's stdin at /dev/null otherwise. The `cat`
    // reads the stdin pipe, which the test holds, and holds stderr's write end: stderr reaches EOF
    // exactly when the `cat` is gone.
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(["sh", "-c", "exec 3<&0; cat <&3 3<&- >/dev/null & echo started; exit 0"]);
    cmd.contain_with(ContainMode::Strongest);
    cmd.stdin(crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.stdout(crate::Stdio::pipe_out()).expect("stdout pipe");
    cmd.stderr(crate::Stdio::pipe_out()).expect("stderr pipe");
    let mut child = cmd.spawn().expect("spawn");
    assert_eq!(child.containment(), Containment::FdMarker);
    let mut out = String::new();
    child
        .stdout()
        .expect("stdout pipe")
        .read_to_string(&mut out)
        .await
        .expect("read stdout to the root's exit");
    assert_eq!(out, "started\n");
    let _stdin = child.stdin().expect("stdin pipe");
    let mut stderr = child.stderr().expect("stderr pipe");
    child.wait().await.expect("reap the root");

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(recorder.killed(), Vec::<i32>::new(), "no killpg after the reap");
    assert_eq!(walks.walked(), Vec::<u32>::new(), "no ppid walk from the reaped root");
    assert!(!sweeps.killed().is_empty(), "the marker-holder sweep still runs");
    assert_eq!(drop_warns_since(mark).len(), 1);
    let mut rest = Vec::new();
    stderr
        .read_to_end(&mut rest)
        .await
        .expect("the sweep ended the cat, closing stderr, with stdin still held");
}

/// A root that is alive when its marker is attached, then killed and reaped. A root that exits
/// before the attach has no identity to walk from, which would make a "no walk" assertion vacuous.
#[cfg(target_os = "macos")]
async fn reaped_blocker_root(mode: ContainMode) -> (u32, crate::tokio::Child) {
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
    cmd.contain_with(mode);
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("stdin pipe");
    assert_eq!(child.containment(), Containment::FdMarker);
    let pid = child.pid();
    child.kill().expect("kill the root");
    // Released after the kill: a `kill` that sent nothing fails the assertion, not the reap.
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().await.expect("reap the root"));
    (pid, child)
}

/// An fd marker with no group (`TreeWalk` mode): after a reap nothing but the holder sweep runs.
/// Mutant: the walk or the root kill still run for it.
#[cfg(target_os = "macos")]
#[skuld::test]
async fn fd_marker_without_a_group_drop_after_wait_only_sweeps_the_marker_holders() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let walks = record_walks();
    let (pid, child) = reaped_blocker_root(ContainMode::TreeWalk).await;

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(walks.walked(), Vec::<u32>::new(), "no ppid walk from the reaped root");
    let warns = drop_warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].1.contains(&format!("root pid {pid}")), "{warns:?}");
}

/// The same with a group: no `killpg`, no walk, one warn. Mutant: the walk still runs for a marker
/// that has a group.
#[cfg(target_os = "macos")]
#[skuld::test]
async fn fd_marker_with_a_group_drop_after_wait_neither_signals_the_group_nor_walks() {
    crate::tokio::test_runtime::assert_current_thread();
    crate::log_capture::install();
    let recorder = record_kill_group();
    let walks = record_walks();
    let (pid, child) = reaped_blocker_root(ContainMode::Strongest).await;

    let mark = crate::log_capture::mark();
    drop(child);

    assert_eq!(recorder.killed(), Vec::<i32>::new(), "no killpg after the reap");
    assert_eq!(walks.walked(), Vec::<u32>::new(), "no ppid walk from the reaped root");
    let warns = drop_warns_since(mark);
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].1.contains(&format!("pgid {pid}")), "{warns:?}");
}