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
//! The process backend behind an async [`Child`](super::Child): tokio's own `process::Child`, or
//! (Windows) a raw `CreateProcessW` child that tokio's `Command` cannot express. `Child` forwards
//! its wait/kill/stream operations here so it stays backend-blind, mirroring the sync
//! [`ProcHandle`](crate::child::proc_handle::ProcHandle).

use std::process::ExitStatus;

#[cfg(unix)]
use crate::child::drop_report::Forgot;
use crate::child::spawn::Diagnosis;
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
#[cfg(unix)]
use crate::signal::RootState;
use crate::signal::{Sent, Sig};
use crate::wait::exit_only::Foreign;

/// How [`ProcSource::wait_and_reap`] ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Waited {
    /// The child exited and is still ours to reap.
    Exited,
    /// Something else reaped it, or (macOS) launchd holds its zombie: it must not be reaped by pid.
    /// The caller forgets it with [`ProcSource::forget_foreign`].
    #[cfg_attr(
        windows,
        allow(dead_code, reason = "a process handle pins its process: no foreign reap")
    )]
    Foreign,
    /// It cannot be shown to be ours, or the wait failed (macOS: no unique id or a failed peek;
    /// Windows: a failed wait on its handle). On Unix it must not be reaped by pid, and the caller
    /// forgets it as for [`Waited::Foreign`].
    Unverified,
}

/// The process backend behind an async [`Child`](super::Child).
// The `Tokio` arm carries `::tokio::process::Child` inline — the common (and, on Unix, only)
// variant, and previously a plain `Child` field, so keeping it inline is no regression. Boxing it
// to shrink the rare Windows-only `Raw` variant would add a heap allocation + indirection to every
// async spawn, so the size difference is accepted deliberately.
#[allow(
    clippy::large_enum_variant,
    reason = "boxing Raw to shrink it would add an allocation to every async spawn on the common Tokio path"
)]
#[derive(Debug)]
pub(crate) enum ProcSource {
    /// A `::tokio::process::Child` (the default path), with what names the process for good.
    Tokio {
        /// tokio's `Child`, held so that nothing but [`ProcSource::release`] hands it to its own
        /// drop, which reaps by pid (see [`Held`]). The paths that have verified the child is ours
        /// release it, every other path forgets it, and dropping the backend with neither done
        /// (an unwind) does whichever is safe.
        child: Held,
        /// The streams tokio had not handed out when the backend was built. They live here, not
        /// in `child`, so that dropping the backend closes this process's ends whatever becomes
        /// of tokio's `Child`.
        stdin: Option<::tokio::process::ChildStdin>,
        stdout: Option<::tokio::process::ChildStdout>,
        stderr: Option<::tokio::process::ChildStderr>,
        /// The pidfd the spawn handshake opened while the child was held before `exec`. It names
        /// this process for good, so a signal through it cannot reach a process that later reuses
        /// the pid.
        #[cfg(target_os = "linux")]
        pidfd: PinnedPidfd,
        /// The child's unique id (see `child::spawn::unique_report`): the only identity a by-pid
        /// signal on macOS is checked against. `None`: no id is held, so the pid is acted on never.
        #[cfg(target_os = "macos")]
        identity: Option<u64>,
    },
    /// A child something else reaped, or one that cannot be shown to be ours (macOS: no unique id,
    /// or a peek that failed): tokio's `Child` is forgotten, and only the streams it had not yet
    /// handed out remain, so a caller who waits and then reads keeps its output.
    #[cfg(unix)]
    Foreign {
        stdin: Option<::tokio::process::ChildStdin>,
        stdout: Option<::tokio::process::ChildStdout>,
        stderr: Option<::tokio::process::ChildStderr>,
        /// Whether the child was shown reaped by someone else ([`Ownership::Foreign`]). `false`: it
        /// could not be shown to be ours, and may still be running.
        reaped_elsewhere: bool,
    },
    /// A raw `CreateProcessW` child owning its process handle directly — the executable/argv[0]
    /// independence (and, later, arbitrary descriptors) that tokio's `Command` cannot express.
    #[cfg(windows)]
    Raw(crate::tokio::spawn::windows_raw::RawAsyncChild),
}

/// The backend's pidfd. A [`ProcSource`] has a `Drop`, so a field cannot be moved out of it; this
/// lets the teardown take the original (never a duplicate, which can fail at the fd limit) and hand
/// it on. Taken only by the hand-off, which forgets the backend at once.
#[cfg(target_os = "linux")]
#[derive(Debug)]
pub(crate) struct PinnedPidfd(Option<std::os::fd::OwnedFd>);

#[cfg(target_os = "linux")]
impl PinnedPidfd {
    fn take(&mut self) -> std::os::fd::OwnedFd {
        self.0
            .take()
            .expect("the pidfd was taken by a hand-off that forgot the backend")
    }
}

#[cfg(target_os = "linux")]
impl std::ops::Deref for PinnedPidfd {
    type Target = std::os::fd::OwnedFd;
    fn deref(&self) -> &std::os::fd::OwnedFd {
        self.0
            .as_ref()
            .expect("the pidfd was taken by a hand-off that forgot the backend")
    }
}

#[cfg(target_os = "linux")]
impl std::os::fd::AsRawFd for PinnedPidfd {
    fn as_raw_fd(&self) -> std::os::fd::RawFd {
        std::os::fd::AsRawFd::as_raw_fd(&**self)
    }
}

#[cfg(target_os = "linux")]
impl std::os::fd::AsFd for PinnedPidfd {
    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
        std::os::fd::AsFd::as_fd(&**self)
    }
}

/// Why a child is forgotten by [`ProcSource::forget_foreign`], completing "child N ...".
#[cfg(unix)]
const FORGET_FOREIGN: &str = "was reaped by someone else, or cannot be shown to be ours";

/// Why a child its handle shows gone, not pinned, or unanswerable is forgotten, completing "child N ...".
#[cfg(unix)]
fn foreign_why(state: &RootState) -> String {
    match state {
        RootState::Unknown(e) => format!("cannot be shown to be ours (RootState::Unknown: {e})"),
        RootState::Unpinned => format!(
            "is not pinned by this process (RootState::Unpinned: {})",
            crate::signal::UNPINNED_WHY
        ),
        RootState::Unreaped | RootState::Reaped => {
            "was reaped by someone else, or cannot be shown to be ours".to_owned()
        }
    }
}

/// Whether a handle's state shows the child reaped by someone else (or held by launchd, which is the
/// same to the fate), rather than unanswerable: only the latter may still be running.
#[cfg(unix)]
fn shown_reaped_elsewhere(state: &RootState) -> bool {
    !matches!(state, RootState::Unknown(_))
}

/// What the one warning for a refused teardown kill says: the kill's error, what became of the
/// child, why the handle forgot it if it did, and what that leaked.
fn refused_kill_warning(
    pid: u32,
    e: &Error,
    handed: bool,
    foreign: Option<&str>,
    leak: Option<&'static str>,
) -> String {
    let mut text = format!(
        "teardown kill of child {pid} failed ({e}); {}",
        refused_kill_fate(handed)
    );
    if let Some(why) = foreign {
        text.push_str(&format!("; the child {why}"));
    }
    if let Some(leak) = leak {
        text.push_str(&format!("; forgetting tokio's handle for it leaks {leak}"));
    }
    text
}

/// What the warning for a refused teardown kill says became of the child: `handed` only when the
/// pidfd teardown really took it.
fn refused_kill_fate(handed: bool) -> &'static str {
    if handed {
        "it is handed to the pidfd teardown"
    } else {
        "it is not waited on"
    }
}

