cosca 0.9.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
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
//! Sweep tests. Every one runs against the real host process table with real descriptors —
//! nothing here is faked, because a sweep fired at a synthetic table proves nothing.
//!
//! Three rules these tests obey, because trials overlap in one process under `--nocapture`
//! with `--test-threads` > 1 (nextest runs each test in its own process):
//! never clear `FD_CLOEXEC` on a descriptor of the test process (a concurrent fork+exec on
//! another thread would leak it into an unrelated child); never key a log assertion on the
//! shared pid alone (every test shares it) — key on the marker handle; and every test that
//! calls `install()` (opening a write-end fd this process holds, CLOEXEC or not) holds
//! `test_spawn_lock()` for its WHOLE body, WHETHER OR NOT that test itself goes on to spawn.
//! The exposure is not "this test's own fork races its own write end" — it is "ANY sibling
//! test's fork, anywhere in this shared process, can land while THIS test's write end happens
//! to be open" — so the guard is owed by every test that opens one, not only the ones that also
//! fork. Without it, a sibling test's `.spawn()` could fork WHILE this test's marker write end
//! is open, transiently inheriting it; if that sibling is mid-`hard_kill()`/`holders()` at that
//! exact moment, its sweep would find and SIGKILL the bystander child.
//!
//! `test_spawn_lock()` is `crate::child::spawn::spawn_lock()` ITSELF, not a private mutex — a
//! separate lock would only serialize these tests against each other, not against every OTHER
//! fork in the same test binary. `cosca::Command::spawn()` (used by tests throughout this
//! crate) already takes `spawn_lock()` internally, so reusing it here gets those tests'
//! serialization for free.
//!
//! This reuse is what makes the guard effective crate-wide, not just within this module:
//! `crate::test_child::spawn_a_process_that_exits` (used by unrelated tests, e.g.
//! `identity/persist_tests.rs`) and every other `--lib`-binary fork site that could race a
//! marker-holding test here also take `spawn_lock()` around their own
//! `std::process::Command::spawn()`/`.output()` calls, for exactly the reason the paragraph
//! above states: any of those forking while THIS module's tests hold a marker write end open
//! could otherwise transiently inherit it, and a
//! concurrently-running `hard_kill()`/`holders()` scan in THIS module could then find and
//! SIGKILL that bystander.

use crate::test_child::{await_member_ready, member_command};
use crate::test_groups::{setuid, Group};
use std::io::BufRead;
use std::os::fd::{AsFd, AsRawFd};

use super::{holders, holds_marker, holds_marker_query, pipe_handle_of, MarkerQuery, PipeFdInfo, PROC_PIDFDPIPEINFO};

/// A root no process holds and no process can be a child of (past `PID_MAX`), so the ppid-walk
/// channel finds nothing and a test sees only the channels it is about.
pub(crate) fn inert_root() -> crate::identity::ProcessId {
    crate::identity::ProcessId::from_parts_for_test(0x7FFF_FFF0, crate::identity::Key::for_test(1))
}

/// `install` on `cmd`, as the only step of its hook.
pub(crate) fn install_on(
    cmd: &mut std::process::Command,
    reserved: &[std::os::fd::RawFd],
) -> Result<super::PreparedMarker, crate::error::Error> {
    crate::child::spawn::in_child::register_alone(cmd, |steps| super::install(steps, reserved, &host_kernel()))
}

/// `prepared`, whose marker's sweeps read through a kernel that refuses every read of `pid`'s record,
/// as the OS can: the identity of `pid` is `Unknown`.
fn refusing_reads_of(prepared: super::PreparedMarker, pid: crate::identity::RawPid) -> super::PreparedMarker {
    reading_through(prepared, crate::identity::unreadable(pid))
}

/// `prepared`, whose marker's sweeps read through `kernel`.
fn reading_through(
    prepared: super::PreparedMarker,
    kernel: impl crate::identity::Kernel + Send + 'static,
) -> super::PreparedMarker {
    super::PreparedMarker {
        kernel: crate::identity::spawn_kernel(kernel),
        ..prepared
    }
}

fn all_pids() -> Vec<crate::identity::RawPid> {
    crate::containment::enumerate::snapshot().0
}

/// See the module docs above: held for the WHOLE body of every test that both installs a
/// marker and spawns a real child, so no such test's fork can land inside another's marker
/// window when trials overlap (`--nocapture` with `--test-threads` > 1). Delegates to the SAME lock production code
/// uses, not a private one, so it also excludes every other cosca-originated spawn elsewhere
/// in this test binary.
fn test_spawn_lock() -> crate::child::spawn::SpawnLockGuard {
    crate::child::spawn::spawn_lock()
}

// No standalone layout test: the layout is guarded at compile time by the
// `const _: () = assert!(…)` trio in the implementation (the crate does not build if it's
// wrong), and at runtime by `a_live_pipe_has_a_nonzero_handle_distinct_per_end` plus the sweep
// tests below (the wrong struct returns `<= 0` and finds nobody — measured fact B's note). A
// test comparing hand-transcribed copies of the same measured-fact table against each other
// would not catch a transcription error either copy shared, so it adds no independent coverage.

/// A real pipe has a readable handle; the two ends are distinct kernel objects with distinct
/// handles, so matching on the write end's handle cannot match a process holding only a read end.
#[skuld::test]
fn a_live_pipe_has_a_nonzero_handle_distinct_per_end() {
    let (r, w) = std::io::pipe().expect("pipe");
    let hw = pipe_handle_of(w.as_fd()).expect("the write end is a pipe");
    let hr = pipe_handle_of(r.as_fd()).expect("the read end is a pipe");
    assert_ne!(hw, 0, "a live pipe's handle must be non-zero");
    assert_ne!(hw, hr, "the two ends of a pipe are distinct kernel objects");
}

/// The mechanism's identity claim needs more than "a released handle isn't reissued while
/// held" — it needs simultaneously-LIVE pipes to never share a handle, or `holders()` could
/// match an unrelated live process by coincidence and get it SIGKILL'd. Measured directly
/// rather than inferred from the `VM_KERNEL_ADDRHASH` name (which suggests a lossy hash): a
/// one-off measurement backing this claim used 20,000 simultaneously-live pipes (40,000
/// handles) on an unconstrained shell (see the final report). THIS test deliberately uses far
/// fewer: macOS's launchd-inherited soft `RLIMIT_NOFILE` defaults to 256 (measured on this host
/// via `launchctl limit maxfiles`), which is what a CI runner gets unless a step raises it, and
/// when trials overlap in one process (`--nocapture` with `--test-threads` > 1) — parking thousands of
/// descriptors here would both risk this test's own `pipe()` calls panicking with `EMFILE` and
/// starve concurrently-running sibling tests' `pipe()`/`File::open` calls into spurious `EMFILE`
/// failures. `N = 50` (100 descriptors) leaves comfortable headroom under even the unraised
/// default while still meaningfully exercising "many simultaneously-live handles, checked
/// pairwise" — weaker statistical power than the one-off 20,000-pipe measurement, but a
/// regression-pinning unit test's job here is to catch a REVERSION of the property (e.g. a
/// kernel/SDK change that reintroduces collisions), not to reproduce the full-scale measurement
/// inside a resource-constrained test process.
#[skuld::test]
fn many_simultaneously_live_pipes_never_share_a_handle() {
    const N: usize = 50;
    let mut pipes = Vec::with_capacity(N);
    for _ in 0..N {
        pipes.push(std::io::pipe().expect("pipe"));
    }
    let mut handles: Vec<u64> = Vec::with_capacity(N * 2);
    for (r, w) in &pipes {
        handles.push(pipe_handle_of(r.as_fd()).expect("read end handle"));
        handles.push(pipe_handle_of(w.as_fd()).expect("write end handle"));
    }
    let unique: std::collections::HashSet<u64> = handles.iter().copied().collect();
    assert_eq!(
        unique.len(),
        handles.len(),
        "{} simultaneously-live pipe handles must all be distinct; found {} unique among {}",
        N,
        unique.len(),
        handles.len()
    );
}

/// A non-pipe descriptor is reported as "not a pipe", never as handle 0.
#[skuld::test]
fn a_non_pipe_descriptor_has_no_pipe_handle() {
    let f = std::fs::File::open("/dev/null").expect("open /dev/null");
    assert!(
        pipe_handle_of(f.as_fd()).is_none(),
        "a character device is not a pipe and must not yield a pipe handle"
    );
}

/// THE MECHANISM'S CENTRAL SAFETY INVARIANT, measured rather than assumed. Once every write
/// end is closed, the kernel frees the pipe pair only if the read end is gone too — so while
/// the supervisor holds the read end, no newly created pipe on this host can ever carry the
/// marker's handle. (With BOTH ends closed the handle is re-issued to the very next pipe,
/// every time, which is why `Marker` owns the read end for its whole life.)
#[skuld::test]
fn holding_the_read_end_keeps_the_handle_from_being_reissued() {
    let (read, write) = std::io::pipe().expect("pipe");
    let handle = pipe_handle_of(write.as_fd()).expect("write end handle");
    drop(write); // the "tree drained" moment: the last write end goes away

    // Churn: allocate and free pipes, looking for the handle to come back.
    for _ in 0..2000 {
        let (r2, w2) = std::io::pipe().expect("churn pipe");
        let h2 = pipe_handle_of(w2.as_fd()).expect("churn handle");
        assert_ne!(
            h2, handle,
            "a new pipe took the marker's handle while the read end was still held — \
             the sweep could match an unrelated process"
        );
        drop((r2, w2));
    }
    drop(read);
}

