cosca 0.8.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
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
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
#[cfg(target_os = "linux")]
use std::os::fd::AsFd as _;

use crate::containment::cgroup::test_support::{
    block_on, childs_copy, entered_leaf_at, fork_running, handle_of, pidfd_of,
};
use crate::containment::cgroup::{DrainStep, LeafError, NotEntered, NotPlaced, PlacementReport, WithoutChild};
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, Group};

// removed_after_drain tests -----
// Linux-only: the function itself is `#[cfg(target_os = "linux")]` (it interprets raw kernel
// errno values that only mean anything against a real cgroupfs).

/// `ENODEV` — a syscall through an fd opened before the leaf was removed, once the kernel
/// deactivates the underlying kernfs node — is proof of drain.
#[cfg(target_os = "linux")]
#[skuld::test]
fn enodev_is_removed_after_drain() {
    let e = std::io::Error::from_raw_os_error(libc::ENODEV);
    assert!(crate::containment::cgroup::removed_after_drain(&e));
}

/// `ENOENT` — a fresh `open` through the now-unlinked leaf directory — is proof of drain too.
#[cfg(target_os = "linux")]
#[skuld::test]
fn enoent_is_removed_after_drain() {
    let e = std::io::Error::from_raw_os_error(libc::ENOENT);
    assert!(crate::containment::cgroup::removed_after_drain(&e));
}

/// Every other errno is a genuine failure, not proof of anything — must NOT be folded into a
/// guessed drain verdict. `EACCES` (permission denied) and `EIO` (real device/backing-store
/// failure) are both plausible `cgroup.events` failures unrelated to removal.
#[cfg(target_os = "linux")]
#[skuld::test]
fn unrelated_errnos_are_not_removed_after_drain() {
    for errno in [libc::EACCES, libc::EIO, libc::EBUSY, libc::EPERM] {
        let e = std::io::Error::from_raw_os_error(errno);
        assert!(
            !crate::containment::cgroup::removed_after_drain(&e),
            "errno {errno} must not be classified as proof of drain"
        );
    }
}

// drain_step's Block carries the caller's own deadline, not a computed duration -----
// A `FakeLeaf`, no COSCA_TEST_CGROUP needed.

/// `Block` carries the caller's deadline instant unchanged, so the wait can arm against it
/// directly. Structural: no clock or thread needed.
#[cfg(target_os = "linux")]
#[skuld::test]
fn drain_step_block_carries_the_original_deadline_instant() {
    use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
    use std::time::{Duration, Instant};

    let fake = FakeLeaf::new("cosca-drain-step-block-deadline", true);
    let leaf = entered_leaf_at(fake.leaf.clone());
    // Disarmed: the fake never drains, so an armed Drop would block forever.
    leaf.disarm();

    // An hour out: a populated leaf never takes the zero-remaining shortcut.
    let at = Instant::now() + Duration::from_secs(3600);
    for (deadline, expected) in [(Some(at), Some(at)), (None, None)] {
        match leaf.drain_step(deadline).expect("drain_step") {
            DrainStep::Block { deadline, .. } => {
                assert_eq!(
                    deadline, expected,
                    "Block must carry the caller's deadline instant unchanged"
                )
            }
            DrainStep::Done(_) => {
                panic!("expected Block for {deadline:?}: a populated fake leaf must not shortcut to Done")
            }
        }
    }

    // Already past: the zero-remaining shortcut, not a `Block` carrying a stale instant.
    let past = Instant::now().checked_sub(Duration::from_secs(1)).unwrap();
    match leaf.drain_step(Some(past)).expect("drain_step") {
        DrainStep::Done(crate::containment::TreeDrain::MembersRemain) => {}
        DrainStep::Done(other) => {
            panic!("expected Done(MembersRemain) for an already-expired deadline, got Done({other:?})")
        }
        DrainStep::Block { .. } => {
            panic!("expected Done(MembersRemain) for an already-expired deadline, got Block")
        }
    }
}

/// The zero-remaining shortcut's own boundary, pinned exactly through `drain_step` itself (not
/// just `remaining` in isolation, which does not prove this consumer reads it the same way), via
/// the frozen test clock rather than a real one: one nanosecond before the deadline still takes
/// `Block`; at the deadline takes the shortcut.
#[cfg(target_os = "linux")]
#[skuld::test]
fn drain_step_pins_the_exact_zero_remaining_boundary() {
    use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
    use std::time::Duration;

    let fake = FakeLeaf::new("cosca-drain-step-zero-boundary", true);
    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();

    let (_guard, t0) = crate::wait::test_clock::FrozenClockGuard::install();
    let at = t0 + Duration::from_secs(3600);
    let deadline = Some(at);

    crate::wait::test_clock::advance(Duration::from_secs(3600) - Duration::from_nanos(1));
    match leaf.drain_step(deadline).expect("drain_step") {
        DrainStep::Block { .. } => {}
        DrainStep::Done(_) => panic!("1ns before the deadline must still take Block, not the shortcut"),
    }

    crate::wait::test_clock::advance(Duration::from_nanos(1));
    match leaf.drain_step(deadline).expect("drain_step") {
        DrainStep::Done(crate::containment::TreeDrain::MembersRemain) => {}
        DrainStep::Done(other) => {
            panic!("at the deadline exactly, expected Done(MembersRemain), got Done({other:?})")
        }
        DrainStep::Block { .. } => {
            panic!("at the deadline exactly, drain_step must take the zero-remaining shortcut, not Block")
        }
    }
}

/// `wait_drained`'s bounded arm, driven end to end on a `FakeLeaf` (no cgroup needed): a
/// populated leaf that never drains must answer `MembersRemain` no earlier than the caller's own
/// deadline. No upper bound is asserted — only that it never answers early.
#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_drained_through_wait_deadline_never_answers_early() {
    use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf, WaitDeadlineArgGuard};
    use crate::containment::TreeDrain;
    use std::time::{Duration, Instant};

    let fake = FakeLeaf::new("cosca-wait-drained-fakeleaf-bounded", true);
    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();

    const BOUND: Duration = Duration::from_millis(50);
    let start = Instant::now();
    let deadline = start + BOUND;
    let (_guard, armed_rx) = WaitDeadlineArgGuard::install();
    let result = leaf.wait_drained(Some(deadline)).expect("wait_drained");
    let elapsed = start.elapsed();

    assert_eq!(
        result,
        TreeDrain::MembersRemain,
        "a populated leaf that never drains must report MembersRemain once its deadline passes"
    );
    assert!(
        elapsed >= BOUND,
        "wait_drained returned after {elapsed:?}, before its own {BOUND:?} deadline"
    );
    let armed: Vec<Instant> = armed_rx.try_iter().collect();
    assert!(
        !armed.is_empty(),
        "a bounded wait with no deadline passed yet must arm `wait_deadline` at least once"
    );
    assert!(
        armed.iter().all(|&at| at == deadline),
        "wait_deadline must be armed with exactly the caller's own requested deadline \
         ({deadline:?}), got {armed:?}"
    );
}

/// `wait_drained`'s bounded arm with its frozen-clock advance dropped fails at the second round
/// instead of re-arming forever.
///
/// Mutant: drop the `advance_by_elapsed_if_frozen` call in `wait_drained` -> same panic, without
/// the seam. Mutant: drop `wait_drained`'s `check.round()` -> the leaf drains after the second
/// block is announced, `wait_drained` returns, and the test fails on "did not panic" instead of
/// the loop spinning forever.
#[cfg(target_os = "linux")]
#[skuld::test]
#[should_panic(expected = "no progress")]
fn wait_drained_panics_when_its_advance_is_dropped() {
    use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf, WaitObserver};
    use crate::wait::test_clock::{FrozenClockGuard, SkipAdvanceGuard};
    use std::time::Duration;

    /// Joins the drainer before the leaf's directory goes, panic or not.
    struct JoinOnDrop(Option<std::thread::JoinHandle<()>>);
    impl Drop for JoinOnDrop {
        fn drop(&mut self) {
            if let Some(drainer) = self.0.take() {
                drainer.join().expect("the drainer thread");
            }
        }
    }

    let fake = FakeLeaf::new("cosca-wait-drained-advance-dropped", true);
    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();

    // Ends a loop whose check is gone: the leaf drains once the second block is announced. The
    // announcement is sent from the waiting thread, so no timing is involved; if the wait
    // panics first, the observer guard drops the sender and the drainer returns.
    let (block_tx, block_rx) = std::sync::mpsc::channel();
    let events = fake.events.clone();
    let _drainer = JoinOnDrop(Some(std::thread::spawn(move || {
        for _ in 0..2 {
            if block_rx.recv().is_err() {
                return;
            }
        }
        FakeLeaf::set_populated(&events, false);
    })));

    let (_clock, at) = FrozenClockGuard::install();
    let _skip = SkipAdvanceGuard::install();
    WaitObserver::run_with_block_sender(block_tx, || leaf.wait_drained(Some(at + Duration::from_millis(5))).ok());
}

/// Under a frozen clock a bounded `wait_drained` on a leaf that never drains ends: each real
/// park advances the clock.
///
/// Mutant: drop the `advance_by_elapsed_if_frozen` call in `wait_drained` -> the second round
/// panics with "no progress" instead of re-arming forever.
#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_drained_terminates_under_a_frozen_clock() {
    use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
    use crate::containment::TreeDrain;
    use crate::wait::test_clock::FrozenClockGuard;
    use std::time::Duration;

    let fake = FakeLeaf::new("cosca-wait-drained-frozen-clock", true);
    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();

    let (_clock, at) = FrozenClockGuard::install();
    let verdict = leaf
        .wait_drained(Some(at + Duration::from_millis(5)))
        .expect("wait_drained");
    assert_eq!(verdict, TreeDrain::MembersRemain);
}

// CgroupLeaf::wait_drained real-mechanism test -----
// Linux + cgroup-v2 only; each takes the `cgroup` fixture.

/// Two real, simultaneously live processes placed directly in the same leaf via the crate's own
/// `place_self_in_cgroup_pre_exec` — not a synthetic membership list — exercising `wait_drained`'s
/// full mechanism: the real kernel `populated` 1→0 transition once both members are gone, and a
/// real park at `wait_drained`'s `Block` arm — proven by counting real pump broadcasts
/// (`fault::set_pump_batch_notifier`) against every park that woke, not just that the wait call
/// returned.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_wait_drained_tracks_two_real_members_through_exit(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::{
        assert_bounded_conclusion, Member, WaitDeadlineArgGuard, WaitObserver,
    };
    use crate::containment::TreeDrain;
    use std::os::unix::process::CommandExt;
    use std::process::{Command, Stdio};
    use std::sync::mpsc;
    use std::time::{Duration, Instant};

    let leaf = crate::containment::cgroup::try_create_leaf(None).unwrap_or_else(|e| {
        panic!(
            "the cgroup tests are enabled but no usable delegated cgroup v2 leaf could be created \
             ({e}) — is this process running inside a writable, delegated cgroup v2 slice with \
             cgroup.kill support (kernel >= 5.14)?"
        )
    });

    // A park proves only that the wait call returned, not that a real broadcast woke it (a
    // dropped listener returns too). Count real pump broadcasts independently: a mutant that
    // fakes a park without ever really waiting cannot fake a matching broadcast, since the pump
    // is a separate thread that only ever reports one for a real, observed leaf change.
    let leaf_name = leaf
        .leaf_path
        .file_name()
        .expect("a leaf has a name")
        .to_str()
        .expect("leaf names are UTF-8");
    let (batches_tx, batches_rx) = mpsc::channel();
    fault::set_pump_batch_notifier(leaf_name, batches_tx);
    let mut total_woken = 0usize;

    // Each member reports through its OWN channel. The leaf's channel carries one report for the whole
    // leaf (see `ReportChannel`), so two members sharing it would read as whichever wrote first.
    //
    // Each member is `cat` reading from a pipe this test holds open and never writes to or closes
    // until it explicitly kills the member (below).
    let spawn_member = |leaf: &crate::containment::cgroup::CgroupLeaf,
                        channel: &crate::containment::cgroup::ReportChannel|
     -> Member {
        let procs_fd = leaf.procs_fd();
        let slot = channel.slot();
        let mut cmd = Command::new("cat");
        cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null());
        // SAFETY: `Command::pre_exec` runs this closure only between `fork` and `exec` in the
        // child; `procs_fd` is a valid, open, writable fd owned by `leaf` for the parent's whole
        // lifetime (fork gives the child its own fd-table entry pointing at the same underlying
        // open file description, and `place_self_in_cgroup_pre_exec` closes only that child-side
        // copy) — exactly its own documented contract. `leaf` and `channel` both outlive every
        // member spawned through them in this test.
        unsafe {
            cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot));
        }
        let mut child = crate::test_spawn::spawn(&mut cmd).expect("spawn a real long-lived cgroup leaf member");
        let stdin = child.stdin.take().expect("cat's stdin must be piped");
        Member(child, stdin)
    };

    let channel_a = crate::containment::cgroup::ReportChannel::new().expect("open member a's report channel");
    let channel_b = crate::containment::cgroup::ReportChannel::new().expect("open member b's report channel");
    let mut a = spawn_member(&leaf, &channel_a);
    let mut b = spawn_member(&leaf, &channel_b);

    // Placement is proven by the `Placed` report, sent only after the `cgroup.procs` write
    // returns — `spawn()` returning does not imply it (see `ReportChannel`, "When the report is
    // final").
    for (name, member, mut channel) in [("a", &a, channel_a), ("b", &b, channel_b)] {
        assert_eq!(
            channel.wait(pidfd_of(member.0.id()).as_fd()),
            PlacementReport::Placed,
            "member {name}'s own report must survive the other member's spawn"
        );
    }
    let procs = std::fs::read_to_string(leaf.leaf_path.join("cgroup.procs")).expect("read cgroup.procs");
    for (name, member) in [("a", &a), ("b", &b)] {
        assert!(
            procs.lines().any(|line| line.trim() == member.0.id().to_string()),
            "member {name} must actually be placed in the leaf; cgroup.procs is {procs:?}"
        );
    }

    let mut bounded_wait_drained = || {
        const BOUND: Duration = Duration::from_millis(250);
        let start = Instant::now();
        let deadline = start + BOUND;
        let (_deadline_arg_guard, armed_rx) = WaitDeadlineArgGuard::install();
        let (result, parks, blocks, zero_remainings) =
            WaitObserver::run(|| leaf.wait_drained(Some(deadline)).expect("wait_drained"));
        let elapsed = start.elapsed();
        assert_bounded_conclusion(&parks, blocks, zero_remainings, deadline);
        // Never early; no upper bound is asserted (scheduler lateness).
        assert!(
            elapsed >= BOUND,
            "wait_drained returned after {elapsed:?}, before its own {BOUND:?} deadline"
        );
        let armed: Vec<Instant> = armed_rx.try_iter().collect();
        assert!(
            armed.iter().all(|&at| at == deadline),
            "wait_deadline must always be armed with exactly the caller's own requested \
             deadline ({deadline:?}), got {armed:?}"
        );
        total_woken += parks.iter().filter(|p| p.woken).count();
        result
    };

    assert_eq!(
        bounded_wait_drained(),
        TreeDrain::MembersRemain,
        "both members are alive; must report MembersRemain"
    );

    // One survivor: `populated` never flips (still nonzero), so the verdict must not change.
    a.0.kill().expect("kill member a");
    a.0.wait().expect("reap member a");
    assert_eq!(
        bounded_wait_drained(),
        TreeDrain::MembersRemain,
        "one member is still alive; must still report MembersRemain"
    );

    // Both gone: an UNBOUNDED wait_drained blocks on the real kernel `populated` 1→0 edge — the
    // "external event that might never happen" case the crate's no-sleep-sync rule allows a real
    // wait for. Made deterministic without timing: run the wait on its own thread, and kill and
    // reap the last member only once that thread's own `drain_blocking` signal proves it armed a
    // listener while the leaf still read populated — a real rendezvous, not a race against how
    // fast the kernel clears `populated` relative to `wait()` returning. A missed wake then hangs
    // until the suite slow-timeout, not a duration this test invented.
    let (rendezvous_tx, rendezvous_rx) = mpsc::channel();
    let (result, parks, zero_remainings) = std::thread::scope(|scope| {
        let handle = scope.spawn(|| {
            WaitObserver::run_with_block_sender(rendezvous_tx, || {
                leaf.wait_drained(None).expect("wait_drained once both are gone")
            })
        });
        rendezvous_rx
            .recv()
            .expect("drain_step must announce blocking before wait_drained returns");
        b.0.kill().expect("kill member b");
        b.0.wait().expect("reap member b");
        handle.join().expect("wait_drained thread must not panic")
    });
    // The rendezvous already consumed one signal via `recv` above; count whatever else arrived.
    let blocks = 1 + rendezvous_rx.try_iter().count();
    assert_eq!(
        result,
        TreeDrain::AllMembersExited,
        "both members exited; must report AllMembersExited"
    );
    assert_eq!(
        zero_remainings, 0,
        "an unbounded call has no deadline to shortcut on, so the zero-remaining seam must never \
         fire, got {zero_remainings}"
    );
    assert_eq!(
        blocks,
        parks.len(),
        "drain_step announced blocking {blocks} times, but the wait site's own wait call \
         returned {} times — every announced block must show up as a wait-site return",
        parks.len()
    );
    assert!(
        !parks.is_empty(),
        "the rendezvous above guarantees the wait call reached the wait site at least once \
         before the kill; got none"
    );
    assert!(
        parks.iter().all(|p| p.deadline.is_none() && p.woken),
        "every park in an unbounded call is armed with no deadline and can only conclude by \
         being woken — it has no timeout to elapse, got {parks:?}"
    );
    total_woken += parks.iter().filter(|p| p.woken).count();

    // The structural proof that a park is real, not merely a wait call returning (a dropped
    // listener returns too, as if woken, with no broadcast behind it): the pump is a thread of
    // its own that only ever reports a batch as "changed" when it observed a real leaf change
    // and genuinely broadcast for it, so no more parks can wake than the pump genuinely woke.
    let changed_batches = batches_rx.try_iter().filter(|&notified| notified).count();
    assert!(
        total_woken <= changed_batches,
        "{total_woken} parks woke across this test, but the pump reported only \
         {changed_batches} batches that actually broadcast — a woken park with no matching real \
         broadcast behind it is not a real park"
    );
}

/// A real leaf of the lane.
#[cfg(target_os = "linux")]
fn lane_leaf() -> crate::containment::cgroup::CgroupLeaf {
    crate::containment::cgroup::try_create_leaf(None).unwrap_or_else(|e| {
        panic!(
            "the cgroup tests are enabled but no usable delegated cgroup v2 leaf could be created ({e}) — is this \
             process running inside a writable, delegated cgroup v2 slice with cgroup.kill support (kernel >= 5.14)?"
        )
    })
}

/// A `cat` blocked on its piped stdin, in the test's own cgroup until the test moves it.
#[cfg(target_os = "linux")]
fn cat_member() -> (
    crate::containment::cgroup::test_support::Member,
    crate::identity::ProcessId,
) {
    cat_member_as(None)
}

