cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
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
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
// Unit tests for dispatch root-detection and mechanism-selection logic.
// These test pure functions directly — no process-env mutation required.

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

/// The pid a gone root's outcome names.
const ROOT_PID: u32 = 4242;

/// A tree walk's mechanism, which answers the members an earlier kill left (the root it walks from
/// is never walked here).
fn walker() -> crate::containment::mechanism::Mechanism {
    crate::containment::mechanism::Mechanism::Walk(crate::containment::treewalk::Walker::new(
        crate::identity::ProcessId::current(),
    ))
}

/// A mechanism that is not a walk, which holds nothing an earlier kill left.
fn non_walk() -> crate::containment::mechanism::Mechanism {
    let (fake, _) = crate::containment::fake::FakeContains::new(crate::containment::Containment::ProcessGroup, false);
    crate::containment::mechanism::Mechanism::Fake(fake)
}

/// A kill that skipped `action`, with the sweep of its marker holders, if it made one, ended as
/// `holders`.
fn skipped_kill(action: &str, holders: Option<Result<(), crate::error::Error>>) -> super::TreeKillOutcome {
    super::TreeKillOutcome::Skipped(crate::containment::Skip {
        action: action.into(),
        why: crate::containment::skip::Why::MayNameAnother(crate::containment::root::Refusal::ReapedElsewhere(1), None),
        root_alone: false,
        holders,
    })
}

/// Three OS codes that name three different failures on this platform.
const CODES: [i32; 3] = if cfg!(windows) { [5, 2, 3] } else { [13, 2, 1] };

/// The member `pid` that a kill left because of the OS error `code`.
fn left_by(pid: u32, code: i32) -> crate::error::Error {
    crate::error::Error::MemberNotKilled {
        pid,
        source: crate::error::Error::io_cause(std::io::Error::from_raw_os_error(code)),
    }
}

/// The `(pid, OS code)` of each member of a `MembersLeft`.
fn members_of(error: &crate::error::Error) -> Vec<(u32, Option<i32>)> {
    let crate::error::Error::MembersLeft { members, .. } = error else {
        panic!("expected MembersLeft, got {error:?}");
    };
    members
        .iter()
        .map(|member| {
            let crate::error::Error::MemberNotKilled { pid, .. } = &**member else {
                panic!("a member of a MembersLeft is a MemberNotKilled: {member:?}");
            };
            (*pid, crate::error::first_os_code(&**member))
        })
        .collect()
}

/// The failures of a `MembersLeft` that name no member.
fn unwalked_of(error: &crate::error::Error) -> Option<&crate::error::Error> {
    let crate::error::Error::MembersLeft { others, .. } = error else {
        panic!("expected MembersLeft, got {error:?}");
    };
    others.as_deref()
}

/// What a tree kill left once the root had its say is one `MembersLeft` of every member, in the order
/// the walk found them and the root last, each with its own cause. Mutants: only the first member is
/// kept; a member's cause is put in a text; the root is listed first.
#[skuld::test]
fn what_a_kill_left_is_one_members_left_of_every_member_with_its_cause() {
    use super::Unkilled;
    let [a, b, c] = CODES;
    let unkilled = || Unkilled {
        members: vec![left_by(2, a), left_by(3, b)],
        root: Some(Box::new(left_by(1, c))),
        resolved: Vec::new(),
    };

    let left = unkilled().unsettled(false).expect_err("members were left");
    assert_eq!(members_of(&left), [(2, Some(a)), (3, Some(b)), (1, Some(c))]);
    assert_eq!(crate::error::first_os_code(&left), Some(a), "the first member's code");

    let left = unkilled().unsettled(true).expect_err("members were left");
    assert_eq!(
        members_of(&left),
        [(2, Some(a)), (3, Some(b))],
        "a root that ended is not left"
    );
}

/// A kill that left one member is a `MembersLeft` of one, and the answer of a mechanism that is no
/// walk (one error that names no member) is that error as it is.
#[skuld::test]
fn one_member_is_a_members_left_and_one_error_that_is_no_member_stays_as_it_is() {
    use super::Unkilled;
    use crate::error::Error;
    let left = Unkilled::from(left_by(2, CODES[0])).unsettled(false).expect_err("left");
    assert_eq!(members_of(&left), [(2, Some(CODES[0]))]);
    assert!(unwalked_of(&left).is_none());

    let refused = Unkilled::from(Error::Containment {
        detail: "a member refused".into(),
        source: None,
    })
    .unsettled(false)
    .expect_err("left");
    assert!(matches!(refused, Error::Containment { .. }), "{refused:?}");
}

/// The error of a walk that was not made, after an earlier kill left members, is the `others` of
/// the `MembersLeft`, no member of it.
#[skuld::test]
fn the_error_of_a_walk_not_made_is_unwalked_after_earlier_members() {
    use super::Unkilled;
    use crate::error::Error;
    let unkilled = Unkilled {
        members: vec![
            left_by(2, CODES[0]),
            Error::Unassessable {
                detail: "the snapshot failed".into(),
                source: None,
            },
        ],
        root: None,
        resolved: Vec::new(),
    };

    let left = unkilled.unsettled(false).expect_err("left");

    assert_eq!(members_of(&left), [(2, Some(CODES[0]))]);
    assert!(
        matches!(unwalked_of(&left), Some(crate::error::Error::Unassessable { detail, .. }) if detail == "the snapshot failed"),
        "{left:?}"
    );
}

/// Two errors that name no member are both kept, whether or not members were left: the `others` of
/// the `MembersLeft` is a `Several` of them, and with no member the answer is that `Several`.
///
/// Mutant: a later error overwrites the earlier one.
#[skuld::test]
fn two_errors_that_name_no_member_are_both_kept() {
    use super::Unkilled;
    use crate::error::Error;
    let unnamed = |detail: &str| Error::Unassessable {
        detail: detail.into(),
        source: None,
    };
    let details = |error: &Error| {
        let Error::Several(list) = error else {
            panic!("expected Several, got {error:?}");
        };
        list.iter()
            .map(|e| match &**e {
                Error::Unassessable { detail, .. } => detail.clone(),
                other => panic!("{other:?}"),
            })
            .collect::<Vec<_>>()
    };

    let with_members = Unkilled {
        members: vec![left_by(2, CODES[0]), unnamed("first"), unnamed("second")],
        root: None,
        resolved: Vec::new(),
    }
    .unsettled(false)
    .expect_err("left");
    assert_eq!(members_of(&with_members), [(2, Some(CODES[0]))]);
    assert_eq!(
        details(unwalked_of(&with_members).expect("both kept")),
        ["first", "second"]
    );

    let alone = Unkilled {
        members: vec![unnamed("first"), unnamed("second")],
        root: None,
        resolved: Vec::new(),
    }
    .unsettled(false)
    .expect_err("left");
    // No member: the first is the answer in its own variant, the second its peer below it.
    let Error::Unassessable { detail, source } = &alone else {
        panic!("expected the first error's own variant, got {alone:?}");
    };
    assert_eq!(detail, "first");
    let Some(Error::Unassessable { detail: peer, .. }) = source.as_deref() else {
        panic!("expected the second error below the first, got {source:?}");
    };
    assert_eq!(peer, "second");
}

/// A call's error holds every member left, so none is warned of by itself: a member is reported once.
/// The pids are this row's own, as the capture is shared by parallel rows.
#[skuld::test]
fn a_kill_that_left_several_members_warns_of_none_of_them_by_itself() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let killed = TreeKilled::default();

    let left = killed
        .settle_for_kill_tree(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![left_by(71_001, CODES[0]), left_by(71_002, CODES[1])],
                root: None,
                resolved: Vec::new(),
            })),
            false,
            super::Keeping::Nothing,
        )
        .answer
        .expect_err("members were left");

    assert_eq!(members_of(&left).len(), 2);
    assert_eq!(
        crate::log_capture::records_since(mark, "pid 7100"),
        Vec::<String>::new()
    );
}

/// Without the marker the process is the root (not nested).
#[skuld::test]
fn is_nested_without_marker_is_false() {
    assert!(!is_nested(false));
}

/// With the marker the process is already inside a contained tree (nested).
#[skuld::test]
fn is_nested_with_marker_is_true() {
    assert!(is_nested(true));
}

/// A unix spawn gives its child the nesting marker exactly when it is contained, a root (the inherited
/// environment has no marker) and marks.
///
/// Mutants: an uncontained spawn marks; a nested spawn marks; an opaque request marks.
#[cfg(unix)]
#[skuld::test]
fn a_unix_child_gets_the_marker_when_contained_root_and_marking() {
    use crate::containment::{marks_child_environment, ContainMode, ContainRequest, Nesting};

    let request = |mode, nesting| ContainRequest { mode, nesting };
    let contained = Some(ContainMode::Session);
    assert!(marks_child_environment(&request(contained, Nesting::Mark), false));
    assert!(!marks_child_environment(&request(None, Nesting::Mark), false));
    assert!(!marks_child_environment(&request(contained, Nesting::Mark), true));
    assert!(!marks_child_environment(&request(contained, Nesting::Opaque), false));
}

// unix_setup_for mutual-exclusivity tests (S3) =====

/// `ContainMode::Session` must select `UnixSetup::Session` (setsid) — never
/// `ProcessGroup`. This is the critical S3 invariant: calling both setsid AND
/// setpgid/process_group(0) on the same Command would cause EPERM.
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_session_selects_setsid() {
    use super::{unix_setup_for, UnixSetup};
    use crate::containment::ContainMode;
    assert_eq!(unix_setup_for(Some(ContainMode::Session)), UnixSetup::Session);
}

/// `ContainMode::Strongest` must select `UnixSetup::ProcessGroup` — never Session.
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_strongest_selects_process_group() {
    use super::{unix_setup_for, UnixSetup};
    use crate::containment::ContainMode;
    assert_eq!(unix_setup_for(Some(ContainMode::Strongest)), UnixSetup::ProcessGroup);
}

/// `ContainMode::TreeWalk` must select `UnixSetup::None` — NO pre-spawn process
/// group. TreeWalk exists to catch children that escape a process group via
/// `setsid`/`setpgid`, so the root must not be put in a group; teardown is by
/// identity at kill time.
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_treewalk_selects_none() {
    use super::{unix_setup_for, UnixSetup};
    use crate::containment::ContainMode;
    assert_eq!(unix_setup_for(Some(ContainMode::TreeWalk)), UnixSetup::None);
}

/// Uncontained (`None` mode) must select `UnixSetup::ProcessGroup` (the
/// prepare path gates on `mode.is_some()` before calling this, but the
/// default fallback is well-defined).
#[cfg(unix)]
#[skuld::test]
fn unix_setup_for_none_mode_selects_process_group() {
    use super::{unix_setup_for, UnixSetup};
    assert_eq!(unix_setup_for(None), UnixSetup::ProcessGroup);
}

// Tree actionability + nested delegation =====

#[skuld::test]
fn a_tree_is_actionable() {
    use crate::containment::{Mechanism, Tree};
    // No teardown mechanism -> not actionable (the _tree guard rejects these).
    assert!(Tree::none().require_contained().is_err()); // uncontained / lone
    assert!(Tree::delegated().require_contained().is_err());
    // Every real mechanism is actionable. Cheap variants are built inline; Cgroup/JobObject
    // need an OS handle, so a test-only constructor builds one (asserted on its own platform).
    let walk = Mechanism::Walk(crate::containment::treewalk::Walker::new(
        crate::identity::ProcessId::current(),
    ));
    assert!(Tree::contained(walk).require_contained().is_ok());
    #[cfg(unix)]
    assert!(
        Tree::contained(Mechanism::Group(crate::containment::unix::Group::process_group(0)))
            .require_contained()
            .is_ok()
    );
    #[cfg(target_os = "linux")]
    assert!(Tree::contained(Mechanism::Cgroup(
        crate::containment::cgroup::CgroupLeaf::placeholder_for_test()
    ))
    .require_contained()
    .is_ok());
    #[cfg(windows)]
    assert!(Tree::contained(Mechanism::Job(
        crate::containment::windows::JobHandle::create_empty_for_test()
    ))
    .require_contained()
    .is_ok());
}

/// macOS: a root launchd holds (`Unpinned`), or one its handle cannot answer for, skips what names
/// the tree by the root's pid: a tree walk walks nothing, and a marker sweeps its holders alone, the
/// root excepted when it is not pinned. A root its handle shows unreaped is killed as usual.
#[cfg(target_os = "macos")]
#[skuld::test]
fn an_untrusted_root_skips_the_walk_and_leaves_a_marker_its_holders() {
    use std::os::unix::process::ExitStatusExt as _;

    use super::TreeKillOutcome;
    use crate::containment::treewalk::Walker;
    use crate::containment::{Mechanism, TerminateOutcome, Tree, Why};
    use crate::signal::RootState;
    use crate::test_support::stated_root::StatedRoot;

    // Held for the body: the marker's write end is open in this process between its install and
    // the holder's exec, and a fork landing there would inherit it.
    let _serialize = crate::child::spawn::spawn_lock();

    let walk = || Tree::contained(Mechanism::Walk(Walker::new(crate::identity::ProcessId::current())));
    let rooted = |state: fn() -> RootState| StatedRoot::with_state(1234, state);
    let unpinned = || rooted(|| RootState::Unpinned);
    let unknown = || rooted(|| RootState::Unknown(std::sync::Arc::new(std::io::Error::other("a failed peek"))));
    for (name, root) in [("unpinned", unpinned()), ("unknown", unknown())] {
        let killed = walk().kill(Some(&root)).outcome();
        assert!(
            matches!(&killed, TreeKillOutcome::Skipped(skip) if matches!(skip.why, Why::Untrusted { .. }) && skip.holders.is_none()),
            "{name}: {killed:?}"
        );
        let (termed, _) = walk().terminate(1234, Some(&root), None);
        assert!(matches!(termed, TerminateOutcome::End(_)), "{name}: {termed:?}");
    }

    // A marker whose only holder is a live child: this process holding the write end would be its
    // own holder, which a sweep refuses. Each call is signalled once, so each gets a fresh holder.
    let held = || {
        let mut cmd = crate::test_child::member_command(0);
        let prepared = crate::containment::fdmarker::fdmarker_tests::install_on(&mut cmd, &[]).expect("install");
        #[allow(
            clippy::disallowed_methods,
            reason = "the test holds spawn_lock for its whole body via `_serialize`"
        )]
        let mut holder = cmd.spawn().expect("spawn the holder");
        drop(cmd);
        crate::test_child::await_member_ready(&mut holder);
        let root_id = crate::containment::fdmarker::fdmarker_tests::inert_root();
        let marker = Tree::contained(Mechanism::Marker(crate::containment::fdmarker::Marker::new(
            prepared,
            root_id,
            Some(1234),
        )));
        (marker, holder)
    };
    for (name, root) in [("unpinned", unpinned()), ("unknown", unknown())] {
        let (marker, mut holder) = held();
        let killed = marker.kill(Some(&root)).outcome();
        assert!(
            matches!(&killed, TreeKillOutcome::Skipped(skip) if matches!(skip.why, Why::Untrusted { .. }) && matches!(skip.holders, Some(Ok(())))),
            "{name}: {killed:?}"
        );
        // A signal ended it, not the stdin's EOF at `wait`, which exits `sh` 1 with none.
        let status = holder.wait().expect("reap the holder");
        assert_eq!(status.signal(), Some(libc::SIGKILL), "{name}: {status:?}");

        let (marker, mut holder) = held();
        let (termed, _) = marker.terminate(1234, Some(&root), None);
        assert!(
            matches!(
                termed,
                TerminateOutcome::Sent {
                    result: Ok(()),
                    earlier: Some("the SIGTERM"),
                    ..
                }
            ),
            "{name}: {termed:?}"
        );
        let status = holder.wait().expect("reap the holder");
        assert_eq!(status.signal(), Some(libc::SIGTERM), "{name}: {status:?}");
    }
}

/// Drives the real `attach()` nested arms (not a hand-built variant): a nested
/// (`!is_root`) contained spawn must yield BOTH halves of the delegated pair —
/// `Containment::Delegated` and `Tree::Delegated` — for a kernel mechanism
/// (Strongest) and TreeWalk, so `containment()` predicts the `_tree` error.
#[skuld::test]
fn nested_attach_is_delegated() {
    use super::{attach, Prepared};
    use crate::containment::{ContainMode, Containment};

    fn spawn_trivial() -> std::process::Child {
        // attach()'s nested arms don't touch the child, so an exited child is fine. Held for
        // the fork itself: a fork landing while a `fdmarker_tests.rs` test's marker write end
        // is transiently open would inherit it into this not-yet-`exec`'d process, and a
        // concurrent sweep could then find and SIGKILL it.
        #[cfg(unix)]
        return crate::test_spawn::spawn(&mut std::process::Command::new("true")).expect("spawn true");
        #[cfg(windows)]
        return crate::test_spawn::spawn(std::process::Command::new("cmd").args(["/C", "exit"])).expect("spawn cmd");
    }

    for mode in [ContainMode::Strongest, ContainMode::TreeWalk] {
        let mut child = spawn_trivial();
        let prepared = Prepared {
            mode: Some(mode),
            is_root: false, // nested member
            #[cfg(target_os = "linux")]
            cgroup_leaf: None,
            #[cfg(target_os = "macos")]
            marker: None,
            #[cfg(windows)]
            graceful: crate::containment::windows::mechanism_from_flags(crate::containment::windows::group_flags()),
            #[cfg(windows)]
            frozen: false,
        };
        #[cfg(windows)]
        let proc_handle = {
            use std::os::windows::io::AsRawHandle;
            child.as_raw_handle()
        };
        let crate::identity::Resolved::Found(id) = crate::identity::ProcessId::of(child.id()) else {
            panic!("the helper child must be readable");
        };
        let attachment = attach(
            #[cfg(unix)]
            child.id(),
            Ok(id),
            #[cfg(target_os = "linux")]
            crate::containment::cgroup::test_support::handle_of(
                child.id(),
                &crate::containment::cgroup::test_support::pidfd_of(child.id()),
            ),
            #[cfg(windows)]
            proc_handle,
            prepared,
        )
        .expect("attach nested");
        let tree = attachment.tree;
        // Reap before asserting: `tree` is owned and independent of `child`, so a
        // failing assertion must not leak the helper (the nested arms don't touch it).
        _ = child.kill();
        _ = child.wait();
        assert_eq!(
            tree.containment(),
            Containment::Delegated,
            "nested member ({mode:?}) must report Containment::Delegated, got {:?}",
            tree.containment()
        );
    }
}