/// The sweep must find this process, which really does hold the write end.
#[skuld::test]
fn the_sweep_finds_this_process_holding_the_marker() {
    let (_r, w) = std::io::pipe().expect("pipe");
    let handle = pipe_handle_of(w.as_fd()).expect("write end handle");
    let me = std::process::id();
    let found = holders(handle, &all_pids());
    assert!(
        found.iter().any(|h| h.pid == me),
        "the sweep must find pid {me}, which holds the marker; found {found:?}"
    );
    assert!(
        holds_marker(me, handle),
        "the single-pid membership check must agree with the sweep"
    );
}

/// `PROC_PIDLISTFDS` denial is measured to return `0` with `errno == EPERM`, not a negative
/// value — pinned here (independent of `pipe_fds_of`/`clear_errno_and_call`, which this fact
/// drives) so the `<= 0` failure gate cannot silently regress to the wrong assumption. pid 1
/// (launchd, root-owned) queried directly is the oracle; this crate's CI and dev hosts run
/// unprivileged, matching every other test here that assumes pid 1 is launchd and unreachable
/// as a signal target.
#[skuld::test]
fn proc_pidlistfds_denial_returns_zero_with_eperm_not_negative() {
    // SAFETY: the sizing form takes a null buffer; `__error()` returns this thread's own errno
    // cell, which writing 0 into is always defined.
    let n = unsafe {
        *libc::__error() = 0;
        libc::proc_pidinfo(1, libc::PROC_PIDLISTFDS, 0, std::ptr::null_mut(), 0)
    };
    let e = std::io::Error::last_os_error();
    assert_eq!(
        n, 0,
        "an EPERM denial from PROC_PIDLISTFDS is measured to return 0 on this platform, not a \
         negative value — a `< 0` failure gate would silently miss it"
    );
    assert_eq!(
        e.raw_os_error(),
        Some(libc::EPERM),
        "pid 1 (launchd, root-owned) must be denied to an unprivileged caller with EPERM; got {e}"
    );
}

/// `PROC_PIDFDPIPEINFO` on an fd that is not currently a pipe on the calling process — never
/// opened, already closed, or open but a different fd type — is measured to return `0` with
/// `errno == EBADF` in every case (not `ENOENT`/`EINVAL`/a type-specific code), pinned here so
/// `fd_pipe_info`'s `Absent` classification cannot silently drift from what the kernel actually
/// reports. Measured directly on this host: a never-opened fd, a closed-then-reused-numerically
/// pipe fd, and an open regular-file fd all produced identical `(0, EBADF)`.
#[skuld::test]
fn proc_pidfdinfo_on_a_non_pipe_fd_returns_zero_with_ebadf_not_a_type_specific_code() {
    let me = std::process::id() as libc::c_int;
    let mut info: PipeFdInfo = unsafe { std::mem::zeroed() };
    let size = std::mem::size_of::<PipeFdInfo>() as libc::c_int;

    // A regular file is open, valid, and NOT a pipe — this is the case the plan's own
    // `Absent` classification must cover, distinct from a genuinely unopened descriptor.
    let file = std::fs::File::open("/dev/null").expect("open /dev/null");
    // SAFETY: `info`'s pointer and `size` match; `file`'s fd stays valid for this call.
    let n = unsafe {
        *libc::__error() = 0;
        libc::proc_pidfdinfo(
            me,
            file.as_raw_fd(),
            PROC_PIDFDPIPEINFO,
            &mut info as *mut _ as *mut libc::c_void,
            size,
        )
    };
    let e = std::io::Error::last_os_error();
    assert_eq!(
        n, 0,
        "a non-pipe fd is measured to return 0, not a negative value; got {n}"
    );
    assert_eq!(
        e.raw_os_error(),
        Some(libc::EBADF),
        "a non-pipe fd is measured to fail with EBADF specifically (not ENOENT/EINVAL); got {e}"
    );
}

/// `holds_marker_query` must report `Denied`, not `NotHeld`, when the WHOLE-pid fd list read
/// is refused — collapsing the two would silently reclassify "still a member, now unreachable"
/// as "no longer a member" (the exact failure `MarkerQuery` exists to prevent; see its doc
/// comment). pid 1 (launchd, root-owned) is the same real, deterministic, unprivileged-EPERM
/// oracle `proc_pidlistfds_denial_returns_zero_with_eperm_not_negative` already establishes —
/// no fault injection needed for this one, since a real, always-available denial exists. The
/// handle value passed is irrelevant: the denial happens before any per-fd handle comparison.
#[skuld::test]
fn holds_marker_query_reports_denied_not_not_held_for_an_unqueryable_pid() {
    assert_eq!(
        holds_marker_query(1, 0),
        MarkerQuery::Denied,
        "pid 1 must be unqueryable (EPERM) to an unprivileged caller; a Denied fd-list read \
         must not be reported as NotHeld"
    );
}

/// A handle naming no live pipe finds nobody, and must not panic or mis-match. `0` is never a
/// valid `pipe_handle` (established above by `a_live_pipe_has_a_nonzero_handle_distinct_per_end`)
/// and cannot become one through any amount of churn (overlapping trials churn pipes in one
/// process), so this is race-free by
/// construction rather than by timing luck.
#[skuld::test]
fn a_dead_handle_finds_no_holders() {
    assert!(
        !holds_marker(std::process::id(), 0),
        "handle 0 is never a valid pipe_handle and must not be reported as held"
    );
}

// Installing the marker on a spawn =====

/// `fd_map::preserve` only clears FD_CLOEXEC — it does not renumber, so the marker keeps the
/// parent's descriptor NUMBER inside the child. `fd_map`'s user mappings `dup2` onto
/// their `child_fd` numbers in the same forked child, closing whatever occupies them, so a
/// marker on one of those numbers would be silently clobbered and the tree would silently
/// lose membership. `F_DUPFD_CLOEXEC` never overwrites an open descriptor, so only `child_fd`
/// values are hazards; std `dup2`s the stdio slots before any pre_exec hook runs, so 0-2 are too.
#[skuld::test]
fn the_marker_fd_is_chosen_clear_of_reserved_child_fds_stdio_and_the_conventional_shell_range() {
    use super::{safe_marker_fd, HIGH_FLOOR};
    assert_eq!(
        safe_marker_fd(7, &[]),
        HIGH_FLOOR,
        "even a low, uncontested candidate is raised clear of the conventional shell-\
         redirection range (3-9), not merely clear of stdio"
    );
    assert_eq!(
        safe_marker_fd(HIGH_FLOOR + 3, &[]),
        HIGH_FLOOR + 3,
        "a candidate already above the floor is kept"
    );
    assert!(
        safe_marker_fd(7, &[HIGH_FLOOR]) > HIGH_FLOOR,
        "a candidate colliding with a reserved fd must move up, even above the floor"
    );
    assert!(
        safe_marker_fd(4, &[3, 4, HIGH_FLOOR + 5]) > HIGH_FLOOR + 5,
        "the marker must clear the HIGHEST reserved fd, whether below or above the floor"
    );
    assert!(safe_marker_fd(1, &[]) >= 3, "the marker must never sit on a stdio slot");
    assert!(
        safe_marker_fd(0, &[3]) >= HIGH_FLOOR,
        "the high floor applies regardless of how low the reserved set is"
    );
}

/// The placement contract, asserted on the placed number itself: `install` must move the
/// marker above every reserved child fd it is told about.
///
/// `cmd` is never spawned here, but `install()` still opens a real, CLOEXEC'd write end in
/// THIS process that stays open for the rest of the test's body (module docs above) — the
/// fork-bystander exposure the lock guards against does not depend on this specific test ever
/// spawning, only on the write end being open while ANY sibling test forks.
#[skuld::test]
fn install_places_the_marker_above_every_reserved_child_fd() {
    let _serialize = test_spawn_lock();
    let reserved = [3, 4, 5, 6, 7, 8, 9, 10];
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = install_on(&mut cmd, &reserved).expect("install");
    assert!(
        prepared.fd > 10,
        "the marker landed on fd {}, which a user mapping would dup2 over",
        prepared.fd
    );
}

/// The same contract end to end, against a REAL colliding mapping: the child gets an fd
/// mapping on the number the marker would naturally have taken, and must still be a holder.
#[skuld::test]
fn a_child_with_a_colliding_fd_mapping_still_holds_the_marker() {
    let _serialize = test_spawn_lock();
    use crate::child::spawn::fd_map::{self, FdMapping};

    let (_probe_r, probe_w) = std::io::pipe().expect("probe pipe");
    // The number `install` would pick with nothing reserved.
    let natural = super::safe_marker_fd(probe_w.as_fd().as_raw_fd(), &[]);
    drop(probe_w);

    let filler = std::fs::File::open("/dev/null").expect("open /dev/null");
    let mut cmd = std::process::Command::new("/bin/sh");
    cmd.arg("-c")
        .arg("echo $$; read _ignored")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    // Both steps in one hook, as a spawn adds them.
    let mut steps = crate::child::spawn::in_child::InChild::default();
    let host = host_kernel();
    let prepared = super::install(&mut steps, &[natural], &host).expect("install");
    let handle = prepared.handle;
    fd_map::install(
        &mut steps,
        vec![FdMapping {
            parent_fd: filler.into(),
            child_fd: natural,
        }],
    )
    .expect("unique child fd");
    steps.register(&mut cmd);

    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut child = cmd.spawn().expect("spawn sh");
    drop(cmd);
    let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
    let mut line = String::new();
    out.read_line(&mut line).expect("read pid line");
    let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");

    assert!(
        holds_marker(kid, handle),
        "a user fd mapping on fd {natural} must not clobber the marker in the child"
    );
    let _keep_alive = prepared.read;

    drop(child.stdin.take()); // EOF releases the child (cleanup, not an assertion)
    _ = child.wait();
}

