cosca 0.5.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
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
//! std-only spawn: resolve the crate's `Stdio` model onto `std::process::Command`,
//! wire the program/args via the `quote` module, and adopt the child into a `SharedChild`.

use std::collections::BTreeMap;
use std::process::Stdio as StdStdio;

use crate::child::proc_handle::ProcHandle;
use crate::child::shared::SharedChild;
pub(crate) use crate::child::spawn::failure::{after_the_spawn, Classify, SpawnFailure};
use crate::child::{Child, ParentEnd};
use crate::command::{Command, CommandInput, EnvOp};
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
use crate::stdio::{Direction, Fd, ResolvedStdio};

// A child-side descriptor handed to std via `Stdio::from`.
#[cfg(unix)]
pub(crate) type ChildEnd = std::os::unix::io::OwnedFd;
#[cfg(windows)]
pub(crate) type ChildEnd = std::os::windows::io::OwnedHandle;

pub(crate) fn spawn(cmd: &mut Command) -> Result<Child, SpawnFailure> {
    let child = spawn_uncommitted(cmd)?;
    child.commit_kill_on_drop();
    Ok(child)
}

/// [`spawn`] up to the handle it returns, whose containment resource still tears the tree down
/// on drop whatever `kill_on_drop` says.
pub(crate) fn spawn_uncommitted(cmd: &mut Command) -> Result<Child, SpawnFailure> {
    let kill_on_drop = cmd.kill_on_drop_flag();
    // Elevation runs BEFORE spawn_unelevated's std::mem::take(cmd.fds_mut()), so the
    // effect layers see/modify cmd.fds() while it is still populated (the honest Windows
    // reject gate and the POSIX derived-command build both depend on it).
    if cmd.elevation_request().enabled {
        #[cfg(windows)]
        {
            return crate::elevation::windows::spawn_elevated(cmd, kill_on_drop);
        }
        #[cfg(unix)]
        {
            let crate::elevation::posix::PosixRewrite {
                derived,
                report,
                password_write,
                backend_path,
            } = crate::elevation::posix::rewrite(cmd).not_started()?;
            // From here the child is the backend: its elevated program may outlive what happens to it.
            let wrapper = report.as_ref().is_some_and(|r| r.via.program_outlives_child());
            let spawned = (|| {
                let mut child = match derived {
                    // The derived program IS the backend; remap an exec failure to
                    // BackendUnavailable ONLY when the backend path is the culprit (a bad cwd
                    // yields the same kind and stays a plain Io). An already-elevated derived
                    // (sanitized original) has no backend path, so it is never remapped.
                    Some(mut derived) => {
                        let r = spawn_unelevated(&mut derived, kill_on_drop);
                        match backend_path.as_deref() {
                            Some(bp) => r.map_err(|f| f.map(|e| crate::elevation::remap_derived_spawn_error(e, bp)))?,
                            None => r?,
                        }
                    }
                    // No derived command: the current POSIX `rewrite` always returns `Some` (it
                    // sanitizes even the already-elevated case into a derived), so this is defensive.
                    None => spawn_unelevated(cmd, kill_on_drop)?,
                };
                // Set the elevation report BEFORE handling the deferred password: a cleanup
                // kill() in the write-failure path must see the elevated state so an EPERM maps
                // to the typed Unkillable rather than leaking a raw Io.
                child.set_elevation(report);
                let written = password_write.map_or(Ok(()), |pw| pw.write_after_spawn());
                finish_elevated(child, written)
            })();
            return spawned.map_err(|failure| if wrapper { failure.behind_wrapper() } else { failure });
        }
        #[cfg(not(any(unix, windows)))]
        {
            return Err(SpawnFailure::NotStarted(Error::Unsupported {
                op: "elevation".into(),
                platform: std::env::consts::OS,
                detail: "no elevation backend on this platform".into(),
            }));
        }
    }
    spawn_unelevated(cmd, kill_on_drop)
}

/// Finish a POSIX elevated spawn whose deferred password write returned `written`.
///
/// On a failed write, do NOT orphan the running elevated child: kill its tree through its
/// containment when it has one, so a descendant forked before the failure dies too, then kill
/// and reap the root by its own handle, folding both outcomes into the error.
///
/// The reap follows the ROOT's kill alone. A tree kill can fail (a setuid member refusing the
/// signal) while the root dies, and a killed root must be waited for, or it stays a zombie. A
/// failed root kill (e.g. `Unkillable`) cannot be waited for, so it gets a non-blocking
/// `try_wait` and the note that it may still be running. A root already reaped (`Sent::Gone`) is
/// neither waited on nor `try_wait`ed, and is reported as "could not be terminated (it was already
/// reaped)".
///
/// A reaped root's number may name another process by now, so the tree kill is skipped when it
/// would name the tree by that number (a process group, a ppid walk), and the note says so.
///
/// A live front outside a cgroup (see [`Child::kill`]) is signalled by neither kill: the root's
/// kill is the typed `Unkillable`, and the note says so. A front that had already exited is reaped,
/// and the note says it had exited. A front in a cgroup is ended by the tree's cgroup kill alone,
/// read after it. The front's gate is decided once, before both kills.
///
/// The backend has run by now, so the program may have started: a backend that needed no password
/// runs it without reading one.
#[cfg(unix)]
pub(crate) fn finish_elevated(child: Child, written: Result<(), Error>) -> Result<Child, SpawnFailure> {
    let Err(write_err) = written else {
        return Ok(child);
    };
    let view = crate::containment::DropView::read(child.id, child.proc.is_reaped(), &child.tree_killed);
    let mut skipped = None;
    // A live front outside a cgroup is not signalled, by its group or otherwise: the root's kill
    // below then says why.
    let gate = child.kill_gate();
    let front_closed = matches!(gate, crate::elevation::front::Gate::Closed(_));
    let tree = (child.containment().can_teardown() && !front_closed).then(|| {
        child
            .attached
            .hard_kill_marking_unless_reaped(view, &child.tree_killed)
            .map(|s| skipped = s)
    });
    let tree_failure = match &tree {
        Some(Err(e)) => Some(e.to_string()),
        _ => None,
    };
    let mut tree_note = report_tree_teardown(tree, &child.attached.teardown_subject());
    if let Some(action) = skipped {
        tree_note.push_str(&format!(
            "; its contained tree was not killed: the root was already reaped, so its number may name another \
             process, and the kill would {action}"
        ));
    }
    let exited_front = matches!(gate, crate::elevation::front::Gate::Exited);
    let root = match gate {
        // Not asked again after the kill: a killed front can read as neither exited nor in its
        // cgroup, between leaving the cgroup's member list and becoming a zombie.
        crate::elevation::front::Gate::CgroupOnly if child.tree_killed.is_set() => {
            child.cgroup_kill_reached().map(|()| crate::signal::Sent::Delivered)
        }
        // No kill reached the cgroup: refused as `kill` refuses, naming why.
        crate::elevation::front::Gate::CgroupOnly => Err(crate::elevation::front::cgroup_not_killed_of(
            child.front,
            child.id().pid(),
            tree_failure.as_deref(),
        )),
        crate::elevation::front::Gate::Closed(unkillable) => Err(unkillable),
        gate => child.kill_sent_gated(gate),
    };
    let pid = child.id().pid();
    let (root_note, fate) = match root {
        Ok(crate::signal::Sent::Gone) if exited_front => (
            "the elevated child had already exited, and was reaped by someone else".to_string(),
            ChildFate::Gone,
        ),
        Ok(crate::signal::Sent::Gone) => (
            "the elevated child could not be terminated (it was already reaped)".to_string(),
            ChildFate::Gone,
        ),
        // A sync child's kill always verifies: the pidfd or the handle names it, and on macOS the
        // unique id every production spawn adopts is held (`SharedChild::adopt` is test-only there).
        // Were it ever not, the child may still be running.
        Ok(crate::signal::Sent::Unverified) => {
            debug_assert!(false, "a sync child's kill always verifies its target");
            (
                "the elevated child could not be terminated (it could not be verified, and may still be running)"
                    .to_string(),
                ChildFate::Running { id: Some(child.id()) },
            )
        }
        Ok(crate::signal::Sent::Delivered) => {
            #[cfg(test)]
            fault::run_between_kill_and_wait();
            match wait_killed_elevated(&child) {
                Ok(_status) => {
                    #[cfg(test)]
                    fault::record_teardown_reap(pid, _status);
                    let note = if exited_front {
                        "the elevated child had already exited, and was reaped"
                    } else {
                        "the elevated child was terminated"
                    };
                    (note.to_string(), ChildFate::Reaped)
                }
                Err(e) if exited_front => {
                    log::warn!("could not reap the exited elevated child pid {pid}: {e}");
                    (
                        format!("the elevated child had already exited, but could not be reaped ({e})"),
                        ChildFate::Killed,
                    )
                }
                Err(e) => {
                    log::warn!("could not reap the killed elevated child pid {pid}: {e}");
                    (
                        format!("the elevated child was killed but could not be reaped ({e})"),
                        ChildFate::Killed,
                    )
                }
            }
        }
        Err(e) => {
            #[cfg(test)]
            fault::run_between_kill_and_wait();
            // The non-blocking look reaps a child that has exited by now.
            let fate = fate_of_a_look(child.try_wait().map_err(|e| e.raw_os_error()), Some(child.id()));
            (format!("the elevated child could not be terminated ({e})"), fate)
        }
    };
    Err(SpawnFailure::started(
        Error::Elevation {
            kind: crate::error::ElevationErrorKind::AuthFailed,
            detail: format!("{write_err}; {root_note}{tree_note}"),
        },
        fate,
    ))
}

/// The fate of a child cosca did not kill (its kill was refused, or never sent), from one
/// non-blocking look that collects it if it has exited: `Reaped` then, `Running` if it has not
/// exited, `Gone` if the look found it reaped by someone else (`ECHILD`), and `Unknown` if the look
/// failed otherwise. `looked` carries the failed look's OS error, and `id` is the child's identity,
/// if the spawn had read one.
pub(crate) fn fate_of_a_look(
    looked: Result<Option<std::process::ExitStatus>, Option<i32>>,
    id: Option<ProcessId>,
) -> ChildFate {
    match looked {
        Ok(Some(_)) => ChildFate::Reaped,
        Ok(None) => ChildFate::Running { id },
        #[cfg(unix)]
        Err(Some(libc::ECHILD)) => ChildFate::Gone,
        Err(_) => ChildFate::Unknown,
    }
}

/// `child.wait()` after the root's kill, which a test can force to fail. The forced failure still
/// REAPS first, so the test that asks for it leaks nothing.
#[cfg(unix)]
fn wait_killed_elevated(child: &Child) -> Result<std::process::ExitStatus, Error> {
    let waited = child.wait();
    #[cfg(test)]
    if let Some(marker) = fault::take_force_reap_failure() {
        return waited.and(Err(Error::Io(std::io::Error::other(marker))));
    }
    waited
}

/// The head of the `warn` line [`report_tree_teardown`] logs.
#[cfg(unix)]
pub(crate) const TREE_TEARDOWN_WARN: &str = "tree teardown after a failed password write failed";

/// The marker of the warning about `leaf_path`'s tree teardown: unique to that leaf, so a twin
/// test running in parallel (same message text) is never miscounted.
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn teardown_warn_marker(leaf_path: &std::path::Path) -> String {
    format!("{TREE_TEARDOWN_WARN} (cgroup leaf {})", leaf_path.display())
}

/// Report a failed password write's tree teardown, for both `finish_elevated` variants: log it at
/// `warn` and return the note for the error's `detail`. `subject` names the tree, because the
/// teardown error itself may not (see `Attached::teardown_subject`).
///
/// `None`: no tree kill was tried, as the containment cannot tear one down. `Some(Ok)`: it worked.
/// Neither is reported.
#[cfg(unix)]
pub(crate) fn report_tree_teardown(tree: Option<Result<(), Error>>, subject: &dyn std::fmt::Display) -> String {
    let Some(Err(e)) = tree else {
        return String::new();
    };
    log::warn!("{TREE_TEARDOWN_WARN} ({subject}): {e}");
    format!("; its contained tree could not be killed ({subject}: {e})")
}

/// The one authority for Windows backend routing: does `cmd` go to the raw `CreateProcessW`
/// backend rather than std? Both routers read this — the sync one below and the async mirror in
/// `crate::tokio::spawn` — so the rule cannot be two copies that drift.
///
/// **Call it before `std::mem::take(cmd.fds_mut())`.** It reads `cmd.fds()`; after the take the
/// map is empty and the fd term silently evaluates false.
///
/// Pinned by `spawn_tests::routes_to_raw_backend_answers_for_executables_and_high_descriptors`,
/// which is also what makes the backend names in `tests/windows_creation_flags.rs` true for its
/// argv legs (an argv-only command reports the same `argv[0]` whichever backend spawned it).
#[cfg(windows)]
pub(crate) fn routes_to_raw_backend(cmd: &Command) -> bool {
    cmd.executable_path().is_some() || cmd.fds().keys().any(|slot| slot.raw() >= 3)
}