// kill_tree handle-backstop (treewalk / macOS fd-marker fault seam) =====

// A long-lived TreeWalk-contained child; no descendants, so with the root identity-kill
// seam-disabled the ONLY killer is kill_tree's handle backstop. Armed AFTER the fallible
// spawn so a spawn panic cannot leak the flag.
//
// On macOS, `ContainMode::TreeWalk` still attaches `Containment::FdMarker` (decision 2: the
// marker installs for every contained root regardless of requested mode) — its `sweep` calls
// `treewalk::kill_by_identity` directly, never `treewalk::hard_kill`, so `treewalk::fault`'s
// seam is never consumed there; `fdmarker::fault` provides the matching seam instead.
#[skuld::test]
fn sync_kill_tree_backstop_is_load_bearing() {
    #[cfg(not(target_os = "macos"))]
    use super::super::treewalk::fault;
    #[cfg(target_os = "macos")]
    use crate::containment::fdmarker::fault;
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    #[cfg(windows)]
    cmd.stdout(crate::Stdio::null()).expect("set stdout null");
    cmd.contain_with(crate::ContainMode::TreeWalk);
    let mut child = cmd.spawn().expect("spawn");
    // Closed right after the kill: a no-op backstop exits 0.
    let stdin = child.stdin().expect("piped stdin");
    fault::set_force_root_kill_noop(true);
    let result = child.kill_tree();
    assert!(
        !fault::armed(),
        "seam not consumed — hard_kill did not run on the arming thread"
    );
    result.expect("kill_tree via backstop");
    drop(stdin);
    let status = child.wait().expect("reap");
    assert!(
        !status.success(),
        "the handle backstop must be what killed the root, got {status:?}"
    );
}

#[cfg(feature = "tokio")]
#[skuld::test]
async fn async_kill_tree_backstop_is_load_bearing() {
    #[cfg(not(target_os = "macos"))]
    use super::super::treewalk::fault;
    #[cfg(target_os = "macos")]
    use crate::containment::fdmarker::fault;
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    #[cfg(windows)]
    cmd.stdout(crate::Stdio::null()).expect("set stdout null");
    cmd.contain_with(crate::ContainMode::TreeWalk);
    let mut child = cmd.spawn().await.expect("spawn");
    // Closed right after the kill: a no-op backstop exits 0.
    let stdin = child.stdin().expect("piped stdin");
    fault::set_force_root_kill_noop(true);
    let result = child.kill_tree().await;
    assert!(
        !fault::armed(),
        "seam not consumed — hard_kill did not run on the arming thread"
    );
    result.expect("kill_tree via backstop");
    drop(stdin);
    let status = child.wait().await.expect("reap");
    assert!(
        !status.success(),
        "the handle backstop must be what killed the root, got {status:?}"
    );
}

/// A `TreeWalk` walk that killed what it could and left a member is not a refusal to walk: the
/// handle backstop still runs and kills the root. A walk that left only the root is settled by that
/// backstop (`Ok`, the tree marked killed); one that left a descendant is still the error naming it.
/// (macOS `TreeWalk` mode is an fd marker, which has no such walk. The fault seam is Unix's; the
/// settling code is shared.)
/// Mutants: the incomplete walk's error is taken for a refusal to walk, so `kill_tree` returns it
/// without the backstop; the backstop's kill of the root does not settle a walk that left only the
/// root; it settles a walk that left a descendant.
#[cfg(all(unix, not(target_os = "macos")))]
#[skuld::test]
fn sync_kill_tree_after_an_incomplete_walk_still_runs_the_handle_backstop() {
    use super::super::treewalk::fault::{self, LeftBehind};
    for left in [LeftBehind::Root, LeftBehind::Descendant, LeftBehind::RootAndDescendant] {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(["cat"]);
        cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
        cmd.contain_with(crate::ContainMode::TreeWalk);
        let mut child = cmd.spawn().expect("spawn");
        // Closed right after the kill: a no-op backstop exits 0.
        let stdin = child.stdin().expect("piped stdin");
        fault::set_force_root_kill_noop(true);
        fault::force_incomplete_once(left);
        let result = child.kill_tree();
        match left {
            LeftBehind::Root => result.expect("only the root was left, and the backstop killed it"),
            LeftBehind::Descendant | LeftBehind::RootAndDescendant => {
                let err = result.expect_err("a descendant was left");
                assert!(matches!(err, crate::error::Error::MembersLeft { .. }), "{err:?}");
            }
        }
        drop(stdin);
        let status = child.wait().expect("reap");
        assert!(
            !status.success(),
            "{left:?}: the handle backstop must be what killed the root, got {status:?}"
        );
    }
}

#[cfg(all(unix, not(target_os = "macos"), feature = "tokio"))]
#[skuld::test]
async fn async_kill_tree_after_an_incomplete_walk_still_runs_the_handle_backstop() {
    use super::super::treewalk::fault::{self, LeftBehind};
    for left in [LeftBehind::Root, LeftBehind::Descendant, LeftBehind::RootAndDescendant] {
        let mut cmd = crate::test_child::tokio_command(Console::Hidden);
        cmd.args(["cat"]);
        cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
        cmd.contain_with(crate::ContainMode::TreeWalk);
        let mut child = cmd.spawn().await.expect("spawn");
        // Closed right after the kill: a no-op backstop exits 0.
        let stdin = child.stdin().expect("piped stdin");
        fault::set_force_root_kill_noop(true);
        fault::force_incomplete_once(left);
        let result = child.kill_tree().await;
        match left {
            LeftBehind::Root => result.expect("only the root was left, and the backstop killed it"),
            LeftBehind::Descendant | LeftBehind::RootAndDescendant => {
                let err = result.expect_err("a descendant was left");
                assert!(matches!(err, crate::error::Error::MembersLeft { .. }), "{err:?}");
            }
        }
        drop(stdin);
        let status = child.wait().await.expect("reap");
        assert!(
            !status.success(),
            "{left:?}: the handle backstop must be what killed the root, got {status:?}"
        );
    }
}

// What a tree kill comes to =====

/// `settle` over every kind of outcome, with and without a member or the root left, and with the
/// root not running or not: what it answers, and whether it marks the tree killed. A kill that did not
/// run marks nothing and answers with what its sweep by identity left.
///
/// A walk that saw the root running vouches for nothing, whatever ended the root afterwards (it may
/// have forked first), but the answer follows the root's end.
///
/// Mutants: a skipped kill marks; a skip drops its sweep's error; the root is dropped from the report
/// whatever the root's end; the root is kept when the root is not running; a root the backstop ended
/// marks the tree killed.
#[skuld::test]
fn settle_answers_and_marks_by_what_ran_what_was_left_and_the_root_s_end() {
    use super::{SettleOutcome, TreeKillOutcome, TreeKilled, Unkilled, UnvouchedKind};
    use crate::error::Error;
    let left = |pid| Error::MemberNotKilled {
        pid,
        source: std::sync::Arc::new(crate::error::Error::Unassessable {
            detail: "refused".into(),
            source: None,
        }),
    };
    let unkilled = |members: &[u32], root: Option<u32>| Unkilled {
        members: members.iter().map(|pid| left(*pid)).collect(),
        root: root.map(|pid| Box::new(left(pid))),
        resolved: Vec::new(),
    };
    let skipped = |holders| skipped_kill("walk", holders);

    // (outcome, root_ended, answer: Ok(outcome) or Err((first, others)), marked)
    type Answer = Result<SettleOutcome, (u32, Vec<u32>)>;
    let table: Vec<(TreeKillOutcome, bool, Answer, bool)> = vec![
        (TreeKillOutcome::Ran(Ok(())), false, Ok(SettleOutcome::Killed), true),
        (
            skipped(Some(Ok(()))),
            true,
            Ok(SettleOutcome::Skipped { over_killed: false }),
            false,
        ),
        (
            skipped(None),
            true,
            Ok(SettleOutcome::Skipped { over_killed: false }),
            false,
        ),
        (skipped(Some(Err(left(7)))), true, Err((7, vec![])), false),
        (
            TreeKillOutcome::Answered(Ok(())),
            false,
            Ok(SettleOutcome::Killed),
            true,
        ),
        (
            TreeKillOutcome::Ran(Err(unkilled(&[], Some(1)))),
            false,
            Err((1, vec![])),
            false,
        ),
        (
            TreeKillOutcome::Ran(Err(unkilled(&[], Some(1)))),
            true,
            Ok(SettleOutcome::Unvouched {
                kind: UnvouchedKind::RootSeenRunning,
            }),
            false,
        ),
        (
            TreeKillOutcome::Ran(Err(unkilled(&[2, 3], None))),
            true,
            Err((2, vec![3])),
            false,
        ),
        (
            TreeKillOutcome::Ran(Err(unkilled(&[2], Some(1)))),
            true,
            Err((2, vec![])),
            false,
        ),
        (
            TreeKillOutcome::Ran(Err(unkilled(&[2], Some(1)))),
            false,
            Err((2, vec![1])),
            false,
        ),
    ];
    for (outcome, root_ended, want, marked) in table {
        let label = format!("{outcome:?}, root_ended {root_ended}");
        let killed = TreeKilled::default();

        let got = killed.settle(Some(&walker()), outcome, root_ended);

        let got = got.answer.map_err(|left| {
            let pids: Vec<u32> = members_of(&left).iter().map(|(pid, _)| *pid).collect();
            (pids[0], pids[1..].to_vec())
        });
        assert_eq!(got, want, "{label}");
        assert_eq!(killed.is_set(), marked, "{label}");
    }
}

/// A walk that was not made, or found no root, killed nothing: `settle` answers it with an error
/// (`Unassessable`; the snapshot's error as it was) and marks nothing, for a reader of any kind.
///
/// Mutants: either is answered `Ok`; either marks the tree killed.
#[skuld::test]
fn settle_answers_a_walk_that_was_not_made_with_an_error_and_marks_nothing() {
    use super::{TreeKillOutcome, TreeKilled};
    use crate::error::Error;
    for outcome in [TreeKillOutcome::NoRoot(ROOT_PID, None), unwalked()] {
        let label = format!("{outcome:?}");
        let killed = TreeKilled::default();

        let left = killed
            .settle(Some(&walker()), outcome, true)
            .answer
            .expect_err("nothing was killed, whatever became of the root");

        assert!(matches!(left, Error::Unassessable { .. }), "{label}: {left}");
        assert!(!killed.is_set(), "{label}");
    }
}

/// A root that is gone leaves nothing to walk once this handle has killed the tree: a later kill or
/// drop that finds no root is settled, not an error. Mutant: it is `Unassessable` whatever the mark
/// says (the drop after a `kill_tree` and a `wait` then warns, on Windows).
#[skuld::test]
fn settle_answers_a_gone_root_as_killed_once_the_handle_killed_the_tree() {
    use super::{SettleOutcome, TreeKillOutcome, TreeKilled};
    let killed = TreeKilled::default();
    killed
        .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), false)
        .answer
        .expect("the tree is killed");

    let later = killed
        .settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, None), false)
        .answer
        .expect("the tree was killed already");

    assert_eq!(later, SettleOutcome::Killed);
}

// The tree's settlement: every state, every outcome =====

/// Where a tree's settlement stands: never settled, killed, left these members (their pids, in
/// order) over a tree never vouched for, or unvouched, with the kind it stores (and the members held
/// over it, if any).
#[derive(Debug, PartialEq)]
enum Standing {
    Never,
    Killed,
    Left(Vec<u32>),
    HeldOnUnvouched(Vec<u32>, super::UnvouchedKind),
    Unvouched(super::UnvouchedKind),
}

/// The state of `killed`.
fn standing(killed: &super::TreeKilled) -> Standing {
    standing_of(&killed.lock())
}

/// `state`, as a `Standing`.
fn standing_of(state: &super::TreeState) -> Standing {
    use super::Vouching;
    let pids: Vec<u32> = state.held.iter().map(crate::containment::treewalk::Left::pid).collect();
    match (state.vouching, pids.is_empty()) {
        (Vouching::Never, true) => Standing::Never,
        (Vouching::Never, false) => Standing::Left(pids),
        (Vouching::Killed, empty) => {
            assert!(empty, "a killed tree holds no member");
            Standing::Killed
        }
        (Vouching::Unvouched(kind), true) => Standing::Unvouched(kind),
        (Vouching::Unvouched(kind), false) => Standing::HeldOnUnvouched(pids, kind),
    }
}

/// `next` over every state and every combination of facts that can occur: a walk or not, members left
/// with identities or none, something left running or not, the root seen running or not. A member
/// left with an identity is something left running; the root seen running is a walk's fact. The
/// state it answers is whole, the kind included: the latest fact names the kind (the root seen
/// running, then held members all gone, then something else left with no identity), and a settlement
/// with no new fact keeps the stored one.
///
/// Mutants: a fact that walked nothing vouches; a member seen running leaves a state as it was
/// (`Never` included: it means only that nothing has settled the tree); held members outlive their
/// own end; an unvouched tree keeps its kind over a newer fact (a root seen running over
/// `HeldMembersGone` or `Earlier`, with members left or none); a kind changes without a fact (a skipped kill, a gone root or a walk not made
/// over a stored kind); members left or gone over an unvouched tree lose its kind; a killed tree
/// stays vouched over members seen running.
#[skuld::test]
fn next_is_the_one_transition_of_state_and_facts() {
    use super::{TreeState, UnvouchedKind, Vouching};
    use crate::containment::treewalk::Left;
    let unread = |pid| Left::Unread {
        pid,
        source: std::sync::Arc::new(crate::error::Error::Unassessable {
            detail: "its identity could not be read".into(),
            source: None,
        }),
    };
    let prev_names = [
        "Never",
        "Killed",
        "Left(7)",
        "Unvouched(HeldMembersGone)",
        "Unvouched(RootSeenRunning)",
        "Unvouched(Earlier)",
        "Unvouched(Earlier) with 7 held",
    ];
    let prev_at = |at: usize| match at {
        0 => TreeState::new(Vouching::Never, vec![]),
        1 => TreeState::new(Vouching::Killed, vec![]),
        2 => TreeState::new(Vouching::Never, vec![unread(7)]),
        3 => TreeState::new(Vouching::Unvouched(UnvouchedKind::HeldMembersGone), vec![]),
        4 => TreeState::new(Vouching::Unvouched(UnvouchedKind::RootSeenRunning), vec![]),
        5 => TreeState::new(Vouching::Unvouched(UnvouchedKind::Earlier), vec![]),
        _ => TreeState::new(Vouching::Unvouched(UnvouchedKind::Earlier), vec![unread(7)]),
    };
    // (label, walked, left_now, running, root_seen_running, next from each state of `prev_names`)
    type Row = (&'static str, bool, Vec<Left>, bool, bool, [Standing; 7]);
    let killed = || Standing::Killed;
    let left_8 = || Standing::Left(vec![8]);
    let held = || Standing::Unvouched(UnvouchedKind::HeldMembersGone);
    let root = || Standing::Unvouched(UnvouchedKind::RootSeenRunning);
    let earlier = || Standing::Unvouched(UnvouchedKind::Earlier);
    let on = |kind| Standing::HeldOnUnvouched(vec![8], kind);
    #[rustfmt::skip]
    let facts: Vec<Row> = vec![
        ("walk, nothing left", true, vec![], false, false,
            [killed(), killed(), killed(), killed(), killed(), killed(), killed()]),
        ("walk, something running with no identity", true, vec![], true, false,
            [earlier(), earlier(), earlier(), earlier(), earlier(), earlier(), earlier()]),
        ("walk, the root seen running", true, vec![], true, true,
            [root(), root(), root(), root(), root(), root(), root()]),
        ("no walk, nothing left (skipped kill, gone root, walk not made)", false, vec![], false, false,
            [Standing::Never, killed(), held(), held(), root(), earlier(), earlier()]),
        ("no walk, something running with no identity", false, vec![], true, false,
            [earlier(), earlier(), earlier(), earlier(), earlier(), earlier(), earlier()]),
        ("walk, member 8 left", true, vec![unread(8)], true, false,
            [left_8(), left_8(), left_8(), on(UnvouchedKind::HeldMembersGone), on(UnvouchedKind::RootSeenRunning),
             on(UnvouchedKind::Earlier), on(UnvouchedKind::Earlier)]),
        ("walk, member 8 left and the root seen running", true, vec![unread(8)], true, true,
            [left_8(), left_8(), left_8(), on(UnvouchedKind::RootSeenRunning), on(UnvouchedKind::RootSeenRunning),
             on(UnvouchedKind::RootSeenRunning), on(UnvouchedKind::RootSeenRunning)]),
        ("no walk, member 8 left", false, vec![unread(8)], true, false,
            [left_8(), left_8(), left_8(), on(UnvouchedKind::HeldMembersGone), on(UnvouchedKind::RootSeenRunning),
             on(UnvouchedKind::Earlier), on(UnvouchedKind::Earlier)]),
    ];
    for (label, walked, left_now, running, root_seen_running, wants) in facts {
        for (at, want) in wants.into_iter().enumerate() {
            let got = super::next(
                &prev_at(at),
                walked,
                left_now.clone(),
                running,
                root_seen_running,
                false,
            );

            assert_eq!(standing_of(&got), want, "{} x {label}", prev_names[at]);
        }
    }
    // A walk that killed all it found and could not read the root's exit flag: unvouched from any state,
    // with the kind it names, nothing held.
    for (at, name) in prev_names.iter().enumerate() {
        let got = super::next(&prev_at(at), true, vec![], false, false, true);
        assert_eq!(
            standing_of(&got),
            Standing::Unvouched(UnvouchedKind::ExitUnread),
            "{name} x the exit flag unread"
        );
    }
}

/// The five outcomes of the table, fresh.
fn table_outcomes() -> [(&'static str, super::TreeKillOutcome); 5] {
    use super::{TreeKillOutcome, Unkilled};
    [
        ("Ran(Ok)", TreeKillOutcome::Ran(Ok(()))),
        (
            "Ran(Err member 8)",
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![member_left(8)],
                root: None,
                resolved: Vec::new(),
            })),
        ),
        ("NoRoot", TreeKillOutcome::NoRoot(ROOT_PID, None)),
        ("Unwalked", unwalked()),
        ("Skipped", skipped_kill("walk the process table", None)),
    ]
}

/// A walk that could not be made.
fn unwalked() -> super::TreeKillOutcome {
    super::TreeKillOutcome::Unwalked(crate::error::Error::Unassessable {
        detail: "the snapshot failed".into(),
        source: None,
    })
}