/// tokio's `Child`, which on Unix reaps by pid on drop, when the pid may name another process by
/// now. It is dropped only through [`ProcSource::release`], leaked only through
/// [`ProcSource::forget`], and dropping the backend with neither done is [`ProcSource`]'s own
/// `Drop`. On Windows the process handle pins the process, so none of this changes what it does.
#[derive(Debug)]
pub(crate) struct Held(Option<::tokio::process::Child>);

impl Held {
    fn take(&mut self) -> Option<::tokio::process::Child> {
        self.0.take()
    }
}

impl std::ops::Deref for Held {
    type Target = ::tokio::process::Child;
    fn deref(&self) -> &::tokio::process::Child {
        self.0
            .as_ref()
            .expect("the backend's tokio child was released or forgotten")
    }
}

impl std::ops::DerefMut for Held {
    fn deref_mut(&mut self) -> &mut ::tokio::process::Child {
        self.0
            .as_mut()
            .expect("the backend's tokio child was released or forgotten")
    }
}

/// Split tokio's untaken streams off `child`, so they outlive whatever becomes of it.
fn hold(
    mut child: ::tokio::process::Child,
) -> (
    Held,
    Option<::tokio::process::ChildStdin>,
    Option<::tokio::process::ChildStdout>,
    Option<::tokio::process::ChildStderr>,
) {
    let streams = (child.stdin.take(), child.stdout.take(), child.stderr.take());
    (Held(Some(child)), streams.0, streams.1, streams.2)
}

/// `child`, counted when it is actually dropped (tests: `fault::count_backend_drops`), so a release
/// that does not drop it is not counted either.
#[cfg(test)]
fn counted(child: ::tokio::process::Child) -> super::fault::CountedDrop {
    super::fault::CountedDrop { _child: child }
}
#[cfg(not(test))]
fn counted(child: ::tokio::process::Child) -> ::tokio::process::Child {
    child
}

/// Dropping a backend that nothing released or forgot (an unwind out of a caller does this) does
/// the one safe thing: the untaken streams close with the fields, and tokio's `Child` goes to its
/// own drop only if [`ProcSource::state`] shows it ours, else it is forgotten. It is quiet where
/// it matters: no `log` call while unwinding, since a logger that panics there aborts.
///
/// Nothing is killed: the backend does not know whether the handle was armed.
#[cfg(unix)]
impl Drop for ProcSource {
    fn drop(&mut self) {
        let ProcSource::Tokio { child, .. } = self else {
            return;
        };
        let Some(child) = child.take() else {
            return;
        };
        // A child tokio already reaped has nothing left to drop wrongly.
        if child.id().is_none() || matches!(self.state_of(&child), RootState::Unreaped) {
            drop(counted(child));
        } else {
            std::mem::forget(child);
            #[cfg(test)]
            super::drop_fault::note_forget();
            if !std::thread::panicking() {
                log::debug!("a backend dropped without a release was forgotten: its child is not shown to be ours");
            }
        }
    }
}

/// What waiting on a forgotten child answers: nothing of ours is left to wait for.
#[cfg(unix)]
fn gone() -> Error {
    Error::Io(std::io::Error::from_raw_os_error(libc::ECHILD))
}

impl ProcSource {
    /// A tokio child that `pidfd`, opened by the spawn handshake, names.
    #[cfg(target_os = "linux")]
    pub(crate) fn new(child: ::tokio::process::Child, pidfd: std::os::fd::OwnedFd) -> ProcSource {
        let (child, stdin, stdout, stderr) = hold(child);
        ProcSource::Tokio {
            child,
            stdin,
            stdout,
            stderr,
            pidfd: PinnedPidfd(Some(pidfd)),
        }
    }

    /// A tokio child whose unique id was read as `identity`.
    #[cfg(target_os = "macos")]
    pub(crate) fn new(child: ::tokio::process::Child, identity: Option<u64>) -> ProcSource {
        let (child, stdin, stdout, stderr) = hold(child);
        ProcSource::Tokio {
            child,
            stdin,
            stdout,
            stderr,
            identity,
        }
    }

    /// A tokio child on Windows, where tokio's own process handle is the one that names it.
    #[cfg(windows)]
    pub(crate) fn new(child: ::tokio::process::Child) -> ProcSource {
        let (child, stdin, stdout, stderr) = hold(child);
        ProcSource::Tokio {
            child,
            stdin,
            stdout,
            stderr,
        }
    }