/// The non-elevated spawn core: resolve stdio, wire program/args, spawn, attach,
/// read identity, adopt. Shared by the ordinary path and the elevation paths'
/// already-elevated / derived-command continuations (which must spawn without
/// re-entering the elevation branch).
///
/// Every failure says whether the program could have started; see [`SpawnFailure`].
pub(crate) fn spawn_unelevated(cmd: &mut Command, kill_on_drop: bool) -> Result<Child, SpawnFailure> {
    // Before anything is made or forked: a pidfd that is refused means no child, and no leaf.
    #[cfg(target_os = "linux")]
    crate::wait::backend::probe_pidfd_support().not_started()?;
    // Read the routing rule BEFORE the take, which empties the map the rule reads. Evaluated
    // after, it would collapse to "does it have an executable()", and a high-descriptor-only
    // command would take the std path — whose fd >= 3 collection is unix-only, so the
    // descriptors would be dropped with no error and no panic.
    #[cfg(windows)]
    let to_raw_backend = routes_to_raw_backend(cmd);
    let fds = std::mem::take(cmd.fds_mut());

    // Windows routing. The raw `CreateProcessW` backend owns the cases std cannot
    // express: an `executable()` loaded independently of argv[0], and arbitrary descriptors
    // (fd >= 3) via the MSVCRT `lpReserved2` fd-table. It handles both uncontained and
    // CONTAINED children (Job Object / TreeWalk).
    #[cfg(windows)]
    if to_raw_backend {
        return windows_raw::spawn_raw(cmd, fds, kill_on_drop);
    }
    #[cfg(target_os = "linux")]
    let (mut std_cmd, handshake) = build_std_command_with(cmd, pidfd_handshake::register).not_started()?;
    #[cfg(target_os = "macos")]
    let (mut std_cmd, report) = build_std_command_with(cmd, unique_report::register).not_started()?;
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    let mut std_cmd = build_std_command(cmd).not_started()?;

    // Resolve every configured slot to a child end via the shared core. Slots: 0/1/2
    // (defaulting to inherit) plus, on Unix, any configured n>=3. We own our pipes
    // (`std::io::pipe`) and keep the parent ends.
    let std_slots = [Fd::STDIN, Fd::STDOUT, Fd::STDERR];
    let all_slots: Vec<Fd> = {
        // Yield 0/1/2 first (even unconfigured, for inherit defaulting), then any
        // configured n>=3. The n>=3 collection is Unix-only: on Windows the routing
        // above (any fd>=3 goes to the raw backend) guarantees `fds` holds no fd>=3,
        // so the push is dead code there — cfg-gate it to make that explicit.
        #[cfg_attr(not(unix), allow(unused_mut, reason = "the n>=3 push below is unix-only"))]
        let mut v: Vec<Fd> = std_slots.to_vec();
        #[cfg(unix)]
        for &fd in fds.keys() {
            if fd.raw() >= 3 {
                v.push(fd);
            }
        }
        v
    };
    let (mut child_ends, parent_ends) = resolve_stdio(&fds, &all_slots, PipeOwnership::Owned).not_started()?;

    // Hand 0/1/2 child ends to std (consumes them; std closes its copies on spawn).
    for slot in std_slots {
        if let Some(end) = child_ends.remove(&slot) {
            let stdio = StdStdio::from(end);
            match slot {
                Fd::STDIN => std_cmd.stdin(stdio),
                Fd::STDOUT => std_cmd.stdout(stdio),
                _ => std_cmd.stderr(stdio),
            };
        }
    }

    // Every child fd number this spawn will occupy, so the macOS fd-marker install (below)
    // places its own descriptor above all of them rather than colliding with a user mapping.
    #[cfg(unix)]
    let reserved: Vec<i32> = child_ends.keys().map(|fd| fd.raw()).collect();
    #[cfg(not(unix))]
    let reserved: Vec<i32> = Vec::new();

    // Phase 1 (before spawn): root detection + pre-spawn containment setup. This
    // MUST run before the fd_map block below so that fd_map installs
    // the LAST pre_exec hook. Why ordering matters: pre_exec hooks run in
    // registration order in the forked child. The Linux cgroup self-placement
    // hook (registered inside `prepare`) writes "0" to a pre-opened cgroup.procs
    // fd (CLOEXEC, which is still open between fork and exec). If
    // fd_map's dup2 ran FIRST, it could dup2 the user's fd over the number
    // that cgroup.procs fd occupies — closing/replacing it — so the later cgroup
    // write would hit a closed/wrong fd (silent CgroupV2->ProcessGroup downgrade,
    // or a stray "0" corrupting the user's fd). By running fd_map LAST, the
    // cgroup write+close happens while its fd is still valid; fd_map may then
    // freely reuse the now-closed slot. The same holds for the channel the child
    // reports that write's outcome through (`cgroup::ReportChannel`). Net child order: std stdio
    // (0/1/2) -> the `raw_executable()` chdir (`build_std_command`'s `enter_in_child`) ->
    // containment pre_execs (cgroup placement / setsid) -> fd_map dup2 (last).
    //
    // On macOS, `prepare` also clears FD_CLOEXEC on the marker write end for the forked
    // child only (the supervisor's own copy stays CLOEXEC — see `fdmarker::install`'s doc
    // comment). That leaves a real, bounded window — between the clear and this spawn's own
    // `exec` — where a truly concurrent, unrelated `fork()` on another thread of THIS process
    // could transiently inherit the marker fd and carry it past its own `exec`. The shared,
    // process-wide `spawn_lock` (already used to serialize against the Windows raw backend)
    // is widened on macOS to enclose `prepare` through `drop(std_cmd)`, closing that window
    // against every other cosca-originated spawn; `install`'s doc comment names the residual
    // (a spawn racing this one via a path outside cosca's own spawn functions) that no local
    // code can close.
    #[cfg(target_os = "macos")]
    let (mut prepared, child, unique) = {
        let _guard = spawn_lock();
        let prepared = crate::containment::prepare(
            &mut std_cmd,
            &cmd.contain_request(),
            cmd.flags_request(),
            &reserved,
            cmd.fd_marker_suppressed(),
            cmd.env_ops(),
        )
        .not_started()?;
        let report = report.open(&_guard).not_started()?;

        // On Unix, hand n>=3 child ends to fd_map. This installs a pre_exec hook
        // that dup2's each OwnedFd to its target number post-fork. It is registered
        // LAST (after `prepare` above) so its dup2 cannot clobber the cgroup
        // self-placement fd; std also dup2's 0/1/2 before any pre_exec runs (std
        // disables posix_spawn when hooks are registered), so our n>=3 mappings never
        // clobber the std stdio fds either. A duplicate child fd number is unreachable:
        // child_ends keys come from a BTreeMap, so each child fd number is unique.
        let mappings: Vec<fd_map::FdMapping> = child_ends
            .into_iter()
            .map(|(fd, owned)| fd_map::FdMapping {
                parent_fd: owned,
                child_fd: fd.raw(),
            })
            .collect();
        fd_map::install(&mut std_cmd, mappings).not_started()?;

        #[allow(
            clippy::disallowed_methods,
            reason = "spawn_lock is held by `_guard`, taken at the top of this block"
        )]
        let (spawned, unique) = report.run(|| std_cmd.spawn().map_err(Error::Io));
        // std collected the child of a spawn it failed, which never ran the program.
        let c = spawned
            .map_err(|e| unique_report::failed_spawn_error(e, &unique))
            .not_started()?;
        drop(std_cmd);
        (prepared, c, unique)
    };
    // Linux holds the child before `exec` until the parent has its pidfd; see `pidfd_handshake`.
    // Everything from the channel's creation to the helper's join is under `spawn_lock`.
    #[cfg(target_os = "linux")]
    let (mut prepared, child, pidfd) = {
        let prepared = crate::containment::prepare(
            &mut std_cmd,
            &cmd.contain_request(),
            cmd.flags_request(),
            &reserved,
            cmd.fd_marker_suppressed(),
            cmd.env_ops(),
        )
        .not_started()?;
        // A front this host could not place after a cgroup kill is refused before it is spawned.
        if let Some(leaf) = prepared
            .cgroup_leaf
            .as_ref()
            .filter(|_| cmd.elevation_front().is_some())
        {
            crate::containment::cgroup::front_placement(|| leaf.id()).not_started()?;
        }

        let _guard = spawn_lock();
        // The hook was registered first of all (see `build_std_command_with`), so `fd_map`'s, which
        // may `dup2` a mapping onto any number, including the channel's, runs after it is done.
        let handshake = handshake.open(&_guard).not_started()?;
        let mappings: Vec<fd_map::FdMapping> = child_ends
            .into_iter()
            .map(|(fd, owned)| fd_map::FdMapping {
                parent_fd: owned,
                child_fd: fd.raw(),
            })
            .collect();
        fd_map::install(&mut std_cmd, mappings).not_started()?;

        // Classified at the SYSCALL, not around the whole spawn: an access-denied from stdio
        // resolution or the post-spawn attach has nothing to do with a breakaway request.
        #[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `_guard` above")]
        let held = handshake.run(|| std_cmd.spawn())?;
        (prepared, held.child, held.pidfd)
    };
    #[cfg(windows)]
    let (mut prepared, child) = {
        let prepared = crate::containment::prepare(
            &mut std_cmd,
            &cmd.contain_request(),
            cmd.flags_request(),
            &reserved,
            cmd.fd_marker_suppressed(),
            cmd.env_ops(),
        )
        .not_started()?;

        // The std Child is owned here so containment can job-assign + resume it. Serialize the
        // spawn against the raw backend's inheritable-handle window via the shared spawn lock: std's
        // own handle-inheritance marking must not overlap a raw spawn on another thread.
        let c = {
            let _guard = spawn_lock();
            // Classified at the SYSCALL, not around the whole spawn: an access-denied from stdio
            // resolution or the post-spawn attach has nothing to do with a breakaway request.
            #[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `_guard` above")]
            let spawned = std_cmd.spawn().map_err(Error::Io);
            let spawned =
                spawned.map_err(|e| crate::command::flags::classify_spawn_syscall_error(e, *cmd.flags_request()));
            spawned.not_started()?
        };
        (prepared, c)
    };
    // Phase 2 (after spawn, before adopt): attach the mechanism (job/cgroup/...).
    // `prepared` is consumed here: Linux cgroup leaf ownership moves to Attached::Cgroup.
    #[cfg(windows)]
    let proc_handle = {
        use std::os::windows::io::AsRawHandle;
        child.as_raw_handle()
    };
    // Linux tears down through the pidfd the child sent: nothing there kills or reaps by pid.
    #[cfg(target_os = "linux")]
    let child = HeldStdChild {
        through: PidfdChild::new(Some(child.id()), pidfd),
        child,
    };
    let front = cmd.elevation_front();
    // macOS has no handle: the unique id the child reported before `exec` is what the identity is
    // checked against and the shared child is adopted with. The report decides first: a child that
    // died before `exec` is that, whatever an attach would find of its pid.
    #[cfg(target_os = "macos")]
    let unique = match unique_report::adopted_id(unique, child.id()) {
        Ok(unique) => unique,
        Err(not_adopted) => return Err(abandon_unadopted(child, not_adopted, front)),
    };
    // A front's leaf subtree, captured while it exists: a failure arm drops the leaf, killing it.
    #[cfg(target_os = "linux")]
    let subtree = front_subtree(front.and(prepared.cgroup_leaf.as_ref()));
    if front.is_some() {
        prepared.watch_front(child.id());
    }
    // Read the identity while we still own the un-reaped `std::process::Child`, and check the read
    // against the handle held since the spawn: a pid alone does not say whom it names once
    // something else has reaped the child. The attach takes this identity and does not re-read
    // the root's, so a reap and reuse after the check cannot make the containment name a stranger.
    // `SharedChild::adopt` reaps nothing, so this is also the identity it takes.
    #[cfg(test)]
    fault::run_at(fault::SpawnPoint::BeforeIdentity, child.id());
    #[cfg(target_os = "linux")]
    let through = child.through.target();
    #[cfg(target_os = "macos")]
    let through = crate::wait::exit_only::Target::pid(child.id(), Some(unique));
    #[cfg(windows)]
    let through = {
        use std::os::windows::io::AsHandle;
        crate::wait::exit_only::Target::Handle(child.as_handle())
    };
    let pid = child.id();
    #[cfg(target_os = "linux")]
    let handle = crate::containment::ChildHandle {
        pid,
        pidfd: std::os::fd::AsFd::as_fd(&child.through.pidfd),
    };
    let id = match resolve_identity(pid, &through) {
        crate::identity::Resolved::Found(id) => id,
        // Different diagnosis per arm: an OS refusal is not a vanish.
        other => {
            // Settle the leaf's verdict before any kill, so the kill never races its reads.
            settle_before_teardown(
                &mut prepared,
                #[cfg(target_os = "linux")]
                handle,
                #[cfg(not(target_os = "linux"))]
                pid,
            );
            // A front's containment goes first: a cgroup leaf's drop kills it, so the teardown below
            // waits for a contained front that kill reached, and says what became of it.
            #[cfg(target_os = "linux")]
            if front.is_some() {
                drop(prepared);
            }
            #[cfg(target_os = "macos")]
            let (fate, child_fate) = {
                let identity = if matches!(other, crate::identity::Resolved::Gone) {
                    crate::containment::RootIdentity::Gone
                } else {
                    crate::containment::RootIdentity::Unknown
                };
                // The read failed, so no identity is known.
                let child_fate = leave_unverified_child(child, identity, None);
                (FrontFate::of_unverified(identity), child_fate)
            };
            // The read failed, so no identity is known.
            #[cfg(target_os = "linux")]
            let (fate, child_fate) = teardown_unadopted_or_front(child, front, None, subtree.as_ref());
            #[cfg(all(not(target_os = "macos"), not(target_os = "linux")))]
            let (fate, child_fate) = teardown_unadopted_or_front(child, front, None);
            // The distinction must survive as a VARIANT, not as prose: a supervisor matching
            // on `Unassessable` to retry elevated would otherwise see an I/O failure and
            // treat a live, merely-unreadable child as a startup failure. A front's fate is a note.
            return Err(SpawnFailure::started(
                fate.note(spawn_identity_error(other), front, Some(pid)),
                child_fate,
            ));
        }
    };
    #[cfg(test)]
    fault::run_at(fault::SpawnPoint::BeforeAttach, child.id());
    let attachment = match attach_or_fault(
        id,
        #[cfg(target_os = "linux")]
        handle,
        #[cfg(windows)]
        proc_handle,
        prepared,
    ) {
        Ok(v) => v,
        Err(error) => {
            log::debug!("attach failed: {error}");
            // macOS: a front is left running and unreaped, sent nothing; any other child is killed
            // and reaped through its verified unique id.
            #[cfg(target_os = "macos")]
            let (fate, child_fate) = {
                assert_attach_cannot_fail(&error);
                if front.is_some() {
                    (
                        leave_front_after_attach_failure(child),
                        ChildFate::Running { id: Some(id) },
                    )
                } else {
                    (FrontFate::NotAFront, teardown_after_attach_failure(child, unique, id))
                }
            };
            // Off macOS: kill + reap so a failed attach never leaks the child (std `Child::drop`
            // neither kills nor reaps), unless it is a front. A failed attach has dropped the
            // containment already: a cgroup leaf's drop kills it, so a front in it is dying, and is
            // waited for.
            #[cfg(target_os = "linux")]
            let (fate, child_fate) = teardown_unadopted_or_front(child, front, Some(id), subtree.as_ref());
            #[cfg(all(not(target_os = "macos"), not(target_os = "linux")))]
            let (fate, child_fate) = teardown_unadopted_or_front(child, front, Some(id));
            return Err(SpawnFailure::started(fate.note(error, front, Some(pid)), child_fate));
        }
    };
    // The pidfd is already held, so adopting cannot fail.
    #[cfg(target_os = "linux")]
    let shared = SharedChild::adopt_opened(child.child, id, child.through.pidfd);
    #[cfg(target_os = "macos")]
    let shared = SharedChild::adopt_verified(child, id, unique);
    #[cfg(windows)]
    let shared = match SharedChild::adopt(child, id) {
        Ok(shared) => shared,
        Err((error, child)) => {
            let (error, fate) = teardown_after_failed_adoption(child, error, Some(id));
            return Err(SpawnFailure::started(error, fate));
        }
    };

    let mut child = Child::from_parts(ProcHandle::std(shared), id, parent_ends, kill_on_drop, attachment);
    child.set_front(cmd.elevation_front());
    Ok(child)
}

