cosca 0.6.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
#[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, reap,
};
use crate::containment::cgroup::{DrainStep, LeafError, NotEntered, NotPlaced, PlacementReport};
#[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(Some(at)), Some(at)), (Some(None), None), (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(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(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(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(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(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().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(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 nextest bound on this test, 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"
    );
}

/// 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().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) {
        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:?}");
    let reason = std::io::Error::from_raw_os_error(libc::ENOENT).to_string();
    assert!(rendered.contains(&reason), "errno missing from {rendered:?}");
}

/// 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()) {
        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()) {
        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) {
        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:?}"
    );
    let reason = std::io::Error::from_raw_os_error(libc::EACCES).to_string();
    assert!(err.to_string().contains(&reason), "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
/// `Attached::hard_kill` 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");
    // Unwrapped: a message wrapper would erase `raw_os_error()` from the public `kill_tree()`
    // error, and several errnos share one `ErrorKind`.
    let crate::error::Error::Io(io) = &err else {
        panic!("a refused cgroup.kill write must surface as Error::Io, got {err:?}");
    };
    assert_eq!(
        io.raw_os_error(),
        Some(libc::EISDIR),
        "the kernel's errno must reach the caller, got {err}"
    );

    let attached = crate::containment::Attached::Cgroup(leaf);
    assert!(
        attached.hard_kill().is_err(),
        "Attached::Cgroup must propagate like every sibling arm; 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 has no member left to signal");

    let attached = crate::containment::Attached::Cgroup(leaf);
    assert!(
        attached.terminate(0).is_ok(),
        "terminate and hard_kill must agree about an already-gone leaf"
    );
    assert!(attached.hard_kill().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 attached = crate::containment::Attached::Cgroup(entered_leaf_at(leaf_path.clone()));
    let mark = crate::log_capture::mark();
    attached.disarm();
    drop(attached);

    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 attached = crate::containment::Attached::Cgroup(entered_leaf_at(leaf_path.clone()));
    attached.disarm();
    drop(attached);

    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();
    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 it is a live opted-out tree keeping its leaf, reported at `debug`, not a leak.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_tree_survived_terminate_is_not_reported_as_a_leak() {
    use std::os::fd::AsRawFd;

    crate::log_capture::install();
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-terminate-survivor-leaf");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let (ready_read, ready_write) = std::io::pipe().expect("pipe");
    let ready_write_fd = ready_write.as_raw_fd();
    let guard = fork_running(move || {
        // SAFETY (in the child): `signal`, `write`, `_exit` and `pause` are async-signal-safe.
        unsafe {
            libc::signal(libc::SIGTERM, libc::SIG_IGN);
            if libc::write(ready_write_fd, b"r".as_ptr().cast(), 1) != 1 {
                // The parent's `block_on` below would otherwise hang forever on a write that
                // never lands: exit so it sees EOF instead.
                libc::_exit(1);
            }
            libc::pause();
        }
    });
    drop(ready_write);
    block_on(ready_read.as_raw_fd()); // the member ignores SIGTERM from here on
    drop(ready_read);
    std::fs::write(leaf_path.join("cgroup.procs"), format!("{}\n", guard.pid())).expect("list the member");
    // `populated 1`: the member is still alive, and Drop's never-killed branch reads this file
    // 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 leaf = entered_leaf_at(leaf_path);
    leaf.disarm();
    leaf.terminate().expect("signal the tree");
    let mark = crate::log_capture::mark();
    drop(leaf);
    drop(guard); // SIGKILLs and reaps the member through its pidfd

    let records = crate::log_capture::records_since(mark, "cosca-terminate-survivor-leaf");
    assert_eq!(
        crate::log_capture::levels_since(mark, "cosca-terminate-survivor-leaf"),
        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:?}"
    );
    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");

    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:?}"
    );
    // The first kill happened before `record_leaf_steps()`, so it leaves no step here — but
    // `Drop` re-fires `cgroup.kill` before waiting (see the next test), which does show up.
    assert_eq!(
        steps,
        vec!["rmdir populated 1", "kill", "rmdir populated 0"],
        "a disarmed leaf's kill must be re-fired and then retried only once it drains, got {steps:?}"
    );
}

