cosca 0.5.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
//! The leaf itself: creating it, placing the child in it, deciding membership, killing
//! through it and removing it.

use std::fmt;
use std::io;
use std::path::PathBuf;

use super::*;

#[cfg(target_os = "linux")]
use std::fs::{self, File};
#[cfg(target_os = "linux")]
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
#[cfg(target_os = "linux")]
use std::path::Path;
#[cfg(target_os = "linux")]
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

/// Process-wide monotonic counter; combined with the pid, gives a unique leaf
/// name even when the same process spawns on multiple threads simultaneously.
#[cfg(target_os = "linux")]
static SEQ: AtomicU64 = AtomicU64::new(0);

#[cfg(target_os = "linux")]
use nix::sys::signal::{kill, Signal};
#[cfg(target_os = "linux")]
use nix::unistd::Pid;

/// Whether `e` is the kernel's proof that this leaf's `cgroup.events` node is already gone —
/// either because the whole path was already removed (`ENOENT`, on a fresh `open` through the
/// now-unlinked leaf directory) or because THIS fd was opened before removal and the
/// underlying kernfs node has since been deactivated (`ENODEV`, on `seek`/`read` through an
/// already-open fd). `rmdir` on a cgroup v2 leaf — whether `Drop`'s own retry or an external
/// cgroup manager's cleanup of an empty leaf — succeeds ONLY once `populated` has already read
/// 0 (see `CgroupLeaf::wait_drained`'s doc); observing the leaf's removal is therefore always
/// proof every member had already exited, never proof of anything else, so no other errno is
/// folded in here (a genuine mechanism failure — `EACCES`, `EIO`, ...— must still surface as
/// `Error::Io`, not be silently reinterpreted as a drain).
#[cfg(target_os = "linux")]
pub(crate) fn removed_after_drain(e: &io::Error) -> bool {
    matches!(e.raw_os_error(), Some(libc::ENODEV) | Some(libc::ENOENT))
}

/// Seek to the start of `file` (a `cgroup.events` handle) and read its current `populated`
/// value. The one read of a held `cgroup.events`, behind [`DrainWatch::populated`].
///
/// A leaf removed after every member has exited (see [`removed_after_drain`]) is reported as
/// `Ok(false)`: the leaf's own removal is itself proof of a full drain, indistinguishable in
/// meaning from an explicit `populated 0`.
#[cfg(target_os = "linux")]
pub(crate) fn read_populated(file: &mut File, buf: &mut String) -> Result<bool, crate::error::Error> {
    use std::io::{Read, Seek, SeekFrom};

    buf.clear();
    if let Err(e) = file.seek(SeekFrom::Start(0)) {
        return if removed_after_drain(&e) {
            Ok(false)
        } else {
            Err(crate::error::Error::Io(e))
        };
    }
    if let Err(e) = file.read_to_string(buf) {
        return if removed_after_drain(&e) {
            Ok(false)
        } else {
            Err(crate::error::Error::Io(e))
        };
    }
    parse_populated(buf).ok_or_else(|| {
        crate::error::Error::Io(io::Error::other(
            "cgroup.events has no 'populated' field — unexpected kernel format",
        ))
    })
}

/// Whether the process `pidfd` names has exited, reaped or not: the pidfd turns readable at exit
/// and stays so.
#[cfg(target_os = "linux")]
fn pidfd_exited(pidfd: std::os::fd::BorrowedFd<'_>) -> io::Result<bool> {
    use rustix::event::{poll, PollFd, PollFlags, Timespec};

    let mut fds = [PollFd::new(&pidfd, PollFlags::IN)];
    let now = Timespec { tv_sec: 0, tv_nsec: 0 };
    loop {
        match poll(&mut fds, Some(&now)) {
            Ok(_) if fds[0].revents().contains(PollFlags::NVAL) => {
                return Err(io::Error::from_raw_os_error(libc::EBADF));
            }
            Ok(_) => return Ok(fds[0].revents().contains(PollFlags::IN)),
            Err(rustix::io::Errno::INTR) => continue,
            Err(e) => return Err(e.into()),
        }
    }
}

/// The state letter of `child`, or `None` when it is unknown; the cause is logged at debug (see
/// [`StateUnknown`]). Only the pidfd says `Z`: the child exited, which separates "the placement
/// write failed" from "the child exited before membership was checked".
///
/// The pidfd is checked before and after the `/proc` read: a child unexited at the second check held
/// `pid` throughout, so the read is its own; otherwise the state is `Z`.
///
/// A `/proc` state of `Z` or `X` with the pidfd unexited is a thread-group leader that exited while
/// other threads run: the group has not exited, so that is no state of the child.
#[cfg(target_os = "linux")]
fn proc_state(child: crate::containment::ChildHandle<'_>) -> Option<char> {
    let crate::containment::ChildHandle { pid, pidfd } = child;
    let exited = |when: &str| match pidfd_exited(pidfd) {
        Ok(exited) => Some(exited),
        Err(e) => {
            log::debug!("cgroup leaf: whether pid {pid} had exited {when} its state was read is unknown: {e}");
            None
        }
    };
    if exited("before")? {
        return Some('Z');
    }
    #[cfg(test)]
    fault::run_before_state_read();
    let state = read_proc_state(pid);
    if exited("after")? {
        return Some('Z');
    }
    match state {
        Ok('Z' | 'X' | 'x') => {
            log::debug!("cgroup leaf: pid {pid}'s leader exited, group lives");
            None
        }
        Ok(state) => Some(state),
        Err(why) => {
            log::debug!("cgroup leaf: pid {pid}'s state is unknown: {why}");
            None
        }
    }
}

/// Why [`read_proc_state`] has no state letter.
#[cfg(target_os = "linux")]
#[derive(Debug)]
enum StateUnknown {
    /// `/proc` belongs to an outer pid namespace, so its `<pid>` could name another process.
    OuterProcfs,
    /// `/proc` could not be verified to be this process's own pid namespace's.
    ViewUnassessable(crate::identity::ViewUnreadable),
    /// `<pid>/stat` could not be read.
    Unreadable(std::io::Error),
    /// `<pid>/stat` has no state field.
    Unparsable(String),
}

#[cfg(target_os = "linux")]
impl std::fmt::Display for StateUnknown {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::OuterProcfs => f.write_str("/proc is an outer pid namespace's"),
            Self::ViewUnassessable(why) => write!(f, "the /proc view could not be established: {why}"),
            Self::Unreadable(e) => write!(f, "its stat could not be read: {e}"),
            Self::Unparsable(stat) => write!(f, "its stat has no state field: {stat:?}"),
        }
    }
}

#[cfg(target_os = "linux")]
fn read_proc_state(pid: u32) -> Result<char, StateUnknown> {
    use crate::identity::ProcView;
    let proc_dir = match crate::identity::proc_view() {
        ProcView::Same(proc_dir) => proc_dir,
        ProcView::Diverged => return Err(StateUnknown::OuterProcfs),
        ProcView::Unassessable(why) => return Err(StateUnknown::ViewUnassessable(why)),
    };
    let stat = proc_dir
        .read_to_string(&format!("{pid}/stat"))
        .map_err(StateUnknown::Unreadable)?;
    state_from_stat(stat)
}

#[cfg(target_os = "linux")]
fn state_from_stat(stat: String) -> Result<char, StateUnknown> {
    parse_proc_stat_state(&stat).ok_or(StateUnknown::Unparsable(stat))
}

/// What [`CgroupLeaf::drain_step`] found.
#[cfg(target_os = "linux")]
pub(crate) enum DrainStep {
    /// The wait's answer.
    Done(crate::containment::TreeDrain),
    /// Block on `listener` until `deadline` (`None`: unbounded), then step again. Carries the
    /// caller's instant, not a duration: a duration would go stale between computing it and
    /// starting the wait.
    Block {
        listener: event_listener::EventListener,
        deadline: Option<std::time::Instant>,
    },
}