/// macOS: the identity is verified and the attach reads nothing, so an attach cannot fail. Only a
/// test seam makes it.
#[cfg(target_os = "macos")]
pub(crate) fn assert_attach_cannot_fail(error: &Error) {
    #[cfg(test)]
    debug_assert!(fault::force_attach_failure(), "a macOS attach cannot fail: {error}");
    #[cfg(not(test))]
    debug_assert!(false, "a macOS attach cannot fail: {error}");
    let _ = error;
}

/// macOS: a front whose attach failed is sent nothing and left running and unreaped, with a warning:
/// a kill would orphan the elevated program. Dropping the `std` `Child` closes our pipe ends only.
#[cfg(target_os = "macos")]
fn leave_front_after_attach_failure(child: std::process::Child) -> FrontFate {
    log::warn!(
        "elevation front pid {} is left running and unreaped, with nothing signalled or waited on by pid: its \
         attach failed, and a kill would orphan the elevated program",
        child.id()
    );
    drop(child);
    FrontFate::LeftUnreaped
}

/// macOS: a child whose attach failed is killed through its verified unique id and reaped only
/// after that id shows the zombie is ours.
/// - A kill that was delivered: wait for the exit, then reap once.
/// - A child already gone: nothing to do.
/// - A kill that failed: one verified, non-blocking reap, and the child is left.
///
/// The checks are not pins: macOS has no handle, so the kill has `via_verified_pid`'s window
/// between its id check and `kill(2)`, and the reap has `try_reap`'s between its id check and the
/// consuming `waitid`. A child that cannot be shown ours (a refused id read) is left with a `warn`;
/// a zombie launchd holds is not ours to reap, and is `Gone` (see [`Foreign::fate`]).
///
/// Dropping the `std` `Child` closes our pipe ends only.
#[cfg(target_os = "macos")]
fn teardown_after_attach_failure(child: std::process::Child, unique: u64, id: ProcessId) -> ChildFate {
    let fate = kill_and_reap_verified(child.id(), unique, Some(id));
    drop(child);
    fate
}

/// The kill and reap of [`teardown_after_attach_failure`], for a child by its pid, whoever holds its
/// handle. `id` is its identity, if one was read.
#[cfg(target_os = "macos")]
pub(crate) fn kill_and_reap_verified(pid: u32, unique: u64, id: Option<ProcessId>) -> ChildFate {
    use crate::signal::{via_verified_pid, Sent, Sig};
    use crate::wait::backend::{await_reapable, Waited};
    use crate::wait::exit_only::Foreign;

    let target = crate::wait::exit_only::Target::pid(pid, Some(unique));
    match via_verified_pid(pid, Some(unique), Sig::Kill) {
        Ok(Sent::Delivered) => match await_reapable(pid, Some(unique), None) {
            Ok(Waited::Reapable) => reap_verified(pid, &target, id, true),
            Ok(Waited::Gone) => {
                log::debug!("spawn teardown: pid {pid} was reaped by someone else");
                Foreign::Gone.fate(true)
            }
            Ok(Waited::Orphaned) => {
                log::warn!(
                    "spawn teardown: pid {pid} is not ours to reap (launchd holds its zombie, because its tracer died)"
                );
                Foreign::Orphaned.fate(true)
            }
            Ok(Waited::DeadlinePassed) => {
                log::warn!("spawn teardown: pid {pid} is still running after its kill");
                ChildFate::Running { id }
            }
            Err(e) => {
                log::warn!("spawn teardown could not wait for pid {pid}: {e}");
                ChildFate::Killed
            }
        },
        Ok(Sent::Gone) => {
            log::debug!("spawn teardown: pid {pid} is already gone");
            Foreign::Gone.fate(false)
        }
        Ok(Sent::Unverified) => {
            debug_assert!(false, "`via_verified_pid` was given `Some(unique)`, so it verifies");
            log::warn!("spawn teardown: pid {pid} could not be verified, so it was not signalled");
            ChildFate::Running { id }
        }
        Err(kill) => {
            log::warn!("spawn teardown failed to kill pid {pid}: {kill}");
            reap_verified(pid, &target, id, false)
        }
    }
}

/// [`teardown_after_attach_failure`]'s reap: consume `target`'s exit record only when a verified
/// peek shows the zombie is ours. Only a verified foreign reap is a `debug`; a child that cannot be
/// shown ours or reaped is a `warn`.
#[cfg(target_os = "macos")]
///
/// `killed`: whether cosca's kill was delivered, which decides the fate of a foreign verdict (see
/// [`Foreign::fate`]).
fn reap_verified(
    pid: u32,
    target: &crate::wait::exit_only::Target<'_>,
    id: Option<ProcessId>,
    killed: bool,
) -> ChildFate {
    use crate::wait::exit_only::{peek_verified, try_reap, Foreign, Peek, Reap, Reaped};

    let unverifiable = |why: &dyn std::fmt::Display| {
        log::warn!("spawn teardown: pid {pid} cannot be shown to be ours or reaped ({why})");
        ChildFate::Unknown
    };
    let foreign = |why: Foreign| {
        match why {
            Foreign::Orphaned => log::warn!(
                "spawn teardown: pid {pid} is not ours to reap (launchd holds its zombie, because its tracer died)"
            ),
            Foreign::Gone | Foreign::Other => log::debug!("spawn teardown: pid {pid} was reaped by someone else"),
        }
        why.fate(killed)
    };
    let running = || {
        log::warn!("spawn teardown: pid {pid} is still running");
        ChildFate::Running { id }
    };
    match peek_verified(target) {
        Err(e) => return unverifiable(&e),
        Ok(Peek::Foreign(why)) => return foreign(why),
        Ok(Peek::Running) => return running(),
        Ok(Peek::Exit(_)) => {}
    }
    match try_reap(target) {
        Ok(Reap::Reaped(Reaped::Status(_))) => ChildFate::Reaped,
        // The consuming `waitid` collected the zombie, whatever it reported.
        Ok(Reap::Reaped(Reaped::Unreadable { si_code })) => {
            log::warn!("spawn teardown: pid {pid}: a consuming waitid returned si_code {si_code}, not an exit record");
            debug_assert!(false, "a consuming waitid on a zombie returned si_code {si_code}");
            ChildFate::Reaped
        }
        Ok(Reap::Running) => running(),
        Ok(Reap::Foreign(why)) => foreign(why),
        Err(e) => {
            log::warn!("spawn teardown failed to reap pid {pid}: {e}");
            ChildFate::Unknown
        }
    }
}

/// macOS: `child` could not be adopted, so it is abandoned with nothing signalled or waited on by
/// pid, and the spawn fails with `not_adopted.error`. A child that died before `exec` is only a
/// corpse nothing collects, and the program did not start. A child that had not reported is left
/// running and unreaped. Any other is left as `leave_unverified_child` leaves it. Either of those may
/// have started the program, and the error notes that a `front` is left unreaped.
#[cfg(target_os = "macos")]
fn abandon_unadopted(
    child: std::process::Child,
    not_adopted: unique_report::NotAdopted,
    front: Option<crate::elevation::front::Front>,
) -> SpawnFailure {
    use unique_report::Unadoptable;

    let pid = child.id();
    let error = not_adopted.error;
    match not_adopted.why {
        Unadoptable::DiedBeforeExec => {
            log::warn!(
                "child {pid} died before exec; nothing is signalled or waited on by pid, so its status is not collected"
            );
            drop(child);
            SpawnFailure::NotStarted(error)
        }
        Unadoptable::Unreported => {
            #[cfg(test)]
            fault::capture(ProcessId::of(pid));
            log::warn!(
                "child {pid} had not reported its unique id when its spawn returned; it is not adopted, nothing is \
                 signalled or waited on by pid, and it may be running"
            );
            drop(child);
            SpawnFailure::started(
                FrontFate::LeftUnreaped.note(error, front, Some(pid)),
                // No unique id was read, so there is no identity to give.
                ChildFate::Running { id: None },
            )
        }
        Unadoptable::Unverified => {
            // No unique id was read, so there is no identity to give.
            let (error, fate) = teardown_after_failed_adoption(child, error, None);
            SpawnFailure::started(
                FrontFate::of_unverified(crate::containment::RootIdentity::Unknown).note(error, front, Some(pid)),
                fate,
            )
        }
    }
}

/// macOS: abandon `child` without signalling or waiting on it by pid, since nothing shows its pid
/// still names it. `RootIdentity::Gone` means someone else reaped it, so it is forgotten; otherwise
/// it is left unreaped. Dropping the `std` `Child` closes our pipe ends only. Either way
/// a warning names the pid, and the spawn still fails: the caller must not assume the program did
/// not start.
#[cfg(target_os = "macos")]
fn leave_unverified_child(
    child: std::process::Child,
    identity: crate::containment::RootIdentity,
    id: Option<ProcessId>,
) -> ChildFate {
    let pid = child.id();
    let fate = if identity == crate::containment::RootIdentity::Gone {
        log::warn!(
            "child {pid} was reaped by someone else; its pid may be reused, so nothing is signalled or waited on by pid"
        );
        ChildFate::Gone
    } else {
        log::warn!(
            "child {pid} cannot be shown to be ours (its identity could not be read); leaving it unreaped, with \
             nothing signalled or waited on by pid, and it may still be running"
        );
        ChildFate::Running { id }
    };
    drop(child);
    fate
}

/// The spawned `child` could not be adopted. Answers `error`.
///
/// - **Windows:** its process handle could not be duplicated. The handle still pins the process, so
///   the child is torn down.
/// - **macOS:** its unique-id report is not an id (unreadable or malformed), so it is left alone
///   (see `leave_unverified_child`).
///
/// Not on Linux, where the pidfd is opened before `exec` (see `pidfd_handshake`) and adoption
/// cannot fail.
#[cfg(not(target_os = "linux"))]
fn teardown_after_failed_adoption(
    child: std::process::Child,
    error: Error,
    id: Option<ProcessId>,
) -> (Error, ChildFate) {
    #[cfg(test)]
    fault::capture(ProcessId::of(child.id()));
    #[cfg(target_os = "macos")]
    let fate = leave_unverified_child(child, crate::containment::RootIdentity::Unknown, id);
    #[cfg(not(target_os = "macos"))]
    let fate = teardown_unadopted(child, id);
    (error, fate)
}

/// Serializes spawns against the process-global inheritable-handle window: on Windows both the std
/// path and the raw `CreateProcessW` backend must mark child-side handles inheritable, spawn, then
/// un-mark/close without a concurrent spawn inheriting them. Held across that window on both paths.
/// **Poison-tolerant:** a panic mid-spawn must not wedge every future spawn, so a poisoned lock is
/// recovered rather than propagated (the guarded data is unit — there is no invariant to protect).
pub(crate) fn spawn_lock() -> SpawnLockGuard {
    acquire_spawn_lock(|| {})
}

static SPAWN_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Holds [`spawn_lock`]. Under `debug_assertions` (and in test builds) it also records that this
/// thread holds the non-reentrant mutex, so a nested acquire fails with a named panic instead of
/// deadlocking.
#[must_use = "if unused the spawn lock is released immediately; bind the guard for the whole window"]
pub(crate) struct SpawnLockGuard {
    _guard: std::sync::MutexGuard<'static, ()>,
}

thread_local! {
    /// Whether THIS thread holds `SPAWN_MUTEX`; set and cleared only by [`SpawnLockGuard`].
    /// `const`-initialized with no destructor, so reading it in a forked child is safe.
    #[cfg(any(test, debug_assertions))]
    static SPAWN_LOCK_HELD_BY_THIS_THREAD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

#[cfg(any(test, debug_assertions))]
impl Drop for SpawnLockGuard {
    fn drop(&mut self) {
        SPAWN_LOCK_HELD_BY_THIS_THREAD.with(|f| f.set(false));
    }
}

/// Takes `SPAWN_MUTEX`. `on_contended` runs first if it is already held, before this blocks.
fn acquire_spawn_lock(on_contended: impl FnOnce()) -> SpawnLockGuard {
    #[cfg(any(test, debug_assertions))]
    assert!(
        !spawn_lock_held_by_this_thread(),
        "spawn_lock re-entered: the mutex is not reentrant; drop the outer spawn_lock() (fork_running and cosca spawns take it themselves)"
    );
    let guard = match SPAWN_MUTEX.try_lock() {
        Ok(guard) => guard,
        Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
        Err(std::sync::TryLockError::WouldBlock) => {
            on_contended();
            SPAWN_MUTEX.lock().unwrap_or_else(|e| e.into_inner())
        }
    };
    #[cfg(any(test, debug_assertions))]
    SPAWN_LOCK_HELD_BY_THIS_THREAD.with(|f| f.set(true));
    SpawnLockGuard { _guard: guard }
}

/// Like [`spawn_lock`], but `on_contended` runs first if the lock is already held, before this
/// blocks on it.
#[cfg(all(target_os = "linux", test))]
pub(crate) fn spawn_lock_tracked(on_contended: impl FnOnce()) -> SpawnLockGuard {
    acquire_spawn_lock(on_contended)
}

/// Whether THIS thread currently holds `spawn_lock`'s mutex.
#[cfg(any(test, debug_assertions))]
pub(crate) fn spawn_lock_held_by_this_thread() -> bool {
    SPAWN_LOCK_HELD_BY_THIS_THREAD.with(|f| f.get())
}

#[cfg(any(not(any(target_os = "linux", target_os = "macos")), test))]
pub(crate) fn build_std_command(cmd: &Command) -> Result<std::process::Command, Error> {
    build_std_command_with(cmd, |_| ()).map(|(std_cmd, ())| std_cmd)
}

/// [`build_std_command`], running `first` on the command before any hook of its own is
/// registered, so a hook `first` registers runs first in the child. Returns what `first` returned.
pub(crate) fn build_std_command_with<R>(
    cmd: &Command,
    first: impl FnOnce(&mut std::process::Command) -> R,
) -> Result<(std::process::Command, R), Error> {
    // Program + args via the `quote` model.
    let StdLaunch {
        program,
        mut std_cmd,
        cwd,
        enter,
    } = match cmd.input() {
        CommandInput::Empty => return Err(Error::Io(std::io::Error::other("no program specified"))),
        CommandInput::Argv(argv) => {
            let (Resolved { program, cwd, enter }, rest) = resolve_program_argv(cmd, argv)?;
            let mut c = std::process::Command::new(&program);
            c.args(rest);
            // POSIX: when executable() overrides the loaded file, preserve the
            // user's argv[0] via arg0() — the executable as written when argv is
            // empty. Without this, std would set argv[0] to the (possibly completed)
            // program path, silently dropping the user's intended name.
            #[cfg(unix)]
            if let Some(exe) = cmd.executable_path() {
                use std::os::unix::process::CommandExt;
                c.arg0(argv.first().map_or(exe.as_os_str(), std::ffi::OsString::as_os_str));
            }
            StdLaunch {
                program,
                std_cmd: c,
                cwd,
                enter,
            }
        }
        CommandInput::CommandLine(line) => build_from_commandline(cmd, line)?,
    };
    // Reject .bat/.cmd (BatBadBut) on Windows, and an interior NUL everywhere — this is the std
    // backend's only NUL check, and the default Windows path. Judged on the token WE resolved,
    // not on `std_cmd.get_program()`: std's Unix constructor swaps a NUL-bearing program for a
    // `<string-with-nul>` sentinel, so reading it back would hide the exact token the gate exists
    // to judge (and would make this verdict differ by platform for reasons unrelated to Windows).
    reject_batch_path(std::path::Path::new(&program))?;
    apply_env(&mut std_cmd, cmd.env_ops());
    let first = first(&mut std_cmd);
    match cwd {
        Some(dir) if enter => enter_in_child(&mut std_cmd, &dir)?,
        Some(dir) => {
            std_cmd.current_dir(dir);
        }
        None => {}
    }
    Ok((std_cmd, first))
}

/// `chdir` to `dir` in the child, after std's own setup and just before its `execvp`, so a
/// relative program is read against the directory the child runs in, both relative to the cwd it
/// inherited (see `crate::resolve::exact::anchor_posix`).
///
/// This is what std's `current_dir` would mostly do already, and it is done here because std does
/// not promise it: "If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
/// whether it should be interpreted relative to the parent's working directory or relative to
/// `current_dir`. The behavior in this case is platform specific and unstable". std 1.97.1 happens
/// to read it against the new directory on both of its paths — fork/exec (which it takes on
/// Apple for this case) and glibc's `posix_spawn` with `addchdir` — but either could change. std
/// documents `pre_exec` hooks as running in the child just before the exec, so the ordering is
/// pinned. The cost is that a hook rules out `posix_spawn`, for these commands only.
#[cfg(unix)]
fn enter_in_child(std_cmd: &mut std::process::Command, dir: &std::path::Path) -> Result<(), Error> {
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::process::CommandExt;
    let dir = std::ffi::CString::new(dir.as_os_str().as_bytes()).map_err(|_| {
        Error::Io(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "current_dir() contains an embedded NUL",
        ))
    })?;
    // SAFETY: `chdir` is async-signal-safe, and `dir` is allocated before the fork and only read
    // after it.
    unsafe {
        std_cmd.pre_exec(move || {
            #[expect(
                clippy::disallowed_methods,
                reason = "this closure runs in the forked child, between fork and exec, so the chdir \
                          moves that child's cwd and never this process's — see this function's doc"
            )]
            let status = libc::chdir(dir.as_ptr());
            if status == 0 {
                Ok(())
            } else {
                Err(std::io::Error::last_os_error())
            }
        });
    }
    Ok(())
}

