cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
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
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
//! Per-OS containment dispatch (two-phase: prepare before spawn, attach after).

use crate::containment::{ContainMode, ContainRequest, Containment, Nesting};
use crate::error::Error;

/// The pre-spawn containment decision produced by `prepare` (env-marker root
/// detection plus per-OS pre-spawn setup).
pub(crate) struct Prepared {
    pub mode: Option<ContainMode>,
    pub is_root: bool,
    /// Pre-created cgroup leaf (Linux only). `Some` means the child must be
    /// placed in the cgroup by the in-child placement step; `None` means fall back
    /// to the process-group mechanism.
    #[cfg(target_os = "linux")]
    pub cgroup_leaf: Option<crate::containment::cgroup::CgroupLeaf>,
    /// Set by a failed async spawn's teardown: this long into each of its waits for the leaf's
    /// drain, a leaf dropped or abandoned here, before `attach` takes it, warns once and keeps
    /// waiting (principle 2). The handle's armed drop warns for a leaf `attach` took.
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    pub teardown_warn_after: Option<std::time::Duration>,
    /// The marker pipe for a contained macOS root. `None` for a nested member, an
    /// uncontained or elevation-derived spawn, or a failed install (which degrades to the
    /// process group).
    #[cfg(target_os = "macos")]
    pub marker: Option<crate::containment::fdmarker::PreparedMarker>,
    /// The cooperative-signal mechanism implied by the creation-flag word this spawn passed to
    /// `CreateProcessW`. Set by whichever backend chose that word, so the derivation reads what
    /// the OS was actually given.
    #[cfg(windows)]
    pub graceful: crate::graceful::GracefulMechanism,
    /// Whether the child is created suspended and `attach` must leave it so (see
    /// [`Command::spawn_suspended`](crate::Command::spawn_suspended)).
    #[cfg(windows)]
    pub frozen: bool,
}

/// A child the spawn has just forked, as the spawn holds it: its pid, and the pidfd the handshake
/// gave it from before `exec`. The pidfd names the child whoever reaps it and whoever takes its
/// number, so everything about the child's exit asks it, and the pid only labels.
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy)]
pub(crate) struct ChildHandle<'a> {
    pub(crate) pid: u32,
    pub(crate) pidfd: std::os::fd::BorrowedFd<'a>,
}

/// Linux 6.9+: `SIGKILL`, through a root's pidfd, the root's process group while the group has a
/// member. `pid` only labels the log. `Err` is the kernel's refusal of the kill, with the group's
/// members possibly left running: `EINVAL` when it refuses the flag (expected below 6.9), in which
/// case nothing is sent, as the group's number may name another group.
#[cfg(target_os = "linux")]
pub(crate) fn kill_group_through_pidfd(
    pidfd: std::os::fd::BorrowedFd<'_>,
    pid: Option<u32>,
) -> Result<(), nix::errno::Errno> {
    use nix::errno::Errno;
    let named = crate::child::spawn::named(pid);
    match crate::containment::unix::pidfd_signal_group(pidfd, nix::sys::signal::Signal::SIGKILL) {
        Ok(()) => log::debug!("spawn teardown: sent SIGKILL to the process group of {named} through its pidfd"),
        Err(Errno::ESRCH) => log::debug!("spawn teardown: the process group of {named} has no member left"),
        Err(e) => return Err(e),
    }
    Ok(())
}

impl Prepared {
    /// The cooperative-signal mechanism for a child spawned from this decision. The `cfg` lives
    /// here, once, so no spawn path carries one for it: every non-Windows child cosca owns can
    /// be sent an identity-bound `SIGTERM`, whatever its containment.
    pub(crate) fn graceful_mechanism(&self) -> crate::graceful::GracefulMechanism {
        #[cfg(windows)]
        return self.graceful;
        #[cfg(not(windows))]
        return crate::graceful::GracefulMechanism::Process;
    }

    /// End the placement exchange of a spawn that failed while the caller still holds its child:
    /// take the verdict, as `attach` would, so the leaf answers only for the tree and
    /// never for the child the caller will reap. Nothing is taken without a leaf, or once the
    /// verdict is taken. A child the leaf does not hold is only logged: the leaf answers for the
    /// tree either way.
    pub(crate) fn settle_verdict(&mut self, #[cfg(target_os = "linux")] child: ChildHandle<'_>) {
        #[cfg(target_os = "linux")]
        if let Some(leaf) = self.cgroup_leaf.as_mut().filter(|leaf| leaf.holds_verdict_to_take()) {
            if let Err(e) = leaf.take_placement(child) {
                log::debug!("cgroup v2: a failed spawn's child is not placed in its leaf: {e}");
            }
        }
    }

    /// Whether the root's process group is its containment: the root is a Session or process-group
    /// root, and no cgroup leaf took it, as `attach` would decide. On Linux the leaf's verdict is
    /// taken first ([`settle_verdict`](Self::settle_verdict)).
    #[cfg(unix)]
    pub(crate) fn group_is_containment(&self) -> bool {
        #[cfg(target_os = "linux")]
        let taken_by_a_leaf = self.cgroup_leaf.as_ref().is_some_and(|leaf| leaf.child_entered());
        #[cfg(not(target_os = "linux"))]
        let taken_by_a_leaf = false;
        self.is_root && !taken_by_a_leaf && matches!(self.mode, Some(mode) if !matches!(mode, ContainMode::TreeWalk))
    }

    /// [`group_is_containment`](Self::group_is_containment) for a spawn with no cgroup leaf, which
    /// needs no verdict: a tokio spawn that fails after its fork has no handle on its child to take
    /// one through. With a leaf the leaf's abandonment decides (see `kill_group_outside_leaf`).
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    pub(crate) fn leafless_group_is_containment(&self) -> bool {
        self.cgroup_leaf.is_none() && self.group_is_containment()
    }

    /// Linux 6.9+: `SIGKILL`, through `child`'s pidfd, the process group of a spawn that failed
    /// before its attach, while the group has a member. The pidfd names the group exactly, whoever
    /// reaped the root. Only a root whose group is its containment is sent it: a Session root, or a
    /// process-group root with no cgroup leaf or one its leaf did not take, as `attach` would decide.
    /// The leaf's verdict is settled first ([`settle_verdict`](Self::settle_verdict)); a leaf that
    /// took the child kills it with the leaf. `Err` is the kernel's refusal of the kill, with the
    /// group's members possibly left running: `EINVAL` when it refuses the flag (expected below
    /// 6.9), in which case nothing is sent, as the group's number may name another group.
    #[cfg(target_os = "linux")]
    pub(crate) fn kill_group_before_attach(&self, child: ChildHandle<'_>) -> Result<(), nix::errno::Errno> {
        if !self.group_is_containment() {
            return Ok(());
        }
        kill_group_through_pidfd(child.pidfd, Some(child.pid))
    }

    /// End the placement exchange of a spawn that failed with no handle left on its child — tokio
    /// can drop one it forked — and say what became of that child. Without a leaf nothing can
    /// tell, so [`AbandonedChild::MaybeUnreachable`]. A child that is an elevation `front` is sent
    /// no signal of its own (see [`CgroupLeaf::abandon_before_verdict`]); `child` is the pidfd its
    /// handshake left for the leaf, with what the handshake expects of a teardown through it.
    ///
    /// [`CgroupLeaf::abandon_before_verdict`]: crate::containment::cgroup::CgroupLeaf::abandon_before_verdict
    #[cfg_attr(
        not(feature = "tokio"),
        allow(
            dead_code,
            reason = "only the tokio spawn path can lose a handle before a verdict is settled"
        )
    )]
    pub(crate) fn abandon_before_verdict(
        &mut self,
        front: bool,
        #[cfg(target_os = "linux")] child: Option<(std::os::fd::OwnedFd, crate::child::owned::teardown::Past)>,
    ) -> AbandonedChild {
        #[cfg(target_os = "linux")]
        if let Some(leaf) = self.cgroup_leaf.as_mut() {
            use crate::containment::cgroup::Abandoned;
            #[cfg(feature = "tokio")]
            let mut warn = crate::containment::cgroup::WarnAfter(self.teardown_warn_after);
            #[cfg(not(feature = "tokio"))]
            let mut warn = crate::containment::cgroup::NoWarn;
            let Some(child) = child else {
                use crate::containment::cgroup::WithoutChild;
                return match leaf.abandon_without_child(&mut warn) {
                    WithoutChild::Unnamed => AbandonedChild::MaybeUnreaped,
                    // A child that named itself has its pidfd in the handshake before it execs, so a
                    // tokio spawn is never here with one (only a sync spawn, where `std` collected
                    // the child, is). Not claimed ended: nothing says it was collected.
                    WithoutChild::Named => {
                        debug_assert!(false, "a child that named itself was abandoned with no handle");
                        AbandonedChild::MaybeUnreachable
                    }
                    // A repeat is a breach too; nothing says what became of the child.
                    WithoutChild::AlreadyAbandoned => {
                        debug_assert!(false, "a spawn's abandonment was asked for twice");
                        AbandonedChild::MaybeUnreachable
                    }
                };
            };
            return match leaf.abandon_before_verdict(front, child, &mut warn) {
                Abandoned::Ended(fate) => AbandonedChild::Ended(fate),
                Abandoned::Uncollected(clause) => AbandonedChild::Uncollected(clause),
                Abandoned::Front(fate) => AbandonedChild::Front(fate),
                Abandoned::Repeated => {
                    debug_assert!(false, "a spawn's abandonment was asked for twice");
                    AbandonedChild::MaybeUnreachable
                }
            };
        }
        #[cfg(not(target_os = "linux"))]
        let _ = front;
        AbandonedChild::MaybeUnreachable
    }

    /// Watch the elevation front `pid` this spawn forked: its cgroup leaf, if it has one, records
    /// the front's place before its removal (see `CgroupLeaf::watch_front`).
    pub(crate) fn watch_front(&mut self, pid: u32) {
        #[cfg(target_os = "linux")]
        if let Some(leaf) = self.cgroup_leaf.as_mut() {
            leaf.watch_front(pid);
        }
        #[cfg(not(target_os = "linux"))]
        let _ = pid;
    }
}

#[cfg(all(target_os = "linux", feature = "tokio"))]
impl Drop for Prepared {
    fn drop(&mut self) {
        if let Some(leaf) = self.cgroup_leaf.take() {
            leaf.drop_warning(&mut crate::containment::cgroup::WarnAfter(self.teardown_warn_after));
        }
    }
}

/// What became of the child of a spawn that failed with no handle left on it (see
/// [`Prepared::abandon_before_verdict`]). Only a Linux leaf tells more than `MaybeUnreachable`.
#[cfg_attr(
    not(all(target_os = "linux", feature = "tokio")),
    allow(
        dead_code,
        reason = "only a Linux leaf under tokio produces more than MaybeUnreachable"
    )
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AbandonedChild {
    /// Nothing of it runs, and it is reaped or will be: its teardown collected it. Says what became
    /// of it.
    Ended(crate::error::ChildFate),
    /// If it was forked, it exits before `exec`, but nothing holds its pid to reap it.
    MaybeUnreaped,
    /// If it was forked, it may be running where nothing can reach it.
    MaybeUnreachable,
    /// The handshake's pidfd reached it, but its teardown left it uncollected. Carries the
    /// teardown's clause, for the one warn, and what its warn asserts. Only a Linux leaf produces
    /// it.
    Uncollected(crate::child::owned::teardown::Left),
    /// It is an elevation front, which was sent no signal of its own, and this is what became of
    /// it.
    Front(crate::child::spawn::FrontFate),
}