/// A live leaf sub-cgroup created for a single spawned process tree. See
/// [`place_self_in_cgroup_pre_exec`] for the placement write's contract.
///
/// [`CgroupLeaf::take_placement`] releases the `cgroup.procs` fd and the report channel: the child
/// needs them only until its `exec`.
///
/// `Drop` removes the leaf directory, but only if the child reported entering it. If the leaf is
/// still occupied, it fires `cgroup.kill` itself — but only while still armed (not
/// [`disarm`](Self::disarm)ed) — then, either way a kill is now in flight (its own, or one the
/// caller already made through [`kill_tree`](Self::kill_tree)/[`hard_kill`](Self::hard_kill)),
/// waits for the leaf to drain, removes its child cgroups, and tries the `rmdir` once more.
#[cfg(target_os = "linux")]
pub(crate) struct CgroupLeaf {
    /// Absolute path to the leaf directory, e.g. `/sys/fs/cgroup/…/cosca-<pid>`, for reports.
    /// Nothing is done through it: see [`LeafDir`].
    pub(super) leaf_path: PathBuf,
    /// The leaf's directory and its parent, held from creation.
    dir: LeafDir,
    /// The leaf's drain watch, held from creation so that no wait on it ever lacks one. Read by
    /// the pump this watcher owns, which broadcasts each change to every wait.
    /// Boxed: its pump would make every `Attached` as large as a leaf.
    watch: Box<Watcher>,
    /// Pre-opened `cgroup.procs` fd for the `pre_exec` write. Close-on-exec: the write happens
    /// between `fork` and `exec`, and no program this process starts may inherit it. Numbered
    /// 3 or above, so it never shares a number with the child's stdio. `None` once the
    /// placement verdict is taken.
    procs_fd: Option<OwnedFd>,
    /// Where the forked child reports whether its self-placement write succeeded. `None` once
    /// the placement verdict is taken.
    pub(super) report: Option<ReportChannel>,
    /// Whether the child reported entering the leaf, recorded when `report` is released.
    pub(super) entered: bool,
    /// The leaf's unified-hierarchy path, as `/proc/<pid>/cgroup` prints it. `None` for a leaf
    /// created outside the cgroup filesystem.
    cgroup_path: Option<String>,
    /// Whether the leaf is already dealt with, so `Drop` has nothing left to do: the spawn was
    /// abandoned before its verdict, or an async `Drop` released it
    /// ([`release_without_waiting`](Self::release_without_waiting)).
    pub(super) abandoned: bool,
    /// Whether the caller still wants cosca to manage the tree. Cleared by `disarm`, for
    /// `detach()` and `kill_on_drop(false)`. `Drop` kills only while this and `entered` both hold.
    armed: AtomicBool,
    /// Whether [`hard_kill`](Self::hard_kill) wrote `cgroup.kill`. A disarmed `Drop` reads it to
    /// tell a tree the caller killed, whose leaf has not drained yet, from one left running.
    /// [`terminate`](Self::terminate) does not set it: a SIGTERM can be caught.
    killed: std::sync::Arc<AtomicBool>,
    /// The elevation front this leaf's child is, by pid, whose place is recorded in `placed` before
    /// each `rmdir` (see [`watch_front`](Self::watch_front)).
    watched: Option<u32>,
    /// Where the watched front was when the leaf was last about to be removed, shared with the
    /// leaf's [`Subtree`]s.
    placed: super::PlacedAtRemoval,
    /// Whether a [`hard_kill`](Self::hard_kill) call failed for a real mechanism reason (not
    /// "leaf already gone", which sets `killed` above instead). A disarmed `Drop` reads it to
    /// `warn` that the caller's own `kill_tree()` never actually reached this leaf, rather than
    /// silently folding a genuine failure into the same `debug` note used for a tree the caller
    /// never asked to kill at all.
    kill_attempt_failed: AtomicBool,
}

/// Why a spawn-side resource of a [`CgroupLeaf`] is missing.
#[cfg(target_os = "linux")]
const RELEASED: &str = "the leaf's spawn-side resources are released once its placement verdict is taken";

/// `listener.wait_deadline(at)` — the only call site for it, so the seam that records `at` (test
/// builds only) can never drift from what's actually passed: both come from the same parameter,
/// in the same function, with nothing between them to retarget one without the other. Closes
/// `event_listener::Listener::wait_deadline`'s own gap — it consumes the listener and exposes no
/// way to read back what it was armed with — from the caller's side instead.
#[cfg(target_os = "linux")]
fn wait_deadline_seamed(listener: event_listener::EventListener, at: std::time::Instant) -> bool {
    use event_listener::Listener as _;

    #[cfg(test)]
    fault::notify_wait_deadline_arg(at);
    listener.wait_deadline(at).is_some()
}

/// What `hard_kill` writes to `cgroup.kill`.
#[cfg(target_os = "linux")]
pub(crate) const KILL_PAYLOAD: &[u8] = b"1";

#[cfg(target_os = "linux")]
impl CgroupLeaf {
    /// Whether the placement verdict is still to be taken: the exchange has not ended.
    pub(crate) fn holds_verdict_to_take(&self) -> bool {
        self.report.is_some()
    }

    /// Returns the raw `cgroup.procs` fd for capture in a `pre_exec` closure. Only before the
    /// placement verdict is taken.
    pub(crate) fn procs_fd(&self) -> RawFd {
        self.procs_fd.as_ref().expect(RELEASED).as_raw_fd()
    }

    /// Whether the child reported entering this leaf, once the verdict is taken.
    fn child_entered(&self) -> bool {
        debug_assert!(self.report.is_none(), "the verdict is not taken yet");
        self.entered
    }

    /// Neutralize `Drop`'s kill, for `detach()`.
    ///
    /// Dropping a `CgroupLeaf` is NOT inert, which is what makes this necessary: `Drop` fires
    /// `cgroup.kill` whenever the first `rmdir` fails, and over a live detached tree that
    /// `rmdir` always fails (`EBUSY`). `Child::drop` opting out via `kill_on_drop` does not
    /// help — the leaf is a field of that `Child` and its own `Drop` runs regardless.
    ///
    /// A disarmed `Drop` never fires `cgroup.kill` itself, and gives up the leaf without
    /// retrying when the tree was never killed (noted at `debug`, never `warn`) — whether or not
    /// it is still live. But it does not give up on a kill the caller already made through
    /// `kill_tree()`/`hard_kill()`: that kill's drain is waited for exactly as an armed `Drop`'s
    /// is, so the `rmdir` retries once the leaf drains, and only reports the leaf as left behind
    /// if it still fails after that.
    pub(crate) fn disarm(&self) {
        self.armed.store(false, Ordering::Relaxed);
    }

    /// The leaf's directory: names the leaf in a caller's own message, since `hard_kill` returns
    /// the kernel's error unwrapped (a message wrapper would erase `raw_os_error()`), and finds
    /// this leaf and no other in tests.
    pub(crate) fn path(&self) -> &Path {
        &self.leaf_path
    }

    /// Remove a leaf that holds nothing of its child's: close the fd and `rmdir`, never
    /// `cgroup.kill`.
    ///
    /// The child's final report is not `Placed`, so it never exec'd a program that could fork
    /// into the leaf (see the module's report contract).
    /// Whatever keeps the `rmdir` from succeeding, cosca did not put there, and killing it would
    /// kill a process cosca was never asked to contain.
    pub(crate) fn remove_unentered(self) {
        debug_assert!(!self.child_entered(), "remove_unentered on a leaf its child entered");
    }

    /// A `Copy` handle to this leaf's placement-report slot, for capture by the `pre_exec`
    /// closure. Only before the placement verdict is taken.
    pub(crate) fn placement_slot(&self) -> ReportSlot {
        self.report.as_ref().expect(RELEASED).slot()
    }

    /// Whether `child` entered this leaf: `Ok` when its own write into it succeeded.
    ///
    /// Used once, post-spawn (parent side). Blocks until the report is final — `spawn` returning
    /// does not make it so (see [`ReportChannel`], which also says why the wait goes through the
    /// child's pidfd). The child's report is the verdict: `cgroup.procs` lists only live tasks, so
    /// a placed child that has already exited reads back absent from it. Only a child that reported
    /// no successful write has `cgroup.procs` and its state read, to diagnose why — see
    /// [`NotPlaced`].
    ///
    /// Taking the verdict closes the `cgroup.procs` fd and the report channel: nothing
    /// needs either after the child's `exec`, and otherwise every live contained child would
    /// hold three fds in the supervisor.
    pub(crate) fn take_placement(&mut self, child: crate::containment::ChildHandle<'_>) -> Result<(), NotPlaced> {
        #[cfg(test)]
        fault::run_on_take_placement();
        let mut channel = self.report.take().expect(RELEASED);
        self.procs_fd = None;
        let report = channel.wait(child.pidfd);
        channel.proceed();
        self.entered = report == PlacementReport::Placed;
        let report = match report {
            PlacementReport::Placed => return Ok(()),
            PlacementReport::NotReported => NotEntered::NotReported,
            PlacementReport::WriteFailed(errno) => NotEntered::WriteFailed(errno),
        };
        let path = self.leaf_path.join("cgroup.procs");
        let child_state = proc_state(child);
        Err(match self.dir.read("cgroup.procs") {
            Ok(procs) => NotPlaced::Absent {
                pid: child.pid,
                path,
                procs,
                report,
                child_state,
            },
            Err(source) => NotPlaced::Unreadable {
                pid: child.pid,
                path,
                source,
                report,
            },
        })
    }