    /// The handle that names the child, for a check that must not go by pid alone. Linux: the pidfd.
    /// macOS: the pid with its unique id, while both are known. Windows: tokio's process handle.
    /// `None` when there is nothing to check a pid against: a forgotten child, a raw Windows child,
    /// or (macOS) one whose unique id or pid is unknown. On Linux a live backend always has its pidfd.
    pub(crate) fn target(&self) -> Option<crate::wait::exit_only::Target<'_>> {
        use crate::wait::exit_only::Target;
        match self {
            #[cfg(target_os = "linux")]
            ProcSource::Tokio { pidfd, .. } => Some(Target::PidFd(std::os::fd::AsFd::as_fd(pidfd))),
            #[cfg(target_os = "macos")]
            ProcSource::Tokio { child, identity, .. } => Some(Target::pid(child.id()?, Some((*identity)?))),
            #[cfg(windows)]
            ProcSource::Tokio { child, .. } => {
                let handle = child.raw_handle()?;
                // SAFETY: tokio owns the live process handle while `raw_handle` is `Some`, and the
                // borrow lasts no longer than `self`.
                Some(Target::Handle(unsafe {
                    std::os::windows::io::BorrowedHandle::borrow_raw(handle)
                }))
            }
            #[cfg(unix)]
            ProcSource::Foreign { .. } => None,
            #[cfg(windows)]
            ProcSource::Raw(_) => None,
        }
    }

    /// The process handle, borrowed from `self`. `None` once tokio has reaped the child and closed it.
    #[cfg(windows)]
    pub(crate) fn raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
        match self {
            ProcSource::Tokio { child, .. } => child.raw_handle(),
            ProcSource::Raw(raw) => Some(raw.raw_handle()),
        }
    }

    /// The child as its spawn holds it, with the handshake pidfd. `None` for a forgotten backend.
    #[cfg(target_os = "linux")]
    pub(crate) fn child_handle(&self, pid: u32) -> Option<crate::containment::ChildHandle<'_>> {
        let crate::wait::exit_only::Target::PidFd(pidfd) = self.target()?;
        Some(crate::containment::ChildHandle { pid, pidfd })
    }

    /// Take tokio's own stdin stream (the Raw backend serves its piped std ends via `owned_std`,
    /// so it has none here).
    pub(crate) fn take_stdin(&mut self) -> Option<::tokio::process::ChildStdin> {
        match self {
            ProcSource::Tokio { stdin, .. } => stdin.take(),
            #[cfg(unix)]
            ProcSource::Foreign { stdin, .. } => stdin.take(),
            #[cfg(windows)]
            ProcSource::Raw(_) => None,
        }
    }
    pub(crate) fn take_stdout(&mut self) -> Option<::tokio::process::ChildStdout> {
        match self {
            ProcSource::Tokio { stdout, .. } => stdout.take(),
            #[cfg(unix)]
            ProcSource::Foreign { stdout, .. } => stdout.take(),
            #[cfg(windows)]
            ProcSource::Raw(_) => None,
        }
    }
    pub(crate) fn take_stderr(&mut self) -> Option<::tokio::process::ChildStderr> {
        match self {
            ProcSource::Tokio { stderr, .. } => stderr.take(),
            #[cfg(unix)]
            ProcSource::Foreign { stderr, .. } => stderr.take(),
            #[cfg(windows)]
            ProcSource::Raw(_) => None,
        }
    }

    /// Block until the child exits, returning its status.
    ///
    /// tokio's own `wait` is a `waitpid` by pid, so on Unix it runs only for a child the handle
    /// shows ours, before and after the exit is awaited (Linux: through the pidfd; macOS: a watch
    /// armed on the unique id read at spawn and checked again after arming). A child reaped
    /// elsewhere is forgotten and answers `ECHILD`. A child the handle cannot answer for
    /// (a failed peek, or macOS without a readable unique id) answers
    /// [`Error::Unassessable`], since it may well be running; it is not forgotten.
    pub(crate) async fn wait(&mut self) -> Result<ExitStatus, Error> {
        match self {
            ProcSource::Tokio { stdin, .. } => {
                // As tokio's own `wait`: stdin closes first, so a child reading it to EOF can exit.
                drop(stdin.take());
                #[cfg(unix)]
                {
                    // Checked before the watch too: a pid that names a stranger now would be
                    // watched until the stranger exits.
                    self.gate()?;
                    self.await_exit().await?;
                    self.gate()?;
                }
                let ProcSource::Tokio { child: c, .. } = self else {
                    unreachable!("a gate that forgot the child returned an error")
                };
                c.wait().await.map_err(Error::Io)
            }
            #[cfg(unix)]
            ProcSource::Foreign { .. } => Err(gone()),
            #[cfg(windows)]
            ProcSource::Raw(r) => r.wait().await,
        }
    }

    /// Exit status if the child has already exited (non-blocking).
    ///
    /// On Unix tokio's `try_wait` is a `waitpid` by pid, so it runs only for a child the handle
    /// shows ours: one reaped elsewhere is forgotten and answers `ECHILD`, and one it cannot answer
    /// for answers [`Error::Unassessable`] (see [`wait`](ProcSource::wait)).
    pub(crate) fn try_wait(&mut self) -> Result<Option<ExitStatus>, Error> {
        #[cfg(unix)]
        self.gate()?;
        match self {
            ProcSource::Tokio { child: c, .. } => c.try_wait().map_err(Error::Io),
            #[cfg(unix)]
            ProcSource::Foreign { .. } => Err(gone()),
            #[cfg(windows)]
            ProcSource::Raw(r) => r.try_wait(),
        }
    }

    /// `Ok` for a child the handle shows ours, or that tokio already reaped. Reaped elsewhere: the
    /// child is forgotten and the answer is `ECHILD`. Not shown either way: `Unassessable`, with the
    /// child left in place, so a later call can still answer and a `Drop` forgets it.
    #[cfg(unix)]
    fn gate(&mut self) -> Result<(), Error> {
        let ProcSource::Tokio { child, .. } = &*self else {
            return Ok(());
        };
        let Some(pid) = child.id() else {
            return Ok(());
        };
        match self.state_of(child) {
            RootState::Unreaped => Ok(()),
            RootState::Reaped => {
                self.forget_as("was reaped by someone else", true);
                Err(gone())
            }
            RootState::Unknown(failed) => Err(Error::Unassessable {
                detail: format!("pid {pid}: the child cannot be shown to be ours; it was not waited on"),
                source: Some(failed),
            }),
            RootState::Unpinned => Err(Error::Unassessable {
                detail: format!(
                    "pid {pid}: the child cannot be shown to be ours ({}); it was not waited on",
                    crate::signal::UNPINNED_WHY
                ),
                source: None,
            }),
        }
    }

    /// Waits, without reaping, until the child's exit is visible through its handle (Linux: the
    /// pidfd turns readable; macOS: the verified-id kqueue watch fires).
    #[cfg(unix)]
    async fn await_exit(&self) -> Result<(), Error> {
        #[cfg(target_os = "linux")]
        {
            let ProcSource::Tokio { pidfd, .. } = self else {
                return Ok(());
            };
            let pidfd = pidfd.try_clone().map_err(Error::Io)?;
            crate::tokio::wait::watch_pidfd(pidfd).await
        }
        #[cfg(target_os = "macos")]
        {
            let ProcSource::Tokio { child, identity, .. } = self else {
                return Ok(());
            };
            // No unique id, or the child already reaped: nothing to watch, and the gate after this
            // decides what that means.
            let (Some(pid), Some(identity)) = (child.id(), *identity) else {
                return Ok(());
            };
            crate::tokio::wait::wait_exit_for(pid, identity).await
        }
    }

    /// Whether the backend still holds something that pins the child's pid against reuse.
    /// tokio's `Child` replaces its inner state the moment `wait`/`try_wait` observes the exit,
    /// dropping the guard that holds the process handle (`id()` goes `None` with it); the raw
    /// backend owns its handle for the child's whole life and never unpins.
    #[cfg(windows)]
    pub(crate) fn pins_pid(&self) -> bool {
        match self {
            ProcSource::Tokio { child: c, .. } => c.id().is_some(),
            ProcSource::Raw(_) => true,
        }
    }

    /// Send `sig` to the child. Does not reap. [`Sent::Gone`] means nothing was delivered because
    /// the child is already gone (reaped by tokio or by someone else); for [`Sent::Unverified`], see
    /// there. Neither is an error.
    ///
    /// - **Linux:** `pidfd_send_signal` on the handshake pidfd, never by pid, so a foreign reap
    ///   followed by a pid reuse cannot redirect it.
    /// - **macOS:** by pid, only while the pid still has the unique id read at spawn; macOS has no
    ///   handle to send through, so a reap between check and send is an accepted gap.
    pub(crate) fn signal(&self, sig: Sig) -> Result<Sent, Error> {
        match self {
            #[cfg(unix)]
            ProcSource::Foreign { reaped_elsewhere, .. } => {
                log::debug!("the child was reaped by someone else, or cannot be shown to be ours; {sig:?} not sent");
                Ok(if *reaped_elsewhere {
                    Sent::Gone
                } else {
                    Sent::Unverified
                })
            }
            #[cfg(unix)]
            ProcSource::Tokio { child, .. } if child.id().is_none() => {
                log::debug!("the child is already reaped; {sig:?} not sent");
                Ok(Sent::Gone)
            }
            #[cfg(target_os = "linux")]
            ProcSource::Tokio { child, pidfd, .. } => {
                let pid = child.id().expect("checked above");
                crate::signal::via_pidfd(Some(std::os::fd::AsFd::as_fd(pidfd)), pid, sig).map_err(Error::Io)
            }
            #[cfg(target_os = "macos")]
            ProcSource::Tokio { child, identity, .. } => {
                let pid = child.id().expect("checked above");
                crate::signal::via_verified_pid(pid, *identity, sig).map_err(Error::Io)
            }
            #[cfg(windows)]
            ProcSource::Tokio { child, .. } => {
                let Sig::Kill = sig;
                use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, HANDLE, WAIT_FAILED};
                use windows::Win32::System::Threading::{TerminateProcess, WaitForSingleObject};
                // tokio drops its handle once it has reaped the child.
                let Some(h) = child.raw_handle() else {
                    return Ok(Sent::Gone);
                };
                // SAFETY: tokio owns the live process handle while `raw_handle` is `Some`; exit
                // code 1 is the forced-kill code std's `Child::kill` uses.
                match unsafe { TerminateProcess(HANDLE(h), 1) } {
                    Ok(()) => Ok(Sent::Delivered),
                    // As std's `Child::kill`: a process that is already exiting answers
                    // `ACCESS_DENIED`, which is success, unless the handle cannot even be waited on.
                    Err(e) if e.code() == windows::core::HRESULT::from_win32(ERROR_ACCESS_DENIED.0) => {
                        // SAFETY: as above; a zero-timeout wait only reads the handle's state.
                        if unsafe { WaitForSingleObject(HANDLE(h), 0) } == WAIT_FAILED {
                            Err(Error::Io(e.into()))
                        } else {
                            Ok(Sent::Delivered)
                        }
                    }
                    Err(e) => Err(Error::Io(e.into())),
                }
            }
            #[cfg(windows)]
            ProcSource::Raw(r) => {
                let Sig::Kill = sig;
                r.start_kill().map(|()| Sent::Delivered)
            }
        }
    }

    /// Whether the root is still this backend's child to act on, from its own handle; see
    /// [`RootState`]. Nothing is logged: it may run during an unwind.
    ///
    /// - **Linux:** a peek through the pidfd. Exact, with no start token to collide.
    /// - **macOS:** a peek that checks the pid's unique id, including that a running child's id can
    ///   be read ([`exit_only::peek_verified`](crate::wait::exit_only)). A child with no unique id
    ///   (a spawn whose unique id was not adopted, see `adopted_id`) is `Unknown`: its unique-id
    ///   read was refused, and nothing shows the pid still names it.
    ///
    /// A child tokio reaped (`id()` is `None`) and a forgotten backend are `Reaped`.
    #[cfg(unix)]
    pub(crate) fn state(&self) -> RootState {
        match self {
            ProcSource::Foreign { .. } => RootState::Reaped,
            ProcSource::Tokio { child, .. } if child.id().is_none() => RootState::Reaped,
            ProcSource::Tokio { child, .. } => self.state_of(child),
        }
    }

    /// [`state`](ProcSource::state) of a `Tokio` backend whose `child` may already be taken out of
    /// it (the drop does that), for a child tokio has not reaped.
    #[cfg(unix)]
    fn state_of(
        &self,
        #[cfg_attr(
            target_os = "linux",
            allow(unused_variables, reason = "Linux peeks the pidfd, not the pid")
        )]
        child: &::tokio::process::Child,
    ) -> RootState {
        let ProcSource::Tokio { .. } = self else {
            return RootState::Reaped;
        };
        #[cfg(target_os = "linux")]
        let peeked = {
            let ProcSource::Tokio { pidfd, .. } = self else {
                unreachable!("checked above")
            };
            crate::wait::exit_only::peek(&crate::wait::exit_only::Target::PidFd(std::os::fd::AsFd::as_fd(pidfd)))
        };
        #[cfg(target_os = "macos")]
        let peeked = {
            let ProcSource::Tokio { identity, .. } = self else {
                unreachable!("checked above")
            };
            let (Some(pid), Some(identity)) = (child.id(), *identity) else {
                return RootState::Unknown(std::io::Error::other(
                    "the child's unique id is unknown, so nothing shows its pid still names it",
                ));
            };
            crate::wait::exit_only::peek_verified(&crate::wait::exit_only::Target::pid(pid, Some(identity)))
        };
        RootState::of_peek(peeked)
    }

    /// The pid and non-`Unreaped` state of a child tokio has not reaped, if its handle shows one.
    #[cfg(unix)]
    fn elsewhere(&self) -> Option<(u32, RootState)> {
        let ProcSource::Tokio { child, .. } = self else {
            return None;
        };
        let pid = child.id()?;
        match self.state_of(child) {
            RootState::Unreaped => None,
            state => Some((pid, state)),
        }
    }

    /// Forget the child: tokio's `Child` is leaked, never dropped, because its drop would reap by
    /// pid, and the pid may name another process by now. The untaken streams close, and so does
    /// cosca's own pidfd. What leaks is tokio's own: on Linux its pidfd and its reactor
    /// registration, on macOS its `SIGCHLD` watch.
    #[cfg(unix)]
    pub(crate) fn forget(mut self) {
        if let ProcSource::Tokio { child, .. } = &mut self {
            if let Some(child) = child.take() {
                std::mem::forget(child);
            }
        }
    }

    /// Hand tokio's `Child` to its own drop, which `try_wait`s once and queues a still-running
    /// child on the runtime's orphan queue. Only for a child verified to be ours: that drop reaps
    /// by pid.
    pub(crate) fn release(mut self) {
        if let ProcSource::Tokio { child, .. } = &mut self {
            drop(child.take().map(counted));
        }
    }

    /// The pidfd naming the child, if the backend holds one (Linux).
    #[cfg(unix)]
    pub(crate) fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
        match self.target()? {
            #[cfg(target_os = "linux")]
            crate::wait::exit_only::Target::PidFd(fd) => Some(fd),
            #[allow(unreachable_patterns, reason = "a Linux backend's target is always its pidfd")]
            _ => None,
        }
    }

    /// Whether the child is still running, read without reaping it: `false` once it is reaped, by
    /// tokio or by someone else, or has exited. On macOS a child with no unique id cannot be read.
    #[cfg(unix)]
    pub(crate) fn is_running(&self) -> std::io::Result<bool> {
        if self.is_reaped() {
            return Ok(false);
        }
        let Some(target) = self.target() else {
            return Err(std::io::Error::other(
                "the child's unique id is unknown, so nothing shows its pid still names it",
            ));
        };
        Ok(matches!(
            crate::wait::exit_only::peek(&target)?,
            crate::wait::exit_only::Peek::Running
        ))
    }

    /// `true` once the backend has collected the child's status, so no reap remains.
    pub(crate) fn is_reaped(&self) -> bool {
        match self {
            ProcSource::Tokio { child: c, .. } => c.id().is_none(),
            #[cfg(unix)]
            ProcSource::Foreign { .. } => true,
            #[cfg(windows)]
            ProcSource::Raw(r) => r.is_reaped(),
        }
    }

    /// Block until the child has exited, then let the backend reap it. **Never kills** — the
    /// caller's own successful kill is what bounds the wait.
    /// **Invariant:** no `wait()` future for this child is in flight when this runs.
    ///
    /// The caller's child was never awaited, so an already-reaped one is a broken precondition,
    /// asserted in debug.
    ///
    /// - **Linux:** `waitid(P_PIDFD, WEXITED | WNOWAIT)` on the kept pidfd, so tokio's own
    ///   field-drop reaps the zombie. `ECHILD` is [`Waited::Foreign`]. So is any other failure (a
    ///   contract breach, asserted in debug): without proof the child is ours, tokio's by-pid reap
    ///   must not run.
    /// - **macOS:** the sync child's verified-id wait (a kqueue plus peeks that check the pid's
    ///   unique id), which never reaps. A child a tracer holds is waited for until the tracer
    ///   hands it back. A foreign reap, a pid with another unique id and a launchd-held zombie are
    ///   [`Waited::Foreign`]. What cannot be shown to be ours or reaped is [`Waited::Unverified`]: a
    ///   refused read, a failed peek or kqueue (warned), and a child with no unique id (a
    ///   spawn whose unique id was not adopted, see `adopted_id`), which is not waited on at all. A reap and reuse
    ///   between the verified exit and tokio's reap is an accepted gap.
    /// - **Windows:** waits on tokio's process handle, which pins the child.
    ///
    /// On [`Waited::Foreign`] or [`Waited::Unverified`] the caller calls
    /// [`forget_foreign`](ProcSource::forget_foreign).
    #[cfg(any(windows, test))]
    pub(crate) fn wait_and_reap(&mut self, pid: u32) -> Waited {
        self.wait_and_reap_at(pid, log::Level::Warn)
    }

    /// [`wait_and_reap`](ProcSource::wait_and_reap), logging what it finds that is not an exit at
    /// `level`: for a caller that reports a [`Waited::Foreign`] itself, in its one warn.
    #[cfg(any(windows, test))]
    pub(crate) fn wait_and_reap_at(&mut self, pid: u32, level: log::Level) -> Waited {
        self.wait_and_reap_caused(pid, level).0
    }

    /// [`wait_and_reap_at`](ProcSource::wait_and_reap_at), and why a [`Waited::Foreign`] was found:
    /// the wait's error, or why the child is not ours.
    pub(crate) fn wait_and_reap_caused(
        &mut self,
        pid: u32,
        #[cfg_attr(
            windows,
            allow(unused_variables, reason = "a process handle pins its process: nothing to log")
        )]
        level: log::Level,
    ) -> (Waited, Option<String>) {
        crate::bounded::assert_may_block("wait_and_reap");
        match self {
            // Already forgotten, with no fresh evidence of what became of it.
            #[cfg(unix)]
            ProcSource::Foreign { .. } => (Waited::Unverified, None),
            #[cfg(target_os = "linux")]
            ProcSource::Tokio { child, pidfd, .. } => {
                if !still_ours(child) {
                    return (Waited::Exited, None);
                }
                #[cfg(test)]
                crate::child::spawn::fault::run_between_kill_and_wait();
                wait_on_pidfd(pid, pidfd, level)
            }
            #[cfg(target_os = "macos")]
            ProcSource::Tokio { child, identity, .. } => {
                if !still_ours(child) {
                    return (Waited::Exited, None);
                }
                // No unique id is held, so nothing shows the pid names this child: it is never waited
                // on.
                let Some(identity) = identity else {
                    return (
                        Waited::Unverified,
                        Some("no unique id is held, so nothing shows its pid names it".to_owned()),
                    );
                };
                #[cfg(test)]
                crate::child::spawn::fault::run_between_kill_and_wait();
                wait_reapable(pid, *identity, level)
            }
            #[cfg(windows)]
            ProcSource::Tokio { child, .. } => {
                if !still_ours(child) {
                    return (Waited::Exited, None);
                }
                #[cfg(test)]
                crate::child::spawn::fault::run_between_kill_and_wait();
                (wait_on_handle(child, pid), None)
            }
            #[cfg(windows)]
            ProcSource::Raw(_) => unreachable!("the raw backend tears its own spawn failures down"),
        }
    }

    /// Give up a child something else reaped, or that cannot be shown to be ours
    /// ([`Waited::Foreign`]): tokio's `Child` is forgotten, never dropped, because its drop
    /// would reap by pid, and the pid may name another process by now. The untaken
    /// streams are kept, and the backend is [`reaped`](ProcSource::is_reaped) from here on.
    ///
    /// Forgetting leaks what tokio's `Child` holds — on Linux its pidfd and its reactor
    /// registration, on macOS its `SIGCHLD` watch — so it is logged at `warn`, naming the pid.
    /// Returns what the forget leaks, or `None` if the backend was already forgotten.
    #[cfg(all(unix, test))]
    pub(crate) fn forget_foreign(&mut self) -> Option<&'static str> {
        self.forget_foreign_noting(&mut Diagnosis::default())
    }

    /// [`forget_foreign`](ProcSource::forget_foreign) for a spawn whose identity check found `why`:
    /// the forget's one warn carries it.
    #[cfg(unix)]
    pub(crate) fn forget_foreign_noting(&mut self, why: &mut Diagnosis) -> Option<&'static str> {
        self.forget_noting(FORGET_FOREIGN, false, why)
    }

    /// [`forget_foreign`](ProcSource::forget_foreign) for any reason: `why` completes "child N ...",
    /// so the warning says what actually happened. A reap by someone else is not claimed: use
    /// [`forget_as`](ProcSource::forget_as) for a child shown reaped elsewhere.
    #[cfg(target_os = "macos")]
    pub(crate) fn forget_because(&mut self, why: &str) -> Option<&'static str> {
        self.forget_as(why, false)
    }

    /// The fate recorded by the forgetting; `None` if not forgotten (see `forget_if_foreign`).
    #[cfg(unix)]
    pub(crate) fn forgotten_fate(&self, id: Option<ProcessId>) -> Option<ChildFate> {
        match self {
            ProcSource::Foreign { reaped_elsewhere, .. } => Some(if *reaped_elsewhere {
                ChildFate::Gone
            } else {
                ChildFate::Running { id }
            }),
            _ => None,
        }
    }

    /// [`forget_because`](ProcSource::forget_because), recording whether the child was shown reaped
    /// by someone else.
    #[cfg(unix)]
    pub(crate) fn forget_as(&mut self, why: &str, reaped_elsewhere: bool) -> Option<&'static str> {
        self.forget_noting(why, reaped_elsewhere, &mut Diagnosis::default())
    }

    /// [`forget_noting`](ProcSource::forget_noting) that logs nothing: the forget is owed to `owed`,
    /// for a caller whose teardown warns next and carries it.
    #[cfg(target_os = "linux")]
    fn forget_deferring(&mut self, why: &str, reaped_elsewhere: bool, owed: &mut Diagnosis) -> Option<&'static str> {
        let (pid, leak) = self.forget_quietly(reaped_elsewhere)?;
        owed.add(format!(
            "child {pid} {why}; forgetting tokio's handle for it leaks {leak}"
        ));
        Some(leak)
    }

    /// [`forget_as`](ProcSource::forget_as) for a spawn whose identity check found `diagnosis`: the
    /// forget's one warn carries it.
    #[cfg(unix)]
    pub(crate) fn forget_noting(
        &mut self,
        why: &str,
        reaped_elsewhere: bool,
        diagnosis: &mut Diagnosis,
    ) -> Option<&'static str> {
        let (pid, leak) = self.forget_quietly(reaped_elsewhere)?;
        log::warn!(
            "{}",
            diagnosis.fold(format!(
                "child {pid} {why}; forgetting tokio's handle for it leaks {leak}"
            ))
        );
        Some(leak)
    }

    /// Forget tokio's `Child` without logging, for a caller that reports the forget in its own one
    /// warn. Returns the child's pid and what the forget leaks, or `None` if the backend was
    /// already forgotten (or never held a child): nothing was forgotten, so nothing leaked.
    /// `reaped_elsewhere`: whether the child was shown reaped by someone else; `false`, it could not
    /// be shown to be ours, and may still be running.
    #[cfg(unix)]
    fn forget_quietly(&mut self, reaped_elsewhere: bool) -> Option<(String, &'static str)> {
        let leak = if cfg!(target_os = "linux") {
            "tokio's pidfd and its reactor registration"
        } else {
            "tokio's SIGCHLD watch"
        };
        let ProcSource::Tokio {
            child,
            stdin,
            stdout,
            stderr,
            ..
        } = self
        else {
            return None;
        };
        let pid = child.id().map_or_else(|| "?".to_owned(), |pid| pid.to_string());
        let foreign = ProcSource::Foreign {
            stdin: stdin.take(),
            stdout: stdout.take(),
            stderr: stderr.take(),
            reaped_elsewhere,
        };
        std::mem::replace(self, foreign).forget();
        #[cfg(test)]
        super::drop_fault::note_forget();
        Some((pid, leak))
    }

    /// Forget tokio's `Child` where `view` shows the drop must not leave it to tokio's own drop,
    /// which reaps by pid. One policy for every drop and cleanup, and a quiet one: the caller's one
    /// warn carries what was forgotten.
    /// - a root the view shows reaped is forgotten on that evidence;
    /// - any other only if a second look shows it gone, not pinned, or unanswerable.
    ///
    /// `None` if nothing was forgotten: tokio already reaped the child, it is already forgotten, or
    /// the second look shows it ours.
    #[cfg(unix)]
    pub(crate) fn forget_for(&mut self, view: &crate::containment::DropView) -> Option<Forgot> {
        use crate::containment::dispatch::RootView;
        let now = match view.root {
            RootView::Reaped => {
                if !self.holds_unreaped_child() {
                    return None;
                }
                None
            }
            RootView::Unknown(_) | RootView::Unpinned | RootView::Trusted => Some(self.elsewhere()?.1),
        };
        let reaped_elsewhere = now.as_ref().is_none_or(shown_reaped_elsewhere);
        let (_, leak) = self.forget_quietly(reaped_elsewhere)?;
        Some(Forgot { leak, now, cause: None })
    }

    /// Forget tokio's `Child` after a wait found it foreign for `cause`, quietly.
    #[cfg(unix)]
    pub(crate) fn forget_for_wait(&mut self, waited: Waited, cause: Option<String>) -> Option<Forgot> {
        let (_, leak) = self.forget_quietly(waited == Waited::Foreign)?;
        Some(Forgot { leak, now: None, cause })
    }

    /// Whether tokio's `Child` is still held and has not reaped its child.
    #[cfg(unix)]
    fn holds_unreaped_child(&self) -> bool {
        matches!(self, ProcSource::Tokio { child, .. } if child.id().is_some())
    }

    /// [`forget_foreign`](ProcSource::forget_foreign), but only on evidence, for the places that
    /// release the backend without waiting: the handle shows the child reaped elsewhere, not
    /// pinned, or cannot be asked. One warn, naming the error when the handle could not say.
    /// Returns what the forget leaks, if it forgot.
    #[cfg(unix)]
    pub(crate) fn forget_if_foreign(&mut self) -> Option<&'static str> {
        self.forget_if_foreign_noting(&mut Diagnosis::default())
    }

    /// [`forget_if_foreign`](ProcSource::forget_if_foreign) for a spawn whose identity check found
    /// `diagnosis`.
    #[cfg(unix)]
    fn forget_if_foreign_noting(&mut self, diagnosis: &mut Diagnosis) -> Option<&'static str> {
        let (_, state) = self.elsewhere()?;
        self.forget_noting(&foreign_why(&state), shown_reaped_elsewhere(&state), diagnosis)
    }

    /// [`forget_if_foreign`](ProcSource::forget_if_foreign) without the warn, for a caller whose
    /// one warn carries it: what the forget leaks, why the child was forgotten, and what became of
    /// it (`Gone` if it was shown reaped by someone else or held by launchd, `Running` with `id`, the
    /// child's identity if the caller has read one, if it cannot be shown to be ours).
    #[cfg(unix)]
    fn forget_if_foreign_quietly(&mut self, id: Option<ProcessId>) -> Option<(&'static str, String, ChildFate)> {
        let (_, state) = self.elsewhere()?;
        let (_, leak) = self.forget_quietly(shown_reaped_elsewhere(&state))?;
        let fate = if shown_reaped_elsewhere(&state) {
            ChildFate::Gone
        } else {
            ChildFate::Running { id }
        };
        Some((leak, foreign_why(&state), fate))
    }

    /// Guaranteed synchronous teardown for a spawn that failed after the fork: kill the child
    /// through its handle (Linux: the pidfd; macOS: the pid, only while it has the child's unique
    /// id; a child with none is neither signalled nor waited on), then block until it has exited. A
    /// child something else reaped, or one that cannot be shown to be ours, is forgotten
    /// ([`forget_foreign`](ProcSource::forget_foreign)) instead, with a warning naming it. The kill
    /// is what bounds the wait, so a caller that has ALREADY killed uses
    /// [`wait_and_reap`](ProcSource::wait_and_reap) instead.
    ///
    /// A refused kill is not waited on here. Linux: the child goes to the pidfd teardown (another
    /// kill, then a reap through the pidfd, or a background reap once it exits) and tokio's `Child` is
    /// forgotten. Elsewhere: a child its handle does not show reaped elsewhere is released to the
    /// runtime's orphan reaper. A child shown reaped elsewhere is forgotten either way. Consumes the
    /// backend, so every path ends in [`release`](ProcSource::release) or
    /// [`forget`](ProcSource::forget). **Invariant:** no `wait()` future for this child is in flight
    /// when this runs.
    ///
    /// `id` is the child's identity, if the spawn had read one.
    pub(crate) fn reap_now(self, pid: u32, id: Option<ProcessId>) -> ChildFate {
        self.reap_now_noting(pid, id, &mut Diagnosis::default())
    }

    /// [`reap_now`](ProcSource::reap_now) for a spawn whose identity check found `why`: the
    /// teardown's one warn carries it.
    pub(crate) fn reap_now_noting(mut self, pid: u32, id: Option<ProcessId>, why: &mut Diagnosis) -> ChildFate {
        crate::bounded::assert_may_block("reap_now");
        let killed = self.teardown_kill();
        if let Err(e) = &killed {
            // Tokio's drop reaps by pid: a child the handle shows reaped elsewhere is forgotten.
            #[cfg(unix)]
            let foreign = self.forget_if_foreign_quietly(id);
            #[cfg(not(unix))]
            let foreign: Option<(&'static str, String, ChildFate)> = None;
            // Handed off before the log and the assertion: a panic from either must not strand a
            // child that is ours. Linux: through its pidfd, never to tokio's orphan queue, whose
            // `waitpid(pid)` could one day reap a reused pid.
            #[cfg(target_os = "linux")]
            let (handed, hand_leak) = self.hand_to_pidfd_reaper(pid, id);
            #[cfg(not(target_os = "linux"))]
            let (handed, hand_leak): (Option<ChildFate>, Option<&'static str>) = {
                self.release();
                (None, None)
            };
            log::warn!(
                "{}",
                why.fold(refused_kill_warning(
                    pid,
                    e,
                    handed.is_some(),
                    foreign.as_ref().map(|f| f.1.as_str()),
                    foreign.as_ref().map(|f| f.0).or(hand_leak)
                ))
            );
            // `EPERM` is a setuid child refusing the kill, reachable without a bug: it alone is not
            // asserted.
            debug_assert!(
                matches!(e, Error::Io(io) if io.kind() == std::io::ErrorKind::PermissionDenied),
                "the teardown kill of an owned child failed: {e}"
            );
            return after_refused_kill(handed, foreign.map(|f| f.2), id);
        }
        // Only the wait's evidence says the child was reaped elsewhere: a kill that found it gone may
        // have sent nothing at all (a macOS child with no unique id). A child the wait cannot show
        // to be ours is dead or dying if the kill was delivered, and may be running if it was not.
        // The wait logs at `debug`: the forget's one warn carries its cause.
        #[cfg(unix)]
        let (waited, cause) = self.wait_and_reap_caused(pid, log::Level::Debug);
        #[cfg(not(unix))]
        let waited = self.wait_and_reap(pid);
        let fate = match waited {
            Waited::Exited => self.collect_exit(id),
            Waited::Foreign => Foreign::Gone.fate(matches!(killed, Ok(Sent::Delivered))),
            Waited::Unverified => match killed {
                Ok(Sent::Delivered) => ChildFate::Killed,
                _ => ChildFate::Running { id },
            },
        };
        #[cfg(unix)]
        match waited {
            Waited::Exited => {}
            Waited::Foreign | Waited::Unverified => {
                let cause = cause.map_or_else(String::new, |c| format!(" ({c})"));
                self.forget_noting(
                    &format!("was reaped by someone else, or cannot be shown to be ours{cause}"),
                    waited == Waited::Foreign,
                    why,
                );
            }
        }
        self.release();
        fate
    }

    /// Collects the exit status of a child [`wait_and_reap`](ProcSource::wait_and_reap) saw exit and
    /// showed ours, so that `Reaped` is said of a status that was collected: the wait only
    /// observes the exit, and tokio would otherwise collect it when the backend is released.
    pub(crate) fn collect_exit(&mut self, id: Option<ProcessId>) -> ChildFate {
        let ProcSource::Tokio { child, .. } = self else {
            unreachable!("only a tokio backend's wait answers `Exited`")
        };
        crate::child::spawn::fate_of_a_look(child.try_wait().map_err(|e| e.raw_os_error()), id)
    }

    /// [`reap_now`](ProcSource::reap_now) for an elevation front (see [`crate::elevation::front`]):
    /// it is sent nothing, and tokio's `Child` is forgotten, never handed to a reaper. The sync
    /// spawn's front teardown reaps it through its pidfd if it has already exited. **Invariant:** no
    /// `wait()` future for this child is in flight.
    #[cfg(target_os = "linux")]
    pub(crate) fn leave_front(
        self,
        pid: u32,
        front: crate::elevation::front::Front,
        id: Option<ProcessId>,
        subtree: Option<&crate::containment::cgroup::Subtree>,
    ) -> (crate::child::spawn::FrontFate, ChildFate) {
        self.leave_front_noting(pid, front, id, subtree, &mut Diagnosis::default())
    }

    /// [`leave_front`](ProcSource::leave_front) for a spawn whose identity check found `why`: the
    /// forget's one warn carries it.
    #[cfg(target_os = "linux")]
    pub(crate) fn leave_front_noting(
        mut self,
        pid: u32,
        front: crate::elevation::front::Front,
        id: Option<ProcessId>,
        subtree: Option<&crate::containment::cgroup::Subtree>,
        why: &mut Diagnosis,
    ) -> (crate::child::spawn::FrontFate, ChildFate) {
        // The forgets are owed to the one warn of the teardown below, not logged on their own.
        if let Some((_, state)) = self.elsewhere() {
            self.forget_deferring(&foreign_why(&state), shown_reaped_elsewhere(&state), why);
        }
        let ProcSource::Tokio { pidfd, .. } = &mut self else {
            // Only something that broke the reaping precondition (see `Command::contain`) leaves a
            // spawn's backend foreign this early.
            log::warn!(
                "{}",
                why.fold(format!(
                    "elevation front pid {pid}: its backend is foreign (reaped elsewhere), so it cannot be waited on"
                ))
            );
            debug_assert!(
                false,
                "elevation front pid {pid}: a spawn's backend is foreign before its teardown"
            );
            return (crate::child::spawn::FrontFate::Unaccounted, ChildFate::Unknown);
        };
        let pidfd = pidfd.take();
        self.forget_deferring(
            "is an elevation front, sent nothing, and handed to the pidfd teardown",
            false,
            why,
        );
        crate::child::spawn::leave_front_through_pidfd_noting(Some(pid), pidfd, front, id, subtree, why)
    }

    /// The teardown's kill: [`Sig::Kill`] through the handle, or (tests) the forced refusal of the
    /// sync seam's "leave it alive" form, which replaces the kill so the child is really left alone.
    fn teardown_kill(&self) -> Result<Sent, Error> {
        #[cfg(test)]
        if let Some((marker, kind, _)) = crate::child::spawn::fault::take_force_kill_failure() {
            return Err(Error::Io(std::io::Error::new(kind, marker)));
        }
        self.signal(Sig::Kill)
    }

    /// A child whose teardown kill was refused (a setuid child answers `EPERM`) and that is not
    /// shown reaped elsewhere: tokio's `Child` is forgotten, never dropped or released, because
    /// tokio would reap it later with `waitpid(pid)` from its orphan queue, when the number may
    /// name another process. The child goes to the same teardown the sync spawn uses, through its own
    /// pidfd, moved out of the backend: another kill, then a reap through the pidfd, or one non-blocking
    /// look and a background reap through the pidfd once it exits. Answers what the pidfd teardown
    /// did with it (`None` when the backend was already forgotten, so nothing is left to hand) and
    /// what the forget leaked, quietly: the caller's one warn carries it.
    #[cfg(target_os = "linux")]
    fn hand_to_pidfd_reaper(mut self, pid: u32, id: Option<ProcessId>) -> (Option<ChildFate>, Option<&'static str>) {
        let ProcSource::Tokio { pidfd, .. } = &mut self else {
            return (None, None);
        };
        // The original, moved out: a duplicate could fail at the fd limit and strand the child.
        let pidfd = pidfd.take();
        let leak = self.forget_quietly(false).map(|(_, leak)| leak);
        let fate = crate::child::spawn::teardown_through_pidfd(Some(pid), pidfd, id);
        (Some(fate), leak)
    }

    /// Linux teardown of a spawn whose identity check could not answer: kill the child through its
    /// pidfd, which pins it whatever any peek said, then reap it through the same pidfd, and forget
    /// tokio's `Child` (its drop would reap a pid that is already collected). Consumes the backend.
    /// A refused kill is handled as in [`reap_now`](ProcSource::reap_now): the child goes to the
    /// pidfd reaper. **Invariant:** no `wait()` future for this child is in flight.
    #[cfg(target_os = "linux")]
    ///
    /// `why`: what the spawn's identity check found, if that is why the child is torn down; the
    /// teardown's one warn carries it.
    pub(crate) fn teardown_through_pidfd(mut self, pid: u32, id: Option<ProcessId>, why: &mut Diagnosis) -> ChildFate {
        use crate::wait::exit_only::{self, Target};

        crate::bounded::assert_may_block("teardown_through_pidfd");
        let killed = self.teardown_kill();
        if let Err(e) = &killed {
            let foreign = self.forget_if_foreign_quietly(id);
            let (handed, hand_leak) = self.hand_to_pidfd_reaper(pid, id);
            log::warn!(
                "{}",
                why.fold(refused_kill_warning(
                    pid,
                    e,
                    handed.is_some(),
                    foreign.as_ref().map(|f| f.1.as_str()),
                    foreign.as_ref().map(|f| f.0).or(hand_leak)
                ))
            );
            debug_assert!(
                matches!(&e, Error::Io(io) if io.kind() == std::io::ErrorKind::PermissionDenied),
                "the teardown kill of an owned child failed: {e}"
            );
            return after_refused_kill(handed, foreign.map(|f| f.2), id);
        }
        let ProcSource::Tokio { pidfd, .. } = &self else {
            unreachable!("a freshly spawned backend is a tokio child");
        };
        let mut failed = None;
        let fate = match exit_only::reap_blocking(&Target::PidFd(std::os::fd::AsFd::as_fd(pidfd))) {
            Ok(Ok(_reaped)) => {
                #[cfg(test)]
                if let exit_only::Reaped::Status(status) = _reaped {
                    crate::child::spawn::fault::record_teardown_reap(pid, status);
                }
                ChildFate::Reaped
            }
            Ok(Err(foreign)) => {
                log::debug!("child {pid} was reaped by someone else during its teardown");
                foreign.fate(matches!(killed, Ok(Sent::Delivered)))
            }
            Err(e) => {
                failed = Some(e);
                ChildFate::Killed
            }
        };
        // One warn: the failed reap, if there was one, and the leak of the forget.
        match &failed {
            Some(e) => self.forget_noting(&format!("could not be reaped through its pidfd ({e})"), false, why),
            None => self.forget_foreign_noting(why),
        };
        debug_assert!(failed.is_none(), "waitid on a child's own pidfd failed: {failed:?}");
        fate
    }

    /// Install the per-instance test wait observer (raw backend only). Panics on a Tokio child —
    /// the observer seam exists solely for the raw async wait path.
    #[cfg(all(test, windows))]
    pub(crate) fn install_wait_observer(
        &mut self,
        started: ::tokio::sync::oneshot::Sender<()>,
        outcome: ::tokio::sync::oneshot::Sender<crate::child::spawn::windows_raw::WaitOutcome>,
    ) {
        match self {
            ProcSource::Raw(r) => r.set_observer(started, outcome),
            ProcSource::Tokio { .. } => panic!("wait observer requires the raw CreateProcessW backend"),
        }
    }
}