/// A tree whose walk left the member `pid` (its identity read when `resolved`).
fn tree_left_with(pid: u32, resolved: Vec<crate::identity::ProcessId>) -> super::TreeKilled {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    let killed = TreeKilled::default();
    killed
        .settle(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![member_left(pid)],
                root: None,
                resolved,
            })),
            true,
        )
        .answer
        .expect_err("a member was left");
    killed
}

/// What a `settle` answers, and the state it leaves.
type Want = (Result<super::SettleOutcome, Vec<String>>, Standing);

/// What a table row runs once it has settled, given the row's name and the members its settlement
/// killed again, before anything lets a held member go.
type AfterRow = Box<dyn FnOnce(&str, &[crate::identity::ProcessId])>;

/// Each outcome of the table settled over a tree that `enter` makes fresh: the answer (the
/// errors' names, first to last) and the state left, against the row of `rows`. `enter` returns the
/// tree, the pid it holds (or 0), and what to run once the row has settled.
fn check_table(state: &str, rows: impl Fn(u32) -> [Want; 5], enter: impl Fn() -> (super::TreeKilled, u32, AfterRow)) {
    use crate::error::Error;
    let name = |error: &Error| match error {
        Error::MemberNotKilled { pid, .. } => format!("pid {pid}"),
        Error::Unassessable { .. } => "unassessable".to_owned(),
        other => panic!("unexpected error {other:?}"),
    };
    for (at, (outcome_name, outcome)) in table_outcomes().into_iter().enumerate() {
        let (killed, pid, after) = enter();
        let (want_answer, want_standing) = rows(pid).into_iter().nth(at).expect("a row per outcome");

        let super::Settled { answer, killed_again } = killed.settle(Some(&walker()), outcome, true);
        let got = answer.map_err(|left| left.left_members().into_iter().map(name).collect::<Vec<_>>());

        assert_eq!(got, want_answer, "{state} x {outcome_name}: answer");
        assert_eq!(standing(&killed), want_standing, "{state} x {outcome_name}: next state");
        after(&format!("{state} x {outcome_name}"), &killed_again);
    }
}

/// A row that expects its settlement to have killed `member` again: fails here, before the member is
/// released, when `killed_again` does not hold it. The kill then sent nothing: a member still running
/// means cosca classified a live member as gone (a product defect), one that exited 0 means it ended
/// before the kill.
fn assert_kill_accepted(row: &str, member: &crate::Child, killed_again: &[crate::identity::ProcessId]) {
    let id = member.id().expect(crate::test_child::IDENTITY_READ);
    if !killed_again.contains(&id) {
        let look = member.try_wait();
        panic!(
            "{row}: the settlement sent no kill to the member {id:?} (killed_again {killed_again:?}); a look at it \
             without waiting: {look:?}. Running: cosca classified a live member as gone. Exited 0: the member ended \
             before the kill."
        );
    }
}

/// Releases a member whose kill `assert_kill_accepted` saw accepted, and reaps it. An accepted kill
/// fixes the exit status, so an exit that is not a kill contradicts that.
fn reap_accepted_kill(row: &str, member: crate::Child, stdin: crate::PipeWriter) {
    drop(stdin);
    crate::test_child::assert_killed(
        &format!("{row}: the member, whose kill was accepted (killed_again holds it)"),
        member.wait().expect("reap the member"),
    );
}

fn gone() -> Vec<String> {
    vec!["unassessable".to_owned()]
}

/// A tree that holds the member `pid`, which no outcome shows killed: every answer starts with it, a
/// gone root adds nothing of its own, and the tree stays left.
fn holding_rows(pid: u32) -> [Want; 5] {
    let held = format!("pid {pid}");
    let two = vec![held.clone(), "pid 8".to_owned()];
    let walk_not_made = vec![held.clone(), "unassessable".to_owned()];
    [
        (Err(vec![held.clone()]), Standing::Left(vec![pid])),
        (Err(two), Standing::Left(vec![pid, 8])),
        (Err(vec![held.clone()]), Standing::Left(vec![pid])),
        (Err(walk_not_made), Standing::Left(vec![pid])),
        (Err(vec![held]), Standing::Left(vec![pid])),
    ]
}

/// `settle` over a tree no walk has settled, one that is killed, and one left an unread member: what
/// each outcome answers, and the state it leaves. The held member is answered first; a gone root adds
/// no error of its own once a walk covered the tree; a member seen running moves a killed tree to
/// left; the state is one value, so no row can be killed and holding at once.
///
/// Mutants: a gone root over a covered tree adds its own error; a tree stays killed while it holds a
/// member; an outcome skips the held member.
#[skuld::test]
fn settle_answers_each_outcome_over_a_tree_never_settled_killed_or_left_an_unread_member() {
    use super::{
        SettleOutcome::{Killed, Skipped},
        TreeKillOutcome, TreeKilled,
    };
    let nothing = || -> AfterRow { Box::new(|_, _| {}) };

    check_table(
        "never settled",
        |_| {
            [
                (Ok(Killed), Standing::Killed),
                (Err(vec!["pid 8".to_owned()]), Standing::Left(vec![8])),
                (Err(gone()), Standing::Never),
                (Err(gone()), Standing::Never),
                (Ok(Skipped { over_killed: false }), Standing::Never),
            ]
        },
        || (TreeKilled::default(), 0, nothing()),
    );
    check_table(
        "killed",
        |_| {
            [
                (Ok(Killed), Standing::Killed),
                (Err(vec!["pid 8".to_owned()]), Standing::Left(vec![8])),
                (Ok(Killed), Standing::Killed),
                (Err(gone()), Standing::Killed),
                (Ok(Skipped { over_killed: true }), Standing::Killed),
            ]
        },
        || {
            let killed = TreeKilled::default();
            killed
                .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
                .answer
                .expect("a complete kill");
            (killed, 0, nothing())
        },
    );
    check_table("left, unread", holding_rows, || {
        (tree_left_with(7, Vec::new()), 7, nothing())
    });
}

/// A member whose kill by identity succeeds is gone after any outcome: each row asserts that
/// `killed_again` holds the member before it is released, then that its exit is a kill. But only an
/// outcome that walked shows the tree killed: the member ran on after its kill was refused and may
/// have forked, and killing it again does not reach its children. A gone root, a walk not made and a
/// skipped kill each walked nothing, so the answer is the outcome's own (a gone root says the tree
/// could not be walked) and the state is unvouched. Mutants: as the table above; a held member is
/// not killed by an outcome that did not run (`killed_again` lacks it); an outcome that walked
/// nothing settles the tree as killed or as never settled.
#[skuld::test]
fn settle_answers_each_outcome_over_a_tree_left_a_member_that_can_be_killed() {
    use super::{
        SettleOutcome::{Killed, Unvouched},
        UnvouchedKind,
    };
    check_table(
        "left, killable",
        |_| {
            [
                (Ok(Killed), Standing::Killed),
                (Err(vec!["pid 8".to_owned()]), Standing::Left(vec![8])),
                (Err(gone()), Standing::Unvouched(UnvouchedKind::HeldMembersGone)),
                (Err(gone()), Standing::Unvouched(UnvouchedKind::HeldMembersGone)),
                (
                    Ok(Unvouched {
                        kind: UnvouchedKind::HeldMembersGone,
                    }),
                    Standing::Unvouched(UnvouchedKind::HeldMembersGone),
                ),
            ]
        },
        || {
            let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
            let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
            let killed = tree_left_with(id.pid(), vec![id]);
            let after: AfterRow = Box::new(move |row, killed_again| {
                assert_kill_accepted(row, &blocker, killed_again);
                reap_accepted_kill(row, blocker, stdin);
            });
            (killed, id.pid(), after)
        },
    );
}

/// A tree whose walk left a member that a gone root's settlement then killed again: unvouched. The
/// returned closure reaps the member, which is held by `stdin` until then.
fn unvouched_tree() -> (super::TreeKilled, Box<dyn FnOnce()>) {
    use super::TreeKillOutcome;
    let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
    let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
    let killed = tree_left_with(id.pid(), vec![id]);
    let super::Settled { answer, killed_again } =
        killed.settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, None), true);
    answer.expect_err("a gone root walked nothing");
    assert_kill_accepted("the unvouched tree's gone-root settlement", &blocker, &killed_again);
    assert_eq!(
        standing(&killed),
        Standing::Unvouched(super::UnvouchedKind::HeldMembersGone)
    );
    let after: Box<dyn FnOnce()> = Box::new(move || {
        reap_accepted_kill("the unvouched tree's gone-root settlement", blocker, stdin);
    });
    (killed, after)
}

/// A tree whose last kill left its root running and no member to hold: unvouched as
/// `RootSeenRunning`.
fn tree_that_saw_the_root_running() -> super::TreeKilled {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    let killed = TreeKilled::default();
    killed
        .settle(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: Vec::new(),
                root: Some(Box::new(member_left(1))),
                resolved: Vec::new(),
            })),
            false,
        )
        .answer
        .expect_err("the root is left");
    assert_eq!(
        standing(&killed),
        Standing::Unvouched(super::UnvouchedKind::RootSeenRunning)
    );
    killed
}

/// A tree whose every member a walk left is gone, and no walk since has vouched for it, is
/// unvouched: only a walk that leaves nothing settles it as killed, a member seen running leaves it
/// holding that member, and any other outcome leaves it unvouched, a gone root answering with the
/// honest error each time. Mutants: an outcome that walked nothing settles it as killed or as never
/// settled; a walk that left nothing does not settle it as killed.
#[skuld::test]
fn settle_answers_each_outcome_over_an_unvouched_tree() {
    use super::{
        SettleOutcome::{Killed, Unvouched},
        UnvouchedKind,
    };
    check_table(
        "unvouched",
        |_| {
            [
                (Ok(Killed), Standing::Killed),
                (
                    Err(vec!["pid 8".to_owned()]),
                    Standing::HeldOnUnvouched(vec![8], UnvouchedKind::HeldMembersGone),
                ),
                (Err(gone()), Standing::Unvouched(UnvouchedKind::HeldMembersGone)),
                (Err(gone()), Standing::Unvouched(UnvouchedKind::HeldMembersGone)),
                (
                    Ok(Unvouched {
                        kind: UnvouchedKind::HeldMembersGone,
                    }),
                    Standing::Unvouched(UnvouchedKind::HeldMembersGone),
                ),
            ]
        },
        || {
            let (killed, reap) = unvouched_tree();
            let after: AfterRow = Box::new(move |_, _| reap());
            (killed, 0, after)
        },
    );
}

/// A member whose kill by identity is refused stays left after any outcome. A setuid-root helper
/// refuses the kill of its caller.
#[cfg(unix)]
#[skuld::test]
fn settle_answers_each_outcome_over_a_tree_left_a_member_that_refuses_the_kill(
    #[fixture(setuid)] _group: &crate::test_groups::Group,
) {
    check_table("left, refusing", holding_rows, || {
        let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
        let id = child.id().expect(crate::test_child::IDENTITY_READ);
        let killed = tree_left_with(id.pid(), vec![id]);
        let after: AfterRow = Box::new(move |_, _| {
            // The helper exits at EOF: nothing killed it.
            drop(stdin);
            assert!(child.wait().expect("the helper exits on EOF").success());
        });
        (killed, id.pid(), after)
    });
}

/// A handle that is not a `TreeWalk` holds no members, so a kill that runs and leaves a member leaves
/// the tree unvouched (a kill happened, and the member seen running may have forked), whether the tree
/// was killed or never settled. Mutants: the tree stays killed; it stays or goes to never settled,
/// after which a gone root would say nothing was killed.
#[skuld::test]
fn a_kill_that_leaves_a_member_after_a_killed_tree_of_a_handle_that_is_not_a_walk_unvouches_it() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled, UnvouchedKind};
    let killed = TreeKilled::default();
    killed
        .settle(Some(&non_walk()), TreeKillOutcome::Ran(Ok(())), true)
        .answer
        .expect("a complete kill");
    assert_eq!(standing(&killed), Standing::Killed);

    let left = killed
        .settle(
            Some(&non_walk()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![member_left(8)],
                root: None,
                resolved: Vec::new(),
            })),
            true,
        )
        .answer
        .expect_err("a member was left");

    assert_eq!(pid_left(first_left(&left)), 8);
    assert_eq!(standing(&killed), Standing::Unvouched(UnvouchedKind::Earlier));

    // The same for a skipped kill whose sweep of the holders left a member.
    killed
        .settle(Some(&non_walk()), TreeKillOutcome::Ran(Ok(())), true)
        .answer
        .expect("a complete kill");
    assert_eq!(standing(&killed), Standing::Killed);
    let skipped_with_a_member = || skipped_kill("walk", Some(Err(member_left(9))));
    killed
        .settle(Some(&non_walk()), skipped_with_a_member(), true)
        .answer
        .expect_err("a member was left");
    assert_eq!(standing(&killed), Standing::Unvouched(UnvouchedKind::Earlier));

    // Over a tree never settled, the sweep that left the member unvouches it too; a tree that is none
    // or delegated has no mechanism to ask.
    let never = TreeKilled::default();
    never
        .settle(None, skipped_with_a_member(), true)
        .answer
        .expect_err("a member was left");
    assert_eq!(standing(&never), Standing::Unvouched(UnvouchedKind::Earlier));
}

/// Only a tree walk leaves the root alone, so a kill that leaves it over a handle that is not a walk
/// asserts in debug.
///
/// Mutant: the default `kill_left` hands a root left back without the assertion.
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "only a tree walk leaves the root alone"))]
fn a_root_left_over_a_handle_that_is_not_a_walk_asserts() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    _ = TreeKilled::default().settle(
        Some(&non_walk()),
        TreeKillOutcome::Ran(Err(Unkilled {
            members: Vec::new(),
            root: Some(Box::new(member_left(8))),
            resolved: Vec::new(),
        })),
        false,
    );
}

// What a `TreeWalk` handle remembers of the members a kill left =====

/// A `MemberNotKilled` for `pid`, as a walk reports a member it left.
fn member_left(pid: u32) -> crate::error::Error {
    crate::error::Error::MemberNotKilled {
        pid,
        source: std::sync::Arc::new(crate::error::Error::Unassessable {
            detail: "its identity could not be read".into(),
            source: None,
        }),
    }
}

/// The first member a settlement's answer holds ([`Error::left_members`](crate::error::Error::left_members)).
fn first_left(error: &crate::error::Error) -> &crate::error::Error {
    error.left_members()[0]
}

/// The pid a `MemberNotKilled` names.
fn pid_left(error: &crate::error::Error) -> u32 {
    match error {
        crate::error::Error::MemberNotKilled { pid, .. } => *pid,
        other => panic!("expected MemberNotKilled, got {other:?}"),
    }
}

/// A member whose identity was never read stays left: a later kill whose walk finds nothing does not
/// settle the tree as killed, but answers with the same member and marks nothing. Once a later kill
/// names it itself, it is not repeated.
///
/// Mutants: a later walk that finds less settles the tree as killed; the member is forgotten after
/// one report; the member is reported twice when the walk names it again.
#[skuld::test]
fn a_member_whose_identity_was_never_read_is_reported_again_until_a_kill_shows_it_killed() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    let killed = TreeKilled::default();
    let left = |pids: &[u32]| {
        TreeKillOutcome::Ran(Err(Unkilled {
            members: pids.iter().copied().map(member_left).collect(),
            root: None,
            resolved: Vec::new(),
        }))
    };

    let first = killed
        .settle(Some(&walker()), left(&[7]), true)
        .answer
        .expect_err("a member was left");
    assert_eq!(pid_left(first_left(&first)), 7);

    let later = killed
        .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
        .answer
        .expect_err("a walk that finds nothing does not show the member killed");
    assert_eq!(later.left_members().into_iter().map(pid_left).collect::<Vec<_>>(), [7]);
    assert!(!killed.is_set());

    let named_again = killed
        .settle(Some(&walker()), left(&[7, 8]), true)
        .answer
        .expect_err("two members are left");
    assert_eq!(
        named_again.left_members().into_iter().map(pid_left).collect::<Vec<_>>(),
        [7, 8]
    );
}

/// Whatever the next kill found, a held member is answered first: a gone root, a walk that could not
/// be made and a skipped kill each leave it reported, and none marks the tree. Mutant: the held
/// members are retried only when the new kill ran.
#[skuld::test]
fn a_held_member_is_answered_first_whatever_the_next_kill_found() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    let skipped = || skipped_kill("walk the process table", None);
    let outcomes: [(&str, &dyn Fn() -> TreeKillOutcome); 3] = [
        ("NoRoot", &|| TreeKillOutcome::NoRoot(ROOT_PID, None)),
        ("Unwalked", &unwalked),
        ("Skipped", &skipped),
    ];
    for (label, outcome) in outcomes {
        let killed = TreeKilled::default();
        killed
            .settle(
                Some(&walker()),
                TreeKillOutcome::Ran(Err(Unkilled {
                    members: vec![member_left(7)],
                    root: None,
                    resolved: Vec::new(),
                })),
                true,
            )
            .answer
            .expect_err("a member was left");

        let again = killed
            .settle(Some(&walker()), outcome(), true)
            .answer
            .expect_err("the member is not shown killed");

        assert_eq!(pid_left(first_left(&again)), 7, "{label}: {again}");
        assert!(!killed.is_set(), "{label}");
    }
}

/// A tree this handle already killed does not excuse a gone root from answering the member a later
/// kill left: the mark shortcut applies only when nothing is held. Mutant: `NoRoot` with the mark set
/// returns `Killed` before the held members are read.
#[skuld::test]
fn a_gone_root_over_a_marked_tree_still_answers_a_held_member() {
    use super::{SettleOutcome, TreeKillOutcome, TreeKilled, Unkilled};
    let killed = TreeKilled::default();
    killed
        .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
        .answer
        .expect("a complete kill");
    assert!(killed.is_set());
    killed
        .settle(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![member_left(7)],
                root: None,
                resolved: Vec::new(),
            })),
            true,
        )
        .answer
        .expect_err("a later kill left a member");

    let again = killed
        .settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, None), true)
        .answer
        .expect_err("the member is not shown killed");
    assert_eq!(pid_left(first_left(&again)), 7, "{again}");

    let nothing_held = TreeKilled::default();
    nothing_held
        .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
        .answer
        .expect("a complete kill");
    assert!(matches!(
        nothing_held
            .settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, None), true)
            .answer,
        Ok(SettleOutcome::Killed)
    ));
}