/// #194 follow-up: a disarmed `Drop` re-fires `cgroup.kill` right before waiting on the drain, so
/// an occupant that migrated into the leaf after the caller's own kill — or one that escaped it by
/// forking while the kill was in flight, on a kernel before 6.14 (`cgroup: fix race between fork
/// and cgroup.kill`) — cannot make `Drop` wait on a drain nothing is driving. A stale `killed` flag
/// must not by itself excuse `Drop` from killing again.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_drop_re_fires_the_kill_before_waiting_on_a_repopulated_leaf() {
    use crate::containment::cgroup::fault;
    use crate::containment::cgroup::test_support::FakeLeaf;

    let fake = FakeLeaf::new("cosca-disarmed-repopulated-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");
    // The first kill's tree fully drains, then an occupant migrates in (or a fork escapes a kill
    // in flight, pre-6.14): the leaf reads populated again, though `killed` is still set from the
    // first, successful write.
    FakeLeaf::set_populated(&fake.events, false);
    FakeLeaf::set_populated(&fake.events, true);

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

    assert!(
        !fake.leaf.exists(),
        "Drop must still remove the leaf once its re-fired kill drains, got {steps:?}"
    );
    let killed_at = steps
        .iter()
        .position(|s| s == "kill")
        .unwrap_or_else(|| panic!("a re-populated leaf must be killed again before Drop waits, got {steps:?}"));
    let after_kill = &steps[killed_at + 1..];
    assert!(
        !after_kill.is_empty(),
        "the drop must retry the rmdir after re-firing the kill, got {steps:?}"
    );
    assert!(
        after_kill.iter().all(|s| s.starts_with("rmdir populated 0")),
        "every rmdir after the re-fired kill must wait for the drain, got {steps:?}"
    );
}

/// #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();
    leaf.hard_kill()
        .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 real kill through the leaf (under test in every
/// caller) 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 `cat`
/// without any kill, so every caller either releases it from a seam that fires after the kill
/// ([`drop_under_a_mount`]) or asserts the exit status carries `SIGKILL`.
#[cfg(target_os = "linux")]
fn entered_real_leaf() -> (
    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().expect("create a real leaf");
    let (procs_fd, slot) = (leaf.procs_fd(), leaf.placement_slot());
    let mut cmd = crate::test_child::held_std_blocker(std::process::Stdio::null());
    // 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();
    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::tokio::wait::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::tokio::wait::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::tokio::wait::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::tokio::wait::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(Some(std::time::Instant::now()))).expect("wait"),
        TreeDrain::MembersRemain
    );
    FakeLeaf::set_populated(&fake.events, false);
    assert_eq!(
        leaf.wait_drained(Some(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(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(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::tokio::wait::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");
        assert!(e.to_string().contains("can no longer be watched"), "{e}");
    }
    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.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()) {
        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()) {
        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:?}"
    );
    let reason = std::io::Error::from_raw_os_error(libc::EMFILE).to_string();
    assert!(err.to_string().contains(&reason), "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_TEST_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(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().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");
}

/// An abandoned spawn's child is killed and reaped through the pidfd its intent carried, whatever
/// `cgroup.kill` returns — it may have left the leaf. Here `cgroup.kill` is a directory, so the
/// leaf's kill fails for real.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_is_killed_and_reaped_by_its_pidfd_when_the_leaf_kill_fails() {
    use std::os::unix::process::CommandExt;

    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-kill-fails");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("make cgroup.kill unwritable");
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    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 = leaf.placement_slot();
    // Blocked on a piped stdin, released by `end_child`'s kill-then-reap seam strictly after its
    // kill returned `Ok`: a real SIGKILL beats the release, so the recorded signal below is
    // SIGKILL; a no-kill mutant lets `cat` exit on the EOF, which fails that assertion at once.
    let mut cmd = std::process::Command::new("/bin/cat");
    cmd.stdin(std::process::Stdio::piped()).process_group(0);
    // SAFETY: the closure runs between fork and exec; /dev/null stands in for cgroup.procs.
    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");
    let stdin = child.stdin.take().expect("piped stdin");
    let pid = child.id();
    let pidfd = pidfd_of(pid);
    // SAFETY: the parent's own copy, closed once.
    unsafe { libc::close(procs_fd) };
    // No handle owns the child once its spawn is abandoned: the leaf reaps it.
    drop(child);

    let _armed = crate::containment::cgroup::fault::set_before_exit_wait(move || drop(stdin));
    drop(leaf);
    crate::containment::cgroup::fault::run_before_exit_wait();

    assert!(
        crate::containment::cgroup::fault::take_reaped_orphans().contains(&(pid, Some(libc::SIGKILL))),
        "the child must be killed by its pidfd"
    );
    assert!(reaped(&pidfd), "and reaped");
}

