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
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! Unit tests for the graceful trio's watch-failure ordering (the fault seam is pub(crate),
//! unreachable from tests/).

use std::time::Duration;

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

use super::fault as term_fault;
use crate::wait::fault;

/// A contained [`crate::test_child::BLOCKER_ARGV`] child with piped stdin and stdout, plus its
/// stdin writer, which the caller must keep for exactly as long as the child must stay running.
/// `Existence::Present` is not proof of life — it is zombie-inclusive on every platform — so a
/// liveness claim goes through [`assert_still_running`].
fn blocker() -> (crate::Child, crate::PipeWriter) {
    crate::test_child::held_contained_blocker_on_console(crate::Stdio::pipe())
}

/// What keeps a [`kill_only_blocker`] running while the caller holds it.
#[cfg(unix)]
type Held = crate::PipeWriter;
#[cfg(windows)]
type Held = std::net::TcpStream;

/// A [`blocker`] for a test whose only end is a real kill: on Unix it ignores `SIGTERM`, on Windows
/// it ignores every console event and is returned after its handshake, which orders a break sent
/// afterwards after the handler's installation (a break before it ends a child with `0xC0000142`,
/// not the kill's 1).
fn kill_only_blocker() -> (crate::Child, Held) {
    #[cfg(unix)]
    {
        crate::test_child::term_ignoring_blocker()
    }
    #[cfg(windows)]
    {
        crate::test_child::ctrl_break::spawn_ignoring_root()
    }
}

/// Proves a [`blocker`] is genuinely still running, not merely resolvable. On Unix, round-trips
/// a byte through `cat`'s piped stdout over the stdin writer the caller holds; a killed-but-unreaped
/// `cat` cannot echo.
///
/// On Windows, `findstr` does not echo and `is_alive()` races the asynchronous `TerminateProcess`.
/// Instead, write a line containing `x`, close stdin, and require both a clean exit (`findstr`'s
/// "a match was found" code) and the echoed match on stdout; a killed process produces neither.
/// This consumes `stdin` and reaps the child.
fn assert_still_running(child: &mut crate::Child, mut stdin: crate::PipeWriter) {
    #[cfg(unix)]
    {
        let mut stdout = child.stdout().expect("piped stdout");
        crate::test_child::assert_echoes(&mut stdin, &mut stdout);
    }
    #[cfg(windows)]
    {
        use std::io::{Read as _, Write as _};
        stdin.write_all(b"x\r\n").expect("write to the blocker");
        drop(stdin); // EOF: findstr can now finish reading and exit
        let mut output = Vec::new();
        child
            .stdout()
            .expect("piped stdout")
            .read_to_end(&mut output)
            .expect("read stdout to EOF");
        let status = child.wait().expect("the blocker must exit after stdin closes");
        assert!(
            status.success(),
            "the blocker must exit 0 (findstr's own 'a match was found' code), got {status:?}"
        );
        assert!(
            output.windows(1).any(|w| w == b"x"),
            "the blocker's stdout must contain the echoed match, got {output:?}"
        );
    }
}

/// Sweeps the tree and reaps the child. Windows discards errors: `assert_still_running` already
/// reaped the child there, so a second kill or wait has nothing to act on.
fn cleanup(child: &mut crate::Child) {
    #[cfg(unix)]
    {
        child.kill_tree().expect("cleanup sweep");
        child.wait().expect("reap");
    }
    #[cfg(windows)]
    {
        _ = child.kill_tree();
        _ = child.wait();
    }
}

// A watch failure must not strand the tree between the soft signal and the hard sweep: the
// sweep and reap still run, then the watch error surfaces. The reap is proven by identity on
// all Unix — procfs and `sysctl KERN_PROC` are both zombie-inclusive, so a swept-but-unreaped
// root would still be exists()-visible. (Windows runs the same body but skips that assert:
// exists() stays true there while `child` still holds the process handle.)
#[skuld::test]
fn graceful_tree_watch_error_still_sweeps_and_reaps() {
    let (child, stdin) = kill_only_blocker();
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    fault::set_force_watch_error(true);
    // Released between the sweep and the reap (see `release_at`).
    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
    let err = child
        .graceful_shutdown_tree(Duration::from_secs(30))
        .expect_err("the watch error must surface");
    assert!(
        !fault::armed(),
        "seam not consumed — the watch did not run on this thread"
    );
    assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
    #[cfg(unix)]
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Gone,
        "root must be swept AND reaped despite the watch error (a zombie would still exist)"
    );
    #[cfg(windows)]
    let _ = id;
    let status = child.wait().expect("cached status — already reaped by the graceful op");
    crate::test_child::assert_killed("the swept root", status);
}

// The LONE-path twin of the same invariant (Unix-gated: graceful_shutdown is Unsupported on
// Windows before the watch runs). With the old `wait_timeout(grace)?` shape the child would
// die by our SIGTERM but stay a zombie — `exists()` catches exactly that on all Unix
// (procfs / `sysctl KERN_PROC` are both zombie-inclusive).
#[cfg(unix)]
#[skuld::test]
fn graceful_lone_watch_error_still_escalates_and_reaps() {
    let (child, stdin) = kill_only_blocker();
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    fault::set_force_watch_error(true);
    // Released between the kill and the reap (see `release_at`).
    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
    let err = child
        .graceful_shutdown(Duration::from_secs(30))
        .expect_err("the watch error must surface");
    assert!(
        !fault::armed(),
        "seam not consumed — the watch did not run on this thread"
    );
    assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Gone,
        "child must be killed AND reaped despite the watch error (a zombie would still exist)"
    );
    let status = child.wait().expect("cached status — already reaped by the graceful op");
    crate::test_child::assert_killed("the escalated child", status);
}

// The graceful path: an uncontained `cat` dies to `SIGTERM`'s default disposition within the
// grace. Its stdin is released via `release_at` after `terminate` returns; a `terminate` that sent
// nothing yields exit 0 and fails the assertion.
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_graceful_path() {
    use std::os::unix::process::ExitStatusExt;
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    let _release = term_fault::release_at(term_fault::HookPoint::AfterTerminate, stdin);
    let status = child
        .graceful_shutdown(Duration::from_secs(30))
        .expect("graceful_shutdown");
    assert_eq!(
        status.signal(),
        Some(libc::SIGTERM),
        "graceful path must exit via SIGTERM, got {status:?}"
    );
}