#[cfg(not(unix))]
fn enter_in_child(_: &mut std::process::Command, _: &std::path::Path) -> Result<(), Error> {
    unreachable!("only anchor_posix asks the child to enter its directory")
}

/// The program to load and the directory to run it in.
struct Resolved {
    program: std::ffi::OsString,
    cwd: Option<std::path::PathBuf>,
    /// The child enters `cwd` itself; see `crate::resolve::exact::Anchored::enter`.
    enter: bool,
}

// Pick the executable file to load (`executable` overrides argv[0]/first-token). On POSIX an
// `Exact` program arrives in a form no exec searches (see `crate::resolve::exact::anchor_posix`);
// on Windows a set executable never reaches this std path, routing to the raw backend instead.
fn resolve_program(cmd: &Command, fallback: std::ffi::OsString) -> Result<Resolved, Error> {
    let as_given = |exe: Option<&std::path::Path>| Resolved {
        program: exe.map_or(fallback, |p| p.as_os_str().to_os_string()),
        cwd: cmd.cwd().map(std::path::Path::to_path_buf),
        enter: false,
    };
    #[cfg(unix)]
    if let Some(crate::command::ExecutableSpec::Exact(p)) = cmd.executable_spec() {
        let a = crate::resolve::exact::anchor_posix(p.as_os_str(), cmd.cwd())?;
        return Ok(Resolved {
            program: a.program.into_os_string(),
            cwd: a.cwd,
            enter: a.enter,
        });
    }
    Ok(as_given(cmd.executable_path()))
}

// Program + the trailing args (argv mode). `executable` overrides the loaded file; argv[0] is the
// conventional program name otherwise — POSIX argv[0] preservation happens at the caller (see
// build_std_command). On Windows a set `executable` never reaches this std path — it routes to
// the raw `CreateProcessW` backend, which preserves argv[0] independently of the loaded image.
fn resolve_program_argv<'a>(
    cmd: &'a Command,
    argv: &'a [std::ffi::OsString],
) -> Result<(Resolved, &'a [std::ffi::OsString]), Error> {
    if argv.is_empty() && cmd.executable_path().is_none() {
        return Err(Error::Io(std::io::Error::other("empty argv")));
    }
    let fallback = if argv.is_empty() {
        std::ffi::OsString::new()
    } else {
        argv[0].clone()
    };
    let program = resolve_program(cmd, fallback)?;
    let rest = if argv.is_empty() { argv } else { &argv[1..] };
    Ok((program, rest))
}

/// The resolved program token alongside the `std::process::Command` built from it and the
/// directory to run it in.
struct StdLaunch {
    program: std::ffi::OsString,
    std_cmd: std::process::Command,
    cwd: Option<std::path::PathBuf>,
    enter: bool,
}

#[cfg(unix)]
fn build_from_commandline(cmd: &Command, line: &std::ffi::OsString) -> Result<StdLaunch, Error> {
    use std::ffi::OsString;
    use std::os::unix::ffi::{OsStrExt, OsStringExt};
    let words = crate::quote::posix::split(line.as_bytes())?;
    // `OsStringExt::from_vec` already yields an OsString; do NOT wrap it in
    // `OsString::from(..)` (that is redundant and fails type inference).
    let argv: Vec<OsString> = words.into_iter().map(OsString::from_vec).collect();
    if argv.is_empty() {
        return Err(Error::Io(std::io::Error::other("empty command line")));
    }
    let Resolved { program, cwd, enter } = resolve_program(cmd, argv[0].clone())?;
    let mut c = std::process::Command::new(&program);
    // When executable() overrides the loaded file, argv[0] from the command
    // line is the user's intended name — preserve it via arg0().
    if cmd.executable_path().is_some() {
        use std::os::unix::process::CommandExt;
        c.arg0(&argv[0]);
    }
    c.args(&argv[1..]);
    Ok(StdLaunch {
        program,
        std_cmd: c,
        cwd,
        enter,
    })
}

#[cfg(windows)]
fn build_from_commandline(cmd: &Command, line: &std::ffi::OsString) -> Result<StdLaunch, Error> {
    use std::os::windows::ffi::{OsStrExt, OsStringExt};
    use std::os::windows::process::CommandExt;
    // Windows is command-line-native. CRITICAL: std::process always PREPENDS a
    // quoted form of the program to lpCommandLine and then appends raw_arg. So
    // raw_arg must be the ARGS portion only (the line MINUS its first token);
    // passing the whole line would duplicate the program token in the child's
    // argv. We split the first token off with first_token_and_rest_wide.
    //
    // This std path is only reached for a commandline() WITHOUT executable(): a set
    // executable() routes to the raw `CreateProcessW` backend (which sets
    // lpApplicationName independently of lpCommandLine) before `build_std_command`
    // is ever called, on both the sync and async spawn paths.
    let wide: Vec<u16> = line.encode_wide().collect();
    let (first, rest) = crate::quote::windows::first_token_and_rest_wide(&wide)
        .ok_or_else(|| Error::Io(std::io::Error::other("empty command line")))?;
    let program = std::ffi::OsString::from_wide(&first);
    let mut c = std::process::Command::new(&program);
    c.raw_arg(std::ffi::OsString::from_wide(&rest)); // args only — program is prepended by std
    Ok(StdLaunch {
        program,
        std_cmd: c,
        cwd: cmd.cwd().map(std::path::Path::to_path_buf),
        enter: false,
    })
}

pub(crate) fn apply_env(std_cmd: &mut std::process::Command, ops: &[EnvOp]) {
    for op in ops {
        match op {
            EnvOp::Set(k, v) => {
                std_cmd.env(k, v);
            }
            EnvOp::Remove(k) => {
                std_cmd.env_remove(k);
            }
            EnvOp::Clear => {
                std_cmd.env_clear();
            }
        }
    }
}

/// The child-side ends (keyed by slot) plus, for `Owned` pipes, the parent ends — the
/// result of [`resolve_stdio`].
pub(crate) type ResolvedStdioEnds = (BTreeMap<Fd, ChildEnd>, BTreeMap<Fd, ParentEnd>);

/// How pipe slots are handled during stdio resolution — the sole axis on which the
/// sync and async spawn paths diverge.
#[derive(Clone, Copy)]
pub(crate) enum PipeOwnership {
    /// Sync: create the OS pipe now (`std::io::pipe`), keep the child end for the
    /// child, and return the parent end to the caller.
    Owned,
    /// Async: tokio owns the piped STD ends (0/1/2) — those slots are left out of the
    /// resolved child ends (the caller assigns `Stdio::piped()`), and a merge into a piped
    /// STD target is rejected (its end is tokio's, not ours to dup). fd >= 3 pipes are OURS
    /// on every path: they resolve like `Owned` and produce parent ends.
    #[cfg_attr(
        not(feature = "tokio"),
        allow(dead_code, reason = "only the async spawn path constructs Deferred")
    )]
    Deferred,
}

/// Shared stdio-resolution core for both spawn paths. `slots` is the resolution order (0/1/2
/// always; the sync path adds Unix n>=3); the per-caller tails (fd>=3 policy, fd_map wiring,
/// final `Stdio` assignment) stay with each spawn.
pub(crate) fn resolve_stdio(
    fds: &BTreeMap<Fd, ResolvedStdio>,
    slots: &[Fd],
    pipe: PipeOwnership,
) -> Result<ResolvedStdioEnds, Error> {
    // Reject merge-targeting-a-merge: the two-pass algorithm resolves only one level of
    // indirection. Transitive chaining (a fixpoint loop) is an unsupported design limit — redirect
    // to a concrete slot (pipe/file/null/inherit) instead.
    for &slot in slots {
        if let Some(ResolvedStdio::Merge(target)) = fds.get(&slot) {
            if matches!(fds.get(target), Some(ResolvedStdio::Merge(_))) {
                return Err(Error::Unsupported {
                    op: format!("merge {slot} -> {target} -> <another merge>"),
                    platform: std::env::consts::OS,
                    detail: "chained merges (merge-to-merge) are not supported; \
                             redirect to a concrete slot (pipe/file/null/inherit)"
                        .into(),
                });
            }
        }
    }

    let mut child_ends: BTreeMap<Fd, ChildEnd> = BTreeMap::new();
    let mut parent_ends: BTreeMap<Fd, ParentEnd> = BTreeMap::new();

    // First pass: resolve non-merge slots. `Deferred` pipe slots are tokio-owned — skip
    // them. Std slots 0/1/2 default to inherit when unconfigured; an n>=3 slot has no
    // default, so skip an unconfigured one.
    for &slot in slots {
        let resolved = fds.get(&slot);
        match resolved {
            Some(ResolvedStdio::Merge(_)) => continue, // second pass
            Some(ResolvedStdio::Pipe(_)) if matches!(pipe, PipeOwnership::Deferred) && slot.raw() < 3 => continue,
            None if slot.raw() >= 3 => continue,
            _ => {
                let (child_end, parent) = resolve_non_merge(slot, resolved)?;
                if let Some(p) = parent {
                    parent_ends.insert(slot, p);
                }
                child_ends.insert(slot, child_end);
            }
        }
    }

    // Second pass: dup each merge from its already-resolved target. With `Deferred` pipes
    // a merge into a pipe target has no child end of ours to dup — reject it.
    for &slot in slots {
        if let Some(ResolvedStdio::Merge(target)) = fds.get(&slot) {
            if matches!(pipe, PipeOwnership::Deferred)
                && target.raw() < 3
                && matches!(fds.get(target), Some(ResolvedStdio::Pipe(_)))
            {
                return Err(Error::Unsupported {
                    op: format!("async merge {slot} -> {target} (piped)"),
                    platform: std::env::consts::OS,
                    detail: "merging into a piped target with a deferred (tokio-owned) pipe end needs \
                             the merge target resolved first; merge into file/null/inherit, or capture \
                             separately"
                        .into(),
                });
            }
            let src = child_ends.get(target).ok_or_else(|| Error::Unsupported {
                op: format!("merge {slot} -> {target}"),
                platform: std::env::consts::OS,
                detail: "merge target descriptor is not configured".into(),
            })?;
            child_ends.insert(slot, dup(src)?);
        }
    }

    Ok((child_ends, parent_ends))
}

// Resolve a non-merge slot to its child-side end + the parent's pipe end (if any).
pub(crate) fn resolve_non_merge(slot: Fd, r: Option<&ResolvedStdio>) -> Result<(ChildEnd, Option<ParentEnd>), Error> {
    match r {
        None | Some(ResolvedStdio::Inherit) => Ok((inherit_end(slot)?, None)),
        Some(ResolvedStdio::Null) => Ok((null_end()?, None)),
        Some(ResolvedStdio::File(f)) => Ok((file_end(f)?, None)),
        Some(ResolvedStdio::Pipe(dir)) => make_pipe(*dir),
        Some(ResolvedStdio::Merge(_)) => unreachable!("merge handled in second pass"),
    }
}

fn make_pipe(dir: Direction) -> Result<(ChildEnd, Option<ParentEnd>), Error> {
    let (reader, writer) = std::io::pipe().map_err(Error::Io)?;
    match dir {
        // Child reads: child gets the reader; parent keeps the writer.
        Direction::In => Ok((ChildEnd::from(reader), Some(ParentEnd::Writer(writer)))),
        // Child writes: child gets the writer; parent keeps the reader.
        Direction::Out => Ok((ChildEnd::from(writer), Some(ParentEnd::Reader(reader)))),
    }
}

pub(crate) fn dup(end: &ChildEnd) -> Result<ChildEnd, Error> {
    #[cfg(unix)]
    {
        use std::os::fd::AsFd;
        end.as_fd().try_clone_to_owned().map_err(Error::Io)
    }
    #[cfg(windows)]
    {
        use std::os::windows::io::AsHandle;
        end.as_handle().try_clone_to_owned().map_err(Error::Io)
    }
}