/// A real spawn through the real installer: the child must be a holder, and the SUPERVISOR
/// must not be — it hands the write end away, so it is never a member of its own tree.
#[skuld::test]
fn install_hands_the_marker_to_the_child_and_keeps_the_supervisor_out() {
    let _serialize = test_spawn_lock();
    let mut cmd = std::process::Command::new("/bin/sh");
    cmd.arg("-c")
        .arg("echo $$; read _ignored")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    let prepared = install_on(&mut cmd, &[]).expect("install");
    let handle = prepared.handle;
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut child = cmd.spawn().expect("spawn sh");
    drop(cmd); // the Command owns the write end; dropping it closes the supervisor's copy

    let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
    let mut line = String::new();
    out.read_line(&mut line).expect("read pid line");
    let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");

    let found = holders(handle, &all_pids());
    assert!(
        found.iter().any(|h| h.pid == kid),
        "the child must inherit the marker across exec; found {found:?}"
    );
    assert!(
        !found.iter().any(|h| h.pid == std::process::id()),
        "the supervisor must not hold the marker, or a sweep could signal it; found {found:?}"
    );
    let _keep_alive = prepared.read;

    drop(child.stdin.take());
    _ = child.wait();
}

/// A holder whose descriptor survives exec is NOT an imminent membership loss, so no warning
/// is due. The check runs against a spawned child (whose copy `fd_map::preserve` has
/// already un-CLOEXEC'd) rather than by mutating this process's own fd table, which a concurrent
/// fork+exec on another thread would leak. The assertion keys on the per-pid message
/// (`fd marker {handle:#x}: holder pid {kid} will lose the marker…`), not on the handle alone:
/// when trials overlap in one process (`--nocapture` with `--test-threads` > 1), the marker
/// write end is open in that shared process from `install()` until `drop(cmd)` — a SIBLING test's `Command::spawn()` forking in
/// that window transiently inherits this fd into a not-yet-`exec`'d bystander (documented in
/// "Holding the read end is a precondition of soundness"), whose CLOEXEC-armed copy of THIS
/// handle would satisfy a handle-only negative check by accident. Keying on the child's own pid
/// too makes that bystander unable to satisfy or spoil the assertion.
#[skuld::test]
fn a_child_holding_a_non_cloexec_marker_produces_no_exec_warning() {
    let _serialize = test_spawn_lock();
    crate::log_capture::install();
    let mut cmd = std::process::Command::new("/bin/sh");
    cmd.arg("-c")
        .arg("echo $$; read _ignored")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    let prepared = install_on(&mut cmd, &[]).expect("install");
    let handle = prepared.handle;
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut child = cmd.spawn().expect("spawn sh");
    drop(cmd);
    let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
    let mut line = String::new();
    out.read_line(&mut line).expect("read pid line");
    let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");

    let mark = crate::log_capture::mark();
    let found = holders(handle, &all_pids());
    let theirs = found.iter().find(|h| h.pid == kid).expect("the child holds the marker");
    assert!(
        !theirs.clexec,
        "fd_map::preserve clears FD_CLOEXEC in the child, so the marker survives its next exec"
    );
    assert!(
        !crate::log_capture::contains_since(
            mark,
            &format!("fd marker {handle:#x}: holder pid {kid} will lose the marker")
        ),
        "no exec warning is due for pid {kid}, whose own descriptor survives exec"
    );
    let _keep_alive = prepared.read;

    drop(child.stdin.take());
    _ = child.wait();
}

/// The complement: a holder whose descriptor is CLOEXEC WILL lose membership at its next exec,
/// and that must be visible one exec in advance via both `Holder.clexec` and a log line.
///
/// Constructed self-referentially against THIS test process, not a spawned child. A live
/// holder whose ONLY copy is CLOEXEC needs to be observed AFTER the exec that starts it, but
/// arming `FD_CLOEXEC` in a `pre_exec` hook closes the descriptor AT the exec that immediately
/// follows — it never survives to be observed as a live holder at all. Setting the flag from
/// WITHIN a live, already-running process is what the real property requires, and nothing
/// available to a unit test (`/bin/sh` has no `fcntl` builtin; a compiled testbin mode is
/// unavailable here — Global Constraints) can do that post-exec. `std::io::pipe()` sets
/// `FD_CLOEXEC` on both ends by default (the reason `install()` needs `F_DUPFD_CLOEXEC` +
/// `fd_map::preserve` to make the write end survive an exec at all), so a bare pipe's write end,
/// right here in this process, IS already the exact state under test — no fd-table mutation
/// needed, so this does not touch the "never clear FD_CLOEXEC on this process's own
/// descriptors" rule (that rule is about CLEARING an existing flag; this relies on the
/// default, never-cleared SET state).
#[skuld::test]
fn a_cloexec_holder_is_reported_and_warned_about() {
    crate::log_capture::install();
    let (_r, w) = std::io::pipe().expect("pipe");
    let handle = pipe_handle_of(w.as_fd()).expect("write end handle");
    let me = std::process::id();

    let mark = crate::log_capture::mark();
    let found = holders(handle, &all_pids());
    let theirs = found
        .iter()
        .find(|h| h.pid == me)
        .expect("this process holds the marker");
    assert!(theirs.clexec, "std::io::pipe() sets FD_CLOEXEC on both ends by default");
    assert!(
        crate::log_capture::contains_since(
            mark,
            &format!("fd marker {handle:#x}: holder pid {me} will lose the marker at its next exec")
        ),
        "an imminent membership loss must leave a log line naming the marker and the pid"
    );
}

/// THE DOCUMENTED ESCAPE, pinned by a test rather than by prose: a child that closes the
/// inherited descriptor leaves the containment set.
///
/// Ordered by a real handshake on BOTH sides of the close, not merely on the print after it:
/// printing `$$` alone orders nothing against the very next statement in the same script, since
/// nothing blocks the child between them — a shell runs its own script far faster than the
/// parent can complete a multi-syscall `holders()` scan, so the first check would otherwise race
/// the close and could observe it already gone (measured: it reliably does, on this host). The
/// child instead blocks on its own `read` immediately after printing `$$`, and only the
/// PARENT'S write releases it into the close — so the first `holds_marker` check is guaranteed
/// to run while the descriptor is still open, not merely likely to.
#[skuld::test]
fn a_child_that_closes_the_marker_leaves_the_holder_set() {
    let _serialize = test_spawn_lock();
    let mut cmd = high_fd_shell();
    cmd.stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    let prepared = install_on(&mut cmd, &[]).expect("install");
    let (handle, marker_fd) = (prepared.handle, prepared.fd);
    cmd.arg("-c").arg(format!(
        "echo $$; read _go; exec {marker_fd}>&-; echo closed; read _ignored"
    ));
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut child = cmd.spawn().expect("spawn bash");
    drop(cmd);

    let mut stdin = child.stdin.take().expect("piped stdin");
    let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
    let mut line = String::new();
    out.read_line(&mut line).expect("read pid line");
    let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");
    assert!(
        holds_marker(kid, handle),
        "the child inherited the marker, and must still hold it while blocked before its own close"
    );

    use std::io::Write;
    stdin.write_all(b"go\n").expect("release the child into its close");

    line.clear();
    out.read_line(&mut line).expect("read closed line");
    assert_eq!(
        line.trim(),
        "closed",
        "the child must confirm the close before the second check"
    );
    assert!(
        !holds_marker(kid, handle),
        "close(fd) leaves the containment set — the documented limit"
    );
    let _keep_alive = prepared.read;

    drop(stdin);
    _ = child.wait();
}

/// Each real failure arm of `install` fails with `Error::Containment` naming which step failed
/// (what `prepare` returns for `Strongest` and logs for the modes that degrade). The seams replace
/// the SYSCALL result, so the genuine branch — its own error and its own early return — is what
/// executes.
///
/// **Deliberate, documented exception to this crate's no-mocks rule**, not an oversight: these
/// three syscalls (`pipe()`, `F_DUPFD_CLOEXEC`, and "the marker pipe has no readable handle")
/// are genuinely hard to fail for real inside this suite without collateral damage.
/// `RLIMIT_NOFILE` (the textbook way to force `pipe()`/`fcntl` to fail) is PROCESS-WIDE, and
/// when trials overlap in one process (`--nocapture` with `--test-threads` > 1), lowering it would spuriously
/// fail any concurrently-running sibling test that happens to open a file or pipe at that
/// moment. The third arm (`pipe_handle_of` returning `None`) has no realistic real-world
/// trigger at all on a healthy pipe. The seam exercises exactly the code adjacent to each
/// injection point (each wrapper's own `if fault::take_if(X) { … }` arm), which is what needs
/// covering here; the SYSCALLS themselves (`pipe()`, `F_DUPFD_CLOEXEC`, `proc_pidfdinfo`) are
/// exercised for real, unmocked, by every OTHER test in this file's success paths. **State this
/// plainly rather than implying more:** this test proves `install`'s three early-return arms
/// compile and fail with the right message — it does NOT prove `install` fails correctly under a
/// genuine OS-level `pipe()`/`fcntl`/`proc_pidfdinfo` failure (`EMFILE`, `ENFILE`, …), whose exact
/// errno/shape this seam does not attempt to reproduce.
#[skuld::test]
fn each_install_failure_arm_fails_and_says_which_step_failed() {
    use super::fault::{set_fault, Fault};
    // `install` makes its pipe under `spawn_lock`, as a spawn does.
    let _spawn_lock = test_spawn_lock();
    for (fault, marker) in [
        (Fault::Pipe, "fd marker: pipe() failed"),
        (Fault::Place, "fd marker: could not place the marker descriptor"),
        (Fault::Handle, "fd marker: the marker pipe has no readable handle"),
    ] {
        let mut cmd = std::process::Command::new("/usr/bin/true");
        set_fault(Some(fault));
        let failed = install_on(&mut cmd, &[]).err();
        assert!(
            matches!(failed, Some(crate::error::Error::Containment { ref detail, .. }) if detail == marker),
            "a failed {fault:?} step must fail with {marker:?}, got {failed:?}"
        );
        assert!(
            super::fault::take_fault().is_none(),
            "the seam must be consumed by install"
        );
    }
}