/// Whether the child `pidfd` names has been reaped — a question a pidfd, unlike a pid, can answer
/// after the reap, since it cannot come to name another process.
#[cfg(target_os = "linux")]
fn reaped(pidfd: &std::os::fd::OwnedFd) -> bool {
    use std::os::fd::AsFd;

    use rustix::process::{waitid, WaitId, WaitIdOptions};

    matches!(
        waitid(
            WaitId::PidFd(pidfd.as_fd()),
            WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
        ),
        Err(rustix::io::Errno::CHILD)
    )
}

/// Spawn `argv` as a child that leads its own group and places itself through `leaf`'s channel,
/// reporting `Placed` (`/dev/null` stands in for `cgroup.procs`) or, with `fail`, the write's
/// `EBADF`. `before` runs in the forked child first. Returns the child, never waited on here.
#[cfg(target_os = "linux")]
fn spawn_placing(
    leaf: &crate::containment::cgroup::CgroupLeaf,
    argv: &[&str],
    fail: bool,
    stdin: std::process::Stdio,
    stdout: std::process::Stdio,
) -> std::process::Child {
    use std::os::unix::process::CommandExt;

    let procs_fd = if fail {
        -1
    } else {
        let sink = std::fs::OpenOptions::new()
            .write(true)
            .open("/dev/null")
            .expect("open /dev/null");
        std::os::fd::IntoRawFd::into_raw_fd(sink)
    };
    let slot = leaf.placement_slot();
    let mut cmd = std::process::Command::new(argv[0]);
    cmd.args(&argv[1..]).stdin(stdin).stdout(stdout).process_group(0);
    // SAFETY: the closure runs between fork and exec, and makes only async-signal-safe calls on
    // descriptors this test and `leaf` keep open across the spawn.
    unsafe { cmd.pre_exec(move || crate::containment::cgroup::placement_hook(procs_fd, slot)) };
    let child = crate::test_spawn::spawn(&mut cmd).expect("spawn");
    if procs_fd >= 0 {
        // SAFETY: the parent's own copy, closed once.
        unsafe { libc::close(procs_fd) };
    }
    child
}

/// An abandoned child whose intent carried no pidfd — `pidfd_open` denied in the child — is still
/// killed and reaped, named by the `/proc/self` directory it sent: a handle on that process, not on
/// its number.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_without_a_pidfd_is_killed_and_reaped_through_its_proc_directory() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-no-pidfd");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    // Inherited by the child forked from this thread, which takes it.
    crate::containment::cgroup::fault::set_force_child_pidfd_failure(true);
    let mut child = spawn_placing(
        &leaf,
        crate::test_child::BLOCKER_ARGV,
        false,
        std::process::Stdio::piped(),
        std::process::Stdio::null(),
    );
    crate::containment::cgroup::fault::set_force_child_pidfd_failure(false);
    // Released once the kill has landed, right before the exit wait: a real kill makes this a
    // no-op, a skipped one lets the child exit 0 on EOF and fails the `SIGKILL` check below.
    let stdin = child.stdin.take().expect("piped stdin");
    let _release = crate::containment::cgroup::fault::set_before_exit_wait(move || drop(stdin));
    let pid = child.id();
    let pidfd = pidfd_of(pid);
    drop(child);

    drop(leaf);
    crate::containment::cgroup::fault::run_before_exit_wait();

    assert!(
        crate::containment::cgroup::fault::take_reaped_orphans().contains(&(pid, Some(libc::SIGKILL))),
        "the child must be killed through its /proc directory"
    );
    assert!(reaped(&pidfd), "and reaped");
}

/// An intent that carries no handle on its sender — neither a pidfd nor a `/proc` directory — names
/// its child by a number alone, which `std` may have freed by reaping it. It is never signalled, even
/// when the number names a live child of this process: that child is not this spawn's. Out of
/// reach, and said so.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_intent_without_a_handle_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 and carries no handle.
    unsafe {
        leaf.placement_slot()
            .send(crate::containment::cgroup::TAG_INTENT, other.id() as i32, 0, -1)
            .expect("send a forged intent");
    }

    assert_eq!(
        leaf.abandon_before_verdict(false, None),
        crate::containment::cgroup::Abandoned::OutOfReach
    );
    assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);

    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 real spawn whose child could open neither a pidfd nor its `/proc` directory sends an intent