    /// Whether `pid` (which `pidfd` names, when there is one) is in this leaf or a cgroup under it,
    /// for a kill through it.
    pub(crate) fn holds_member(&self, pid: u32, pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> io::Result<bool> {
        self.names(pid, pidfd)
    }

    /// Whether the task `pid` (which `pidfd` names, when there is one) is in this leaf or a cgroup
    /// under it (see [`Subtree::holds`]).
    pub(crate) fn names(&self, pid: u32, pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> io::Result<bool> {
        self.subtree()?.holds(pid, pidfd)
    }

    /// The leaf's cgroup id (see [`cgroup_id`](super::cgroup_id)).
    pub(crate) fn id(&self) -> io::Result<u64> {
        #[cfg(test)]
        if let Some(errno) = fault::cgroup_id_fails() {
            return Err(io::Error::from_raw_os_error(errno));
        }
        self.dir.id()
    }

    /// The leaf as a place to read a task's membership in, once the leaf may be gone: its own
    /// cgroup id, its directory, its path, what its sweep removed, and whether a kill through it
    /// has landed.
    pub(crate) fn subtree(&self) -> io::Result<Subtree> {
        #[cfg(test)]
        if let Some(errno) = fault::subtree_fails() {
            return Err(io::Error::from_raw_os_error(errno));
        }
        Ok(Subtree::new(
            self.id()?,
            Some(self.dir.shared()),
            self.cgroup_path.clone(),
            self.dir.swept(),
            self.placed.clone(),
            std::sync::Arc::clone(&self.killed),
        ))
    }

    /// Watch the elevation front `pid`, this leaf's child: its place is recorded before each
    /// `rmdir` of the leaf, while the leaf's own path still reads without ` (deleted)` (see
    /// [`Subtree::holds`]).
    pub(crate) fn watch_front(&mut self, pid: u32) {
        debug_assert!(
            self.watched.is_none_or(|watched| watched == pid),
            "a leaf watches one front: {:?}, then {pid}",
            self.watched
        );
        self.watched = Some(pid);
    }

    /// Record where the watched front is, by `/proc/<pid>/cgroup`, before the leaf may be removed.
    /// At an `rmdir` that succeeds, the leaf holds no live task, so a front recorded in it is past
    /// leaving its cgroup and can no longer be moved, and a front recorded outside it can no
    /// longer enter it: the record stays true once the leaf is gone.
    ///
    /// While the leaf is live its own path reads plainly: a front that reads it with ` (deleted)`
    /// after it is in a live cgroup of that name beside it, and recorded outside. If the leaf is
    /// already gone (removed by someone else), or whether it is live cannot be read, that path is
    /// undecidable, and nothing is recorded.
    fn record_watched_place(&self) {
        let (Some(pid), Some(path)) = (self.watched, &self.cgroup_path) else {
            return;
        };
        // Outside only when the leaf's own file opens: the leaf is live. Any error, its removal or
        // any other, leaves the path undecided.
        let outside_if_live = || {
            #[cfg(test)]
            let opened = match fault::liveness_read_fails() {
                Some(errno) => Err(io::Error::from_raw_os_error(errno)),
                None => self.dir.open("cgroup.events", rustix::fs::OFlags::PATH),
            };
            #[cfg(not(test))]
            let opened = self.dir.open("cgroup.events", rustix::fs::OFlags::PATH);
            opened.ok().map(|_| false)
        };
        match super::proc_names(path, pid, outside_if_live, false) {
            Ok(inside) => self.placed.record(pid, inside),
            Err(e) => {
                log::debug!(
                    "cgroup v2: elevation front pid {pid}'s place before its leaf's removal cannot be read ({e})"
                );
                self.placed.clear();
            }
        }
    }

    fn rmdir_leaf(&self) -> io::Result<()> {
        self.record_watched_place();
        #[cfg(test)]
        fault::record_leaf_step(|| {
            let events = self.dir.read("cgroup.events").unwrap_or_default();
            format!("rmdir {}", events.lines().next().unwrap_or("(no cgroup.events)"))
        });
        #[cfg(test)]
        if let Some(result) = fault::run_rmdir_hook(&self.leaf_path) {
            return result;
        }
        self.dir.rmdir()
    }

    /// Hard-kill all processes in the cgroup via `cgroup.kill` (kernel ≥ 5.14).
    ///
    /// `Ok` means the tree is dead: either the atomic kill fired, or the leaf was already gone
    /// ([`removed_after_drain`]), which is itself proof every member had exited — `rmdir` on a
    /// cgroup v2 leaf succeeds only once `populated` reads 0.
    ///
    /// Every other errno means the atomic kill did NOT happen — the tree may still be running
    /// (a delegated subtree whose `cgroup.kill` stopped being writable after a privilege drop,
    /// or a cgroupfs remounted `ro`). That is a teardown-mechanism failure and is returned, the
    /// same way every sibling mechanism's is (`Attached::hard_kill`): a caller that reads
    /// `Child::kill_tree() -> Ok(())` over a live tree has been told the opposite of the truth.
    ///
    /// The kill is complete only on kernels with the `cgroup.kill` fork-race fix (`b69bb476dee9`);
    /// see [`Command::kill_on_drop`](crate::Command::kill_on_drop).
    pub(crate) fn hard_kill(&self) -> Result<(), crate::error::Error> {
        let path = self.leaf_path.join("cgroup.kill");
        #[cfg(test)]
        fault::run_before_kill_write();
        #[cfg(test)]
        let written = if fault::kill_writes_fail() || fault::take_next_kill_write_failure() {
            Err(std::io::Error::from_raw_os_error(libc::EIO))
        } else {
            self.dir.write("cgroup.kill", KILL_PAYLOAD)
        };
        #[cfg(not(test))]
        let written = self.dir.write("cgroup.kill", KILL_PAYLOAD);
        match written {
            Ok(()) => {
                #[cfg(test)]
                fault::record_leaf_step(|| "kill".to_string());
                self.killed.store(true, Ordering::Relaxed);
                Ok(())
            }
            Err(e) if removed_after_drain(&e) => {
                log::debug!("cgroup.kill: leaf {} is already gone", path.display());
                Ok(())
            }
            Err(e) => {
                self.kill_attempt_failed.store(true, Ordering::Relaxed);
                Err(crate::error::Error::Io(e))
            }
        }
    }

    /// Block until every process in the leaf has EXITED (not reaped) — `cgroup.events`'s
    /// `populated` reads 0, or the leaf is removed — or until `deadline` (see
    /// [`crate::wait::remaining`]). Reads the leaf first, and answers from that read if it has
    /// drained or the deadline has passed, starting nothing. Otherwise listens to the leaf's
    /// [`Watcher`], starting its pump, reads the leaf again, and blocks until the next broadcast:
    /// no interval, and a wait holds nothing another needs. The watch wakes on the leaf's removal as well as on `populated`,
    /// since the kernel can cancel the one notification a drain sends. A removed leaf holds
    /// nothing: `rmdir` succeeds only on a drained leaf ([`removed_after_drain`]).
    pub(crate) fn wait_drained(
        &self,
        deadline: Option<Option<std::time::Instant>>,
    ) -> Result<crate::containment::TreeDrain, crate::error::Error> {
        use event_listener::Listener as _;

        #[cfg(feature = "tokio")]
        crate::bounded::assert_may_block("waiting for a cgroup leaf to drain");

        // Only the bounded arm advances the frozen clock, so only it is checked.
        #[cfg(test)]
        let mut check = crate::wait::test_clock::RoundCheck::new("wait_drained");
        loop {
            match self.drain_step(deadline)? {
                DrainStep::Done(drain) => return Ok(drain),
                DrainStep::Block {
                    listener,
                    deadline: None,
                } => {
                    listener.wait();
                    #[cfg(test)]
                    fault::notify_wait_site_park(fault::WaitSitePark {
                        deadline: None,
                        woken: true,
                    });
                }
                // A timeout is looked at by the next step, which reads the leaf once more.
                DrainStep::Block {
                    listener,
                    deadline: Some(at),
                } => {
                    #[cfg(test)]
                    check.round();
                    #[cfg(test)]
                    let call_start = std::time::Instant::now();
                    #[cfg_attr(
                        not(test),
                        allow(unused_variables, reason = "`woken` is read only by the test-only recording below")
                    )]
                    let woken = wait_deadline_seamed(listener, at);
                    // Bounds what would otherwise be an unbounded spin under a mock clock a test
                    // forgot to advance: `at` is a real `Instant`, so once real time passes it
                    // this returns immediately every iteration, and only a frozen `remaining()`
                    // that never catches up would keep re-arming the same, already-past
                    // deadline forever. See `test_clock::advance_by_elapsed_if_frozen`'s own doc.
                    // A no-op outside tests and whenever the clock isn't frozen.
                    #[cfg(test)]
                    crate::wait::test_clock::advance_by_elapsed_if_frozen(call_start.elapsed());
                    #[cfg(test)]
                    fault::notify_wait_site_park(fault::WaitSitePark {
                        deadline: Some(at),
                        woken,
                    });
                }
            }
        }
    }

    /// One step of a wait on the leaf's drain, shared by the sync and async waits: read the leaf,
    /// and answer if it has drained or `deadline` has passed. Otherwise listen, starting the pump
    /// (which can itself take real time — spawning its thread), and read it again: a change
    /// after that read is always heard, so the caller may block on the returned listener until
    /// `deadline`, then take another step. Returns `deadline`'s own instant unchanged, in
    /// `Block` — see its doc for why. Reads the clock via [`crate::wait::remaining`], which
    /// honours the test clock in test builds, so a test can pin the zero-remaining shortcut's
    /// boundary exactly without a real one.
    pub(crate) fn drain_step(
        &self,
        deadline: Option<Option<std::time::Instant>>,
    ) -> Result<DrainStep, crate::error::Error> {
        self.drain_step_on(deadline, crate::wait::now)
    }