/// What became of a child whose teardown kill was refused (a setuid child answers `EPERM`): the pidfd
/// reaper's answer if it was handed one (`handed`, Linux), else the forgetting's (`forgotten`, a child
/// not shown to be ours), else it was released to tokio's orphan queue, still running. `id` is its
/// identity, if the spawn had read one.
fn after_refused_kill(handed: Option<ChildFate>, forgotten: Option<ChildFate>, id: Option<ProcessId>) -> ChildFate {
    if let Some(fate) = handed.or(forgotten) {
        return fate;
    }
    // Linux hands every child it does not forget to the pidfd reaper.
    #[cfg(target_os = "linux")]
    debug_assert!(
        false,
        "a refused teardown kill left a child neither handed to the pidfd reaper nor forgotten"
    );
    ChildFate::Running { id }
}

/// Whether tokio still holds the child, so its pid is pinned. Once tokio is `Done` (a prior
/// `wait()` reaped it) the pid may be recycled and nothing may wait on it.
fn still_ours(child: &::tokio::process::Child) -> bool {
    let ours = child.id().is_some();
    debug_assert!(
        ours,
        "wait_and_reap found an already-reaped child where one was impossible"
    );
    ours
}

/// Linux: waits until the exit is visible to this process, through the child's own pidfd. What it
/// finds that is not an exit is logged at `level` and returned as the cause.
#[cfg(target_os = "linux")]
fn wait_on_pidfd(pid: u32, pidfd: &std::os::fd::OwnedFd, level: log::Level) -> (Waited, Option<String>) {
    use std::os::fd::AsFd;

    use crate::wait::exit_only::{self, Peek, Target};

    match exit_only::wait_visible_exit(&Target::PidFd(pidfd.as_fd())) {
        Ok(Peek::Exit(_reaped)) => {
            #[cfg(test)]
            if let exit_only::Reaped::Status(status) = _reaped {
                crate::child::spawn::fault::record_teardown_reap(pid, status);
            }
            (Waited::Exited, None)
        }
        Ok(Peek::Foreign(_)) => (
            Waited::Foreign,
            Some("waitid on its pidfd found it reaped by someone else (ECHILD)".to_owned()),
        ),
        // A blocking wait that returns without an exit is a contract breach, like an errno that
        // is not `ECHILD`. Without proof the child is ours, tokio's by-pid reap must not run.
        Ok(Peek::Running) => {
            log::log!(
                level,
                "wait_and_reap: waitid on child {pid}'s pidfd returned without an exit"
            );
            debug_assert!(false, "a blocking waitid on a pidfd returned without an exit");
            (
                Waited::Unverified,
                Some("waitid on its pidfd returned without an exit".to_owned()),
            )
        }
        Err(e) => {
            log::log!(level, "wait_and_reap: waitid on child {pid}'s pidfd failed: {e}");
            debug_assert!(false, "waitid on a child's own pidfd failed: {e}");
            (Waited::Unverified, Some(format!("waitid on its pidfd failed: {e}")))
        }
    }
}