/// with no handle: its abandoned child is out of reach, and is not signalled.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_with_no_handle_on_itself_is_out_of_reach() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-no-handle-spawn");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    // Inherited by the child forked from this thread, which takes them.
    crate::containment::cgroup::fault::set_force_child_pidfd_failure(true);
    crate::containment::cgroup::fault::set_force_child_proc_dir_failure(true);
    // `try_wait().is_none()` alone would race a late SIGKILL, so liveness is an echo round trip.
    let mut child = spawn_placing(
        &leaf,
        &["cat"],
        true,
        std::process::Stdio::piped(),
        std::process::Stdio::piped(),
    );
    crate::containment::cgroup::fault::set_force_child_pidfd_failure(false);
    crate::containment::cgroup::fault::set_force_child_proc_dir_failure(false);

    assert_eq!(
        leaf.abandon_before_verdict(false, None),
        crate::containment::cgroup::Abandoned::OutOfReach
    );
    assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
    crate::test_child::assert_echoes(
        child.stdin.as_mut().expect("stdin"),
        child.stdout.as_mut().expect("stdout"),
    );
    child.kill().expect("kill the child");
    child.wait().expect("reap the child");
}

/// `std` reaps the child of a spawn it failed before returning the error, freeing its pid. The
/// abandoned exchange then holds that child's `/proc` directory, which no longer opens anything:
/// the child is gone, and nothing is signalled — whatever process the number names by now.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_std_already_reaped_is_never_signalled() {
    use std::io::Write;
    use std::os::fd::AsRawFd;

    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-reaped");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    let slot = leaf.placement_slot();
    let (gate_read, mut gate_write) = std::io::pipe().expect("open the gate");
    let gate = gate_read.as_raw_fd();
    crate::containment::cgroup::fault::set_force_child_pidfd_failure(true);
    let guard = fork_running(move || {
        // SAFETY: this child's inherited copy of the channel's child end.
        _ = unsafe { slot.send_intent() };
        block_on(gate);
    });
    crate::containment::cgroup::fault::set_force_child_pidfd_failure(false);
    gate_write.write_all(b"x").expect("release the child");
    // Reaped as `std` reaps it: before the exchange is abandoned.
    reap(guard.defuse());

    assert_eq!(
        leaf.abandon_before_verdict(false, None),
        crate::containment::cgroup::Abandoned::Ended
    );
    assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
    assert_eq!(crate::containment::cgroup::fault::take_reaped_orphans(), Vec::new());
}

/// 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_before_verdict(false, None),
        crate::containment::cgroup::Abandoned::MaybeUnreaped
    );
    assert!(!leaf_path.exists(), "the empty leaf is removed");
    assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
}

/// A child reaped between the check that it lives and the kill — only by a reaper the crate's
/// contract forbids — is signalled through its handle, which now names nothing: no other process
/// can be hit. The kill finds it gone, and nothing is reaped twice.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_child_reaped_between_the_check_and_the_kill_is_not_signalled_by_number() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-window");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    let child = spawn_placing(
        &leaf,
        &["/bin/true"],
        false,
        std::process::Stdio::inherit(),
        std::process::Stdio::null(),
    );
    let pid = child.id();
    drop(child);
    crate::containment::cgroup::fault::set_between_check_and_kill(move || reap(pid));

    assert_eq!(
        leaf.abandon_before_verdict(false, None),
        crate::containment::cgroup::Abandoned::Ended
    );
    assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
    assert_eq!(crate::containment::cgroup::fault::take_reaped_orphans(), Vec::new());
}