/// [`cat_member`], run as `uid` where there is one (the cgroup group's root may switch to any).
#[cfg(target_os = "linux")]
fn cat_member_as(
    uid: Option<u32>,
) -> (
    crate::containment::cgroup::test_support::Member,
    crate::identity::ProcessId,
) {
    use std::os::unix::process::CommandExt as _;
    use std::process::{Command, Stdio};

    let mut cat = Command::new("cat");
    cat.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null());
    if let Some(uid) = uid {
        cat.uid(uid);
    }
    let mut child = crate::test_spawn::spawn(&mut cat).expect("spawn a member");
    let stdin = child.stdin.take().expect("cat's stdin is piped");
    let id = crate::identity::ProcessId::of(child.id())
        .found()
        .expect("the member's identity");
    (crate::containment::cgroup::test_support::Member(child, stdin), id)
}

/// Move `member` into the cgroup `dir`.
#[cfg(target_os = "linux")]
fn place(member: &crate::containment::cgroup::test_support::Member, dir: &std::path::Path) {
    std::fs::write(dir.join("cgroup.procs"), member.0.id().to_string())
        .unwrap_or_else(|e| panic!("move {} into {}: {e}", member.0.id(), dir.display()));
}

/// The listing a cgroup kill makes names the members of every cgroup under the leaf, `cgroup.kill`
/// reaching them all: one in the leaf, one in a cgroup under it, and one under that.
///
/// Mutant: the listing reads the leaf's own `cgroup.procs` alone.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_cgroup_listing_names_the_members_of_the_cgroups_under_the_leaf(#[fixture(cgroup)] _group: &Group) {
    let leaf = lane_leaf();
    let (in_leaf, in_leaf_id) = cat_member();
    let (under, under_id) = cat_member();
    let (deeper, deeper_id) = cat_member();
    let nested = leaf.leaf_path.join("nested");
    let deepest = nested.join("deeper");
    std::fs::create_dir(&nested).expect("make a cgroup under the leaf");
    std::fs::create_dir(&deepest).expect("make a cgroup under that");
    place(&in_leaf, &leaf.leaf_path);
    place(&under, &nested);
    place(&deeper, &deepest);

    let (members, unobserved) = leaf.list_members(None);

    assert!(unobserved.is_empty(), "every member can be named: {unobserved:?}");
    for (id, who) in [
        (in_leaf_id, "the member in the leaf"),
        (under_id, "the member in a cgroup under the leaf"),
        (deeper_id, "the member two cgroups down"),
    ] {
        assert!(members.iter().any(|m| m.id == id), "{who} is named: {members:?}");
    }
}

/// A member the walk of the leaf's descendants cannot place is placed through `/proc`, and its listing
/// keeps no cgroup id: only an id that itself placed it is kept. The member's pidfd is made to read
/// an id that is no cgroup, and the walk to fail at a cgroup under the leaf.
///
/// Mutant: the id the pidfd read is kept whichever route placed the member.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_placed_through_proc_is_listed_with_no_cgroup_id(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::WalkStep;

    let leaf = lane_leaf();
    let (member, id) = cat_member();
    place(&member, &leaf.leaf_path);
    std::fs::create_dir(leaf.leaf_path.join("nested")).expect("make a cgroup under the leaf");
    let _read = fault::force_pidfd_cgroup_id(u64::MAX);
    let _walk = fault::fail_walk_step("./nested", WalkStep::Id, libc::EIO);

    let (listed, unobserved) = leaf.list_members(None);

    assert!(unobserved.is_empty(), "{unobserved:?}");
    assert_eq!(
        listed.iter().map(|m| (m.id, m.seen)).collect::<Vec<_>>(),
        [(id, None)],
        "placed through /proc, so no cgroup id placed it"
    );
}

/// The members are listed before `cgroup.kill`, not after it: a member that has gone from the leaf by
/// the time the kill is written is still named. The member is ended and reaped right before the write,
/// so the leaf's `cgroup.procs` is empty when the kill runs.
///
/// Mutant: the listing is read after the kill.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_cgroup_lists_its_members_before_it_kills_them(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::fault;
    use crate::containment::Contains as _;

    let leaf = lane_leaf();
    let (member, id) = cat_member();
    place(&member, &leaf.leaf_path);
    let member = std::rc::Rc::new(std::cell::RefCell::new(member));
    let _ending = fault::set_before_kill_write({
        let member = member.clone();
        move || {
            let mut member = member.borrow_mut();
            member.0.kill().expect("end the member");
            member.0.wait().expect("reap the member");
        }
    });

    let (sent, wait) = leaf.kill(None).split();

    sent.into_result().expect("the leaf's kill");
    assert_eq!(
        wait.members_for_test(),
        [id],
        "the member was named before the kill ended it"
    );
}

/// A kill the kernel refused names no member to wait for: its `Err` is returned, where a wait over
/// members it did not kill would hang. The wait is made to end the member where it blocks, so a mutant
/// fails by assertion.
///
/// Mutant: the members are named whether or not the kill landed.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_cgroup_kill_the_kernel_refused_waits_for_no_member(#[fixture(cgroup)] _group: &Group) {
    use std::cell::Cell;
    use std::rc::Rc;

    use crate::containment::cgroup::fault;
    use crate::containment::Contains as _;

    let leaf = lane_leaf();
    let (member, _) = cat_member();
    place(&member, &leaf.leaf_path);
    let pid = member.0.id();
    let _refused = fault::fail_next_kill_write();

    let (sent, wait) = leaf.kill(None).split();
    assert!(sent.into_result().is_err(), "the kill was refused");
    let blocked = Rc::new(Cell::new(false));
    let _blocking = crate::wait::block_probe::on_blocking({
        let blocked = blocked.clone();
        move || {
            blocked.set(true);
            nix::sys::signal::kill(
                nix::unistd::Pid::from_raw(pid as i32),
                nix::sys::signal::Signal::SIGKILL,
            )
            .expect("end the member");
        }
    });
    wait.wait().expect("a kill that failed waits for nothing");

    assert!(!blocked.get(), "the wait blocked on a member the kill did not reach");
    drop(member);
}

/// A member that left the leaf between the listing and `cgroup.kill` is not reached by the kill: it is
/// no part of the tree, so it is neither killed nor waited for. If the wait blocks on it, the probe
/// ends it, so the row fails by assertion.
///
/// Mutant: every listed member is waited for, whether or not the kill reached it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_that_left_the_leaf_before_the_kill_is_neither_killed_nor_waited_for(#[fixture(cgroup)] _group: &Group) {
    use std::cell::Cell;
    use std::rc::Rc;

    use crate::containment::cgroup::fault;
    use crate::containment::Contains as _;

    let leaf = lane_leaf();
    let (member, _) = cat_member();
    place(&member, &leaf.leaf_path);
    let pid = member.0.id();
    let outside = leaf
        .leaf_path
        .parent()
        .expect("the leaf has a parent cgroup")
        .to_owned();
    let member = Rc::new(std::cell::RefCell::new(member));
    let _leaving = fault::set_before_kill_write({
        let member = member.clone();
        move || place(&member.borrow(), &outside)
    });
    let blocked = Rc::new(Cell::new(false));
    let _blocking = crate::wait::block_probe::on_blocking({
        let blocked = blocked.clone();
        move || {
            blocked.set(true);
            _ = nix::sys::signal::kill(
                nix::unistd::Pid::from_raw(pid as i32),
                nix::sys::signal::Signal::SIGKILL,
            );
        }
    });

    let (sent, wait) = leaf.kill(None).split();
    sent.into_result().expect("the leaf's kill");
    wait.wait().expect("the leaf drained");

    assert!(!blocked.get(), "the wait blocked on a member that left the leaf");
    let mut member = member.borrow_mut();
    assert_eq!(
        member.0.try_wait().expect("look at the member"),
        None,
        "the member outside the leaf was not killed"
    );
    member.0.kill().expect("end the member");
    _ = member.0.wait();
}

/// After a kill that landed, a listed member still in the leaf was reached (whatever its credentials: the
/// kernel's kill does not ask), one that left the leaf was not, and one that is gone has exited and
/// is kept, its wait ending at once. The check sends nothing: the members it leaves running still run.
///
/// Mutant: every listed member is kept.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_still_in_the_leaf_is_reached_by_the_kill_and_one_that_left_is_not(#[fixture(cgroup)] _group: &Group) {
    use crate::identity::HostKernel;

    let leaf = lane_leaf();
    let (mut inside, inside_id) = cat_member();
    let (mut outside, outside_id) = cat_member();
    let (mut gone, gone_id) = cat_member();
    place(&inside, &leaf.leaf_path);
    place(&outside, leaf.leaf_path.parent().expect("the leaf has a parent cgroup"));
    gone.0.kill().expect("end the member");
    gone.0.wait().expect("reap the member");
    leaf.kill.record(Ok(()));

    let (reached, unobserved) = leaf.reached_by_kill(
        &HostKernel,
        [inside_id, outside_id, gone_id].map(listed_before).to_vec(),
    );

    assert_eq!(reached, [inside_id, gone_id]);
    assert!(unobserved.is_empty(), "every member could be placed: {unobserved:?}");
    for (member, who) in [
        (&mut inside, "the member in the leaf"),
        (&mut outside, "the member outside"),
    ] {
        assert_eq!(
            member.0.try_wait().expect("look at the member"),
            None,
            "{who} was not signalled by the check"
        );
        member.0.kill().expect("end the member");
        _ = member.0.wait();
    }
}

/// `id` as a listing before the kill would have named it, with no cgroup id seen.
#[cfg(target_os = "linux")]
fn listed_before(id: crate::identity::ProcessId) -> super::Listed {
    super::Listed { id, seen: None }
}

/// A member of another uid still in the leaf is reached by the kill and waited for, as one of the
/// tree's own uid: the kernel's `cgroup.kill` asks nobody's credentials, and the check sends nothing,
/// so no refused send takes it out. The lane's root runs the member as the `nobody` uid.
///
/// Mutant: a member the check cannot signal is left out.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_of_another_uid_still_in_the_leaf_is_reached_by_the_kill(#[fixture(cgroup)] _group: &Group) {
    use crate::identity::HostKernel;

    let leaf = lane_leaf();
    let (mut other, other_id) = cat_member_as(Some(65534));
    place(&other, &leaf.leaf_path);
    let (listed, unobserved) = leaf.list_members(None);
    assert_eq!(
        listed.iter().map(|m| m.id).collect::<Vec<_>>(),
        [other_id],
        "the member is listed"
    );
    leaf.kill.record(Ok(()));

    let (reached, unplaced) = leaf.reached_by_kill(&HostKernel, listed);

    assert_eq!(reached, [other_id]);
    assert!(
        unobserved.is_empty() && unplaced.is_empty(),
        "{unobserved:?} {unplaced:?}"
    );
    assert_eq!(
        other.0.try_wait().expect("look at the member"),
        None,
        "the check signalled nothing"
    );
    other.0.kill().expect("end the member");
    _ = other.0.wait();
}

/// A listed member that cannot be opened to be placed is not dropped: it is an error saying its exit
/// cannot be observed, and it names the member.
///
/// Mutant: a member whose check fails is left out without a word.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_whose_place_cannot_be_checked_after_the_kill_is_an_unobserved_error(#[fixture(cgroup)] _group: &Group) {
    use crate::identity::{FakeKernel, HostKernel};

    let leaf = lane_leaf();
    let (mut unplaced, unplaced_id) = cat_member();
    place(&unplaced, &leaf.leaf_path);
    let kernel = FakeKernel::over(&HostKernel).on_pidfd_open(unplaced_id.pid(), Err(rustix::io::Errno::MFILE));
    leaf.kill.record(Ok(()));

    let (reached, unobserved) = leaf.reached_by_kill(&kernel, vec![listed_before(unplaced_id)]);

    assert!(
        reached.is_empty(),
        "a member that cannot be placed is not claimed reached"
    );
    assert_eq!(unobserved.len(), 1, "it is reported: {unobserved:?}");
    let report = crate::error::said(&unobserved[0]);
    assert!(
        report.contains(&unplaced_id.pid().to_string()) && report.contains("exit cannot be observed"),
        "the error names the member and what is left undone: {report}"
    );
    unplaced.0.kill().expect("end the member");
    _ = unplaced.0.wait();
}

/// The wait over a leaf's listed members blocks on a member that is running, and ends once it has exited
/// and the leaf has drained. The kill is stated, not made: a real kill ends the member before the wait
/// looks at it, so only a member the kill left running shows that the wait blocks.
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_wait_over_a_leafs_listed_members_blocks_on_a_running_member(#[fixture(cgroup)] _group: &Group) {
    use std::cell::Cell;
    use std::rc::Rc;

    use crate::containment::dispatch::TreeKillOutcome;
    use crate::containment::drain_edge::DrainEdge;
    use crate::containment::TreeKill;

    let leaf = lane_leaf();
    let (mut member, id) = cat_member();
    place(&member, &leaf.leaf_path);
    let pid = member.0.id();
    let (members, unobserved) = leaf.list_members(None);
    assert_eq!(
        members.iter().map(|m| m.id).collect::<Vec<_>>(),
        [id],
        "the member is listed"
    );
    let members = members.into_iter().map(|m| m.id).collect();
    let blocked = Rc::new(Cell::new(false));
    let _blocking = crate::wait::block_probe::on_blocking({
        let blocked = blocked.clone();
        move || {
            blocked.set(true);
            nix::sys::signal::kill(
                nix::unistd::Pid::from_raw(pid as i32),
                nix::sys::signal::Signal::SIGKILL,
            )
            .expect("end the member");
        }
    });

    let (_, wait) = TreeKill::listed(
        TreeKillOutcome::Ran(Ok(())),
        members,
        unobserved,
        DrainEdge::Cgroup(&leaf),
    )
    .split();
    wait.wait().expect("the member exited and the leaf drained");

    assert!(blocked.get(), "the wait did not block on a member that was running");
    _ = member.0.wait();
}

/// The parent's `cgroup.procs` fd stays close-on-exec for as long as the parent holds it. The
/// child's `pre_exec` write needs it only between `fork` and `exec`, where a CLOEXEC fd is still
/// open; any other program this process starts meanwhile must not inherit a writable
/// `cgroup.procs`, through which it could move itself into the leaf and be killed with it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_leaf_procs_fd_is_not_inherited_across_exec(#[fixture(cgroup)] _group: &Group) {
    let leaf = crate::containment::cgroup::try_create_leaf(None).unwrap_or_else(|e| {
        panic!("the cgroup tests are enabled but no usable delegated cgroup v2 leaf could be created ({e})")
    });
    // SAFETY: `procs_fd` is open for as long as `leaf` lives.
    let flags = unsafe { libc::fcntl(leaf.procs_fd(), libc::F_GETFD) };
    assert_ne!(flags, -1, "F_GETFD: {}", std::io::Error::last_os_error());
    assert_ne!(
        flags & libc::FD_CLOEXEC,
        0,
        "the parent-held cgroup.procs fd must be CLOEXEC"
    );

    // An unrelated program started while the leaf is alive lists its own open descriptors.
    let out =
        crate::test_spawn::output_captured(std::process::Command::new("/bin/sh").args(["-c", "ls -l /proc/$$/fd"]))
            .expect("run sh");
    assert!(out.status.success(), "ls failed: {out:?}");
    let fds = String::from_utf8_lossy(&out.stdout);
    let procs = leaf.leaf_path.join("cgroup.procs");
    assert!(
        !fds.contains(&*procs.to_string_lossy()),
        "an unrelated program inherited {}:\n{fds}",
        procs.display()
    );
}

// Linux failure-path tests -----
// Real filesystem, no cgroup v2 required: `create_leaf_under` is parameterised by the
// directory it creates the leaf in, so every precondition it checks can be failed for real
// against a temp directory on any Linux host.

/// A `mkdir` the kernel refuses reports the `mkdir` step, its path and its errno — not a
/// bare "cgroups unavailable".
///
/// The refusal is a parent directory that does not exist (`ENOENT`), not one whose mode
/// forbids writing: CI's cgroup lane runs as root, and root ignores directory permissions, so
/// a mode-based refusal would be a no-op there and this test would assert nothing. `ENOENT`
/// is uid-independent, and the step maps every errno the same way — it carries the kernel's
/// reason rather than classifying it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_a_refused_mkdir() {
    let dir = tempfile::tempdir().expect("tempdir");
    let parent = dir.path().join("no-such-slice");

    let err = match crate::containment::cgroup::create_leaf_under(&parent, None) {
        Err(e) => e,
        Ok(_) => panic!("creating a leaf under a nonexistent directory must fail"),
    };
    assert!(
        matches!(err, LeafError::CreateLeafDir { .. }),
        "expected CreateLeafDir, got {err:?}"
    );
    let rendered = err.to_string();
    assert!(rendered.contains("no-such-slice"), "path missing from {rendered:?}");
    assert_eq!(first_source_code(&err), Some(libc::ENOENT), "{err:?}");
}

/// The OS code on `err`'s `source()`.
#[cfg(target_os = "linux")]
fn first_source_code(err: &LeafError) -> Option<i32> {
    std::error::Error::source(err)
        .and_then(|source| source.downcast_ref::<std::io::Error>())
        .and_then(std::io::Error::raw_os_error)
}

/// A writable directory with no `cgroup.kill` in the created leaf (i.e. not a cgroupfs, or a
/// kernel older than 5.14) reports THAT, and leaves no stray directory behind.
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_a_missing_cgroup_kill() {
    let dir = tempfile::tempdir().expect("tempdir");
    let err = match crate::containment::cgroup::create_leaf_under(dir.path(), None) {
        Err(e) => e,
        Ok(_) => panic!("a plain directory has no cgroup.kill; leaf creation must fail"),
    };
    assert!(
        matches!(err, LeafError::KillUnsupported { .. }),
        "expected KillUnsupported, got {err:?}"
    );
    assert!(err.to_string().contains("cgroup.kill"), "got {err}");
    let strays: Vec<_> = std::fs::read_dir(dir.path())
        .expect("read tempdir")
        .map(|e| e.expect("entry").file_name())
        .collect();
    assert!(strays.is_empty(), "a failed leaf creation left {strays:?} behind");
}

/// A degrade whose leaf cannot be removed says so, the way `Drop` does for a leaf it could not
/// remove: a stray `cosca-*` cgroup stays on the host, and this record is all anyone will have.
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_a_leaf_its_unwind_could_not_remove() {
    crate::log_capture::install();
    let dir = tempfile::tempdir().expect("tempdir");
    let marker = dir.path().to_string_lossy().into_owned();
    crate::containment::cgroup::fault::set_force_occupy_before_unwind(true);

    let mark = crate::log_capture::mark();
    let err = match crate::containment::cgroup::create_leaf_under(dir.path(), None) {
        Err(e) => e,
        Ok(_) => panic!("a plain directory has no cgroup.kill; leaf creation must fail"),
    };
    assert!(
        !crate::containment::cgroup::fault::occupy_before_unwind_armed(),
        "the seam must be consumed by the unwind it stands in for"
    );
    assert!(matches!(err, LeafError::KillUnsupported { .. }), "got {err:?}");
    assert_eq!(
        crate::log_capture::levels_since(mark, &marker),
        vec![log::Level::Warn],
        "the unwind left a leaf behind and must say so"
    );
    let enotempty = std::io::Error::from_raw_os_error(libc::ENOTEMPTY).to_string();
    assert!(
        crate::log_capture::records_since(mark, &marker)
            .iter()
            .any(|record| record.contains(&enotempty)),
        "the record must carry the kernel's reason"
    );
}