/// macOS: waits, through the same verified-id wait the sync child uses, until the child is a zombie
/// this process can reap. It never reaps: tokio's field-drop does. A child a tracer holds answers
/// `ECHILD` to `waitid` and is still running, so the wait goes on until the tracer hands it back.
/// A foreign reap is [`Waited::Foreign`]; anything else that cannot be shown to be ours is
/// [`Waited::Unverified`] (see [`ProcSource::wait_and_reap`]), logged at `level` and returned as the
/// cause.
#[cfg(target_os = "macos")]
fn wait_reapable(pid: u32, identity: u64, level: log::Level) -> (Waited, Option<String>) {
    use crate::wait::backend::{await_reapable, Waited as Awaited};
    match await_reapable(pid, Some(identity), None) {
        Ok(Awaited::Reapable) => {
            #[cfg(test)]
            if let Ok(crate::wait::exit_only::Peek::Exit(crate::wait::exit_only::Reaped::Status(status))) =
                crate::wait::exit_only::peek(&crate::wait::exit_only::Target::pid(pid, Some(identity)))
            {
                crate::child::spawn::fault::record_teardown_reap(pid, status);
            }
            (Waited::Exited, None)
        }
        Ok(Awaited::Gone) => (
            Waited::Foreign,
            Some("its pid is gone, or names another process".to_owned()),
        ),
        // Exited, and not ours to reap, like a foreign reap.
        Ok(Awaited::Orphaned) => {
            log::log!(
                level,
                "wait_and_reap: child {pid} is not ours to reap (launchd holds its zombie, because its tracer died)"
            );
            (Waited::Foreign, Some(crate::signal::UNPINNED_WHY.to_owned()))
        }
        // Unbounded, so the deadline cannot pass: a contract breach.
        Ok(Awaited::DeadlinePassed) => {
            log::log!(
                level,
                "wait_and_reap: the unbounded wait on child {pid} reported a passed deadline"
            );
            debug_assert!(false, "an unbounded wait reported a passed deadline");
            (
                Waited::Unverified,
                Some("the unbounded wait reported a passed deadline".to_owned()),
            )
        }
        // Without proof the child is ours, tokio's by-pid reap must not run.
        Err(e) => {
            log::log!(level, "wait_and_reap: waiting on child {pid} failed: {e}");
            (Waited::Unverified, Some(format!("waiting on it failed: {e}")))
        }
    }
}