fn null_end() -> Result<ChildEnd, Error> {
    let f = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(if cfg!(windows) { "NUL" } else { "/dev/null" })
        .map_err(Error::Io)?;
    Ok(ChildEnd::from(f))
}

fn file_end(f: &std::fs::File) -> Result<ChildEnd, Error> {
    // Dup the file so the caller's File stays usable.
    let dup = f.try_clone().map_err(Error::Io)?;
    Ok(ChildEnd::from(dup))
}

fn inherit_end(slot: Fd) -> Result<ChildEnd, Error> {
    // Duplicate the parent's matching std stream. Bind the stream to a variable
    // before borrowing its descriptor (a temporary would be dropped while borrowed).
    // For n>=3, Stdio::inherit() has no defined parent stream to dup — a design limit
    // kept as a loud Unsupported on every path (the raw backend routes here too), never a
    // silent drop.
    #[cfg(unix)]
    {
        use std::os::fd::AsFd;
        let owned = match slot {
            Fd::STDIN => {
                let s = std::io::stdin();
                s.as_fd().try_clone_to_owned()
            }
            Fd::STDOUT => {
                let s = std::io::stdout();
                s.as_fd().try_clone_to_owned()
            }
            Fd::STDERR => {
                let s = std::io::stderr();
                s.as_fd().try_clone_to_owned()
            }
            other => {
                return Err(Error::Unsupported {
                    op: format!("Stdio::inherit() on {other}"),
                    platform: "unix",
                    detail: "inherit on fd >= 3 has no defined parent stream; \
                             use pipe/file/null instead"
                        .into(),
                })
            }
        };
        owned.map_err(Error::Io)
    }
    #[cfg(windows)]
    {
        use std::os::windows::io::AsHandle;
        let owned = match slot {
            Fd::STDIN => {
                let s = std::io::stdin();
                s.as_handle().try_clone_to_owned()
            }
            Fd::STDOUT => {
                let s = std::io::stdout();
                s.as_handle().try_clone_to_owned()
            }
            Fd::STDERR => {
                let s = std::io::stderr();
                s.as_handle().try_clone_to_owned()
            }
            // fd >= 3 has no defined parent std stream to dup (mirrors the Unix arm). Retained design
            // limit: the raw backend routes fd >= 3 inherit through here and rejects it too.
            other => {
                return Err(Error::Unsupported {
                    op: format!("Stdio::inherit() on {other}"),
                    platform: "windows",
                    detail: "inherit on fd >= 3 has no defined parent stream; \
                             use pipe/file/null instead"
                        .into(),
                })
            }
        };
        owned.map_err(Error::Io)
    }
}

/// The error for a spawn whose child could not be identified. `Gone` is an absence;
/// `Unknown` is an OS refusal about a child that may be running fine - never report the
/// second as the first.
pub(crate) fn spawn_identity_error(outcome: crate::identity::Resolved<ProcessId>) -> Error {
    match outcome {
        // An unavailable Linux `/proc` view is named; any other refusal is the OS's.
        crate::identity::Resolved::Unknown => crate::identity::unknown_identity_error("the spawned child")
            .unwrap_or_else(|| Error::Unassessable {
                detail: "the OS refused to report the spawned child's identity".into(),
                source: None,
            }),
        _ => Error::Io(std::io::Error::other(
            "the spawned child exited and was reaped by another party, or its zombie is held by one, before its \
             identity could be read",
        )),
    }
}

/// Read the spawned child's stable identity, then check through `through`, the handle held since
/// the spawn, that the read named our child.
///
/// - **Linux:** a peek through the pidfd after the read. `Running` and `Exit` keep the read (a
///   reap is irreversible, so the pid named our child throughout); `Foreign` is `Gone`; a failed
///   peek is `Unknown`, warned.
/// - **macOS:** the same, but the peek compares the pid's current unique id with the one `through`
///   carries; a mismatch is `Foreign`, an unreadable id is an error (`Unknown`), and `Orphaned`
///   (held by launchd after its tracer died) is `Gone`, as every foreign verdict is.
/// - **Windows:** the process handle pins the pid, so the read stands.
///
/// On macOS the `through` id is the one the child reported before `exec`.
pub(crate) fn resolve_identity(
    pid: u32,
    through: &crate::wait::exit_only::Target<'_>,
) -> crate::identity::Resolved<ProcessId> {
    use crate::identity::Resolved;

    let read = resolve_identity_unchecked(pid);
    let Resolved::Found(_) = read else {
        return read;
    };
    #[cfg(test)]
    fault::run_at(fault::SpawnPoint::AfterIdentityRead, pid);
    #[cfg(unix)]
    {
        use crate::wait::exit_only::Peek;
        #[cfg(target_os = "linux")]
        let peeked = crate::wait::exit_only::peek(through);
        #[cfg(target_os = "macos")]
        let peeked = crate::wait::exit_only::peek_verified(through);
        match peeked {
            Ok(Peek::Running | Peek::Exit(_)) => read,
            // macOS: held by launchd after its tracer died. It has exited and is not ours to reap, so it
            // is `Gone`, with a warning that its zombie is not collected.
            #[cfg(target_os = "macos")]
            Ok(Peek::Foreign(crate::wait::exit_only::Foreign::Orphaned)) => {
                log::warn!("child {pid}: launchd holds its zombie, so its tracer died; it is not ours to reap");
                Resolved::Gone
            }
            Ok(Peek::Foreign(_)) => Resolved::Gone,
            Err(e) => {
                log::warn!("child {pid}: its identity could not be checked against its handle ({e}); it is not shown to be ours");
                Resolved::Unknown
            }
        }
    }
    #[cfg(windows)]
    {
        let _ = through;
        read
    }
}

/// The unchecked half of [`resolve_identity`]: the read by pid alone, which nothing has yet shown
/// to name our child. Only `resolve_identity` and tests call it. A test-only fault seam (`fault`)
/// can force the vanished or unreadable branch.
pub(crate) fn resolve_identity_unchecked(pid: u32) -> crate::identity::Resolved<ProcessId> {
    #[cfg(test)]
    {
        if fault::force_identity_unknown() {
            fault::capture(ProcessId::of(pid));
            return crate::identity::Resolved::Unknown;
        }
        if fault::force_identity_vanished() {
            // Capture the child's real identity for the test to check what became of the child,
            // then simulate a vanish so `spawn` takes the identity-failure arm.
            fault::capture(ProcessId::of(pid));
            // The seam simulates a VANISH, not a refusal.
            return crate::identity::Resolved::Gone;
        }
    }
    ProcessId::of(pid)
}

/// `containment::attach` for the child whose identity `id` the spawn verified, with a test-only
/// seam to force its failure.
pub(crate) fn attach_or_fault(
    id: ProcessId,
    #[cfg(target_os = "linux")] child: crate::containment::ChildHandle<'_>,
    #[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
    prepared: crate::containment::Prepared,
) -> Result<crate::containment::Attachment, Error> {
    #[cfg(test)]
    if fault::force_attach_failure() {
        // Capture identity for the test to check what became of the child, then simulate an attach
        // failure so `spawn` takes the attach-error arm. The caller still holds the child, so the
        // verdict is taken before `prepared` drops, as a real attach takes it.
        fault::capture(crate::identity::Resolved::Found(id));
        let mut prepared = prepared;
        prepared.settle_verdict(
            #[cfg(target_os = "linux")]
            child,
            #[cfg(not(target_os = "linux"))]
            id.pid(),
        );
        // Model a REAL attach failure, which surfaces as `Error::Containment` (not `Error::Io`), so
        // the tests assert production behavior rather than the seam's fabricated variant.
        return Err(Error::Containment {
            detail: "forced attach failure (test seam)".into(),
        });
    }
    #[cfg(all(test, target_os = "linux"))]
    if let Some(attachment) = fault::take_attachment_override() {
        let mut prepared = prepared;
        prepared.settle_verdict(
            #[cfg(target_os = "linux")]
            child,
            #[cfg(not(target_os = "linux"))]
            id.pid(),
        );
        return Ok(attachment);
    }
    crate::containment::attach(
        id,
        #[cfg(target_os = "linux")]
        child,
        #[cfg(windows)]
        proc_handle,
        prepared,
    )
}

/// A spawned child that an error path abandons before adoption, killed and reaped by
/// [`teardown_unadopted`].
#[cfg(not(target_os = "macos"))]
trait Unadopted: Send + 'static {
    /// Its pid, for logs; `None` where the spawn that failed never handed the child back.
    fn pid(&self) -> Option<u32>;
    /// `Ok` for a child that has already exited.
    fn kill(&mut self) -> std::io::Result<()>;
    /// Whether the last `kill` delivered a signal, rather than finding the child already gone.
    #[cfg(unix)]
    fn kill_delivered(&self) -> bool {
        true
    }
    fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>>;
    /// Blocks until the child exits, and reaps it.
    fn wait(&mut self) -> std::io::Result<std::process::ExitStatus>;
    /// The pidfd naming it, where there is one (Linux).
    #[cfg(target_os = "linux")]
    fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>>;
}

/// `pid {pid}`, or what stands for an unknown one.
#[cfg(not(target_os = "macos"))]
pub(crate) fn named(pid: Option<u32>) -> String {
    match pid {
        Some(pid) => format!("pid {pid}"),
        None => "the spawned child (pid unknown)".to_string(),
    }
}

#[cfg(not(target_os = "macos"))]
#[cfg(not(target_os = "linux"))]
impl Unadopted for std::process::Child {
    fn pid(&self) -> Option<u32> {
        Some(std::process::Child::id(self))
    }
    fn kill(&mut self) -> std::io::Result<()> {
        std::process::Child::kill(self)
    }
    fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
        std::process::Child::try_wait(self)
    }
    fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
        std::process::Child::wait(self)
    }
}

/// A Linux child, by the pidfd it sent while it was held before `exec`. Kills and reaps through
/// the pidfd, never by pid.
#[cfg(target_os = "linux")]
struct PidfdChild {
    pid: Option<u32>,
    pidfd: std::os::fd::OwnedFd,
    /// Kept once reaped, as std keeps it: a later `try_wait` or `wait` answers it, not `ECHILD`.
    reaped: Option<std::process::ExitStatus>,
    /// Whether its kill delivered a signal (see [`Unadopted::kill_delivered`]).
    delivered: bool,
}

#[cfg(target_os = "linux")]
impl PidfdChild {
    fn new(pid: Option<u32>, pidfd: std::os::fd::OwnedFd) -> PidfdChild {
        PidfdChild {
            pid,
            pidfd,
            reaped: None,
            delivered: false,
        }
    }

    fn target(&self) -> crate::wait::exit_only::Target<'_> {
        use std::os::fd::AsFd;
        crate::wait::exit_only::Target::PidFd(self.pidfd.as_fd())
    }
}

#[cfg(target_os = "linux")]
impl Unadopted for PidfdChild {
    fn pid(&self) -> Option<u32> {
        self.pid
    }
    fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
        use std::os::fd::AsFd;
        Some(self.pidfd.as_fd())
    }
    fn kill(&mut self) -> std::io::Result<()> {
        use std::os::fd::AsFd;
        // A zombie takes the signal too, so an exited child is `Ok`, and so is one reaped elsewhere.
        // An unknown pid (a child tokio dropped) is named 0 in the helper's log.
        let sent = crate::signal::via_pidfd(
            Some(self.pidfd.as_fd()),
            self.pid.unwrap_or(0),
            crate::signal::Sig::Kill,
        )?;
        self.delivered = matches!(sent, crate::signal::Sent::Delivered);
        Ok(())
    }
    #[cfg(unix)]
    fn kill_delivered(&self) -> bool {
        self.delivered
    }
    fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
        use crate::wait::exit_only::{try_reap, Reap, Reaped};
        if self.reaped.is_some() {
            return Ok(self.reaped);
        }
        match try_reap(&self.target())? {
            Reap::Reaped(Reaped::Status(status)) => {
                self.reaped = Some(status);
                Ok(Some(status))
            }
            Reap::Reaped(Reaped::Unreadable { si_code }) => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("the child's exit record was unreadable (si_code {si_code})"),
            )),
            Reap::Running => Ok(None),
            Reap::Foreign(_) => Err(std::io::Error::from_raw_os_error(libc::ECHILD)),
        }
    }
    fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
        use crate::wait::exit_only::{reap_blocking, Reaped};
        if let Some(status) = self.reaped {
            return Ok(status);
        }
        match reap_blocking(&self.target())? {
            Ok(Reaped::Status(status)) => {
                self.reaped = Some(status);
                Ok(status)
            }
            Ok(Reaped::Unreadable { si_code }) => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("the child's exit record was unreadable (si_code {si_code})"),
            )),
            Err(_) => Err(std::io::Error::from_raw_os_error(libc::ECHILD)),
        }
    }
}

/// A sync spawn's Linux child before adoption: std's handle, and the pidfd it is torn down through.
#[cfg(target_os = "linux")]
struct HeldStdChild {
    child: std::process::Child,
    through: PidfdChild,
}

#[cfg(target_os = "linux")]
impl HeldStdChild {
    fn id(&self) -> u32 {
        self.child.id()
    }
}

#[cfg(target_os = "linux")]
impl Unadopted for HeldStdChild {
    fn pid(&self) -> Option<u32> {
        Some(self.child.id())
    }
    fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
        self.through.pidfd()
    }
    fn kill(&mut self) -> std::io::Result<()> {
        self.through.kill()
    }
    #[cfg(unix)]
    fn kill_delivered(&self) -> bool {
        self.through.kill_delivered()
    }
    fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
        self.through.try_wait()
    }
    fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
        self.through.wait()
    }
}

/// What a failed spawn's teardown did with its child, when that child is an elevation front (see
/// [`crate::elevation::front`]), which it never signals: a kill of it would orphan the program.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
    target_os = "macos",
    allow(
        dead_code,
        reason = "macOS leaves an unverified child without tearing it down, so it is never reaped here"
    )
)]
pub(crate) enum FrontFate {
    /// Not a front: torn down as any child.
    NotAFront,
    /// It had exited, or a cgroup leaf's kill ended it, and was reaped.
    Reaped,
    /// It was running, and is left unreaped (it stays a zombie once it exits).
    LeftUnreaped,
    /// It could not be waited on: reaped by someone else, or unreadable.
    Unaccounted,
    /// Where it is could not be read, so it is not known whether its cgroup's kill ended it. It is
    /// left unreaped.
    #[cfg_attr(
        not(target_os = "linux"),
        allow(dead_code, reason = "only a Linux cgroup leaf places a front")
    )]
    Unplaced,
}