/// What a spawn achieved, beyond the child handle itself: the tree-teardown mechanism and the
/// cooperative-signal mechanism, which are independent axes (see [`crate::graceful`]).
///
/// Bundled rather than threaded as separate positional arguments so the spawn constructors do
/// not grow an argument per spawn fact, and so a new fact is a compile error at every
/// construction site rather than a silently diverging path.
pub(crate) struct Attachment {
    pub containment: Containment,
    pub attached: Attached,
    pub graceful: crate::graceful::GracefulMechanism,
}

#[cfg(windows)]
impl Attachment {
    /// The attachment for a UAC-elevated spawn, which `ShellExecuteEx("runas")` creates through
    /// a system service with creation flags this process never sees and never chose.
    ///
    /// The mechanism is `Unknown`, so [`crate::graceful::signal`] refuses this child rather than
    /// addressing a console control event to its pid. `OtherConsoleGroup` would claim a route to
    /// a group known to exist, and `None` that no cooperative signal exists from any process
    /// ever; cosca can make neither claim about a child it did not create.
    pub(crate) fn uac_elevated() -> Attachment {
        Attachment {
            containment: Containment::None,
            attached: Attached::None,
            graceful: crate::graceful::GracefulMechanism::Unknown,
        }
    }
}

/// What a drop or a failed-spawn cleanup knows of the root, from its own handle and its number.
#[cfg(unix)]
#[derive(Debug)]
pub(crate) enum RootView {
    /// The root has been reaped, so its number may name another process: the handle says
    /// `Reaped`, or the number no longer reads as this root.
    Reaped,
    /// The handle could not say whether the root is reaped, and nothing else did.
    Unknown(std::io::Error),
    /// This process does not pin the root (macOS: launchd holds its zombie), and nothing else shows
    /// it reaped. [`UNPINNED_WHY`](crate::signal::UNPINNED_WHY) says why.
    Unpinned,
    /// The root is an unreaped child, and its number names it.
    Trusted,
}

/// Who tears a child down. The caller prefixes the teardown's log lines and names its own event in
/// them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TeardownCaller {
    /// A `Child`'s own drop.
    Drop,
    /// A helper that owns the child and failed after its spawn (`Command::status`, `output`, `read`,
    /// `SuspendedChild::resume`).
    FailedRun,
    /// A spawn's teardown of the child it holds, when its identity read or its attach fails (sync
    /// or async), and the cleanup of a child the handshake abandons.
    #[cfg_attr(
        not(any(target_os = "linux", windows, feature = "tokio")),
        allow(
            dead_code,
            reason = "only the Linux and Windows spawns and the async spawn tear a child down"
        )
    )]
    FailedSpawn,
    /// The cleanup of an elevated spawn that cannot finish.
    #[cfg(unix)]
    FinishElevated,
}

impl TeardownCaller {
    /// The prefix of the caller's log lines.
    pub(crate) fn label(self) -> &'static str {
        match self {
            TeardownCaller::Drop => "Child::drop",
            TeardownCaller::FailedRun => "teardown after a failed run",
            TeardownCaller::FailedSpawn => "teardown after a failed spawn",
            #[cfg(unix)]
            TeardownCaller::FinishElevated => "finish_elevated",
        }
    }

    /// How a log line of the caller refers to its own event: a drop is "this drop", any other
    /// teardown is "this teardown".
    #[cfg(unix)]
    pub(crate) fn this_event(self) -> &'static str {
        match self {
            TeardownCaller::Drop => "this drop",
            TeardownCaller::FailedSpawn | TeardownCaller::FailedRun | TeardownCaller::FinishElevated => "this teardown",
        }
    }
}

/// What a `Child`'s drop knows about its root, for [`Attached::hard_kill_for_drop`].
#[cfg(unix)]
#[derive(Debug)]
pub(crate) struct DropView {
    /// The caller's name, prefixing its log lines.
    pub(crate) caller: TeardownCaller,
    pub(crate) root_pid: u32,
    pub(crate) root: RootView,
    /// This handle already killed the tree completely.
    pub(crate) tree_killed: bool,
}

#[cfg(unix)]
impl DropView {
    /// Read the state a drop or a failed-spawn cleanup decides on: the root's number first, then
    /// the handle's own answer ([`RootState`](crate::signal::RootState)). The handle is exact
    /// where the number is not: a foreign reap followed by a same-tick reuse still reads as this
    /// root by its start token. A root with no identity (`id` is `None`) has nothing the number can
    /// be compared with, so only a number that names no process shows it reaped, and the handle
    /// decides alone otherwise.
    ///
    /// Reading emits no `warn`: the caller reports once, with a
    /// [`DropReport`](crate::child::drop_report::DropReport). `caller` names itself in log lines.
    pub(crate) fn read(
        caller: TeardownCaller,
        root_pid: u32,
        id: Option<crate::identity::ProcessId>,
        root: impl FnOnce() -> crate::signal::RootState,
        tree_killed: &TreeKilled,
    ) -> DropView {
        use crate::signal::RootState;
        let label = caller.label();
        let now = crate::child::root_identity_now(root_pid);
        let state = root();
        let handle_reaped = matches!(state, RootState::Reaped { .. });
        let root = if crate::child::root_reaped(handle_reaped, id, now) {
            // The number shows the reap where the handle could not say; say so in the log.
            match &state {
                RootState::Unknown(e) => log::debug!(
                    "{label}: the root's own handle could not say whether it was reaped ({e}), but its number shows it reaped"
                ),
                RootState::Unpinned => log::debug!(
                    "{label}: the root is not pinned by this process, but its number shows it reaped"
                ),
                RootState::Unreaped | RootState::Reaped { .. } => {}
            }
            RootView::Reaped
        } else {
            match state {
                RootState::Unreaped => RootView::Trusted,
                RootState::Unknown(e) => RootView::Unknown(e),
                RootState::Unpinned => RootView::Unpinned,
                RootState::Reaped { .. } => RootView::Reaped,
            }
        };
        let view = DropView {
            caller,
            root_pid,
            root,
            tree_killed: tree_killed.is_set(),
        };
        if now.is_unknown() && !handle_reaped {
            if view.unsettled() {
                log::debug!(
                    "{label}: the root's number ({root_pid}) could not be read either; kills by that number are skipped"
                );
            } else {
                log::debug!(
                    "{label}: the root's number ({root_pid}) could not be read; treating the root as not reaped"
                );
            }
        }
        view
    }

    /// The handle could not settle whether the root is still ours to act on, and nothing else did:
    /// `Unknown`, or `Unpinned`.
    pub(crate) fn unsettled(&self) -> bool {
        matches!(self.root, RootView::Unknown(_) | RootView::Unpinned)
    }

    /// Whether the root's number may name another process, or cannot be shown to name the root:
    /// nothing that names the tree by that number may run.
    pub(crate) fn number_untrusted(&self) -> bool {
        !matches!(self.root, RootView::Trusted)
    }

    /// This process does not pin the root (macOS: launchd holds it), and nothing else shows it
    /// reaped: its pid is not ours to signal or wait on.
    pub(crate) fn unpinned_root(&self) -> bool {
        matches!(self.root, RootView::Unpinned)
    }

    /// Whether the root itself is neither signalled nor waited on: it is reaped, or this process
    /// does not pin it (so its pid is not ours).
    pub(crate) fn leaves_root_alone(&self) -> bool {
        matches!(self.root, RootView::Reaped | RootView::Unpinned)
    }

    /// Why [`number_untrusted`](Self::number_untrusted), for a log line or a note.
    pub(crate) fn why_number_untrusted(&self) -> String {
        match &self.root {
            RootView::Unknown(e) => format!("the root could not be shown to be unreaped (RootState::Unknown: {e})"),
            RootView::Unpinned => format!(
                "the root is not pinned by this process (RootState::Unpinned: {})",
                crate::signal::UNPINNED_WHY
            ),
            RootView::Reaped => "the root is already reaped".to_owned(),
            RootView::Trusted => {
                debug_assert!(false, "a trusted root's number is not untrusted");
                "the root's number is trusted".to_owned()
            }
        }
    }

    /// What a kill by the root's number would do to the tree, when the number is untrusted and the
    /// drop therefore skips it: `None` for a number that is trusted, or a mechanism that does not
    /// name the tree by it.
    pub(crate) fn skipped_action(&self, attached: &Attached) -> Option<String> {
        attached
            .named_by_root_number(self.root_pid, "kill")
            .filter(|_| self.number_untrusted())
    }
}

/// Where a `Child` handle's tree stands after the kills and drops that settled it
/// ([`Attached::settle`] alone writes it): one state under one lock, so a reader sees what the last
/// settlement left. `settle` holds the lock across its kills by identity, which take a `Kernel` and
/// a `ProcessId` and never reach a `TreeKilled`, so the lock is not re-entered.
///
/// A drop that skips a number-named kill reads it to see whether it has anything to warn about
/// ([`DropView`]); a caller that has just run a kill reads the kill's own [`SettleOutcome`].
#[derive(Debug, Default)]
pub(crate) struct TreeKilled {
    state: std::sync::Mutex<TreeState>,
}

/// The settlement of a tree ([`TreeKilled`]): each state is a fact the handle knows, and [`next`]
/// moves them by one rule. Only a walk that leaves nothing vouches for the tree; only a member seen
/// running un-vouches it. A settlement, from any state:
///
/// - leaves members with identities (held ones still left, or new ones): `Left`;
/// - is a walk (`Ran`) that leaves nothing, held members included: `Killed`;
/// - leaves something running that holds no identity (a member of a handle that is not a `TreeWalk`,
///   or a walk that left the root, whatever then ended it): `Unvouched`, from any state;
/// - otherwise (a gone root, a walk not made, or a skipped kill whose sweep left nothing: none saw a
///   member running) keeps the state, except that `Left` whose held members all dropped out is
///   `Unvouched`. A held member is held because its kill was refused: it ran on and may have forked,
///   and killing it again by identity does not reach its children.
///
/// The kind of an `Unvouched` state is the latest fact:
///
/// - a walk that saw the root running names [`RootSeenRunning`](UnvouchedKind::RootSeenRunning),
///   whether or not the root had ended;
/// - held members that all dropped out name [`HeldMembersGone`](UnvouchedKind::HeldMembersGone);
/// - something else left running with no identity names [`Earlier`](UnvouchedKind::Earlier), from
///   any previous state.
///
/// A settlement with no new fact keeps the stored kind.
#[derive(Debug, Default)]
enum TreeState {
    /// Nothing has settled the tree: no kill left anything running, and no walk left nothing.
    #[default]
    Never,
    /// A walk left nothing: vouched for.
    Killed,
    /// A walk left these members, never none, so every later kill and drop answers them first: the
    /// root's death reparents them out of a later walk, so the handle kills the ones whose identity
    /// was read again and reports the others again.
    Left(Vec<crate::containment::treewalk::Left>),
    /// A kill ran, and no member it left is held now (each is gone, or the handle never held an
    /// identity for it), but no walk since has vouched for the tree: a member seen running may have
    /// forked, and its children were never looked for. The kind says what was found where the tree
    /// became unvouched: every text over this state is chosen by it.
    Unvouched(UnvouchedKind),
}