// Teardown: one snapshot, three channels =====

/// The sweep must never signal the supervisor or pid 1. Asserted on the filter directly, not
/// inferred from "the test process is still alive" — which would pass by luck if the filter
/// were wrong and the signal merely failed.
#[skuld::test]
fn the_kill_filter_excludes_this_process_and_pid_one() {
    assert!(
        !super::is_signalable(std::process::id()),
        "the supervisor is never a sweep target"
    );
    assert!(!super::is_signalable(1), "pid 1 is never a sweep target");
    assert!(!super::is_signalable(0), "pid 0 is never a sweep target");
    assert!(
        super::is_signalable(std::process::id() + 1),
        "an ordinary pid is signalable"
    );
}

/// The shape the ppid walk structurally cannot reach: a descendant that calls `setsid`,
/// double-forks so its parent exits, is reparented to launchd, and execs — its ppid is 1, but
/// the marker sweep still finds it, and `hard_kill` kills it.
///
/// Deterministic with no timer: `sh` prints the orphan's pid, then exits; `wait()` returning
/// proves `sh` is gone, which is exactly the event that reparents the orphan. Death is proven
/// by EOF on the orphan's OWN inherited stdout, not by re-resolving its identity right after
/// `kill()` returns: `kill(2)` only posts the signal and returns immediately, so checking
/// `ProcessId::of` in the very next line races the kernel's own delivery-and-reap timing — a
/// zombie orphan (signalled, not yet reaped by launchd) still resolves via `proc_pidinfo` with
/// the SAME start token, so that check alone can pass before the kill has actually landed. `sh`
/// backgrounds `cat` without redirecting its stdout, so `cat` inherits `sh`'s piped stdout; once
/// `sh` exits (`child.wait()`, above), the orphaned `cat` is the pipe's ONLY remaining write
/// end, so a blocking read on it returns EOF exactly when `cat` dies — a real event, not a
/// timer.
///
/// The orphan is a `cat` blocked on a held stdin (see `test_child::BLOCKER_ARGV` for the
/// backgrounding idiom), so only `hard_kill()` can end it.
#[skuld::test]
fn hard_kill_reaches_a_setsid_double_forked_orphan_the_ppid_walk_cannot() {
    let _serialize = test_spawn_lock();
    let mut cmd = std::process::Command::new("/bin/sh");
    // `cat` inherits the marker across sh's fork and its own exec; `echo $!` publishes it.
    cmd.arg("-c")
        .arg("exec 3<&0; cat <&3 3<&- & echo $!")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    // setsid: the orphan leaves this process's session AND process group, so killpg misses it.
    // SAFETY: pre_exec runs post-fork, pre-exec; `libc::setsid` is async-signal-safe.
    unsafe {
        use std::os::unix::process::CommandExt;
        cmd.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
    let prepared = install_on(&mut cmd, &[]).expect("install");
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut child = cmd.spawn().expect("spawn sh");
    drop(cmd);

    // Held past the kill: `child.wait()` closes the child's own stdin, and only `hard_kill()` may
    // end the orphan.
    let mut stdin = child.stdin.take().expect("piped stdin");
    let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
    let mut line = String::new();
    out.read_line(&mut line).expect("read orphan pid");
    let orphan: crate::identity::RawPid = line.trim().parse().expect("orphan pid");
    child.wait().expect("reap sh"); // sh's exit is what reparents the orphan

    let (_, parents, _) = crate::containment::enumerate::snapshot();
    let ppid = parents.iter().find(|(p, _)| *p == orphan).map(|(_, pp)| *pp);
    assert_eq!(ppid, Some(1), "precondition: the orphan must be reparented to launchd");

    // The root is inert: sh is reaped, so ONLY the marker channel can reach the orphan.
    let orphan_id = crate::identity::ProcessId::of(orphan)
        .found()
        .expect("the orphan's identity");
    let marker = super::Marker::new(prepared, inert_root(), None);
    let mut killed = Vec::new();
    marker
        .hard_kill(
            Some(&crate::test_support::stated_root::StatedRoot::unreaped()),
            &mut killed,
        )
        .expect("hard_kill");
    assert!(
        killed.contains(&orphan_id),
        "the orphan is among the members the sweep reached, for the wait: {killed:?}"
    );
    assert!(
        !killed.contains(&inert_root()),
        "the root is not: its owner waits for it: {killed:?}"
    );

    // If `hard_kill()` missed the orphan, the live `cat` echoes this byte and then exits on the
    // EOF, so `rest` below is non-empty. If the kill landed, this writes to a dead pipe.
    crate::test_child::write_to_possibly_dead_stdin(&mut stdin, b"x");
    drop(stdin);

    // The proof: `cat` is the pipe's sole remaining writer, so EOF fires exactly on its
    // death — a real event, not a timer.
    let mut rest = Vec::new();
    std::io::Read::read_to_end(&mut out, &mut rest).expect("read to EOF on the orphan's stdout");
    assert!(rest.is_empty(), "unexpected trailing output from the orphan: {rest:?}");

    // No liveness assertion follows the EOF, deliberately: `proc_exit` invalidates the fd table
    // (what the EOF above observes) long before it marks the process a zombie, the state
    // `is_alive` reads — so `Alive` is reachable here for an orphan that has already died. Nor is
    // there a sound edge to wait for instead: this orphan belongs to launchd, so `waitid` returns
    // `ECHILD`. The EOF is the proof, and it is the only one available.
}

/// A pid that stopped holding the marker before the sweep must survive a REAL `hard_kill()`,
/// not merely fail the underlying `holds_marker` primitive in isolation (`a_dead_handle_finds_
/// no_holders`, Task 2, already covers that narrower claim) — proving `kill_holder`'s live
/// re-check inside a genuine sweep. The escapee is Task 3's documented `close(fd)` limit: it
/// closes the marker, confirms the close over the SAME pipe (ordering the sweep strictly
/// after, not racing it), then proves it is still alive by echoing back what the
/// test writes to it AFTER `hard_kill()` returns.
#[skuld::test]
fn hard_kill_never_reaches_a_pid_that_closed_the_marker_before_the_sweep() {
    let _serialize = test_spawn_lock();
    let mut cmd = high_fd_shell();
    cmd.stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    let prepared = install_on(&mut cmd, &[]).expect("install");
    let (handle, marker_fd) = (prepared.handle, prepared.fd);
    cmd.arg("-c").arg(format!(
        r#"echo $$; exec {marker_fd}>&-; echo closed; while read x; do echo "$x"; done"#
    ));
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut child = cmd.spawn().expect("spawn bash");
    drop(cmd);
    let mut out = std::io::BufReader::new(child.stdout.take().expect("piped stdout"));
    let mut line = String::new();
    out.read_line(&mut line).expect("read child pid");
    let kid: crate::identity::RawPid = line.trim().parse().expect("child pid");
    line.clear();
    out.read_line(&mut line).expect("read closed confirmation");
    assert_eq!(
        line.trim(),
        "closed",
        "the child must confirm the close before the sweep runs"
    );
    assert!(
        !holds_marker(kid, handle),
        "precondition: the escapee no longer holds the marker"
    );

    let marker = super::Marker::new(prepared, inert_root(), None);
    let mut killed = Vec::new();
    marker
        .hard_kill(
            Some(&crate::test_support::stated_root::StatedRoot::unreaped()),
            &mut killed,
        )
        .expect("hard_kill");
    assert!(
        killed.iter().all(|id| id.pid() != kid),
        "a holder that closed the marker is not among the members the sweep reached: {killed:?}"
    );

    // Alive, proven positively: a line in, the same line back — the sweep must not have
    // touched a pid that was never in its holder set to begin with.
    let mut stdin = child.stdin.take().expect("piped stdin");
    std::io::Write::write_all(&mut stdin, b"still-here\n").expect("write probe line");
    line.clear();
    out.read_line(&mut line).expect("read probe echo");
    assert_eq!(
        line.trim(),
        "still-here",
        "the escapee closed the marker before hard_kill ran and must survive it"
    );

    drop(stdin);
    _ = child.wait();
}

/// `pid_is_live_group_member` — the group-signal re-fire gate's anchor — confirms a real,
/// currently-live member of its own group, and rejects both a mismatched pgid and a pid that
/// has already exited (the `getpgid` call itself fails `ESRCH` for a gone pid, which is the
/// whole reason no separate liveness check is needed — see the function's doc).
#[skuld::test]
fn pid_is_live_group_member_confirms_membership_and_rejects_mismatch_or_death() {
    let _serialize = test_spawn_lock();
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut child = member_command(0).spawn().expect("spawn member"); // pgid == the child's own pid
    await_member_ready(&mut child);
    let pid = child.id() as crate::identity::RawPid;
    let pgid = child.id() as i32;

    assert!(
        super::pid_is_live_group_member(pid, pgid),
        "a live child must be confirmed a member of its own pgid"
    );
    assert!(
        !super::pid_is_live_group_member(pid, pgid.wrapping_add(1)),
        "a mismatched pgid must not be confirmed, even for a live pid"
    );

    child.kill().expect("kill");
    child.wait().expect("reap");
    assert!(
        !super::pid_is_live_group_member(pid, pgid),
        "a reaped pid must not be confirmed a member of anything — getpgid must fail ESRCH"
    );
}

/// A shell for scripts that redirect or close `marker_fd`, which `safe_marker_fd`/`HIGH_FLOOR` in
/// `fdmarker.rs` guarantee is always >= 64: the fd number sits BEFORE the operator, in the
/// IO_NUMBER position, and a dash-family shell only recognizes a single-digit IO_NUMBER there —
/// so `exec 64>&-` parses as plain `exec 64` with stdout closed, and fails with
/// "exec: 64: not found" rather than closing fd 64.
fn high_fd_shell() -> std::process::Command {
    std::process::Command::new("/bin/bash")
}

/// Item 1's central regression test: `sweep_pass`'s group-signal gate must re-fire on a LATER
/// pass when THAT pass's own holder scan just confirmed a fresh, live, `getpgid`-verified member
/// of `self.pgid` — closing the "a process joins the group strictly between passes" gap
/// `sweep_pass`'s own doc names — and the "skipping this pass's group signal" log line, the
/// probe an earlier review round used to catch this gap missing entirely, must NOT appear on
/// that pass.
///
/// `sweep_pass` is called directly, twice, bypassing `hard_kill`'s automatic loop — the only way
/// to get a deterministic injection point *between* two passes with no sleep and no race:
/// `hard_kill`'s own loop offers no such hook.
///
/// Four roles, three real target processes — all [`member_command`] members, none scanned until
/// [`await_member_ready`] has read its announcement:
/// - **P** mints a real, currently-valid pgid (`process_group(0)`: P's pgid == P's own pid), AND
///   carries a THROWAWAY marker (`scratch`, installed on P's own command) that exists only to
///   give pass 1 a valid `Marker` to call `sweep_pass` on — pass 1's own holder scan finding P
///   holding it is incidental (P dies from the group signal either way) and is not asserted on.
///   Reusing P's command this way, rather than leaving a SEPARATE unspawned command's write end
///   sitting open in this test process across pass 1, is what keeps this test itself clear of
///   the self-exclusion guard `sweep_pass` enforces on its caller (see below).
/// - **T** ("witness") carries the REAL marker (`marker`, installed on T's own command) `hard_
///   kill`/`terminate` would actually track. Not spawned until strictly between the two passes,
///   for two independent reasons that happen to coincide: (a) `pid_is_live_group_member` must
///   confirm T as a FRESH `pgid` member on pass 2, so T cannot have been a member during pass
///   1's unconditional `killpg`; (b) `install()`'s write end sits open in the CALLER (this test)
///   until the command is actually spawned, and `sweep_pass`'s own self-exclusion guard
///   `debug_assert!`-panics if a holder scan ever finds ITS OWN caller holding the marker it is
///   sweeping — so `marker`'s `install()` must not be called until immediately before spawning
///   T, with no `sweep_pass` call in between.
/// - **Q** ("protected target") holds no marker and is never named as `root`, so `killpg` on
///   `self.pgid` is the ONLY channel that can reach it. Q's death is therefore unambiguous proof
///   that pass 2's group signal actually fired, not a side effect of the marker or ppid-walk
///   channels. Also not spawned until between the two passes, for reason (a) above.
///
/// T and Q join `pgid` directly at their own spawn (`.process_group(pgid)`, a `setpgid(0, pgid)`
/// on THEMSELVES before their own `exec`, always POSIX-legal) rather than via a `setpgid` issued
/// BY this test after the fact: POSIX reserves that second form for a still-pre-`exec` child of
/// the caller, so a parent-issued `setpgid` on an already-`exec`'d child fails `EPERM`/`EACCES`
/// on every POSIX platform — measured here as `EPERM`, a real, unconditional OS restriction an
/// earlier draft of this test hit and had to route around, not a flake. `pgid` stays valid for T
/// and Q to join because P is left an unreaped zombie throughout (never `.wait()`ed) — the same
/// "the kernel still lists a zombie in its process group" fact `group_tests.rs`'s `await_zombie`
/// already relies on, applied here to keep `pgid` allocated across the gap instead of to query
/// it.
#[skuld::test]
fn sweep_pass_refires_the_group_signal_on_a_later_pass_that_confirms_a_new_live_member() {
    let _serialize = test_spawn_lock();
    crate::log_capture::install();

    let mut p_cmd = member_command(0); // pgid == P's own pid.
    let scratch = install_on(&mut p_cmd, &[]).expect("install scratch marker on P");
    // P is deliberately left unreaped for the rest of the test (see the doc above): that keeps
    // `pgid` allocated across the gap.
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut p_child = p_cmd.spawn().expect("spawn P");
    drop(p_cmd);
    await_member_ready(&mut p_child); // P's own group exists before T and Q ask to join it.
    let pgid = p_child.id() as i32;

    let pass1_marker = super::Marker::new(scratch, inert_root(), Some(pgid));
    let mut reached = Vec::new();
    let mut state = super::SweepState::new(&mut reached);

    // Pass 1: fires unconditionally (first_pass=true), killing P via killpg(pgid). Neither T
    // nor Q exists yet, so pass 1 cannot reach either regardless.
    pass1_marker.sweep_pass(
        nix::sys::signal::Signal::SIGKILL,
        &mut state,
        true,
        super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
    );
    drop(pass1_marker); // its scratch handle has no further use.

    // Between passes: T's real marker is installed and T is spawned in the same breath (no
    // sweep_pass call in between — see the self-exclusion note above), born directly into
    // `pgid`. Q is born into `pgid` too, holding no marker.
    let mut t_cmd = member_command(pgid);
    let prepared = install_on(&mut t_cmd, &[]).expect("install marker on T");
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut t_child = t_cmd.spawn().expect("spawn T");
    drop(t_cmd);
    // T is the member pass 2's own holder scan must find, so the scan runs behind T's
    // announcement — the state `spawn()` returning leaves unestablished.
    await_member_ready(&mut t_child);

    let mut q_cmd = member_command(pgid);
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut q_child = q_cmd.spawn().expect("spawn Q");
    // Q's announcement proves it is a live member of `pgid`, blocked on its stdin, before the
    // signal fires. It does NOT make a non-success exit proof of the signal: `wait()` closes Q's
    // piped stdin before waiting, and `read` at EOF exits `sh` 1 on its own — which is why the
    // assertion below is on the termination signal, not on `!success()`.
    await_member_ready(&mut q_child);

    let handle = prepared.handle;
    let marker = super::Marker::new(prepared, inert_root(), Some(pgid));
    let mark = crate::log_capture::mark();

    // A stand-in for the sibling record this assertion must ignore, emitted inside the window
    // it scans so the scoping below is proven on every run rather than argued: `log_capture` is
    // one process-global buffer, and every `kill_tree()` on a contained macOS child logs this
    // same sentence under ITS OWN handle on its second pass. Keyed on `0`, which `install`
    // refuses as a write-end handle, so it is provably not `handle` and provably not any live
    // marker's — the decoy cannot become the contamination it stands in for.
    log::debug!(
        "fd marker {:#x}: skipping this pass's group signal — no live member confirmed this \
         pass's pgid, so it may have been recycled",
        0u64
    );

    // Pass 2: T's own holder scan on THIS pass confirms a live member of `pgid` (T itself), so
    // the gate must open and the group signal must re-fire, reaching Q via killpg.
    marker.sweep_pass(
        nix::sys::signal::Signal::SIGKILL,
        &mut state,
        false,
        super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
    );

    // Keyed on THIS marker's handle, per the module docs' rule: the bare sentence is emitted by
    // every other marker's sweep too, so an unscoped probe reads a concurrent sibling's teardown
    // as this pass's own skip. `handle` names a pipe object that cannot be reissued while this
    // test holds the read end, so no simultaneously-live marker can share it.
    assert!(
        !crate::log_capture::contains_since(
            mark,
            &format!("fd marker {handle:#x}: skipping this pass's group signal")
        ),
        "pass 2 must not skip the group signal: a live, getpgid-confirmed member (T) was just \
         found in this pass's own holder scan"
    );

    // The proof: Q holds no marker and was never named `root`, so a SIGKILL on Q can only have
    // come from `killpg(pgid)`. It must be the signal that ended Q, not `wait()`'s own stdin
    // close: a gate that stopped re-firing would leave Q alive to read that EOF and exit 1,
    // which `signal()` reports as `None`.
    use std::os::unix::process::ExitStatusExt;
    let status = q_child.wait().expect("reap Q");
    assert_eq!(
        status.signal(),
        Some(libc::SIGKILL),
        "Q must have died from the pass-2 group signal (killpg on pgid), the only channel that \
         reaches it; got {status:?}"
    );

    // T is reachable by the marker channel too (this same pass 2 call's own holder-kill loop),
    // so it should already be gone or going; reap it rather than leave it running either way.
    _ = t_child.kill();
    _ = t_child.wait();
}

/// `kill_holder`'s `MarkerQuery::Denied` arm, end to end: a KNOWN holder that becomes
/// unqueryable at re-check time must be left unsignalled AND reported as a kill not attempted,
/// never silently treated as resolved. `id` names pid 1 (launchd) — the same real,
/// unprivileged-EPERM oracle used throughout this file — fed directly to the private method
/// rather than through a real sweep, since pid 1 can never naturally appear in a real sweep's
/// holder set (it does not hold this marker) or its ppid-walk (the pid 1 launchd walk read
/// would itself be catastrophic — see the `Marker::sweep`-level test below for why root=pid 1
/// is never used there either).
///
/// `ProcessId::of(1)` is asserted to resolve (not skipped if it doesn't): `identity/macos.rs`
/// falls back to the `sysctl(KERN_PROC_PID)` reader specifically because `proc_pidinfo` denies
/// pid 1 to an unprivileged caller, and that fallback is documented to succeed for exactly this
/// case — a `Resolved::Unknown` here would mean that documented fallback regressed, which this
/// test must fail loudly on, not quietly skip past.
#[skuld::test]
fn kill_holder_leaves_a_denied_pid_unsignalled_and_reports_incomplete() {
    let _serialize = test_spawn_lock();
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = install_on(&mut cmd, &[]).expect("install");
    let marker = super::Marker::new(prepared, inert_root(), None);

    let id = match crate::identity::ProcessId::of(1) {
        crate::identity::Resolved::Found(id) => id,
        other => panic!(
            "pid 1 must resolve via the documented sysctl fallback for this test's oracle to \
             hold; got {other:?}"
        ),
    };

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let outcome = marker.kill_holder(id, nix::sys::signal::Signal::SIGKILL);
    assert!(
        matches!(
            outcome,
            Some(crate::containment::treewalk::KillOutcome::NotAttempted(_))
        ),
        "a Denied re-check on a supposedly-known holder must be a kill not attempted (which the sweep \
         folds into `incomplete`), not silently succeed: {outcome:?}"
    );
    // The fd marker's own warning, once, naming the pid: the treewalk's text is for its own members.
    let warns = crate::log_capture::records_since_on_current_thread(mark, "pid 1 (a confirmed holder");
    assert!(
        matches!(&warns[..], [(log::Level::Warn, text)]
            if text.starts_with("fd marker ") && text.contains("not signalled, left running")),
        "{warns:?}"
    );
}

/// A later pass that re-fires the group signal after an earlier pass's group signal failed folds both
/// failures together: neither erases the other. A live holder in the group (P, which carries the
/// marker) is what opens the gate for the re-fire.
#[skuld::test]
fn a_refired_group_signal_that_fails_again_keeps_both_failures() {
    let _serialize = test_spawn_lock();
    let mut p_cmd = member_command(0); // pgid == P's own pid.
    let prepared = install_on(&mut p_cmd, &[]).expect("install marker on P");
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut p_child = p_cmd.spawn().expect("spawn P");
    drop(p_cmd);
    await_member_ready(&mut p_child);
    let pgid = p_child.id() as i32;

    let marker = super::Marker::new(prepared, inert_root(), Some(pgid));
    let mut reached = Vec::new();
    let mut state = super::SweepState::new(&mut reached);
    state.group_result = Err(crate::error::Error::Io(std::io::Error::from_raw_os_error(libc::EPERM)));
    let sends = crate::containment::unix::fault::record_kill_group();
    sends.fail_with_unassessable();

    marker.sweep_pass(
        nix::sys::signal::Signal::SIGKILL,
        &mut state,
        false,
        super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
    );

    assert_eq!(
        sends.killed(),
        [pgid],
        "the later pass must re-fire the group signal, or the row proves nothing"
    );
    let said = crate::error::said(state.group_result.as_ref().expect_err("both passes failed"));
    assert!(
        said.contains("os error 1") && said.contains("forced by a test"),
        "the group result must keep both failures: {said}"
    );

    _ = p_child.kill(); // P holds the marker, so the pass signalled it.
    _ = p_child.wait();
}

/// `finish_sweep` names what went wrong and no more: the still-forking text appears only for a sweep
/// that stopped on a count that did not fall, and the incomplete text only for an incomplete one.
#[skuld::test]
fn finish_sweep_names_only_the_causes_that_apply() {
    const INCOMPLETE: &str = "could not be assessed or signalled";
    const FORKING: &str = "still forking";
    let finish = |incomplete, still_forking| super::Marker::finish_sweep(0x1, Ok(()), incomplete, still_forking);
    let message = |result: Result<(), crate::error::Error>| match result {
        Err(crate::error::Error::Unassessable { detail, .. }) => detail,
        other => panic!("expected an Unassessable error; got {other:?}"),
    };

    let incomplete_only = message(finish(true, false));
    assert!(incomplete_only.contains(INCOMPLETE) && !incomplete_only.contains(FORKING));

    let forking_only = message(finish(false, true));
    assert!(forking_only.contains(FORKING) && !forking_only.contains(INCOMPLETE));

    let both = message(finish(true, true));
    assert!(both.contains(INCOMPLETE) && both.contains(FORKING));

    assert!(finish(false, false).is_ok(), "a sweep with neither cause is Ok");
}

/// A sweep that failed twice, a group send and an incomplete pass, returns the group's failure with the
/// incomplete summary as its peer, so the group's OS code is the one `first_os_code` finds.
///
/// Mutant: the incomplete summary comes first, so the code is lost below it.
#[skuld::test]
fn a_sweep_that_failed_twice_leads_with_the_groups_failure() {
    use crate::error::Error;
    let group = Error::Containment {
        detail: "the group could not be signalled".to_owned(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
    };
    let swept = super::Marker::finish_sweep(0x1, Err(group), true, false).expect_err("both failed");
    assert!(
        matches!(&swept, Error::Containment { detail, .. } if detail.contains("group")),
        "{swept:?}"
    );
    assert_eq!(crate::error::first_os_code(&swept), Some(libc::EPERM));
    let Error::Containment {
        source: Some(source), ..
    } = &swept
    else {
        panic!("{swept:?}");
    };
    assert!(
        matches!(&**source, Error::Several(list) if list.iter().len() == 2),
        "the incomplete summary is the group's peer: {source:?}"
    );
}

/// A pass counts the identities no earlier pass had seen. Two processes hold the marker (`sh`, and
/// the `cat` it forked), `sh` is already in `seen`, so the pass counts and signals `cat` alone.
///
/// Mutant: the count includes an identity already in `seen`.
#[skuld::test]
fn a_pass_counts_only_the_identities_no_earlier_pass_had_seen() {
    let _serialize = test_spawn_lock();
    let mut cmd = std::process::Command::new("/bin/sh");
    // `cat` inherits the marker across sh's fork; `echo $!` publishes it, and `wait` keeps `sh` alive.
    cmd.arg("-c")
        .arg("exec 3<&0; cat <&3 3<&- & echo $!; wait")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    let prepared = install_on(&mut cmd, &[]).expect("install");
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut sh = cmd.spawn().expect("spawn sh");
    drop(cmd);
    let mut out = std::io::BufReader::new(sh.stdout.take().expect("piped stdout"));
    let mut line = String::new();
    out.read_line(&mut line).expect("read cat's pid");
    let cat = crate::identity::ProcessId::of(line.trim().parse().expect("cat's pid"))
        .found()
        .expect("cat resolves");
    let sh_id = crate::identity::ProcessId::of(sh.id()).found().expect("sh resolves");

    let marker = super::Marker::new(prepared, inert_root(), None);
    let mut reached = Vec::new();
    let mut state = super::SweepState::new(&mut reached);
    state.seen.insert(sh_id);
    let found = marker.sweep_pass(
        nix::sys::signal::Signal::SIGKILL,
        &mut state,
        false,
        super::Scope::HoldersOnly { except: None },
    );

    assert_eq!(found, 1, "cat is the only identity no earlier pass had seen");
    assert!(state.seen.contains(&cat));
    drop(state);
    assert_eq!(reached, [cat], "the pass signals cat alone");

    _ = sh.kill();
    _ = sh.wait();
}

/// `Marker::sweep`'s top-level `incomplete`/`Err` return, end to end through the REAL public
/// `hard_kill()` — not a synthetic check of the `incomplete` bool in isolation. Forces a
/// genuinely blind pass via the enumerate backend's test-only fault seam (module docs at the
/// top of `enumerate/macos.rs`), NOT by naming an unkillable real pid as `root`: an unprivileged
/// but real identity like pid 1 cannot be used as `root` here, because the sweep's
/// `treewalk::walk_from` would then walk pid 1's ENTIRE real ppid subtree — every process on the host, launchd being
/// everyone's eventual ancestor — and this sweep would attempt to SIGKILL every one of them.
/// `inert_root()` and `pgid: None` keep every channel this test does not need inert, so the blind
/// pass is the ONLY source of `incomplete` — no real process is signalled by this test at all.
#[skuld::test]
fn hard_kill_reports_err_on_a_genuinely_blind_pass() {
    let _serialize = test_spawn_lock();
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = install_on(&mut cmd, &[]).expect("install");
    // The write end closes with the command: pass 1 finds the root, so a second, seeing pass
    // follows, and it must not find this process holding its own marker.
    drop(cmd);
    let marker = super::Marker::new(prepared, inert_root(), None);

    crate::containment::enumerate::force_blind_snapshots(1);
    let result = marker.hard_kill(
        Some(&crate::test_support::stated_root::StatedRoot::unreaped()),
        &mut Vec::new(),
    );

    assert!(
        result.is_err(),
        "a sweep whose only pass was blind must report Err, not silently converge as Ok(())"
    );
}

/// A pass whose root's identity cannot be read (its kernel refuses its record, as the OS can) skips
/// the walk channel and is `incomplete`: not observed is not observed absent. The
/// root is already in `seen`, so the pass signals no one, and the walk is the only source of
/// `incomplete`, and no walk is recorded. The warn names the marker handle. Mutants: the unreadable
/// root is `Ok(None)` (a gone root), which walks nothing and reports a complete pass; the walk is
/// recorded before the root is proved.
#[skuld::test]
fn a_pass_whose_root_cannot_be_read_skips_the_walk_and_is_incomplete() {
    let _serialize = test_spawn_lock();
    crate::log_capture::install();
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = install_on(&mut cmd, &[]).expect("install");
    drop(cmd);
    let root = inert_root();
    let marker = super::Marker::new(refusing_reads_of(prepared, root.pid()), root, None);

    let mut reached = Vec::new();
    let mut state = super::SweepState::new(&mut reached);
    state.seen.insert(root);
    let walks = crate::containment::treewalk::fault::record_walks();
    let mark = crate::log_capture::mark();
    let found = marker.sweep_pass(
        nix::sys::signal::Signal::SIGKILL,
        &mut state,
        true,
        super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
    );

    assert!(state.incomplete, "an unreadable root is not a complete walk");
    assert_eq!(found, 0, "nothing was found or signalled");
    assert_eq!(
        walks.walked(),
        Vec::<u32>::new(),
        "no walk began from a root that could not be read"
    );
    let warned = crate::log_capture::records_since_on_current_thread(
        mark,
        &format!(
            "fd marker {:#x}: the root's descendants could not be walked",
            marker.handle
        ),
    );
    assert_eq!(warned.len(), 1, "{warned:?}");
}

/// A pass whose walk cannot read a live child of its live root (its kernel refuses the child's
/// record, as the OS can) does not signal it and is `incomplete`: not observed is not
/// observed absent. The root is already in `seen`, so the child is the only candidate and nothing
/// is signalled. Mutant: the sweep takes the walk's members and ignores `unassessed`: the pass
/// reports complete.
#[skuld::test]
fn a_pass_with_a_child_that_cannot_be_read_does_not_signal_it_and_is_incomplete() {
    use std::io::Read as _;
    use std::os::unix::process::ExitStatusExt as _;

    let _serialize = test_spawn_lock();
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = install_on(&mut cmd, &[]).expect("install");
    drop(cmd);
    // A root `sh` that has announced its pid and forked an `sh` that prints `released` at EOF of its
    // stdin, which the test holds the write end of.
    let mut root_cmd = std::process::Command::new("/bin/sh");
    root_cmd
        .arg("-c")
        .arg("exec 3<&0; sh -c 'read _ignored; echo released' <&3 3<&- & echo $$; wait")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut root_child = root_cmd.spawn().expect("spawn the root");
    crate::test_child::await_member_ready(&mut root_child);
    let root = crate::identity::ProcessId::of(root_child.id())
        .found()
        .expect("the live root resolves");
    let children = root
        .children(crate::Recursive::No)
        .expect("the root's children are readable");
    let [child] = children[..] else {
        panic!("the root has exactly one child, got {children:?}");
    };
    let marker = super::Marker::new(refusing_reads_of(prepared, child.pid()), root, None);

    let mut reached = Vec::new();
    let mut state = super::SweepState::new(&mut reached);
    state.seen.insert(root);
    let found = marker.sweep_pass(
        nix::sys::signal::Signal::SIGKILL,
        &mut state,
        true,
        super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
    );

    assert!(
        state.incomplete,
        "a child the walk could not read is not a complete walk"
    );
    assert_eq!(found, 0, "nothing was found or signalled");
    drop(root_child.stdin.take());
    let mut printed = String::new();
    root_child
        .stdout
        .take()
        .expect("piped stdout")
        .read_to_string(&mut printed)
        .expect("read to EOF");
    assert_eq!(
        printed, "released\n",
        "the unreadable child must not have been signalled"
    );
    let status = root_child.wait().expect("reap the root");
    assert_eq!((status.signal(), status.code()), (None, Some(0)));
}

/// A [`member_command`] child that holds a marker installed on it, with the marker's parts. The caller
/// holds `test_spawn_lock()` for its whole body.
fn held_child() -> (std::process::Child, super::PreparedMarker) {
    let mut cmd = member_command(0);
    let prepared = install_on(&mut cmd, &[]).expect("install the marker on the child");
    #[allow(
        clippy::disallowed_methods,
        reason = "the caller holds spawn_lock for its whole body"
    )]
    let mut child = cmd.spawn().expect("spawn the child");
    drop(cmd);
    await_member_ready(&mut child);
    (child, prepared)
}