/// A `cgroup.kill` the kernel cannot even look up is not a missing one: the errno is the
/// diagnosis, and "the kernel is older than 5.14" would be a confident false cause. The lookup is
/// through the held leaf directory, where a temp directory yields only `ENOENT`, so the fault
/// seam supplies the errno.
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_a_cgroup_kill_it_could_not_check() {
    let dir = tempfile::tempdir().expect("tempdir");
    let parent = dir.path().to_path_buf();
    crate::containment::cgroup::fault::set_force_kill_check_errno(libc::EACCES);

    let err = match crate::containment::cgroup::create_leaf_under(&parent, None) {
        Err(e) => e,
        Ok(_) => panic!("a plain directory has no cgroup.kill; leaf creation must fail"),
    };
    assert!(
        matches!(err, LeafError::CheckKill { .. }),
        "expected CheckKill, got {err:?}"
    );
    assert_eq!(
        first_source_code(&err),
        Some(libc::EACCES),
        "the errno is the diagnosis: {err:?}"
    );
    let strays: Vec<_> = std::fs::read_dir(&parent)
        .expect("read the parent")
        .map(|e| e.expect("entry").file_name())
        .collect();
    assert!(strays.is_empty(), "a failed leaf creation left {strays:?} behind");
}

// hard_kill outcome reporting -----
// `cgroup.kill` is the whole of the CgroupV2 mechanism's teardown promise, so whether the write
// landed is the caller's answer, not a detail. Real filesystem, no cgroupfs: a `cgroup.kill`
// that is a DIRECTORY makes the kernel refuse the write with `EISDIR` on any Linux host, which
// is the same shape as the production failures (`EACCES` after a privilege drop, `EROFS` on a
// remounted cgroupfs) — a kill that did NOT happen.

/// A `cgroup.kill` write the kernel refused must reach the caller through the public
/// `Tree::kill`'s cgroup arm, exactly as every sibling mechanism's failure does. Swallowing it
/// makes `Child::kill_tree()` return `Ok(())` over a tree that is still running.
#[cfg(target_os = "linux")]
#[skuld::test]
fn hard_kill_propagates_a_kill_the_kernel_refused() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-refused-kill");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    // A directory where the kernel expects a writable file: `write` fails with EISDIR.
    std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("create cgroup.kill as a directory");

    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    let err = leaf
        .hard_kill()
        .expect_err("a refused cgroup.kill write must not read as success");
    // A `Containment` over the kernel's error, not a bare `Io`: a kill that can have peers returns a
    // variant with a `source`. The errno stays down the chain, and several errnos share one `ErrorKind`.
    assert!(
        matches!(&err, crate::error::Error::Containment { source: Some(_), .. }),
        "a refused cgroup.kill write must surface as Error::Containment over the OS error, got {err:?}"
    );
    assert_eq!(
        crate::error::first_os_code(&err),
        Some(libc::EISDIR),
        "the kernel's errno must reach the caller, got {err}"
    );

    let tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(leaf));
    assert!(
        tree.kill(None).outcome().into_result().is_err(),
        "a cgroup tree must propagate like every sibling mechanism; swallowing it makes \
         kill_tree() report a completed teardown over a live tree"
    );
}

/// An already-removed leaf is a COMPLETED teardown, not a failed kill: `rmdir` on a cgroup v2
/// leaf succeeds only once the leaf is empty, so its absence is proof every member had already
/// exited. It must stay `Ok`, and must not be narrated at `warn` — nothing was reduced.
#[cfg(target_os = "linux")]
#[skuld::test]
fn hard_kill_reads_an_already_removed_leaf_as_a_completed_teardown() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();

    // Its OWN leaf name, not the shared placeholder: `log_capture` is process-wide and
    // trials can overlap (`--nocapture` with `--test-threads` > 1), so a marker a sibling test also emits makes the
    // count below a count of whatever else happened to run alongside.
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(std::path::PathBuf::from(
        "/nonexistent/cosca-hard-kill-already-gone",
    ));
    leaf.hard_kill()
        .expect("an already-removed leaf is a completed teardown, not a failure");

    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-hard-kill-already-gone"),
        vec![log::Level::Debug],
        "an already-gone leaf is routine: exactly one record, and not at warn"
    );
}

/// `terminate` reads an already-removed leaf as a completed teardown, as `hard_kill` does.
#[cfg(target_os = "linux")]
#[skuld::test]
fn terminate_reads_an_already_removed_leaf_as_a_completed_teardown() {
    // Its own leaf name, for the reason `hard_kill`'s twin above gives.
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(std::path::PathBuf::from(
        "/nonexistent/cosca-terminate-already-gone",
    ));
    leaf.terminate()
        .expect("an already-removed leaf lists no member")
        .expect("an already-removed leaf has no member left to signal");

    let tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(leaf));
    assert!(
        matches!(
            tree.terminate(0, None),
            crate::containment::TerminateOutcome::Sent { result: Ok(()), .. }
        ),
        "terminate and hard_kill must agree about an already-gone leaf"
    );
    assert!(tree.kill(None).outcome().into_result().is_ok());
}

// Drop's leaf-removal reporting -----
// `Drop` is the only place a leaf cosca could not remove is ever mentioned: it has returned by
// the time anything could look, and nothing — cosca or a cgroup manager — revisits a `cosca-*`
// leaf by name. A host accumulating them is diagnosable only if each one says so as it
// happens.

/// A leaf the host refuses to remove is reported through the real `Drop`. Real filesystem, any
/// Linux host: a leaf directory holding a subdirectory refuses both `rmdir`s.
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_reports_a_leaf_it_could_not_remove() {
    crate::log_capture::install();
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-undeletable-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    // A file, not a directory: `rmdir` refuses it, and no child-cgroup sweep removes it.
    std::fs::write(leaf_path.join("occupant"), "").expect("make the leaf unremovable");

    let mark = crate::log_capture::mark();
    drop(crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path));

    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-undeletable-leaf"),
        vec![log::Level::Warn],
        "a leaf that outlived its Drop is reported, or never known about"
    );
}

/// `Drop` writes `cgroup.kill` through an unremovable leaf only when the child reported `Placed`
/// (see the module's report contract). Before the verdict, `Drop` abandons the exchange first,
/// which makes what was received final: nothing received then means the child never execs.
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_kills_through_a_leaf_unless_the_child_provably_never_entered() {
    crate::log_capture::install();
    let reports = [
        PlacementReport::NotReported,
        PlacementReport::WriteFailed(libc::EBADF),
        PlacementReport::Placed,
    ];
    // Before the verdict `Drop` reads the report from the channel; after it, from what the
    // verdict recorded when it released the channel.
    for (report, verdict_taken) in reports.into_iter().flat_map(|report| [(report, false), (report, true)]) {
        let kills = report == PlacementReport::Placed;
        let dir = tempfile::tempdir().expect("tempdir");
        let leaf_path = dir.path().join("cosca-drop-kill-leaf");
        std::fs::create_dir(&leaf_path).expect("create the leaf");
        // A file, not a directory: `rmdir` refuses it, and no child-cgroup sweep removes it.
        std::fs::write(leaf_path.join("occupant"), "").expect("make the leaf unremovable");

        let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
        match report {
            PlacementReport::NotReported => {}
            // SAFETY: fd -1 is never writable, so the write fails with EBADF; closing -1 is a
            // no-op. The slot's channel lives as long as `leaf`.
            PlacementReport::WriteFailed(_) => {
                _ = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(-1, leaf.placement_slot()) };
            }
            // SAFETY: the slot's channel lives as long as `leaf`.
            PlacementReport::Placed => unsafe { leaf.placement_slot().report_placed_for_test() },
        }
        if verdict_taken {
            // The verdict needs a live pid: this process's own stands in for the child.
            assert_eq!(
                leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id())))
                    .is_ok(),
                report == PlacementReport::Placed
            );
            assert!(!leaf.holds_spawn_resources());
        }
        let mark = crate::log_capture::mark();
        drop(leaf);

        assert_eq!(
            leaf_path.join("cgroup.kill").exists(),
            kills,
            "a child that reported {report:?} (verdict taken: {verdict_taken}): cgroup.kill \
             written must be {kills}"
        );
        assert_eq!(
            crate::log_capture::levels_since(mark, &leaf_path.to_string_lossy()),
            vec![log::Level::Warn],
            "the unremoved leaf is reported either way"
        );
    }
}

// detach's disarm -----
// See `CgroupLeaf::disarm`.

/// A disarmed leaf never writes `cgroup.kill`, and leaves the occupied directory alone. The
/// occupant stands in for the detached tree; a real leaf refuses both `rmdir`s while one runs.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_does_not_kill_the_tree_it_was_detached_from() {
    crate::log_capture::install();
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-detached-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    std::fs::write(leaf_path.join("occupant"), "").expect("stand in for the detached tree");
    std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
    // `populated 1`: a real cgroupfs always has this file, and Drop's never-killed branch reads
    // it to tell a leaf still holding its tree from one that already drained on its own.
    std::fs::write(leaf_path.join("cgroup.events"), b"populated 1\nfrozen 0\n").expect("create cgroup.events");

    let tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(entered_leaf_at(
        leaf_path.clone(),
    )));
    let mark = crate::log_capture::mark();
    tree.disarm().expect("disarm");
    drop(tree);

    assert_eq!(
        std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
        b"",
        "a detached tree must not be killed: cgroup.kill must never be written"
    );
    assert!(leaf_path.is_dir(), "the detached tree's leaf must survive with it");
    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-detached-leaf"),
        vec![log::Level::Debug],
        "a leaf left behind for a detached tree is what the caller asked for, not a leak"
    );
}

/// The same leaf, left armed, DOES fire `cgroup.kill` — so the test above pins the disarm, not
/// an inert path.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_leaf_still_kills_the_tree_on_drop() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-armed-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    std::fs::write(leaf_path.join("occupant"), "").expect("keep the leaf unremovable");
    std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");

    drop(entered_leaf_at(leaf_path.clone()));

    assert_eq!(
        std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
        b"1",
        "an occupied leaf that was NOT detached must still be killed on Drop"
    );
}

/// A disarmed leaf whose tree has already gone still removes the empty directory: detach gives
/// up the KILL, not the tidying. cosca does not come back for a leaf it left.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_still_removes_itself_once_it_is_empty() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-detached-empty-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");

    let tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(entered_leaf_at(
        leaf_path.clone(),
    )));
    tree.disarm().expect("disarm");
    drop(tree);

    assert!(
        !leaf_path.exists(),
        "an empty leaf is removable, and cosca does not come back for one it left"
    );
}

/// A disarmed leaf whose tree the caller KILLED (`kill_on_drop(false)`, `kill_tree()`, no
/// `wait_tree()`) is not simply left behind for a live detached tree: this fix makes `Drop`
/// wait for that kill's drain before retrying the `rmdir`, exactly as the armed path does (see
/// `a_disarmed_leaf_whose_tree_was_killed_removes_itself_only_after_it_drains`, which proves the
/// retried `rmdir` succeeds once a — there, simulated — drain completes). This leaf's directory
/// has no `cgroup.events`, so its drain watch arms as already-gone (see `DrainWatch::arm`) and the
/// wait is a no-op — the retried `rmdir` still fails here on `ENOTEMPTY`, from the leftover
/// `occupant` and `cgroup.kill` files left in the directory, a genuine leftover unrelated to the
/// drain. It is reported once, at `warn`, like every other leaf `Drop` fails to remove.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_tree_was_killed_but_still_refuses_rmdir_is_reported_once() {
    crate::log_capture::install();
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-killed-opted-out-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    std::fs::write(leaf_path.join("occupant"), "").expect("leftover file that makes rmdir fail with ENOTEMPTY");
    std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");

    let leaf = entered_leaf_at(leaf_path);
    leaf.disarm();
    // Only sets the leaf's "killed" flag: this test's subject is the log level, not the write.
    leaf.hard_kill().expect("kill the tree");
    let mark = crate::log_capture::mark();
    drop(leaf);

    let records = crate::log_capture::records_since(mark, "cosca-killed-opted-out-leaf");
    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-killed-opted-out-leaf"),
        vec![log::Level::Warn],
        "a killed tree's leaf that outlived its Drop is a leak, got {records:?}"
    );
    assert!(
        records.iter().all(|r| !r.contains("detached")),
        "the caller killed this tree; it was not left running, got {records:?}"
    );
}

/// A SIGTERM is catchable, so `terminate_tree()` proves no teardown: a disarmed leaf whose tree
/// ignored a SIGTERM that was sent is a live opted-out tree keeping its leaf, reported at `debug`,
/// not a leak. Mutant for the premise: "`terminate` sends nothing" (the SIGTERM assertion fails).
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_tree_survived_terminate_is_not_reported_as_a_leak(#[fixture(cgroup)] _group: &Group) {
    use std::io::Read as _;

    crate::log_capture::install();
    let mut cmd = std::process::Command::new("sh");
    cmd.args(["-c", "trap '' TERM; echo r; exec cat"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    let (leaf, mut member, stdin) = entered_real_leaf_of(cmd);
    let pid = member.id();
    let leaf_path = leaf.path().to_owned();
    let leaf_name = leaf_path
        .file_name()
        .expect("a leaf name")
        .to_string_lossy()
        .into_owned();
    // The member ignores SIGTERM from here on, and keeps it ignored through its `exec`.
    let mut ready = [0u8; 2];
    member
        .stdout
        .as_mut()
        .expect("piped stdout")
        .read_exact(&mut ready)
        .expect("the member reports that it ignores SIGTERM");
    leaf.disarm();
    crate::containment::cgroup::fault::take_member_terms();
    leaf.terminate()
        .expect("cgroup.procs is readable")
        .expect("terminate the leaf");
    assert_eq!(
        crate::containment::cgroup::fault::take_member_terms(),
        [(Some(pid), crate::send_log::Via::Pidfd, libc::SIGTERM)],
        "the SIGTERM the member survives was sent"
    );
    let mark = crate::log_capture::mark();
    drop(leaf);
    let levels = crate::log_capture::levels_since(mark, &leaf_name);
    let records = crate::log_capture::records_since(mark, &leaf_name);
    // The member lives until its stdin closes: the leaf's `Drop` has run with it alive.
    drop(stdin);
    member.wait().expect("reap the member");
    // The disarmed leaf was left for its tree; the tree is gone, and the leaf is empty.
    std::fs::remove_dir(&leaf_path).expect("remove the emptied leaf");

    assert_eq!(
        levels,
        vec![log::Level::Debug],
        "a tree that survived SIGTERM is left running, not leaked, got {records:?}"
    );
}

/// A disarmed leaf whose directory is already GONE leaves nothing behind, so `Drop` must not
/// say it did. `rmdir` failing with `ENOENT` is proof of removal, not of survival — the armed
/// path already reads it that way, and a detached leaf's one `rmdir` is the only reading it
/// gets.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_that_is_already_gone_reports_nothing() {
    crate::log_capture::install();
    let leaf = entered_leaf_at(std::path::PathBuf::from("/nonexistent/cosca-detached-gone-leaf"));
    leaf.disarm();

    let mark = crate::log_capture::mark();
    drop(leaf);

    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-detached-gone-leaf"),
        Vec::<log::Level>::new(),
        "nothing is left behind for the detached tree, so there is nothing to report"
    );
}

// Drop's three flags -----
// See the truth table in `CgroupLeaf`'s `Drop`.

/// All four combinations, each against an occupied leaf whose verdict is taken: only both-set
/// writes `cgroup.kill`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_kills_only_a_leaf_its_child_entered_and_that_is_armed() {
    for (entered, armed) in [(true, true), (true, false), (false, true), (false, false)] {
        let dir = tempfile::tempdir().expect("tempdir");
        let leaf_path = dir.path().join("cosca-two-flags-leaf");
        std::fs::create_dir(&leaf_path).expect("create the leaf");
        std::fs::write(leaf_path.join("occupant"), "").expect("keep the leaf unremovable");
        std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");

        let leaf = if entered {
            entered_leaf_at(leaf_path.clone())
        } else {
            let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
            // SAFETY: fd -1 is never writable, so the write fails with EBADF; closing -1 is a
            // no-op. The slot's channel lives as long as `leaf`.
            _ = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(-1, leaf.placement_slot()) };
            assert!(
                leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id())))
                    .is_err(),
                "a failed write is not a placement"
            );
            leaf
        };
        if !armed {
            leaf.disarm();
        }
        drop(leaf);

        let expected: &[u8] = if entered && armed { b"1" } else { b"" };
        assert_eq!(
            std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
            expected,
            "entered={entered}, armed={armed}"
        );
    }
}

// A killed leaf's drain, armed and disarmed -----
// Each test gives a fake leaf cgroupfs's `rmdir` answers through the rmdir hook, and drives it from
// another thread that acts only once the drop's drain wait is about to block.

/// Run `act` on another thread each time a drain wait on THIS thread is about to block, until the
/// returned guard drops. `act` gets the number of the block, from 0.
#[cfg(target_os = "linux")]
fn on_each_drain_block(mut act: impl FnMut(usize) + Send + 'static) -> impl Drop {
    struct Stop(Option<std::thread::JoinHandle<()>>);
    impl Drop for Stop {
        fn drop(&mut self) {
            // Dropping the only sender ends the actor's loop.
            crate::containment::cgroup::fault::take_drain_blocking_notifier();
            self.0.take().expect("actor").join().expect("actor thread");
        }
    }
    let (blocking_tx, blocking_rx) = std::sync::mpsc::channel();
    let actor = std::thread::spawn(move || {
        let mut n = 0;
        while blocking_rx.recv().is_ok() {
            act(n);
            n += 1;
        }
    });
    crate::containment::cgroup::fault::set_drain_blocking_notifier(blocking_tx);
    Stop(Some(actor))
}

/// An armed `Drop` that kills through its leaf removes it only once the leaf has drained: no
/// `rmdir` after the `cgroup.kill` write sees `populated 1`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_drop_removes_its_leaf_only_after_it_drains() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let fake = FakeLeaf::new("cosca-draining-leaf", true);
    let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
    fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));
    let events = fake.events.clone();
    let actor = on_each_drain_block(move |_| FakeLeaf::set_populated(&events, false));

    fault::record_leaf_steps();
    drop(entered_leaf_at(fake.leaf.clone()));
    let steps = fault::take_leaf_steps();
    drop(actor);
    fault::take_rmdir_hook();

    assert!(
        !fake.leaf.exists(),
        "the drop must remove the drained leaf, got {steps:?}"
    );
    assert_eq!(
        fake.kill_written(),
        crate::containment::cgroup::KILL_PAYLOAD,
        "the drop must write cgroup.kill, not only record the step, got {steps:?}"
    );
    let killed_at = steps
        .iter()
        .position(|s| s == "kill")
        .unwrap_or_else(|| panic!("an occupied armed leaf must be killed through, got {steps:?}"));
    let after_kill = &steps[killed_at + 1..];
    assert!(!after_kill.is_empty(), "the drop must retry the rmdir, got {steps:?}");
    assert!(
        after_kill.iter().all(|s| s.starts_with("rmdir populated 0")),
        "every rmdir after the kill must wait for the drain, got {steps:?}"
    );
}