// The graceful half of `graceful_shutdown_tree`: a contained `cat` root dies to the group's
// `SIGTERM` within the grace, and the call returns its status. Its stdin is released via
// `release_at` after `terminate_tree` returns; a `terminate_tree` that sent nothing yields exit 0
// and fails the assertion.
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_tree_graceful_root_sigterm() {
    let _warns = crate::log_capture::warn_watch();
    use std::os::unix::process::ExitStatusExt;
    let (child, stdin) = crate::test_child::held_contained_blocker_without_cgroup(crate::Stdio::pipe());
    let _release = term_fault::release_at(term_fault::HookPoint::AfterTerminate, stdin);
    let status = child
        .graceful_shutdown_tree(Duration::from_secs(30))
        .expect("tree graceful");
    assert_eq!(
        status.signal(),
        Some(libc::SIGTERM),
        "root must exit via SIGTERM, got {status:?}"
    );
}

// A contained two-member tree, a root `cat` and a grandchild `sh` reading the same stdin pipe: the
// group's `SIGTERM` leaves neither alive. The root's status is `SIGTERM`, which the release (as in
// the test above) turns into 0 if no `SIGTERM` was sent. The grandchild prints `leaf` once the
// released stdin ends it, so an empty stdout shows it was ended by the `SIGTERM`.
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_tree_tears_down_tree() {
    let _warns = crate::log_capture::warn_watch();
    use std::io::Read as _;
    use std::os::unix::process::ExitStatusExt;
    let mut cmd = crate::test_child::command(Console::Hidden);
    // `exec 3<&0` keeps the backgrounded `sh` on the real pipe (see `test_child::BLOCKER_ARGV`).
    cmd.args([
        "sh",
        "-c",
        "exec 3<&0; sh -c 'echo r; read -r _; echo leaf' <&3 3<&- & exec cat",
    ]);
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    crate::test_child::contain_without_cgroup(&mut cmd);
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    let mut stdout = child.stdout().expect("piped stdout");
    // The grandchild writes the readiness line, so both members exist.
    let mut ready = [0u8; 2];
    stdout.read_exact(&mut ready).expect("readiness line");
    assert_eq!(&ready, b"r\n");

    let _release = term_fault::release_at(term_fault::HookPoint::AfterTerminate, stdin);
    let status = child
        .graceful_shutdown_tree(Duration::from_secs(30))
        .expect("tree graceful");

    assert_eq!(
        status.signal(),
        Some(libc::SIGTERM),
        "root must exit via SIGTERM, got {status:?}"
    );
    let mut rest = Vec::new();
    stdout
        .read_to_end(&mut rest)
        .expect("both members are gone, so the pipe ends");
    assert!(rest.is_empty(), "nothing was written: {rest:?}");
}

// The case the sweep-before-reap invariant protects: the root honors the group's `SIGTERM` and ends
// within the grace, but the grandchild ignores it and survives, so only the hard sweep, which runs
// while the unreaped root still pins the group, can end it. The grandchild never ends on its own,
// so the grace runs out (1 s, the call's own bound). Its stdin is released once the sweep returned
// (`release_at`): a grandchild the sweep missed then ends of its own accord and prints `eof`, so an
// empty stdout shows it was killed. The root's own status is not asserted: the sweep's `SIGKILL`
// may reach it before its `SIGTERM` has ended it.
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_tree_sweeps_survivor_after_graceful_root_exit() {
    let _warns = crate::log_capture::warn_watch();
    use std::io::Read as _;
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::TERM_SURVIVOR_TREE_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    crate::test_child::contain_without_cgroup(&mut cmd);
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    let mut stdout = child.stdout().expect("piped stdout");
    let mut ready = [0u8; 2];
    stdout.read_exact(&mut ready).expect("readiness line");
    assert_eq!(&ready, b"r\n");

    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
    child
        .graceful_shutdown_tree(Duration::from_secs(1))
        .expect("tree graceful with survivor");

    let mut rest = Vec::new();
    stdout
        .read_to_end(&mut rest)
        .expect("every member is gone, so the pipe ends");
    assert!(rest.is_empty(), "the sweep missed the grandchild: {rest:?}");
}

// The escalation: a child that ignores `SIGTERM` is still alive at `Duration::ZERO`'s one poll, so
// only the hard kill can end it, and `SIGKILL` is the only signal it can die of. Its stdin is
// released via `release_at` after the kill; an escalation that sent nothing yields exit 0.
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_escalates() {
    let (child, stdin) = crate::test_child::term_ignoring_blocker();
    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
    let status = child
        .graceful_shutdown(Duration::ZERO)
        .expect("graceful_shutdown escalates");
    crate::test_child::assert_killed("the SIGTERM-ignoring child", status);
}

// The tree escalation: all three members ignore the group's `SIGTERM` (`TERM_IGNORING_TREE_ARGV`),
// so only the hard sweep ends them. The root's status shows it was killed; the subshell and its
// child each print a marker once the released stdin ends them, so an empty stdout shows the sweep
// ended both.
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_tree_escalates_with_a_surviving_grandchild() {
    let _warns = crate::log_capture::warn_watch();
    use std::io::Read as _;
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::TERM_IGNORING_TREE_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    crate::test_child::contain_without_cgroup(&mut cmd);
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    let mut stdout = child.stdout().expect("piped stdout");
    let mut ready = [0u8; 2];
    stdout.read_exact(&mut ready).expect("readiness line");
    assert_eq!(
        &ready,
        b"r
"
    );

    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
    let status = child.graceful_shutdown_tree(Duration::ZERO).expect("tree escalates");

    crate::test_child::assert_killed("the SIGTERM-ignoring root", status);
    let mut rest = Vec::new();
    stdout
        .read_to_end(&mut rest)
        .expect("every member is gone, so the pipe ends");
    assert!(rest.is_empty(), "the sweep missed a grandchild: {rest:?}");
}