impl FrontFate {
    /// The fate of a child left unverified (macOS: `leave_unverified_child`): one reaped by someone
    /// else is unaccounted for, and any other is left unreaped.
    #[cfg_attr(
        not(target_os = "macos"),
        allow(dead_code, reason = "only macOS leaves a child unverified")
    )]
    pub(crate) fn of_unverified(identity: crate::containment::RootIdentity) -> FrontFate {
        match identity {
            crate::containment::RootIdentity::Gone => FrontFate::Unaccounted,
            crate::containment::RootIdentity::Unknown => FrontFate::LeftUnreaped,
        }
    }

    /// A failed spawn's `error`, with what became of the front `pid` (unknown: `None`) noted, its
    /// variant and kind kept (see [`Error::with_note`]). Not a front's: `error` itself.
    pub(crate) fn note(self, error: Error, front: Option<crate::elevation::front::Front>, pid: Option<u32>) -> Error {
        let Some(front) = front else {
            return error;
        };
        let what = crate::elevation::front::describe(front, pid);
        let fate = match self {
            FrontFate::NotAFront => {
                debug_assert!(false, "a front's teardown reports its fate");
                return error;
            }
            FrontFate::Reaped => {
                "it was sent no signal of its own; it had exited, or its cgroup's kill ended it, and it was reaped"
            }
            FrontFate::LeftUnreaped => {
                "it was sent nothing, so the elevated program may be running; it is left unreaped"
            }
            FrontFate::Unaccounted => {
                "it was sent nothing and could not be waited on, so the elevated program may be running"
            }
            FrontFate::Unplaced => {
                "it was sent nothing, and where it is cannot be read, so the elevated program may be running; it \
                 is left unreaped"
            }
        };
        error.with_note(&format!("{what}; {fate}"))
    }
}

/// Settle `prepared`'s placement verdict in a failure arm after the fork, before the child is torn
/// down, so the teardown never races the verdict's reads.
pub(crate) fn settle_before_teardown(
    prepared: &mut crate::containment::Prepared,
    #[cfg(target_os = "linux")] child: crate::containment::ChildHandle<'_>,
    #[cfg(not(target_os = "linux"))] pid: u32,
) {
    prepared.settle_verdict(
        #[cfg(target_os = "linux")]
        child,
        #[cfg(not(target_os = "linux"))]
        pid,
    );
}

/// The subtree of the leaf of an elevation front, captured while the leaf exists: a failure arm
/// drops the leaf, killing it. One that cannot be read leaves the front unplaceable by the arm,
/// which then leaves it unreaped.
#[cfg(target_os = "linux")]
pub(crate) fn front_subtree(
    leaf: Option<&crate::containment::cgroup::CgroupLeaf>,
) -> Option<crate::containment::cgroup::Subtree> {
    match leaf?.subtree() {
        Ok(subtree) => Some(subtree),
        Err(e) => {
            log::debug!("spawn: an elevation front's leaf subtree cannot be read ({e}); its teardown cannot place it");
            None
        }
    }
}

/// [`teardown_unadopted`], unless `child` is an elevation front: a kill of that would orphan the
/// elevated program. A front is sent nothing. One that has exited is reaped now. One a cgroup kill
/// landed on and reached (see [`Subtree::reached`](crate::containment::cgroup::Subtree::reached)) is
/// dying: its exit, which that kill bounds, is waited for, and it is reaped. Any other is left
/// unreaped, with nothing that waits for it, and stays a zombie once it exits. The caller returns
/// its error with the front's fate noted ([`FrontFate::note`]).
#[cfg(not(target_os = "macos"))]
fn teardown_unadopted_or_front(
    mut child: impl Unadopted,
    front: Option<crate::elevation::front::Front>,
    id: Option<ProcessId>,
    #[cfg(target_os = "linux")] subtree: Option<&crate::containment::cgroup::Subtree>,
) -> (FrontFate, ChildFate) {
    if front.is_none() {
        return (FrontFate::NotAFront, teardown_unadopted(child, id));
    }
    // Dropping the handle afterwards closes it; it neither signals nor reaps the child.
    #[cfg(all(test, target_os = "linux"))]
    if fault::fronts_exit_before_teardown() {
        // The wait below ends only with the front, which only the leaf's kill brings about: that the
        // kill was written is checked first (and the record restarted for the next arm), so a
        // teardown that skipped it fails here instead of hanging.
        let steps = crate::containment::cgroup::fault::take_leaf_steps();
        crate::containment::cgroup::fault::record_leaf_steps();
        assert!(
            steps.iter().any(|s| s == "kill"),
            "the leaf's kill was written before the teardown waits for the front's exit: {steps:?}"
        );
        if let Some(pid) = child.pid() {
            crate::test_child::wait_until_zombie(pid);
        }
    }
    #[cfg(test)]
    let tried = if fault::fronts_seen_running() {
        Ok(None)
    } else {
        child.try_wait()
    };
    #[cfg(not(test))]
    let tried = child.try_wait();
    let fate = fate_of_a_look(tried.as_ref().map(|s| *s).map_err(std::io::Error::raw_os_error), id);
    match tried {
        Ok(Some(_)) => (FrontFate::Reaped, fate),
        Ok(None) => {
            #[cfg(target_os = "linux")]
            let mut unplaced = false;
            #[cfg(target_os = "linux")]
            if let (Some(subtree), Some(pid)) = (subtree, child.pid()) {
                match subtree.reached(pid, child.pidfd()) {
                    Ok(true) => {
                        #[cfg(test)]
                        fault::run_between_kill_and_wait();
                        return match child.wait() {
                            Ok(_status) => {
                                #[cfg(test)]
                                fault::record_teardown_reap(pid, _status);
                                (FrontFate::Reaped, ChildFate::Reaped)
                            }
                            Err(e) => {
                                log::warn!(
                                    "spawn teardown: elevation front {} could not be reaped ({e})",
                                    named(Some(pid))
                                );
                                (FrontFate::Unaccounted, ChildFate::Killed)
                            }
                        };
                    }
                    Ok(false) => {}
                    // Where it is cannot be read, so it is not known whether the kill ended it.
                    Err(e) => {
                        log::debug!(
                            "spawn teardown: elevation front {}'s cgroup cannot be read ({e})",
                            named(Some(pid))
                        );
                        unplaced = true;
                    }
                }
            }
            log::warn!(
                "spawn teardown left elevation front {} running, unsignalled and unreaped: a kill would orphan the \
                 elevated program",
                named(child.pid())
            );
            #[cfg(target_os = "linux")]
            if unplaced {
                return (FrontFate::Unplaced, ChildFate::Unknown);
            }
            (FrontFate::LeftUnreaped, fate)
        }
        // Reaped by someone else, or unreadable: nothing is signalled or waited on.
        Err(e) => {
            log::debug!(
                "spawn teardown: elevation front {} cannot be waited on ({e})",
                named(child.pid())
            );
            (FrontFate::Unaccounted, fate)
        }
    }
}

/// [`teardown_through_pidfd`] for an elevation front: sent nothing, reaped now only if it has
/// exited (see [`teardown_unadopted_or_front`]).
#[cfg(target_os = "linux")]
pub(crate) fn leave_front_through_pidfd(
    pid: Option<u32>,
    pidfd: std::os::fd::OwnedFd,
    front: crate::elevation::front::Front,
    id: Option<ProcessId>,
    subtree: Option<&crate::containment::cgroup::Subtree>,
) -> (FrontFate, ChildFate) {
    teardown_unadopted_or_front(PidfdChild::new(pid, pidfd), Some(front), id, subtree)
}

/// Kill and reap, through `pidfd`, the child of a spawn that failed after its fork, unless it is
/// already collected: std reaps the child of a spawn it fails; tokio can fail a spawn after std's
/// succeeded, and drops the child neither killed nor reaped.
/// `id` is the child's identity, if the spawn had read one.
#[cfg(target_os = "linux")]
pub(crate) fn teardown_through_pidfd(
    pid: Option<u32>,
    pidfd: std::os::fd::OwnedFd,
    id: Option<ProcessId>,
) -> ChildFate {
    use crate::wait::exit_only::{peek, Peek};

    let child = PidfdChild::new(pid, pidfd);
    match peek(&child.target()) {
        Ok(Peek::Foreign(why)) => {
            log::debug!("{}: already collected when its spawn failed", named(pid));
            return why.fate(false);
        }
        Ok(Peek::Exit(_) | Peek::Running) => {}
        // `waitid` on a pidfd of this process's own child answers or says `ECHILD`.
        Err(e) => {
            log::warn!(
                "{}: its spawn failed, and its pidfd could not be waited on ({e}); it is left as it is",
                named(pid)
            );
            debug_assert!(false, "waitid on a spawned child's pidfd failed: {e}");
            return ChildFate::Unknown;
        }
    }
    teardown_unadopted(child, id)
}

/// Kill and reap a spawned child that an error path is abandoning before adoption, logging a
/// failure of either at `warn` and `debug_assert`ing it.
///
/// A child that could not be killed is NOT waited for here: it may still be running — a setuid
/// child such as `sudo` refuses our SIGKILL with EPERM — and a blocking `wait()` would hang the
/// spawn for as long as it runs. If it has not exited, it is handed to [`reap_in_background`],
/// which reaps it whenever it does, so it never lingers as a zombie. EPERM is the one kill failure
/// that is not asserted, because it is reachable without any bug.
///
/// `id` is the child's identity, if the spawn had read one.
#[cfg(not(target_os = "macos"))]
fn teardown_unadopted(mut child: impl Unadopted, id: Option<ProcessId>) -> ChildFate {
    // warn before any assert: `debug_assert` is compiled out in release, and a swallowed failure
    // would otherwise leave no trace at all there.
    if let Err(kill) = kill_unadopted(&mut child) {
        log::warn!(
            "spawn teardown failed to kill {}: {kill}; reaping it in the background once it exits",
            named(child.pid())
        );
        let looked = child.try_wait();
        let fate = fate_of_a_look(looked.as_ref().map(|s| *s).map_err(std::io::Error::raw_os_error), id);
        if !matches!(looked, Ok(Some(_))) {
            reap_in_background(child);
        }
        // After the handoff, so a debug build's panic cannot strand the child.
        debug_assert!(
            kill.kind() == std::io::ErrorKind::PermissionDenied,
            "sync spawn teardown failed to kill child: {kill}"
        );
        return fate;
    }
    #[cfg(test)]
    fault::run_between_kill_and_wait();
    match reap_unadopted(&mut child) {
        Ok(_) => ChildFate::Reaped,
        // Reaped by someone else: a handled case, not a contract violation.
        #[cfg(unix)]
        Err(reap) if reap.raw_os_error() == Some(libc::ECHILD) => {
            log::debug!("spawn teardown: {} was reaped by someone else", named(child.pid()));
            // The kill went first: delivered, it is `Killed`; found nothing to signal, `Gone`.
            crate::wait::exit_only::Foreign::Gone.fate(child.kill_delivered())
        }
        Err(reap) => {
            log::warn!("spawn teardown failed to reap {}: {reap}", named(child.pid()));
            debug_assert!(false, "sync spawn teardown failed to reap child: {reap}");
            ChildFate::Killed
        }
    }
}

/// Reap `child` on a detached thread once it exits on its own. The thread blocks on the child's
/// exit, an event outside this process's control; nothing waits for the thread.
#[cfg(not(target_os = "macos"))]
fn reap_in_background(mut child: impl Unadopted) {
    #[cfg(test)]
    let notify = fault::take_background_reap_notifier();
    let name = child
        .pid()
        .map_or_else(|| "cosca-reap".to_string(), |pid| format!("cosca-reap-{pid}"));
    let pid = named(child.pid());
    let reaper_pid = pid.clone();
    let spawned = std::thread::Builder::new().name(name).spawn(move || {
        let pid = reaper_pid;
        let reaped = child.wait().map(drop);
        if let Err(e) = &reaped {
            log::warn!("background reap of {pid} failed: {e}");
        }
        #[cfg(test)]
        if let Some(notify) = notify {
            _ = notify.send(reaped);
        }
    });
    if let Err(e) = spawned {
        log::warn!("could not start a thread to reap {pid}, which stays unreaped: {e}");
    }
}

/// `child.kill()`, `Ok` for a child that has already exited on every platform, and forceable to
/// fail by a test.
///
/// std returns `Ok` for an exited child on Windows (`TerminateProcess`'s `ACCESS_DENIED` is
/// checked with `try_wait`) and, on Unix, for one it has already waited on. An exited child it has
/// NOT waited on is left to `kill(2)`, whose answer for a zombie std does not promise — so an
/// `Err` here is checked the same way Windows' is, and dropped if the child has exited. (Linux
/// signals through the pidfd, which takes the signal for a zombie too.)
///
/// A test can also make `kill` fail for a child that has really exited (see
/// `fault::set_force_kill_error_after_exit`).
///
/// The forced failure KILLS AND REAPS first, so the test that asks for it leaks nothing although
/// the teardown then skips its own reap — unless it was set to leave the child alive.
#[cfg(not(target_os = "macos"))]
fn kill_unadopted(child: &mut impl Unadopted) -> std::io::Result<()> {
    #[cfg(test)]
    if let Some((marker, kind, alive)) = fault::take_force_kill_failure() {
        if !alive {
            child.kill()?;
            child.wait()?;
        }
        return Err(std::io::Error::new(kind, marker));
    }
    #[cfg(test)]
    let killed = match fault::take_force_kill_error_after_exit() {
        Some((marker, kind)) => {
            child.wait()?;
            Err(std::io::Error::new(kind, marker))
        }
        None => child.kill(),
    };
    #[cfg(not(test))]
    let killed = child.kill();
    match killed {
        Err(_) if matches!(child.try_wait(), Ok(Some(_))) => Ok(()),
        other => other,
    }
}

/// `child.wait()`, which a test can force to fail. The forced failure still REAPS first, so the
/// test that asks for it leaks nothing.
#[cfg(not(target_os = "macos"))]
fn reap_unadopted(child: &mut impl Unadopted) -> std::io::Result<std::process::ExitStatus> {
    #[cfg(test)]
    let forced = fault::take_force_reap_failure();
    let status = child.wait()?;
    #[cfg(test)]
    // An unknown pid records as 0.
    fault::record_teardown_reap(child.pid().unwrap_or(0), status);
    #[cfg(test)]
    if let Some(marker) = forced {
        return Err(std::io::Error::other(marker));
    }
    Ok(status)
}

/// Test-only fault injection + assertions for the spawn error-teardown paths, shared by both spawns.
#[cfg(test)]
pub(crate) mod fault {
    use std::cell::Cell;

    use crate::identity::ProcessId;