/// A `Child`'s `kill_tree` whose walk was not made answers the walk's own `Unassessable` and does not
/// kill the root through its handle (its own retry walks from it). What it does with the held member
/// follows the handle's own look at the root: a root it sees running, or cannot say has exited, keeps
/// the member for the retry's walk (the call waits for nothing); a root it sees exited has no walk that
/// reaches the member, so the call kills it by identity and waits for it. The fake mechanism kills
/// nothing and states that it killed the member again, so the row reads the wait the sweep made of it;
/// the kill itself is the settlement's (`a_settlement_of_a_walk_not_made_kills_the_held_members`). The
/// fake's looks answer on every platform, the exited one included: the rule reads `exited_by`, not a
/// peek.
///
/// Mutants: the sweep runs the root's backstop over an unwalked walk; it answers that walk with another
/// error; it kills the held member whatever the look says, or never kills it; a look that fails is
/// taken as an exit.
#[cfg(unix)]
#[skuld::test]
fn a_child_kill_tree_over_an_unwalked_walk_keeps_the_held_member_unless_its_root_looks_exited() {
    use crate::containment::fake::FakeContains;
    use crate::containment::treewalk::Listing;
    use crate::containment::Containment;
    use crate::error::Error;
    use crate::os_process::fake::Answer;
    use crate::test_child::over_fake::{child_with, live_member, root_looking};
    // What the sweep waits for: the held member only over an exited root.
    let looks = [
        ("running", Answer::Running, false),
        ("unknown", Answer::Err(std::io::ErrorKind::PermissionDenied), false),
        ("exited", Answer::Exited, true),
    ];
    for (root_looks, looks, killed_in_call) in looks {
        let (member, stdin, id) = live_member();
        let (fake, _) = FakeContains::new(Containment::TreeWalk, false);
        let root = root_looking([looks; 4]);
        let child = child_with(&root, fake.unwalked().killing_again([id]));
        child.tree.hold_walked(
            Listing {
                members: vec![id],
                complete: true,
            },
            None,
        );

        let swept = child.kill_tree_after("kill_tree", None, None);

        let failure = swept.answer.as_ref().expect_err("the walk was not made");
        assert!(
            matches!(failure.error, Error::Unassessable { .. }),
            "{:?}",
            failure.error
        );
        let waited_for: &[crate::identity::ProcessId] = if killed_in_call { &[id] } else { &[] };
        assert_eq!(
            swept.wait.members_for_test(),
            waited_for,
            "a root that looks {root_looks}: the held member is killed in the call only when no walk can reach it"
        );
        assert!(
            root.signal_calls().is_empty(),
            "a root that looks {root_looks} is not killed"
        );
        // Released after the checks: the fake kills nothing, so only the end of the member's stdin ends it.
        drop((swept, stdin));
        member.wait().expect("reap the member");
    }
}

/// A `Child` whose tree holds no member has nothing to keep or kill over a walk not made, so its
/// `kill_tree` answers the walk's error without a look at the root. The fake root has no look scripted,
/// and a look past them panics.
///
/// Mutant: the sweep looks at the root whatever the tree holds.
#[cfg(unix)]
#[skuld::test]
fn a_child_kill_tree_over_an_unwalked_walk_looks_at_no_root_when_the_tree_holds_nothing() {
    use crate::containment::fake::FakeContains;
    use crate::containment::Containment;
    use crate::error::Error;
    use crate::test_child::over_fake::{child_with, root_looking};
    let (fake, _) = FakeContains::new(Containment::TreeWalk, false);
    let root = root_looking([]);
    let child = child_with(&root, fake.unwalked());

    let swept = child.kill_tree_after("kill_tree", None, None);

    let failure = swept.answer.as_ref().expect_err("the walk was not made");
    assert!(
        matches!(failure.error, Error::Unassessable { .. }),
        "{:?}",
        failure.error
    );
    assert_eq!(root.looks(), 0, "no look at the root");
    assert!(root.signal_calls().is_empty(), "the root is not killed");
}

/// A member whose identity was read and whose kill was refused is killed by identity again by the
/// next kill that runs, and the tree is then settled and marked. Mutants: the retry does not kill it;
/// it kills it and still answers with the earlier error.
#[skuld::test]
fn a_member_whose_kill_was_refused_is_killed_again_by_identity_and_then_settled() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
    let killed = TreeKilled::default();
    let id = blocker.id().expect(crate::test_child::IDENTITY_READ);

    let first = killed
        .settle(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![member_left(id.pid())],
                root: None,
                resolved: vec![id],
            })),
            true,
        )
        .answer
        .expect_err("the member was left");
    assert_eq!(pid_left(first_left(&first)), id.pid());
    assert!(!killed.is_set());

    killed
        .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
        .answer
        .expect("the retry killed the member by its identity");

    assert!(killed.is_set());
    // Released after the kill: a retry that sent nothing lets the member exit on EOF, so the
    // assertion fails instead of the wait hanging.
    drop(stdin);
    crate::test_child::assert_killed("the member", blocker.wait().expect("reap the member"));
}

/// A gone root over members an earlier kill left, which are gone now, says so each time, in the same
/// words: the tree could not be walked, but "nothing was killed" and "killed again" are each false for
/// a member that exited on its own. `exits_on_its_own`: the member exits at EOF before the
/// settlement instead of being killed by it.
fn gone_root_answers_over_gone_members_each_time(exits_on_its_own: bool) {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
    let killed = TreeKilled::default();
    let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
    killed
        .settle(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![member_left(id.pid())],
                root: None,
                resolved: vec![id],
            })),
            true,
        )
        .answer
        .expect_err("the member was left");
    let mut held = Some(stdin);
    if exits_on_its_own {
        drop(held.take());
        blocker.wait().expect("the member exits on its own and is reaped");
    }

    let texts: Vec<String> = (0..2)
        .map(|_| {
            let left = killed
                .settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, None), true)
                .answer
                .expect_err("a gone root walked nothing");
            assert_eq!(left.left_members().len(), 1, "{left}");
            assert_eq!(
                standing(&killed),
                Standing::Unvouched(super::UnvouchedKind::HeldMembersGone)
            );
            first_left(&left).to_string()
        })
        .collect();

    if !exits_on_its_own {
        drop(held.take());
        crate::test_child::assert_killed("the member", blocker.wait().expect("reap the member"));
    }
    assert_eq!(texts[0], texts[1]);
    for text in &texts {
        assert!(text.contains("are gone"), "{text}");
        assert!(!text.contains("nothing was killed"), "{text}");
        assert!(!text.contains("killed again"), "{text}");
    }
}

/// A member a cooperative walk reached is held like one a refused kill left: a gone root's settlement
/// kills it by its identity, and one held twice is held once. Nothing held for an empty list.
///
/// Mutants: the held member is not killed; the second hold adds it again; an empty hold marks the tree
/// left.
#[skuld::test]
fn members_a_cooperative_walk_reached_are_killed_by_identity_when_the_root_is_gone() {
    use super::{TreeKillOutcome, TreeKilled};
    let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
    let killed = TreeKilled::default();
    let id = blocker.id().expect(crate::test_child::IDENTITY_READ);

    killed.hold(Vec::new(), true, None);
    assert_eq!(standing(&killed), Standing::Never);
    killed.hold(vec![id], true, None);
    killed.hold(vec![id], true, None);
    assert_eq!(standing(&killed), Standing::Left(vec![id.pid()]));

    let settled = killed.settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, None), true);
    settled.answer.expect_err("a gone root walked nothing");
    assert_eq!(settled.killed_again, vec![id], "the held member was killed again");
    assert_eq!(
        standing(&killed),
        Standing::Unvouched(super::UnvouchedKind::HeldMembersGone)
    );
    // Released after the kill: a settlement that sent nothing lets the member exit on EOF, which
    // fails the assertion instead of leaving a wait unbounded.
    drop(stdin);
    crate::test_child::assert_killed("the held member", blocker.wait().expect("reap the member"));
}

/// A settlement of a walk that could not be made, with nothing kept for a walk from a running root,
/// kills the held members, a `SIGTERM` walk's and a refused kill's, by identity, and answers the walk's
/// own `Unassessable`, for a drop's settlement and a `kill_tree` call's alike.
///
/// Mutants: an unmade walk leaves held members running (`Termed` or `Resolved`); it answers none of
/// the walk's error.
#[skuld::test]
fn a_settlement_of_a_walk_not_made_kills_the_held_members() {
    use super::{Keeping, TreeKillOutcome, TreeKilled, Unkilled};
    use crate::error::Error;
    for by_kill_tree in [false, true] {
        let (termed, termed_stdin) = crate::test_child::held_uncontained_blocker(false);
        let termed_id = termed.id().expect(crate::test_child::IDENTITY_READ);
        let (refused, refused_stdin) = crate::test_child::held_uncontained_blocker(false);
        let refused_id = refused.id().expect(crate::test_child::IDENTITY_READ);
        let killed = TreeKilled::default();
        killed
            .settle(
                Some(&walker()),
                TreeKillOutcome::Ran(Err(Unkilled {
                    members: vec![member_left(refused_id.pid())],
                    root: None,
                    resolved: vec![refused_id],
                })),
                true,
            )
            .answer
            .expect_err("a member was left");
        killed.hold(vec![termed_id], true, None);
        let held = Standing::Left(vec![refused_id.pid(), termed_id.pid()]);
        assert_eq!(standing(&killed), held);

        let (error, killed_again) = if by_kill_tree {
            let settled = killed.settle_for_kill_tree(Some(&walker()), unwalked(), false, Keeping::Nothing);
            (settled.answer.expect_err("a walk not made"), settled.killed_again)
        } else {
            let settled = killed.settle(Some(&walker()), unwalked(), false);
            (settled.answer.expect_err("a walk not made"), settled.killed_again)
        };

        assert!(matches!(error, Error::Unassessable { .. }), "{by_kill_tree}: {error:?}");
        assert_eq!(killed_again, vec![refused_id, termed_id], "{by_kill_tree}");
        // Released after the kills: a settlement that sent nothing lets a member exit on EOF, which
        // fails the assertion instead of leaving a wait unbounded.
        drop((termed_stdin, refused_stdin));
        crate::test_child::assert_killed("the termed member", termed.wait().expect("reap the member"));
        crate::test_child::assert_killed("the refused member", refused.wait().expect("reap the member"));
    }
}

/// The drop's warn over a walk not made claims a kill by identity only when the handle held members,
/// and names the ones the settlement killed; the root is killed regardless, and the warn says so either
/// way.
///
/// Mutants: the warn claims kills over a tree that held nothing; it names no pid.
#[skuld::test]
fn a_drop_over_a_walk_not_made_claims_only_the_kills_the_settlement_made() {
    use super::TreeKilled;
    let none_held = TreeKilled::default()
        .settle_for_drop(Some(&walker()), unwalked(), true)
        .expect("a walk not made is warned of")
        .text;
    assert!(none_held.contains("the snapshot failed"), "{none_held}");
    assert!(none_held.contains("may be orphaned"), "{none_held}");
    assert!(!none_held.contains("killed by identity"), "{none_held}");

    let (held, held_stdin) = crate::test_child::held_uncontained_blocker(false);
    let held_id = held.id().expect(crate::test_child::IDENTITY_READ);
    let killed = TreeKilled::default();
    killed.hold(vec![held_id], true, None);
    let warn = killed
        .settle_for_drop(Some(&walker()), unwalked(), true)
        .expect("a walk not made is warned of")
        .text;
    assert!(
        warn.contains(&format!("killed by identity (pid {})", held_id.pid())),
        "{warn}"
    );
    assert!(warn.contains("may be orphaned"), "{warn}");
    drop(held_stdin);
    crate::test_child::assert_killed("the held member", held.wait().expect("reap the member"));
}

/// A settlement of a walk not made that a `Child` keeps for a walk from its running root kills
/// nothing, and still answers every member an earlier kill could not kill beside the walk's own
/// `Unassessable`: the one whose identity was read and that still runs, and the one never read. A
/// refused member that is gone is not named, and a member only a `SIGTERM` walk reached was refused by
/// nothing. The state is left as it was.
///
/// Mutants: the answer is the walk's error alone; a refused member that is gone is named; a `Termed`
/// one is named; a member is killed.
#[skuld::test]
fn a_kept_settlement_of_a_walk_not_made_names_the_members_an_earlier_kill_refused() {
    use super::{Keeping, TreeKillOutcome, TreeKilled, Unkilled};
    use crate::error::Error;
    let alive_member = || {
        let (member, stdin) = crate::test_child::held_uncontained_blocker(false);
        let id = member.id().expect(crate::test_child::IDENTITY_READ);
        (member, stdin, id)
    };
    let (refused, refused_stdin, refused_id) = alive_member();
    let (termed, termed_stdin, termed_id) = alive_member();
    let (gone, gone_stdin, gone_id) = alive_member();
    let never_read = u32::MAX - 1;
    let killed = TreeKilled::default();
    killed
        .settle(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![
                    member_left(refused_id.pid()),
                    member_left(never_read),
                    member_left(gone_id.pid()),
                ],
                root: None,
                resolved: vec![refused_id, gone_id],
            })),
            false,
        )
        .answer
        .expect_err("the members were left");
    killed.hold(vec![termed_id], true, None);
    drop(gone_stdin);
    gone.wait().expect("the member exits on its own and is reaped");
    let held = standing(&killed);

    let settled = killed.settle_for_kill_tree(Some(&walker()), unwalked(), false, Keeping::ForWalkFromRunningRoot);

    let error = settled.answer.expect_err("a walk not made");
    assert_eq!(
        members_of(&error).iter().map(|(pid, _)| *pid).collect::<Vec<_>>(),
        [refused_id.pid(), never_read],
        "{error}"
    );
    assert!(
        matches!(unwalked_of(&error), Some(Error::Unassessable { detail, .. }) if detail == "the snapshot failed"),
        "{error:?}"
    );
    assert_eq!(settled.killed_again, vec![], "nothing is killed");
    for id in [refused_id, termed_id] {
        assert_eq!(id.is_alive(), crate::identity::Liveness::Alive, "{id:?} is not killed");
    }
    assert_eq!(standing(&killed), held, "the state is kept for the retry");
    drop((refused_stdin, termed_stdin));
    refused.wait().expect("reap the member");
    termed.wait().expect("reap the member");
}

/// A call whose own complete `SIGTERM` walk reached the held members stands on it when the root has
/// exited: every one gone or killed leaves the tree vouched for and the answer `Ok`; a walk that found
/// nothing is an empty listing. A member another call's walk reached, a walk that could not read every
/// candidate (it still holds and kills what it reached), and a gone root with no call do not vouch.
///
/// Mutants: the token is ignored; a member held by another call is vouched; an empty walk is none; an
/// incomplete walk vouches or does not hold its members.
#[skuld::test]
fn a_gone_root_over_the_calls_own_walk_is_vouched_only_when_every_held_member_is_its_own() {
    use super::{TreeKillOutcome, TreeKilled};
    use crate::containment::treewalk::WalkToken;
    let gone_root = |call: Option<WalkToken>| TreeKillOutcome::NoRoot(ROOT_PID, call);

    // An empty complete walk over a tree never settled.
    let killed = TreeKilled::default();
    let call = WalkToken::new();
    let walk = killed.hold(Vec::new(), true, Some(&call));
    killed
        .settle(Some(&walker()), gone_root(walk), true)
        .answer
        .expect("an empty walk is a listing");
    assert_eq!(standing(&killed), Standing::Killed);
    // No call: the gone root's own answer.
    let killed = TreeKilled::default();
    killed
        .settle(Some(&walker()), gone_root(None), true)
        .answer
        .expect_err("no call, no walk");
    assert_eq!(standing(&killed), Standing::Never);

    // A held member the call's walk reached is killed by identity, and the tree is vouched for.
    let (named, named_stdin) = crate::test_child::held_uncontained_blocker(false);
    let named_id = named.id().expect(crate::test_child::IDENTITY_READ);
    let killed = TreeKilled::default();
    let walk = killed.hold(vec![named_id], true, Some(&call));
    let settled = killed.settle(Some(&walker()), gone_root(walk), true);
    settled.answer.expect("every member the walk reached is killed");
    assert_eq!(settled.killed_again, vec![named_id]);
    assert_eq!(standing(&killed), Standing::Killed);

    // A member another call's walk reached is killed, and the tree is not vouched for.
    let (other, other_stdin) = crate::test_child::held_uncontained_blocker(false);
    let other_id = other.id().expect(crate::test_child::IDENTITY_READ);
    let killed = TreeKilled::default();
    killed.hold(vec![other_id], true, Some(&WalkToken::new()));
    let settled = killed.settle(Some(&walker()), gone_root(Some(call.clone())), true);
    settled.answer.expect_err("the held member is another call's");
    assert_eq!(settled.killed_again, vec![other_id]);
    assert_eq!(
        standing(&killed),
        Standing::Unvouched(super::UnvouchedKind::HeldMembersGone)
    );

    // An incomplete walk holds and kills what it reached, and vouches for nothing.
    let (partial, partial_stdin) = crate::test_child::held_uncontained_blocker(false);
    let partial_id = partial.id().expect(crate::test_child::IDENTITY_READ);
    let killed = TreeKilled::default();
    let walk = killed.hold(vec![partial_id], false, Some(&call));
    assert!(walk.is_none(), "an incomplete walk has no token to vouch with");
    assert_eq!(standing(&killed), Standing::Left(vec![partial_id.pid()]));
    let settled = killed.settle(Some(&walker()), gone_root(walk), true);
    settled.answer.expect_err("an incomplete walk cannot vouch");
    assert_eq!(settled.killed_again, vec![partial_id]);

    // Released after the kills: a settlement that sent nothing lets a member exit on EOF, which fails
    // the assertion instead of leaving a wait unbounded.
    drop((named_stdin, other_stdin, partial_stdin));
    crate::test_child::assert_killed("the call's member", named.wait().expect("reap the member"));
    crate::test_child::assert_killed("the other call's member", other.wait().expect("reap the member"));
    crate::test_child::assert_killed("the incomplete walk's member", partial.wait().expect("reap the member"));
}