// A term_group refusal must not strand the tree between the soft signal and the hard sweep:
// the sweep and reap still run, then the refusal surfaces. Mirrors
// `graceful_tree_watch_error_still_sweeps_and_reaps` above, for the terminate seam instead
// of the watch seam. Uses `Duration::ZERO`, not a nonzero grace: the watch-error test's
// `from_secs(30)` was safe there because that seam fires BEFORE the watch ever runs, so the
// grace is never actually waited. This seam replaces `terminate_tree` itself, so with a
// nonzero grace the watch WOULD really block for the full window, synchronizing on time. `ZERO` is
// documented (`graceful_shutdown`'s own rustdoc) as "signals, polls once, then escalates",
// which is exactly the ordering this test needs and nothing more.
#[skuld::test]
fn graceful_tree_terminate_refusal_still_sweeps_and_reaps() {
    let (child, stdin) = kill_only_blocker();
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    term_fault::set_force_terminate(term_fault::Forced::Containment);
    // A successful sweep is fresher, positive proof the group cleared, superseding the held
    // refusal — the call must report `Ok`, not resurface the disproved `Containment` error.
    // Released between the sweep and the reap (see `release_at`).
    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
    let status = child
        .graceful_shutdown_tree(std::time::Duration::ZERO)
        .expect("a successful sweep must supersede the forced terminate refusal");
    crate::test_child::assert_killed("the root", status);
    assert!(
        crate::log_capture::contains_since(
            mark,
            &format!(
                "graceful_shutdown_tree({pid}): tree confirmed clear; discarding the superseded terminate_tree refusal",
                pid = id.pid()
            )
        ),
        "the refusal must be logged as discarded, not silently dropped"
    );
    #[cfg(unix)]
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Gone,
        "root must be swept AND reaped despite the forced terminate refusal"
    );
    #[cfg(windows)]
    let _ = id;
}

// Same hold-and-continue contract as the `Containment` test above, but for the OTHER
// ordinary #61 outcome: `Error::Unassessable { source: None, .. }` (group::decide's
// per-member-unconfirmed shape). Mirrors the test above almost exactly; kept as a fully
// separate test (not parameterized) matching this file's existing convention of one test
// per forced-error shape.
#[skuld::test]
fn graceful_tree_unassessable_per_member_still_sweeps_and_reaps() {
    let (child, stdin) = kill_only_blocker();
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    term_fault::set_force_terminate(term_fault::Forced::UnassessablePerMember);
    // Same supersession as the `Containment` test above: the sweep's success disproves the
    // held per-member-unconfirmed state, so the call must report `Ok`.
    // Released between the sweep and the reap (see `release_at`).
    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
    let status = child
        .graceful_shutdown_tree(std::time::Duration::ZERO)
        .expect("a successful sweep must supersede the forced unassessable state");
    crate::test_child::assert_killed("the root", status);
    assert!(
        crate::log_capture::contains_since(
            mark,
            &format!(
                "graceful_shutdown_tree({pid}): tree confirmed clear; discarding the superseded terminate_tree refusal",
                pid = id.pid()
            )
        ),
        "the refusal must be logged as discarded, not silently dropped"
    );
    #[cfg(unix)]
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Gone,
        "root must be swept AND reaped despite the forced unassessable state"
    );
    #[cfg(windows)]
    let _ = id;
}

// A failed check after the signal went out, whatever its variant, holds like a refusal does: the
// grace is waited and the sweep runs. Here the `Unassessable` carries a `source`, as a failed
// listing of a process group's members does after the `killpg`.
#[skuld::test]
fn graceful_tree_unassessable_with_a_source_still_sweeps_and_reaps() {
    let (child, stdin) = kill_only_blocker();
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    term_fault::set_force_terminate(term_fault::Forced::UnassessableMechanism);
    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
    let status = child
        .graceful_shutdown_tree(std::time::Duration::ZERO)
        .expect("a successful sweep must supersede the forced check failure");
    crate::test_child::assert_killed("the root", status);
    #[cfg(unix)]
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Gone,
        "root must be swept AND reaped despite the forced check failure"
    );
    #[cfg(windows)]
    let _ = id;
}

// The sweep's failure is the answer, and what failed decides its variant, not how many things failed:
// the forced sweep failure is an `Io`, which no variant's meaning covers, so it is the answer as it is
// and the refusal of the cooperative signal and the grace wait's failure are each logged at warn,
// naming the call, in that order.
#[skuld::test]
fn graceful_tree_io_sweep_error_stays_the_answer_and_the_refusal_and_the_watch_error_are_warns() {
    use crate::error::Error;
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let (mut child, stdin) = kill_only_blocker();
    term_fault::set_force_terminate(term_fault::Forced::Containment);
    fault::set_force_watch_error(true);
    let _armed = term_fault::ArmedKillTreeError::arm();
    let err = child
        .graceful_shutdown_tree(Duration::ZERO)
        .expect_err("the sweep failed");
    assert!(
        matches!(&err, Error::Io(e) if e.to_string().contains("forced kill_tree failure")),
        "{err:?}"
    );
    let call = format!("graceful_shutdown_tree({})", child.pid());
    let logged = crate::log_capture::records_since_on_current_thread(mark, &call);
    assert!(
        matches!(&logged[..], [(log::Level::Warn, refusal), (log::Level::Warn, watch)]
            if refusal.contains("forced term_group refusal") && watch.contains("forced grace-watch failure")),
        "{logged:?}"
    );
    cleanup(&mut child);
    drop(stdin);
}

/// A sweep that left a member has a slot for the call's other failures: the refusal of the
/// cooperative signal and the grace wait's failure are its `others`, in that order, and not members.
///
/// Mutants: they are logged and dropped, or become members.
#[cfg(all(unix, not(target_os = "macos")))]
#[skuld::test]
fn graceful_tree_that_left_members_carries_the_refusal_and_the_watch_error_in_others() {
    use crate::containment::treewalk::fault::{self as walk_fault, LeftBehind};
    use crate::error::Error;
    use std::io::Read as _;

    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::TERM_IGNORING_BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    cmd.contain_with(crate::ContainMode::TreeWalk);
    let mut child = cmd.spawn().expect("spawn");
    let _stdin = child.stdin().expect("piped stdin");
    let mut readiness = [0u8; 1];
    child
        .stdout()
        .expect("piped stdout")
        .read_exact(&mut readiness)
        .expect("readiness byte");

    walk_fault::force_incomplete_once(LeftBehind::Descendant);
    term_fault::set_force_terminate(term_fault::Forced::Containment);
    fault::set_force_watch_error(true);
    let err = child
        .graceful_shutdown_tree(Duration::from_millis(200))
        .expect_err("a descendant was left");

    let Error::MembersLeft { members, others } = &err else {
        panic!("expected MembersLeft, got {err:?}");
    };
    assert!(
        members.iter().all(|m| matches!(**m, Error::MemberNotKilled { .. })),
        "{err:?}"
    );
    let Some(Error::Several(others)) = others.as_deref() else {
        panic!("expected the refusal and the watch failure in others: {err:?}");
    };
    let others: Vec<&Error> = others.iter().map(|e| &**e).collect();
    assert!(
        matches!(others[..], [Error::Containment { .. }, watch]
            if crate::error::said(watch).contains("forced grace-watch failure")),
        "{others:?}"
    );
}