/// A marker holder that the marker's kernel cannot read (its record is refused, as the OS can, while
/// the host reads it) is not signalled, and the sweep is `incomplete`: the holder's identity is read
/// through the marker's kernel. The rows are asserted taken.
///
/// Mutant: the sweep reads the holder through `HostKernel`: the host finds it, the sweep signals it,
/// and the rows are left.
#[skuld::test]
fn a_holder_its_kernel_cannot_read_is_not_signalled_and_the_sweep_is_incomplete() {
    use crate::identity::{FakeKernel, HostKernel, ReadErr};

    let _serialize = test_spawn_lock();
    let (holder, prepared) = held_child();
    let pid = holder.id();
    let kernel = std::sync::Arc::new(
        FakeKernel::over(&HostKernel)
            .on_bsd_info(pid, Err(ReadErr::Refused(libc::EPERM)))
            .on_kinfo_refused(pid, libc::EPERM),
    );
    let root = inert_root();
    let marker = super::Marker::new(reading_through(prepared, std::sync::Arc::clone(&kernel)), root, None);

    let mut reached = Vec::new();
    let mut state = super::SweepState::new(&mut reached);
    state.seen.insert(root);
    let found = marker.sweep_pass(
        nix::sys::signal::Signal::SIGKILL,
        &mut state,
        true,
        super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
    );

    assert!(
        kernel.all_rows_taken(),
        "the holder was read through the marker's kernel"
    );
    assert!(state.incomplete, "a holder that cannot be read is not a complete sweep");
    assert_eq!(found, 0, "nothing was found or signalled");
    crate::child::spawn::identity_macos_tests::end_unsignalled_and_reap(pid);
}