    /// [`drain_step`](Self::drain_step) reading `now` from `clock`, for a wait whose timer runs
    /// on another clock (tokio's).
    pub(crate) fn drain_step_on(
        &self,
        deadline: Option<Option<std::time::Instant>>,
        clock: impl FnOnce() -> std::time::Instant,
    ) -> Result<DrainStep, crate::error::Error> {
        use crate::containment::TreeDrain;

        if let Some(drain) = self.drain_seen()? {
            return Ok(DrainStep::Done(drain));
        }
        if crate::wait::remaining_at(deadline, clock()) == Some(std::time::Duration::ZERO) {
            #[cfg(test)]
            fault::notify_drain_zero_remaining();
            return Ok(DrainStep::Done(TreeDrain::MembersRemain));
        }
        let listener = self.watch.listen().map_err(crate::error::Error::Io)?;
        if let Some(drain) = self.drain_seen()? {
            return Ok(DrainStep::Done(drain));
        }
        #[cfg(test)]
        fault::notify_drain_blocking();
        Ok(DrainStep::Block {
            listener,
            deadline: deadline.flatten(),
        })
    }

    /// `Some(AllMembersExited)` if the leaf has drained or is gone; `None` if it still holds a
    /// member; an error if the pump that would report a change has stopped.
    fn drain_seen(&self) -> Result<Option<crate::containment::TreeDrain>, crate::error::Error> {
        use crate::containment::TreeDrain;

        if self.watch.saw_removal() || self.drain_now()? == TreeDrain::AllMembersExited {
            return Ok(Some(TreeDrain::AllMembersExited));
        }
        match self.watch.failure() {
            Some(why) => Err(crate::error::Error::Io(io::Error::other(format!(
                "the drain of cgroup leaf {} can no longer be watched: {why}",
                self.leaf_path.display()
            )))),
            None => Ok(None),
        }
    }

    /// Whether the leaf has drained, read now through the held leaf directory, without the watch.
    pub(crate) fn drain_now(&self) -> Result<crate::containment::TreeDrain, crate::error::Error> {
        use crate::containment::TreeDrain;

        let events = match self.dir.read("cgroup.events") {
            Ok(events) => events,
            Err(e) if removed_after_drain(&e) => return Ok(TreeDrain::AllMembersExited),
            Err(e) => return Err(crate::error::Error::Io(e)),
        };
        match parse_populated(&events) {
            Some(true) => Ok(TreeDrain::MembersRemain),
            Some(false) => Ok(TreeDrain::AllMembersExited),
            None => Err(crate::error::Error::Io(io::Error::other(
                "cgroup.events has no 'populated' field — unexpected kernel format",
            ))),
        }
    }

    /// Block until the leaf drains, on the watch held since creation.
    fn block_until_drained(&mut self) -> Result<(), crate::error::Error> {
        #[cfg(feature = "tokio")]
        crate::bounded::assert_may_block("waiting for a cgroup leaf to drain");
        // Stops and joins the pump first: the watch is then this `Drop`'s alone.
        match self.watch.get_mut() {
            Some(watch) => watch.wait(),
            None => Ok(()),
        }
    }

    /// SIGTERM every pid currently listed in `cgroup.procs`.
    ///
    /// An already-gone leaf is `Ok`, on the same proof [`hard_kill`](Self::hard_kill) rests on
    /// ([`removed_after_drain`]): there is no member left to signal. The two halves must agree
    /// about one leaf — a caller doing terminate-then-kill would otherwise take an error from
    /// the graceful half and success from the hard one over the identical directory.
    ///
    /// # PID-reuse window
    /// This reads the pid list then signals each entry. Between the read and
    /// the signal a pid may exit and be recycled, potentially signalling an
    /// unrelated process. This is the same race as the process-group `SIGTERM`
    /// path; the cgroup mechanism's advantage (atomic, pid-free kill) applies
    /// only to `hard_kill` via `cgroup.kill`.
    pub(crate) fn terminate(&self) -> io::Result<()> {
        let path = self.leaf_path.join("cgroup.procs");
        let content = match self.dir.read("cgroup.procs") {
            Ok(c) => c,
            Err(e) if removed_after_drain(&e) => {
                log::debug!("cgroup terminate: leaf {} is already gone", path.display());
                return Ok(());
            }
            Err(e) => return Err(e),
        };
        for line in content.lines() {
            if let Ok(pid) = line.trim().parse::<i32>() {
                _ = kill(Pid::from_raw(pid), Signal::SIGTERM);
            }
        }
        Ok(())
    }
}

#[cfg(all(target_os = "linux", test))]
impl CgroupLeaf {
    /// Test-only placeholder pointing at no real cgroup. Safe to construct and drop —
    /// `remove_dir` of a nonexistent path is a harmless no-op — so it is
    /// usable ONLY for variant-level assertions, never for an operation that touches the
    /// fd or path.
    ///
    /// Its path is shared by every caller, so a test asserting on LOG RECORDS must not use
    /// it: `log_capture` is process-wide, trials can overlap (`--nocapture` with
    /// `--test-threads` > 1), and records from a concurrent sibling would be indistinguishable from its own. Such a test
    /// names its own leaf through [`for_test_at`](Self::for_test_at).
    pub(crate) fn placeholder_for_test() -> CgroupLeaf {
        CgroupLeaf::for_test_at(PathBuf::from("/nonexistent/cosca-cgroup-placeholder"))
    }

    /// Test-only leaf pointing at `leaf_path`, which a test shapes with ordinary files and
    /// directories. Every operation that reads or writes the leaf path (`hard_kill`,
    /// `take_placement`, `Drop`) then runs for real against the kernel's own errnos, on any
    /// Linux host and without a cgroupfs. It has no `cgroup.procs` fd.
    pub(crate) fn for_test_at(leaf_path: PathBuf) -> CgroupLeaf {
        let dir = LeafDir::open_for_test(&leaf_path);
        CgroupLeaf {
            watch: Box::new(Watcher::new(
                DrainWatch::arm(&dir).expect("arm a test leaf's drain watch"),
                dir.name().to_os_string(),
            )),
            dir,
            leaf_path,
            procs_fd: None,
            report: Some(ReportChannel::new().expect("open a placement-report channel")),
            entered: false,
            cgroup_path: None,
            abandoned: false,
            armed: AtomicBool::new(true),
            killed: std::sync::Arc::new(AtomicBool::new(false)),
            watched: None,
            placed: super::PlacedAtRemoval::default(),
            kill_attempt_failed: AtomicBool::new(false),
        }
    }

    /// Give a test leaf the unified-hierarchy path `/proc/<pid>/cgroup` prints for it.
    pub(crate) fn set_cgroup_path_for_test(&mut self, path: String) {
        self.cgroup_path = Some(path);
    }

    /// The record of the watched front's place, as the leaf's subtrees read it.
    pub(crate) fn placed_for_test(&self) -> super::PlacedAtRemoval {
        self.placed.clone()
    }

    /// Whether the leaf still holds its `cgroup.procs` fd or its report channel.
    pub(crate) fn holds_spawn_resources(&self) -> bool {
        self.procs_fd.is_some() || self.report.is_some()
    }
}

#[cfg(target_os = "linux")]
impl Drop for CgroupLeaf {
    fn drop(&mut self) {
        // The pump the leaf owns stops and is joined before anything else: the teardown below
        // uses the watch itself.
        self.watch.stop_pump();
        self.procs_fd = None;
        // Before the verdict — a spawn that failed, maybe after its fork — end the exchange.
        if self.report.is_some() {
            self.abandon_before_verdict(false, None);
        }
        if self.abandoned {
            return;
        }
        // Remove the leaf. If still occupied (e.g. hard_kill not yet called), fire cgroup.kill,
        // wait for the leaf to drain, then retry — but only if the child entered it: a final
        // report other than `Placed` proves nothing of the child's is there. A leaf that outlives
        // the removal is reported.
        let Err(first) = self.rmdir_leaf() else {
            return;
        };
        // `Drop` kills only when the child entered the leaf and it is still armed:
        //
        // | entered | armed | killed | Drop                                                                        |
        // |---------|-------|--------|-----------------------------------------------------------------------------|
        // | true    | true  | –      | rmdir; if it fails, cgroup.kill, drain, sweep, rmdir                        |
        // | true    | false | true   | rmdir; if it fails, re-fire cgroup.kill, wait for the drain, sweep, rmdir   |
        // | true    | false | false  | rmdir; if `populated 0` already, sweep, rmdir; else one rmdir, left running |
        // | false   | –     | –      | one rmdir: the child never entered the leaf                                 |
        if !self.child_entered() {
            if !removed_after_drain(&first) {
                warn_leaf_left_behind(
                    &self.leaf_path,
                    format_args!("rmdir failed ({first}); cgroup.kill not written: nothing of the child's is in it"),
                );
            }
            return;
        }
        // Opted out (see `disarm`): Drop itself never fires `cgroup.kill`. But opting out of
        // Drop's own teardown is not opting out of a kill the caller already did through
        // `kill_tree()`/`hard_kill()`: that kill is real and its drain is exactly as awaitable as
        // the armed path's. An `ENOENT` or `ENODEV` from the first `rmdir` proves the leaf is
        // already gone ([`removed_after_drain`]). Otherwise, a tree the caller killed has not
        // drained yet (`cgroup.kill` is asynchronous) — wait for it, then retry, as the armed path
        // does. A tree left running (never killed) keeps its leaf by request, with no retry.
        if !self.armed.load(Ordering::Relaxed) {
            if removed_after_drain(&first) {
                return;
            }
            if self.killed.load(Ordering::Relaxed) {
                // A stale `killed` flag must not make this wait forever: re-fire the kill before
                // waiting on its drain. An occupant that migrated in after the first kill was
                // never targeted, and on a kernel before 6.14 a process that forked while that
                // kill was in flight could escape it (`cgroup: fix race between fork and
                // cgroup.kill`, Linux 6.14) — either way, `drain_and_remove(false, ..)` re-runs
                // `hard_kill()` first, exactly as the armed path's own kill-then-wait does.
                self.drain_and_remove(
                    false,
                    "after an explicit kill through a handle that opted out of Drop's own teardown",
                );
                return;
            }
            // Never killed: the caller asked for this tree to be left running, and Drop honors
            // that — it does not kill. But "left running" and "already exited on its own" are
            // different questions: a leaf whose `cgroup.events` already reads `populated 0` has
            // nothing left to wait for, so its empty child cgroups are worth one sweep and one
            // more `rmdir`, exactly as a killed leaf's are, before anything is reported. A leaf
            // that is still populated keeps the old single-rmdir, debug-only behaviour — the
            // caller asked for this, so it is not a leak.
            match self.drain_now() {
                Ok(crate::containment::TreeDrain::AllMembersExited) => {
                    self.sweep_and_retry_rmdir("after a caller-opted-out tree exited on its own");
                }
                // Still populated (or unreadable): the tree was never killed. If the caller's own
                // kill_tree()/hard_kill() had actually been attempted and failed, that is not the
                // "opted out and left running" case this leaf's own doc promises — it is a
                // mechanism failure, reported exactly as loudly as the armed path's own kill
                // failure is.
                _ if self.kill_attempt_failed.load(Ordering::Relaxed) => {
                    warn_leaf_left_behind(
                        &self.leaf_path,
                        format_args!(
                            "rmdir failed ({first}); its cgroup.kill failed, so the tree that \
                             opted out of Drop's own teardown is still running"
                        ),
                    );
                }
                _ => {
                    log::debug!(
                        "cgroup leaf {} is left behind for a tree that opted out of teardown ({first})",
                        self.leaf_path.display()
                    );
                }
            }
            return;
        }
        // Armed: kill through the leaf, wait for it to drain, and only then remove it. A leaf
        // that is already gone left nothing behind.
        if !removed_after_drain(&first) {
            self.drain_and_remove(false, "after its handle's teardown");
        }
    }
}