/// A refused cooperative signal is never lost: when the reap fails after the tree was proved clear, the
/// reap's failure is the answer and the refusal is in the call's report. The reap's failure here is
/// an `Io`, which holds nothing, so the refusal is logged at warn, naming the call.
///
/// Mutant: the refusal is dropped when the reap fails.
#[skuld::test]
fn a_refused_terminate_is_logged_when_the_reap_fails_after_a_clean_sweep() {
    use crate::containment::fake::FakeContains;
    use crate::containment::Containment;
    use crate::error::Error;
    use crate::os_process::fake::{Answer, ReapAnswer};
    use crate::test_child::over_fake::{child_with, root_looking};

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let root = root_looking([Answer::Exited; 4]).reaps([ReapAnswer::Err(std::io::ErrorKind::PermissionDenied)]);
    // The sweep runs for real, and a Linux sweep reads the root's state, which the helper answers only
    // on macOS.
    #[cfg(all(unix, not(target_os = "macos")))]
    let root = root.peeks(std::iter::repeat_with(|| Ok(crate::os_process::child::PeekOutcome::Running)).take(32));
    let (fake, _) = FakeContains::new(Containment::Session, false);
    let child = child_with(&root, fake);
    term_fault::set_force_terminate(term_fault::Forced::Containment);

    let err = child
        .graceful_shutdown_tree(Duration::ZERO)
        .expect_err("the reap failed");

    assert!(
        matches!(&err, Error::Io(e) if e.kind() == std::io::ErrorKind::PermissionDenied),
        "{err:?}"
    );
    let logged = crate::log_capture::records_since_on_current_thread(mark, "forced term_group refusal");
    let call = format!("graceful_shutdown_tree({})", child.pid());
    assert!(
        matches!(&logged[..], [(log::Level::Warn, line)] if line.starts_with(&call)),
        "{logged:?}"
    );
}

/// The best-effort reap after a failed sweep of an exited root is secondary to the sweep's error,
/// which stays the answer; its own failure is logged once, at warn, naming the call.
///
/// Mutants: the reap's failure is logged at debug, not logged, or put in the answer.
#[cfg(unix)]
#[skuld::test]
fn a_best_effort_reap_that_fails_after_a_failed_sweep_is_logged_once_at_warn() {
    use crate::containment::fake::FakeContains;
    use crate::containment::Containment;
    use crate::error::Error;
    use crate::os_process::fake::{Answer, ReapAnswer};
    use crate::test_child::over_fake::{child_with, root_looking};

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let root = root_looking([Answer::Exited; 4]).reaps([ReapAnswer::Err(std::io::ErrorKind::PermissionDenied)]);
    let (fake, _) = FakeContains::new(Containment::Session, false);
    let child = child_with(&root, fake);
    let _armed = term_fault::ArmedKillTreeError::arm();

    let err = child
        .graceful_shutdown_tree(Duration::ZERO)
        .expect_err("the sweep failed");

    assert!(
        matches!(&err, Error::Io(e) if e.to_string().contains("forced kill_tree failure")),
        "{err:?}"
    );
    let logged = crate::log_capture::records_since_on_current_thread(mark, "best-effort reap");
    assert!(
        matches!(&logged[..], [(log::Level::Warn, line)] if line.contains("graceful_shutdown_tree(")),
        "{logged:?}"
    );
}

// The invariant under test: only an AUTHORITATIVE drain-observable mechanism (cgroup v2, Windows
// job object — kernel-owned membership a live process cannot leave without exiting) may skip
// the hard sweep when a tree drains on its own within `grace`. macOS's fd marker IS
// drain-observable (`can_observe_drain()` is true) but its EOF is advisory — see `TreeDrain`'s
// own doc — so it must land in the same "sweep always runs" bucket as a mechanism with no drain
// edge at all, not the "skip the sweep" bucket. Proven by forcing `kill_tree` to fail: the call
// only comes back `Ok` if that branch was never entered. Both arms are real, exercised
// assertions on every platform, not a skip.
//
// Both arms block on a readiness edge from the child's own code before signalling. Without it
// the child has not registered with the console (Windows) or installed its disposition (Unix)
// when the signal arrives, and what the test measures is an abrupt death during startup rather
// than the cooperative path it is named for.
//
// `contain` is the mechanism the caller asks for and `expected` the one it must get, which
// decides the arm: each mechanism has its own test below.
fn drained_tree_sweep_decision(contain: impl FnOnce(&mut crate::Command), expected: crate::Containment) {
    use std::io::Read;

    // Asked on Windows: the test sends a console-group break to a child that registered with the
    // console; a unix child has no console, so the argument is moot there.
    let mut cmd = crate::test_child::command(Console::Asked);
    #[cfg(unix)]
    {
        // `exec` keeps the signalled root `cat` itself, so the SIGTERM assertion still means what it
        // says; the `AfterTerminate` release (below) ends it on EOF if the SIGTERM never came.
        cmd.args(["sh", "-c", "echo r; exec cat"]);
        cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
        cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    }
    #[cfg(windows)]
    let (listener, addr) = crate::test_child::registration_rendezvous();
    #[cfg(windows)]
    {
        cmd.executable(std::env::current_exe().expect("current_exe"))
            .args(crate::test_child::fixture_argv(
                crate::test_child::FIXTURE_REGISTERS_THEN_BLOCKS_TEST,
            ));
        cmd.env(crate::test_child::FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV, addr);
        crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
        cmd.env(crate::test_child::ack::ACK_ENV, "1");
    }
    contain(&mut cmd);
    #[cfg_attr(
        windows,
        allow(
            unused_mut,
            reason = "on windows only .containment()/.graceful_shutdown_tree() are called below, both &self; unix's child.stdout() needs &mut"
        )
    )]
    let mut child = cmd.spawn().expect("spawn");
    assert_eq!(child.containment(), expected);
    #[cfg(unix)]
    let stdin = child.stdin().expect("piped stdin");
    #[cfg(unix)]
    {
        let mut readiness = [0u8; 1];
        child
            .stdout()
            .expect("piped stdout")
            .read_exact(&mut readiness)
            .expect("readiness byte");
    }
    #[cfg(windows)]
    let _sock = {
        let mut sock = crate::test_child::accept_or_die(&listener, child.id().expect(crate::test_child::IDENTITY_READ));
        let mut tag = [0u8; 1];
        sock.read_exact(&mut tag).expect("registration tag");
        sock
    };
    let authoritative = matches!(
        expected,
        crate::containment::Containment::CgroupV2 | crate::containment::Containment::JobObject
    );
    let armed = term_fault::ArmedKillTreeError::arm();
    // Released once `terminate_tree` has returned, before any watch: SIGTERM is then already
    // pending on the root, so it beats the EOF this release causes.
    #[cfg(unix)]
    let _release = term_fault::release_at(term_fault::HookPoint::AfterTerminate, stdin);
    // Windows: assert the break was sent once `terminate_tree` returns, so a missing one fails
    // here and not when the grace runs out.
    #[cfg(windows)]
    let check = {
        let pid = child.pid();
        term_fault::at_checked(term_fault::HookPoint::AfterTerminate, move || {
            crate::test_child::ctrl_break::assert_break_sent_to(pid)
        })
    };
    let result = child.graceful_shutdown_tree(Duration::from_secs(30));
    #[cfg(windows)]
    check.assert_fired();
    if authoritative {
        let status = result.expect("an authoritatively-drained tree must not invoke the sweep at all");
        assert!(
            term_fault::kill_tree_armed(),
            "the forced kill_tree failure must still be armed — the sweep was never entered"
        );
        drop(armed); // disarm now that this branch's own assertion above has run
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            assert_eq!(
                status.signal(),
                Some(libc::SIGTERM),
                "graceful root exit, got {status:?}"
            );
        }
        #[cfg(windows)]
        assert_eq!(
            status.code(),
            Some(0xC000013A_u32 as i32),
            "the root must die to the console event, not to a loader-init kill or the sweep, got {status:?}"
        );
    } else {
        // Either the marker is advisory (macOS, drain-observable but not authoritative) or
        // there is no kernel drain edge at all: either way the sweep is unconditional by design
        // (see graceful_shutdown_tree's own doc), so the forced failure must surface — proving
        // the sweep WAS entered, the opposite of the branch above.
        let err = result.expect_err("a non-authoritative mechanism must always run the sweep");
        assert!(
            !term_fault::kill_tree_armed(),
            "the sweep must have consumed the forced-failure seam"
        );
        drop(armed); // already disarmed by the sweep above; this is a no-op, kept for symmetry
        assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
        _ = child.kill_tree(); // cleanup: the forced failure means the real sweep never ran
        let status = child.wait().expect("the root was observed exited, so it is reaped");
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            assert_eq!(
                status.signal(),
                Some(libc::SIGTERM),
                "the root must die to the SIGTERM, not exit on its own, got {status:?}"
            );
        }
        #[cfg(windows)]
        assert_eq!(
            status.code(),
            Some(0xC000013A_u32 as i32),
            "the root must die to the console event, not to the cleanup sweep, got {status:?}"
        );
    }
}