    thread_local! {
        #[cfg(not(target_os = "macos"))]
        static FRONTS_SEEN_RUNNING: Cell<bool> = const { Cell::new(false) };
        #[cfg(target_os = "linux")]
        static FRONTS_EXIT_FIRST: Cell<bool> = const { Cell::new(false) };
    }

    /// While the guard lives, a failed spawn's teardown on this thread, and a leaf's abandonment,
    /// find every elevation front still running, as they find one its leaf's kill reached but that
    /// has not exited yet: in the kernel a task leaves its cgroup, which ends the leaf's drain,
    /// before its parent can collect it.
    #[cfg(target_os = "linux")]
    pub(crate) fn see_fronts_running() -> SeeFrontsRunning {
        FRONTS_SEEN_RUNNING.with(|f| f.set(true));
        SeeFrontsRunning(())
    }

    #[cfg(target_os = "linux")]
    #[must_use = "fronts are seen as they are again as soon as the guard is dropped"]
    pub(crate) struct SeeFrontsRunning(());

    #[cfg(target_os = "linux")]
    impl Drop for SeeFrontsRunning {
        fn drop(&mut self) {
            FRONTS_SEEN_RUNNING.with(|f| f.set(false));
        }
    }

    #[cfg(not(target_os = "macos"))]
    pub(crate) fn fronts_seen_running() -> bool {
        FRONTS_SEEN_RUNNING.with(Cell::get)
    }

    /// While the guard lives, a failed spawn's teardown on this thread waits, before it reads an
    /// elevation front, until the front has exited (a `WNOWAIT` wait: it stays a zombie), so the
    /// teardown's own read finds the zombie its leaf's kill made. For a test whose kill is known to
    /// land: one that does not blocks.
    #[cfg(target_os = "linux")]
    pub(crate) fn exit_fronts_before_teardown() -> ExitFrontsFirst {
        FRONTS_EXIT_FIRST.with(|f| f.set(true));
        ExitFrontsFirst(())
    }

    #[cfg(target_os = "linux")]
    #[must_use = "fronts are read as they are again as soon as the guard is dropped"]
    pub(crate) struct ExitFrontsFirst(());

    #[cfg(target_os = "linux")]
    impl Drop for ExitFrontsFirst {
        fn drop(&mut self) {
            FRONTS_EXIT_FIRST.with(|f| f.set(false));
        }
    }

    #[cfg(target_os = "linux")]
    pub(crate) fn fronts_exit_before_teardown() -> bool {
        FRONTS_EXIT_FIRST.with(Cell::get)
    }

    /// A seam's hook, run with the child's pid.
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    type PidHook = Box<dyn FnOnce(u32)>;

    thread_local! {
        static FORCE_VANISH: Cell<bool> = const { Cell::new(false) };
        static FORCE_UNKNOWN: Cell<bool> = const { Cell::new(false) };
        static FORCE_ATTACH_FAIL: Cell<bool> = const { Cell::new(false) };
        static FORCE_REAP_FAIL: Cell<Option<&'static str>> = const { Cell::new(None) };
        static FORCE_KILL_FAIL: Cell<Option<(&'static str, std::io::ErrorKind, bool)>> = const { Cell::new(None) };
        static FORCE_KILL_ERROR_AFTER_EXIT: Cell<Option<(&'static str, std::io::ErrorKind)>> = const { Cell::new(None) };
        static BACKGROUND_REAP_NOTIFY: Cell<Option<std::sync::mpsc::Sender<std::io::Result<()>>>> = const { Cell::new(None) };
        static CAPTURED: Cell<Option<crate::identity::Resolved<ProcessId>>> = const { Cell::new(None) };
        static BETWEEN_KILL_AND_WAIT: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
        static SPAWN_PID: Cell<Option<u32>> = const { Cell::new(None) };
        static BEFORE_IDENTITY: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
        static BEFORE_ATTACH: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
        static AFTER_IDENTITY_READ: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
        static TEARDOWN_REAPS: std::cell::RefCell<Option<Vec<TeardownReap>>> = const { std::cell::RefCell::new(None) };
        #[cfg(target_os = "linux")]
        static ATTACHMENT_OVERRIDE: std::cell::RefCell<Option<crate::containment::Attachment>> =
            const { std::cell::RefCell::new(None) };
        #[cfg(all(target_os = "linux", feature = "tokio"))]
        static FORCE_POST_FORK_FAIL: Cell<bool> = const { Cell::new(false) };
        #[cfg(feature = "tokio")]
        static FAIL_TOKIO_SPAWN: Cell<bool> = const { Cell::new(false) };
        #[cfg(all(target_os = "linux", feature = "tokio"))]
        static AFTER_FAILED_TOKIO_FORK: std::cell::RefCell<Option<PidHook>> = const { std::cell::RefCell::new(None) };
        #[cfg(feature = "tokio")]
        static FORGOTTEN_PID: Cell<Option<u32>> = const { Cell::new(None) };
        #[cfg(all(target_os = "linux", feature = "tokio"))]
        static FORGOTTEN_LEAF: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
        #[cfg(all(target_os = "linux", feature = "tokio"))]
        static FORGOTTEN_PIDFD: std::cell::RefCell<Option<std::os::fd::OwnedFd>> = const { std::cell::RefCell::new(None) };
    }

    /// Fail the NEXT tokio spawn after its fork succeeded, the way tokio's own `build_child` can
    /// (stdio registration, its pidfd reaper, its signal driver): the child is dropped neither
    /// killed nor reaped, and the error returns while `Prepared` — with any cgroup leaf — drops.
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    pub(crate) fn set_force_post_fork_failure(on: bool) {
        FORCE_POST_FORK_FAIL.with(|f| f.set(on));
    }

    /// The pid of the child the last forced post-fork failure dropped. It is still this
    /// process's unreaped child, so the caller may wait on it.
    #[cfg(feature = "tokio")]
    pub(crate) fn take_forgotten_pid() -> Option<u32> {
        FORGOTTEN_PID.with(|f| f.take())
    }

    /// A pidfd for the child the last forced post-fork failure dropped.
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    pub(crate) fn take_forgotten_pidfd() -> Option<std::os::fd::OwnedFd> {
        FORGOTTEN_PIDFD.with(|f| f.borrow_mut().take())
    }

    /// The cgroup leaf of the spawn the last forced post-fork failure dropped, if it had one.
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    pub(crate) fn take_forgotten_leaf() -> Option<std::path::PathBuf> {
        FORGOTTEN_LEAF.with(|f| f.take())
    }

    /// While the guard lives, tokio's own `spawn()` on this thread fails after its fork, dropping the
    /// child neither killed nor reaped, as a failed reaper registration (`epoll_ctl`'s `ENOSPC` or
    /// `ENOMEM`) does. The child's pid is kept for [`take_forgotten_pid`].
    #[cfg(feature = "tokio")]
    pub(crate) fn fail_tokio_spawns_after_fork() -> FailTokioSpawns {
        FAIL_TOKIO_SPAWN.with(|f| f.set(true));
        FailTokioSpawns(())
    }

    /// [`fail_tokio_spawns_after_fork`], running `hook` with the next forgotten child's pid as the
    /// spawn fails, before anything tears the child down.
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    pub(crate) fn fail_tokio_spawns_after_fork_then(hook: impl FnOnce(u32) + 'static) -> FailTokioSpawns {
        AFTER_FAILED_TOKIO_FORK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
        fail_tokio_spawns_after_fork()
    }

    #[cfg(feature = "tokio")]
    #[must_use = "spawns succeed again as soon as the guard is dropped"]
    pub(crate) struct FailTokioSpawns(());

    #[cfg(feature = "tokio")]
    impl Drop for FailTokioSpawns {
        fn drop(&mut self) {
            FAIL_TOKIO_SPAWN.with(|f| f.set(false));
            #[cfg(target_os = "linux")]
            AFTER_FAILED_TOKIO_FORK.with(|h| h.borrow_mut().take());
        }
    }

    /// While [`fail_tokio_spawns_after_fork`]'s guard lives, makes tokio's `spawn()` fail after its
    /// fork: the child is forgotten, and its pid, a pidfd on it and `leaf`, the cgroup leaf of the
    /// spawn, are kept for the `take_forgotten_*` readers. The spawn's own answer is what production
    /// gives a child tokio dropped.
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    pub(crate) fn fail_tokio_spawn_after_fork(
        spawned: std::io::Result<::tokio::process::Child>,
        leaf: Option<&std::path::Path>,
    ) -> std::io::Result<::tokio::process::Child> {
        if !FAIL_TOKIO_SPAWN.with(Cell::get) {
            return spawned;
        }
        FORGOTTEN_LEAF.with(|f| *f.borrow_mut() = leaf.map(std::path::Path::to_path_buf));
        let child = spawned?;
        if let (Some(hook), Some(pid)) = (AFTER_FAILED_TOKIO_FORK.with(|h| h.borrow_mut().take()), child.id()) {
            hook(pid);
        }
        forget_child(child);
        Err(std::io::Error::from_raw_os_error(libc::ENOSPC))
    }

    /// [`fail_tokio_spawns_after_fork`] for a platform without the pidfd handshake: tokio's `spawn()`
    /// fails after its fork, and the child is forgotten, neither killed nor reaped. Its pid is kept
    /// for [`take_forgotten_pid`].
    #[cfg(all(not(target_os = "linux"), feature = "tokio"))]
    pub(crate) fn fail_tokio_spawn_after_fork(
        spawned: std::io::Result<::tokio::process::Child>,
    ) -> std::io::Result<::tokio::process::Child> {
        if !FAIL_TOKIO_SPAWN.with(Cell::get) {
            return spawned;
        }
        let child = spawned?;
        FORGOTTEN_PID.with(|f| f.set(child.id()));
        std::mem::forget(child);
        Err(std::io::Error::other(
            "forced tokio spawn failure after the fork (test seam)",
        ))
    }

    /// Forgets `child`, neither killed nor reaped, keeping its pid and a pidfd on it.
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    fn forget_child(child: ::tokio::process::Child) -> u32 {
        FORGOTTEN_PID.with(|f| f.set(child.id()));
        // A handle on the child that cannot come to name another process, taken while tokio still
        // pins its pid, so a test can prove the child reaped without probing a freed pid.
        let pidfd = child
            .id()
            .and_then(|pid| rustix::process::Pid::from_raw(pid as i32))
            .and_then(|pid| rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).ok())
            // Above 2: a test may have 0, 1 or 2 closed across the spawn, and restore them.
            .and_then(|pidfd| rustix::io::fcntl_dupfd_cloexec(&pidfd, 3).ok());
        FORGOTTEN_PIDFD.with(|f| *f.borrow_mut() = pidfd);
        let pid = child.id().expect("an unreaped child has its pid");
        std::mem::forget(child);
        pid
    }

    /// Fails the NEXT tokio spawn on this thread after the handshake concluded, forgetting its child
    /// as [`fail_tokio_spawn_after_fork`] does. That answer is the seam's own, not production's: a
    /// test through it checks the leaf and the warnings, never the answer (use
    /// [`fail_tokio_spawns_after_fork`] for that).
    #[cfg(all(target_os = "linux", feature = "tokio"))]
    pub(crate) fn post_fork_failure(
        spawned: Result<::tokio::process::Child, super::SpawnFailure>,
        leaf: Option<&std::path::Path>,
    ) -> Result<::tokio::process::Child, super::SpawnFailure> {
        if !FORCE_POST_FORK_FAIL.with(|f| f.replace(false)) {
            return spawned;
        }
        FORGOTTEN_LEAF.with(|f| *f.borrow_mut() = leaf.map(std::path::Path::to_path_buf));
        let child = spawned?;
        let pid = forget_child(child);
        // Its pid names this spawn's failure, so a test can tell its log records from any other's.
        // It models tokio failing after std's spawn succeeded: after `exec`.
        Err(super::SpawnFailure::started(
            crate::error::Error::Io(std::io::Error::other(format!(
                "forced post-fork spawn failure (test seam) for child {pid}"
            ))),
            crate::error::ChildFate::Unknown,
        ))
    }

    pub(crate) fn set_force_identity_vanished(on: bool) {
        FORCE_VANISH.with(|f| f.set(on));
    }
    /// As [`set_force_identity_vanished`], but the identity read is refused (`Unknown`).
    #[cfg(unix)]
    pub(crate) fn set_force_identity_unknown(on: bool) {
        FORCE_UNKNOWN.with(|f| f.set(on));
    }
    pub(crate) fn force_identity_unknown() -> bool {
        FORCE_UNKNOWN.with(|f| f.get())
    }
    pub(crate) fn force_identity_vanished() -> bool {
        FORCE_VANISH.with(|f| f.get())
    }
    pub(crate) fn set_force_attach_failure(on: bool) {
        FORCE_ATTACH_FAIL.with(|f| f.set(on));
    }
    /// Hand the NEXT spawn on this thread `attachment` in place of the one `attach` would build,
    /// so a test can give a real child a leaf it shapes itself. TAKE semantics.
    #[cfg(target_os = "linux")]
    pub(crate) fn set_attachment_override(attachment: crate::containment::Attachment) {
        ATTACHMENT_OVERRIDE.with(|f| *f.borrow_mut() = Some(attachment));
    }

    #[cfg(target_os = "linux")]
    pub(crate) fn take_attachment_override() -> Option<crate::containment::Attachment> {
        ATTACHMENT_OVERRIDE.with(|f| f.borrow_mut().take())
    }

    pub(crate) fn force_attach_failure() -> bool {
        FORCE_ATTACH_FAIL.with(|f| f.get())
    }
    /// Make the next teardown reap on this thread fail with `marker` as its error. TAKE semantics:
    /// the teardown consumes it, and a test that set it asserts it was consumed, so it cannot
    /// outlive the spawn it was meant for.
    pub(crate) fn set_force_reap_failure(marker: &'static str) {
        FORCE_REAP_FAIL.with(|f| f.set(Some(marker)));
    }
    pub(crate) fn take_force_reap_failure() -> Option<&'static str> {
        FORCE_REAP_FAIL.with(|f| f.take())
    }
    /// Make the next teardown kill on this thread fail with an error of `kind` carrying `marker`,
    /// with the same TAKE semantics as [`set_force_reap_failure`].
    #[cfg(not(target_os = "macos"))]
    pub(crate) fn set_force_kill_failure(marker: &'static str, kind: std::io::ErrorKind) {
        FORCE_KILL_FAIL.with(|f| f.set(Some((marker, kind, false))));
    }
    /// As [`set_force_kill_failure`] with an `Other` error, but the child is NOT killed first: it
    /// is left running, as a child that refused the kill would be.
    #[cfg(not(target_os = "macos"))]
    pub(crate) fn set_force_kill_failure_leaving_child_alive(marker: &'static str) {
        set_force_kill_failure_leaving_child_alive_as(marker, std::io::ErrorKind::Other);
    }
    /// As [`set_force_kill_failure_leaving_child_alive`], failing with `kind`. Also consumed by the
    /// async spawn's teardown (`ProcSource::reap_now`).
    #[cfg(any(not(target_os = "macos"), feature = "tokio"))]
    pub(crate) fn set_force_kill_failure_leaving_child_alive_as(marker: &'static str, kind: std::io::ErrorKind) {
        FORCE_KILL_FAIL.with(|f| f.set(Some((marker, kind, true))));
    }
    /// Make the next teardown kill on this thread wait for its child to exit on its own, then fail
    /// with an error of `kind` carrying `marker`: an `Err` from `kill` for a child that is gone.
    #[cfg(not(target_os = "macos"))]
    pub(crate) fn set_force_kill_error_after_exit(marker: &'static str, kind: std::io::ErrorKind) {
        FORCE_KILL_ERROR_AFTER_EXIT.with(|f| f.set(Some((marker, kind))));
    }
    #[cfg(not(target_os = "macos"))]
    pub(crate) fn take_force_kill_error_after_exit() -> Option<(&'static str, std::io::ErrorKind)> {
        FORCE_KILL_ERROR_AFTER_EXIT.with(|f| f.take())
    }
    /// Have the next background reap started on this thread report its outcome on `notify`.
    #[cfg(not(target_os = "macos"))]
    pub(crate) fn set_background_reap_notifier(notify: std::sync::mpsc::Sender<std::io::Result<()>>) {
        BACKGROUND_REAP_NOTIFY.with(|f| f.set(Some(notify)));
    }
    #[cfg(not(target_os = "macos"))]
    pub(crate) fn take_background_reap_notifier() -> Option<std::sync::mpsc::Sender<std::io::Result<()>>> {
        BACKGROUND_REAP_NOTIFY.with(|f| f.take())
    }
    #[cfg(any(not(target_os = "macos"), feature = "tokio"))]
    pub(crate) fn take_force_kill_failure() -> Option<(&'static str, std::io::ErrorKind, bool)> {
        FORCE_KILL_FAIL.with(|f| f.take())
    }
    pub(crate) fn capture(id: crate::identity::Resolved<ProcessId>) {
        CAPTURED.with(|c| c.set(Some(id)));
    }
    pub(crate) fn take_captured() -> Option<crate::identity::Resolved<ProcessId>> {
        CAPTURED.with(|c| c.take())
    }