/// How an abandoned spawn's child ended up (see [`CgroupLeaf::abandon_before_verdict`]).
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Abandoned {
    /// Nothing of the child's runs, and it is reaped or will be: it was killed, or had already
    /// exited and been reaped.
    Ended,
    /// The child sent nothing, so nothing names it: there may be none, or one that exits at its
    /// first send, before `exec` and outside the leaf — but that nothing here holds the pid to reap.
    MaybeUnreaped,
    /// The child may be running, and cosca could not kill it: it has no pidfd or refused the
    /// signal, and its leaf does not hold it.
    OutOfReach,
    /// The child is an elevation front, which was sent no signal of its own (see
    /// [`CgroupLeaf::abandon_before_verdict`]), and this is what became of it.
    Front(crate::child::spawn::FrontFate),
}

/// What became of the child itself when its spawn was abandoned.
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ChildFate {
    /// Never sent its intent: if it exists, it exits at its first send, never entering the leaf,
    /// and nothing here can reap it.
    NeverReached,
    /// Already exited and reaped by whoever failed the spawn (std reaps the child of a spawn it
    /// failed).
    Gone,
    /// Killed through its pidfd, with its process group, and reaped.
    Killed,
    /// Could not be killed: no pidfd, or the signal was refused.
    Unkillable,
}

#[cfg(target_os = "linux")]
impl CgroupLeaf {
    /// End the exchange of a spawn that failed before its verdict (see the module's contract),
    /// and answer for its child: kill it and its group, kill through the leaf if it entered, reap
    /// it if no handle owns it, and remove the leaf.
    ///
    /// Idempotent: the channel is taken once, and `Drop` does nothing after it.
    ///
    /// Only a spawn whose child no handle owns may reach this with the child unreaped: tokio drops
    /// a child it forked and then failed to set up, neither killed nor reaped. A spawn path that
    /// still holds its child takes the verdict first, and one whose child `std` reaped leaves
    /// nothing to reap here.
    ///
    /// A child that is an elevation `front` (see [`crate::elevation::front`]) is sent no signal of
    /// its own, which would orphan its elevated program: it is killed through the leaf alone (see
    /// [`end_front`]).
    pub(crate) fn abandon_before_verdict(&mut self, front: bool, handshake: Option<OwnedFd>) -> Abandoned {
        let Some(channel) = self.report.take() else {
            return Abandoned::Ended;
        };
        self.procs_fd = None;
        self.abandoned = true;
        let mut received = channel.shut();
        self.entered = received.placement() == PlacementReport::Placed;
        // The handshake's pidfd names the child where its intent named it by no handle.
        if received.pidfd.is_none() && received.proc_dir.is_none() {
            received.pidfd = handshake;
        }
        // A child that never named itself never reached the point where it could run the program:
        // it is no front, and the handshake's pidfd alone can reap it.
        if received.pid.is_none() {
            if let Some(pidfd) = received.pidfd.take() {
                self.remove_holding_nothing();
                crate::child::spawn::teardown_through_pidfd(None, pidfd, None);
                return Abandoned::Ended;
            }
        }
        // Only a child that reported goes on to `exec`: one that named itself and sent no report
        // never runs the program, and is answered as any child.
        if front && received.report.is_some() {
            if let Some(pid) = received.pid {
                self.watch_front(pid);
            }
            return self.abandon_front(&received);
        }
        // The child first, by its pidfd and as its group, whatever the leaf's own kill does: it
        // may have left the leaf, or never entered it.
        let fate = end_child(&received);
        let through_leaf = self.entered.then(|| self.hard_kill());
        if self.entered {
            self.remove_killing_through(
                through_leaf.as_ref().is_some_and(Result::is_ok),
                "after its spawn was abandoned",
            );
        } else {
            self.remove_holding_nothing();
        }
        match (fate, through_leaf) {
            (ChildFate::NeverReached, _) => Abandoned::MaybeUnreaped,
            (ChildFate::Gone | ChildFate::Killed, _) => Abandoned::Ended,
            // `cgroup.kill` needs no credential, so a placed child is killed through its leaf.
            (ChildFate::Unkillable, Some(Ok(()))) => Abandoned::Ended,
            (ChildFate::Unkillable, _) => Abandoned::OutOfReach,
        }
    }

    /// [`abandon_before_verdict`](Self::abandon_before_verdict) for an elevation front: the leaf
    /// is killed through and removed as for any child, and the front itself is sent nothing. Its
    /// subtree is read first, so the front can still be placed in it once the leaf is gone.
    fn abandon_front(&mut self, received: &Received) -> Abandoned {
        let subtree = self.subtree();
        if let Err(e) = &subtree {
            log::debug!("cgroup v2: an abandoned front's leaf subtree cannot be read ({e})");
        }
        if self.entered {
            let killed = self.hard_kill().is_ok();
            self.remove_killing_through(killed, "after its spawn was abandoned");
        } else {
            self.remove_holding_nothing();
        }
        // Any kill through the leaf, this one or the removal's own, ends what it held.
        end_front(received, |pid, pidfd| match &subtree {
            Ok(subtree) => subtree.reached(pid, pidfd),
            Err(e) => Err(io::Error::new(
                e.kind(),
                format!("its leaf's subtree cannot be read: {e}"),
            )),
        })
    }

    /// Remove a leaf its child entered: killed through, drained, its empty child cgroups removed,
    /// then removed once, a failure reported (see [`drain_and_remove`](Self::drain_and_remove)). `killed`
    /// says whether the caller's own kill through it succeeded; `context` says what removal this
    /// is, for the report of a leaf left behind.
    fn remove_killing_through(&mut self, killed: bool, context: &str) {
        match self.rmdir_leaf() {
            Ok(()) => {}
            Err(e) if removed_after_drain(&e) => {}
            Err(_) => self.drain_and_remove(killed, context),
        }
    }

    /// [`remove_killing_through`](Self::remove_killing_through) after an `rmdir` that failed.
    ///
    /// Kills through the leaf, waits however long the drain takes (a [`DrainWatch`]), removes the
    /// leaf's child cgroups, and makes one more `rmdir`. Any failure of that `rmdir` is final and
    /// reported: after the drain and the sweep, an `EBUSY` means something another party did
    /// since ([`LEFT_BEHIND_CAUSES`]), which another attempt would only make rarer, never
    /// impossible.
    fn drain_and_remove(&mut self, killed: bool, context: &str) {
        if !killed {
            if let Err(e) = self.hard_kill() {
                return warn_leaf_left_behind(
                    &self.leaf_path,
                    format_args!("rmdir failed {context}; cgroup.kill failed ({e})"),
                );
            }
        }
        if let Err(e) = self.block_until_drained() {
            return warn_leaf_left_behind(
                &self.leaf_path,
                format_args!("rmdir failed {context}; its drain could not be watched ({e})"),
            );
        }
        if let Err(e) = self.dir.remove_children() {
            return warn_leaf_left_behind(
                &self.leaf_path,
                format_args!("rmdir failed {context}; a child cgroup could not be removed ({e})"),
            );
        }
        match self.rmdir_leaf() {
            Ok(()) => {}
            Err(e) if removed_after_drain(&e) => {}
            Err(e) if e.raw_os_error() == Some(libc::EBUSY) => warn_leaf_left_behind(
                &self.leaf_path,
                format_args!("rmdir failed ({e}) {context}, after its kill, drain and sweep: {LEFT_BEHIND_CAUSES}"),
            ),
            Err(e) => warn_leaf_left_behind(&self.leaf_path, format_args!("rmdir failed ({e}) {context}")),
        }
    }