/// A Job Object is authoritative: the drained tree skips the sweep.
#[cfg(windows)]
#[skuld::test]
fn graceful_tree_drained_skips_sweep_in_a_job_object() {
    drained_tree_sweep_decision(|cmd| _ = cmd.contain(), crate::Containment::JobObject);
}

/// A cgroup leaf is authoritative: the drained tree skips the sweep.
#[cfg(target_os = "linux")]
#[skuld::test]
fn graceful_tree_drained_skips_sweep_in_a_cgroup(#[fixture(cgroup)] _group: &Group) {
    drained_tree_sweep_decision(|cmd| _ = cmd.contain(), crate::Containment::CgroupV2);
}

/// A session (Linux) has no drain edge and the macOS fd marker's is advisory: the sweep always runs.
#[cfg(unix)]
#[skuld::test]
fn graceful_tree_drained_still_sweeps_without_an_authoritative_mechanism() {
    drained_tree_sweep_decision(
        |cmd| _ = crate::test_child::contain_without_cgroup(cmd),
        crate::test_child::contain_without_cgroup_gives(),
    );
}

// Regression test: on the `MembersRemain` branch (a drain-observable mechanism whose tree does
// NOT fully drain within `grace`), `root_exited` must come from its own zero-duration probe of the
// root, not be hardcoded `false`. Otherwise an already-exited-but-unreaped root is stranded as a
// zombie when the hard sweep also fails, because the best-effort reap is gated on `root_exited`.
//
// Fixture: the root shell ignores TERM (`trap ''` survives `exec`) and backgrounds a `cat` blocked
// on a stdin this test holds open, so the tree cannot drain. It then writes a readiness byte (the
// trap and background job are in place) and waits for a line on fd 4 before `exit 0`. The gate
// keeps the exit from racing `spawn()`.
// The test releases it with `x\n`: `read` returns on the newline, so the release does not depend
// on EOF, which a concurrent fork inheriting the write end would withhold. It then waits with
// `OwnedChild::exited_by`, which does not reap, so the root is an unreaped zombie when
// `graceful_shutdown_tree` runs. Asserting `Present` at that point keeps the final `Gone` from
// passing vacuously: had the test reaped the root itself, a mutant that skips the function's own
// reap would still read `Gone`.
//
// The `exec 3<&0; cat <&3 3<&- &` idiom is explained at `test_child::BLOCKER_ARGV`. Without a
// kernel drain edge, the fixture still exercises the root-only watch, asserted below.
//
// `mode` is the mechanism the root runs under, and `swept` asserts what a `kill_tree` says once the
// call has reaped the root.
#[cfg(unix)]
fn members_remain_still_reaps_an_already_exited_root(mode: crate::ContainMode, swept: impl FnOnce(&crate::Child)) {
    use std::io::{Read, Write};

    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args([
        "sh",
        "-c",
        "trap '' TERM; exec 3<&0; cat <&3 >/dev/null 3<&- & echo r; read _ <&4; exit 0",
    ]);
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    cmd.fd(4, crate::Stdio::pipe_in()).expect("set exit-gate pipe");
    cmd.contain_with(mode);
    let mut child = cmd.spawn().expect("spawn");
    // Held for the test's whole body: dropping it delivers EOF to the backgrounded `cat`.
    let stdin = child.stdin().expect("piped stdin");
    let mut exit_gate = child.fd_write_end(4.into()).expect("exit-gate write end");
    let mut readiness = [0u8; 1];
    child
        .stdout()
        .expect("piped stdout")
        .read_exact(&mut readiness)
        .expect("readiness byte");
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    // The root is still blocked on `read _ <&4`: release it, then wait for its exit WITHOUT
    // reaping.
    exit_gate.write_all(b"x\n").expect("release the root's exit 0");
    drop(exit_gate);
    assert!(
        child.proc.exited_by(None).expect("the root must exit"),
        "exited_by must observe the exit, not a timeout (None means unbounded)"
    );
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Present,
        "the exited root must still be an unreaped zombie before graceful_shutdown_tree runs"
    );
    term_fault::set_force_kill_tree_error(true);
    let err = child
        .graceful_shutdown_tree(Duration::from_secs(2))
        .expect_err("the forced sweep failure must surface");
    assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
    assert!(
        !term_fault::kill_tree_armed(),
        "the sweep must have consumed the forced-failure seam"
    );
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Gone,
        "an already-exited root must be best-effort reaped even when the sweep fails"
    );
    // The forced sweep failure was a stub, so the TERM-ignoring descendant is still alive, and the
    // call above reaped the root.
    swept(&child);
    drop(stdin);
}