/// The state after a settlement, by the rule on [`TreeState`]. The facts: `walked`, the outcome was a
/// walk that ran; `left_now`, the members it left with identities; `running`, the outcome left
/// something running (the root included, whatever then ended it), not merely an error for a walk it
/// did not make (a gone root's or an unmade walk's error is not a member seen running);
/// `root_seen_running`, the walk left the root (whatever then ended it), which is `running`.
fn next(
    prev: &TreeState,
    walked: bool,
    left_now: Vec<crate::containment::treewalk::Left>,
    running: bool,
    root_seen_running: bool,
) -> TreeState {
    debug_assert!(
        !root_seen_running || running,
        "a root seen running is something left running"
    );
    if !left_now.is_empty() {
        return TreeState::Left(left_now);
    }
    // The kind the facts name, for a state they leave unvouched. Something running with no identity
    // and no root seen is `Earlier` from any state; with nothing running, the only way to be
    // unvouched is `Left` whose held members all dropped out.
    let named = if root_seen_running {
        UnvouchedKind::RootSeenRunning
    } else if running {
        UnvouchedKind::Earlier
    } else {
        UnvouchedKind::HeldMembersGone
    };
    match prev {
        _ if walked && !running => TreeState::Killed,
        TreeState::Never if !running => TreeState::Never,
        TreeState::Killed if !running => TreeState::Killed,
        TreeState::Unvouched(kept) if !running => TreeState::Unvouched(*kept),
        TreeState::Never | TreeState::Killed | TreeState::Left(_) | TreeState::Unvouched(_) => {
            TreeState::Unvouched(named)
        }
    }
}

impl TreeKilled {
    fn lock(&self) -> std::sync::MutexGuard<'_, TreeState> {
        self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Whether the tree is killed. Only a Unix drop reads it (`DropView`), and the tests.
    #[cfg(any(unix, test))]
    pub(crate) fn is_set(&self) -> bool {
        matches!(*self.lock(), TreeState::Killed)
    }
}

/// Which signal a tree path sends.
#[cfg(unix)]
#[derive(Debug, Clone, Copy)]
pub(crate) enum TreeSignal {
    Kill,
    Term,
}

#[cfg(unix)]
impl TreeSignal {
    pub(crate) fn verb(self) -> &'static str {
        match self {
            TreeSignal::Kill => "kill",
            TreeSignal::Term => "signal",
        }
    }
}

/// What a drop's kill does to the tree ([`Attached::drop_reach`]).
#[cfg(unix)]
enum DropReach {
    /// Kill it as usual.
    Kill,
    /// Linux 6.9+: the root is reaped, and its pidfd shows its process group has no member left:
    /// nothing to kill.
    #[cfg(target_os = "linux")]
    GroupGone,
    /// Skip what names the tree by the root's number, which this says.
    Skip(String),
}

/// A tree kill that did not complete, and every member it left running. It reports none of them:
/// [`Attached::settle`] decides what the root's own death leaves, and the caller reports that, once.
#[derive(Debug)]
pub(crate) struct Unkilled {
    /// Every member left but the root. For a walk, in the order it found them; for a mechanism that
    /// is not a walk, its one error.
    pub(crate) members: Vec<Error>,
    /// The root, when a walk left it. Only a `TreeWalk` walk can: the root's own death then settles it.
    pub(crate) root: Option<Error>,
    /// The members of `members` whose identity a `TreeWalk` walk read, and whose kill was refused: a
    /// later kill can kill them again by it. The others were never read.
    pub(crate) resolved: Vec<crate::identity::ProcessId>,
}

impl Unkilled {
    /// The first member left: a member before the root. A kill that completed is not an `Unkilled`,
    /// so there is one.
    #[cfg(unix)]
    pub(crate) fn first(&self) -> &Error {
        self.members
            .first()
            .or(self.root.as_ref())
            .expect("an incomplete kill left a member")
    }

    /// [`first`](Self::first), owned, for the tests that read what a walk returned.
    #[cfg(test)]
    pub(crate) fn into_error(self) -> Error {
        self.members
            .into_iter()
            .next()
            .or(self.root)
            .expect("an incomplete kill left a member")
    }

    /// What is still left once the root's own handle has had its say: `Ok` when nothing is, else the
    /// first member and the others as data. `root_ended`: the root is not running, so a root the walk
    /// left is not left.
    pub(crate) fn unsettled(self, root_ended: bool) -> Result<(), Unsettled> {
        let mut left = self.members.into_iter().chain(self.root.filter(|_| !root_ended));
        match left.next() {
            None => Ok(()),
            Some(first) => Err(Unsettled {
                first,
                others: left.collect(),
            }),
        }
    }
}

impl From<Error> for Unkilled {
    fn from(error: Error) -> Unkilled {
        Unkilled {
            members: vec![error],
            root: None,
            resolved: Vec::new(),
        }
    }
}

/// What a tree kill left once the root's own death had its say ([`Attached::settle`]): the first
/// member left, which the caller returns, and the others, as data for the caller's one report.
#[derive(Debug)]
pub(crate) struct Unsettled {
    pub(crate) first: Error,
    pub(crate) others: Vec<Error>,
}

impl Unsettled {
    /// The error a caller returns: the first member left. The caller's one report is that error, and a
    /// `warn`, led by `caller`, for each of the others.
    pub(crate) fn report(self, caller: &str) -> Error {
        for other in &self.others {
            log::warn!("{caller}: {other}");
        }
        self.first
    }
}

impl std::fmt::Display for Unsettled {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.first)?;
        self.others.iter().try_for_each(|other| write!(f, "; {other}"))
    }
}

/// How an [`Attached::settle`] that found nothing left came out, by the state it left ([`TreeKilled`]):
/// the answer `Ok` does not say the tree is vouched for, this does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SettleOutcome {
    /// The kill ran, or found the killed tree already gone, and the state left is killed: nothing is
    /// left for the caller to report, and the tree is vouched for.
    Killed,
    /// The kill was skipped (and the sweep by identity of a macOS fd marker left nothing): it killed
    /// nothing, and the state left is not unvouched.
    Skipped,
    /// The state left is [`Unvouched`](TreeState::Unvouched), whatever the call did: a skipped kill
    /// over a tree a skip moved there from [`Left`](TreeState::Left), or a walk that left only the
    /// root, whose own end then made the answer `Ok`. `kind` says what was found.
    Unvouched { kind: UnvouchedKind },
}

/// What a settlement found of a tree it cannot vouch for ([`SettleOutcome::Unvouched`]), as far as
/// the settlement knows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UnvouchedKind {
    /// The tree held members an earlier kill left, which are gone now.
    HeldMembersGone,
    /// A walk saw the root running and left it. If the root's own kill then ended it, the call was
    /// `Ok`. What the root forked meanwhile was never looked for.
    RootSeenRunning,
    /// A kill, this settlement's own or an earlier one, left something running that it could not name
    /// (members the handle holds no identity for, or members since gone), and the settlement
    /// no longer knows which.
    Earlier,
}

impl UnvouchedKind {
    /// What the settlement found, as the clause of a text about a tree it cannot vouch for.
    fn found(self) -> &'static str {
        match self {
            UnvouchedKind::HeldMembersGone => {
                "the members an earlier kill left are gone now, but no later walk has checked what they forked"
            }
            UnvouchedKind::RootSeenRunning => {
                "the walk found the root running, and what the root forked meanwhile was never looked for"
            }
            UnvouchedKind::Earlier => {
                "a kill left something running that it could not name, and no later walk has checked what it forked"
            }
        }
    }

    /// The text of a cleanup's or a drop's report over a tree it cannot vouch for.
    pub(crate) fn unvouched_text(self) -> String {
        format!("{}, so the tree could not be vouched for", self.found())
    }

    /// The drop's warn for a settlement over a tree it cannot vouch for: a kind that came of a skipped
    /// kill says so.
    fn drop_text(self) -> String {
        match self {
            UnvouchedKind::HeldMembersGone | UnvouchedKind::Earlier => {
                format!("the drop skipped the kill, and {}", self.unvouched_text())
            }
            UnvouchedKind::RootSeenRunning => self.unvouched_text(),
        }
    }

    /// What a gone root answers over a tree of this kind: the tree could not be walked, but not
    /// nothing was killed.
    fn gone_root_text(self) -> &'static str {
        match self {
            UnvouchedKind::HeldMembersGone => {
                "the members an earlier kill left are gone; the tree could not be walked from its gone root, so \
                 what they forked is unknown"
            }
            UnvouchedKind::RootSeenRunning => {
                "the root an earlier walk found running is gone; the tree could not be walked from it, so what it \
                 forked is unknown"
            }
            UnvouchedKind::Earlier => {
                "a kill left something running that it could not name, and no walk since has checked what it \
                 forked; the tree could not be walked from its gone root"
            }
        }
    }
}

/// What a tree kill did ([`Attached::hard_kill_for_drop`], [`Attached::hard_kill`]): the one value
/// [`Attached::settle`] turns into what is left and into the handle's state ([`TreeKilled`]).
#[derive(Debug)]
pub(crate) enum TreeKillOutcome {
    /// The kill ran, or there was nothing to kill (a Linux process group with no member left); `Err`
    /// is what it left.
    Ran(Result<(), Unkilled>),
    /// A `TreeWalk` walk could not be made (the snapshot could not be taken, or the root exists but
    /// could not be queried), so NOTHING was killed, the root included: killing the root anyway would
    /// reparent its descendants out of the ppid walk, so a retry could no longer find them. The
    /// error says why. Every other failure is a kill that was attempted, a `TreeWalk`'s
    /// [`Error::MemberNotKilled`] included.
    Unwalked(Error),
    /// A `TreeWalk` walk found its root gone, or holding its pid no longer: there is no tree to walk
    /// from, so this kill killed nothing. It is [`Error::Unassessable`]: [`no_root_error`](Self::no_root_error)
    /// over a tree never settled, [`no_root_after_kills_error`](Self::no_root_after_kills_error) over
    /// an unvouched one, worded by what the settlement knows of it ([`UnvouchedKind`]).
    NoRoot,
    /// The root's number is untrusted, so the kill skipped what names the tree by it. The tree is
    /// not killed.
    #[cfg_attr(
        not(unix),
        allow(dead_code, reason = "only a Unix drop or cleanup skips a kill by the root's number")
    )]
    Skipped {
        /// What the skip left undone, as an action ("walk the process table from the root's pid").
        action: String,
        /// The sweep by identity a macOS fd marker still makes of its holders; `Ok` elsewhere.
        holders: Result<(), Unkilled>,
    },
}

/// A kill that ran: what [`Attached::hard_kill`] and the paths that send by hand return.
impl From<Result<(), Unkilled>> for TreeKillOutcome {
    fn from(result: Result<(), Unkilled>) -> TreeKillOutcome {
        TreeKillOutcome::Ran(result)
    }
}

impl TreeKillOutcome {
    /// What [`NoRoot`](Self::NoRoot) is as an error: nothing was killed, because no walk ran.
    pub(crate) fn no_root_error() -> Error {
        Error::Unassessable {
            detail: "the root is gone or no longer holds its pid, so no walk ran and nothing was killed".to_owned(),
            source: None,
        }
    }

    /// What a [`NoRoot`](Self::NoRoot) is as an error over a tree an earlier kill left unvouched
    /// (`kind` says what it found): the tree could not be walked, but not nothing was killed.
    pub(crate) fn no_root_after_kills_error(kind: UnvouchedKind) -> Error {
        Error::Unassessable {
            detail: kind.gone_root_text().to_owned(),
            source: None,
        }
    }

    /// What the kill left: `Ok` for one that ran and left nothing, or a skip whose sweep left
    /// nothing. A walk that was not made or found no root left its error, as the only member.
    pub(crate) fn into_result(self) -> Result<(), Unkilled> {
        match self {
            TreeKillOutcome::Ran(result) | TreeKillOutcome::Skipped { holders: result, .. } => result,
            TreeKillOutcome::Unwalked(error) => Err(Unkilled::from(error)),
            TreeKillOutcome::NoRoot => Err(Unkilled::from(Self::no_root_error())),
        }
    }

    /// Whether the kill reached the front it was made for: it ran and left nothing, the root
    /// included. The one predicate of every gate that asks, with a cgroup
    /// front, whether the cgroup kill ended it.
    #[cfg(unix)]
    pub(crate) fn completed(&self) -> bool {
        matches!(self, TreeKillOutcome::Ran(Ok(())))
    }