/// The call stands on its walk only when every held member is one that walk reached: one member of the
/// call's own walk held beside a tokenless walk's, another call's, a refused kill's leftover whose
/// identity was read (`Resolved`) or one never read (`Unread`) is not vouched. Each member that can be
/// killed is, by identity, and the answer is the held members' own.
///
/// Mutants: the vouching asks for any held member of the call's, not all; a `Resolved` or an `Unread`
/// member counts as the call's own.
#[skuld::test]
fn a_gone_root_over_the_calls_own_member_beside_another_kind_is_not_vouched() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled, UnvouchedKind};
    use crate::containment::treewalk::WalkToken;
    let call = WalkToken::new();
    let mut spawned = Vec::new();
    for other in ["tokenless", "another call's", "resolved", "unread"] {
        let (own, own_stdin) = crate::test_child::held_uncontained_blocker(false);
        let own_id = own.id().expect(crate::test_child::IDENTITY_READ);
        let (second, second_stdin) = crate::test_child::held_uncontained_blocker(false);
        let second_id = second.id().expect(crate::test_child::IDENTITY_READ);
        let killed = TreeKilled::default();
        let left = |members: Vec<crate::error::Error>, resolved| {
            killed
                .settle(
                    Some(&walker()),
                    TreeKillOutcome::Ran(Err(Unkilled {
                        members,
                        root: None,
                        resolved,
                    })),
                    true,
                )
                .answer
                .expect_err("a member was left")
        };
        match other {
            "tokenless" => _ = killed.hold(vec![second_id], true, None),
            "another call's" => _ = killed.hold(vec![second_id], true, Some(&WalkToken::new())),
            "resolved" => _ = left(vec![member_left(second_id.pid())], vec![second_id]),
            _ => _ = left(vec![member_left(8)], Vec::new()),
        }
        let walk = killed.hold(vec![own_id], true, Some(&call));
        assert!(walk.is_some(), "{other}: the call's walk is complete");

        let settled = killed.settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, walk), true);

        let answer = settled.answer.expect_err(other);
        assert!(!killed.is_set(), "{other}: the tree is not vouched for");
        assert!(
            settled.killed_again.contains(&own_id),
            "{other}: the call's member is killed"
        );
        if other == "unread" {
            assert_eq!(pid_left(first_left(&answer)), 8, "{other}");
            assert_eq!(standing(&killed), Standing::Left(vec![8]), "{other}");
        } else {
            assert!(
                matches!(answer, crate::error::Error::Unassessable { .. }),
                "{other}: {answer}"
            );
            assert_eq!(
                standing(&killed),
                Standing::Unvouched(UnvouchedKind::HeldMembersGone),
                "{other}"
            );
            assert!(
                settled.killed_again.contains(&second_id),
                "{other}: the other member is killed"
            );
        }
        spawned.push((other, own, own_stdin, second, second_stdin));
    }
    // Released after the kills: a settlement that sent nothing lets a member exit on EOF, which fails
    // the assertion instead of leaving a wait unbounded.
    for (other, own, own_stdin, second, second_stdin) in spawned {
        drop((own_stdin, second_stdin));
        crate::test_child::assert_killed("the call's member", own.wait().expect("reap the member"));
        let status = second.wait().expect("reap the member");
        if other == "unread" {
            // Never held (the row's unread member is the number 8): it only exits on the EOF.
            assert!(status.success(), "{status:?}");
        } else {
            crate::test_child::assert_killed("the other member", status);
        }
    }
}

/// A member held again keeps what its first hold decided: a re-hold with the call's complete token tags
/// a member an earlier tokenless walk reached, so the call's sweep may stand on it; a tokenless re-hold
/// keeps the tag a call's walk set; a member held as `Resolved` (a refused kill's leftover) stays so
/// whoever holds it again, and does not vouch.
///
/// Mutants: a re-hold never retags; a re-hold always overwrites the tag; a `Resolved` member held again
/// becomes a walk's member and vouches.
#[skuld::test]
fn holding_a_member_again_retags_it_only_with_a_calls_token_and_keeps_a_resolved_one() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    use crate::containment::treewalk::WalkToken;
    let call = WalkToken::new();
    let mut spawned = Vec::new();
    for (label, vouched) in [
        ("tokenless, then the call's", true),
        ("the call's, then tokenless", true),
        ("resolved, then the call's", false),
    ] {
        let (member, stdin) = crate::test_child::held_uncontained_blocker(false);
        let id = member.id().expect(crate::test_child::IDENTITY_READ);
        let killed = TreeKilled::default();
        let walk = match label {
            "tokenless, then the call's" => {
                killed.hold(vec![id], true, None);
                killed.hold(vec![id], true, Some(&call))
            }
            "the call's, then tokenless" => {
                let walk = killed.hold(vec![id], true, Some(&call));
                killed.hold(vec![id], true, None);
                walk
            }
            _ => {
                killed
                    .settle(
                        Some(&walker()),
                        TreeKillOutcome::Ran(Err(Unkilled {
                            members: vec![member_left(id.pid())],
                            root: None,
                            resolved: vec![id],
                        })),
                        true,
                    )
                    .answer
                    .expect_err("a member was left");
                killed.hold(vec![id], true, Some(&call))
            }
        };
        assert_eq!(standing(&killed), Standing::Left(vec![id.pid()]), "{label}: held once");

        let settled = killed.settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, walk), true);

        assert_eq!(settled.answer.is_ok(), vouched, "{label}");
        assert_eq!(killed.is_set(), vouched, "{label}");
        assert_eq!(settled.killed_again, vec![id], "{label}: killed by identity");
        spawned.push((member, stdin));
    }
    for (member, stdin) in spawned {
        drop(stdin);
        crate::test_child::assert_killed("the held member", member.wait().expect("reap the member"));
    }
}

/// The error of a gone root is true on the platform: Unix reparents at an exit, Windows never does and
/// says only that the pid names no process of the tree. Both name the pid and that no walk ran.
///
/// Mutant: the Windows text says its descendants were reparented.
#[skuld::test]
fn a_gone_roots_error_names_the_pid_and_says_what_is_true_on_the_platform() {
    let detail = match super::TreeKillOutcome::no_root_error(ROOT_PID) {
        crate::error::Error::Unassessable { detail, .. } => detail,
        other => panic!("expected Unassessable, got {other:?}"),
    };
    assert!(detail.contains(&ROOT_PID.to_string()), "{detail}");
    assert!(detail.contains("no walk ran and nothing was killed"), "{detail}");
    #[cfg(unix)]
    assert!(detail.contains("reparented"), "{detail}");
    #[cfg(not(unix))]
    assert!(
        detail.contains("names no process of this tree") && !detail.contains("reparented"),
        "{detail}"
    );
}

/// A walk on a tree an earlier kill left unvouched holds its members all the same, to be killed by
/// identity, and the tree keeps its kind: the call cannot vouch for what the earlier kill did not, so
/// the answer is `Unassessable`, never `Ok`.
///
/// Mutants: `hold` drops the members of such a tree; `hold` loses the kind; the call's token vouches
/// for an unvouched tree.
#[skuld::test]
fn a_walk_on_an_unvouched_tree_holds_its_members_and_keeps_the_kind() {
    use super::{TreeKillOutcome, UnvouchedKind};
    use crate::containment::treewalk::WalkToken;
    let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
    let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
    let killed = tree_that_saw_the_root_running();
    let call = WalkToken::new();

    let walk = killed.hold(vec![id], true, Some(&call));

    assert_eq!(
        standing(&killed),
        Standing::HeldOnUnvouched(vec![id.pid()], UnvouchedKind::RootSeenRunning)
    );
    let settled = killed.settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, walk), true);
    settled.answer.expect_err("a walk cannot vouch for an unvouched tree");
    assert_eq!(settled.killed_again, vec![id], "the held member was killed by identity");
    assert_eq!(standing(&killed), Standing::Unvouched(UnvouchedKind::RootSeenRunning));
    drop(stdin);
    crate::test_child::assert_killed("the held member", blocker.wait().expect("reap the member"));
}

/// A walk that finds live members on a killed tree has seen it run on: the tree is not killed
/// (`is_set`) while it holds them, and only the call's own complete walk, through its sweep, vouches
/// for it again. A walk that could not read every candidate, or a `terminate_tree` with no sweep token,
/// held its members to be killed by identity, but its sweep answers `Unassessable`, never `Ok`.
///
/// Mutants: a killed tree stays killed under held members; an incomplete walk or a tokenless hold
/// vouches over a killed tree.
#[skuld::test]
fn a_walk_that_finds_members_on_a_killed_tree_unvouches_it_until_its_own_complete_walk_vouches() {
    use super::{TreeKillOutcome, TreeKilled, UnvouchedKind};
    use crate::containment::treewalk::WalkToken;
    // (complete walk, sweep token handed back to the call, the sweep vouches)
    for (label, complete, with_call, vouches) in [
        ("complete walk with its token", true, true, true),
        ("incomplete walk", false, true, false),
        ("terminate_tree, no sweep token", true, false, false),
    ] {
        let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
        let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
        let killed = TreeKilled::default();
        killed
            .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
            .answer
            .expect("a complete kill");
        assert!(killed.is_set(), "{label}");
        let call = WalkToken::new();

        let walk = killed.hold(vec![id], complete, with_call.then_some(&call));

        assert_eq!(standing(&killed), Standing::Left(vec![id.pid()]), "{label}");
        assert!(!killed.is_set(), "{label}: a tree seen running on is not killed");
        let settled = killed.settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, walk), true);
        assert_eq!(settled.answer.is_ok(), vouches, "{label}: {:?}", settled.answer);
        assert_eq!(
            settled.killed_again,
            vec![id],
            "{label}: the held member was killed by identity"
        );
        assert_eq!(killed.is_set(), vouches, "{label}");
        assert_eq!(
            standing(&killed),
            if vouches {
                Standing::Killed
            } else {
                Standing::Unvouched(UnvouchedKind::HeldMembersGone)
            },
            "{label}"
        );
        drop(stdin);
        crate::test_child::assert_killed("the held member", blocker.wait().expect("reap the member"));
    }
}

/// The kind of an unvouched tree survives a held member whose kill by identity is refused and that then
/// exits: `RootSeenRunning`, held, refused, gone, is still `RootSeenRunning`. A setuid-root helper
/// refuses the kill of its caller.
///
/// Mutant: held members that drop out over an unvouched tree name `HeldMembersGone`.
#[cfg(unix)]
#[skuld::test]
fn a_held_member_that_refuses_its_kill_and_then_exits_leaves_the_unvouched_kind_as_it_was(
    #[fixture(setuid)] _group: &crate::test_groups::Group,
) {
    use super::{TreeKillOutcome, UnvouchedKind};
    use crate::containment::treewalk::WalkToken;
    let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let killed = tree_that_saw_the_root_running();
    let walk = killed.hold(vec![id], true, Some(&WalkToken::new()));

    killed
        .settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, walk), true)
        .answer
        .expect_err("the helper refused the kill");
    assert_eq!(
        standing(&killed),
        Standing::HeldOnUnvouched(vec![id.pid()], UnvouchedKind::RootSeenRunning)
    );

    // The helper exits at EOF: nothing killed it.
    drop(stdin);
    assert!(child.wait().expect("the helper exits on EOF").success());
    // The handle's end consumes the zombie, which a wait leaves and a held identity still finds.
    drop(child);
    killed
        .settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, None), true)
        .answer
        .expect_err("the held member is gone, and nothing walked what it forked");
    assert_eq!(standing(&killed), Standing::Unvouched(UnvouchedKind::RootSeenRunning));
}

/// A member is held once by its identity, pid and start together, not by its pid: a later holder of a
/// pid is another member.
///
/// Mutant: held entries are deduped by raw pid.
#[skuld::test]
fn held_members_are_told_apart_by_identity_not_pid() {
    use super::TreeKilled;
    let first = crate::identity::ProcessId::current();
    let reused = first.with_other_value();
    assert_eq!((first.pid(), first == reused), (reused.pid(), false));
    let killed = TreeKilled::default();
    killed.hold(vec![first], true, None);
    killed.hold(vec![first], true, None);
    assert_eq!(standing(&killed), Standing::Left(vec![first.pid()]));
    killed.hold(vec![reused], true, None);
    assert_eq!(standing(&killed), Standing::Left(vec![first.pid(), reused.pid()]));
}

/// Mutant: the answer is `no_root_error`, or says the members were killed again, or changes with the
/// second call.
#[skuld::test]
fn a_gone_root_over_members_killed_by_the_settlement_says_they_are_gone_each_time() {
    gone_root_answers_over_gone_members_each_time(false);
}

/// Mutant: the answer says the members were killed.
#[skuld::test]
fn a_gone_root_over_a_member_that_exited_on_its_own_says_it_is_gone_each_time() {
    gone_root_answers_over_gone_members_each_time(true);
}

/// A kill that ran and killed everything but could not read the root's exit flag leaves the tree
/// unvouched, and a drop over it warns that the root's exit could not be told begun or not: no member
/// was seen running and no kill was skipped, so neither is said.
///
/// Mutants: the tree is `Killed` (no warn); the kind is `Earlier` ("left something running").
#[skuld::test]
fn a_drop_over_a_tree_whose_exit_flag_was_unread_warns_of_the_exit() {
    use super::{TreeKillOutcome, TreeKilled};
    let killed = TreeKilled::default();
    killed
        .settle(
            Some(&walker()),
            TreeKillOutcome::ExitUnread(crate::error::Error::Unassessable {
                detail: "the exit flag could not be read".into(),
                source: None,
            }),
            true,
        )
        .answer
        .expect_err("the read's error is the answer");

    let warn = killed
        .settle_for_drop(Some(&walker()), skipped_kill("walk the process table", None), true)
        .expect("an unvouched tree is warned of")
        .text;

    assert!(warn.contains("could not be vouched for"), "{warn}");
    assert!(warn.contains("whether the root's exit had begun"), "{warn}");
    assert!(!warn.contains("left something running"), "{warn}");
    assert!(!warn.contains("skipped the kill"), "{warn}");
}

/// A drop that skips the kill over a tree it cannot vouch for warns of it, in words true of what
/// `settle` found: members an earlier kill left that are gone now (a held member that exited or was
/// killed by the settlement), or, when the cause is no longer known (members never identified, or
/// members since gone), only that something was left running and no walk
/// has checked what it forked. A tree that was killed, or never settled (a skipped kill has its own
/// warn), says nothing here.
///
/// Mutants: the drop is silent over an unvouched tree; a text speaks of members after a walk left only
/// the root; a text says "no longer tracked" of members known gone.
#[skuld::test]
fn a_drop_over_an_unvouched_tree_warns_of_what_settle_found() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    let skipped = || skipped_kill("walk the process table", None);

    // Held members that the settlement found gone.
    let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
    let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
    let held_gone = tree_left_with(id.pid(), vec![id]);
    let warn = held_gone
        .settle_for_drop(Some(&walker()), skipped(), true)
        .expect("an unvouched tree is warned of")
        .text;
    drop(stdin);
    crate::test_child::assert_killed("the member", blocker.wait().expect("reap the member"));
    assert!(warn.contains("could not be vouched for"), "{warn}");
    assert!(warn.contains("skipped the kill"), "{warn}");
    assert!(warn.contains("are gone"), "{warn}");
    assert!(!warn.contains("no longer tracked"), "{warn}");

    // Something left running that no settlement knows more of: a member of a handle that is not a walk,
    // which holds no identity for it.
    let root_left = || {
        TreeKillOutcome::Ran(Err(Unkilled {
            members: Vec::new(),
            root: Some(Box::new(member_left(1))),
            resolved: Vec::new(),
        }))
    };
    let earlier = TreeKilled::default();
    earlier
        .settle(
            Some(&non_walk()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![member_left(8)],
                root: None,
                resolved: Vec::new(),
            })),
            true,
        )
        .answer
        .expect_err("a member is running");
    let warn = earlier
        .settle_for_drop(Some(&walker()), skipped(), true)
        .expect("an unvouched tree is warned of")
        .text;
    assert!(warn.contains("could not be vouched for"), "{warn}");
    assert!(warn.contains("skipped the kill"), "{warn}");
    assert!(warn.contains("left something running that it could not name"), "{warn}");
    assert!(!warn.contains("earlier kill"), "{warn}");
    assert!(!warn.contains("members"), "{warn}");

    // A walk that saw the root running and left it, whose end the call did not see: the root was seen
    // running, whatever the kind the tree had.
    let root_running = TreeKilled::default();
    root_running
        .settle(Some(&walker()), root_left(), false)
        .answer
        .expect_err("the root is running");
    let warn = root_running
        .settle_for_drop(Some(&walker()), skipped(), true)
        .expect("an unvouched tree is warned of")
        .text;
    assert!(warn.contains("found the root running"), "{warn}");
    assert!(!warn.contains("had ended"), "{warn}");
    assert!(!warn.contains("members"), "{warn}");

    // A walk that left only the root, then a `kill_tree` that answered `Ok`: the drop says what that
    // call found, every time, not that it skipped a kill over something an earlier kill left.
    let root_only = TreeKilled::default();
    root_only
        .settle(Some(&walker()), root_left(), true)
        .answer
        .expect("the root ended");
    for _ in 0..2 {
        let warn = root_only
            .settle_for_drop(Some(&walker()), skipped(), true)
            .expect("an unvouched tree is warned of")
            .text;
        assert!(warn.contains("could not be vouched for"), "{warn}");
        assert!(warn.contains("found the root running"), "{warn}");
        assert!(warn.contains("never looked for"), "{warn}");
        assert!(!warn.contains("had ended"), "{warn}");
        assert!(!warn.contains("members"), "{warn}");
        assert!(!warn.contains("skipped the kill"), "{warn}");
        assert!(!warn.contains("earlier kill"), "{warn}");
    }

    // The drop's own walk saw the root running, and its root kill ended it: no later settlement
    // warns, so this one does.
    let warn = TreeKilled::default()
        .settle_for_drop(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: Vec::new(),
                root: Some(Box::new(member_left(1))),
                resolved: Vec::new(),
            })),
            true,
        )
        .expect("a walk that left the root is warned of")
        .text;
    assert!(warn.contains("could not be vouched for"), "{warn}");
    assert!(warn.contains("found the root running"), "{warn}");
    assert!(warn.contains("never looked for"), "{warn}");
    assert!(!warn.contains("had ended"), "{warn}");
    assert!(!warn.contains("members"), "{warn}");
    assert!(!warn.contains("skipped the kill"), "{warn}");

    let killed = TreeKilled::default();
    killed
        .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
        .answer
        .expect("a complete kill");
    assert!(killed.settle_for_drop(Some(&walker()), skipped(), true).is_none());
    assert!(TreeKilled::default()
        .settle_for_drop(Some(&walker()), skipped(), true)
        .is_none());
}