/// Disarmed twin of `an_armed_drop_removes_its_leaf_only_after_it_drains`: a
/// leaf whose caller explicitly killed the tree (`hard_kill`, mirroring `Child::kill_tree()`)
/// and THEN disarmed `Drop`'s own teardown (`kill_on_drop(false)`) must still have its `Drop`
/// wait for that kill's drain before its retried `rmdir` — not fire one unwaited `rmdir` and
/// report the leaf left behind while the kill it already made is still draining.
///
/// Deterministic, no sleeps: `on_each_drain_block` drives the fake leaf's `populated` flag from
/// another thread, released only once `Drop`'s wait is actually blocked on it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_tree_was_killed_removes_itself_only_after_it_drains() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let fake = FakeLeaf::new("cosca-disarmed-draining-leaf", true);
    let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
    fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));
    let events = fake.events.clone();
    let actor = on_each_drain_block(move |_| FakeLeaf::set_populated(&events, false));

    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();
    leaf.hard_kill().expect("kill the tree");
    fake.clear_kill();

    fault::record_leaf_steps();
    drop(leaf);
    let steps = fault::take_leaf_steps();
    drop(actor);
    fault::take_rmdir_hook();

    assert!(
        !fake.leaf.exists(),
        "a disarmed Drop must still remove a leaf its caller already killed, once it drains, got {steps:?}"
    );
    assert_eq!(fake.kill_written(), b"", "the landed kill is not written again");
    // The kill happened before `record_leaf_steps()`, so it leaves no step here.
    assert_eq!(
        steps,
        vec!["rmdir populated 1", "rmdir populated 0"],
        "a disarmed leaf's landed kill is not written again, and the rmdir retries only once it drains, got {steps:?}"
    );
}

/// An armed `Drop` after a `cgroup.kill` that failed does not write it again: the failure is final,
/// the leaf is left behind and the failed kill is warned once. The fault fails only the first
/// write, so a second would be recorded as a kill (and would drain the leaf, so the drop would wait
/// for it, with nothing to end the wait: the suite slow-timeout bounds it).
///
/// Mutant: the armed `Drop` writes `cgroup.kill` again after a failed write.
#[cfg(target_os = "linux")]
#[skuld::test]
fn death_watch_an_armed_drop_after_a_failed_kill_does_not_write_it_again() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    crate::log_capture::install();
    let name = "cosca-armed-drop-earlier-kill-failed";
    let fake = FakeLeaf::new(name, true);
    let (leaf_dir, events) = (fake.leaf.clone(), fake.events.clone());
    fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf_dir, &events));
    let leaf = entered_leaf_at(fake.leaf.clone());
    {
        let _first_write_fails = fault::fail_next_kill_write();
        leaf.hard_kill().expect_err("the forced failure");
    }
    let mark = crate::log_capture::mark();
    fault::record_leaf_steps();
    drop(leaf);
    let steps = fault::take_leaf_steps();
    fault::take_rmdir_hook();

    assert_eq!(steps, ["rmdir populated 1"], "no second write, and no wait for a drain");
    assert_eq!(fake.kill_written(), b"", "nothing wrote cgroup.kill");
    assert!(fake.leaf.exists(), "the leaf is left behind");
    let warns = crate::log_capture::records_since(mark, "cgroup.kill failed");
    assert_eq!(warns.len(), 1, "the failed kill is warned once: {warns:?}");
}

/// An armed `Drop` after a `cgroup.kill` that landed (`kill_tree()`) waits for that kill's drain and
/// does not write it again: one write per teardown. The cleared fake file shows a second write.
///
/// Mutant: the armed `Drop` writes `cgroup.kill` again after a landed write.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_drop_after_a_landed_kill_waits_for_its_drain_and_does_not_write_it_again() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let fake = FakeLeaf::new("cosca-armed-drop-landed-kill", true);
    let (leaf_dir, events) = (fake.leaf.clone(), fake.events.clone());
    fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf_dir, &events));
    let events = fake.events.clone();
    let actor = on_each_drain_block(move |_| FakeLeaf::set_populated(&events, false));

    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.hard_kill().expect("kill the tree");
    fake.clear_kill();
    fault::record_leaf_steps();
    drop(leaf);
    let steps = fault::take_leaf_steps();
    drop(actor);
    fault::take_rmdir_hook();

    assert_eq!(fake.kill_written(), b"", "the landed kill is not written again");
    assert_eq!(
        steps,
        ["rmdir populated 1", "rmdir populated 0"],
        "the drop waits for the drain of the kill that landed, then removes the leaf"
    );
    assert!(!fake.leaf.exists());
}

/// #194 follow-up: in `Drop`'s never-killed branch, a first `rmdir` that fails is not always the
/// caller's tree left running by request — a leaf can drain on its own (no kill needed) yet still
/// hold an empty child cgroup a grandchild left behind. `cgroup.events` already reading
/// `populated 0` is `Drop`'s cue to sweep that child cgroup away and retry, exactly as the killed
/// path already does, rather than reporting — or silently keeping — a leaf nothing is running in.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_never_killed_leaf_sweeps_and_retries_once_it_has_already_drained() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let fake = FakeLeaf::new("cosca-disarmed-self-drained-leaf", false);
    std::fs::create_dir(fake.leaf.join("leftover-child")).expect("leave an empty child cgroup behind");
    let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
    // Real cgroupfs `rmdir` semantics: `EBUSY` while a child cgroup exists, same errno as while
    // populated — neither is proof of anything else ([`removed_after_drain`] never applies to it).
    fault::set_rmdir_hook(move |path| {
        if !path.exists() {
            return Err(std::io::Error::from_raw_os_error(libc::ENOENT));
        }
        if path.join("leftover-child").exists() {
            return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
        }
        FakeLeaf::rmdir(&leaf, &events)
    });

    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    drop(leaf);
    fault::take_rmdir_hook();

    assert!(
        !fake.leaf.exists(),
        "a leaf that already drained on its own must be removed once its leftover child cgroup is swept"
    );
    assert!(
        !crate::log_capture::levels_since(mark, "cosca-disarmed-self-drained-leaf").contains(&log::Level::Warn),
        "a clean sweep-and-retry is success, not a leak"
    );
}

/// The sibling of the previous test: a leaf that never killed its tree and is STILL populated
/// keeps the old single-`rmdir`, debug-only behaviour — the caller asked for the tree to be left
/// running, and `Drop` must not sweep a child cgroup a still-live tree may yet be using.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_never_killed_leaf_still_populated_does_not_sweep() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let fake = FakeLeaf::new("cosca-disarmed-still-populated-leaf", true);
    std::fs::create_dir(fake.leaf.join("live-child")).expect("a live tree's own child cgroup");
    let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
    let sweeps = std::rc::Rc::new(std::cell::Cell::new(0));
    let counted = sweeps.clone();
    fault::set_rmdir_hook(move |path| {
        if !path.exists() {
            return Err(std::io::Error::from_raw_os_error(libc::ENOENT));
        }
        if path.join("live-child").exists() {
            counted.set(counted.get() + 1);
            return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
        }
        FakeLeaf::rmdir(&leaf, &events)
    });

    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    drop(leaf);
    fault::take_rmdir_hook();

    assert_eq!(
        sweeps.get(),
        1,
        "a still-populated leaf gets exactly the one, doomed rmdir, no retry"
    );
    assert!(
        fake.leaf.join("live-child").exists(),
        "a live tree's child cgroup must not be swept away"
    );
    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-disarmed-still-populated-leaf"),
        vec![log::Level::Debug],
        "a tree the caller left running is not a leak"
    );
}

/// A disarmed leaf whose caller's own `kill_tree()`/`hard_kill()` genuinely FAILED (not merely
/// "already gone") is not the "opted out and left running by request" case the debug-level message
/// promises: the caller was told the opposite of the truth if this is buried at `debug`. It is
/// reported exactly as loudly as the armed path reports its own kill failure.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_kill_attempt_failed_is_reported_at_warn() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    crate::log_capture::install();
    let fake = FakeLeaf::new("cosca-disarmed-kill-failed-leaf", true);
    // A directory, not a file, in `cgroup.kill`'s place: opening it for writing fails `EISDIR`,
    // unconditionally — no permission bit a privileged test process could bypass.
    std::fs::remove_file(fake.leaf.join("cgroup.kill")).expect("remove the real cgroup.kill");
    std::fs::create_dir(fake.leaf.join("cgroup.kill")).expect("make cgroup.kill unwritable");
    let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
    fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));

    let leaf = entered_leaf_at(fake.leaf.clone());
    leaf.disarm();
    // A kill the kernel took empties the leaf. This write is refused, so it never does. A call
    // that returns `Ok` anyway drains the fake here, so the `expect_err` fails by assertion.
    let killed = leaf.hard_kill();
    if killed.is_ok() {
        FakeLeaf::set_populated(&fake.events, false);
    }
    killed.expect_err("a directory cannot be written as cgroup.kill");

    let mark = crate::log_capture::mark();
    drop(leaf);
    fault::take_rmdir_hook();

    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-disarmed-kill-failed-leaf"),
        vec![log::Level::Warn],
        "a kill_tree() that actually failed is a mechanism failure, not an opt-out"
    );
}

/// A drain wait wakes when the leaf is removed, even with no event on `cgroup.events`: removing a
/// cgroup cancels a `populated` notification the kernel had postponed (see `DrainWatch`), so a
/// third party can remove a drained leaf while the wait still reads it populated.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_drain_wait_wakes_when_the_leaf_is_removed_without_a_populated_event() {
    use crate::containment::cgroup::test_support::FakeLeaf;
    use crate::containment::TreeDrain;

    let fake = FakeLeaf::new("cosca-removed-while-waited", true);
    let waited = fake.leaf.clone();
    let removed = fake.leaf.clone();
    let waiter = std::thread::spawn(move || {
        let _actor = on_each_drain_block(move |_| FakeLeaf::remove(&removed));
        crate::containment::cgroup::CgroupLeaf::for_test_at(waited).wait_drained(None)
    });

    assert_eq!(
        waiter.join().expect("waiter").expect("wait_drained"),
        TreeDrain::AllMembersExited,
        "a removed leaf holds no member"
    );
}

/// The same for a `Drop` killing through its leaf: it wakes, finds the leaf gone, and reports
/// nothing, since nothing was left behind.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_drop_whose_leaf_a_third_party_removes_reports_nothing() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    crate::log_capture::install();
    let fake = FakeLeaf::new("cosca-removed-under-drop", true);
    let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
    fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));
    let removed = fake.leaf.clone();
    let actor = on_each_drain_block(move |_| FakeLeaf::remove(&removed));

    let mark = crate::log_capture::mark();
    drop(entered_leaf_at(fake.leaf.clone()));
    drop(actor);
    fault::take_rmdir_hook();

    let records = crate::log_capture::records_since(mark, "cosca-removed-under-drop");
    assert!(
        !crate::log_capture::levels_since(mark, "cosca-removed-under-drop").contains(&log::Level::Warn),
        "a leaf a third party removed was not left behind, got {records:?}"
    );
}

/// An `rmdir` that fails `EBUSY` after the kill, drain and sweep is terminal: `Drop` tries once,
/// then reports the leaf once, naming what can have held it. A retry would only make a third
/// party's race rarer, never impossible.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_drop_reports_an_rmdir_refused_after_its_drain_once_without_retrying() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    crate::log_capture::install();
    let fake = FakeLeaf::new("cosca-refused-after-drain", true);
    let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
    let drained_rmdirs = std::rc::Rc::new(std::cell::Cell::new(0));
    let counted = drained_rmdirs.clone();
    fault::set_rmdir_hook(move |_| {
        if !FakeLeaf::is_populated(&events) {
            counted.set(counted.get() + 1);
            // Something a third party did since the sweep.
            return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
        }
        FakeLeaf::rmdir(&leaf, &events)
    });
    let events = fake.events.clone();
    let actor = on_each_drain_block(move |_| FakeLeaf::set_populated(&events, false));

    let mark = crate::log_capture::mark();
    drop(entered_leaf_at(fake.leaf.clone()));
    drop(actor);
    fault::take_rmdir_hook();

    let records = crate::log_capture::records_since(mark, "cosca-refused-after-drain");
    assert_eq!(drained_rmdirs.get(), 1, "one rmdir after the drain, no retry");
    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-refused-after-drain"),
        vec![log::Level::Warn],
        "reported once, got {records:?}"
    );
    for cause in ["moved into it after the kill", "child cgroup", "mount"] {
        assert!(
            records[0].contains(cause),
            "the report must name {cause:?}: {}",
            records[0]
        );
    }
}

/// A child-cgroup sweep of a leaf that is already gone removes nothing, and is no failure.
#[cfg(target_os = "linux")]
#[skuld::test]
fn sweeping_a_leaf_that_is_already_gone_removes_nothing() {
    let dir = tempfile::tempdir().expect("tempdir");
    assert_eq!(
        crate::containment::cgroup::LeafDir::open_for_test(&dir.path().join("cosca-gone"))
            .remove_children()
            .expect("sweep"),
        0
    );
}

/// A real leaf whose one member, a `cat` blocked on a piped stdin, entered it. For the lane tests.
///
/// Returns the member's `ChildStdin` separately so a caller cannot forget it: the member's only
/// job is to keep the leaf populated until a signal under test ends it, which needs the writer held
/// for exactly that long. Dropping it, or `member.wait()` (which closes a piped stdin before
/// waiting), is an EOF that ends the member without any signal, so every caller either releases it
/// from a seam that fires after the signal under test ([`drop_under_a_mount`]), or asserts the exit
/// status carries the signal it expects, or asserts none.
#[cfg(target_os = "linux")]
fn entered_real_leaf() -> (
    crate::containment::cgroup::CgroupLeaf,
    std::process::Child,
    std::process::ChildStdin,
) {
    entered_real_leaf_of(crate::test_child::held_std_blocker(std::process::Stdio::null()))
}

/// [`entered_real_leaf`] with `cmd` as the member: it must have a piped stdin.
#[cfg(target_os = "linux")]
fn entered_real_leaf_of(
    mut cmd: std::process::Command,
) -> (
    crate::containment::cgroup::CgroupLeaf,
    std::process::Child,
    std::process::ChildStdin,
) {
    use std::os::unix::process::CommandExt;

    let mut leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
    let (procs_fd, slot) = (leaf.procs_fd(), leaf.placement_slot());
    // SAFETY: as `cgroup_wait_drained_tracks_two_real_members_through_exit`'s member spawn: the
    // closure runs between fork and exec, and `leaf` outlives the spawn.
    unsafe {
        cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot));
    }
    let mut member = crate::test_spawn::spawn(&mut cmd).expect("spawn a member");
    let stdin = member.stdin.take().expect("piped stdin");
    leaf.take_placement(handle_of(member.id(), &pidfd_of(member.id())))
        .expect("the member entered the leaf");
    (leaf, member, stdin)
}

/// Give the calling thread alone a mount namespace, private, so that every mount it makes stays in
/// it and is gone with the thread.
#[cfg(target_os = "linux")]
fn enter_a_private_mount_namespace() {
    // SAFETY: plain syscalls on valid NUL-terminated strings.
    unsafe {
        assert_eq!(
            libc::unshare(libc::CLONE_NEWNS),
            0,
            "unshare: {}",
            std::io::Error::last_os_error()
        );
        assert_eq!(
            libc::mount(
                std::ptr::null(),
                c"/".as_ptr(),
                std::ptr::null(),
                libc::MS_REC | libc::MS_PRIVATE,
                std::ptr::null()
            ),
            0,
            "make / private: {}",
            std::io::Error::last_os_error()
        );
    }
}

/// Mount a tmpfs over `over`, in the calling thread's mount namespace.
#[cfg(target_os = "linux")]
fn mount_a_tmpfs_over(over: &std::path::Path) {
    let over = std::ffi::CString::new(over.as_os_str().as_encoded_bytes()).expect("no NUL");
    // SAFETY: a plain syscall on valid NUL-terminated strings.
    let mounted = unsafe { libc::mount(c"tmpfs".as_ptr(), over.as_ptr(), c"tmpfs".as_ptr(), 0, std::ptr::null()) };
    assert_eq!(mounted, 0, "mount a tmpfs: {}", std::io::Error::last_os_error());
}

/// Drop `leaf` on a thread of its own mount namespace, private to it, with a tmpfs mounted over
/// `over`, and return the levels and texts of the records its `Drop` made about `marker`. The mount is
/// gone with the thread.
///
/// `member_stdin` (the member's piped stdin) is released, via [`on_each_drain_block`], the moment
/// the drop's drain wait is about to block, which is strictly after `Drop`'s own `hard_kill()`.
/// After a real kill the release is a no-op; if the kill were skipped, the member would exit on
/// the EOF, so `drop(leaf)` returns either way and the caller's `SIGKILL` assertion fails.
#[cfg(target_os = "linux")]
fn drop_under_a_mount(
    leaf: crate::containment::cgroup::CgroupLeaf,
    over: std::path::PathBuf,
    marker: String,
    member_stdin: std::process::ChildStdin,
) -> (Vec<log::Level>, Vec<String>) {
    crate::log_capture::install();
    std::thread::spawn(move || {
        enter_a_private_mount_namespace();
        mount_a_tmpfs_over(&over);
        let mut stdin = Some(member_stdin);
        let _guard = on_each_drain_block(move |_| {
            if let Some(mut s) = stdin.take() {
                crate::test_child::write_to_possibly_dead_stdin(&mut s, b"x");
            }
        });
        let mark = crate::log_capture::mark();
        drop(leaf);
        (
            crate::log_capture::levels_since(mark, &marker),
            crate::log_capture::records_since(mark, &marker),
        )
    })
    .join()
    .expect("the dropping thread")
}

/// A mount over the leaf itself: `rmdir` of its name fails `EBUSY` in the VFS, before cgroupfs is
/// asked. `Drop` kills the real tree through the held leaf, and reports the leaf it cannot remove
/// rather than retrying forever.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_an_armed_drop_under_a_mount_over_its_leaf_kills_the_tree_and_reports_the_leaf(
    #[fixture(cgroup)] _group: &Group,
) {
    use std::os::unix::process::ExitStatusExt as _;

    let (leaf, mut member, stdin) = entered_real_leaf();
    let leaf_path = leaf.leaf_path.clone();
    let name = leaf_path.file_name().expect("a name").to_string_lossy().into_owned();

    let (levels, records) = drop_under_a_mount(leaf, leaf_path.clone(), name, stdin);
    let status = member.wait().expect("reap the member");
    // Outside the dropping thread's namespace nothing is mounted over the leaf.
    std::fs::remove_dir(&leaf_path).expect("remove the drained leaf");

    assert_eq!(status.signal(), Some(libc::SIGKILL), "the real tree must be killed");
    assert_eq!(levels, vec![log::Level::Warn], "the leaf left behind is reported, once");
    assert!(
        records[0].contains("mount"),
        "the report must name a mount as a cause: {}",
        records[0]
    );
}