/// An abandoned child cosca may not kill is out of reach, and still never left a zombie: a
/// background reaper waits for its exit, however that comes — here, the test's own kill.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_that_refuses_the_kill_is_reaped_once_it_exits() {
    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-refuses");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    // Its placement write fails, so the leaf does not hold it either.
    // `!reaped(&pidfd)` alone would race a late SIGKILL, so liveness is an echo round trip.
    let mut child = spawn_placing(
        &leaf,
        &["cat"],
        true,
        std::process::Stdio::piped(),
        std::process::Stdio::piped(),
    );
    let pid = child.id();
    let pidfd = pidfd_of(pid);
    // Taken out of `child` so dropping it does not close the pipes.
    let mut stdin = child.stdin.take().expect("piped stdin");
    let mut stdout = child.stdout.take().expect("piped stdout");
    drop(child);
    let (reaped_tx, reaped_rx) = std::sync::mpsc::channel();
    crate::containment::cgroup::fault::set_force_child_kill_denied(true);
    crate::containment::cgroup::fault::set_background_reap_notifier(reaped_tx);

    assert_eq!(
        leaf.abandon_before_verdict(false, None),
        crate::containment::cgroup::Abandoned::OutOfReach
    );
    crate::test_child::assert_echoes(&mut stdin, &mut stdout);
    assert!(!reaped(&pidfd), "the child refused the kill and is still running");

    // Its pid is pinned while it is unreaped.
    rustix::process::pidfd_send_signal(&pidfd, rustix::process::Signal::KILL).expect("kill the child");
    reaped_rx.recv().expect("the background reaper must reap it");
    assert!(reaped(&pidfd), "the child must be reaped once it exits");
}

/// An abandoned child is killed as the process group it leads: what it forked after `exec` is in
/// that group, whether or not it is in the leaf. Here the leaf's own kill kills nothing (a
/// directory, not a cgroup), so only the group kill can end the descendant, which holds the
/// child's stdout: reading it to EOF proves both dead. The descendant is a `cat` blocked on a
/// stdin this test holds (see `test_child::BLOCKER_ARGV` for the idiom), so it dies only from a
/// real signal. The stdin is released by `fault::set_before_exit_wait`, which fires after
/// `end_child`'s own kill and before its blocking `waitid` on the shell: the shell is parked in
/// its own `wait`, so with that kill skipped `drop(leaf)` would never return. A real kill has
/// already landed by then, so the byte goes nowhere; a skipped one lets the live `cat` echo it,
/// so `rest` is non-empty and the test fails at once rather than hanging. `drop(leaf)` may also
/// return before the hook's fire point, so the test fires it itself afterwards.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_is_killed_with_the_group_it_leads() {
    use std::io::{BufRead, Read};

    let dir = tempfile::tempdir().expect("tempdir");
    let leaf_path = dir.path().join("cosca-abandoned-group");
    std::fs::create_dir(&leaf_path).expect("create the leaf");
    let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
    let mut child = spawn_placing(
        &leaf,
        &["/bin/sh", "-c", "exec 3<&0; cat <&3 3<&- & echo forked; wait"],
        false,
        std::process::Stdio::piped(),
        std::process::Stdio::piped(),
    );
    // Moved into the hook below; see this function's doc.
    let mut stdin = child.stdin.take().expect("piped stdin");
    let mut stdout = std::io::BufReader::new(child.stdout.take().expect("stdout"));
    let mut line = String::new();
    stdout.read_line(&mut line).expect("read the child's line");
    assert_eq!(
        line, "forked\n",
        "the descendant must exist before the spawn is abandoned"
    );
    drop(child);

    let _release = crate::containment::cgroup::fault::set_before_exit_wait(move || {
        crate::test_child::write_to_possibly_dead_stdin(&mut stdin, b"x");
        drop(stdin);
    });
    drop(leaf);
    crate::containment::cgroup::fault::run_before_exit_wait();

    let mut rest = Vec::new();
    stdout
        .read_to_end(&mut rest)
        .expect("read to EOF: every process holding stdout is dead");
    assert!(
        rest.is_empty(),
        "the descendant echoed a byte written after drop(leaf) — the group kill failed to reach \
         it in time, got {rest:?}"
    );
}

/// 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().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);
}

// Blocking waits refuse to run inside a bounded section -----
//
// These sit here, not in `bounded_tests`, because the waits are private to `leaf`. A wait that
// lost its `assert_may_block` returns at once on the inputs below, so each test fails on "did not
// panic" rather than hanging.

/// `end_child` waits for a child's exit, so it refuses a section before it looks at its input.
///
/// Mutant: drop the assert from `end_child`.
#[cfg(all(target_os = "linux", feature = "tokio"))]
#[skuld::test]
fn end_child_refuses_inside_a_section() {
    let received = crate::containment::cgroup::Received {
        report: None,
        pid: None,
        pidfd: None,
        proc_dir: None,
    };
    let _section = crate::bounded::Section::enter();
    let refused = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::end_child(&received)));
    assert!(refused.is_err(), "end_child must refuse inside a bounded section");
}

/// 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}");
}