/// A walk that saw the root running and left it un-vouches the tree, from any state and whatever
/// ended the root afterwards (the root may have forked between the snapshot and the backstop): a kill
/// happened, so a gone root afterwards says the tree could not be walked, not that nothing was
/// killed. The answer follows the root's end: `Ok` once it ended, the root's error while it runs. The
/// kind the state stores is the root seen running, whatever the kind it had and whether or not the
/// root had ended: the latest fact names it, so a gone root afterwards says the root was found running,
/// not that members an earlier kill left are gone.
///
/// Mutants: the state goes to or stays never settled, after which a gone root says nothing was
/// killed; the state stays or becomes killed once the backstop ended the root; an unvouched tree keeps
/// its kind over the walk that saw the root running.
#[skuld::test]
fn a_walk_that_saw_the_root_running_unvouches_the_tree_whatever_ended_it_afterwards() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled, UnvouchedKind};
    let root_left = || {
        TreeKillOutcome::Ran(Err(Unkilled {
            members: Vec::new(),
            root: Some(Box::new(member_left(1))),
            resolved: Vec::new(),
        }))
    };
    for start in ["never", "killed", "root seen running", "held members gone", "earlier"] {
        for root_ended in [false, true] {
            let label = format!("{start}, root_ended {root_ended}");
            let mut after: Box<dyn FnOnce()> = Box::new(|| {});
            let killed = match start {
                "held members gone" => {
                    let (killed, reap) = unvouched_tree();
                    after = reap;
                    killed
                }
                _ => TreeKilled::default(),
            };
            if matches!(start, "killed") {
                killed
                    .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
                    .answer
                    .expect("a complete kill");
            }
            if start == "root seen running" {
                killed
                    .settle(Some(&walker()), root_left(), false)
                    .answer
                    .expect_err("the root is left");
            }
            if start == "earlier" {
                killed
                    .settle(
                        Some(&non_walk()),
                        TreeKillOutcome::Ran(Err(Unkilled {
                            members: vec![member_left(8)],
                            root: None,
                            resolved: Vec::new(),
                        })),
                        true,
                    )
                    .answer
                    .expect_err("a member is running");
            }
            let want_start = match start {
                "never" => Standing::Never,
                "killed" => Standing::Killed,
                "root seen running" => Standing::Unvouched(UnvouchedKind::RootSeenRunning),
                "held members gone" => Standing::Unvouched(UnvouchedKind::HeldMembersGone),
                _ => Standing::Unvouched(UnvouchedKind::Earlier),
            };
            assert_eq!(standing(&killed), want_start, "{label}: start");

            let answer = killed.settle(Some(&walker()), root_left(), root_ended);

            match answer.answer {
                Ok(outcome) => {
                    assert!(root_ended, "{label}: the root is running");
                    assert_eq!(
                        outcome,
                        super::SettleOutcome::Unvouched {
                            kind: super::UnvouchedKind::RootSeenRunning
                        },
                        "{label}"
                    );
                }
                Err(left) => {
                    assert!(!root_ended, "{label}: the root ended");
                    assert_eq!(pid_left(first_left(&left)), 1, "{label}");
                }
            }
            assert_eq!(
                standing(&killed),
                Standing::Unvouched(UnvouchedKind::RootSeenRunning),
                "{label}"
            );

            let want = "found running";
            let mut texts = Vec::new();
            for _ in 0..2 {
                let gone = killed
                    .settle(Some(&walker()), TreeKillOutcome::NoRoot(ROOT_PID, None), true)
                    .answer
                    .expect_err("a gone root walked nothing");
                let text = first_left(&gone).to_string();
                assert!(!text.contains("nothing was killed"), "{label}: {gone}");
                assert!(!text.contains("members"), "{label}: {gone}");
                assert!(text.contains(want), "{label}: {gone}");
                assert_eq!(
                    standing(&killed),
                    Standing::Unvouched(UnvouchedKind::RootSeenRunning),
                    "{label}"
                );
                texts.push(text);
            }
            assert_eq!(texts[0], texts[1], "{label}");
            after();
        }
    }
}

/// A member whose identity was read and that has exited since stops failing the call: nothing is
/// signalled, and the tree is settled. Mutant: the earlier error is returned whatever became of the
/// member.
#[skuld::test]
fn a_member_that_exited_since_it_was_left_stops_failing_the_call() {
    use super::{TreeKillOutcome, TreeKilled, Unkilled};
    let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
    let killed = TreeKilled::default();
    let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
    killed
        .settle(
            Some(&walker()),
            TreeKillOutcome::Ran(Err(Unkilled {
                members: vec![member_left(id.pid())],
                root: None,
                resolved: vec![id],
            })),
            true,
        )
        .answer
        .expect_err("the member was left");
    drop(stdin);
    blocker.wait().expect("the member exits on its own and is reaped");

    killed
        .settle(Some(&walker()), TreeKillOutcome::Ran(Ok(())), true)
        .answer
        .expect("a member that is gone is not left");

    assert!(killed.is_set());
}

// A sweep's answer over the root's backstop =====

/// The answer of `SweepFailure::of` for a root `1`: `walk` is what the mechanism's kill left, and
/// `backstop` the handle's own kill of the root, which ended it when it is `Ok`.
fn swept(walk: super::TreeKillOutcome, backstop: Result<(), crate::error::Error>) -> crate::error::Error {
    swept_in(walker(), walk, backstop)
}

/// [`swept`] over a tree of `mechanism`.
fn swept_in(
    mechanism: crate::containment::mechanism::Mechanism,
    walk: super::TreeKillOutcome,
    backstop: Result<(), crate::error::Error>,
) -> crate::error::Error {
    let root_ended = backstop.is_ok();
    let tree = crate::containment::Tree::contained(mechanism);
    super::SweepFailure::of(&tree, walk, backstop, 1, root_ended)
        .answer
        .expect_err("a member was left")
        .error
}

fn io_error(code: i32) -> crate::error::Error {
    crate::error::Error::Io(std::io::Error::from_raw_os_error(code))
}

/// A root that the walk left and the backstop could not kill either is one member, whose cause holds
/// both failures, the backstop's first. Mutants: the backstop's failure is dropped, or kept beside
/// the member as a second one; the walk's cause is dropped; the other members are lost.
#[skuld::test]
fn a_root_the_walk_left_and_the_backstop_failed_to_kill_is_one_member_with_both_causes() {
    use super::{TreeKillOutcome, Unkilled};
    let [a, b, c] = CODES;
    let error = swept(
        TreeKillOutcome::Ran(Err(Unkilled {
            members: vec![left_by(2, a)],
            root: Some(Box::new(left_by(1, c))),
            resolved: Vec::new(),
        })),
        Err(io_error(b)),
    );

    assert_eq!(members_of(&error), [(2, Some(a)), (1, Some(b))]);
    let crate::error::Error::MembersLeft { members, .. } = &error else {
        unreachable!()
    };
    let crate::error::Error::MemberNotKilled { source, .. } = &**members.iter().nth(1).expect("the root") else {
        panic!("{members:?}");
    };
    let crate::error::Error::Several(causes) = &**source else {
        panic!("expected Several, got {source:?}");
    };
    let codes: Vec<_> = causes
        .iter()
        .map(|cause| crate::error::first_os_code(&**cause))
        .collect();
    assert_eq!(codes, [Some(b), Some(c)], "the backstop's first");
}

/// A backstop that fails after a walk that left nothing is a `MembersLeft` of the root alone, not the
/// bare error of the kill.
#[skuld::test]
fn a_backstop_failure_after_a_walk_that_left_nothing_is_a_members_left_of_the_root() {
    let error = swept(super::TreeKillOutcome::Ran(Ok(())), Err(io_error(CODES[1])));

    assert_eq!(members_of(&error), [(1, Some(CODES[1]))]);
}

/// A member the walk left, with a root it did not leave and the backstop could not kill: the root is
/// another member, after those the walk named.
#[skuld::test]
fn a_backstop_failure_adds_the_root_to_the_members_the_walk_left() {
    use super::{TreeKillOutcome, Unkilled};
    let [a, b, _] = CODES;
    let error = swept(
        TreeKillOutcome::Ran(Err(Unkilled {
            members: vec![left_by(2, a)],
            root: None,
            resolved: Vec::new(),
        })),
        Err(io_error(b)),
    );

    assert_eq!(members_of(&error), [(2, Some(a)), (1, Some(b))]);
}

/// A walk that left a member and then could not be made again keeps its `others` error; the root the
/// backstop failed to kill joins the members.
/// Mutant: the root is dropped, or put in `others`, or `others` is lost.
#[skuld::test]
fn a_backstop_failure_adds_the_root_to_the_members_and_keeps_the_unwalked_error() {
    use super::{TreeKillOutcome, Unkilled};
    let [a, b, _] = CODES;
    let error = swept(
        TreeKillOutcome::Ran(Err(Unkilled {
            members: vec![
                left_by(2, a),
                crate::error::Error::Unassessable {
                    detail: "the walk could not be made".into(),
                    source: None,
                },
            ],
            root: None,
            resolved: Vec::new(),
        })),
        Err(io_error(b)),
    );

    assert_eq!(members_of(&error), [(2, Some(a)), (1, Some(b))]);
    assert!(
        matches!(unwalked_of(&error), Some(crate::error::Error::Unassessable { detail, .. }) if detail == "the walk could not be made"),
        "{error:?}"
    );
}

/// A mechanism that is no walk answers one error that names no member, and keeps its variant when the
/// backstop fails too: the root, as a `MemberNotKilled`, comes below it after its own cause.
///
/// Mutants: the error becomes a `MembersLeft`; the root's failure is dropped; it comes before the
/// error's own cause.
#[skuld::test]
fn a_backstop_failure_keeps_the_error_of_a_mechanism_that_is_no_walk_with_the_root_below_it() {
    use super::TreeKillOutcome;
    use crate::error::Error;
    let [a, b, _] = CODES;
    let swept = |source| {
        swept_in(
            non_walk(),
            TreeKillOutcome::Ran(Err(super::Unkilled::from(Error::Containment {
                detail: "a member refused".into(),
                source,
            }))),
            Err(io_error(b)),
        )
    };

    let alone = swept(None);
    assert!(
        matches!(&alone, Error::Containment { detail, source: Some(source) }
            if detail == "a member refused" && matches!(&**source, Error::MemberNotKilled { pid: 1, .. })),
        "{alone:?}"
    );
    assert_eq!(crate::error::first_os_code(&alone), Some(b));

    let with_cause = swept(Some(Error::io_cause(std::io::Error::from_raw_os_error(a))));
    let Error::Containment {
        source: Some(source), ..
    } = &with_cause
    else {
        panic!("{with_cause:?}");
    };
    let Error::Several(list) = &**source else {
        panic!("expected Several, got {source:?}");
    };
    assert!(matches!(
        &**list.iter().nth(1).expect("the root"),
        Error::MemberNotKilled { pid: 1, .. }
    ));
    assert_eq!(crate::error::first_os_code(&**list.first()), Some(a));
}

/// A backstop that fails after a kill that left nothing, on a mechanism that is no walk, is a
/// `Containment` over the root as a `MemberNotKilled`: `MembersLeft` is the walk's variant.
///
/// Mutant: the answer is a `MembersLeft`.
#[skuld::test]
fn a_backstop_failure_after_a_clean_kill_of_a_mechanism_that_is_no_walk_is_a_containment_over_the_root() {
    use super::TreeKillOutcome;
    use crate::error::Error;
    let error = swept_in(non_walk(), TreeKillOutcome::Ran(Ok(())), Err(io_error(CODES[1])));

    let Error::Containment {
        source: Some(source), ..
    } = &error
    else {
        panic!("{error:?}");
    };
    assert!(matches!(&**source, Error::MemberNotKilled { pid: 1, .. }), "{source:?}");
    assert_eq!(crate::error::first_os_code(&error), Some(CODES[1]));
}

/// A backstop that fails after a walk that left nothing is a `MembersLeft` of the root alone.
/// Mutant: the answer is the `Containment` of every other mechanism.
#[skuld::test]
fn a_backstop_failure_after_a_clean_walk_is_a_members_left_of_the_root_alone() {
    use super::TreeKillOutcome;
    use crate::error::Error;
    let error = swept(TreeKillOutcome::Ran(Ok(())), Err(io_error(CODES[1])));

    let Error::MembersLeft { members, .. } = &error else {
        panic!("{error:?}");
    };
    assert_eq!(members.iter().len(), 1);
    assert!(
        matches!(&**members.first(), Error::MemberNotKilled { pid: 1, .. }),
        "{error:?}"
    );
    assert_eq!(crate::error::first_os_code(&error), Some(CODES[1]));
}

/// With the root ended by the backstop, the answer is what the walk left, as it was.
#[skuld::test]
fn a_walk_that_left_members_stays_the_answer_when_the_backstop_killed_the_root() {
    use super::{TreeKillOutcome, Unkilled};
    let error = swept(
        TreeKillOutcome::Ran(Err(Unkilled {
            members: vec![left_by(2, CODES[0])],
            root: Some(Box::new(left_by(1, CODES[2]))),
            resolved: Vec::new(),
        })),
        Ok(()),
    );

    assert_eq!(members_of(&error), [(2, Some(CODES[0]))]);
}

// fd marker install policy (macOS) =====

/// The install policy, exhaustively: every mode installs a marker for a ROOT spawn, no
/// nested spawn ever does (it inherits the root's), no uncontained spawn does, and an
/// elevation-derived spawn does not (its `sudo` wrapper closes every descriptor >= 3).
#[cfg(target_os = "macos")]
#[skuld::test]
fn marker_wanted_installs_for_every_contained_root_and_nothing_else() {
    use crate::containment::fdmarker::marker_wanted;
    use crate::containment::ContainMode;
    for mode in [ContainMode::Strongest, ContainMode::Session, ContainMode::TreeWalk] {
        assert!(
            marker_wanted(Some(mode), true, false),
            "{mode:?} root installs a marker"
        );
        assert!(
            !marker_wanted(Some(mode), false, false),
            "{mode:?} nested inherits, never installs"
        );
        assert!(
            !marker_wanted(Some(mode), true, true),
            "{mode:?} elevated root must not install"
        );
    }
    assert!(
        !marker_wanted(None, true, false),
        "an uncontained spawn installs no marker"
    );
}

/// The marker mechanism is actionable: `kill_tree`/`terminate_tree` act on it.
#[cfg(target_os = "macos")]
#[skuld::test]
fn a_marker_tree_is_actionable() {
    use std::os::fd::{AsFd, AsRawFd};

    use crate::containment::{Containment, Mechanism, Tree};
    let (read, write) = std::io::pipe().expect("pipe");
    let handle = crate::containment::fdmarker::pipe_handle_of(write.as_fd()).expect("handle");
    let read_handle = crate::containment::fdmarker::pipe_handle_of(read.as_fd()).expect("read handle");
    let prepared = crate::containment::fdmarker::PreparedMarker {
        read: std::os::fd::OwnedFd::from(read),
        handle,
        read_handle,
        fd: write.as_fd().as_raw_fd(),
        kernel: crate::identity::spawn_kernel(crate::identity::HostKernel),
    };
    let marker = crate::containment::fdmarker::Marker::new(
        prepared,
        crate::containment::fdmarker::fdmarker_tests::inert_root(),
        None,
    );
    let tree = Tree::contained(Mechanism::Marker(marker));
    assert!(tree.require_contained().is_ok());
    assert_eq!(tree.containment(), Containment::FdMarker);
}

/// The leaf `prepare` creates for a contained Linux root holds the warn threshold its spawn's
/// policy gave it, for the waits of its own teardown (the cgroup lane: a leaf is a real directory).
///
/// Mutants: `prepare` hands `try_create_leaf` no threshold; `try_create_leaf` or `create_leaf_under`
/// stores none.
#[cfg(target_os = "linux")]
#[skuld::test]
fn prepare_creates_the_leaf_with_its_spawns_warn_threshold(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::{ContainMode, ContainRequest, Nesting};

    let threshold = std::time::Duration::from_millis(1234);
    let prepared = super::prepare(
        &mut crate::child::spawn::in_child::InChild::default(),
        &ContainRequest {
            mode: Some(ContainMode::Strongest),
            nesting: Nesting::Mark,
        },
        &crate::command::flags::FlagsRequest::default(),
        &[],
        false,
        &[],
        Some(threshold),
        &crate::identity::spawn_kernel(crate::identity::HostKernel),
    )
    .expect("prepare is infallible off Windows");

    let leaf = prepared
        .cgroup_leaf
        .as_ref()
        .expect("a contained Linux root gets a leaf");
    assert_eq!(leaf.warn().0, Some(threshold));
}

/// `prepare` must thread the caller's reserved child fds through to the placement, or a user
/// fd mapping would dup2 over the marker in the child.
#[cfg(target_os = "macos")]
#[skuld::test]
fn prepare_places_the_marker_above_the_callers_reserved_fds() {
    use crate::containment::{ContainMode, ContainRequest, Nesting};
    // `prepare` makes the marker pipe, which a spawn does under `spawn_lock`.
    let _lock = crate::child::spawn::spawn_lock();
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = super::prepare(
        &mut cmd,
        &mut crate::child::spawn::in_child::InChild::default(),
        &ContainRequest {
            mode: Some(ContainMode::Strongest),
            nesting: Nesting::Mark,
        },
        &crate::command::flags::FlagsRequest::default(),
        &[3, 4, 5, 6, 7, 8, 9, 10],
        false,
        &[],
        None,
        &crate::identity::spawn_kernel(crate::identity::HostKernel),
    )
    .expect("prepare is infallible off Windows");
    let marker = prepared.marker.as_ref().expect("a contained macOS root gets a marker");
    assert!(
        marker.fd > 10,
        "prepare placed the marker on fd {}, which a user mapping would dup2 over",
        marker.fd
    );
}

/// `prepare` for a root asking for `mode` whose marker install is made to fail.
#[cfg(target_os = "macos")]
fn prepare_with_a_failing_marker_install(
    mode: crate::containment::ContainMode,
) -> Result<super::Prepared, crate::error::Error> {
    use crate::containment::fdmarker::fault::{set_fault, Fault};
    use crate::containment::{ContainRequest, Nesting};
    let mut cmd = std::process::Command::new("/usr/bin/true");
    set_fault(Some(Fault::Pipe));
    super::prepare(
        &mut cmd,
        &mut crate::child::spawn::in_child::InChild::default(),
        &ContainRequest {
            mode: Some(mode),
            nesting: Nesting::Mark,
        },
        &crate::command::flags::FlagsRequest::default(),
        &[],
        false,
        &[],
        None,
        &crate::identity::spawn_kernel(crate::identity::HostKernel),
    )
}