    /// Why the kill did not leave the tree killed, or `None` when it [`completed`](Self::completed):
    /// the first member a kill left, or what a skip left undone. For the text of a gate that reads it.
    #[cfg(unix)]
    pub(crate) fn incomplete(&self) -> Option<String> {
        if self.completed() {
            return None;
        }
        Some(match self {
            TreeKillOutcome::Ran(Err(left)) | TreeKillOutcome::Skipped { holders: Err(left), .. } => {
                left.first().to_string()
            }
            TreeKillOutcome::Skipped {
                action,
                holders: Ok(()),
            } => format!("the kill was skipped, and would {action}"),
            TreeKillOutcome::Unwalked(error) => error.to_string(),
            TreeKillOutcome::NoRoot => Self::no_root_error().to_string(),
            TreeKillOutcome::Ran(Ok(())) => unreachable!("a completed kill has nothing left"),
        })
    }

    /// What the kill skipped, as an action, when it was skipped.
    #[cfg(unix)]
    pub(crate) fn skipped(&self) -> Option<&str> {
        match self {
            TreeKillOutcome::Skipped { action, .. } => Some(action),
            TreeKillOutcome::Ran(_) | TreeKillOutcome::Unwalked(_) | TreeKillOutcome::NoRoot => None,
        }
    }

    /// What a drop did not do, because the root's number is untrusted and this handle had not already
    /// killed the tree: the tree it names may outlive the drop.
    #[cfg(unix)]
    pub(crate) fn left_undone(&self, view: &DropView) -> Option<String> {
        self.skipped().filter(|_| !view.tree_killed).map(str::to_owned)
    }

    /// Why and what a skipped kill left undone, for a cleanup's note.
    #[cfg(unix)]
    pub(crate) fn skip_note(&self, view: &DropView) -> Option<String> {
        self.skipped().map(|action| {
            format!(
                "{}, so its number may name another process, and the kill would {action}",
                view.why_number_untrusted()
            )
        })
    }
}

/// A `kill_tree` sweep that failed, and whether the root is dead all the same: its handle backstop
/// ended it. A caller that waits for the root before it returns the error reads that.
pub(crate) struct SweepFailure {
    pub(crate) error: Error,
    pub(crate) root_ended: bool,
}

/// A failure before the backstop ran, or that sent it nowhere: the root is not known dead.
impl From<Error> for SweepFailure {
    fn from(error: Error) -> SweepFailure {
        SweepFailure {
            error,
            root_ended: false,
        }
    }
}

impl SweepFailure {
    /// Whether the root is not running after a kill of it through its handle: it was killed, or was
    /// already dead ([`ChildFate::not_running`](crate::error::ChildFate::not_running)'s meaning). A
    /// kill that could not be verified (`Sent::Unverified`) may have left the root running.
    pub(crate) fn killed_root(sent: &Result<crate::signal::Sent, Error>) -> bool {
        use crate::signal::Sent;
        matches!(sent, Ok(Sent::Delivered | Sent::Gone))
    }

    /// The handle backstop's answer from its root kill's `sent`, and whether it ended the root.
    pub(crate) fn backstop_of(sent: Result<crate::signal::Sent, Error>) -> (Result<(), Error>, bool) {
        let ended = Self::killed_root(&sent);
        (sent.map(drop), ended)
    }

    /// The answer of a `kill_tree` sweep: the walk's error, settled by the root's death
    /// ([`Attached::settle`]), else the backstop's. `root_ended`: the backstop ended the root. This is
    /// the call's one report of the members the walk left: the error names the first, and each other
    /// is warned of here. `op` names the call.
    pub(crate) fn of(
        op: &str,
        attached: &Attached,
        killed: &TreeKilled,
        walk: TreeKillOutcome,
        backstop: Result<(), Error>,
        root_ended: bool,
    ) -> Result<(), SweepFailure> {
        let walk = attached.settle_for_kill_tree(op, killed, walk, root_ended);
        if let (Err(walk), Err(backstop)) = (&walk, &backstop) {
            // The backstop's error is dropped: the walk's names the member left.
            log::debug!("{op} handle backstop also failed ({backstop}); surfacing the walk's error: {walk}");
        }
        walk.and(backstop).map_err(|error| SweepFailure { error, root_ended })
    }
}

/// Owns the OS containment resource for a spawned child; `hard_kill`/`terminate`
/// act on the tree, `disarm` neutralizes teardown for `detach()`. `None` =
/// uncontained (lone-process semantics).
#[derive(Debug, Default)]
pub(crate) enum Attached {
    #[default]
    None,
    /// A nested containment member: it joined an ancestor's group/job and owns no
    /// teardown mechanism of its own (the outermost root tears the tree down). Distinct
    /// from `None` (genuinely uncontained) so `_tree` ops can error honestly.
    Delegated,
    #[cfg(unix)]
    ProcessGroup(i32), // pgid (== root pid)
    #[cfg(target_os = "linux")]
    Cgroup(crate::containment::cgroup::CgroupLeaf),
    #[cfg(windows)]
    JobObject(crate::containment::windows::JobHandle),
    /// macOS inherited-fd marker: membership survives `setsid`, `setpgid`, reparenting and
    /// `exec`. Owns the supervisor's read end of the marker pipe — which is what keeps the
    /// pipe's kernel identity from being re-issued — plus, when the mode created one, the pgid.
    #[cfg(target_os = "macos")]
    FdMarker(crate::containment::fdmarker::Marker),
    /// Identity-aware tree-walk teardown (cross-platform; the root identity is
    /// re-enumerated and killed by identity at teardown). No cfg gate: this is
    /// the universal fallback and a directly-selectable mode on every OS.
    TreeWalk(crate::identity::ProcessId),
}

// CgroupLeaf is not Debug; provide a minimal impl.
#[cfg(target_os = "linux")]
impl std::fmt::Debug for crate::containment::cgroup::CgroupLeaf {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CgroupLeaf").finish_non_exhaustive()
    }
}

impl Attached {
    /// What names this mechanism's tree in a message about its teardown: the cgroup leaf's path
    /// (`hard_kill` returns the kernel's error unwrapped, so the error does not name it), else
    /// the mechanism itself.
    #[cfg(unix)]
    pub(crate) fn teardown_subject(&self) -> String {
        #[cfg(target_os = "linux")]
        if let Attached::Cgroup(leaf) = self {
            return format!("cgroup leaf {}", leaf.path().display());
        }
        format!("{self:?}")
    }