/// The leaf is swept by its own handle.
#[cfg(target_os = "linux")]
#[skuld::test]
fn graceful_tree_members_remain_still_reaps_an_already_exited_root_in_a_cgroup(#[fixture(cgroup)] _group: &Group) {
    members_remain_still_reaps_an_already_exited_root(crate::ContainMode::Strongest, |child| {
        assert_eq!(child.containment(), crate::containment::Containment::CgroupV2);
        child.kill_tree().expect("the leaf is swept by its own handle");
    });
}

/// A cgroup leaf whose only listed member could not be shown to be in it got no `SIGTERM`, and the
/// call's answer is an `Unassessable` with a `source`. Nothing proves the send did not go out for the
/// others, so it holds like any failed check: the grace is waited and the sweep's `cgroup.kill` ends
/// the tree.
///
/// Mutant: a failed `terminate` whose `Unassessable` has one cause returns at once.
#[cfg(target_os = "linux")]
#[skuld::test]
fn graceful_tree_with_only_unprovable_members_still_sweeps_in_a_cgroup(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::fault::{fail_terminate_once, TerminateStep};
    let (child, stdin) = kill_only_blocker();
    assert_eq!(child.containment(), crate::containment::Containment::CgroupV2);
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let _pin = fail_terminate_once(TerminateStep::Pin, libc::EMFILE);
    let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);

    let status = child
        .graceful_shutdown_tree(Duration::ZERO)
        .expect("the sweep ends the tree the unprovable member left");

    crate::test_child::assert_killed("the root", status);
    assert_eq!(id.exists(), crate::identity::Existence::Gone, "the root is reaped");
}

/// A reaped root's group is not signalled by its number. The TERM-ignoring member keeps the group's
/// number its own while the call runs.
#[cfg(unix)]
#[skuld::test]
fn graceful_tree_members_remain_still_reaps_an_already_exited_root_in_a_process_group() {
    members_remain_still_reaps_an_already_exited_root(crate::ContainMode::Session, |child| {
        assert_eq!(child.containment(), crate::test_child::session_gives());
        // Below Linux 6.9 a group is signalled by its number alone.
        #[cfg(target_os = "linux")]
        let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
        let err = child
            .kill_tree()
            .expect_err("a reaped root's group is not signalled by its number");
        assert!(matches!(err, crate::error::Error::Unassessable { .. }), "got {err:?}");
    });
}

/// A sweep that left a descendant behind but whose backstop killed the root has killed the root: it
/// is reaped, its status is kept, and the sweep's error is what returns. The root ignores `SIGTERM`,
/// so the grace ends with it running and the sweep is what kills it. A reap of a root nothing
/// killed would not return. Mutant: the error is returned before the root is reaped.
#[cfg(all(unix, not(target_os = "macos")))]
#[skuld::test]
fn graceful_tree_that_left_a_descendant_reaps_the_root_the_backstop_killed_and_returns_the_error() {
    use std::io::Read as _;

    use crate::containment::treewalk::fault::{self, LeftBehind};

    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::TERM_IGNORING_BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    cmd.contain_with(crate::ContainMode::TreeWalk);
    let mut child = cmd.spawn().expect("spawn");
    let _stdin = child.stdin().expect("piped stdin");
    let mut readiness = [0u8; 1];
    child
        .stdout()
        .expect("piped stdout")
        .read_exact(&mut readiness)
        .expect("readiness byte");
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Present,
        "precondition: the root runs"
    );

    fault::force_incomplete_once(LeftBehind::Descendant);
    let err = child
        .graceful_shutdown_tree(Duration::from_millis(200))
        .expect_err("a descendant was left");

    assert!(matches!(err, crate::error::Error::MembersLeft { .. }), "{err:?}");
    assert_eq!(
        id.exists(),
        crate::identity::Existence::Gone,
        "the root the backstop killed must be reaped before the error returns"
    );
    crate::test_child::assert_killed("the root", child.wait().expect("the reaped root's status is kept"));
}