/// A failed install degrades every mode but `Strongest` to the pre-existing mechanism rather than
/// failing the spawn, and says so at `warn`: `BestEffort`, and an explicit `Session` or `TreeWalk`.
#[cfg(target_os = "macos")]
#[skuld::test]
fn a_failed_marker_install_leaves_prepare_without_one_unless_strongest() {
    use crate::containment::ContainMode;
    // Held for the whole body: the warn's text has no per-call discriminator, and the `Fault::Pipe`
    // of another test's spawn emits it too (see `lock_for_log_assertion`).
    let _serialize = crate::containment::fdmarker::fault::lock_for_log_assertion();
    crate::log_capture::install();
    for mode in [ContainMode::BestEffort, ContainMode::Session, ContainMode::TreeWalk] {
        let mark = crate::log_capture::mark();
        let prepared =
            prepare_with_a_failing_marker_install(mode).unwrap_or_else(|e| panic!("{mode:?} degrades, got {e:?}"));
        assert!(
            prepared.marker.is_none(),
            "{mode:?}: the forced failure must yield no marker"
        );
        assert!(
            crate::log_capture::contains_since(mark, "fd marker: pipe() failed"),
            "{mode:?}: the fallback is logged"
        );
        assert!(
            crate::log_capture::contains_since(mark, "falling back to the pre-existing containment channel"),
            "{mode:?}: the fallback says what it fell back to"
        );
    }
}

/// `Strongest` has no mechanism below the marker to degrade to: a failed install fails the spawn,
/// naming the marker.
#[cfg(target_os = "macos")]
#[skuld::test]
fn a_failed_marker_install_fails_a_strongest_prepare() {
    let Err(error) = prepare_with_a_failing_marker_install(crate::containment::ContainMode::Strongest) else {
        panic!("a failed marker install must fail a Strongest prepare");
    };
    assert!(
        matches!(error, crate::error::Error::Containment { ref detail, .. } if detail.contains("fd marker")),
        "{error:?}"
    );
}

/// An elevation-derived spawn must not install a marker: `sudo` closes every descriptor >= 3.
#[cfg(target_os = "macos")]
#[skuld::test]
fn prepare_installs_no_marker_for_an_elevation_derived_spawn() {
    use crate::containment::{ContainMode, ContainRequest, Nesting};
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let prepared = super::prepare(
        &mut cmd,
        &mut crate::child::spawn::in_child::InChild::default(),
        &ContainRequest {
            mode: Some(ContainMode::Strongest),
            nesting: Nesting::Mark,
        },
        &crate::command::flags::FlagsRequest::default(),
        &[],
        true,
        &[],
        None,
        &crate::identity::spawn_kernel(crate::identity::HostKernel),
    )
    .expect("prepare is infallible off Windows");
    assert!(
        prepared.marker.is_none(),
        "an elevated spawn must not claim marker containment"
    );
}

/// The spawn's identity read tells an OS refusal from a vanished pid: denial must not read as
/// vanishing, and absence must not read as denial.
#[cfg(windows)]
#[skuld::test]
fn spawn_identity_distinguishes_a_denied_pid_from_a_vanished_one() {
    let Some(done) = crate::test_own_process::own_process(
        crate::test_own_process::test_path!(spawn_identity_distinguishes_a_denied_pid_from_a_vanished_one),
        crate::test_spawn::spawn,
    ) else {
        return;
    };
    use crate::child::spawn::{resolve_identity_unchecked, spawn_identity_error};
    use windows::Win32::System::Threading::PROCESS_SYNCHRONIZE;
    let child = crate::identity::windows_fixture::spawn_restricted(&done, PROCESS_SYNCHRONIZE.0);
    assert!(child.is_running(), "precondition: the subject must be live");

    let (read, cause) = resolve_identity_unchecked(&crate::identity::HostKernel, child.pid());
    let denied = spawn_identity_error(read, cause);
    assert!(
        matches!(denied, crate::error::Error::Unassessable { .. }),
        "a pid we may not query must not read as vanished: {denied:?}"
    );

    // Contrast: a pid no process holds.
    let (read, cause) = resolve_identity_unchecked(&crate::identity::HostKernel, 0xFFFF_FFF0);
    let absent = spawn_identity_error(read, cause);
    assert!(
        matches!(&absent, crate::error::Error::Io(e) if e.to_string().contains("reaped by another party")),
        "absence must not read as denial: {absent:?}"
    );
}

#[cfg(target_os = "macos")]
#[skuld::test]
fn wait_drained_is_unsupported_without_a_marker() {
    // Mirrors `require_contained`: a mechanism that cannot answer says so, rather than
    // implying a guarantee it has not got.
    use crate::containment::Tree;
    for tree in [Tree::none(), Tree::delegated()] {
        let err = tree
            .wait_drained(None)
            .expect_err("a mechanism with no drain edge must be Unsupported");
        assert!(matches!(err, crate::error::Error::Unsupported { .. }), "got {err:?}");
    }
}

#[cfg(target_os = "macos")]
#[skuld::test]
fn wait_drained_reports_members_remain_then_all_markers_closed() {
    use crate::containment::fdmarker::{pipe_handle_of, Marker, PreparedMarker};
    use crate::containment::{Mechanism, Tree, TreeDrain};
    use std::os::fd::{AsFd, OwnedFd};

    // A real holder in a separate process, mirroring marker_eof_tests.rs's
    // spawn_marker_holder: the marker's write end lives in the child, not in-process, so
    // wait_drained observes a genuinely open, then genuinely closed, write end.
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.executable("/bin/sh").args(["sh", "-c", "exec cat >/dev/null"]);
    cmd.fd(0, crate::Stdio::pipe_in()).expect("stdin pipe");
    cmd.fd(3, crate::Stdio::pipe_out()).expect("marker pipe");
    let mut child = cmd.spawn().expect("spawn /bin/sh");
    let marker = child.fd_read_end(3.into()).expect("marker read end");
    let stdin = child.fd_write_end(crate::Fd::STDIN).expect("stdin write end");

    // wait_drained now consults read_handle too (Marker::wait_drained calls
    // check_read_end_still_valid first, same as hard_kill/terminate) — so this uses the read
    // end's REAL current handle for both fields, standing in for install()'s full write-end
    // capture sequence without replicating it.
    let handle = pipe_handle_of(marker.as_fd()).expect("handle");
    let prepared = PreparedMarker {
        read: OwnedFd::from(marker),
        handle,
        read_handle: handle,
        fd: 3,
        kernel: crate::identity::spawn_kernel(crate::identity::HostKernel),
    };
    let tree = Tree::contained(Mechanism::Marker(Marker::new(
        prepared,
        crate::containment::fdmarker::fdmarker_tests::inert_root(),
        None,
    )));
    let edge = tree.drain_edge().expect("a marker has a drain edge");

    assert_eq!(
        edge.wait(Some(std::time::Instant::now()))
            .expect("bounded wait while the holder is alive"),
        TreeDrain::MembersRemain
    );

    drop(stdin); // cat's stdin EOFs, so cat exits, closing its inherited marker write end
    child.wait().expect("reap");

    assert_eq!(
        edge.wait(None).expect("unbounded wait after the holder exits"),
        TreeDrain::AllMarkersClosed
    );
}

/// The UAC-elevated attachment bypasses `mechanism_from_flags` entirely — nothing in the flag
/// matrix covers it — so its three fields are pinned here. `Unknown`, not the `None` a flagless
/// spawn yields nor the `OtherConsoleGroup` a suppressed one does: a copy-paste of either must
/// fail. What the dispatcher then does with the value is
/// `signal_refuses_a_child_cosca_did_not_create`, in `src/graceful_tests.rs`.
#[cfg(windows)]
#[skuld::test]
fn uac_elevated_attachment_has_no_in_process_route() {
    use super::Attachment;
    use crate::containment::Containment;
    use crate::graceful::GracefulMechanism;

    let a = Attachment::uac_elevated();
    assert_eq!(a.tree.containment(), Containment::None);
    assert_eq!(a.graceful, GracefulMechanism::Unknown);
}

// The cgroup placement decision =====
// `attach_tree` decides whether a Strongest root's leaf owns its tree. The child's own
// self-placement report is the oracle: a later `cgroup.procs` read lists only LIVE tasks, so a
// placed child that has already exited reads back as absent. Real filesystem, no cgroupfs: each
// leaf is a temp directory shaped with ordinary files. These tests are about what the decision
// does with a report, not how a child earns one: a failed write is made for real, in-process,
// but `Placed` is stored directly, since a successful write to anything but a real `cgroup.procs`
// is the very false report the live cgroup lane guards against.

/// What the child's `pre_exec` closure reported, if it ran at all.
#[cfg(target_os = "linux")]
#[derive(Clone, Copy)]
enum ChildReport {
    Placed,
    WriteFailed,
    /// The write failed with this errno, which the child reported.
    WriteFailedWith(i32),
    NotReported,
    /// The spawn could not read the child's status channel (this errno), so what the child reported is
    /// not known.
    Unknown(i32),
}

/// Run the decision for a leaf at `leaf_path` whose child reported `report`, for a root that asked
/// for `Strongest`.
#[cfg(target_os = "linux")]
fn decide(leaf_path: &std::path::Path, report: ChildReport) -> crate::containment::Tree {
    decide_for(crate::containment::ContainMode::Strongest, leaf_path, report).expect("attach_tree")
}

/// [`decide`] for a root that asked for `mode`: the decision, which may be a failed attach.
#[cfg(target_os = "linux")]
fn decide_for(
    mode: crate::containment::ContainMode,
    leaf_path: &std::path::Path,
    report: ChildReport,
) -> Result<crate::containment::Tree, super::AttachFailure> {
    use crate::containment::cgroup::{CgroupLeaf, PlacementReport};

    let mut leaf = CgroupLeaf::for_test_at(leaf_path.to_path_buf());
    match report {
        ChildReport::Placed => leaf.record_placement(PlacementReport::Placed),
        ChildReport::WriteFailed => leaf.record_placement(PlacementReport::WriteFailed(libc::EBADF)),
        ChildReport::WriteFailedWith(errno) => leaf.record_placement(PlacementReport::WriteFailed(errno)),
        ChildReport::Unknown(errno) => leaf.record_placement(PlacementReport::Unknown(errno)),
        ChildReport::NotReported => {}
    }
    let prepared = super::Prepared {
        mode: Some(mode),
        is_root: true,
        cgroup_leaf: Some(leaf),
    };
    super::attach_tree(
        std::process::id(),
        Ok(crate::identity::ProcessId::current()),
        crate::containment::cgroup::test_support::handle_of(
            std::process::id(),
            &crate::containment::cgroup::test_support::pidfd_of(std::process::id()),
        ),
        prepared,
    )
}

/// A leaf directory whose `cgroup.procs` lists some OTHER pid, never this test's.
#[cfg(target_os = "linux")]
fn leaf_listing_another_pid(dir: &std::path::Path) -> std::path::PathBuf {
    let leaf_path = dir.join("cosca-decision-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let other = std::process::id().wrapping_add(1);
    std::fs::write(leaf_path.join("cgroup.procs"), format!("{other}\n")).expect("write cgroup.procs");
    leaf_path
}

/// A child that reported its write accepted, and has since exited: `cgroup.procs` no longer
/// lists it. Anything it forked is still in the leaf, so the leaf owns the tree.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn a_placed_report_outranks_a_cgroup_procs_that_omits_the_child() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = leaf_listing_another_pid(dir.path());

    let tree = decide(&leaf_path, ChildReport::Placed);

    assert_eq!(tree.containment(), crate::containment::Containment::CgroupV2);
    let Some(leaf) = tree.cgroup_leaf_for_test() else {
        panic!("got {tree:?}");
    };
    assert!(
        !leaf.holds_spawn_resources(),
        "a live child's leaf must not hold its cgroup.procs fd or report pipe past the verdict"
    );
    assert!(
        !leaf_path.join("cgroup.kill").exists(),
        "the leaf owns a live tree; nothing may kill it at spawn time"
    );
}

/// Membership that cannot be read is unknown, not absent — and the child's own report already
/// answers it.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn a_placed_report_outranks_an_unreadable_cgroup_procs() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-decision-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf (no cgroup.procs inside)");

    let tree = decide(&leaf_path, ChildReport::Placed);

    assert_eq!(tree.containment(), crate::containment::Containment::CgroupV2);
    assert!(tree.cgroup_leaf_for_test().is_some(), "got {tree:?}");
}

/// A child whose write failed never entered the leaf, so neither did anything it forked: a
/// `BestEffort` spawn degrades and the empty leaf is removed.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_write_degrades_a_best_effort_spawn_and_removes_the_leaf() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-decision-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");

    let tree = decide_for(
        crate::containment::ContainMode::BestEffort,
        &leaf_path,
        ChildReport::WriteFailed,
    )
    .expect("attach_tree");

    assert_eq!(tree.containment(), crate::containment::Containment::ProcessGroup);
    assert!(tree.signals_a_group_for_test(), "got {tree:?}");
    assert!(!leaf_path.exists(), "the degrade must remove the leaf it created");
}

/// The same child under `Strongest`: the attach fails as a spawn that did not start (the program
/// never ran: the child's report proves it), the error names the leaf and says this layer only, and
/// keeps the placement write's errno as its source, with the unreadable `cgroup.procs` of the diagnosis
/// beside it as a second cause, and the empty leaf is removed. The diagnosis itself goes to the debug
/// log. The failed attach's teardown ends the child.
///
/// Mutants: the detail carries the OS words or the errno; the errno is not the first cause; the
/// failed diagnosis read is dropped; the diagnosis is not logged; the failure is not a not-started
/// one.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_write_fails_a_strongest_attach_and_removes_the_leaf() {
    crate::log_capture::install();
    for errno in [libc::EBADF, libc::EBUSY, libc::EPERM] {
        let dir = tempfile::tempdir().expect("tempdir");
        let leaf_path = dir.path().join("cosca-decision-leaf");
        std::fs::create_dir(&leaf_path).expect("create the leaf");
        let mark = crate::log_capture::mark();

        let failure = decide_for(
            crate::containment::ContainMode::Strongest,
            &leaf_path,
            ChildReport::WriteFailedWith(errno),
        )
        .expect_err("a Strongest root the leaf did not take fails its attach");

        assert!(failure.not_started, "the program never ran: {failure:?}");
        let crate::error::Error::Containment { detail, .. } = &failure.cause else {
            panic!("{failure:?}");
        };
        assert_eq!(
            detail,
            &format!(
                "cgroup v2: the child could not be placed in its leaf cgroup {}, so the program did not run",
                leaf_path.display()
            ),
            "the detail says only this layer: the errno and its words are the source's"
        );
        assert_eq!(crate::error::first_os_code(&failure.cause), Some(errno));
        // The leaf has no `cgroup.procs`, so the diagnosis read failed too: its error is a second
        // cause beside the write's, not lost.
        let causes: Vec<Option<i32>> = failure
            .cause
            .failures_below()
            .into_iter()
            .map(|cause| match cause {
                crate::error::Error::Io(e) => e.raw_os_error(),
                other => panic!("a cause that is not an OS error: {other:?}"),
            })
            .collect();
        assert_eq!(causes, [Some(errno), Some(libc::ENOENT)]);
        let logs = crate::log_capture::records_since_on_current_thread(mark, "is not in the leaf cgroup");
        assert!(
            logs.iter()
                .any(|(level, said)| *level == log::Level::Debug && said.contains("could not be read")),
            "the diagnosis is logged at debug: {logs:?}"
        );
        assert!(!leaf_path.exists(), "the failed attach must remove the leaf it created");
    }
}

/// A child that sent no report never ran the program, whatever the mode: the attach fails as one
/// that did not start, saying that no report came (not that the child "could not be placed"), with
/// no write errno beneath it, and the leaf is removed. The leaf here has no `cgroup.procs`, so the
/// diagnosis read failed: its error is the one cause, as for a failed write.
///
/// Mutants: `BestEffort` degrades it, the text says the placement failed, it has a write errno as a
/// source, or the failed diagnosis read is dropped.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_unreported_child_fails_the_attach_in_every_mode() {
    for mode in [
        crate::containment::ContainMode::Strongest,
        crate::containment::ContainMode::BestEffort,
    ] {
        let dir = tempfile::tempdir().expect("tempdir");
        let leaf_path = dir.path().join("cosca-decision-leaf");
        std::fs::create_dir(&leaf_path).expect("create the leaf");

        let failure = decide_for(mode, &leaf_path, ChildReport::NotReported)
            .expect_err("a child that sent no report never ran, so the spawn fails");

        assert!(failure.not_started, "{mode:?}: the program never ran: {failure:?}");
        let crate::error::Error::Containment { detail, source } = &failure.cause else {
            panic!("{mode:?}: {failure:?}");
        };
        assert_eq!(
            detail,
            &format!(
                "cgroup v2: the child did not report its placement in leaf cgroup {}, so the program did not run",
                leaf_path.display()
            ),
            "{mode:?}"
        );
        assert!(
            matches!(source.as_deref(), Some(crate::error::Error::Io(e)) if e.raw_os_error() == Some(libc::ENOENT)),
            "{mode:?}: {source:?}"
        );
        assert!(!leaf_path.exists(), "{mode:?}: the failed attach must remove the leaf");
    }
}