    /// Whether this mechanism's kill reaches `pid` whatever its credentials: only a cgroup's
    /// `cgroup.kill` does, and only while `pid` is in it. A signal to a group or to walked members is
    /// subject to the kernel's permission check, so it is `false` for every other mechanism.
    /// `pid` must be this process's unreaped child, so its number is not reused.
    #[cfg(unix)]
    #[cfg_attr(
        not(target_os = "linux"),
        allow(unused_variables, reason = "only a Linux cgroup reads it")
    )]
    pub(crate) fn kill_reaches_across_credentials(
        &self,
        pid: u32,
        pidfd: Option<std::os::fd::BorrowedFd<'_>>,
    ) -> std::io::Result<bool> {
        #[cfg(target_os = "linux")]
        if let Attached::Cgroup(leaf) = self {
            return leaf.holds_member(pid, pidfd);
        }
        Ok(false)
    }

    /// Whether this is a cgroup leaf with a `cgroup.kill` write that landed or found the leaf gone,
    /// which bounds its drain.
    /// `false` for every other mechanism.
    #[cfg(all(feature = "tokio", target_os = "linux"))]
    pub(crate) fn cgroup_kill_landed(&self) -> bool {
        matches!(self, Attached::Cgroup(leaf) if leaf.kill_landed())
    }

    /// Whether `pid` (which `pidfd` names, when there is one) is in a cgroup's leaf or a cgroup
    /// under it (see `CgroupLeaf::names`). `false` for every other mechanism.
    #[cfg(unix)]
    #[cfg_attr(
        not(target_os = "linux"),
        allow(unused_variables, reason = "only a Linux cgroup reads it")
    )]
    pub(crate) fn cgroup_names(&self, pid: u32, pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> std::io::Result<bool> {
        #[cfg(target_os = "linux")]
        if let Attached::Cgroup(leaf) = self {
            return leaf.names(pid, pidfd);
        }
        Ok(false)
    }

    /// Hard-kill the contained tree (best-effort; a member that is already gone is success). What
    /// `Ok` says depends on how the mechanism names the tree:
    ///
    /// - A cgroup leaf and a Job Object name it in the kernel: `Ok` says the kernel killed every
    ///   member, however it was spawned.
    /// - A process group or session, and an fd marker, name it by a number or a pipe: `Ok` says every
    ///   member they list or find holding it was reached. A member outside it (one that left the group,
    ///   or on Linux one `hidepid` hides) is not.
    /// - A `TreeWalk` names it by parentage: `Ok` says every descendant of the root at the walk's
    ///   snapshot was killed. A process already reparented away from the root (an orphan), or one the
    ///   snapshot did not list, is not a descendant to it and is not killed. A descendant it left
    ///   running is an [`Error::MemberNotKilled`].
    ///
    /// `root` is the root a send to a group named by its pid needs (see
    /// [`GroupRoot`](crate::containment::GroupRoot)); every other mechanism ignores it.
    #[cfg_attr(
        not(unix),
        allow(unused_variables, reason = "only Unix names a group by the root's pid")
    )]
    pub(crate) fn hard_kill(&self, root: &crate::containment::GroupRoot<'_>) -> TreeKillOutcome {
        let ran = |result: Result<(), Error>| TreeKillOutcome::Ran(result.map_err(Unkilled::from));
        match self {
            Attached::None | Attached::Delegated => TreeKillOutcome::Ran(Ok(())),
            #[cfg(unix)]
            Attached::ProcessGroup(pgid) => ran(crate::containment::unix::kill_group(*pgid, root)),
            #[cfg(target_os = "linux")]
            Attached::Cgroup(leaf) => ran(leaf.hard_kill()),
            #[cfg(windows)]
            Attached::JobObject(job) => ran(job.hard_kill().map_err(Error::Io)),
            #[cfg(target_os = "macos")]
            Attached::FdMarker(m) => ran(m.hard_kill(root)),
            Attached::TreeWalk(root) => crate::containment::treewalk::hard_kill(&crate::identity::HostKernel, *root),
        }
    }

    /// [`hard_kill`](Self::hard_kill) for a caller with no root to kill after it, settled and reported
    /// as [`settle_for_kill_tree`](Self::settle_for_kill_tree) does, with the root not ended. `caller`
    /// names the call in the warns of the members it left besides the first.
    #[cfg(unix)]
    pub(crate) fn hard_kill_settled(
        &self,
        caller: &str,
        killed: &TreeKilled,
        root: &crate::containment::GroupRoot<'_>,
    ) -> Result<(), Error> {
        self.settle_for_kill_tree(caller, killed, self.hard_kill(root), false)
    }

    /// What a tree kill's `outcome` comes to once the root's own handle has had its say: the one place
    /// that decides what a walk left behind, and the only one that writes `killed`. `root_ended`: the
    /// root is not running (killed, or already dead), so a root the walk left is not left. The answer
    /// is `Ok` when nothing is left. Otherwise it is the first member left, and the others as data: it
    /// reports none of them.
    ///
    /// It decides under the one lock of `killed`, by its state and the outcome, and leaves the state
    /// by the rule on [`TreeState`]. The members a `TreeWalk` state holds are answered first, whatever
    /// the outcome. A gone root over a killed tree is `Ok`, and over held members still left it adds no
    /// error of its own; over a tree never settled it is [`TreeKillOutcome::no_root_error`], and over
    /// an unvouched one (held members that are all gone, or left so earlier) it is
    /// [`TreeKillOutcome::no_root_after_kills_error`].
    ///
    /// `kill_tree` reads `root_ended` from its backstop, which it runs for any walk; a drop or a
    /// failed spawn's cleanup reads it from the fate of the root kill it made after the walk.
    pub(crate) fn settle(
        &self,
        killed: &TreeKilled,
        outcome: impl Into<TreeKillOutcome>,
        root_ended: bool,
    ) -> Result<SettleOutcome, Unsettled> {
        let outcome = outcome.into();
        let walk = matches!(self, Attached::TreeWalk(_));
        let mut state = killed.lock();
        let was_killed = matches!(*state, TreeState::Killed);
        // The state is read here and written once, at the end, so an unwind leaves it as it was.
        let held = match &*state {
            TreeState::Left(held) => held.clone(),
            TreeState::Never | TreeState::Killed | TreeState::Unvouched(_) => Vec::new(),
        };
        let gone_root = matches!(outcome, TreeKillOutcome::NoRoot);
        let ran = matches!(outcome, TreeKillOutcome::Ran(_));
        // What a walk not made or a gone root leaves is its error, not a member seen running.
        let looked_for_no_member = matches!(outcome, TreeKillOutcome::NoRoot | TreeKillOutcome::Unwalked(_));
        // A walk already covered the tree unless it was never settled: a gone root adds no error of its own.
        let covered = gone_root && !matches!(*state, TreeState::Never);
        let mut result = if covered { Ok(()) } else { outcome.into_result() };
        let mut left_now = Vec::new();
        if walk {
            result = crate::containment::treewalk::with_earlier(&crate::identity::HostKernel, held, result);
            if let Err(left) = &result {
                left_now = crate::containment::treewalk::Left::of(left);
            }
        }
        // A member the walk saw running un-vouches the tree, whatever ended it afterwards: it may have
        // forked first. Only the answer follows the root's end.
        let running = result.is_err() && !looked_for_no_member;
        let root_seen_running = matches!(&result, Err(left) if left.root.is_some());
        let after = next(&state, ran, left_now, running, root_seen_running);
        if gone_root && result.is_ok() && !was_killed {
            // What an earlier walk left is gone or unknown, but nothing walked the tree for what it forked.
            let error = match after {
                TreeState::Unvouched(kind) => TreeKillOutcome::no_root_after_kills_error(kind),
                TreeState::Never | TreeState::Killed | TreeState::Left(_) => {
                    debug_assert!(
                        false,
                        "a gone root over held or unvouched members leaves the tree unvouched"
                    );
                    // Release: the gone-root answer of a tree no kill left unvouched.
                    TreeKillOutcome::no_root_error()
                }
            };
            result = Err(Unkilled::from(error));
        }
        let unsettled = match result {
            Ok(()) => Ok(()),
            Err(left) => {
                debug_assert!(left.root.is_none() || walk, "only a tree walk leaves the root alone");
                left.unsettled(root_ended)
            }
        };
        // The answer follows the state left: `Killed` only over a vouched tree. A gone root answers
        // `Ok` only over a killed tree.
        let answer = unsettled.map(|()| match &after {
            TreeState::Unvouched(kind) => SettleOutcome::Unvouched { kind: *kind },
            _ if ran || gone_root => {
                debug_assert!(matches!(after, TreeState::Killed), "`Killed` answers a killed tree");
                SettleOutcome::Killed
            }
            _ => SettleOutcome::Skipped,
        });
        *state = after;
        answer
    }

    /// [`settle`](Self::settle) for a `kill_tree` call, which reports: the error names the first member
    /// left, and each other is warned of here, once. `caller` names the call in those warns.
    pub(crate) fn settle_for_kill_tree(
        &self,
        caller: &str,
        killed: &TreeKilled,
        walk: impl Into<TreeKillOutcome>,
        root_ended: bool,
    ) -> Result<(), Error> {
        self.settle(killed, walk, root_ended)
            .map(drop)
            .map_err(|left| left.report(caller))
    }

    /// `walk` for a `kill_tree` that goes on to the root's backstop: a `TreeWalk` that could not walk
    /// killed nothing, and the root's death would strand the descendants beyond a retry, so it is
    /// settled here and returned as the error with the tree intact. Any other `walk` is handed back.
    pub(crate) fn unless_unwalked(
        &self,
        caller: &str,
        killed: &TreeKilled,
        walk: TreeKillOutcome,
    ) -> Result<TreeKillOutcome, SweepFailure> {
        if !matches!(walk, TreeKillOutcome::Unwalked(_)) {
            return Ok(walk);
        }
        match self.settle_for_kill_tree(caller, killed, walk, false) {
            Err(error) => Err(SweepFailure::from(error)),
            // The walk's error is a member left, and the root is not ended.
            Ok(()) => unreachable!("a walk not made leaves its error"),
        }
    }

    /// [`settle`](Self::settle) for a drop: the text of its warn when the tree is not settled, worded
    /// here and only when it will be logged.
    pub(crate) fn settle_for_drop(
        &self,
        killed: &TreeKilled,
        outcome: impl Into<TreeKillOutcome>,
        root_ended: bool,
    ) -> Option<String> {
        let outcome = outcome.into();
        let after = match &outcome {
            // A drop cannot retry a walk that was not made.
            TreeKillOutcome::Unwalked(_) => "; the root is killed regardless, so its descendants may be orphaned",
            TreeKillOutcome::Ran(_) | TreeKillOutcome::NoRoot | TreeKillOutcome::Skipped { .. } => "",
        };
        let left = match self.settle(killed, outcome, root_ended) {
            Err(left) => left.to_string(),
            Ok(SettleOutcome::Unvouched { kind }) => kind.drop_text(),
            Ok(SettleOutcome::Killed | SettleOutcome::Skipped) => return None,
        };
        Some(format!("contained-tree teardown did not fully succeed: {left}{after}"))
    }

    /// Send the graceful termination signal to the group (signal-only).
    #[cfg_attr(
        not(unix),
        allow(unused_variables, reason = "only Unix names a group by the root's pid")
    )]
    pub(crate) fn terminate(&self, _child_pid: u32, root: &crate::containment::GroupRoot<'_>) -> Result<(), Error> {
        match self {
            Attached::None | Attached::Delegated => {
                debug_assert!(
                    self.is_actionable(),
                    "Attached::terminate on a non-actionable mechanism"
                );
                Err(crate::error::Error::Unsupported {
                    op: "terminate on a non-actionable mechanism".into(),
                    platform: std::env::consts::OS,
                    detail: "internal invariant: a non-actionable mechanism reached terminate".into(),
                })
            }
            #[cfg(unix)]
            Attached::ProcessGroup(pgid) => crate::containment::unix::term_group(*pgid, root),
            #[cfg(target_os = "linux")]
            Attached::Cgroup(leaf) => leaf.terminate(),
            #[cfg(windows)]
            Attached::JobObject(_) => crate::containment::windows::terminate(_child_pid),
            #[cfg(target_os = "macos")]
            Attached::FdMarker(m) => m.terminate(root),
            Attached::TreeWalk(root) => crate::containment::treewalk::terminate(&crate::identity::HostKernel, *root),
        }
    }

    /// Apply a handle's `kill_on_drop` decision to the containment resource, once its spawn is
    /// committed.
    ///
    /// `Child::drop` returning early on `kill_on_drop == false` skips only ITS teardown. The
    /// resource is a field of that handle and drops with it regardless — and a `CgroupLeaf`'s
    /// `Drop` fires `cgroup.kill` over an occupied leaf, a Job Object's close fires
    /// `KILL_ON_JOB_CLOSE`. So the opt-out has to reach the resource as well, which is what
    /// [`disarm`](Self::disarm) is for; without this, `kill_on_drop(false)` killed exactly the
    /// contained trees [`Child::detach`](crate::Child::detach) (which disarms) keeps alive,
    /// while [`Command::kill_on_drop`](crate::Command::kill_on_drop) documents the two as the
    /// same opt-out.
    ///
    /// Called by `spawn` as it hands the handle to the caller, not when the handle is built: a
    /// spawn that fails after that (the POSIX password write) must still tear its tree down.
    /// Not in `Drop` either: a supervisor that exits without running destructors still has its
    /// Job Object handle closed by the OS, and with `KILL_ON_JOB_CLOSE` still set that close is
    /// the kill. `detach()` disarms eagerly for the same reason.
    ///
    /// # Errors
    ///
    /// The refusal of the disarm (Windows: `SetInformationJobObject`), when the handle opted out
    /// of `kill_on_drop`: the resource is then still armed, and the caller must not hand the child
    /// over as one cosca no longer kills.
    pub(crate) fn honor_kill_on_drop(&self, kill_on_drop: bool) -> std::io::Result<()> {
        if kill_on_drop {
            Ok(())
        } else {
            self.disarm()
        }
    }

    /// Neutralize teardown so `detach()` leaves the tree running. For Job Objects,
    /// clears `KILL_ON_JOB_CLOSE` so the handle close does not kill the tree; for a cgroup
    /// leaf, stops `Drop` firing `cgroup.kill`. No-op only for mechanisms whose resource-drop
    /// genuinely does not kill (pgroup/treewalk/fd marker/none), which `Child::drop`'s
    /// `kill_on_drop` opt-out already covers.
    ///
    /// Only a Job Object's disarm can fail (the OS refuses `SetInformationJobObject`); the
    /// resource is then still armed.
    pub(crate) fn disarm(&self) -> std::io::Result<()> {
        match self {
            Attached::None | Attached::Delegated => {}
            #[cfg(unix)]
            Attached::ProcessGroup(_) => {} // pgroup drop doesn't kill — no-op
            #[cfg(target_os = "linux")]
            Attached::Cgroup(leaf) => leaf.disarm(), // CgroupLeaf::drop kills an occupied leaf
            #[cfg(windows)]
            Attached::JobObject(job) => return job.disarm(), // clear KILL_ON_JOB_CLOSE before handle drops
            // dropping the read end does not kill; detach opts out via kill_on_drop
            #[cfg(target_os = "macos")]
            Attached::FdMarker(_) => {}
            Attached::TreeWalk(_) => {} // no kernel resource whose drop kills; detach opts out via kill_on_drop
        }
        Ok(())
    }

    /// Whether this mechanism signals a process group named by the root's pid: `ProcessGroup`, and
    /// a macOS fd marker whose mode made a group.
    #[cfg(all(test, unix))]
    pub(crate) fn signals_a_group(&self) -> bool {
        match self {
            Attached::ProcessGroup(_) => true,
            #[cfg(target_os = "macos")]
            Attached::FdMarker(m) => m.pgid().is_some(),
            _ => false,
        }
    }

    /// Whether this mechanism reaches the tree through the root's number (`ProcessGroup`'s `killpg`;
    /// a macOS `FdMarker`'s walk and group), which the root's reap frees for reuse, so
    /// `kill_tree`/`terminate_tree` check the root first
    /// ([`crate::child::tree_call::root_number`]). `TreeWalk` checks for itself
    /// (`treewalk::walk_from`).
    #[cfg(unix)]
    pub(crate) fn needs_root_check(&self) -> bool {
        match self {
            Attached::ProcessGroup(_) => true,
            #[cfg(target_os = "macos")]
            Attached::FdMarker(_) => true,
            _ => false,
        }
    }

    /// What [`hard_kill`](Self::hard_kill) would do to the tree by the root's own number, phrased
    /// as actions for a log line; `None` if it would do nothing of the kind. A cgroup and a Job
    /// Object name the tree through a kernel object, so a reaped root changes nothing for them.
    ///
    /// A process group is the root's number. A `TreeWalk` walks ppid edges from it, and on Unix
    /// that names no descendant of the reaped root: reparenting cleared those edges, so the only
    /// processes with that ppid belong to whoever reused the number. A macOS fd marker does both.
    #[cfg(unix)]
    pub(crate) fn named_by_root_number(&self, root_pid: u32, verb: &str) -> Option<String> {
        match self {
            Attached::ProcessGroup(pgid) => Some(format!("{verb} its process group (pgid {pgid})")),
            #[cfg(target_os = "macos")]
            Attached::FdMarker(m) => {
                // A group only if the mode made one; the walk always runs.
                let walk = format!("walk the process table from the root's pid (root pid {root_pid})");
                Some(match m.pgid() {
                    Some(pgid) => format!("{verb} its process group (pgid {pgid}) or {walk}"),
                    None => walk,
                })
            }
            Attached::TreeWalk(_) => Some(format!(
                "walk the process table from the root's pid (root pid {root_pid})"
            )),
            _ => None,
        }
    }

    /// [`hard_kill`](Self::hard_kill) for a drop. Once the root is reaped nothing pins its number,
    /// so no channel that names the tree by that number may run: not the `killpg`, not a ppid walk
    /// from the root's pid, not a kill of the root by that pid. Each could hit an unrelated process
    /// that reused the number. A macOS fd marker still sweeps its marker holders, which are named
    /// by identity. Cgroup and Job Object never skip. On Linux 6.9+ a process group is decided by
    /// the root's pidfd instead, as a tree call decides it ([`DropReach`]).
    ///
    /// `view` is one look at the root, taken right before this call. Each send by the group's number
    /// after it checks the root again, as for [`Child::kill_tree`](crate::Child::kill_tree).
    ///
    /// The same skip when the root's own handle could not say whether it is reaped
    /// (`RootState::Unknown`): nothing then shows the number still names the root.
    ///
    /// Logs nothing above `debug`: what a skip left undone is returned in
    /// [`TreeKillOutcome::Skipped`], for the caller's one report.
    #[cfg(unix)]
    pub(crate) fn hard_kill_for_drop(
        &self,
        view: &DropView,
        root: &crate::containment::GroupRoot<'_>,
    ) -> TreeKillOutcome {
        let action = match self.drop_reach(view, root) {
            DropReach::Kill => return self.hard_kill(root),
            #[cfg(target_os = "linux")]
            DropReach::GroupGone => return TreeKillOutcome::Ran(Ok(())),
            DropReach::Skip(action) => action,
        };
        let why = view.why_number_untrusted();
        let (label, this) = (view.caller.label(), view.caller.this_event());
        if view.tree_killed {
            log::debug!(
                "{label}: {why} and this handle already killed the tree, \
                 so {this} does not {action}"
            );
        } else if !matches!(view.root, RootView::Reaped) {
            // A reaped root's skip is the drop's warn; an unsettled root's is part of its state's.
            log::debug!("{label}: {why}, so {this} does not {action}");
        }
        let holders = match self {
            #[cfg(target_os = "macos")]
            Attached::FdMarker(m) => m
                .hard_kill_holders_only(m.root().filter(|_| view.unpinned_root()))
                .map_err(Unkilled::from),
            _ => Ok(()),
        };
        TreeKillOutcome::Skipped { action, holders }
    }

    /// What a drop, or a failed spawn's cleanup, does to the tree after its look at the root
    /// (`view`). A root whose number is trusted, or a mechanism that does not name the tree by it,
    /// is killed as usual. On Linux 6.9+ a process group whose root's number is not trusted is
    /// decided by the root's pidfd, exactly as a tree call decides it
    /// ([`through_the_pidfd`](crate::child::tree_call::through_the_pidfd)): killed while the group
    /// has a member, whoever reaped the root, and gone once a reaped root's group has none.
    /// Otherwise, and below 6.9 and on macOS, what names the tree by the root's number is skipped.
    #[cfg(unix)]
    fn drop_reach(&self, view: &DropView, root: &crate::containment::GroupRoot<'_>) -> DropReach {
        let reach = self.decide_drop_reach(view, root);
        #[cfg(test)]
        crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
        reach
    }

    /// [`drop_reach`](Self::drop_reach)'s decision.
    #[cfg(unix)]
    #[cfg_attr(not(target_os = "linux"), allow(unused_variables, reason = "only Linux has a pidfd"))]
    fn decide_drop_reach(&self, view: &DropView, root: &crate::containment::GroupRoot<'_>) -> DropReach {
        let Some(skipped) = view.skipped_action(self) else {
            return DropReach::Kill;
        };
        #[cfg(target_os = "linux")]
        {
            use crate::child::tree_call::{through_the_pidfd, RootNumber};
            let why = view.why_number_untrusted();
            let number = RootNumber::MayNameAnother {
                exact_root: matches!(view.root, RootView::Unknown(_)),
                why: why.clone(),
            };
            match through_the_pidfd(self, number, root) {
                RootNumber::Trusted => return DropReach::Kill,
                RootNumber::GroupGone => {
                    log::debug!(
                        "{}: {why}, and its pidfd shows its process group has no member left, so nothing is sent",
                        view.caller.label()
                    );
                    return DropReach::GroupGone;
                }
                _ => {}
            }
        }
        DropReach::Skip(skipped)
    }

    /// A tree path's signal while the root's number cannot be trusted (`root` is `Unpinned` or
    /// `Unknown`): what a drop does. Nothing that names the tree by the root's number runs (the
    /// `killpg`, the walk from the root's pid, the root's kill by pid). A macOS fd marker still
    /// signals its holders, which are named by identity; a `Term` there is `Ok` when every holder was
    /// reached, and a `Kill` is `Unassessable` even then, as the kill skipped what it was to do. Any
    /// other number-named mechanism has no channel left: `Unassessable`, with what was skipped.
    /// `None` for a mechanism that names the tree some other way, which signals as usual. The caller
    /// settles a `Kill`'s answer ([`TreeCall`](crate::child::TreeCall)).
    #[cfg(target_os = "macos")]
    pub(crate) fn signal_tree_untrusted(
        &self,
        signal: TreeSignal,
        root: &crate::signal::RootState,
        root_pid: u32,
        op: &str,
        earlier: Option<&str>,
    ) -> Option<Result<(), Error>> {
        let skipped = self.named_by_root_number(root_pid, signal.verb())?;
        let why = crate::signal::why_untrusted(root);
        let earlier = earlier.map_or_else(String::new, |sent| format!(", though {sent} was sent before it"));
        let unassessable = |sent: &str, because: &str| Error::Unassessable {
            detail: format!("pid {root_pid}: {why}; {op} {sent}{earlier}: {because}it did not {skipped}"),
            source: None,
        };
        let Attached::FdMarker(m) = self else {
            return Some(Err(unassessable(
                "sent nothing",
                "its signals are all named by the root's number, so ",
            )));
        };
        let except = m.root().filter(|_| matches!(root, crate::signal::RootState::Unpinned));
        log::debug!("{op}: {why}, so it does not {skipped}; it signals the marker holders");
        Some(match signal {
            // The holders are not the tree: a kill that skipped the rest is not `Ok`.
            TreeSignal::Kill => m
                .hard_kill_holders_only(except)
                .and_then(|()| Err(unassessable("signalled only the marker holders", ""))),
            TreeSignal::Term => m.terminate_holders_only(except),
        })
    }

    /// Send `signal` to the tree through what names it by identity alone, for a root that is
    /// reaped: a macOS fd marker's holders, named by the pipe they hold, which no reuse of a pid
    /// redirects. `None` for a mechanism with no such channel. The caller settles a `Kill`'s answer.
    #[cfg(unix)]
    #[cfg_attr(
        not(target_os = "macos"),
        allow(unused_variables, reason = "only a macOS fd marker names its tree by identity")
    )]
    pub(crate) fn signal_holders_only(&self, signal: TreeSignal) -> Option<Result<(), Error>> {
        match self {
            #[cfg(target_os = "macos")]
            Attached::FdMarker(m) => Some(match signal {
                TreeSignal::Kill => m.hard_kill_holders_only(None),
                TreeSignal::Term => m.terminate_holders_only(None),
            }),
            _ => None,
        }
    }

    /// Whether this is a macOS fd marker, and if so whether its mode made a group. `None`: not an
    /// fd marker.
    #[cfg(target_os = "macos")]
    pub(crate) fn fd_marker_has_group(&self) -> Option<bool> {
        match self {
            Attached::FdMarker(m) => Some(m.pgid().is_some()),
            _ => None,
        }
    }

    /// Send `signal` to a macOS fd marker's group and holders, with no walk from the root's pid: for
    /// a root this process reaped, whose pid names no process. `None` for any other mechanism. The
    /// caller settles a `Kill`'s answer.
    #[cfg(target_os = "macos")]
    pub(crate) fn signal_group_and_holders(
        &self,
        signal: TreeSignal,
        root: &crate::containment::GroupRoot<'_>,
    ) -> Option<Result<(), Error>> {
        let Attached::FdMarker(m) = self else {
            return None;
        };
        Some(match signal {
            TreeSignal::Kill => m.hard_kill_group_and_holders(root),
            TreeSignal::Term => m.terminate_group_and_holders(root),
        })
    }

    /// Whether [`signal_tree_untrusted`](Self::signal_tree_untrusted) has a channel left to signal
    /// the tree through: one named by identity rather than by the root's number.
    #[cfg(target_os = "macos")]
    pub(crate) fn names_tree_by_identity(&self) -> bool {
        matches!(self, Attached::FdMarker(_))
    }

    /// Whether this is a Linux cgroup leaf.
    #[cfg(unix)]
    pub(crate) fn is_cgroup(&self) -> bool {
        #[cfg(target_os = "linux")]
        return matches!(self, Attached::Cgroup(_));
        #[cfg(not(target_os = "linux"))]
        false
    }

    /// Whether this child holds an actionable tree-teardown mechanism.
    pub(crate) fn is_actionable(&self) -> bool {
        match self {
            Attached::None | Attached::Delegated => false,
            #[cfg(unix)]
            Attached::ProcessGroup(_) => true,
            #[cfg(target_os = "linux")]
            Attached::Cgroup(_) => true,
            #[cfg(windows)]
            Attached::JobObject(_) => true,
            #[cfg(target_os = "macos")]
            Attached::FdMarker(_) => true,
            Attached::TreeWalk(_) => true,
        }
    }

    /// Give up the containment resource without waiting for anything: what an async
    /// `Child::drop` that does not wait for the drain does with it, where a plain drop could
    /// block. A cgroup leaf goes through `CgroupLeaf::release_without_waiting`; every other
    /// mechanism drops in place, which is bounded.
    #[cfg(feature = "tokio")]
    pub(crate) fn release_without_waiting(self) {
        match self {
            #[cfg(target_os = "linux")]
            Attached::Cgroup(leaf) => leaf.release_without_waiting(),
            other => drop(other),
        }
    }

    /// Whether this handle owns a mechanism with a kernel drain edge — mirrors
    /// [`Containment::can_observe_drain`](crate::containment::Containment::can_observe_drain),
    /// checked against the concrete resource rather than the reported enum so the two can
    /// never drift silently (`require_drainable` asserts them equal in debug).
    pub(crate) fn can_observe_drain(&self) -> bool {
        match self {
            #[cfg(target_os = "linux")]
            Attached::Cgroup(_) => true,
            #[cfg(windows)]
            Attached::JobObject(_) => true,
            #[cfg(target_os = "macos")]
            Attached::FdMarker(_) => true,
            _ => false,
        }
    }

    /// Block until every member of the contained tree has EXITED (not reaped), or until
    /// `deadline`. `Unsupported` on every mechanism without a kernel drain edge (checked by the
    /// caller via `require_drainable`/`can_observe_drain` before this is reached in the public
    /// API, but this still refuses honestly if ever called directly against a non-drainable
    /// mechanism).
    pub(crate) fn wait_drained(
        &self,
        deadline: Option<std::time::Instant>,
    ) -> Result<crate::containment::TreeDrain, Error> {
        // Whatever the mechanism: a caller inside an async `Drop` is refused even where the
        // mechanism has no drain edge to wait on.
        #[cfg(feature = "tokio")]
        crate::bounded::assert_may_block("waiting for the contained tree to drain");
        match self {
            #[cfg(target_os = "linux")]
            Attached::Cgroup(leaf) => leaf.wait_drained(deadline),
            #[cfg(windows)]
            Attached::JobObject(job) => job.wait_drained(deadline, None),
            #[cfg(target_os = "macos")]
            Attached::FdMarker(m) => m.wait_drained(deadline),
            _ => Err(Error::Unsupported {
                op: "wait for the contained tree to drain".into(),
                platform: std::env::consts::OS,
                detail: "this child's containment mechanism exposes no kernel edge for tree drain".into(),
            }),
        }
    }
}