/// A mount over the leaf's name in the namespace its held descriptors were opened in: the name
/// no longer reaches the leaf, which says nothing about whether the leaf is gone. `Drop` kills the
/// real tree through the held leaf, and reports the leaf it cannot remove.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_an_armed_drop_under_a_mount_over_its_name_in_its_own_namespace_kills_the_tree_and_reports_the_leaf(
    #[fixture(cgroup)] _group: &Group,
) {
    use std::os::unix::process::ExitStatusExt as _;

    crate::log_capture::install();
    let (leaf_path, mut member, levels, records) = std::thread::spawn(|| {
        enter_a_private_mount_namespace();
        let (leaf, member, stdin) = entered_real_leaf();
        let leaf_path = leaf.leaf_path.clone();
        let name = leaf_path.file_name().expect("a name").to_string_lossy().into_owned();
        mount_a_tmpfs_over(&leaf_path);
        // Released after Drop's `hard_kill()`; see `drop_under_a_mount`.
        let mut stdin = Some(stdin);
        let _guard = on_each_drain_block(move |_| {
            if let Some(mut s) = stdin.take() {
                crate::test_child::write_to_possibly_dead_stdin(&mut s, b"x");
            }
        });
        let mark = crate::log_capture::mark();
        drop(leaf);
        (
            leaf_path,
            member,
            crate::log_capture::levels_since(mark, &name),
            crate::log_capture::records_since(mark, &name),
        )
    })
    .join()
    .expect("the dropping thread");
    let status = member.wait().expect("reap the member");
    // Outside the dropping thread's namespace nothing is mounted over the leaf.
    std::fs::remove_dir(&leaf_path).expect("remove the drained leaf");

    assert_eq!(status.signal(), Some(libc::SIGKILL), "the real tree must be killed");
    assert_eq!(levels, vec![log::Level::Warn], "the leaf left behind is reported, once");
    assert!(
        records[0].contains("mount"),
        "the report must name a mount as a cause: {}",
        records[0]
    );
}

/// A mount over the leaf's parent: the leaf's path finds nothing, which says nothing about the
/// leaf. `Drop` kills, drains and removes the real leaf through the held directories.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_an_armed_drop_under_a_mount_over_its_parent_still_removes_the_leaf(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;

    let (leaf, mut member, stdin) = entered_real_leaf();
    let leaf_path = leaf.leaf_path.clone();
    let parent = leaf_path.parent().expect("a parent").to_path_buf();
    let name = leaf_path.file_name().expect("a name").to_string_lossy().into_owned();

    let (levels, _) = drop_under_a_mount(leaf, parent, name, stdin);
    let removed = !leaf_path.exists();
    let status = member.wait().expect("reap the member");
    if !removed {
        crate::containment::cgroup::test_support::remove_drained_leaf(&leaf_path);
    }

    assert!(removed, "the real leaf must be killed through and removed");
    assert_eq!(status.signal(), Some(libc::SIGKILL), "the real tree must be killed");
    assert!(
        !levels.contains(&log::Level::Warn),
        "nothing was left behind, got {levels:?}"
    );
}

/// Without an inotify instance — `fs.inotify.max_user_instances` reached — no leaf is created:
/// the spawn degrades as for any other failed step, rather than leaving a leaf whose teardown
/// could not be watched. The half-made leaf is removed.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_a_leaf_whose_drain_cannot_be_watched_is_not_created(#[fixture(cgroup)] _group: &Group) {
    crate::containment::cgroup::fault::set_force_inotify_failure(true);
    let result = crate::containment::cgroup::try_create_leaf(None);
    let consumed = !crate::containment::cgroup::fault::take_force_inotify_failure();

    assert!(consumed, "the creation must have tried, and failed, to watch");
    // The error names the leaf it made, so the check needs no view of what else is in its parent.
    let leaf = match result {
        Err(LeafError::WatchDrain { source, path }) => {
            assert_eq!(source.raw_os_error(), Some(libc::EMFILE));
            path.parent().expect("cgroup.events is in the leaf").to_path_buf()
        }
        Err(e) => panic!("expected WatchDrain, got {e:?}"),
        Ok(_) => panic!("a leaf whose drain cannot be watched must not be created"),
    };
    assert!(!leaf.exists(), "the half-made leaf must be removed: {}", leaf.display());
}

// The leaf's shared watcher -----
// A leaf holds one inotify instance. Its pump, a thread the leaf owns, blocks on it and broadcasts
// every change; waits only listen and re-read the leaf.

/// A thread's own notifier for "a wait is about to block", as a sender to share.
#[cfg(all(target_os = "linux", feature = "tokio"))]
fn signal_when_blocking(tx: std::sync::mpsc::Sender<()>) {
    crate::containment::cgroup::fault::set_drain_blocking_notifier(tx);
}

/// A wait polled once and then never again holds nothing another wait needs: a second wait on
/// the same leaf, already blocked when the leaf drains, still returns.
#[cfg(all(target_os = "linux", feature = "tokio"))]
#[skuld::test]
fn a_parked_async_wait_does_not_hold_up_another() {
    use std::future::Future as _;

    use crate::containment::cgroup::test_support::FakeLeaf;
    use crate::containment::TreeDrain;

    let fake = FakeLeaf::new("cosca-parked-waiter", true);
    let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
    let runtime = ::tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("a runtime");
    runtime.block_on(async {
        let mut parked = std::pin::pin!(crate::containment::drain_edge::cgroup_wait_tree_drained(&leaf, None));
        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
        assert!(parked.as_mut().poll(&mut context).is_pending(), "the leaf is populated");

        let (blocking, blocking_rx) = std::sync::mpsc::channel();
        let other_leaf = leaf.clone();
        let other = std::thread::spawn(move || {
            signal_when_blocking(blocking);
            let runtime = ::tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("a runtime");
            runtime.block_on(crate::containment::drain_edge::cgroup_wait_tree_drained(
                &other_leaf,
                None,
            ))
        });
        blocking_rx.recv().expect("the second wait blocks");
        FakeLeaf::set_populated(&fake.events, false);
        assert_eq!(
            other.join().expect("the second waiter").expect("wait"),
            TreeDrain::AllMembersExited
        );
        // Still parked, never polled again: it held nothing the second wait needed.
        let _ = &parked;
    });
}

/// A sync and an async wait on one leaf both return once it drains, on the leaf's one watch: no
/// second inotify instance is armed.
#[cfg(all(target_os = "linux", feature = "tokio"))]
#[skuld::test]
fn a_sync_and_an_async_wait_share_the_leafs_one_watch() {
    use crate::containment::cgroup::test_support::FakeLeaf;
    use crate::containment::TreeDrain;

    let fake = FakeLeaf::new("cosca-two-waiters", true);
    let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
    let (blocking, blocking_rx) = std::sync::mpsc::channel();

    let (sync_leaf, sync_blocking) = (leaf.clone(), blocking.clone());
    let sync_waiter = std::thread::spawn(move || {
        signal_when_blocking(sync_blocking);
        sync_leaf.wait_drained(None)
    });
    let (async_leaf, async_blocking) = (leaf.clone(), blocking.clone());
    let async_waiter = std::thread::spawn(move || {
        signal_when_blocking(async_blocking);
        let runtime = ::tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime");
        runtime.block_on(crate::containment::drain_edge::cgroup_wait_tree_drained(
            &async_leaf,
            None,
        ))
    });

    blocking_rx.recv().expect("a waiter blocks");
    blocking_rx.recv().expect("the other waiter blocks");
    FakeLeaf::set_populated(&fake.events, false);

    assert_eq!(
        sync_waiter.join().expect("sync waiter").expect("sync wait"),
        TreeDrain::AllMembersExited
    );
    assert_eq!(
        async_waiter.join().expect("async waiter").expect("async wait"),
        TreeDrain::AllMembersExited
    );
    assert_eq!(
        crate::containment::cgroup::fault::arms_of("cosca-two-waiters"),
        1,
        "only the leaf's own watch is armed, at creation"
    );
}

/// A cancelled async wait leaves the others waiting as before.
#[cfg(all(target_os = "linux", feature = "tokio"))]
#[skuld::test]
fn a_cancelled_async_wait_leaves_the_others_waiting() {
    use crate::containment::cgroup::test_support::FakeLeaf;
    use crate::containment::TreeDrain;

    let fake = FakeLeaf::new("cosca-cancelled-waiter", true);
    let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
    let (blocking, blocking_rx) = std::sync::mpsc::channel();
    let (cancel, cancelled) = ::tokio::sync::oneshot::channel::<()>();

    let async_leaf = leaf.clone();
    let async_waiter = std::thread::spawn(move || {
        signal_when_blocking(blocking);
        let runtime = ::tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime");
        runtime.block_on(async {
            ::tokio::select! {
                drained = crate::containment::drain_edge::cgroup_wait_tree_drained(&async_leaf, None) => {
                    panic!("the leaf was never drained, got {drained:?}")
                }
                _ = cancelled => {}
            }
        });
    });
    blocking_rx.recv().expect("the async wait blocks");
    cancel.send(()).expect("cancel the async wait");
    async_waiter.join().expect("the async waiter");

    FakeLeaf::set_populated(&fake.events, false);
    assert_eq!(leaf.wait_drained(None).expect("wait"), TreeDrain::AllMembersExited);
}

/// A wait whose deadline has passed answers from the leaf's state at once.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_wait_past_its_deadline_answers_from_the_leafs_state() {
    use crate::containment::cgroup::test_support::FakeLeaf;
    use crate::containment::TreeDrain;

    let fake = FakeLeaf::new("cosca-past-deadline", true);
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
    assert_eq!(
        leaf.wait_drained(Some(std::time::Instant::now())).expect("wait"),
        TreeDrain::MembersRemain
    );
    FakeLeaf::set_populated(&fake.events, false);
    assert_eq!(
        leaf.wait_drained(Some(std::time::Instant::now())).expect("wait"),
        TreeDrain::AllMembersExited
    );
}

/// Block a wait on `leaf` on a thread of its own, returning once it blocks. The caller must keep
/// the returned `Receiver` alive until the handle is joined: `drain_step` can legally re-block
/// (`populated` is re-read before the pump's own broadcast lands), sending on this notifier
/// again, and a send with no live receiver is a contract violation `notify_drain_blocking`
/// debug-asserts against.
#[cfg(target_os = "linux")]
fn blocked_wait(
    leaf: &std::sync::Arc<crate::containment::cgroup::CgroupLeaf>,
) -> (
    std::thread::JoinHandle<Result<crate::containment::TreeDrain, crate::error::Error>>,
    std::sync::mpsc::Receiver<()>,
) {
    let (blocking, blocking_rx) = std::sync::mpsc::channel();
    let leaf = leaf.clone();
    let waiter = std::thread::spawn(move || {
        crate::containment::cgroup::fault::set_drain_blocking_notifier(blocking);
        leaf.wait_drained(None)
    });
    blocking_rx.recv().expect("the wait blocks");
    (waiter, blocking_rx)
}

/// The pump starts with the first wait that blocks, and dropping the leaf stops and joins it
/// before `drop` returns.
#[cfg(target_os = "linux")]
#[skuld::test]
fn dropping_the_leaf_stops_and_joins_its_pump() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;
    use crate::containment::TreeDrain;

    let fake = FakeLeaf::new("cosca-pumped-leaf", true);
    let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
    _ = leaf.wait_drained(Some(std::time::Instant::now()));
    assert_eq!(
        fault::pumps_of("cosca-pumped-leaf"),
        (0, 0),
        "a wait that cannot block starts none"
    );

    let (waiter, _blocking_rx) = blocked_wait(&leaf);
    assert_eq!(
        fault::pumps_of("cosca-pumped-leaf"),
        (1, 0),
        "a blocking wait starts the pump"
    );
    FakeLeaf::set_populated(&fake.events, false);
    assert_eq!(
        waiter.join().expect("waiter").expect("wait"),
        TreeDrain::AllMembersExited
    );

    FakeLeaf::set_populated(&fake.events, true);
    let (waiter, _blocking_rx) = blocked_wait(&leaf);
    FakeLeaf::set_populated(&fake.events, false);
    assert_eq!(
        waiter.join().expect("waiter").expect("wait"),
        TreeDrain::AllMembersExited
    );
    assert_eq!(fault::pumps_of("cosca-pumped-leaf"), (1, 0), "one pump per leaf");

    drop(std::sync::Arc::into_inner(leaf).expect("the waiters are joined"));
    assert_eq!(
        fault::pumps_of("cosca-pumped-leaf"),
        (1, 1),
        "the drop joins the pump it stopped"
    );
}

/// A drained leaf is answered from one read: no pump is started for it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_drained_leaf_is_answered_without_a_pump() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;
    use crate::containment::TreeDrain;

    let fake = FakeLeaf::new("cosca-drained-unpumped", false);
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
    assert_eq!(leaf.wait_drained(None).expect("wait"), TreeDrain::AllMembersExited);
    assert_eq!(
        leaf.wait_drained(Some(std::time::Instant::now())).expect("wait"),
        TreeDrain::AllMembersExited
    );
    #[cfg(feature = "tokio")]
    {
        let runtime = ::tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime");
        assert_eq!(
            runtime
                .block_on(crate::containment::drain_edge::cgroup_wait_tree_drained(&leaf, None))
                .expect("wait"),
            TreeDrain::AllMembersExited
        );
    }
    assert_eq!(fault::pumps_of("cosca-drained-unpumped"), (0, 0));
}

/// A pump that stops on its own wakes every wait, and each reports why.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_pump_wakes_every_wait_with_its_error() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let fake = FakeLeaf::new("cosca-failed-pump", true);
    let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
    let waiters = [blocked_wait(&leaf), blocked_wait(&leaf)];
    fault::set_force_pump_failure("cosca-failed-pump");
    // Readable once more: the pump wakes, and fails.
    FakeLeaf::set_populated(&fake.events, true);

    for (waiter, _blocking_rx) in waiters {
        let e = waiter.join().expect("waiter").expect_err("the pump failed");
        let said = crate::error::said(&e);
        assert!(said.contains("can no longer be watched"), "{said}");
        // The failed read of the watch is the error's source, with its code (the forced failure is
        // an `EIO`), and its words do not say it was forced.
        assert_eq!(crate::error::first_os_code(&e), Some(libc::EIO), "{e:?}");
        assert!(!said.contains("forced"), "{said}");
    }
    assert!(
        !fault::take_force_pump_failure("cosca-failed-pump".as_ref()),
        "the pump took it"
    );
}

/// A sibling's removal reaches the pump, which wakes no wait for it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_siblings_removal_wakes_no_wait() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;
    use crate::containment::TreeDrain;

    let fake = FakeLeaf::new("cosca-sibling-watcher", true);
    let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
    let (batches, batches_rx) = std::sync::mpsc::channel();
    fault::set_pump_batch_notifier("cosca-sibling-watcher", batches);
    let (waiter, _blocking_rx) = blocked_wait(&leaf);

    let sibling = fake.leaf.with_file_name("cosca-sibling");
    std::fs::create_dir(&sibling).expect("make a sibling");
    std::fs::remove_dir(&sibling).expect("remove the sibling");
    assert!(
        !batches_rx.recv().expect("a batch"),
        "a sibling's removal notifies no one"
    );

    FakeLeaf::set_populated(&fake.events, false);
    assert!(batches_rx.recv().expect("a batch"), "a write to cgroup.events notifies");
    assert_eq!(
        waiter.join().expect("waiter").expect("wait"),
        TreeDrain::AllMembersExited
    );
}

/// A pump started with no watch fails, waking its waits with the reason, rather than exiting
/// silently. Debug builds also assert it: every leaf that can be waited on holds a watch.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_pump_without_a_watch_fails_loudly() {
    use event_listener::Listener as _;

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let watcher = crate::containment::cgroup::Watcher::new(None, "cosca-unwatched".into());
    let listener = watcher.listen().expect("start the pump");
    listener.wait();
    assert!(
        watcher.failure().is_some_and(|why| why.words.contains("never armed")),
        "{:?}",
        watcher.failure()
    );
    drop(watcher);
    assert_eq!(
        crate::log_capture::contains_since(mark, "cosca-unwatched"),
        cfg!(debug_assertions),
        "the joined pump panicked on its debug assertion in exactly the builds that keep it"
    );
}

/// The pump's thread name fits Linux's 15 bytes, which would truncate it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_pump_thread_name_fits_the_kernels_limit() {
    assert!(crate::containment::cgroup::PUMP_THREAD.len() <= 15);
}

/// A leaf that is already GONE is not a leak at all: `rmdir` failing with `ENOENT` means some
/// other party removed it, which on a cgroup v2 leaf can only happen once it was empty. There
/// is nothing left on this host, so `Drop` must not report one — `hard_kill`'s own `debug` note
/// that the leaf is gone is the whole of what this path may say.
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_reports_nothing_for_a_leaf_that_is_already_gone() {
    crate::log_capture::install();
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-already-gone-leaf");

    let mark = crate::log_capture::mark();
    drop(crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path));

    let levels = crate::log_capture::levels_since(mark, "cosca-already-gone-leaf");
    assert!(
        !levels.contains(&log::Level::Warn),
        "an already-removed leaf left nothing on this host; reporting one as a leak is \
         narrating a non-event, got {levels:?}"
    );
}

// Leaf-creation steps past the cgroup.kill check -----
// `create_leaf_under` refuses a leaf with no `cgroup.kill` before it reaches any later step, so
// a temp directory cannot exercise those steps at all. The fault seam supplies exactly the one
// fact a temp directory cannot (`cgroup.kill` is present); everything after it — the open, the
// mapping, the unwind — then runs for real against the kernel's own errnos.

/// A `cgroup.procs` that cannot be opened reports THAT step, and takes the leaf it just created
/// with it. The leaf must not survive the degrade: a stray `cosca-*` cgroup is permanent on the
/// host, since nothing ever revisits it.
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_an_unopenable_cgroup_procs_and_removes_the_leaf() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::containment::cgroup::fault::set_force_kill_supported(true);
    let err = match crate::containment::cgroup::create_leaf_under(dir.path(), None) {
        Err(e) => e,
        Ok(_) => panic!("a plain directory has no cgroup.procs to open; leaf creation must fail"),
    };
    assert!(
        !crate::containment::cgroup::fault::kill_supported_armed(),
        "the seam must be consumed by the step it stands in for"
    );
    assert!(
        matches!(err, LeafError::OpenProcs { .. }),
        "expected OpenProcs, got {err:?}"
    );
    assert!(err.to_string().contains("cgroup.procs"), "got {err}");

    let strays: Vec<_> = std::fs::read_dir(dir.path())
        .expect("read tempdir")
        .map(|e| e.expect("entry").file_name())
        .collect();
    assert!(
        strays.is_empty(),
        "the degrade left {strays:?} behind — a cosca-* cgroup this host then keeps forever"
    );
}