/// A child whose report the spawn could not read may or may not be in its leaf (and, under `BestEffort`,
/// in the process group instead), so the attach builds no containment on it, in any mode: it fails as a
/// spawn that may have started, naming the leaf and keeping the read's errno as its source, and the leaf is
/// killed through, since nothing proves it holds nothing of the child's.
///
/// Mutants: the attach builds the cgroup tree on it (`Ok`); a `BestEffort` attach degrades to the process
/// group and removes the leaf unkilled; the failure is a not-started one; the leaf is not written
/// `cgroup.kill`; the read's errno is lost; the child's process group is not killed (a `BestEffort`
/// child that exec'd outside the leaf may have forked into it); a refused group kill is dropped
/// instead of going into the failure's `cleanup`.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn an_unreadable_report_fails_the_attach_and_kills_through_the_leaf() {
    for mode in [
        crate::containment::ContainMode::Strongest,
        crate::containment::ContainMode::BestEffort,
    ] {
        let dir = tempfile::tempdir().expect("tempdir");
        let leaf_path = occupied_leaf_for_test(dir.path(), "cosca-unknown-report-leaf");

        // The test's own process stands in for the child: its group is not sent anything, the kernel's
        // refusal is answered in its place.
        let refused = crate::containment::unix::fault::refuse_group_sends();
        let capture = crate::send_log::Capture::start();
        let failure = decide_for(mode, &leaf_path, ChildReport::Unknown(libc::EISDIR))
            .expect_err("a child whose placement is unknown has no containment built on it");
        let steps = capture.group_steps();
        drop((refused, capture));

        assert_eq!(
            steps,
            [crate::send_log::GroupStep::Group(
                crate::send_log::Route::Pidfd,
                libc::SIGKILL
            )],
            "{mode:?}: the child's process group is killed through its pidfd"
        );
        let cleanup = failure
            .cleanup
            .as_ref()
            .expect("the refused group kill is the cleanup's");
        assert_eq!(cleanup.iter().len(), 1, "{mode:?}: {cleanup:?}");
        assert_eq!(
            crate::error::first_os_code(cleanup.first().as_ref()),
            Some(libc::EPERM),
            "{mode:?}: {cleanup:?}"
        );

        assert!(!failure.not_started, "{mode:?}: the program may have run: {failure:?}");
        let crate::error::Error::Containment { detail, .. } = &failure.cause else {
            panic!("{mode:?}: {failure:?}");
        };
        assert_eq!(
            detail,
            &format!(
                "cgroup v2: the spawn could not read the child's status channel, so it is not known whether \
                 the child entered its leaf cgroup {}; the child is torn down",
                leaf_path.display()
            ),
            "{mode:?}"
        );
        assert_eq!(
            crate::error::first_os_code(&failure.cause),
            Some(libc::EISDIR),
            "{mode:?}"
        );
        assert_eq!(
            std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
            b"1",
            "{mode:?}: the leaf is killed through: nothing proves it holds nothing of the child's"
        );
    }
}

/// A child whose placement is unknown may be in its process group as well as in its leaf, so the group is
/// its containment too: a failed spawn's group kill is owed (`group_is_containment`), where a child
/// the leaf provably holds is the leaf's alone.
///
/// Mutant: an unknown placement is taken as the leaf's.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_child_of_unknown_placement_has_its_group_as_containment() {
    use crate::containment::cgroup::{CgroupLeaf, PlacementReport};

    for (report, group_is_containment) in [
        (PlacementReport::Placed, false),
        (PlacementReport::Unknown(libc::EIO), true),
    ] {
        let dir = tempfile::tempdir().expect("tempdir");
        let leaf_path = dir.path().join("cosca-group-leaf");
        std::fs::create_dir(&leaf_path).expect("create the leaf");
        let mut leaf = CgroupLeaf::for_test_at(leaf_path);
        leaf.record_placement(report);
        let mut prepared = super::Prepared {
            mode: Some(crate::containment::ContainMode::BestEffort),
            is_root: true,
            cgroup_leaf: Some(leaf),
        };
        let pidfd = crate::containment::cgroup::test_support::pidfd_of(std::process::id());
        let handle = crate::containment::cgroup::test_support::handle_of(std::process::id(), &pidfd);
        // This test's own process stands in for the child: the verdict is taken, nothing is signalled.
        prepared.settle_verdict(handle);
        assert_eq!(prepared.group_is_containment(), group_is_containment, "{report:?}");
    }
}

/// Removing a leaf the child never entered must never write `cgroup.kill`, even when the leaf
/// will not go away: whatever is in it, cosca did not put there. The leaf left behind is
/// reported. A failed write degrades under `BestEffort`; a child that sent no report fails the
/// attach, and its leaf is left alone the same way.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_degrade_never_kills_through_the_leaf() {
    crate::log_capture::install();
    for report in [ChildReport::WriteFailed, ChildReport::NotReported] {
        let dir = tempfile::tempdir().expect("tempdir");
        // A `cgroup.procs` file makes the directory non-empty, so its `rmdir` fails.
        let leaf_path = leaf_listing_another_pid(dir.path());

        let mark = crate::log_capture::mark();
        let decided = decide_for(crate::containment::ContainMode::BestEffort, &leaf_path, report);

        match (report, decided) {
            (ChildReport::WriteFailed, Ok(tree)) => {
                assert_eq!(tree.containment(), crate::containment::Containment::ProcessGroup);
            }
            (ChildReport::NotReported, Err(failure)) => assert!(failure.not_started, "{failure:?}"),
            (_, other) => panic!("not the answer for this report: {other:?}"),
        }
        assert!(
            !leaf_path.join("cgroup.kill").exists(),
            "a degrade wrote cgroup.kill: it would kill a tree cosca had just been asked to contain"
        );
        let left_behind: Vec<String> = crate::log_capture::records_since(mark, &leaf_path.to_string_lossy())
            .into_iter()
            .filter(|record| record.contains("was not removed"))
            .collect();
        assert_eq!(
            left_behind.len(),
            1,
            "the unremoved leaf is reported once: {left_behind:?}"
        );
    }
}

// kill_on_drop's reach into the containment resource =====
// See `Tree::honor_kill_on_drop`.

/// A leaf standing in for a live contained tree: occupied (so `rmdir` fails and `Drop` would
/// reach for `cgroup.kill`) and carrying an empty `cgroup.kill` to read the write back from.
#[cfg(target_os = "linux")]
fn occupied_leaf_for_test(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
    let leaf_path = dir.join(name);
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    std::fs::write(leaf_path.join("occupant"), "").expect("stand in for the live tree");
    std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
    leaf_path
}

#[cfg(target_os = "linux")]
fn cgroup_tree_for_test(leaf_path: &std::path::Path) -> crate::containment::Tree {
    crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(
        crate::containment::cgroup::test_support::entered_leaf_at(leaf_path.to_path_buf()),
    ))
}

/// `kill_on_drop(false)` must disarm the cgroup leaf. Without it the handle's own teardown is
/// skipped and the leaf's `Drop` kills the tree anyway — the opposite of the opt-out.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn kill_on_drop_false_disarms_a_cgroup_leaf() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = occupied_leaf_for_test(dir.path(), "cosca-kill-on-drop-false-leaf");

    let tree = cgroup_tree_for_test(&leaf_path);
    tree.honor_kill_on_drop(false).expect("disarm");
    drop(tree);

    assert_eq!(
        std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
        b"",
        "kill_on_drop(false) opts out of the teardown; a tree it killed anyway is the opposite"
    );
}

/// The same leaf under `kill_on_drop(true)` DOES fire `cgroup.kill`, so the test above pins
/// the disarm rather than an inert path.
#[cfg(target_os = "linux")]
#[skuld::test(labels = [crate::test_harness::CGROUP])]
fn kill_on_drop_true_leaves_a_cgroup_leaf_armed() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = occupied_leaf_for_test(dir.path(), "cosca-kill-on-drop-true-leaf");

    let tree = cgroup_tree_for_test(&leaf_path);
    tree.honor_kill_on_drop(true).expect("nothing to disarm");
    drop(tree);

    assert_eq!(
        std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
        b"1",
        "the default is still a kill-on-drop teardown"
    );
}

// ===== frozen attach (Windows) =====

#[cfg(windows)]
mod frozen_attach {
    use crate::containment::dispatch::{attach, Attachment, Prepared};
    use crate::containment::windows::fault::{force_next, Step};
    use crate::containment::{ContainMode, Containment};
    use crate::error::Error;
    use crate::test_frozen::{
        assert_not_released, limit_flags, raw, release, spawn_suspended_blocker, spawn_suspended_releasable,
        InitialThread,
    };
    use windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

    const ERROR_ACCESS_DENIED: u32 = 5;
    const ERROR_INVALID_HANDLE: u32 = 6;

    fn prepared(mode: Option<ContainMode>, is_root: bool, frozen: bool) -> Prepared {
        Prepared {
            mode,
            is_root,
            graceful: crate::graceful::GracefulMechanism::None,
            frozen,
        }
    }

    fn attach_suspended(child: &std::process::Child, prepared: Prepared) -> Result<Attachment, Error> {
        let crate::identity::Resolved::Found(id) = crate::identity::ProcessId::of(child.id()) else {
            panic!("the suspended child must be readable");
        };
        attach(Ok(id), raw(child), prepared).map_err(|failure| failure.cause)
    }

    /// The identity read the OS refused, as the spawn hands it to the attach.
    fn refused_identity() -> Error {
        Error::Unassessable {
            detail: "the OS refused to report the spawned child's identity".into(),
            source: None,
        }
    }

    /// A job needs no identity: a Strongest root whose identity could not be read still gets one.
    ///
    /// Mutant: the attach fails early for want of an identity, whatever the mechanism.
    #[skuld::test]
    fn attach_assigns_a_strongest_roots_job_though_its_identity_could_not_be_read() {
        let child = spawn_suspended_blocker();
        let prepared = prepared(Some(ContainMode::Strongest), true, false);

        let attachment = attach(Err(refused_identity()), raw(&child), prepared).expect("attach");

        assert_eq!(attachment.tree.containment(), Containment::JobObject);
        drop(attachment);
    }

    /// A tree walk names its tree by the root's identity, so it fails the attach with the read's error.
    ///
    /// Mutant: the attach succeeds with a tree walk that has no root.
    #[skuld::test]
    fn attach_fails_a_tree_walk_root_with_the_identity_reads_error() {
        let child = spawn_suspended_blocker();

        let err = attach(
            Err(refused_identity()),
            raw(&child),
            prepared(Some(ContainMode::TreeWalk), true, false),
        )
        .err()
        .expect("a tree walk without an identity must fail the attach")
        .cause;

        assert!(matches!(err, Error::Unassessable { source: None, .. }), "got {err:?}");
    }

    /// A frozen Strongest root is assigned its containment job and stays suspended.
    #[skuld::test]
    fn death_watch_attach_frozen_assigns_a_strongest_roots_job_and_leaves_the_thread_suspended() {
        let mut child = spawn_suspended_releasable();
        let thread = InitialThread::of(child.id());

        let attachment = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, true)).expect("attach");

        assert_eq!(attachment.tree.containment(), Containment::JobObject);
        let Some(job) = attachment.tree.job_for_test() else {
            panic!("expected a job, got {:?}", attachment.tree);
        };
        assert_ne!(
            limit_flags(job).0 & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.0,
            0,
            "the job must kill on close: the frozen child never runs, so nothing else ends it"
        );
        assert_eq!(thread.suspend_count(), 1, "a frozen attach must not resume");
        drop(attachment);
        // The close's kill ended it. A close that killed nothing leaves a frozen child that never
        // runs, so it is released to run to its end, which `assert_not_released` rejects.
        release(&mut child, &thread);
        assert_not_released("the frozen child", child.wait().expect("reap the frozen child"));
    }

    /// A frozen root needs its job to be held, so a failed assignment fails the attach instead of
    /// falling back to `TreeWalk`, which would leave nothing to kill it.
    #[skuld::test]
    fn attach_frozen_fails_when_the_strongest_assignment_fails_instead_of_falling_back_to_treewalk() {
        let child = spawn_suspended_blocker();
        let _forced = force_next(Step::Assign, ERROR_ACCESS_DENIED);

        let err = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, true))
            .err()
            .expect("a frozen attach with no job must fail");

        let Error::Containment { detail, .. } = &err else {
            panic!("got {err:?}");
        };
        assert_eq!(
            crate::error::first_os_code(&err),
            Some(ERROR_ACCESS_DENIED as i32),
            "{err:?}"
        );
        let os_text = std::io::Error::from_raw_os_error(ERROR_ACCESS_DENIED as i32).to_string();
        assert!(!detail.contains(&os_text), "{detail}");
    }

    /// A frozen root whose initial thread cannot be resumed fails the attach with the OS error as the
    /// source, and not in the text.
    #[skuld::test]
    fn attach_whose_resume_fails_has_the_win32_error_as_its_source() {
        let child = spawn_suspended_blocker();
        let _forced = force_next(Step::Resume, ERROR_INVALID_HANDLE);

        let err = attach_suspended(&child, prepared(Some(ContainMode::Strongest), true, false))
            .err()
            .expect("an attach whose resume fails must fail");

        let Error::Containment { detail, .. } = &err else {
            panic!("got {err:?}");
        };
        assert_eq!(
            crate::error::first_os_code(&err),
            Some(ERROR_INVALID_HANDLE as i32),
            "{err:?}"
        );
        let os_text = std::io::Error::from_raw_os_error(ERROR_INVALID_HANDLE as i32).to_string();
        assert!(!detail.contains(&os_text), "{detail}");
    }

    /// The attach of `child`, whose failure is returned whole.
    fn attach_failure_of(
        child: &std::process::Child,
        prepared: Prepared,
    ) -> crate::containment::dispatch::AttachFailure {
        let crate::identity::Resolved::Found(id) = crate::identity::ProcessId::of(child.id()) else {
            panic!("the suspended child must be readable");
        };
        attach(Ok(id), raw(child), prepared)
            .err()
            .expect("the attach was forced to fail")
    }

    /// `Strongest` (and `Session`, which Windows treats as `Strongest`) is a Job Object or an error:
    /// a failed assignment fails the attach as one that proves the program never ran, with the OS
    /// error as the source. The child is not resumed, and the failure holds the proof's suspend (count
    /// 2, the creator's and the proof's) until it is dropped, which resumes nothing: the caller ends the
    /// process while it is still frozen.
    ///
    /// Mutants: the attach resumes the child before it fails, or when the failure is dropped; it falls
    /// back to `TreeWalk`; the failure is not marked not started; the OS error is dropped or goes into
    /// the text.
    #[skuld::test]
    fn attach_fails_a_strict_root_whose_job_assignment_fails_without_resuming_it() {
        for mode in [ContainMode::Strongest, ContainMode::Session] {
            let child = spawn_suspended_blocker();
            let thread = InitialThread::of(child.id());
            let _forced = force_next(Step::Assign, ERROR_ACCESS_DENIED);

            let failure = attach_failure_of(&child, prepared(Some(mode), true, false));

            assert!(failure.not_started, "{mode:?}: the program never ran: {failure:?}");
            assert!(failure.cleanup.is_none(), "{mode:?}: {failure:?}");
            let Error::Containment { detail, .. } = &failure.cause else {
                panic!("{mode:?}: got {:?}", failure.cause);
            };
            assert!(
                detail.contains("Job Object"),
                "{mode:?}: the error names the Job: {detail}"
            );
            assert_eq!(
                crate::error::first_os_code(&failure.cause),
                Some(ERROR_ACCESS_DENIED as i32),
                "{mode:?}: {:?}",
                failure.cause
            );
            let os_text = std::io::Error::from_raw_os_error(ERROR_ACCESS_DENIED as i32).to_string();
            assert!(!detail.contains(&os_text), "{mode:?}: {detail}");
            assert_eq!(
                thread.suspend_count(),
                2,
                "{mode:?}: the child must not be resumed, and the failure holds the proof's suspend"
            );
            drop(failure);
            assert_eq!(
                thread.suspend_count(),
                2,
                "{mode:?}: dropping the failure resumes nothing"
            );
        }
    }

    /// A strict root that something resumed before the failed assignment fails the attach as one that
    /// may have started: not marked not started, nothing held, and the read's suspend undone.
    ///
    /// Mutant: the attach answers not started from the root's state before the read.
    #[skuld::test]
    fn attach_fails_a_strict_root_that_was_resumed_as_one_that_may_have_started() {
        let child = spawn_suspended_blocker();
        let thread = InitialThread::of(child.id());
        assert_eq!(thread.release_one(), 1);
        let _forced = force_next(Step::Assign, ERROR_ACCESS_DENIED);

        let failure = attach_failure_of(&child, prepared(Some(ContainMode::Strongest), true, false));

        assert!(!failure.not_started, "{failure:?}");
        assert!(failure.proven.is_none(), "{failure:?}");
        let Error::Containment { detail, .. } = &failure.cause else {
            panic!("got {:?}", failure.cause);
        };
        assert!(!detail.contains("did not run"), "{detail}");
        assert_eq!(thread.suspend_count(), 0, "the read's suspend was undone");
    }

    /// `BestEffort` is the ordinary attach: it resumes, a failed assignment degrades to `TreeWalk`,
    /// and the degrade is said at `warn`, naming the Job Object and the OS error.
    ///
    /// Mutants: the degrade is silent; the warn leaves the OS error out.
    #[skuld::test]
    fn attach_under_best_effort_resumes_falls_back_to_treewalk_and_warns() {
        crate::log_capture::install();
        let child = spawn_suspended_blocker();
        let thread = InitialThread::of(child.id());
        let _forced = force_next(Step::Assign, ERROR_ACCESS_DENIED);
        let mark = crate::log_capture::mark();

        let attachment =
            attach_suspended(&child, prepared(Some(ContainMode::BestEffort), true, false)).expect("attach");

        assert_eq!(attachment.tree.containment(), Containment::TreeWalk);
        assert_eq!(thread.suspend_count(), 0, "the ordinary attach resumes the child");
        let warns = crate::log_capture::warns_since(mark, "Job Object");
        assert_eq!(warns.len(), 1, "{warns:?}");
        let os_text = std::io::Error::from_raw_os_error(ERROR_ACCESS_DENIED as i32).to_string();
        assert!(warns[0].contains(&os_text), "the warn names the OS error: {warns:?}");
    }

    /// Every shape without a cosca job of its own (`TreeWalk` root, nested member, uncontained) is
    /// left frozen and unjobbed: `attach` adds no job and keeps the containment it would report if
    /// the child were not frozen.
    #[skuld::test]
    fn attach_frozen_gives_treewalk_nested_and_uncontained_shapes_no_job_and_leaves_them_suspended() {
        let shapes = [
            (
                "treewalk root",
                Some(ContainMode::TreeWalk),
                true,
                Containment::TreeWalk,
            ),
            (
                "nested strongest member",
                Some(ContainMode::Strongest),
                false,
                Containment::Delegated,
            ),
            (
                "nested treewalk member",
                Some(ContainMode::TreeWalk),
                false,
                Containment::Delegated,
            ),
            ("uncontained", None, false, Containment::None),
        ];
        for (name, mode, is_root, expected) in shapes {
            let child = spawn_suspended_blocker();
            let thread = InitialThread::of(child.id());

            let attachment = attach_suspended(&child, prepared(mode, is_root, true)).expect(name);

            assert_eq!(attachment.tree.containment(), expected, "{name}");
            assert!(attachment.tree.job_for_test().is_none(), "{name}: no job of its own");
            assert_eq!(thread.suspend_count(), 1, "{name}: a frozen attach must not resume");
            drop(attachment);
        }
    }
}