/// Returns `true` when the current process is the outermost contained root
/// (i.e. the env marker is absent). Pure function: takes the marker-presence
/// flag so it can be unit-tested without touching the process environment.
pub(crate) fn is_nested(marker_present: bool) -> bool {
    marker_present
}

/// What the spawn's identity read said of a child it cannot verify (macOS leaves such a child alone).
#[cfg_attr(
    not(target_os = "macos"),
    allow(dead_code, reason = "only macOS leaves a child unverified")
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RootIdentity {
    /// The root was already reaped (someone else reaped it, and its pid may be reused).
    Gone,
    /// The read was refused or could not be trusted.
    Unknown,
}

/// Whether the tree kill of this mechanism reached the child. Only a cgroup leaf's `cgroup.kill` is
/// shown to, whatever the child's credentials: its flag says the write landed, then where the child
/// is says it was in the leaf. A signal to a group or to walked members is subject to the kernel's
/// permission check, as the child's own kill is, so it reaches nothing that kill does not.
#[cfg(unix)]
impl crate::child::owned::teardown::Reach for Attached {
    #[cfg_attr(
        not(target_os = "linux"),
        allow(unused_variables, reason = "only a Linux cgroup reads it")
    )]
    fn reached(&self, child: &crate::child::owned::OwnedChild) -> std::io::Result<bool> {
        #[cfg(target_os = "linux")]
        if let Attached::Cgroup(leaf) = self {
            return leaf.subtree()?.reached(child);
        }
        Ok(false)
    }
}