    /// Run `hook` at the next kill-then-blocking-wait teardown on this thread, once the kill has
    /// returned `Ok` and before the wait: `teardown_unadopted`, the sync `finish_elevated`, or the
    /// async `wait_and_reap`. A fixture that only that kill would end is released here, so a
    /// no-kill mutant fails an assertion on how the child died (see [`record_teardown_reaps`])
    /// instead of hanging the wait.
    pub(crate) fn set_between_kill_and_wait(hook: impl FnOnce() + 'static) -> ArmedBetweenKillAndWait {
        crate::oneshot_hook::arm(&BETWEEN_KILL_AND_WAIT, hook)
    }
    pub(crate) fn run_between_kill_and_wait() {
        crate::oneshot_hook::fire(&BETWEEN_KILL_AND_WAIT);
    }
    pub(crate) type ArmedBetweenKillAndWait = crate::oneshot_hook::Armed;

    /// A point in a spawn where a test can run a hook.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum SpawnPoint {
        /// Right before the spawn reads the child's identity (the tokio spawn's macOS unique id is
        /// read earlier, before the backend exists).
        BeforeIdentity,
        /// Right before the spawn attaches the containment.
        BeforeAttach,
        /// Right after the spawn read the child's identity, before it checks the read against the
        /// child's handle.
        AfterIdentityRead,
    }

    fn hook_at(point: SpawnPoint) -> &'static std::thread::LocalKey<crate::oneshot_hook::OneShotHook> {
        match point {
            SpawnPoint::BeforeIdentity => &BEFORE_IDENTITY,
            SpawnPoint::BeforeAttach => &BEFORE_ATTACH,
            SpawnPoint::AfterIdentityRead => &AFTER_IDENTITY_READ,
        }
    }

    /// Run `hook` once at the next `point` on this thread; the guard clears it on drop.
    #[cfg_attr(
        not(all(feature = "tokio", target_os = "linux")),
        allow(dead_code, reason = "only the Linux async spawn's tests arm a spawn point so far")
    )]
    pub(crate) fn set_at(point: SpawnPoint, hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
        crate::oneshot_hook::arm(hook_at(point), hook)
    }

    /// Fire the hook armed for `point`, if any. Called by both spawns with the child's pid, which
    /// the hook reads through [`spawn_pid`].
    pub(crate) fn run_at(point: SpawnPoint, pid: u32) {
        SPAWN_PID.with(|p| p.set(Some(pid)));
        crate::oneshot_hook::fire(hook_at(point));
        SPAWN_PID.with(|p| p.set(None));
    }

    /// The pid of the child the spawn that fired the running hook has just forked.
    #[cfg_attr(
        not(all(feature = "tokio", target_os = "linux")),
        allow(dead_code, reason = "only the Linux async spawn's tests arm a spawn point so far")
    )]
    pub(crate) fn spawn_pid() -> u32 {
        SPAWN_PID.with(Cell::get).expect("spawn_pid is read from a spawn hook")
    }

    /// A reaped teardown child's pid and exit status.
    type TeardownReap = (u32, std::process::ExitStatus);

    /// Record the pid and status of every child those three teardowns (see
    /// [`set_between_kill_and_wait`]) wait on for real on this thread until the returned guard
    /// drops. A failed wait records nothing.
    pub(crate) fn record_teardown_reaps() -> TeardownReaps {
        let previous = TEARDOWN_REAPS.with(|r| r.borrow_mut().replace(Vec::new()));
        debug_assert!(previous.is_none(), "teardown reaps are already being recorded");
        TeardownReaps
    }
    pub(crate) fn record_teardown_reap(pid: u32, status: std::process::ExitStatus) {
        TEARDOWN_REAPS.with(|r| {
            if let Some(reaps) = r.borrow_mut().as_mut() {
                reaps.push((pid, status));
            }
        });
    }
    /// Stops the [`record_teardown_reaps`] recording on drop.
    #[must_use]
    pub(crate) struct TeardownReaps;
    impl TeardownReaps {
        /// The `(pid, status)` of each reap recorded so far, oldest first.
        pub(crate) fn recorded(&self) -> Vec<TeardownReap> {
            TEARDOWN_REAPS.with(|r| r.borrow().clone().unwrap_or_default())
        }
    }
    impl Drop for TeardownReaps {
        fn drop(&mut self) {
            let reaps = TEARDOWN_REAPS.with(|r| r.borrow_mut().take());
            drop(reaps);
        }
    }

    /// A stdin for a child only a kill ends. Its writer is released between the code under test's
    /// kill and its blocking wait ([`set_between_kill_and_wait`]), so a no-kill mutant lets the
    /// child exit 0 and fails [`TeardownBlocker::assert_killed`] rather than hanging the wait. Keep
    /// the guard alive through the assertion: dropping it clears the hook and recorder.
    ///
    /// The child must exit 0 on stdin EOF: `cat` on Unix, `more.com` on Windows (whose `findstr x`
    /// exits 1, which is what a kill reports) with a null stdout, because `more` echoes. Use
    /// [`teardown_blocker_parts`] to get the whole child.
    pub(crate) fn teardown_blocker_stdin() -> (crate::stdio::Stdio, TeardownBlocker) {
        let (reader, writer) = std::io::pipe().expect("pipe");
        #[cfg(unix)]
        let reader = std::os::fd::OwnedFd::from(reader);
        #[cfg(windows)]
        let reader = std::os::windows::io::OwnedHandle::from(reader);
        let fired = std::rc::Rc::new(std::cell::Cell::new(false));
        let release = set_between_kill_and_wait({
            let fired = std::rc::Rc::clone(&fired);
            move || {
                drop(writer);
                fired.set(true);
            }
        });
        let reaps = record_teardown_reaps();
        (
            crate::stdio::Stdio::from_file(std::fs::File::from(reader)),
            TeardownBlocker {
                _release: release,
                #[cfg(any(not(target_os = "macos"), feature = "tokio"))]
                fired,
                reaps,
            },
        )
    }

    /// Everything a test needs to configure a [`teardown_blocker_stdin`] child on either
    /// `Command` type: apply `argv`, `stdin`, and `stdout` when it is `Some`.
    pub(crate) struct TeardownBlockerParts {
        pub(crate) argv: Vec<std::ffi::OsString>,
        pub(crate) stdin: crate::stdio::Stdio,
        pub(crate) stdout: Option<crate::stdio::Stdio>,
        pub(crate) guard: TeardownBlocker,
    }

    /// The argv and stdio of a [`teardown_blocker_stdin`] child, for the sync and async `Command`.
    pub(crate) fn teardown_blocker_parts() -> TeardownBlockerParts {
        let (stdin, guard) = teardown_blocker_stdin();
        #[cfg(unix)]
        let (argv, stdout) = (crate::test_child::BLOCKER_ARGV.iter().map(Into::into).collect(), None);
        #[cfg(windows)]
        let (argv, stdout) = (
            vec![crate::test_child::windows_more().into_os_string()],
            Some(crate::stdio::Stdio::null()),
        );
        TeardownBlockerParts {
            argv,
            stdin,
            stdout,
            guard,
        }
    }

    /// See [`teardown_blocker_stdin`].
    #[must_use]
    pub(crate) struct TeardownBlocker {
        _release: ArmedBetweenKillAndWait,
        #[cfg(any(not(target_os = "macos"), feature = "tokio"))]
        fired: std::rc::Rc<std::cell::Cell<bool>>,
        reaps: TeardownReaps,
    }
    impl TeardownBlocker {
        /// The `(pid, status)` of each reap the teardown recorded so far.
        #[cfg(unix)]
        pub(crate) fn recorded(&self) -> Vec<TeardownReap> {
            self.reaps.recorded()
        }

        /// The teardown's kill fired the release hook, and every child it reaped died of
        /// `SIGKILL` (Unix) or exit code 1 (Windows).
        #[cfg(any(not(target_os = "macos"), feature = "tokio"))]
        pub(crate) fn assert_killed(&self) {
            assert!(
                self.fired.get(),
                "the teardown must have reached its between-kill-and-wait hook"
            );
            let reaps = self.reaps.recorded();
            assert!(!reaps.is_empty(), "the teardown must have reaped the child");
            for (pid, status) in reaps {
                #[cfg(unix)]
                {
                    use std::os::unix::process::ExitStatusExt as _;
                    assert_eq!(
                        status.signal(),
                        Some(libc::SIGKILL),
                        "pid {pid} must be SIGKILLed by its teardown kill, not merely reaped once it exits on its own: {status:?}"
                    );
                }
                #[cfg(windows)]
                assert_eq!(
                    status.code(),
                    Some(1),
                    "pid {pid} must be terminated by its teardown kill (`TerminateProcess` exits 1), not merely reaped once it exits on its own"
                );
            }
        }
    }

    /// Assert the spawned child was fully torn down — reuse-immune, via the child's stable identity
    /// (pid + start token). On Unix a not-yet-reaped zombie keeps that identity (Linux /proc
    /// persists; macOS `sysctl KERN_PROC` resolves zombies) → caught on ALL Unix; a reaped pid
    /// resolves to `None` or a *different* identity → passes, so a
    /// recycled pid never false-fails. Windows has no zombies, and its process-object cleanup is not
    /// synchronous with `wait()`, so there we assert only that the child is dead (`!is_alive()`, also
    /// reuse-immune via the start token).
    #[cfg(any(not(target_os = "macos"), feature = "tokio"))]
    pub(crate) fn assert_child_reaped(captured: crate::identity::Resolved<ProcessId>) {
        let crate::identity::Resolved::Found(captured) = captured else {
            panic!("the seam must capture a resolved identity, got {captured:?}");
        };
        #[cfg(unix)]
        match ProcessId::of(captured.pid()) {
            crate::identity::Resolved::Found(id) => assert_ne!(
                id, captured,
                "a failed spawn must fully reap its child (no lingering zombie at its identity)"
            ),
            crate::identity::Resolved::Gone => {}
            // NOT a panic: once the child is reaped its pid is free host-wide, so a recycle
            // between the failed `/proc` read and the `kill(pid, 0)` probe legitimately
            // yields Unknown. What matters is only that the pid no longer resolves to OUR
            // identity, and an unreadable stranger is not our child either.
            crate::identity::Resolved::Unknown => {}
        }
        #[cfg(windows)]
        assert_eq!(
            captured.is_alive(),
            crate::identity::Liveness::Dead,
            "a failed spawn must leave the child dead"
        );
    }
}

// The `.bat`/`.cmd` refusal every backend runs before it spawns.
#[path = "spawn/batch_gate.rs"]
mod batch_gate;
pub(crate) use batch_gate::reject_batch_path;

// cosca-owned fd-mapping pre_exec (replaces `command-fds` — see the module docs).
#[cfg(unix)]
#[path = "spawn/fd_map.rs"]
pub(crate) mod fd_map;

// The `pre_exec` fd-channel primitive of `pidfd_handshake` and, on macOS, `unique_report`.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[path = "spawn/fd_channel.rs"]
pub(crate) mod fd_channel;

// A failed spawn's answer to whether the program could have started.
#[path = "spawn/failure.rs"]
pub(crate) mod failure;

// Linux: holds a forked child before `exec` until the parent has its pidfd.
#[cfg(target_os = "linux")]
#[path = "spawn/pidfd_handshake.rs"]
pub(crate) mod pidfd_handshake;

// Windows raw `CreateProcessW` spawn backend.
#[cfg(windows)]
#[path = "spawn/windows_raw.rs"]
pub(crate) mod windows_raw;

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

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/placement_reuse_tests.rs"]
mod placement_reuse_tests;

#[cfg(test)]
#[path = "spawn/spawn_lock_tests.rs"]
mod spawn_lock_tests;

#[cfg(all(test, unix))]
#[path = "spawn/exact_posix_tests.rs"]
mod exact_posix_tests;

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/identity_error_tests.rs"]
mod identity_error_tests;

#[cfg(all(test, target_os = "macos"))]
#[path = "spawn/identity_macos_tests.rs"]
pub(crate) mod identity_macos_tests;

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/identity_peek_tests.rs"]
mod identity_peek_tests;

#[cfg(target_os = "macos")]
#[path = "spawn/unique_report.rs"]
pub(crate) mod unique_report;

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/front_teardown_tests.rs"]
mod front_teardown_tests;