/// Windows: waits on tokio's process handle, which pins the child.
#[cfg(windows)]
fn wait_on_handle(child: &::tokio::process::Child, pid: u32) -> Waited {
    use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
    use windows::Win32::System::Threading::{WaitForSingleObject, INFINITE};
    let _ = pid;
    let h = child.raw_handle().expect("tokio owns the handle while id() is Some");
    // SAFETY: tokio owns and (on its field-drop) closes the handle; we only wait on it.
    // INFINITE is bounded by the kill the caller already issued.
    let waited = unsafe { WaitForSingleObject(HANDLE(h), INFINITE) };
    debug_assert!(
        waited == WAIT_OBJECT_0,
        "wait_and_reap did not observe the child's exit: {waited:?}"
    );
    if waited != WAIT_OBJECT_0 {
        log::warn!("wait_and_reap: the wait on child {pid}'s handle failed: {waited:?}");
        return Waited::Unverified;
    }
    #[cfg(test)]
    {
        use std::os::windows::process::ExitStatusExt as _;
        let mut code = 0u32;
        // SAFETY: `h` is tokio's live process handle and `code` a valid out-parameter.
        unsafe { windows::Win32::System::Threading::GetExitCodeProcess(HANDLE(h), &mut code) }
            .expect("GetExitCodeProcess on an exited child");
        crate::child::spawn::fault::record_teardown_reap(pid, std::process::ExitStatus::from_raw(code));
    }
    Waited::Exited
}

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