    /// Remove a leaf [`drain_now`](Self::drain_now) already found at `populated 0` on its own —
    /// nothing was killed, so nothing needs waiting for. Removes the leaf's now-empty child
    /// cgroups and makes one more `rmdir`; any failure of that `rmdir` other than the leaf already
    /// being gone is reported, the same way [`drain_and_remove`](Self::drain_and_remove)'s own
    /// post-drain sweep is.
    fn sweep_and_retry_rmdir(&mut self, context: &str) {
        if let Err(e) = self.dir.remove_children() {
            return warn_leaf_left_behind(
                &self.leaf_path,
                format_args!("rmdir failed {context}; a child cgroup could not be removed ({e})"),
            );
        }
        match self.rmdir_leaf() {
            Ok(()) => {}
            Err(e) if removed_after_drain(&e) => {}
            Err(e) if e.raw_os_error() == Some(libc::EBUSY) => warn_leaf_left_behind(
                &self.leaf_path,
                format_args!("rmdir failed ({e}) {context}, after its sweep: {LEFT_BEHIND_CAUSES}"),
            ),
            Err(e) => warn_leaf_left_behind(&self.leaf_path, format_args!("rmdir failed ({e}) {context}")),
        }
    }

    /// Remove an abandoned leaf that holds nothing of its child's: never killed through — an
    /// occupant is not cosca's — though its empty child cgroups are removed.
    fn remove_holding_nothing(&mut self) {
        let first = match self.rmdir_leaf() {
            Ok(()) => return,
            Err(e) if removed_after_drain(&e) => return,
            Err(e) => e,
        };
        let why = match self.dir.remove_children() {
            Ok(removed) if removed > 0 => match self.rmdir_leaf() {
                Ok(()) => return,
                Err(e) if removed_after_drain(&e) => return,
                Err(e) => format!("its child cgroups were removed, but rmdir failed again ({e})"),
            },
            Ok(_) => "cgroup.kill not written: nothing of the child's is in it".to_string(),
            Err(e) => format!("a child cgroup could not be removed ({e})"),
        };
        warn_leaf_left_behind(
            &self.leaf_path,
            format_args!("rmdir failed ({first}) after its spawn was abandoned; {why}"),
        );
    }
}

/// Answer for an abandoned spawn's child: kill it and the group it leads, then reap it — it is
/// killed directly, so the wait ends with its exit, and no handle owns it (see
/// [`CgroupLeaf::abandon_before_verdict`]).
///
/// The child is named by the handle its intent carried — a pidfd, or its `/proc/<pid>` directory —
/// never by its number alone. Which path failed the spawn does not need knowing: `std` reaps the
/// child of a spawn it fails, and tokio's post-fork failure never does, but tokio reports both as
/// one error. The handle answers instead: a process `std` reaped opens nothing through it, however
/// its number has been reused since. An intent with no handle names nothing cosca may signal.
///
/// A child it may not signal (`EPERM`) is handed to a background reaper, so it is reaped once it
/// exits, however that comes.
#[cfg(target_os = "linux")]
fn end_child(received: &Received) -> ChildFate {
    use rustix::process::{pidfd_send_signal, waitid, WaitIdOptions};

    #[cfg(feature = "tokio")]
    crate::bounded::assert_may_block("end_child");

    let Some(pid) = received
        .pid
        .and_then(|pid| i32::try_from(pid).ok())
        .and_then(rustix::process::Pid::from_raw)
    else {
        return ChildFate::NeverReached;
    };
    let Some(handle) = received.pidfd.as_ref().or(received.proc_dir.as_ref()) else {
        log::warn!("cgroup v2: an abandoned spawn's child sent no handle on itself ({pid:?}); it is not signalled");
        return ChildFate::Unkillable;
    };
    let id = || wait_id(received, pid);
    if !still_unreaped(received, pid) {
        return ChildFate::Gone;
    }
    #[cfg(test)]
    fault::run_between_check_and_kill();
    #[cfg(test)]
    let denied = fault::take_force_child_kill_denied();
    #[cfg(not(test))]
    let denied = false;
    // Through the handle: the kernel takes a `/proc/<pid>` directory as a pidfd here.
    let killed = if denied {
        Err(rustix::io::Errno::PERM)
    } else {
        pidfd_send_signal(handle, rustix::process::Signal::KILL)
    };
    let killed = match killed {
        // Reaped since the check — only a reaper the crate's contract forbids can have — so it is
        // gone, and its number is not signalled.
        Err(rustix::io::Errno::SRCH) => return ChildFate::Gone,
        // `pidfd_send_signal` itself refused, as a seccomp filter can: the identity was proven a
        // moment ago, and only this process may reap the child, so its pid still names it.
        Err(rustix::io::Errno::NOSYS) | Err(rustix::io::Errno::PERM) if !denied => {
            #[cfg(test)]
            fault::record_signalled_by_pid();
            rustix::process::kill_process(pid, rustix::process::Signal::KILL)
        }
        other => other,
    };
    // The group it leads: an unreaped leader pins the group's id, so this names its group alone.
    if !denied {
        _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
    }
    if let Err(e) = killed {
        log::warn!("cgroup v2: could not kill an abandoned spawn's child ({e}); it is reaped once it exits");
        reap_in_background(id_owned(received, pid));
        return ChildFate::Unkillable;
    }
    #[cfg(test)]
    fault::run_before_exit_wait();
    let status = loop {
        match waitid(id(), WaitIdOptions::EXITED) {
            Err(rustix::io::Errno::INTR) => continue,
            other => break other,
        }
    };
    match status {
        Ok(status) => {
            log::debug!("cgroup v2: reaped an abandoned spawn's child: {status:?}");
            #[cfg(test)]
            fault::record_reaped_orphan(
                received.pid.unwrap_or(0),
                status.and_then(|status| status.terminating_signal()),
            );
        }
        // Nothing else may reap it: the child was unreaped a moment ago, and no handle owns it.
        Err(e) => {
            log::warn!("cgroup v2: could not reap an abandoned spawn's child: {e}");
            debug_assert!(false, "an abandoned spawn's child could not be reaped: {e}");
        }
    }
    ChildFate::Killed
}

/// What names the child `received` names, `pid`, to its reaper: its pidfd, or — with its `/proc`
/// directory proving the number is still its own, and it unreaped — its pid.
#[cfg(target_os = "linux")]
fn wait_id(received: &Received, pid: rustix::process::Pid) -> rustix::process::WaitId<'_> {
    use std::os::fd::AsFd;
    match &received.pidfd {
        Some(pidfd) => rustix::process::WaitId::PidFd(pidfd.as_fd()),
        None => rustix::process::WaitId::Pid(pid),
    }
}

/// Whether the child `received` names, `pid`, is still unreaped. A process `std` reaped is gone:
/// its pidfd waits on nothing, its `/proc` directory opens nothing. A child that sent no handle on
/// itself is not.
#[cfg(target_os = "linux")]
fn still_unreaped(received: &Received, pid: rustix::process::Pid) -> bool {
    use rustix::process::{waitid, WaitIdOptions};
    match (&received.pidfd, &received.proc_dir) {
        (Some(_), _) => loop {
            match waitid(
                wait_id(received, pid),
                WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
            ) {
                Err(rustix::io::Errno::INTR) => continue,
                Err(rustix::io::Errno::CHILD) => break false,
                _ => break true,
            }
        },
        (None, Some(proc_dir)) => {
            // Safety: a NUL-terminated name relative to an open directory; the result is closed.
            let stat =
                unsafe { libc::openat(proc_dir.as_raw_fd(), c"stat".as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC) };
            if stat >= 0 {
                // Safety: the descriptor just opened, closed once.
                unsafe { libc::close(stat) };
            }
            stat >= 0
        }
        (None, None) => false,
    }
}