/// A report channel that cannot be opened is its own degrade reason, and unwinds the leaf too.
/// `OpenReportChannel` is a condition that did not exist before the placement report did, so the
/// step it names, and the fact it leaves nothing behind, are both worth pinning.
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_an_unopenable_report_channel_and_removes_the_leaf() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::containment::cgroup::fault::set_force_kill_supported(true);
    crate::containment::cgroup::fault::set_force_report_channel_failure(true);
    let err = match crate::containment::cgroup::create_leaf_under(dir.path(), None) {
        Err(e) => e,
        Ok(_) => panic!("the report channel could not be opened; leaf creation must fail"),
    };
    assert!(
        !crate::containment::cgroup::fault::report_channel_failure_armed(),
        "the seam must be consumed by the channel it fails"
    );
    assert!(
        matches!(err, LeafError::OpenReportChannel(_)),
        "expected OpenReportChannel, got {err:?}"
    );
    assert_eq!(first_source_code(&err), Some(libc::EMFILE), "got {err:?}");

    let strays: Vec<_> = std::fs::read_dir(dir.path())
        .expect("read tempdir")
        .map(|e| e.expect("entry").file_name())
        .collect();
    assert!(strays.is_empty(), "a failed channel left {strays:?} behind");
}

/// A `cgroup.procs` that cannot be read is reported with the read's own error.
#[cfg(target_os = "linux")]
#[skuld::test]
fn take_placement_reports_an_unreadable_cgroup_procs() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-unreadable-procs");
    std::fs::create_dir(&leaf_path).expect("create the leaf");

    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
    match leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id()))) {
        Err(NotPlaced::Unreadable {
            pid,
            path,
            source,
            report,
        }) => {
            assert_eq!(pid, std::process::id());
            assert_eq!(path, leaf_path.join("cgroup.procs"));
            assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
            assert_eq!(report, NotEntered::NotReported, "no child ever ran");
        }
        Err(other) => panic!("an unreadable cgroup.procs must not read as an empty one: {other}"),
        Ok(()) => panic!("no child reported a placement"),
    }
}

/// A child that reported a failed write is diagnosed from the real `cgroup.procs` and its real
/// `/proc` state. The child is a zombie — exited, not yet reaped — so its state is known.
#[cfg(target_os = "linux")]
#[skuld::test]
fn take_placement_reads_the_real_procs_and_state_of_a_child_that_did_not_enter() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-absent-procs");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let listed = format!("{}\n", std::process::id());
    std::fs::write(leaf_path.join("cgroup.procs"), &listed).expect("write cgroup.procs");

    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
    // SAFETY: fd -1 is never writable, so the write fails with EBADF; closing -1 is a no-op.
    _ = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(-1, leaf.placement_slot()) };

    let mut child = crate::test_spawn::spawn(&mut std::process::Command::new("/bin/true")).expect("spawn");
    let pid = child.id();
    // Block until the child has exited, leaving it unreaped (WNOWAIT): a zombie.
    // SAFETY: `info` is a valid, writable siginfo_t; `pid` is this process's own child.
    let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
    let waited = unsafe { libc::waitid(libc::P_PID, pid, &mut info, libc::WEXITED | libc::WNOWAIT) };
    assert_eq!(waited, 0, "waitid: {}", std::io::Error::last_os_error());

    let verdict = leaf.take_placement(handle_of(pid, &pidfd_of(pid)));
    child.wait().expect("reap the child");
    match verdict {
        Err(NotPlaced::Absent {
            pid: reported,
            path,
            procs,
            report,
            child_state,
        }) => {
            assert_eq!(reported, pid);
            assert_eq!(path, leaf_path.join("cgroup.procs"));
            assert_eq!(procs, listed, "the file's real contents");
            assert_eq!(report, NotEntered::WriteFailed(libc::EBADF));
            assert_eq!(child_state, Some('Z'), "the child's real /proc state");
        }
        Err(other) => panic!("a readable cgroup.procs must be quoted: {other}"),
        Ok(()) => panic!("the child reported a failed write"),
    }
}

/// The child's `/proc` state is read BEFORE `cgroup.procs`, so a `Z` in the diagnosis means the
/// child had exited before the file was read.
///
/// `cgroup.procs` is a FIFO here, so the read of it is an event the test can act on: its writer
/// makes the child a zombie only once the read has begun, and lets the read finish only after.
/// Read first, the state is the live child's; read second, it would be `Z`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn take_placement_reads_the_childs_state_before_cgroup_procs() {
    use std::io::Write;

    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-ordered-reads");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let procs_path = leaf_path.join("cgroup.procs");
    nix::unistd::mkfifo(&procs_path, nix::sys::stat::Mode::S_IRWXU).expect("mkfifo cgroup.procs");
    // No report was stored, so the verdict reads both to diagnose the child.
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);

    // A live child, blocked reading a pipe nothing writes to.
    let mut child =
        crate::test_spawn::spawn(std::process::Command::new("/bin/cat").stdin(std::process::Stdio::piped()))
            .expect("spawn");
    let pid = child.id();
    let writer = std::thread::spawn(move || {
        // Blocks until the verdict opens the FIFO to read it.
        let mut fifo = std::fs::OpenOptions::new()
            .write(true)
            .open(&procs_path)
            .expect("open the FIFO");
        child.kill().expect("kill the child");
        // Block until the child has exited, leaving it unreaped (WNOWAIT): a zombie.
        // SAFETY: `info` is a valid, writable siginfo_t; `pid` is this process's own child.
        let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
        let waited = unsafe { libc::waitid(libc::P_PID, pid, &mut info, libc::WEXITED | libc::WNOWAIT) };
        assert_eq!(waited, 0, "waitid: {}", std::io::Error::last_os_error());
        fifo.write_all(b"listed\n").expect("write the FIFO");
        child
    });

    let verdict = leaf.take_placement(handle_of(pid, &pidfd_of(pid)));
    writer.join().expect("the writer").wait().expect("reap the child");
    match verdict {
        Err(NotPlaced::Absent { procs, child_state, .. }) => {
            assert_eq!(procs, "listed\n");
            assert!(
                child_state.is_some_and(|state| state != 'Z'),
                "the state was read after cgroup.procs: {child_state:?}"
            );
        }
        Err(other) => panic!("a readable cgroup.procs must be quoted: {other}"),
        Ok(()) => panic!("no child reported a placement"),
    }
}

// What the placement hook returns -----
// `pre_exec` failing aborts the spawn. A failed placement must not (the child degrades to its
// process group); a report the waiting parent can never receive must (it would read as never
// placed for as long as the child lives).

/// A failed placement whose report is delivered lets the spawn proceed.
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_proceeds_past_a_failed_placement() {
    let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
    // SAFETY: fd -1 is never writable, so the placement fails with EBADF; the channel is open.
    let result = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(-1, channel.slot()) };
    assert!(
        result.is_ok(),
        "a failed placement must not abort the spawn: {result:?}"
    );
    assert_eq!(channel.report_for_test(), PlacementReport::WriteFailed(libc::EBADF));
}

/// A report that cannot be sent to a parent still waiting for it fails the spawn.
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_fails_when_its_report_cannot_be_sent() {
    let sink = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/null")
        .expect("open /dev/null");
    let procs_fd = std::os::fd::IntoRawFd::into_raw_fd(sink);
    // fd -1 is never open, so the send fails with EBADF.
    let slot = crate::containment::cgroup::ReportSlot { fd: -1, parent_fd: -1 };
    // SAFETY: `procs_fd` is open and closed by the hook; the slot's fd is deliberately invalid.
    let result = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot) };
    assert_eq!(
        result.map_err(|e| e.raw_os_error()),
        Err(Some(libc::EBADF)),
        "an undeliverable report must abort the spawn"
    );
}

/// A parent that decided without the exchange sends *proceed* and closes its end. In a real
/// spawn the child's own inherited copy of that end would keep the socket open, so the hook closes
/// it first; the child's send then fails, finds *proceed*, and the child carries on to `exec` —
/// without `SIGPIPE`, and without touching the leaf it no longer needs.
///
/// Ordered by primitives: the forked child signals, then waits on a gate that the deciding thread
/// opens only after it has decided.
///
/// Runs in a copy of this test binary running only this test. Any other process this one forks
/// while the channel is open holds a copy of the parent's end until its own `exec`, and would keep
/// the socket open past the parent's close — the child's send would then queue, and the child
/// carry on having written its placement: a decision honoured, but not the branch under test.
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_proceeds_when_the_parent_decided_without_the_exchange() {
    use std::io::{Read, Write};
    use std::os::fd::{AsRawFd, IntoRawFd};
    use std::os::unix::process::CommandExt;

    const NAME: &str =
        "containment::cgroup::leaf::leaf_tests::placement_hook_proceeds_when_the_parent_decided_without_the_exchange";
    const INNER: &str = "COSCA_TESTCFG_DECIDED_ALONE";
    if std::env::var_os(INNER).is_none() {
        let out = crate::test_spawn::output_captured(
            crate::test_reexec::with_json_events(
                crate::test_reexec::command(std::env::current_exe().expect("this test binary")).args([
                    NAME,
                    "--exact",
                    crate::test_reexec::NOCAPTURE,
                    "--test-threads=1",
                ]),
            )
            .env(INNER, "1"),
        )
        .expect("run the case alone");
        let stdout = String::from_utf8_lossy(&out.stdout);
        if let Err(why) = crate::test_reexec::suite_passed_exactly_one(&out) {
            panic!(
                "{why}\n{}\n--- stdout ---\n{stdout}\n--- stderr ---\n{}",
                out.status,
                String::from_utf8_lossy(&out.stderr)
            );
        }
        return;
    }

    let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
    let slot = channel.slot();
    let (procs_read, procs_write) = std::io::pipe().expect("a pipe standing in for cgroup.procs");
    let procs_fd = procs_write.into_raw_fd();
    let (mut forked_read, forked_write) = std::io::pipe().expect("open the forked signal");
    let (gate_read, mut gate_write) = std::io::pipe().expect("open the gate");
    let (forked_fd, gate_fd) = (forked_write.as_raw_fd(), gate_read.as_raw_fd());
    let decider = std::thread::spawn(move || {
        let mut byte = [0u8; 1];
        forked_read.read_exact(&mut byte).expect("the child forked");
        channel.proceed();
        gate_write.write_all(b"x").expect("release the child");
    });
    let mut cmd = std::process::Command::new("/bin/true");
    // SAFETY: the closure runs between fork and exec, and makes only async-signal-safe calls on
    // descriptors this test keeps open across the spawn.
    unsafe {
        cmd.pre_exec(move || {
            libc::write(forked_fd, b"x".as_ptr().cast(), 1);
            block_on(gate_fd);
            crate::containment::cgroup::placement_hook(procs_fd, slot)
        })
    };
    let status = crate::test_spawn::spawn(&mut cmd)
        .expect("a decided exchange must not abort the spawn")
        .wait();
    // SAFETY: the parent's own copy, closed once.
    unsafe { libc::close(procs_fd) };
    decider.join().expect("the deciding thread");
    drop(forked_write);
    assert!(status.expect("wait").success(), "the child must have exec'd");
    assert_eq!(
        std::io::read_to_string(procs_read).expect("read the pipe"),
        "",
        "no placement write"
    );
}

/// A parent that abandoned the spawn shut its end without *proceed*: the child's first send fails,
/// and the hook fails the spawn with `ECANCELED` before touching the leaf — so the child exits
/// instead of exec'ing.
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_fails_a_spawn_the_parent_abandoned_before_touching_the_leaf() {
    let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
    let (_end, slot) = childs_copy(&channel);
    let (procs_read, procs_write) = std::io::pipe().expect("a pipe standing in for cgroup.procs");
    let received = channel.shut();
    assert!(received.pid.is_none(), "nothing was sent before the shut");
    // SAFETY: as above.
    let result = unsafe {
        crate::containment::cgroup::place_self_in_cgroup_pre_exec(
            std::os::fd::IntoRawFd::into_raw_fd(procs_write),
            slot,
        )
    };
    assert_eq!(result.map_err(|e| e.raw_os_error()), Err(Some(libc::ECANCELED)));
    assert_eq!(
        std::io::read_to_string(procs_read).expect("read the pipe"),
        "",
        "no placement write"
    );
}

/// A child held before its hook while the parent abandons the spawn never execs: released, its
/// first send fails with no *proceed*, and it exits from inside its hook with `ABANDONED_EXIT`,
/// rather than return an error to `std` — which would write its error record to the fd number its
/// error channel had, a stdio slot once `std` returned early. A regression exits 0 here (the
/// forked body's own `_exit`).
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_child_released_after_its_spawn_was_abandoned_never_execs() {
    use std::io::Write;
    use std::os::fd::{AsRawFd, IntoRawFd};

    let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
    let slot = channel.slot();
    let (procs_read, procs_write) = std::io::pipe().expect("a pipe standing in for cgroup.procs");
    let procs_fd = procs_write.into_raw_fd();
    let (gate_read, mut gate_write) = std::io::pipe().expect("open the gate");
    let gate = gate_read.as_raw_fd();
    let guard = fork_running(&[gate, procs_fd, slot.fd, slot.parent_fd], move || {
        block_on(gate);
        // SAFETY: this child's inherited copies of the channel's ends and the pipe.
        _ = unsafe { crate::containment::cgroup::placement_hook(procs_fd, slot) };
    });
    // SAFETY: the parent's own copy, closed once; the child keeps its own.
    unsafe { libc::close(procs_fd) };
    let received = channel.shut();
    assert!(received.pid.is_none(), "the child was held before its hook");
    gate_write.write_all(b"x").expect("release the child");

    let pid = guard.defuse();
    let mut status = 0;
    // SAFETY: `pid` is this process's own child; `status` is a valid, writable int.
    assert_eq!(unsafe { libc::waitpid(pid as i32, &mut status, 0) }, pid as i32);
    assert!(libc::WIFEXITED(status), "status {status:#x}");
    assert_eq!(
        libc::WEXITSTATUS(status),
        crate::containment::cgroup::ABANDONED_EXIT,
        "the abandoned child must exit from its hook, not exec"
    );
    assert_eq!(
        std::io::read_to_string(procs_read).expect("read the pipe"),
        "",
        "no placement write"
    );
}

/// Through a real spawn: an undeliverable report aborts it rather than exec'ing a child the
/// parent would misread as never placed.
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_aborts_a_spawn_whose_report_cannot_be_sent() {
    use std::os::unix::process::CommandExt;

    let sink = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/null")
        .expect("open /dev/null");
    let procs_fd = std::os::fd::IntoRawFd::into_raw_fd(sink);
    let slot = crate::containment::cgroup::ReportSlot { fd: -1, parent_fd: -1 };
    let mut cmd = std::process::Command::new("/bin/true");
    // SAFETY: the closure runs between fork and exec, and performs only async-signal-safe calls.
    unsafe { cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot)) };
    let result = crate::test_spawn::spawn(&mut cmd);
    // SAFETY: the parent's own copy of the descriptor, closed exactly once.
    unsafe { libc::close(procs_fd) };
    assert!(result.is_err(), "the spawn must fail");
}

/// A leaf dropped before its verdict, with no report received and nothing in it, is removed: a
/// removed leaf admits no member, so the in-flight report cannot matter.
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_removes_an_empty_leaf_whose_report_is_in_flight_without_a_kill() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-in-flight-empty");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    drop(crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone()));
    assert!(!leaf_path.exists(), "the leaf must be removed");
}

/// A real leaf dropped before its verdict, occupied by a process that is not its child: the
/// abandoned exchange received nothing, so nothing of the child's is there, and the occupant is
/// not cosca's to kill. It survives — proven by an echo — and the leaf is reported, not killed.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_drop_of_an_abandoned_spawn_spares_an_occupant_that_is_not_its_child(#[fixture(cgroup)] _group: &Group) {
    use std::io::{Read, Write};
    use std::os::unix::process::CommandExt;
    let leaf = crate::containment::cgroup::try_create_leaf(None).expect("a delegated cgroup v2 leaf");
    let leaf_path = leaf.leaf_path.clone();
    // The occupant reports through a channel of its own, so the leaf's receives nothing.
    let own = crate::containment::cgroup::ReportChannel::new().expect("open the occupant's channel");
    let (procs_fd, slot) = (leaf.procs_fd(), own.slot());
    let mut cmd = std::process::Command::new("/bin/cat");
    cmd.stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    // SAFETY: the closure runs between fork and exec, and performs only async-signal-safe calls
    // on descriptors `leaf` and `own` keep open across the spawn.
    unsafe { cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot)) };
    let mut occupant = crate::test_spawn::spawn(&mut cmd).expect("spawn the occupant");

    drop(leaf);

    let mut echo = [0u8; 1];
    occupant
        .stdin
        .as_mut()
        .expect("stdin")
        .write_all(b"x")
        .expect("write to the occupant");
    occupant
        .stdout
        .as_mut()
        .expect("stdout")
        .read_exact(&mut echo)
        .expect("the occupant must still be alive to echo");
    assert_eq!(&echo, b"x");
    assert!(leaf_path.exists(), "an occupied leaf is left, and reported");

    occupant.kill().expect("kill the occupant");
    occupant.wait().expect("reap the occupant");
    std::fs::remove_dir(&leaf_path).expect("remove the emptied leaf");
}

/// A leaf that is already gone answers its `cgroup.kill` write `Ok`, and that answer is the
/// teardown's one: a removal that then fails makes no second write (the fault would fail one).
///
/// Mutant: a write answered by a gone leaf is not recorded, so the removal writes again.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_gone_leafs_kill_is_the_teardowns_one_write() {
    use crate::containment::cgroup::fault;

    crate::log_capture::install();
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-gone-leaf-kill");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
    std::fs::remove_dir(&leaf_path).expect("remove the leaf behind the handle's back");
    leaf.hard_kill().expect("a gone leaf is a completed teardown");
    let _next_write_fails = fault::fail_next_kill_write();

    let mark = crate::log_capture::mark();
    leaf.drain_and_remove("in a test", &mut crate::containment::cgroup::NoWarn, false);

    let warns = crate::log_capture::records_since_on_current_thread(mark, "cgroup.kill failed");
    assert!(warns.is_empty(), "the removal wrote again: {warns:?}");
}

/// The teardown that makes the `cgroup.kill` write and the one that finds it made word its failure
/// the same.
///
/// Mutant: the writing path answers with the failure's whole chain, the recorded one with its text.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_leaf_kill_is_worded_the_same_by_the_writer_and_by_a_later_teardown() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-kill-wording");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    let _write_fails = crate::containment::cgroup::fault::fail_next_kill_write();

    let written = leaf.kill_unless_written();
    let found = leaf.kill_unless_written();

    assert_eq!(written, Err(std::io::Error::from_raw_os_error(libc::EIO).to_string()));
    assert_eq!(found, written);
}