/// A sweep's kill of a member its walk found reads the member's identity through the marker's kernel:
/// a kernel that refuses that read leaves the member running and the sweep `incomplete`. The root is
/// the member, and the walk's reads of it are records, so the unique-id row is the kill's. The row is
/// asserted taken.
///
/// Mutant: the sweep's kill reads through `HostKernel`: the host finds the member, which is killed, and
/// the row is left.
#[skuld::test]
fn a_sweeps_kill_of_a_walked_member_reads_its_identity_through_the_markers_kernel() {
    use crate::identity::{FakeKernel, HostKernel};

    let _serialize = test_spawn_lock();
    let (member, prepared) = held_child();
    let pid = member.id();
    let root = crate::identity::ProcessId::of(pid)
        .found()
        .expect("the live member resolves");
    let kernel = std::sync::Arc::new(
        FakeKernel::over(&HostKernel).on_unique_info(pid, crate::child::spawn::identity_macos_tests::REFUSED_KILL_READ),
    );
    let marker = super::Marker::new(reading_through(prepared, std::sync::Arc::clone(&kernel)), root, None);

    let mut reached = Vec::new();
    let mut state = super::SweepState::new(&mut reached);
    marker.sweep_pass(
        nix::sys::signal::Signal::SIGKILL,
        &mut state,
        true,
        super::Scope::Full(Some(&crate::test_support::stated_root::StatedRoot::unreaped())),
    );

    assert!(
        kernel.all_rows_taken(),
        "the kill read the member's identity through the marker's kernel"
    );
    assert!(
        state.incomplete,
        "a member whose kill was refused is not a complete sweep"
    );
    crate::child::spawn::identity_macos_tests::end_unsignalled_and_reap(pid);
}