/// Which Unix setup action to apply to a root `Command` for a given mode.
/// Pure function: used by `prepare` and unit-tested separately to verify
/// mutual exclusivity: Session → setsid only; Strongest/default → pgroup
/// only; TreeWalk → neither (it must catch process-group escapees).
#[cfg(unix)]
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum UnixSetup {
    /// Add the `setsid` step to the spawn's in-child hook (ContainMode::Session). Must NOT be
    /// combined with ProcessGroup on the same Command (EPERM on a session leader).
    Session,
    /// Apply `process_group(0)` (ContainMode::Strongest or default).
    ProcessGroup,
    /// Apply NO pre-spawn grouping (ContainMode::TreeWalk). TreeWalk's whole
    /// point is to catch children that `setsid`/`setpgid` out of a process group,
    /// so it must not put the root in a group itself; teardown is by identity.
    None,
}

/// Decide which Unix mechanism to apply for `mode` (root spawns only).
/// Keeping this as a pure function makes the mutual-exclusivity invariant
/// directly unit-testable without inspecting `std::process::Command` internals.
#[cfg(unix)]
pub(crate) fn unix_setup_for(mode: Option<ContainMode>) -> UnixSetup {
    match mode {
        Some(ContainMode::Session) => UnixSetup::Session,
        Some(ContainMode::TreeWalk) => UnixSetup::None,
        _ => UnixSetup::ProcessGroup,
    }
}

/// The Windows pre-spawn containment decision, shared by the std `prepare` path and the raw
/// `CreateProcessW` backend. Encodes ONLY the decision; the caller applies it (`creation_flags`
/// onto the command, the root env marker, `clear_std_handle_inheritance`).
#[cfg(windows)]
pub(crate) struct WindowsContain {
    /// Creation flags to OR into the spawn: `root_flags` (suspend + new group) for a Strongest
    /// root, `group_flags` (new group only) otherwise; `0` when uncontained (`mode` is `None`).
    pub creation_flags: u32,
    /// Whether this spawn must set the inherited root marker so descendants join THIS group.
    pub marker_env: bool,
}

/// Decide the Windows pre-spawn containment flags + marker for `req`/`is_root`. Pure — directly
/// unit-testable. Returns `{ creation_flags: 0, marker_env: false }` when `req.mode` is `None`.
#[cfg(windows)]
pub(crate) fn windows_contain_setup(req: &ContainRequest, is_root: bool) -> WindowsContain {
    let Some(mode) = req.mode else {
        return WindowsContain {
            creation_flags: 0,
            marker_env: false,
        };
    };
    let creation_flags = if is_root && !matches!(mode, ContainMode::TreeWalk) {
        // Strongest root: suspend + new process group (job assigned in attach).
        crate::containment::windows::root_flags()
    } else {
        // TreeWalk root (no suspend, no job — identity teardown) and all nested spawns:
        // CREATE_NEW_PROCESS_GROUP only, so `terminate` can CTRL_BREAK the root's group.
        crate::containment::windows::group_flags()
    };
    WindowsContain {
        creation_flags,
        marker_env: is_root && req.nesting == Nesting::Mark,
    }
}

/// Phase 1 (before spawn): env-marker root detection + pre-spawn OS setup. On Unix, what the child
/// does for itself between `fork` and `exec` goes into `steps`, which the caller registers.
///
/// `reserved_fds` and `marker_suppressed` drive the macOS fd-marker install only; every
/// other platform ignores them. `flags` is the caller's creation-flag request, which only
/// Windows can honour.
///
/// Fallible only on Windows, where the composed creation-flag word may name a reserved bit. The
/// composition runs at the very top — before anything is mutated, so a refusal leaves nothing to
/// unwind, and above the uncontained early return, so an uncontained spawn carries the caller's
/// flags too.
pub(crate) fn prepare(
    std_cmd: &mut std::process::Command,
    #[cfg(unix)] steps: &mut crate::child::spawn::in_child::InChild,
    req: &ContainRequest,
    #[cfg_attr(
        not(windows),
        allow(
            unused_variables,
            reason = "only Windows can honour the caller's creation-flag request"
        )
    )]
    flags: &crate::command::flags::FlagsRequest,
    #[cfg_attr(
        not(target_os = "macos"),
        allow(unused_variables, reason = "drives the macOS fd-marker install only")
    )]
    reserved_fds: &[i32],
    #[cfg_attr(
        not(target_os = "macos"),
        allow(unused_variables, reason = "drives the macOS fd-marker install only")
    )]
    marker_suppressed: bool,
    #[cfg_attr(
        not(windows),
        allow(unused_variables, reason = "only the Windows path composes env ops into the request")
    )]
    env_ops: &[crate::command::EnvOp],
) -> Result<Prepared, Error> {
    let mode = req.mode;
    // Read once, above every branch, so the word is composed exactly once per spawn and no two
    // compositions can disagree. Reading it for an uncontained spawn too is unobservable.
    //
    // On Unix cosca never sets this variable in its own process, so it can only change here if the
    // user `set_var`s it concurrently, which is the user's data race. On Windows `set_var` is sound
    // from any thread, so the marker comes from one snapshot, and a contained child's whole
    // environment is built from that same snapshot below: the decision and the child agree.
    #[cfg(windows)]
    let snapshot = crate::child::spawn::windows_raw::env_snapshot::EnvSnapshot::read()?;
    #[cfg(windows)]
    let marker_present = snapshot
        .var(std::ffi::OsStr::new(crate::containment::NESTED_ENV))
        .is_some();
    #[cfg(not(windows))]
    let marker_present = std::env::var_os(crate::containment::NESTED_ENV).is_some();
    let is_root = !is_nested(marker_present);

    #[cfg(windows)]
    let graceful = {
        use std::os::windows::process::CommandExt;
        let spawn =
            crate::command::flags::windows_spawn(req, *flags, is_root, crate::command::flags::SpawnBackend::Std)?;
        std_cmd.creation_flags(spawn.creation_flags);
        // Sound for THIS derivation and no other: `mechanism_from_flags` reads only
        // CREATE_NEW_PROCESS_GROUP / DETACHED_PROCESS / CREATE_NEW_CONSOLE / CREATE_NO_WINDOW,
        // and std adds and removes none of them. The word is what cosca supplies, never what
        // `CreateProcessW` receives — see `crate::command::flags`.
        crate::containment::windows::mechanism_from_flags(spawn.creation_flags)
    };

    if mode.is_none() {
        return Ok(Prepared {
            mode: None,
            is_root: false,
            #[cfg(target_os = "linux")]
            cgroup_leaf: None,
            #[cfg(all(target_os = "linux", feature = "tokio"))]
            teardown_warn_after: None,
            #[cfg(target_os = "macos")]
            marker: None,
            #[cfg(windows)]
            graceful,
            #[cfg(windows)]
            frozen: flags.suspended,
        });
    }
    let marker_env = is_root && req.nesting == Nesting::Mark;
    // Windows: hand std the whole environment, rebuilt from the snapshot the marker was read from,
    // so std does not read this process's environment again at `CreateProcessW`. The marker is an
    // op after the user's, named as std names it; it survives a user `env_clear`.
    #[cfg(windows)]
    {
        use crate::child::spawn::windows_raw::{child_ops, resolve::ChildEnv};
        let env = ChildEnv::capture(&snapshot, &child_ops(env_ops, marker_env));
        std_cmd.env_clear();
        std_cmd.envs(env.captured_vars().expect("a capture is never inherited"));
    }
    // Elsewhere: set AFTER any user env ops (env_clear) have been applied to std_cmd by the spawn
    // engine, so the marker survives env_clear. `env` appends.
    #[cfg(not(windows))]
    if marker_env {
        std_cmd.env(crate::containment::NESTED_ENV, "1");
    }

    // Linux: session mode or (cgroup v2 + process group).
    // Mechanism selection via `unix_setup_for` (setsid/pgroup mutual exclusivity):
    // Session → setsid only; Strongest/TreeWalk → process_group(0) + try cgroup.
    #[cfg(target_os = "linux")]
    {
        if is_root && mode.is_some() {
            match unix_setup_for(mode) {
                UnixSetup::Session => {
                    // Session: setsid only — no process_group(0) (would EPERM).
                    crate::containment::unix::set_session(steps);
                    return Ok(Prepared {
                        mode,
                        is_root,
                        cgroup_leaf: None, // cgroup not used for Session
                        #[cfg(all(target_os = "linux", feature = "tokio"))]
                        teardown_warn_after: None,
                    });
                }
                UnixSetup::None => {
                    // TreeWalk: NO process group / setsid / cgroup — teardown is
                    // by identity so we can catch process-group escapees.
                    return Ok(Prepared {
                        mode,
                        is_root,
                        cgroup_leaf: None,
                        #[cfg(all(target_os = "linux", feature = "tokio"))]
                        teardown_warn_after: None,
                    });
                }
                UnixSetup::ProcessGroup => {
                    // Strongest: set a new process group + try cgroup.
                    crate::containment::unix::set_process_group(std_cmd);
                }
            }

            // A failed leaf creation degrades this spawn to the process group set above. The
            // decision is unchanged; only the silence is — `log_degrade` names the step that
            // failed and the kernel's reason for it.
            let leaf = match crate::containment::cgroup::try_create_leaf() {
                Ok(leaf) => Some(leaf),
                Err(e) => {
                    crate::containment::cgroup::log_degrade(&e);
                    None
                }
            };
            if let Some(ref l) = leaf {
                // The child's self-placement step. A failed placement (e.g. EBUSY — "no internal
                // processes" rule) returns Ok, so the spawn proceeds and `attach` falls back to the
                // already-configured process group. Only a report the child cannot send fails the
                // spawn. Both the sync and the tokio spawn add this one step through `prepare`.
                // SAFETY: the leaf, which owns both the fd and the report channel, stays in
                // `Prepared` until after the spawn.
                unsafe { steps.place(l.procs_fd(), l.placement_slot()) };
            }
            return Ok(Prepared {
                mode,
                is_root,
                cgroup_leaf: leaf,
                #[cfg(all(target_os = "linux", feature = "tokio"))]
                teardown_warn_after: None,
            });
        }
        return Ok(Prepared {
            mode,
            is_root,
            cgroup_leaf: None,
            #[cfg(all(target_os = "linux", feature = "tokio"))]
            teardown_warn_after: None,
        });
    }

    // Non-Linux Unix: process group or session (mutually exclusive).
    // Mechanism selection via `unix_setup_for`: Session → setsid only;
    // Strongest (= ProcessGroup on macOS) → process_group(0).
    #[cfg(all(unix, not(target_os = "linux")))]
    if is_root && mode.is_some() {
        match unix_setup_for(mode) {
            UnixSetup::Session => crate::containment::unix::set_session(steps),
            UnixSetup::ProcessGroup => crate::containment::unix::set_process_group(std_cmd),
            UnixSetup::None => {} // TreeWalk: no pre-spawn grouping (identity teardown)
        }
    }

    // macOS: install the inherited-fd marker for every contained root, regardless of the
    // requested mode (decision: the marker survives what the mode-specific mechanism above
    // does not). `marker_wanted` gates on root/mode/suppression; `install` degrades to `None`
    // on any failure rather than failing the spawn.
    #[cfg(target_os = "macos")]
    let marker = if crate::containment::fdmarker::marker_wanted(mode, is_root, marker_suppressed) {
        crate::containment::fdmarker::install(steps, reserved_fds)
    } else {
        None
    };

    // Windows: stop the child inheriting this process's std handles. Contained spawns only, and
    // below the composition above so a refused spawn has mutated nothing. The creation-flag word
    // itself is applied at the top, since an uncontained spawn never reaches this point.
    #[cfg(windows)]
    crate::containment::windows::clear_std_handle_inheritance();

    // On `target_os = "linux"` only, every path through the `#[cfg(target_os = "linux")]` block
    // above returns, so this expression is unreachable there — but it is the live tail expression
    // on every other target.
    #[cfg_attr(
        target_os = "linux",
        expect(unreachable_code, reason = "the linux block above returns on every path")
    )]
    Ok(Prepared {
        mode,
        is_root,
        #[cfg(target_os = "linux")]
        cgroup_leaf: None,
        #[cfg(all(target_os = "linux", feature = "tokio"))]
        teardown_warn_after: None,
        #[cfg(target_os = "macos")]
        marker,
        #[cfg(windows)]
        graceful,
        #[cfg(windows)]
        frozen: flags.suspended,
    })
}