/// A failed `cgroup.kill` of an abandoned spawn is warned once when the `rmdir` then succeeds: the
/// removal reports nothing, so the abandonment's one warn carries it.
///
/// Mutant: the failed kill is logged at `debug` and the successful removal says nothing.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_spawns_failed_leaf_kill_is_warned_when_the_removal_succeeds() {
    crate::log_capture::install();
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-kill-failed-removed");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
    // The report says `Placed`, as a child that entered the leaf sends; no child is given.
    let sink = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/null")
        .expect("open /dev/null");
    let procs_fd = std::os::fd::IntoRawFd::into_raw_fd(sink);
    // SAFETY: `procs_fd` is open and closed by the hook; the channel is open.
    unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, leaf.placement_slot()) }
        .expect("report a placement");
    let _first_write_fails = crate::containment::cgroup::fault::fail_next_kill_write();

    let mark = crate::log_capture::mark();
    assert_eq!(
        leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
        WithoutChild::Named
    );

    assert!(!leaf_path.exists(), "the leaf is removed");
    let warns = crate::log_capture::records_since_on_current_thread(mark, "cgroup.kill failed");
    assert_eq!(warns.len(), 1, "the failed kill is warned once: {warns:?}");
}

/// An intent names its child by a number alone, which `std` may have freed by reaping it. Given no
/// pidfd for it, the abandonment answers for no child and sends nothing, even when the number
/// names a live child of this process: that child is not this spawn's.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_intent_given_no_pidfd_is_never_signalled() {
    use std::io::{Read, Write};

    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-no-handle");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    let mut other = crate::test_spawn::spawn(
        std::process::Command::new("/bin/cat")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped()),
    )
    .expect("spawn another child");
    // SAFETY: the leaf's channel is open; the intent claims `other`'s pid.
    unsafe {
        leaf.placement_slot()
            .send(crate::containment::cgroup::TAG_INTENT, other.id() as i32)
            .expect("send a forged intent");
    }

    assert_eq!(
        leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
        WithoutChild::Named,
        "the intent named a pid"
    );

    let mut echo = [0u8; 1];
    other
        .stdin
        .as_mut()
        .expect("stdin")
        .write_all(b"x")
        .expect("write to the other child");
    other
        .stdout
        .as_mut()
        .expect("stdout")
        .read_exact(&mut echo)
        .expect("the other child must be alive to echo");
    other.kill().expect("kill the other child");
    other.wait().expect("reap the other child");
}

/// A spawn abandoned before its child sent anything cannot tell whether it forked: a child that
/// exists exits at its first send, but nothing holds its pid to reap it. That is not `Ended`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_spawn_whose_child_sent_nothing_may_leave_it_unreaped() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-silent");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());

    assert_eq!(
        leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
        WithoutChild::Unnamed,
        "nothing named a pid"
    );
    assert!(!leaf_path.exists(), "the empty leaf is removed");
}

/// The leaf answers for a spawn once: a second abandonment is a breach of the contract, which
/// debug builds assert.
///
/// Mutant: a repeated call answers as the first did, or silently.
#[cfg(all(target_os = "linux", debug_assertions))]
#[skuld::test]
#[should_panic(expected = "the leaf answers for a child once")]
fn an_abandonment_without_a_child_repeated_is_a_breach() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-twice");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);

    assert_eq!(
        leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
        WithoutChild::Unnamed
    );
    assert_eq!(
        leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
        WithoutChild::AlreadyAbandoned
    );
}

/// Only a write of the whole `"0"` is a placement. A write that returns without writing it — 0,
/// where no errno is set — is a failed placement, reported as `EIO`, never as `Placed`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_reports_a_write_that_wrote_nothing_as_failed() {
    let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
    let sink = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/null")
        .expect("open /dev/null");
    let procs_fd = std::os::fd::IntoRawFd::into_raw_fd(sink);
    crate::containment::cgroup::fault::set_force_placement_write_result(0);
    // SAFETY: `procs_fd` is open and closed by the hook; the channel is open.
    let result = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, channel.slot()) };
    assert!(
        result.is_ok(),
        "a failed placement must not abort the spawn: {result:?}"
    );
    assert_eq!(channel.report_for_test(), PlacementReport::WriteFailed(libc::EIO));
}

/// `rmdir` refuses a leaf that holds a child cgroup with the same `EBUSY` it gives a populated
/// one, and killing through the leaf removes no directory. A leaf dropped with its report in
/// flight must remove the empty child cgroups itself rather than kill-and-retry forever. A
/// regression hangs this test in `drop`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_drop_removes_a_leaf_holding_child_cgroups(#[fixture(cgroup)] _group: &Group) {
    // Placed: killed through, drained, swept. Nothing received: swept without a kill.
    for placed in [true, false] {
        let leaf = crate::containment::cgroup::try_create_leaf(None).expect("a delegated cgroup v2 leaf");
        let leaf_path = leaf.leaf_path.clone();
        std::fs::create_dir_all(leaf_path.join("nested").join("deeper")).expect("create child cgroups");
        if placed {
            // SAFETY: the slot's channel lives as long as `leaf`.
            unsafe { leaf.placement_slot().report_placed_for_test() };
        }

        drop(leaf);

        assert!(
            !leaf_path.exists(),
            "placed: {placed}: the leaf and its child cgroups must be removed"
        );
    }
}

/// A leaf's name carries 64 random bits past the pid and sequence number, which repeat across
/// pid namespaces sharing a delegated parent, and across processes reusing a pid.
#[cfg(target_os = "linux")]
#[skuld::test]
fn leaf_names_carry_random_bits_past_the_pid_and_sequence() {
    let suffix = |name: String| {
        let parts = name.split('-').collect::<Vec<_>>();
        assert_eq!(parts.len(), 4, "cosca-<pid>-<seq>-<random>: {name}");
        assert_eq!((parts[0], parts[1]), ("cosca", std::process::id().to_string().as_str()));
        assert!(
            parts[3].len() == 16 && parts[3].bytes().all(|b| b.is_ascii_hexdigit()),
            "{name}"
        );
        parts[3].to_owned()
    };
    let a = suffix(crate::containment::cgroup::leaf_name().expect("a name"));
    let b = suffix(crate::containment::cgroup::leaf_name().expect("a name"));
    assert_ne!(a, b);
}

/// A leaf watches one front: watching it again is fine, and a second front is refused. A contract,
/// asserted in debug.
#[cfg(all(target_os = "linux", debug_assertions))]
#[skuld::test]
fn a_leaf_watches_one_front() {
    let mut leaf = crate::containment::cgroup::CgroupLeaf::placeholder_for_test();
    leaf.watch_front(7);
    leaf.watch_front(7);
    let second = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| leaf.watch_front(8)));
    let message = second.expect_err("a second front was watched");
    let message = message
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| message.downcast_ref::<&str>().copied())
        .unwrap_or_default();
    assert!(message.contains("a leaf watches one front"), "{message}");
}

/// How [`terminate_reports_a_member_it_could_not_signal`] keeps a member from its `SIGTERM`.
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy)]
enum Unsignalled {
    Unpinned,
    Unplaced,
    SendFailed,
}

/// A member `terminate` could not pin, place or signal got no `SIGTERM`: the call is an error, and
/// one `warn` names the leaf and the pid. The member ends at its stdin's EOF, after the call, so a
/// `SIGTERM` sent anyway shows as its death by that signal. Mutants: "a member left unsignalled is a
/// `debug` line and `Ok`", "the member is signalled anyway, then reported", "a send the seam
/// refused is noted as made".
#[cfg(target_os = "linux")]
fn terminate_reports_a_member_it_could_not_signal(how: Unsignalled) {
    use std::os::unix::process::ExitStatusExt as _;

    use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
    crate::log_capture::install();
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf
        .path()
        .file_name()
        .expect("a leaf name")
        .to_string_lossy()
        .into_owned();
    take_member_terms();
    let mark = crate::log_capture::mark();
    let guard: Box<dyn std::any::Any> = match how {
        Unsignalled::Unpinned => Box::new(fail_terminate(TerminateStep::Pin, libc::EMFILE)),
        // Neither route can place the member: `/proc` hides it, and no pidfd gives its cgroup.
        Unsignalled::Unplaced => Box::new((
            crate::containment::cgroup::fault::miss_pidfd_info(),
            crate::containment::cgroup::fault::hide_proc(),
        )),
        Unsignalled::SendFailed => Box::new(fail_terminate(TerminateStep::Send, libc::EIO)),
    };
    let result = leaf.terminate().expect("cgroup.procs is readable");
    drop(guard);
    // No send was made, so none is noted, a refused one included.
    assert_eq!(take_member_terms(), []);
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    drop(stdin);
    let status = member.wait().expect("reap the member");
    drop(leaf);
    assert_eq!(status.signal(), None, "the member got no SIGTERM: {status:?}");
    let err = result.expect_err("a member got no SIGTERM");
    // The error names the leaf; the member below it names its pid.
    let detail = err.to_string();
    assert!(detail.contains(&leaf_name), "{detail}");
    let reported = crate::error::said(&err);
    assert!(reported.contains(&format!("pid {pid}")), "{reported}");
    match how {
        Unsignalled::SendFailed => assert!(matches!(err, crate::error::Error::Containment { .. }), "{err:?}"),
        _ => assert!(matches!(err, crate::error::Error::Unassessable { .. }), "{err:?}"),
    }
    // The one member's cause is the error's source, with its OS code, and not in its text.
    let code = match how {
        Unsignalled::Unpinned => Some(libc::EMFILE),
        Unsignalled::SendFailed => Some(libc::EIO),
        // Which errno a hidden `/proc` answers is the kernel's.
        Unsignalled::Unplaced => None,
    };
    match code {
        Some(code) => {
            assert_eq!(crate::error::first_os_code(&err), Some(code), "{err:?}");
            let os_error = std::io::Error::from_raw_os_error(code).to_string();
            assert!(!detail.contains(&os_error), "{detail}");
        }
        None => assert!(crate::error::first_os_code(&err).is_some(), "{err:?}"),
    }
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains(&format!("pid {pid}")), "{warns:?}");
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_it_could_not_pin(#[fixture(cgroup)] _group: &Group) {
    terminate_reports_a_member_it_could_not_signal(Unsignalled::Unpinned);
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_it_could_not_place(#[fixture(cgroup)] _group: &Group) {
    terminate_reports_a_member_it_could_not_signal(Unsignalled::Unplaced);
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_whose_sigterm_failed(#[fixture(cgroup)] _group: &Group) {
    terminate_reports_a_member_it_could_not_signal(Unsignalled::SendFailed);
}

/// `terminate` signals a member only once it is shown, through a pidfd that pins it, to still be in
/// the leaf: one that left between the `cgroup.procs` read and that check is not signalled. A member
/// that leaves after the check is signalled anyway (see `CgroupLeaf::terminate`). Mutant: "signal
/// every listed pid by number".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_leaves_alone_a_member_that_left_after_the_listing(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    let _armed = crate::containment::cgroup::fault::set_after_procs_read(move || {
        crate::child::front_cgroup_tests::move_out_of_its_leaf(pid);
    });
    crate::containment::cgroup::fault::take_member_terms();
    leaf.terminate().expect("cgroup.procs is readable").expect("terminate");
    assert_eq!(crate::containment::cgroup::fault::take_member_terms(), []);
    drop(stdin);
    let status = member.wait().expect("reap the member");
    assert_eq!(status.signal(), None, "the member exited on its own EOF: {status:?}");
    drop(leaf);
}

/// `terminate` sends a running member its `SIGTERM` through the member's pidfd, which the shared
/// send notes once made, with the route of its syscall. Mutants: "the `SIGTERM` is not sent", "the
/// `SIGTERM` goes by the member's number", "the `SIGTERM` is another signal".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_sends_a_member_its_sigterm(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    crate::containment::cgroup::fault::take_member_terms();
    let result = leaf.terminate().expect("cgroup.procs is readable");
    let noted = crate::containment::cgroup::fault::take_member_terms();
    drop(stdin);
    let status = member.wait().expect("reap the member");
    drop(leaf);
    assert_eq!(status.signal(), Some(libc::SIGTERM), "got {status:?}");
    assert_eq!(noted, [(Some(pid), crate::send_log::Via::Pidfd, libc::SIGTERM)]);
    result.expect("terminate");
}

/// A member that exits and is reaped after `terminate` pinned it, before it is placed, is gone, not
/// a failure: its place can no longer be read, and its pidfd says it exited. Nothing is sent, and
/// nothing warns; the debug record of it carries the placement error. Mutants: "a placement error
/// after the pin is a failure", "the record leaves the placement error out".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_counts_a_member_reaped_after_its_pin_as_gone(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let (leaf, member, _stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf
        .path()
        .file_name()
        .expect("a leaf name")
        .to_string_lossy()
        .into_owned();
    let _armed = crate::containment::cgroup::fault::set_after_terminate_pin(move || {
        // SAFETY: `pid` is this test's own unreaped child.
        assert_eq!(
            unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) },
            0,
            "kill the member"
        );
        crate::test_child::reaped_elsewhere::reap_behind(pid);
    });
    crate::containment::cgroup::fault::take_member_terms();
    let mark = crate::log_capture::mark();
    let result = leaf.terminate().expect("cgroup.procs is readable");
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    let gone = crate::log_capture::records_since_on_current_thread(mark, "exited before it was placed");
    assert_eq!(crate::containment::cgroup::fault::take_member_terms(), []);
    result.expect("a member reaped after its pin is gone");
    assert_eq!(warns, Vec::<String>::new(), "nothing warns of a member that is gone");
    let [(level, text)] = gone.as_slice() else {
        panic!("the member's debug record is the one that says it exited before it was placed: {gone:?}");
    };
    assert_eq!(*level, log::Level::Debug, "{text}");
    assert!(
        text.contains("os error"),
        "the record carries the placement error it was told by: {text}"
    );
    drop(leaf);
}

/// A leaf whose cgroup id cannot be read (no `CONFIG_FHANDLE`, a seccomp filter) still has its
/// members signalled, placed through `/proc`: the id serves only the pidfd route. The fallback is
/// logged at `debug`, naming `/proc`, and nothing warns. Mutants: "`terminate` needs the leaf's id
/// to place any member", "the fallback is a `warn`", "the fallback is not logged".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_signals_a_member_when_the_leafs_id_cannot_be_read(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;
    crate::log_capture::install();
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf_name_of(&leaf);
    let _no_id = crate::containment::cgroup::fault::fail_cgroup_id(libc::EPERM);
    crate::containment::cgroup::fault::take_member_terms();
    let mark = crate::log_capture::mark();
    let result = leaf.terminate().expect("cgroup.procs is readable");
    let noted = crate::containment::cgroup::fault::take_member_terms();
    let records = crate::log_capture::records_since_on_current_thread(mark, &leaf_name);
    drop(stdin);
    let status = member.wait().expect("reap the member");
    drop(_no_id);
    drop(leaf);
    assert_eq!(status.signal(), Some(libc::SIGTERM), "got {status:?}");
    assert_eq!(noted, [(Some(pid), crate::send_log::Via::Pidfd, libc::SIGTERM)]);
    result.expect("terminate");
    let [(level, text)] = records.as_slice() else {
        panic!("the fallback is the one record naming the leaf: {records:?}");
    };
    assert_eq!(*level, log::Level::Debug, "{text}");
    assert!(text.contains("/proc"), "{text}");
}

/// A leaf whose cgroup id cannot be read and a member that got no `SIGTERM` make one `warn` between
/// them: the call's own, which names the leaf and the member. Mutant: "the fallback warns too".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_warns_once_when_the_id_cannot_be_read_and_a_member_is_unsignalled(
    #[fixture(cgroup)] _group: &Group,
) {
    crate::log_capture::install();
    let leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
    let leaf_name = leaf_name_of(&leaf);
    let _no_id = crate::containment::cgroup::fault::fail_cgroup_id(libc::EPERM);
    let mark = crate::log_capture::mark();
    let result = leaf.terminate_listed("0\n");
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    drop(_no_id);
    drop(leaf);
    assert!(
        matches!(result, Err(crate::error::Error::Unassessable { .. })),
        "got {result:?}"
    );
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("pid 0"), "{warns:?}");
}

/// The leaf's name, which its log records carry.
#[cfg(target_os = "linux")]
fn leaf_name_of(leaf: &crate::containment::cgroup::CgroupLeaf) -> String {
    leaf.path()
        .file_name()
        .expect("a leaf name")
        .to_string_lossy()
        .into_owned()
}

/// A real leaf with `n` members, each a blocker on a piped stdin it holds open, and those pipes'
/// write ends: dropping one ends its member.
#[cfg(target_os = "linux")]
fn real_leaf_with_members(
    n: usize,
) -> (
    crate::containment::cgroup::CgroupLeaf,
    Vec<(std::process::Child, std::process::ChildStdin)>,
) {
    use std::os::unix::process::CommandExt;

    let leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
    let members = (0..n)
        .map(|_| {
            // Each member reports through its own channel: the leaf's carries one report.
            let mut channel = crate::containment::cgroup::ReportChannel::new().expect("open a report channel");
            let mut cmd = crate::test_child::held_std_blocker(std::process::Stdio::null());
            let (procs_fd, slot) = (leaf.procs_fd(), channel.slot());
            // SAFETY: as `entered_real_leaf_of`'s member spawn: the closure runs between fork and
            // exec, and `leaf` outlives the spawn.
            unsafe {
                cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot));
            }
            let mut member = crate::test_spawn::spawn(&mut cmd).expect("spawn a member");
            let stdin = member.stdin.take().expect("piped stdin");
            assert_eq!(
                channel.wait(pidfd_of(member.id()).as_fd()),
                PlacementReport::Placed,
                "the member entered the leaf"
            );
            (member, stdin)
        })
        .collect();
    (leaf, members)
}

/// A listed pid `0` is a live member in a pid namespace this process cannot see, which it can
/// neither name nor signal: the members after it are still signalled, and the call is
/// `Unassessable`, with one `warn` naming the leaf and `pid 0`, as for any member that got no
/// `SIGTERM`. Mutants: "a listed `0` is skipped and the call is `Ok`", "a listed `0` is pinned like
/// any pid" (it is then reported as a pin failure, not as a member in another namespace).
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_listed_pid_zero_as_unassessable(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;
    crate::log_capture::install();
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf
        .path()
        .file_name()
        .expect("a leaf name")
        .to_string_lossy()
        .into_owned();
    crate::containment::cgroup::fault::take_member_terms();
    let mark = crate::log_capture::mark();
    let result = leaf.terminate_listed(&format!(
        "0
{pid}
"
    ));
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    drop(stdin);
    let status = member.wait().expect("reap the member");
    drop(leaf);
    assert_eq!(
        status.signal(),
        Some(libc::SIGTERM),
        "the member after the 0 is signalled: {status:?}"
    );
    match result {
        // The one member that got no SIGTERM is the call's `source`, with its pid in its own words.
        Err(error @ crate::error::Error::Unassessable { .. }) => {
            let said = crate::error::said(&error);
            assert!(said.contains("pid 0: "), "{said}");
            assert!(said.contains("pid namespace"), "{said}");
            assert!(
                !said.contains(&format!("pid {pid}:")),
                "the signalled member is not reported: {said}"
            );
        }
        other => panic!("a listed pid 0 was not signalled: expected Unassessable, got {other:?}"),
    }
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("pid 0"), "{warns:?}");
}