/// A holder's kill reads its identity through the marker's kernel: a kernel that refuses that read
/// leaves the holder running, and the kill is not attempted. The row is asserted taken.
///
/// Mutant: the holder's kill reads through `HostKernel`: the host finds the holder, which is killed, and
/// the row is left.
#[skuld::test]
fn a_holders_kill_reads_its_identity_through_the_markers_kernel() {
    use crate::identity::{FakeKernel, HostKernel};

    let _serialize = test_spawn_lock();
    let (holder, prepared) = held_child();
    let pid = holder.id();
    let id = crate::identity::ProcessId::of(pid)
        .found()
        .expect("the live holder resolves");
    let kernel = std::sync::Arc::new(
        FakeKernel::over(&HostKernel).on_unique_info(pid, crate::child::spawn::identity_macos_tests::REFUSED_KILL_READ),
    );
    let marker = super::Marker::new(
        reading_through(prepared, std::sync::Arc::clone(&kernel)),
        inert_root(),
        None,
    );

    let outcome = marker.kill_holder(id, nix::sys::signal::Signal::SIGKILL);

    assert!(
        matches!(
            outcome,
            Some(crate::containment::treewalk::KillOutcome::NotAttempted(_))
        ),
        "{outcome:?}"
    );
    assert!(
        kernel.all_rows_taken(),
        "the kill read the holder's identity through the marker's kernel"
    );
    crate::child::spawn::identity_macos_tests::end_unsignalled_and_reap(pid);
}