// Windows twin of `graceful_tree_members_remain_still_reaps_an_already_exited_root` above,
// reached via a job object instead of cgroup/process-group — but NOT a check on the same
// postcondition, because that postcondition does not translate. The Unix test proves an
// already-exited root is best-effort REAPED (`waitpid`-collected) even when the sweep also
// fails, so it never strands a zombie. Windows has no reap concept to strand: per the
// `shared_child` crate's own comment on its Windows backend (the dependency `SharedChild`
// replaced), "there's no such thing as reaping
// child processes on Windows — instead, you close the child handle when you're done with it,
// like a file", and `Child::wait()` never closes that handle on any Windows backend (raw or
// std) — only `Child`'s own `Drop` does. A Windows process object stays resolvable exactly as
// long as ANY handle referencing it is open, including this very `Child`'s own handle, held for
// this whole test — so `id.exists()` reports `Present` here whether or not the best-effort
// `self.wait()` call inside `graceful_shutdown_tree` ran, on both the fixed code and the bug it
// was meant to catch. There is no Windows-observable difference to assert here; asserting `Gone`
// would be tautologically false regardless of correctness (as CI's `left: Present, right: Gone`
// failure demonstrated) rather than evidence of anything. What IS Windows-observable, and
// exercised below, is that a drain-observable-but-not-fully-drained mechanism (`MembersRemain`)
// still runs the hard sweep and surfaces its failure — the same control flow this branch is
// otherwise built to protect.
//
// Fixture: `test_child::fixture_survives_group_signal` (see its own doc) plays the Unix root
// shell's role — it spawns a `CREATE_NEW_PROCESS_GROUP` grandchild the group `CTRL_BREAK` can
// never reach (forcing `MembersRemain` on the drain-observable job object, exactly like the Unix
// fixture's backgrounded, TERM-immune `cat`). The grandchild is itself a re-exec'd
// `fixture_registers_then_blocks`, blocked on a control socket connected DIRECTLY to the
// listener below — not to a socket the short-lived intermediate `fixture_survives_group_signal`
// process would itself own and then close on its own exit. That connect-and-tag IS the
// happens-before edge (the grandchild cannot tag until its own code is running, in its own
// group), over the same control-channel shape `tests/common::spawn_tree` uses (a stdout byte
// would not work here: the fixture's stdout is null — see the fixture's own doc). `sock` is held for this
// whole test: dropping it would deliver EOF and let the grandchild exit on its own, defeating
// the MembersRemain fixture.
#[cfg(windows)]
#[skuld::test]
fn windows_graceful_tree_members_remain_surfaces_the_forced_sweep_failure() {
    use std::io::Read;
    use std::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0").expect("bind readiness listener");
    let addr = listener.local_addr().expect("local_addr").to_string();

    // Asked: `graceful_shutdown_tree` breaks the root's console group, which a hidden root would
    // not be in.
    let mut cmd = crate::test_child::command(Console::Asked);
    cmd.executable(std::env::current_exe().expect("current_exe"))
        .args(crate::test_child::fixture_argv(
            crate::test_child::FIXTURE_SURVIVES_GROUP_SIGNAL_TEST,
        ));
    cmd.env(crate::test_child::FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR_ENV, addr);
    crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
    cmd.env(crate::test_child::ack::ACK_ENV, "1");
    cmd.contain();
    let child = std::sync::Arc::new(cmd.spawn().expect("spawn"));
    // The fixture exits at once and its descendant connects: see `accept_or_signalled`. The
    // watcher is detached, so the test returns its assertion or a failed kill even if the job
    // never drains.
    let drained = std::sync::Arc::new(crate::test_child::DrainSignal::new());
    {
        let (child, drained) = (child.clone(), drained.clone());
        std::thread::spawn(move || drained.watch(|| child.wait_tree()));
    }
    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        // Blocks until the survivor has connected, which it does only once it exists in its
        // own process group (see the fixture's own doc).
        let mut sock = crate::test_child::accept_or_signalled(&listener, &drained);
        let mut tag = [0u8; 1];
        sock.read_exact(&mut tag).expect("readiness tag");
        term_fault::set_force_kill_tree_error(true);
        let err = child
            .graceful_shutdown_tree(Duration::from_secs(2))
            .expect_err("the forced sweep failure must surface");
        assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
        assert!(
            !term_fault::kill_tree_armed(),
            "the sweep must have consumed the forced-failure seam"
        );
    }));
    // The forced failure was a stub, so the survivor lives; the real sweep (seam consumed) kills it
    // and drains the job.
    if let Err(e) = child.kill_tree() {
        let unwinding = outcome.as_ref().err().map(|p| {
            p.downcast_ref::<String>()
                .cloned()
                .or_else(|| p.downcast_ref::<&str>().map(|s| s.to_string()))
                .unwrap_or_default()
        });
        panic!("cleanup kill_tree failed ({e}); unwinding from: {unwinding:?}");
    }
    if let Err(payload) = outcome {
        std::panic::resume_unwind(payload);
    }
}

// `accept_or_signalled` fails once the job drains with nothing having connected, instead of
// waiting forever. The contained fixture matches no test, so it exits at once and leaves no
// descendant.
#[cfg(windows)]
#[skuld::test]
fn death_watch_windows_accept_or_signalled_panics_when_the_tree_drains_before_anything_connects() {
    use std::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0").expect("bind readiness listener");
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.executable(std::env::current_exe().expect("current_exe"))
        .args(crate::test_child::fixture_argv("test_child::__no_such_test__"));
    cmd.contain();
    let child = cmd.spawn().expect("spawn");
    let drained = crate::test_child::DrainSignal::new();
    let result = std::thread::scope(|scope| {
        scope.spawn(|| drained.watch(|| child.wait_tree()));
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            crate::test_child::accept_or_signalled(&listener, &drained)
        }))
    });
    let payload = result.expect_err("a drained job with no connection must panic");
    let message = payload
        .downcast_ref::<String>()
        .cloned()
        .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
        .expect("string panic payload");
    assert!(
        message.starts_with("the tree drained (") && message.ends_with(") before anything connected"),
        "got: {message:?}"
    );
    child.wait().expect("reap the root");
}

// A terminate_tree error that says nothing was sent (`NotSent`, modelling NoConsole/Unsupported)
// is not held: no signal went out, so no grace is waited and nothing is swept, and the tree is left
// running. `Duration::ZERO` here too: the function returns before ever reaching the watch,
// whatever the requested grace, so there is nothing to synchronize on.
#[skuld::test]
fn graceful_tree_non_containment_terminate_error_fails_fast() {
    let (mut child, stdin) = blocker();
    term_fault::set_force_terminate(term_fault::Forced::Unsupported);
    let err = child
        .graceful_shutdown_tree(std::time::Duration::ZERO)
        .expect_err("the forced Unsupported error must surface immediately");
    assert!(matches!(err, crate::error::Error::Unsupported { .. }), "got {err:?}");
    // Fails fast: no grace was waited, no sweep ran, so the child is STILL ALIVE.
    assert_still_running(&mut child, stdin);
    cleanup(&mut child);
}

/// A stand-in tree in a child's place, disarmed so its drop kills nothing, and the child's own tree put
/// back when this drops: a failing assertion cannot leave the stand-in to drop with the child, nor drop
/// the child's own tree early (which would tear the child down).
#[cfg(target_os = "linux")]
struct TreeStandIn<'a> {
    child: &'a mut crate::Child,
    own: Option<crate::containment::Tree>,
}

#[cfg(target_os = "linux")]
impl<'a> TreeStandIn<'a> {
    fn new(child: &'a mut crate::Child, stand_in: crate::containment::Tree) -> TreeStandIn<'a> {
        stand_in.disarm().expect("disarm the stand-in");
        let own = std::mem::replace(&mut child.tree, stand_in);
        TreeStandIn { child, own: Some(own) }
    }
}

#[cfg(target_os = "linux")]
impl Drop for TreeStandIn<'_> {
    fn drop(&mut self) {
        if let Some(own) = self.own.take() {
            self.child.tree = own;
        }
    }
}