/// A leaf that lists only pid `0` has nothing signalled, and says so: `Unassessable`, not `Ok`.
/// Mutant: "no pid left to signal is `Ok`, whatever was skipped".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_leaf_listing_only_pid_zero(#[fixture(cgroup)] _group: &Group) {
    let leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
    let result = leaf.terminate_listed("0\n");
    drop(leaf);
    assert!(
        matches!(result, Err(crate::error::Error::Unassessable { .. })),
        "got {result:?}"
    );
}

/// Listed members that got no `SIGTERM` are each a member of the `Several` below the error, in the
/// order of the listing, each with its own cause; the error's own words count them and carry no
/// member's pid or cause. Unprivileged: no member is real, as the pin is refused by a fault.
///
/// Mutants: the causes are folded into the detail; only one cause is kept when there are several; the
/// members with no cause of their own are dropped.
#[cfg(target_os = "linux")]
#[skuld::test]
fn terminate_of_several_members_it_could_not_signal_keeps_every_cause_below_the_error() {
    use crate::containment::cgroup::fault::{fail_terminate, TerminateStep};
    use crate::error::Error;
    let _pin = fail_terminate(TerminateStep::Pin, libc::EMFILE);

    let result = crate::containment::cgroup::CgroupLeaf::placeholder_for_test()
        .terminate_listed("0\nnot-a-pid\n4000001\n4000002\n");

    let err = result.expect_err("no member got a SIGTERM");
    let Error::Unassessable {
        detail,
        source: Some(source),
    } = &err
    else {
        panic!("{err:?}");
    };
    assert!(detail.contains("4 could not be shown to be members"), "{detail}");
    assert!(
        !detail.contains("pid 4000001") && !detail.contains("os error"),
        "{detail}"
    );
    let Error::Several(members) = &**source else {
        panic!("expected Several, got {source:?}");
    };
    let said: Vec<_> = members.iter().map(|m| m.to_string()).collect();
    assert!(said[0].contains("pid 0"), "{said:?}");
    assert!(said[1].contains("not-a-pid"), "{said:?}");
    assert!(
        said[2].contains("pid 4000001") && said[3].contains("pid 4000002"),
        "{said:?}"
    );
    let codes: Vec<_> = members.iter().map(|m| crate::error::first_os_code(&**m)).collect();
    assert_eq!(codes, [None, None, Some(libc::EMFILE), Some(libc::EMFILE)]);
}

/// A member shown to be in the leaf whose exit then cannot be read got no `SIGTERM`, and the error
/// says its exit could not be read, not that it could not be placed. Mutant: "a failed exit read is
/// folded into the placement failure".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_whose_exit_could_not_be_read(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;

    use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
    crate::log_capture::install();
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf_name_of(&leaf);
    take_member_terms();
    let mark = crate::log_capture::mark();
    let guard = fail_terminate(TerminateStep::Exited, libc::EIO);
    let result = leaf.terminate().expect("cgroup.procs is readable");
    drop(guard);
    let noted = take_member_terms();
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    drop(stdin);
    let status = member.wait().expect("reap the member");
    drop(leaf);
    assert_eq!(status.signal(), None, "the member got no SIGTERM: {status:?}");
    assert_eq!(noted, []);
    let err = result.expect_err("a member got no SIGTERM");
    let crate::error::Error::Unassessable { .. } = &err else {
        panic!("expected Unassessable, got {err:?}");
    };
    let reported = crate::error::said(&err);
    assert!(
        reported.contains(&format!("pid {pid}: its exit could not be read")),
        "{reported}"
    );
    assert!(!reported.contains("could not be placed"), "{reported}");
    // The failed read is the source, with its code.
    assert_eq!(crate::error::first_os_code(&err), Some(libc::EIO), "{err:?}");
    assert_eq!(warns.len(), 1, "{warns:?}");
}

/// A member whose place and whose exit both cannot be read got no `SIGTERM`, and the error says
/// both. Mutant: "an unreadable exit after an unreadable place is reported as the place alone".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_whose_place_and_exit_cannot_be_read(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;

    use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
    let (leaf, mut member, stdin) = entered_real_leaf();
    take_member_terms();
    let guard = (
        // Neither route can place the member, and its exit cannot be read either.
        crate::containment::cgroup::fault::miss_pidfd_info(),
        crate::containment::cgroup::fault::hide_proc(),
        fail_terminate(TerminateStep::Exited, libc::EIO),
    );
    let result = leaf.terminate().expect("cgroup.procs is readable");
    drop(guard);
    let noted = take_member_terms();
    drop(stdin);
    let status = member.wait().expect("reap the member");
    drop(leaf);
    assert_eq!(status.signal(), None, "the member got no SIGTERM: {status:?}");
    assert_eq!(noted, []);
    let err = result.expect_err("a member got no SIGTERM");
    let crate::error::Error::Unassessable { .. } = &err else {
        panic!("expected Unassessable, got {err:?}");
    };
    let rendered = crate::error::said(&err);
    assert!(rendered.contains("could not be placed"), "{rendered}");
    assert!(
        rendered.contains("its placement and its exit could not be read"),
        "{rendered}"
    );
    assert!(
        rendered.contains("its exit could not be read") && rendered.contains("(os error 5)"),
        "the failed exit read is in the report too: {rendered}"
    );
    // The code the walk finds is the placement's (`hide_proc` answers `ENOENT`), not the exit read's.
    assert_eq!(crate::error::first_os_code(&err), Some(libc::ENOENT), "{err:?}");
}

/// A placement that fails while the exit cannot be read either fails with the placement's own
/// `io::Error` as the error's source, so its OS code is reachable by walking `source()`; the exit
/// read's failure is in the detail, and the error's own text does not repeat the placement's.
/// Unprivileged: the placement is refused by a fault, with an errno other than the exit read's.
///
/// Mutants: the two failures are folded into one new `io::Error` with no OS code; the detail repeats
/// the placement's error.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_placement_whose_exit_read_fails_too_keeps_its_os_code_as_the_source() {
    use crate::containment::cgroup::fault::{fail_pidfd_info, fail_terminate, TerminateStep};
    use crate::containment::cgroup::test_support::kill_record;

    let subtree = crate::containment::cgroup::Subtree::new(
        Some(7),
        None,
        None,
        crate::containment::cgroup::Swept::default(),
        crate::containment::cgroup::PlacedAtRemoval::default(),
        kill_record(true),
    );
    let pidfd = rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty())
        .expect("pidfd_open");
    let _placement = fail_pidfd_info();
    let _exit = fail_terminate(TerminateStep::Exited, libc::EBADF);

    let result = super::placed_or_exited(pidfd.as_fd(), subtree.holds(std::process::id(), Some(pidfd.as_fd())));

    let err = match result {
        Err(err) => err,
        Ok(_) => panic!("neither the place nor the exit could be read"),
    };
    assert_eq!(crate::error::first_os_code(&err), Some(libc::EIO), "{err:?}");
    let own = err.to_string();
    assert!(own.contains("its placement and its exit could not be read"), "{own}");
    assert!(!own.contains("process containment failed"), "{own}");
    assert!(
        !own.contains("(os error"),
        "both errors are below the error, not in its own text: {own}"
    );
    // Both failures are kept whole, the placement's first.
    let crate::error::Error::Unassessable {
        source: Some(source), ..
    } = &err
    else {
        panic!("{err:?}");
    };
    let crate::error::Error::Several(both) = &**source else {
        panic!("expected Several, got {source:?}");
    };
    let codes: Vec<_> = both.iter().map(|e| crate::error::first_os_code(&**e)).collect();
    assert_eq!(codes, [Some(libc::EIO), Some(libc::EBADF)]);
}

/// A member whose placement fails while it is alive got no `SIGTERM`, and the message names the OS's
/// error once.
///
/// Mutant: the message renders the error through the report, which prints an `io::Error`'s text twice.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_whose_placement_fails_is_named_with_the_os_text_once() {
    use crate::containment::cgroup::fault::fail_pidfd_info;
    use crate::containment::cgroup::test_support::kill_record;

    let subtree = crate::containment::cgroup::Subtree::new(
        Some(7),
        None,
        None,
        crate::containment::cgroup::Swept::default(),
        crate::containment::cgroup::PlacedAtRemoval::default(),
        kill_record(true),
    );
    let _placement = fail_pidfd_info();
    // A live child of this test, blocked on its stdin: the member the row names, reaped below.
    let mut child =
        crate::test_spawn::spawn(std::process::Command::new("/bin/cat").stdin(std::process::Stdio::piped()))
            .expect("spawn a member");

    let result = crate::containment::cgroup::CgroupLeaf::placeholder_for_test().terminate_member(child.id(), &subtree);

    drop(child.stdin.take());
    let status = child.wait().expect("reap the member");
    assert!(status.success(), "the member was signalled: {status:?}");
    let Err(super::Unsignalled::Unproven(unsent)) = result else {
        panic!("a placement that failed on a live member is unproven");
    };
    // The error is the cause, named once, and not in the member's own words.
    let crate::error::Error::Unassessable {
        detail,
        source: Some(cause),
    } = &unsent
    else {
        panic!("a member that could not be placed is an Unassessable with its cause: {unsent:?}");
    };
    assert_eq!(detail.matches("(os error 5)").count(), 0, "{detail}");
    assert!(detail.contains(&format!("pid {}", child.id())), "{detail}");
    let message = crate::error::said(&**cause);
    assert_eq!(message.matches("(os error 5)").count(), 1, "{message}");
}

/// A listed member that has exited and is not yet reaped is not signalled, and is no failure: it
/// still has the leaf's place, so only its pidfd says it is gone. Nothing warns. Mutant: "a pinned
/// member shown to be in the leaf is signalled without asking whether it exited".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_does_not_signal_a_member_that_exited_unreaped(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::fault::take_member_terms;
    crate::log_capture::install();
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf_name_of(&leaf);
    // SAFETY: `pid` is this test's own unreaped child.
    assert_eq!(
        unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) },
        0,
        "kill the member"
    );
    crate::test_child::wait_until_zombie(pid);
    take_member_terms();
    let mark = crate::log_capture::mark();
    let result = leaf.terminate_listed(&format!("{pid}\n"));
    let noted = take_member_terms();
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    drop(stdin);
    member.wait().expect("reap the member");
    drop(leaf);
    result.expect("a member that exited is not a failure");
    assert_eq!(noted, [], "a member that exited was signalled");
    assert_eq!(warns, Vec::<String>::new());
}

/// A listed pid that is gone before its pin (`pidfd_open` answers `ESRCH`) is not signalled and is
/// no failure. Mutant: "`ESRCH` from the pin is an unpinned member".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_counts_a_member_gone_before_its_pin_as_gone(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::fault::take_member_terms;
    crate::log_capture::install();
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf_name_of(&leaf);
    drop(stdin);
    member.wait().expect("reap the member");
    take_member_terms();
    let mark = crate::log_capture::mark();
    let result = leaf.terminate_listed(&format!("{pid}\n"));
    let noted = take_member_terms();
    let gone = crate::log_capture::records_since_on_current_thread(mark, &format!("pid {pid} is gone"));
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    drop(leaf);
    result.expect("a member gone before its pin is not a failure");
    assert_eq!(noted, []);
    assert_eq!(gone.len(), 1, "the pin answered ESRCH: {gone:?}");
    assert_eq!(warns, Vec::<String>::new());
}

/// A member that exits after the pin and before its `SIGTERM` (`pidfd_send_signal` answers
/// `ESRCH`) is gone, no failure, and nothing is noted as sent. Mutant: "`ESRCH` from the send is a
/// failed send".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_counts_a_member_gone_at_its_send_as_gone(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;

    use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
    crate::log_capture::install();
    let (leaf, mut member, stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf_name_of(&leaf);
    take_member_terms();
    let mark = crate::log_capture::mark();
    let guard = fail_terminate(TerminateStep::Send, libc::ESRCH);
    let result = leaf.terminate().expect("cgroup.procs is readable");
    drop(guard);
    let noted = take_member_terms();
    let exited =
        crate::log_capture::records_since_on_current_thread(mark, &format!("pid {pid} exited before its SIGTERM"));
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    drop(stdin);
    let status = member.wait().expect("reap the member");
    drop(leaf);
    assert_eq!(status.signal(), None, "the seam refused the send: {status:?}");
    result.expect("a member gone at its send is not a failure");
    assert_eq!(noted, []);
    assert_eq!(exited.len(), 1, "{exited:?}");
    assert_eq!(warns, Vec::<String>::new());
}

/// A member that exits and is reaped between its pin and its placement is gone when the placement
/// is read through `/proc` (`ENOENT`), whatever the kernel: with `PIDFD_GET_INFO` missing, as
/// before 6.13, the place is read there. Mutant: "an `ENOENT` from `/proc` after the pin is an
/// unplaced member".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_counts_a_member_reaped_after_its_pin_as_gone_through_proc(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let (leaf, member, _stdin) = entered_real_leaf();
    let pid = member.id();
    let leaf_name = leaf_name_of(&leaf);
    let _armed = crate::containment::cgroup::fault::set_after_terminate_pin(move || {
        // SAFETY: `pid` is this test's own unreaped child.
        assert_eq!(
            unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) },
            0,
            "kill the member"
        );
        crate::test_child::reaped_elsewhere::reap_behind(pid);
    });
    crate::containment::cgroup::fault::take_member_terms();
    let _no_info = crate::containment::cgroup::fault::miss_pidfd_info();
    let mark = crate::log_capture::mark();
    let result = leaf.terminate().expect("cgroup.procs is readable");
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    let gone =
        crate::log_capture::records_since_on_current_thread(mark, &format!("pid {pid} exited before it was placed"));
    drop(_no_info);
    assert_eq!(crate::containment::cgroup::fault::take_member_terms(), []);
    result.expect("a member reaped after its pin is gone");
    assert_eq!(warns, Vec::<String>::new());
    assert_eq!(
        gone.len(),
        1,
        "the place was read through /proc and found gone: {gone:?}"
    );
    drop(leaf);
}

/// A member that cannot be pinned does not stop the members listed after it: each is still
/// signalled, and the call reports only the one. Mutant: "the first member that got no `SIGTERM`
/// ends the call".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_tries_every_member_after_one_fails(#[fixture(cgroup)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;

    use crate::containment::cgroup::fault::{fail_terminate_once, take_member_terms, TerminateStep};
    let (leaf, mut members) = real_leaf_with_members(2);
    let pids: Vec<u32> = members.iter().map(|(m, _)| m.id()).collect();
    take_member_terms();
    let guard = fail_terminate_once(TerminateStep::Pin, libc::EMFILE);
    let result = leaf.terminate_listed(&format!("{}\n{}\n", pids[0], pids[1]));
    drop(guard);
    let noted = take_member_terms();
    let statuses: Vec<_> = members
        .drain(..)
        .map(|(mut member, stdin)| {
            drop(stdin);
            member.wait().expect("reap the member")
        })
        .collect();
    drop(leaf);
    assert_eq!(statuses[0].signal(), None, "the unpinned member got no SIGTERM");
    assert_eq!(
        statuses[1].signal(),
        Some(libc::SIGTERM),
        "the member after the failed one is signalled: {:?}",
        statuses[1]
    );
    assert_eq!(noted, [(Some(pids[1]), crate::send_log::Via::Pidfd, libc::SIGTERM)]);
    let said = match result {
        Err(error @ crate::error::Error::Unassessable { .. }) => crate::error::said(&error),
        other => panic!("expected Unassessable, got {other:?}"),
    };
    assert!(said.contains(&format!("pid {}:", pids[0])), "{said}");
    assert!(!said.contains(&format!("pid {}:", pids[1])), "{said}");
}

/// Several members that got no `SIGTERM`, of both kinds, make one error and one `warn`, naming each
/// pid; a failed send is what makes it `Containment`. Each member is an error of its own below the
/// call, with its OS cause, the failed sends first, and none of them is in the call's detail.
/// Mutants: "a mix of failed and unproven members is `Unassessable`", "one `warn` per member",
/// "only the first member of a kind is named", "a member's cause is dropped".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_every_member_that_got_no_sigterm_in_one_error_and_warn(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
    crate::log_capture::install();
    let (leaf, mut members) = real_leaf_with_members(2);
    let pids: Vec<u32> = members.iter().map(|(m, _)| m.id()).collect();
    let leaf_name = leaf_name_of(&leaf);
    take_member_terms();
    let mark = crate::log_capture::mark();
    let guard = fail_terminate(TerminateStep::Send, libc::EIO);
    // Pid 0 is unproven, and both real members' sends fail.
    let result = leaf.terminate_listed(&format!("0\n{}\n{}\n", pids[0], pids[1]));
    drop(guard);
    let noted = take_member_terms();
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    for (mut member, stdin) in members.drain(..) {
        drop(stdin);
        member.wait().expect("reap the member");
    }
    drop(leaf);
    assert_eq!(noted, []);
    let (detail, source) = match result {
        Err(crate::error::Error::Containment { detail, source }) => (detail, source),
        other => panic!("a failed send makes the call Containment, got {other:?}"),
    };
    // Three members: the two failed sends first, then the unproven pid 0, each below the call.
    assert!(
        !detail.contains("pid 0:") && !detail.contains("os error"),
        "no member's words are in the detail: {detail}"
    );
    assert!(detail.contains("failed for 2"), "{detail}");
    let Some(source) = source else {
        panic!("the members are the call's source");
    };
    let crate::error::Error::Several(members) = &*source else {
        panic!("expected Several, got {source:?}");
    };
    let said: Vec<_> = members.iter().map(|m| m.to_string()).collect();
    assert_eq!(said.len(), 3, "{said:?}");
    for (member, pid) in said
        .iter()
        .zip([pids[0].to_string(), pids[1].to_string(), "0".to_owned()])
    {
        assert!(member.contains(&format!("pid {pid}:")), "{pid}: {said:?}");
    }
    let codes: Vec<_> = members.iter().map(|m| crate::error::first_os_code(&**m)).collect();
    assert_eq!(codes, [Some(libc::EIO), Some(libc::EIO), None]);
    assert_eq!(warns.len(), 1, "{warns:?}");
    for needle in [format!("pid {}:", pids[0]), format!("pid {}:", pids[1])] {
        assert!(warns[0].contains(&needle), "{needle} is not named: {warns:?}");
    }
}

/// A `cgroup.procs` line that is no pid is a member the call could not show or signal, not a line
/// to drop: `Unassessable`, with one `warn`, naming the line. Mutant: "a line that does not parse
/// is skipped".
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_listed_line_that_is_no_pid(#[fixture(cgroup)] _group: &Group) {
    crate::log_capture::install();
    let leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
    let leaf_name = leaf_name_of(&leaf);
    let mark = crate::log_capture::mark();
    let result = leaf.terminate_listed("abc\n");
    let warns = crate::log_capture::warns_since(mark, &leaf_name);
    drop(leaf);
    let said = match result {
        Err(error @ crate::error::Error::Unassessable { .. }) => crate::error::said(&error),
        other => panic!("expected Unassessable, got {other:?}"),
    };
    assert!(said.contains("\"abc\""), "{said}");
    assert_eq!(warns.len(), 1, "{warns:?}");
}