/// Two failures of one teardown fold into one error with both failures whole as the members of the
/// `Several` below it, and neither's words in the detail. The variant says what failed:
/// `Containment` when either is one, else `Unassessable`.
///
/// Mutants: the two are joined into a text; a `Containment` folds into `Unassessable` because the
/// other side is not one, or two failures that are none into `Containment`.
#[skuld::test]
fn two_group_errors_fold_into_one_variant_with_both_below_it() {
    use crate::error::Error;
    let ordinary = |detail: &str| Error::Containment {
        detail: detail.to_owned(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
    };
    let mechanism = || Error::Io(std::io::Error::from_raw_os_error(libc::EIO));
    let below = |error: &Error| {
        let (Error::Containment { source, detail } | Error::Unassessable { source, detail }) = error else {
            panic!("{error:?}");
        };
        let Some(source) = source else {
            panic!("no cause: {error:?}");
        };
        let Error::Several(list) = &**source else {
            panic!("expected Several, got {source:?}");
        };
        (
            detail.clone(),
            list.iter()
                .map(|m| crate::error::first_os_code(&**m))
                .collect::<Vec<_>>(),
        )
    };

    let both_ordinary = super::combine_group_errors(ordinary("first words"), ordinary("latest words"));
    assert!(matches!(both_ordinary, Error::Containment { .. }), "{both_ordinary:?}");
    let (detail, codes) = below(&both_ordinary);
    assert_eq!(codes, [Some(libc::EPERM), Some(libc::EPERM)]);
    assert!(!detail.contains("words"), "{detail}");

    let one_containment = super::combine_group_errors(ordinary("first words"), mechanism());
    assert!(
        matches!(one_containment, Error::Containment { .. }),
        "{one_containment:?}"
    );
    assert_eq!(below(&one_containment).1, [Some(libc::EPERM), Some(libc::EIO)]);

    let none_containment = super::combine_group_errors(
        Error::Unassessable {
            detail: "unknown".to_owned(),
            source: None,
        },
        Error::Unassessable {
            detail: "unknown too".to_owned(),
            source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EIO))),
        },
    );
    assert!(
        matches!(none_containment, Error::Unassessable { .. }),
        "{none_containment:?}"
    );
    assert_eq!(below(&none_containment).1, [None, Some(libc::EIO)]);
}

// Holders-only sweeps (a reaped root) =====

/// A marker nothing was spawned under, its write end closed with the command, whose sweeps read
/// through `kernel`.
fn marker_without_holders(
    root: crate::identity::ProcessId,
    pgid: Option<i32>,
    kernel: crate::identity::SpawnKernel,
) -> super::Marker {
    let mut cmd = std::process::Command::new("true");
    let prepared = install_on(&mut cmd, &[]).expect("install a scratch marker");
    drop(cmd);
    super::Marker::new(super::PreparedMarker { kernel, ..prepared }, root, pgid)
}

/// The kernel of the host, as a spawn starts with it.
fn host_kernel() -> crate::identity::SpawnKernel {
    crate::identity::spawn_kernel(crate::identity::HostKernel)
}

/// A group that cannot be signalled (`pgid` 0, which `signal_group` refuses) means the marker's
/// terminate sent nothing: the tree call says so, so `graceful_shutdown_tree` ends at once.
///
/// Mutant: the refusal folds into `Sent { result: Err(..) }`, which `graceful_shutdown_tree` holds for.
#[skuld::test]
fn a_terminate_whose_group_cannot_be_signalled_says_nothing_was_sent() {
    let _serialize = test_spawn_lock();
    let marker = marker_without_holders(inert_root(), Some(0), host_kernel());
    let root = crate::test_support::stated_root::StatedRoot::unreaped();
    match marker.terminate_tree(Some(&root)) {
        crate::containment::TerminateOutcome::NotSent(crate::error::Error::Unassessable { source: None, .. }) => {}
        other => panic!("expected NotSent(Unassessable), got {other:?}"),
    }
}

/// A terminate that sent nothing keeps what else went wrong in the pass: the group's refusal is below
/// the `NotSent` error with the unreadable root's incomplete walk as its peer, as `finish_sweep` says it.
/// A group refusal with no cause of its own leaves the incomplete summary as its whole cause.
///
/// Mutant: `NotSent` carries the group's refusal alone, dropping the members the pass could not reach.
#[skuld::test]
fn a_terminate_that_sent_nothing_keeps_the_members_it_could_not_reach() {
    let _serialize = test_spawn_lock();
    let root_id = inert_root();
    let marker = marker_without_holders(
        root_id,
        Some(0),
        crate::identity::spawn_kernel(crate::identity::unreadable(root_id.pid())),
    );
    let root = crate::test_support::stated_root::StatedRoot::unreaped();
    match marker.terminate_tree(Some(&root)) {
        crate::containment::TerminateOutcome::NotSent(crate::error::Error::Unassessable {
            detail,
            source: Some(source),
        }) => {
            assert!(
                detail.contains("not a valid group id"),
                "the group's failure first: {detail}"
            );
            assert!(
                matches!(&*source, crate::error::Error::Unassessable { detail, .. } if detail.contains("incomplete")),
                "{source:?}"
            );
        }
        other => panic!("expected NotSent(the group's refusal over the incomplete walk), got {other:?}"),
    }
}

/// A group that cannot be signalled is one failed channel, not the end of the pass: a marker holder is
/// still sent the `SIGTERM`, so the signal went out and the answer is `Sent`, with the group's failure
/// among the errors checked after it (`graceful_shutdown_tree` holds the grace and sweeps for it).
///
/// Mutant: the failed group send ends the pass, so the holder is not signalled and the answer is `NotSent`.
#[skuld::test]
fn a_group_send_that_fails_while_a_holder_is_signalled_is_sent() {
    use std::os::unix::process::ExitStatusExt;
    let _serialize = test_spawn_lock();
    let mut holder_cmd = member_command(0);
    let prepared = install_on(&mut holder_cmd, &[]).expect("install the marker on the holder");
    #[allow(
        clippy::disallowed_methods,
        reason = "the test holds spawn_lock for its whole body via `_serialize`"
    )]
    let mut holder = holder_cmd.spawn().expect("spawn the holder");
    drop(holder_cmd);
    await_member_ready(&mut holder);
    let marker = super::Marker::new(prepared, inert_root(), Some(0));
    let root = crate::test_support::stated_root::StatedRoot::unreaped();

    let outcome = marker.terminate_tree(Some(&root));

    let status = holder.wait().expect("reap the holder");
    assert_eq!(status.signal(), Some(libc::SIGTERM), "the holder was sent the SIGTERM");
    match outcome {
        crate::containment::TerminateOutcome::Sent {
            result: Err(crate::error::Error::Unassessable { source: None, .. }),
            ..
        } => {}
        other => panic!("expected Sent with the group's refusal, got {other:?}"),
    }
}

/// A kill skipped because the root was reaped elsewhere names what the marker would have done by the
/// root's number: the walk always, and the group only when the mode made one.
#[skuld::test]
fn a_skipped_kill_names_the_walk_and_the_group_only_when_there_is_one() {
    let _serialize = test_spawn_lock();
    let reaped = crate::test_support::stated_root::StatedRoot::with_state(4242, || crate::signal::RootState::Reaped);
    let skipped = |marker| {
        let kill = crate::containment::Tree::contained(crate::containment::Mechanism::Marker(marker))
            .kill(Some(&reaped))
            .outcome();
        let skipped = kill
            .skipped()
            .expect("the reaped root's kill by its number is skipped")
            .to_owned();
        kill.into_result().expect("the holders-only sweep");
        skipped
    };

    let root = crate::identity::ProcessId::from_parts_for_test(4242, crate::identity::Key::for_test(1));
    let rooted = skipped(marker_without_holders(root, None, host_kernel()));
    assert!(
        rooted.contains("root pid 4242") && !rooted.contains("pgid"),
        "{rooted:?}"
    );

    let grouped = skipped(marker_without_holders(root, Some(4243), host_kernel()));
    assert!(
        grouped.contains("pgid 4243") && grouped.contains("root pid 4242"),
        "{grouped:?}"
    );
}

/// A sweep's kill of a member that refuses it (a setuid-root root refuses its caller's `SIGKILL`) warns
/// of the refusal once, though the member is both found by the walk and a holder of the marker.
///
/// Mutants: the sweep does not warn of it; it warns once for each channel that finds the member.
#[skuld::test]
fn a_sweep_warns_once_of_a_member_that_refuses_the_kill(#[fixture(setuid)] _group: &Group) {
    use std::io::Read as _;
    crate::log_capture::install();
    let mut cmd = crate::test_privilege::setuid_blocker_command();
    cmd.contain();
    cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
    cmd.stderr(crate::Stdio::null()).expect("stderr null");
    let mut child = cmd.spawn().expect("spawn the setuid helper");
    let stdin = child.stdin().expect("piped stdin");
    let mut ready = [0u8; 1];
    child
        .stdout()
        .expect("piped stdout")
        .read_exact(&mut ready)
        .expect("the helper reports ready");
    assert_eq!(ready, *b"+");
    let mark = crate::log_capture::mark();

    child.kill_tree().expect_err("the root refuses the kill");

    let warned = crate::log_capture::warns_since(mark, "was sent no SIGKILL");
    assert_eq!(warned.len(), 1, "{warned:?}");
    drop(stdin);
    assert!(child.wait().expect("the helper exits on EOF").success());
}