/// A leaf whose `cgroup.procs` cannot be read listed no member, so nothing was sent: `NotSent`, which
/// `graceful_shutdown_tree` ends the call on, with no grace waited and no sweep, so the tree is left
/// running. Here `cgroup.procs` is a directory, which a real read of it fails on (`EISDIR`).
///
/// Mutant: the leaf's outer `Err` is read as a send that went out (`Sent { result: Err(..) }`), so the call
/// holds and sweeps and the child is dead.
#[cfg(target_os = "linux")]
#[skuld::test]
fn graceful_tree_over_a_leaf_whose_procs_cannot_be_read_fails_fast() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-unreadable-procs-leaf");
    std::fs::create_dir_all(leaf_path.join("cgroup.procs")).expect("make cgroup.procs a directory");
    let (mut child, stdin) = blocker();
    let in_place = TreeStandIn::new(
        &mut child,
        crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(
            crate::containment::cgroup::test_support::entered_leaf_at(leaf_path),
        )),
    );

    let err = in_place
        .child
        .graceful_shutdown_tree(std::time::Duration::ZERO)
        .expect_err("a leaf that cannot list its members sent nothing");

    drop(in_place);
    assert_eq!(crate::error::first_os_code(&err), Some(libc::EISDIR), "{err:?}");
    // Fails fast: no grace was waited, no sweep ran, so the child is STILL ALIVE.
    assert_still_running(&mut child, stdin);
    cleanup(&mut child);
}

/// A holders-only escalation whose wait for the holders it killed fails answers with the
/// holders-only error, as `kill_tree` answers a failed kill over a failed wait; the wait's failure is
/// logged once, at warn (`log_failed_wait`). The fake has no drain edge, so the grace wait fails too;
/// that failure is below the answer.
///
/// Mutants: `finish` puts the wait's failure in the error; `finish` returns the error without
/// waiting; the grace wait's failure is logged and dropped.
#[cfg(unix)]
#[skuld::test]
fn a_holders_only_escalation_whose_wait_fails_answers_the_holders_only_error() {
    use crate::containment::fake::FakeContains;
    use crate::containment::Containment;
    use crate::os_process::fake::Answer;
    use crate::test_child::over_fake::{child_with, holders_only_skip, root_looking};

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let root = root_looking([Answer::Exited]);
    let (fake, _) = FakeContains::new(Containment::Session, false);
    let child = child_with(&root, fake.reaching_unobserved(4242));
    let skip = holders_only_skip(&child);

    let error = child.shut_down_holders_only(skip, std::time::Duration::ZERO);

    assert!(
        matches!(&error, crate::error::Error::Unassessable { detail, .. }
            if detail.contains("sent the SIGTERM only to the marker holders")),
        "the answer is the holders-only error: {error}"
    );
    assert!(
        matches!(error.failures_below()[..], [crate::error::Error::Unsupported { .. }]),
        "the holders' grace wait's failure is its cause: {error:?}"
    );
    let waited = crate::log_capture::records_since_on_current_thread(mark, "the wait after a holders-only shutdown");
    assert!(
        matches!(&waited[..], [(log::Level::Warn, line)]
            if line.contains("pid 4242 was killed, but its exit cannot be observed")),
        "the member was waited for, and its failure is logged once, at warn: {waited:?}"
    );
}

/// A root reaped elsewhere (`ECHILD`) leaves no exit status: the answer is `Unassessable`, with the
/// `ECHILD` as its `source()`, so a caller can tell this from any other refusal.
///
/// Mutant: the answer drops the error of the wait.
#[cfg(unix)]
#[skuld::test]
fn a_root_reaped_elsewhere_answers_unassessable_with_its_echild_as_the_source() {
    use crate::error::Error;

    let waited = Err(Error::Io(std::io::Error::from_raw_os_error(libc::ECHILD)));

    let answer = super::status_unless_reaped_elsewhere(waited, 4242).expect_err("no exit status was collected");

    assert!(matches!(answer, Error::Unassessable { .. }), "{answer:?}");
    assert_eq!(crate::error::first_os_code(&answer), Some(libc::ECHILD), "{answer:?}");
}

/// An `ECHILD` deep in the chain of a variant that is not an `Error::Io` is not a root reaped
/// elsewhere: the wait's answer is kept as it is.
///
/// Mutant: any error with an `ECHILD` anywhere down its chain counts.
#[cfg(unix)]
#[skuld::test]
fn an_echild_below_a_variant_that_is_not_io_is_not_a_root_reaped_elsewhere() {
    use crate::error::Error;

    let echild = || Error::io_cause(std::io::Error::from_raw_os_error(libc::ECHILD));
    let waits = [
        Error::Containment {
            detail: "the wait's own failure".into(),
            source: Some(echild()),
        },
        Error::MemberNotKilled {
            pid: 4243,
            source: echild(),
        },
    ];
    for waited in waits {
        let words = waited.to_string();

        let answer = super::status_unless_reaped_elsewhere(Err(waited), 4242).expect_err("the wait failed");

        assert_eq!(answer.to_string(), words, "kept as it is: {answer:?}");
        assert!(!matches!(answer, Error::Unassessable { .. }), "{answer:?}");
    }
}

/// A wait's `ECHILD` below a context or a note is still a reap elsewhere: the answer is the same
/// `Unassessable`, and the wait's error, words included, is its `source()`.
///
/// Mutant: only a bare `Error::Io` with the code itself counts.
#[cfg(unix)]
#[skuld::test]
fn a_wrapped_echild_is_still_a_root_reaped_elsewhere() {
    use crate::error::Error;

    let echild = || std::io::Error::from_raw_os_error(libc::ECHILD);
    let waits = [
        Error::Io(crate::error::io_context("waiting for pid 4242", echild())),
        Error::Io(echild()).with_note("while tearing down"),
    ];
    for waited in waits {
        let words = waited.to_string();

        let answer = super::status_unless_reaped_elsewhere(Err(waited), 4242).expect_err("no exit status");

        assert!(matches!(answer, Error::Unassessable { .. }), "{answer:?}");
        assert_eq!(crate::error::first_os_code(&answer), Some(libc::ECHILD), "{answer:?}");
        let report = crate::error::said(&answer);
        assert!(report.contains(&words), "the wait's words are kept: {report}");
    }
}