/// Phase 2 (after spawn, before the `OwnedChild` adopts): attach the mechanism and bundle it with the
/// spawn's other achieved facts. Consumes `prepared` so Linux cgroup leaf ownership transfers
/// cleanly to `Attached::Cgroup` without requiring interior mutability — hence the
/// cooperative-signal mechanism is read off it first.
///
/// `id` is the identity the spawn read of the root, or the error of the read that failed. A
/// mechanism that names the tree by the root's identity (a tree walk, the macOS fd marker) fails the
/// attach with that error; one that attaches by pid or handle (a cgroup, a process group, a Job
/// Object) does not need it.
pub(crate) fn attach(
    #[cfg(unix)] pid: u32,
    id: Result<crate::identity::ProcessId, Error>,
    #[cfg(target_os = "linux")] child: ChildHandle<'_>,
    #[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
    prepared: Prepared,
) -> Result<Attachment, Error> {
    let graceful = prepared.graceful_mechanism();
    let (containment, attached) = attach_tree(
        #[cfg(unix)]
        pid,
        id,
        #[cfg(target_os = "linux")]
        child,
        #[cfg(windows)]
        proc_handle,
        prepared,
    )?;
    Ok(Attachment {
        containment,
        attached,
        graceful,
    })
}

/// The tree-teardown half of [`attach`]: which mechanism owns this child's tree.
fn attach_tree(
    #[cfg(unix)] pid: u32,
    id: Result<crate::identity::ProcessId, Error>,
    #[cfg(target_os = "linux")] child: ChildHandle<'_>,
    #[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
    prepared: Prepared,
) -> Result<(Containment, Attached), Error> {
    // Linux: session, or cgroup v2 / process group.
    #[cfg(target_os = "linux")]
    {
        let mut prepared = prepared;
        if prepared.mode.is_some() {
            if prepared.is_root {
                // TreeWalk root: no kernel container / process group; teardown is
                // by identity: the one the spawn verified against the child's handle.
                if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
                    return Ok((Containment::TreeWalk, Attached::TreeWalk(id?)));
                }

                let raw_pid = pid;
                debug_assert!(
                    raw_pid <= i32::MAX as u32,
                    "pid {raw_pid} exceeds i32::MAX; pgid cast would truncate"
                );
                let pgid = raw_pid as i32;

                // Session mode: setsid was applied pre-spawn; no cgroup.
                // pgid == sid == pid for the session leader; killpg works.
                if matches!(prepared.mode, Some(ContainMode::Session)) {
                    return Ok((Containment::Session, Attached::ProcessGroup(pgid)));
                }

                // Strongest: cgroup v2 if available, else process group.
                if let Some(mut leaf) = prepared.cgroup_leaf.take() {
                    // The pre_exec write can fail (EBUSY — the "no internal processes" rule
                    // when the supervisor is itself an undelegated leaf). The child's own
                    // report of that write decides membership; re-reading cgroup.procs cannot,
                    // because it lists only live tasks and a placed child may already have
                    // exited. Taking the verdict waits for that report — `spawn` returning does
                    // not mean the child has made it — then releases the leaf's fd and pipe.
                    match leaf.take_placement(child) {
                        Ok(()) => return Ok((Containment::CgroupV2, Attached::Cgroup(leaf))),
                        // Nothing of the child's is in the leaf: its final report is not Placed. The
                        // process group set pre-spawn is the real container; the leaf is
                        // removed without writing cgroup.kill.
                        Err(reason) => {
                            crate::containment::cgroup::log_degrade(&reason);
                            leaf.remove_unentered();
                            return Ok((Containment::ProcessGroup, Attached::ProcessGroup(pgid)));
                        }
                    }
                }
                // No cgroup leaf: fall back to process group (set pre-spawn).
                return Ok((Containment::ProcessGroup, Attached::ProcessGroup(pgid)));
            } else {
                // Nested member: it joined the ancestor's cgroup/process group (or the
                // root's tree-walk) rather than creating its own, so it owns no teardown —
                // the outermost root tears the whole tree down.
                return Ok((Containment::Delegated, Attached::Delegated));
            }
        }
    }

    // Non-Linux Unix: process group or session.
    // For Session: setsid was called pre-spawn (not process_group(0)); the child
    // is a session leader with pgid == pid. Teardown via killpg is identical —
    // Attached::ProcessGroup(pgid) is reused since the pgroup == session leader's pid.
    // For Strongest (= ProcessGroup on macOS): process_group(0) was called pre-spawn.
    #[cfg(all(unix, not(target_os = "linux")))]
    {
        if prepared.mode.is_some() {
            if prepared.is_root {
                // macOS fd marker: installed for every contained root regardless of mode, so
                // it takes priority over the mode-specific mechanism below — it is what
                // survives setsid/reparenting/exec that the mode-specific mechanism does not.
                #[cfg(target_os = "macos")]
                if let Some(marker) = prepared.marker {
                    let pgid = match prepared.mode {
                        Some(ContainMode::TreeWalk) => None,
                        _ => {
                            debug_assert!(
                                pid <= i32::MAX as u32,
                                "pid {pid} exceeds i32::MAX; pgid cast would truncate"
                            );
                            Some(pid as i32)
                        }
                    };
                    return Ok((
                        Containment::FdMarker,
                        Attached::FdMarker(crate::containment::fdmarker::Marker::new(marker, id?, pgid)),
                    ));
                }
                // TreeWalk root: no process group; identity teardown.
                if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
                    return Ok((Containment::TreeWalk, Attached::TreeWalk(id?)));
                }
                let raw_pid = pid;
                debug_assert!(
                    raw_pid <= i32::MAX as u32,
                    "pid {raw_pid} exceeds i32::MAX; pgid cast would truncate"
                );
                let pgid = raw_pid as i32;
                let containment = match prepared.mode {
                    Some(ContainMode::Session) => Containment::Session,
                    _ => Containment::ProcessGroup,
                };
                return Ok((containment, Attached::ProcessGroup(pgid)));
            } else {
                // Nested member: it joined the ancestor's process group (or the root's
                // tree-walk) rather than creating its own, so it owns no teardown — the
                // outermost root tears the whole tree down.
                #[cfg(target_os = "macos")]
                if prepared.marker.is_some() {
                    log::warn!(
                        "fd marker: a nested spawn's prepare() unexpectedly produced a marker; \
                         a nested member must inherit the root's marker, never create its own \
                         — discarding it"
                    );
                    debug_assert!(
                        false,
                        "a nested member inherits the root's marker and must never create one"
                    );
                }
                return Ok((Containment::Delegated, Attached::Delegated));
            }
        }
    }

    // Windows: Job Object (strongest available on this OS), or TreeWalk.
    #[cfg(windows)]
    {
        if prepared.mode.is_some() && prepared.is_root {
            // TreeWalk root: no job (spawned with CREATE_NEW_PROCESS_GROUP only);
            // identity teardown, with CTRL_BREAK to the group as cooperative term.
            if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
                return Ok((Containment::TreeWalk, Attached::TreeWalk(id?)));
            }
            // A frozen root is assigned its job and left suspended. It gets no `TreeWalk` fallback:
            // a frozen root without a job would have nothing to kill it if its owner died.
            if prepared.frozen {
                return match crate::containment::windows::assign_held(proc_handle) {
                    Ok(job) => Ok((Containment::JobObject, Attached::JobObject(job))),
                    Err(e) => Err(Error::Containment { detail: e.to_string() }),
                };
            }
            match crate::containment::windows::attach_job(proc_handle) {
                Ok(Some(job)) => return Ok((Containment::JobObject, Attached::JobObject(job))),
                Ok(None) => {
                    // Job assignment failed: fall back to the universal TreeWalk
                    // mechanism rather than silently yielding no containment. The
                    // root was spawned with CREATE_NEW_PROCESS_GROUP (root_flags),
                    // so `terminate`'s CTRL_BREAK still reaches the group.
                    return Ok((Containment::TreeWalk, Attached::TreeWalk(id?)));
                }
                Err(e) => return Err(Error::Containment { detail: e.to_string() }),
            }
        } else if prepared.mode.is_some() {
            // Nested member: it inherits the ancestor's job (or the root's tree-walk; no
            // new job is created), so it owns no teardown — the outermost root's job tears
            // the whole tree down.
            return Ok((Containment::Delegated, Attached::Delegated));
        }
    }

    // Uncontained (or unsupported platform).
    let _ = prepared;
    Ok((Containment::None, Attached::None))
}

#[cfg(test)]
#[path = "dispatch_tests.rs"]
mod dispatch_tests;