/// Answer for an abandoned spawn's elevation front, sent nothing: one that has exited is reaped,
/// one its leaf's kill `reached` (given its pid and pidfd) is waited for, through its pidfd, and
/// reaped; any other is left running and unreaped, with nothing that waits for it.
///
/// A child that never named itself, or that `std` collected, never ran the elevated program, so it
/// is no front: it is answered as any child.
#[cfg(target_os = "linux")]
fn end_front(
    received: &Received,
    reached: impl FnOnce(u32, Option<std::os::fd::BorrowedFd<'_>>) -> io::Result<bool>,
) -> Abandoned {
    use std::os::fd::AsFd;

    use crate::child::spawn::FrontFate;
    use rustix::process::{waitid, WaitIdOptions};

    #[cfg(feature = "tokio")]
    crate::bounded::assert_may_block("end_front");

    let Some((raw, pid)) = received
        .pid
        .and_then(|raw| Some((raw, rustix::process::Pid::from_raw(i32::try_from(raw).ok()?)?)))
    else {
        return Abandoned::MaybeUnreaped;
    };
    if received.pidfd.is_none() && received.proc_dir.is_none() {
        log::warn!("cgroup v2: an abandoned spawn's elevation front (pid {raw}) sent no handle on itself; it is left");
        return Abandoned::Front(FrontFate::Unaccounted);
    }
    if !still_unreaped(received, pid) {
        return Abandoned::Ended;
    }
    #[cfg(test)]
    let seen_running = crate::child::spawn::fault::fronts_seen_running();
    #[cfg(not(test))]
    let seen_running = false;
    let exited = if seen_running {
        Ok(None)
    } else {
        loop {
            match waitid(wait_id(received, pid), WaitIdOptions::EXITED | WaitIdOptions::NOHANG) {
                Err(rustix::io::Errno::INTR) => continue,
                other => break other,
            }
        }
    };
    match exited {
        Ok(Some(_)) => return Abandoned::Front(FrontFate::Reaped),
        Ok(None) => {}
        Err(e) => {
            log::warn!("cgroup v2: an abandoned spawn's elevation front (pid {raw}) cannot be waited on ({e})");
            return Abandoned::Front(FrontFate::Unaccounted);
        }
    }
    match reached(raw, received.pidfd.as_ref().map(AsFd::as_fd)) {
        Ok(true) => {}
        Ok(false) => {
            log::warn!(
                "cgroup v2: an abandoned spawn's elevation front (pid {raw}) is outside its leaf's reach; it is left \
                 running, unsignalled and unreaped: a kill would orphan the elevated program"
            );
            return Abandoned::Front(FrontFate::LeftUnreaped);
        }
        Err(e) => {
            log::warn!(
                "cgroup v2: an abandoned spawn's elevation front (pid {raw}) cannot be placed ({e}); it is left \
                 unsignalled and unreaped, and its leaf's kill may have ended it"
            );
            return Abandoned::Front(FrontFate::Unplaced);
        }
    }
    // The leaf's kill reached it, so this wait ends with its exit.
    #[cfg(test)]
    fault::run_before_exit_wait();
    let status = loop {
        match waitid(wait_id(received, pid), WaitIdOptions::EXITED) {
            Err(rustix::io::Errno::INTR) => continue,
            other => break other,
        }
    };
    match status {
        Ok(_) => Abandoned::Front(FrontFate::Reaped),
        Err(e) => {
            log::warn!("cgroup v2: an abandoned spawn's elevation front (pid {raw}) could not be reaped ({e})");
            Abandoned::Front(FrontFate::Unaccounted)
        }
    }
}

/// What names a child to its reaper: its own pidfd, or its pid once its `/proc` directory proved
/// the number its own (see [`end_child`]).
#[cfg(target_os = "linux")]
enum ChildId {
    PidFd(OwnedFd),
    Pid(rustix::process::Pid),
}

#[cfg(target_os = "linux")]
fn id_owned(received: &Received, pid: rustix::process::Pid) -> ChildId {
    match received.pidfd.as_ref().and_then(|pidfd| pidfd.try_clone().ok()) {
        Some(pidfd) => ChildId::PidFd(pidfd),
        None => ChildId::Pid(pid),
    }
}

/// Reap `child` on a detached thread once it exits on its own — a child cosca could not kill.
/// The thread blocks on the child's exit, an event outside this process's control; nothing waits
/// for the thread. That is unowned state (principle 1): the end state is a teardown a handle
/// owns and joins deterministically (units UA, U6 and U7 of the split-165 plan), not a shared
/// reaper.
#[cfg(target_os = "linux")]
fn reap_in_background(child: ChildId) {
    use std::os::fd::AsFd;

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

    #[cfg(test)]
    let notify = fault::take_background_reap_notifier();
    let spawned = std::thread::Builder::new().name("cosca-reap".into()).spawn(move || {
        let id = || match &child {
            ChildId::PidFd(pidfd) => WaitId::PidFd(pidfd.as_fd()),
            ChildId::Pid(pid) => WaitId::Pid(*pid),
        };
        loop {
            match waitid(id(), WaitIdOptions::EXITED) {
                Err(rustix::io::Errno::INTR) => continue,
                Err(e) => log::warn!("cgroup v2: background reap of an abandoned spawn's child failed: {e}"),
                Ok(_) =>
                {
                    #[cfg(test)]
                    if let Some(notify) = &notify {
                        _ = notify.send(());
                    }
                }
            }
            break;
        }
    });
    if let Err(e) = spawned {
        log::warn!("cgroup v2: could not start a thread to reap an abandoned spawn's child, which stays unreaped: {e}");
    }
}

/// What can make a leaf refuse its `rmdir` after its tree was killed and drained and its child
/// cgroups removed. cgroupfs refuses with `EBUSY` only while the leaf holds a process or a child
/// cgroup (`cgroup_destroy_locked`, kernel v6.12), and the VFS gives the same errno, before
/// cgroupfs is asked, for a directory something is mounted on.
#[cfg(target_os = "linux")]
pub(crate) const LEFT_BEHIND_CAUSES: &str = "another party did something since: a process moved into it after the \
     kill, a child cgroup created in it after the sweep, or a mount on it or on a child cgroup";

/// Report a `cosca-*` leaf cosca failed to remove. Nothing revisits a leaf by name, so this
/// record, made as it happens, is all a host accumulating them has to go on.
#[cfg(target_os = "linux")]
fn warn_leaf_left_behind(leaf_path: &Path, what_failed: fmt::Arguments<'_>) {
    log::warn!(
        "cgroup leaf {} was not removed: {what_failed}; it stays on this host until a cgroup \
         manager reaps it",
        leaf_path.display()
    );
}

/// Detect the current process's cgroup v2 path and create a leaf sub-cgroup
/// for containment. Returns the failing step on any failure, so the caller can
/// fall back to the process-group mechanism *and say why it had to*.
///
/// Failure conditions include: cgroup v2 not mounted at `/sys/fs/cgroup`,
/// current process not in a v2 cgroup (v1-only system), leaf directory not
/// writable (undelegated slice), or `cgroup.kill` absent (kernel < 5.14).
#[cfg(target_os = "linux")]
pub(crate) fn try_create_leaf() -> Result<CgroupLeaf, LeafError> {
    let cgroup_file = fs::read_to_string("/proc/self/cgroup").map_err(LeafError::ReadProcSelfCgroup)?;
    let rel_path = parse_v2_relative_path(&cgroup_file).ok_or_else(|| {
        let (line_count, controllers) = summarize_cgroup_controllers(&cgroup_file);
        LeafError::NoUnifiedLine {
            line_count,
            controllers,
        }
    })?;

    let mut leaf = create_leaf_under(&Path::new("/sys/fs/cgroup").join(rel_path.trim_start_matches('/')))?;
    let name = leaf.leaf_path.file_name().expect("a leaf has a name").to_string_lossy();
    leaf.cgroup_path = Some(format!("{}/{name}", rel_path.trim_end_matches('/')));
    Ok(leaf)
}

/// A new leaf's name: `cosca-<pid>-<seq>-<random>`. The pid and sequence number name the spawn for
/// a reader; the 64 random bits keep the name from recurring, as the pid and sequence do across
/// pid namespaces sharing a delegated parent and across processes reusing a pid. `rmdir` relies
/// on it: see [`LeafDir::rmdir`].
#[cfg(target_os = "linux")]
pub(crate) fn leaf_name() -> io::Result<String> {
    let mut random = [0u8; 8];
    getrandom::fill(&mut random).map_err(io::Error::other)?;
    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
    Ok(format!(
        "cosca-{}-{seq}-{:016x}",
        std::process::id(),
        u64::from_ne_bytes(random)
    ))
}

/// Create a containment leaf directly under `current` — the supervisor's own cgroup in
/// production, and a temp directory in the tests that fail each precondition for real.
///
/// Every early return names its step: the caller degrades either way, but never silently.
#[cfg(target_os = "linux")]
pub(crate) fn create_leaf_under(current: &Path) -> Result<CgroupLeaf, LeafError> {
    let leaf_name = leaf_name().map_err(|source| LeafError::CreateLeafDir {
        path: current.join("cosca-*"),
        source,
    })?;
    let leaf_path = current.join(&leaf_name);

    let dir = LeafDir::create(current, &leaf_name).map_err(|source| LeafError::CreateLeafDir {
        path: leaf_path.clone(),
        source,
    })?;

    // Every failure past this point removes the leaf it just created, and reports one it could
    // not remove.
    let fail = |leaf_path: &Path, err: LeafError| -> LeafError {
        #[cfg(test)]
        if fault::take_force_occupy_before_unwind() {
            fs::create_dir(leaf_path.join("occupant")).expect("occupy the leaf");
        }
        if let Err(e) = dir.rmdir() {
            if !removed_after_drain(&e) {
                warn_leaf_left_behind(
                    leaf_path,
                    format_args!("rmdir failed ({e}) after its creation failed ({err})"),
                );
            }
        }
        err
    };

    // Require cgroup.kill (kernel ≥ 5.14); without it there is no atomic kill. A lookup that
    // fails is not an absent file, and is reported with its own errno.
    let kill_path = leaf_path.join("cgroup.kill");
    // Test-only fault seam: treat the leaf as kill-capable (take semantics — see `fault`).
    let kill_exists = || match rustix::fs::statat(dir.dir(), "cgroup.kill", rustix::fs::AtFlags::empty()) {
        Ok(_) => Ok(true),
        Err(rustix::io::Errno::NOENT) => Ok(false),
        Err(e) => Err(io::Error::from(e)),
    };
    #[cfg(test)]
    let kill_supported = if fault::take_force_kill_supported() {
        Ok(true)
    } else if let Some(errno) = fault::take_force_kill_check_errno() {
        Err(io::Error::from_raw_os_error(errno))
    } else {
        kill_exists()
    };
    #[cfg(not(test))]
    let kill_supported = kill_exists();
    match kill_supported {
        Ok(true) => {}
        Ok(false) => {
            return Err(fail(
                &leaf_path,
                LeafError::KillUnsupported {
                    path: leaf_path.clone(),
                },
            ))
        }
        Err(source) => {
            return Err(fail(
                &leaf_path,
                LeafError::CheckKill {
                    path: kill_path,
                    source,
                },
            ))
        }
    }

    // The report channel is opened before the procs fd so a failure here unwinds nothing but
    // the directory: a leaf whose child could not report its placement outcome would reopen
    // exactly the silence this module is reporting its way out of.
    let report = match ReportChannel::new() {
        Ok(r) => r,
        Err(e) => return Err(fail(&leaf_path, LeafError::OpenReportChannel(e))),
    };

    // Open cgroup.procs for writing, close-on-exec: the child's pre_exec write runs after fork
    // and before exec, where the fd is still open.
    //
    // Then move it to fd 3 or above. `open` takes the lowest free number, so with 0, 1 or 2
    // closed here the fd would share its number with one of the child's stdio slots, which std
    // `dup2`s into place before any pre_exec runs: the placement write would land in the
    // caller's stdio target instead, and report a placement that never happened.
    let procs_path = leaf_path.join("cgroup.procs");
    let procs_fd = dir
        .open("cgroup.procs", rustix::fs::OFlags::WRONLY)
        .and_then(crate::above_stdio::above_stdio);
    let procs_fd = match procs_fd {
        Ok(fd) => fd,
        Err(source) => {
            return Err(fail(
                &leaf_path,
                LeafError::OpenProcs {
                    path: procs_path,
                    source,
                },
            ))
        }
    };

    // Armed now, so that no teardown of this leaf can later find itself without a watch.
    let watch = match DrainWatch::arm(&dir) {
        Ok(Some(watch)) => watch,
        // The leaf has no `cgroup.events`: another party removed it since the `mkdir`.
        Ok(None) => {
            return Err(fail(
                &leaf_path,
                LeafError::WatchDrain {
                    path: leaf_path.join("cgroup.events"),
                    source: io::Error::from_raw_os_error(libc::ENOENT),
                },
            ))
        }
        Err(source) => {
            return Err(fail(
                &leaf_path,
                LeafError::WatchDrain {
                    path: leaf_path.join("cgroup.events"),
                    source,
                },
            ))
        }
    };

    Ok(CgroupLeaf {
        leaf_path,
        dir,
        watch: Box::new(Watcher::new(Some(watch), leaf_name.clone().into())),
        procs_fd: Some(procs_fd),
        report: Some(report),
        entered: false,
        cgroup_path: None,
        abandoned: false,
        armed: AtomicBool::new(true),
        killed: std::sync::Arc::new(AtomicBool::new(false)),
        watched: None,
        placed: super::PlacedAtRemoval::default(),
        kill_attempt_failed: AtomicBool::new(false),
    })
}

/// The status an abandoned spawn's child exits with, from inside its hook.
#[cfg(target_os = "linux")]
pub(crate) const ABANDONED_EXIT: i32 = 125;

/// The placement hook a contained spawn registers: close the forked child's inherited copy of the
/// parent's end, then place the child (see [`place_self_in_cgroup_pre_exec`]).
///
/// A spawn the parent abandoned makes the child `_exit` here, with [`ABANDONED_EXIT`], instead of
/// returning an error to `std`. A child that never execs needs no error channel, and `std` would
/// write its error record to the number its channel had — which, once `std`'s spawn returned
/// early because two of fds 0–2 were closed, is one of the child's own stdio slots.
///
/// # Safety
/// As [`place_self_in_cgroup_pre_exec`], in a forked child only.
#[cfg(target_os = "linux")]
pub(crate) unsafe fn placement_hook(procs_fd: RawFd, slot: ReportSlot) -> io::Result<()> {
    // Test-only fault seam: wait for the test's go-ahead (async-signal-safe: one `read`).
    #[cfg(test)]
    if let Some(gate) = fault::take_hook_gate() {
        let mut byte = 0u8;
        // Safety: a one-byte buffer on this frame; `gate` is this child's inherited copy.
        while unsafe { libc::read(gate, (&raw mut byte).cast(), 1) } == -1
            && unsafe { *libc::__errno_location() } == libc::EINTR
        {}
    }
    // Safety: the caller's guarantee: this is the forked child.
    unsafe { slot.close_parents_end() };
    #[cfg(test)]
    fault::die_if_at(fault::ChildDeath::BeforeIntent);
    // Safety: the caller's guarantee.
    match unsafe { place_self_in_cgroup_pre_exec(procs_fd, slot) } {
        // Safety: `_exit` is async-signal-safe, and runs nothing of this process's.
        Err(e) if e.raw_os_error() == Some(libc::ECANCELED) => unsafe { libc::_exit(ABANDONED_EXIT) },
        other => other,
    }
}

/// Place the calling process into the pre-created cgroup leaf by writing `"0"`
/// to `procs_fd`, then close the fd so it does not propagate to grandchildren.
///
/// Called inside a `pre_exec` closure (post-fork, pre-exec), whose `Err` aborts the spawn. It is
/// the child's half of the placement exchange (see the module's contract): it sends its intent,
/// makes the write, and sends its report.
///
/// A failed write (e.g. `EBUSY` when the supervisor's cgroup is itself a leaf — the "no internal
/// processes" rule) returns `Ok`: the child proceeds in the process group already set up, and the
/// parent degrades on the report. So does a parent that decided without the exchange: the child
/// then skips whatever of it is left. `Err` is a spawn the parent abandoned (`ECANCELED`), or a
/// message that could not be sent: a parent still waiting for it would misread the child for its
/// whole life, so the spawn fails instead.
///
/// # Safety
/// Must be called only from a `pre_exec` closure. `procs_fd` must be a valid,
/// open, writable fd in the child process, and `slot`'s channel must still be open.
/// Async-signal-safe: raw `libc` syscalls, no allocation, no format strings.
#[cfg(target_os = "linux")]
pub(crate) unsafe fn place_self_in_cgroup_pre_exec(procs_fd: RawFd, slot: ReportSlot) -> io::Result<()> {
    static ZERO: &[u8] = b"0";
    let abandoned = || io::Error::from_raw_os_error(libc::ECANCELED);
    // The intent goes first, before the leaf is touched: a child the parent has abandoned never
    // enters it.
    // Safety: the caller guarantees the slot's channel is open.
    let intent = unsafe { slot.send_intent() };
    if !matches!(intent, Ok(Delivery::Queued)) {
        // Safety: procs_fd is valid; close is async-signal-safe.
        unsafe { libc::close(procs_fd) };
        return match intent? {
            Delivery::Abandoned => Err(abandoned()),
            _ => Ok(()),
        };
    }
    #[cfg(test)]
    fault::die_if_at(fault::ChildDeath::BeforeReport);
    // Test-only fault seam: a write that returns this instead of writing (take semantics — see
    // `fault`), so a failed placement leaves the child out of the leaf, as a real one does.
    #[cfg(test)]
    let forced = fault::take_force_placement_write_result();
    // Safety: ZERO is a valid buffer; procs_fd is valid (caller guarantees).
    let write = || unsafe { libc::write(procs_fd, ZERO.as_ptr().cast(), ZERO.len()) };
    #[cfg(test)]
    let ret = forced.unwrap_or_else(write);
    #[cfg(not(test))]
    let ret = write();
    // Read errno before `close`, which is free to clobber it.
    // Safety: errno is this thread's own; `__errno_location` is async-signal-safe.
    let errno = if ret == -1 {
        unsafe { *libc::__errno_location() }
    } else {
        0
    };
    // Always close the fd — even on error — so it does not propagate to children.
    // Safety: procs_fd is valid; close is async-signal-safe.
    unsafe { libc::close(procs_fd) };
    let report = match ret {
        // Only the whole write is a placement.
        _ if ret == ZERO.len() as isize => REPORT_PLACED,
        // `write(2)` only ever sets a positive errno, but a report of -1 means "placed", so a
        // nonsensical value is mapped to EIO rather than read back as a fabricated placement.
        -1 if errno > 0 => errno,
        // A write that returned without writing (0) sets no errno.
        _ => libc::EIO,
    };
    // Safety: the caller guarantees the slot's channel is open.
    match unsafe { slot.send_report(report) }? {
        Delivery::Abandoned => Err(abandoned()),
        Delivery::Queued | Delivery::Decided => Ok(()),
    }
}

#[cfg(all(feature = "tokio", target_os = "linux"))]
#[path = "leaf/release.rs"]
mod release;

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

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

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

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