cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
//! Identity-aware process-tree teardown — the cross-platform mechanism, used
//! both when requested directly (`ContainMode::TreeWalk`) and as the terminal
//! fallback on Windows, where a job-assign failure falls back to it for `ContainMode::BestEffort`
//! only; `ContainMode::Strongest` fails the spawn.
//!
//! Unlike a kernel container, this mechanism has no enforced membership: at
//! teardown it takes a `(pid, ppid)` snapshot of the host, walks the ppid chain
//! down from the root, and kills each *genuine* descendant by identity. It is
//! best-effort and reports as [`crate::containment::Containment::TreeWalk`]: it
//! misses reparented orphans (a child whose parent exited before the walk read the
//! child, so its ppid no longer chains to the root), a descendant whose parent exits while the walk
//! runs, the root included, with its subtree (see the parent read below), and broker-spawned escapes. On Windows it also
//! misses a genuine descendant whose creator exited and whose creator's pid now belongs to a later
//! in-tree process, with its subtree (see the parent-order rule below).
//!
//! # The PID-reuse / stale-ppid defense
//!
//! A `(pid, ppid)` snapshot is racy: a candidate's `pid` may have been recycled, or its `ppid` may
//! name a *recycled* pid. So a chained ppid alone does not prove descent: each candidate is read
//! again, under the parent the walk accepted for it (see the parent read below).
//!
//! The walk cannot defend a root whose own pid was recycled: the new owner's children read as
//! genuine. So it takes its snapshot first, then proves the root still holds its pid ([`anchor`]); a
//! root that does not walks nothing. A root that is gone walks nothing; one that exists but cannot
//! be read is an error (`Error::Unassessable`), never an empty walk.
//!
//! - **Linux/macOS** reparent orphans to pid 1 / launchd, so a process whose ppid, read after its
//!   parent was proved, still equals the parent's pid genuinely descends from it: ppid is
//!   *authoritative*, and no order rule applies. One would drop a child whose in-tree tracer started
//!   after it (XNU's `PT_ATTACH` makes the tracer the parent), or one older than the root that an
//!   in-tree debugger attached to. The root is only proved: one gone between the snapshot and the
//!   proof walks nothing, which loses no one, because its children are reparented at its exit and no
//!   longer descend from it.
//! - **Windows** never reparents, and the parent field is the *creator*, which survives its
//!   creator's exit and can name a pid a later process holds. So the proof of the root and its
//!   [`OrderKey`] (the process sequence number, a creation counter) are one read on one handle: a root
//!   that exits cannot be proved and then found gone with its unreparented children unwalked. The
//!   order key is then the bound of the rule below.
//!
//! # A root that has exited (Unix)
//!
//! The kernel reparents a process's children at its exit, so a walk from the pid of a root whose exit has
//! begun may find none of them or only some, and an empty walk says nothing of the tree. Whether the exit
//! has begun is the kernel's exit flag, read after every walk and before the root is signalled (cosca's
//! own signal would begin its exit), through the `/proc` view the walk's own snapshot was read through
//! ([`Table`]). The flag shows before the exit reparents the children and never clears, so a root that
//! shows it clear after the walk's last read had no child moved by its exit. Linux: every thread of the
//! group shows `PF_EXITING` (the leader alone is no sign, for `pthread_exit` sets it while the process
//! runs). macOS: `P_WEXIT` in `kinfo_proc`'s `p_flag`; where macOS 14's order differs the exit goes
//! unseen, which is the race of any parent below the root (see the parent read below). Windows never
//! reparents; nothing changes there.
//!
//! A kill or [`terminate`] whose root's exit had begun when its walk ended, or whose flag could not be
//! read, never answers `Ok`:
//!
//! - **No member found:** [`TreeKillOutcome::NoRoot`] and [`Terminated::RootExited`], nothing sent. With
//!   the flag unreadable, [`TreeKillOutcome::Unwalked`] (a [`terminate`]'s `Err`): nothing is sent, and a
//!   retry can read it.
//! - **Members found:** they are killed or signalled all the same. A [`hard_kill`] that left nothing is
//!   [`TreeKillOutcome::RootExiting`], settled as a gone root is (a graceful call's own complete
//!   `SIGTERM` listing may vouch for the tree, as it does a moment later, when the root is a zombie); one
//!   that left anything (a member, a candidate it could not read, the root's own kill) adds an
//!   [`Error::Unassessable`] that names no member. A [`terminate`]'s [`Listing`] is not complete.
//! - **Flag unreadable, members found:** a [`hard_kill`] that left nothing else is
//!   [`TreeKillOutcome::ExitUnread`], not a member seen running; one that left something holds the read's
//!   error in its [`Unkilled`]. A [`terminate`]'s [`Listing`] is not complete.
//!
//! Members a [`terminate`] walk reached while the root ran are held by identity (`TreeKilled::hold`).
//!
//! # The parent-order rule (Windows only)
//!
//! Where the parent field is the creator ([`ORDER_AFTER_PARENT`]), a candidate is kept only if its
//! key orders strictly after its accepted parent's, the root's for a root's child. An impostor — a
//! *stale ppid* pointing at a *recycled* pid — was created before the pid's later holder, so it
//! orders before it and is dropped. Keys are unique (one per process creation) and a process's
//! exceeds its creator's, so the strict rule loses no genuine child. [`children_of_with`] needs no
//! switch: its parent is the anchor. `ProcessId::parent` follows the same const.
//!
//! [`ORDER_AFTER_PARENT`]: crate::identity::ORDER_AFTER_PARENT
//!
//! The rule also drops a genuine descendant whose creator exited and whose creator's pid now belongs
//! to a later in-tree process, with its subtree: from the snapshot alone it cannot be told from a
//! stale-creator impostor.
//!
//! # The parent read (every platform)
//!
//! A snapshot row's ppid is only a number. The resolver reads the candidate again, and its parent
//! number and id (on Windows, also the order key) all come from that one read, so they describe the
//! same process. A candidate whose parent number is not the accepted parent's pid is dropped, and so is one whose accepted
//! parent no longer holds that pid when the read is done. So a descendant whose parent exits while
//! the walk runs is dropped with its subtree: Linux and macOS reparent it, so its record names its
//! new parent; Windows never updates the creator pid, which still names the dead parent, and the
//! read cannot tell that from a pid that changed hands. On Windows a candidate whose key does not
//! follow the bound (above) is dropped as `Gone` in the same read, before the parent is proved: a
//! process that cannot be the child is not a member the walk failed to assess. A candidate whose own
//! read fails (no record, on Windows no sequence number, or a parent number that cannot be read) goes to the proof of the accepted parent
//! first: a parent that is gone drops it quietly, as `Gone`; one that cannot be proved drops it with
//! an error naming `ppid N`; and only a held parent lets its own failure stand, an error naming the
//! candidate (on Windows, with the refused query's `NTSTATUS`, as a Win32 code, for its source).
//!
//! # A walk that could not assess a member
//!
//! Both of those drops are a candidate the walk could not assess, unlike a `Gone` one, which is
//! not a member and is dropped silently. The walk returns them in [`Walk::unassessed`] beside its
//! members, so no caller takes a short list for the whole tree: [`hard_kill`] returns each as a
//! member left behind, the fd marker's sweep reports itself incomplete, and `ProcessId::children`
//! is an error ([`Walk::complete_members`]). The walk logs nothing: its caller reports, once. A
//! caller with no error to return for them says each ([`warn_unassessed`]).
//!
//! A process the walk cannot read is not a member only when the listing's order shows it. On Windows
//! that includes a process it cannot open (one the caller may not query), whose creator pid is never
//! updated and whose parent number and key cannot be read. The listing ([`process_parents`]) is in
//! process-list insertion order, so a candidate listed before an anchor row (a process already listed
//! before the parent could create anything; see [`Anchors`]) is not the parent's child. A candidate
//! with no anchor row after it stays an error: every walk from that root is incomplete for as long as
//! it lives. Only a walk is affected: a Job Object holds its members by membership and never walks.
//!
//! [`process_parents`]: crate::containment::enumerate::process_parents

use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
use crate::containment::drain_edge::DrainEdge;
use crate::containment::enumerate::Table;
#[cfg(unix)]
use crate::containment::mechanism::Release;
use crate::containment::mechanism::{Contains, KillLeftOutcome};
#[cfg(target_os = "macos")]
use crate::containment::Why;
use crate::containment::{Containment, Root, Skip, TerminateOutcome, TreeKill};
use crate::error::Error;
use crate::identity::Resolved;
use crate::identity::{resolution_of, Kernel, OrderKey, ProcessId, RawPid, Resolution};
use crate::os_process::OsProcess;
#[cfg(unix)]
use crate::signal::RootState;
use crate::signal::{Sent, Sig};
use crate::Recursive;
use std::sync::Arc;

/// A tree named by parentage: the root's identity, from which its descendants are enumerated and
/// killed by identity at teardown ([`kill_tree`], [`terminate_tree`]).
#[derive(Debug)]
pub(crate) struct Walker {
    root: ProcessId,
}

impl Walker {
    pub(crate) fn new(root: ProcessId) -> Walker {
        Walker { root }
    }

    /// The root the walk starts from.
    #[cfg(all(test, unix))]
    pub(crate) fn root(&self) -> ProcessId {
        self.root
    }
}

impl Contains for Walker {
    fn kill(&self, root: Option<&dyn crate::containment::Root>) -> TreeKill<'_> {
        kill_tree(self.root, root)
    }

    fn root_left(&self, root: Error) -> Error {
        Error::members_left(crate::error::Failures::new(Arc::new(root), []), None)
    }

    /// Kills again the members an earlier kill left ([`with_earlier`]), and holds the ones this one
    /// leaves.
    fn kill_left(&self, result: Result<(), Unkilled>, left: Vec<Left>) -> KillLeftOutcome {
        let (merged, killed) = with_earlier(&crate::identity::HostKernel, left, result);
        let left_now = match &merged {
            Ok(()) => Vec::new(),
            Err(left) => Left::of(left),
        };
        KillLeftOutcome {
            result: merged,
            left: left_now,
            killed,
        }
    }

    fn send_terminate(
        &self,
        _pid: u32,
        root: Option<&dyn crate::containment::Root>,
    ) -> (TerminateOutcome, Option<Listing>) {
        terminate_tree(&crate::identity::HostKernel, self.root, root)
    }

    /// No kernel object says "every member has exited".
    fn drain_edge(&self) -> Option<DrainEdge<'_>> {
        None
    }

    fn kind(&self) -> Containment {
        Containment::TreeWalk
    }

    /// There is no kernel resource whose drop kills.
    fn disarm(&self) -> std::io::Result<()> {
        Ok(())
    }

    #[cfg(unix)]
    fn subject(&self) -> String {
        format!("TreeWalk({:?})", self.root)
    }

    /// A signal to a walked member is subject to the kernel's permission check, as the child's own
    /// kill is.
    #[cfg(unix)]
    fn would_reach(&self, _pid: u32, _pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> Result<bool, crate::error::Error> {
        Ok(false)
    }

    #[cfg(unix)]
    fn reached(&self, _child: &crate::child::owned::OwnedChild) -> Result<bool, crate::error::Error> {
        Ok(false)
    }

    #[cfg(unix)]
    fn release(self) -> (Release, Option<Walker>) {
        (Release::nothing(), Some(self))
    }

    #[cfg(all(feature = "tokio", target_os = "linux"))]
    fn awaitable_release(&self) -> Option<crate::containment::mechanism::AwaitableRelease<'_>> {
        None
    }
}

/// What one identity-verified kill attempt achieved. `AlreadyGone` and `NotAttempted` are
/// both "no signal was delivered", but only the first means there was nothing to deliver one
/// to.
#[derive(Debug)]
pub(crate) enum KillOutcome {
    /// The signal reached the verified identity.
    Terminated,
    /// The pid holds no process, or holds a different one - nothing to kill.
    AlreadyGone,
    /// A live-or-unassessable process we did not signal, with why. The only outcome that can leave a
    /// process running. Warns of nothing: the caller that reports it ([`hard_kill`]) or cannot
    /// ([`warn_if_not_attempted`]) says it.
    NotAttempted(Error),
}

impl KillOutcome {
    /// What `sent`, the answer of the one send to a process held by identity, achieved. The one
    /// reading of a send's answer for every per-member send of a walk and of a group's resend. A
    /// refusal is the OS's own error, as `Process::kill` gives it. Already gone (`ESRCH`, or exited
    /// when the call came) is success. [`Sent::Unverified`] is a contract breach, asserted in debug:
    /// every handle a send goes through (a member's opened by identity, a child's, which always holds
    /// the unique id it sends with) verifies its target. Release reads it as nothing sent to a
    /// process that may be running.
    pub(crate) fn of(sent: Result<Sent, Error>) -> KillOutcome {
        match sent {
            Ok(Sent::Delivered) => KillOutcome::Terminated,
            Ok(Sent::Gone) => KillOutcome::AlreadyGone,
            Ok(Sent::Unverified) => {
                debug_assert!(false, "a walk's send cannot be unverified");
                KillOutcome::NotAttempted(Error::Unassessable {
                    detail: "it could not be verified".to_owned(),
                    source: None,
                })
            }
            Err(refused) => KillOutcome::NotAttempted(refused),
        }
    }
}

/// Warn of a best-effort kill of `id` with `signal` that sent nothing to a process that may be
/// running, for a caller that returns no error for it ([`terminate`], the fd marker's sweep).
#[cfg(unix)]
pub(crate) fn warn_if_not_attempted(id: ProcessId, signal: Signal, outcome: &KillOutcome) {
    if let KillOutcome::NotAttempted(why) = outcome {
        log::warn!(
            "treewalk: pid {} was sent no {signal}: {report}",
            id.pid(),
            report = crate::error::Report(why)
        );
    }
}

/// What a walk found: the genuine members, and the candidates it could not assess.
///
/// A candidate whose identity could not be read stays out of `members` (the walk cannot kill what it
/// cannot verify), and so does its subtree, which the walk cannot reach through it. It is counted in
/// `unassessed`, so a caller never takes a short `members` for the whole tree. A candidate that is
/// gone is in neither.
#[derive(Debug, Default)]
pub(crate) struct Walk {
    pub(crate) members: Vec<ProcessId>,
    /// Each candidate dropped for an `Unknown` read, with why ([`unqueryable_read`](crate::identity::unqueryable_read)):
    /// the candidate's own failure, or the proof of the parent it was read under.
    pub(crate) unassessed: Vec<(RawPid, Error)>,
}

impl Walk {
    /// The members, for a query that must not take a short list for the tree: `Err` when the walk
    /// could not assess a candidate, the first one's error, with each other's whole error below its
    /// variant ([`Error::with_peers`]), or below an `Unassessable` when the first is an [`Error::Io`],
    /// which has no slot for them. It logs nothing; the caller decides.
    pub(crate) fn complete_members(self) -> Result<Vec<ProcessId>, Error> {
        let Walk { members, unassessed } = self;
        let mut unassessed = unassessed.into_iter();
        let Some((_, first)) = unassessed.next() else {
            return Ok(members);
        };
        Err(first.with_peers_or_unassessable(
            || "the walk could not assess every candidate".to_owned(),
            None,
            unassessed.map(|(_, why)| Arc::new(why)),
        ))
    }
}

/// Warn of each candidate in `unassessed` the walk could not read, for a caller with no error to
/// return for them (`terminate`, the fd marker's sweep). The others report theirs in the error
/// ([`hard_kill`], `ProcessId::children`), so a member is reported once.
#[cfg(unix)]
pub(crate) fn warn_unassessed(unassessed: &[(RawPid, Error)]) {
    for (pid, why) in unassessed {
        log::warn!(
            "treewalk: pid {pid} dropped from the walk ({report})",
            report = crate::error::Report(why)
        );
    }
}

/// The tree-walk resolver. Denied is returned as `Err` (counted in [`Walk::unassessed`], which the
/// walk's caller reports); gone is `Ok(None)`.
///
/// `parent` is the process the walk accepted as the parent the snapshot gave `pid`. Where the read of
/// `pid` carries its parent, a candidate
/// is dropped when its parent's number is another now, which means the pid changed hands since the
/// snapshot or the same process was orphaned and is no longer in the tree; and when its parent's
/// number no longer holds `parent`, which means the parent was reaped and its number taken by a
/// process whose own children the candidate could be. `bound` is the order key the candidate must
/// follow ([`ProcessId::of_ordered_with`]), given only where the platform orders by it: one that
/// does not is dropped as gone, before `parent` is proved.
pub(crate) fn resolve_or_drop(
    kernel: &dyn Kernel,
    pid: RawPid,
    parent: ProcessId,
    bound: Option<OrderKey>,
) -> Resolution {
    resolution_of(
        "pid",
        pid,
        ProcessId::of_ordered_with(kernel, pid, Some(parent), None, bound),
    )
}

#[cfg(unix)]
use nix::sys::signal::Signal;

/// Pure descendant filter (host-testable on every OS). Walks `parents` down from
/// `root`, and for each pid whose ppid chains to `root.pid()` resolves its
/// identity via `resolve(pid, parent, bound)`, `parent` being the accepted process whose pid the
/// edge names, and `bound` the order key the candidate must follow (see module docs): the accepted
/// parent's, which only Windows gives (`root_bound` for the root's children, and the `Option<OrderKey>`
/// each resolution carries for the rest). The resolver answers `Ok(None)` for a candidate that does
/// not follow it. `resolve` is injected so the filter is pure: live code passes [`resolve_or_drop`],
/// tests pass a stub. A candidate the resolver errs on is dropped with its subtree and listed once in
/// [`Walk::unassessed`], unless the listing's order shows it was created before its parent
/// ([`Anchors::list_before`]; `reads` are its reads, injected like `resolve`):
/// then it is not a member, and dropped as gone.
///
/// The root itself is never included (callers kill the root explicitly first).
pub(crate) fn descendants_with(
    root: ProcessId,
    root_bound: Option<OrderKey>,
    parents: &[(RawPid, RawPid)],
    resolve: impl Fn(RawPid, ProcessId, Option<OrderKey>) -> Resolution,
    reads: &AnchorReads<'_>,
) -> Walk {
    // BFS over the ppid forest. `frontier` holds the accepted pids whose children we still
    // need to visit, each with the bound its children follow; it starts as just the root. A pid joins
    // the result (and the next frontier) only if its ppid is in the current accepted set AND the
    // resolver finds it ordered after the bound. No fixed iteration cap: the loop drains a
    // strictly shrinking set of not-yet-visited edges.
    let mut walk = Walk::default();
    let mut frontier: Vec<(ProcessId, Option<OrderKey>)> = vec![(root, root_bound)];
    // The rows of the remaining (pid, ppid) edges not yet attached to the tree.
    let mut pending: Vec<usize> = (0..parents.len()).collect();
    // Pids already accepted, so a duplicate edge (e.g. a snapshot that lists a
    // pid twice) never enumerates/kills the same process twice.
    let mut accepted: std::collections::HashSet<RawPid> = std::collections::HashSet::new();
    // Memoize identity resolution per pid so `resolve(pid)` runs at most once per
    // pid even when an edge is re-examined across frontier iterations or a pid
    // appears in multiple edges; identity is stable for the duration of the walk.
    let mut resolved: std::collections::HashMap<RawPid, Option<(ProcessId, Option<OrderKey>)>> =
        std::collections::HashMap::new();
    // Each parent's anchor rows, looked up at the first of its candidates that cannot be read.
    let mut anchors: std::collections::HashMap<RawPid, Anchors<'_>> = std::collections::HashMap::new();

    while !frontier.is_empty() {
        let mut next: Vec<(ProcessId, Option<OrderKey>)> = Vec::new();
        // Partition: edges whose ppid is in the current frontier are candidates.
        let mut still_pending: Vec<usize> = Vec::with_capacity(pending.len());
        for row in pending.drain(..) {
            let (pid, ppid) = parents[row];
            let Some(&(parent, bound)) = frontier.iter().find(|(p, _)| p.pid() == ppid) else {
                still_pending.push(row);
                continue;
            };
            // A process is never its own parent; guard against a degenerate
            // pid == ppid self-loop that would otherwise spin the BFS.
            if pid == ppid {
                continue;
            }
            let read = *resolved
                .entry(pid)
                .or_insert_with(|| match resolve(pid, parent, bound) {
                    Ok(None) => {
                        log::debug!(
                        "treewalk: pid {pid} gone, or an impostor (recycled pid / stale ppid) - dropping its subtree"
                    );
                        None
                    }
                    Ok(read) => read,
                    Err(why) => {
                        let anchors = anchors
                            .entry(parent.pid())
                            .or_insert_with(|| Anchors::new(parents, parent, bound, reads));
                        if anchors.list_before(row) {
                            log::debug!(
                                "treewalk: pid {pid} unreadable, and listed before an anchor row - not its child"
                            );
                        } else {
                            // Reported by the walk's caller, from the list.
                            walk.unassessed.push((pid, why));
                        }
                        None
                    }
                });
            let Some((id, children_bound)) = read else {
                continue;
            };
            // `accepted.insert` dedups so a duplicate edge never enumerates/kills the
            // same process twice.
            if accepted.insert(pid) {
                walk.members.push(id);
                next.push((id, children_bound));
            }
        }
        pending = still_pending;
        frontier = next;
    }

    walk
}

/// `anchor`, proved to hold its pid for a walk from it, and the bound its children follow
/// ([`ProcessId::anchor_bound_with`]): the proof is read after the snapshot, so a walk takes its
/// edges from the snapshot only for a root that held the pid throughout. [`walk_from`] is its only
/// caller.
///
/// # Errors
///
/// `Ok(None)` when `anchor` is gone or another process holds its pid now (logged at `debug`):
/// there is nothing to walk. [`Error::Unassessable`] (or `Unsupported`) when that cannot be told:
/// an empty walk there would let a caller kill the anchor and leave its descendants running.
fn anchor(kernel: &dyn Kernel, anchor: ProcessId) -> Result<Option<AnchorProof>, Error> {
    let proof = resolution_of("pid", anchor.pid(), anchor.anchor_bound_with(kernel))?;
    if proof.is_none() {
        log::debug!("treewalk: pid {pid} is gone - walking nothing", pid = anchor.pid());
    }
    Ok(proof.map(|bound| AnchorProof { bound }))
}

/// A walk's anchor, proved to hold its pid: the bound its children follow (see
/// [`ProcessId::anchor_bound_with`]).
struct AnchorProof {
    bound: Option<OrderKey>,
}

/// Pure one-level child filter (host-testable): keep each pid whose ppid == the parent's
/// pid and which the resolver finds ordered after `parent_bound`: `resolve(pid, parent, bound)` is
/// injected for purity, with `parent_bound` as the bound. The parent itself is never included. A pid
/// the resolver errs on is listed once in [`Walk::unassessed`], unless [`Anchors::list_before`] (by
/// `reads`) shows it is not the parent's child.
pub(crate) fn children_of_with(
    parent: ProcessId,
    parent_bound: Option<OrderKey>,
    parents: &[(RawPid, RawPid)],
    resolve: impl Fn(RawPid, ProcessId, Option<OrderKey>) -> Resolution,
    reads: &AnchorReads<'_>,
) -> Walk {
    let mut walk = Walk::default();
    let anchors = Anchors::new(parents, parent, parent_bound, reads);
    // Each pid is resolved once, so a duplicate edge cannot list a pid twice or be read differently.
    let mut resolved = std::collections::HashSet::new();
    for (row, &(pid, ppid)) in parents.iter().enumerate() {
        if ppid != parent.pid() || pid == ppid || !resolved.insert(pid) {
            continue;
        }
        match resolve(pid, parent, parent_bound) {
            Ok(Some((id, _))) => walk.members.push(id),
            Ok(None) => {
                log::debug!(
                    "treewalk: pid {pid} gone, or an impostor (recycled pid / stale ppid) - dropped from children"
                );
            }
            Err(_) if anchors.list_before(row) => {
                log::debug!("treewalk: pid {pid} unreadable, and listed before an anchor row - not its child");
            }
            Err(why) => walk.unassessed.push((pid, why)),
        }
    }
    walk
}

/// The two live reads [`Anchors`] makes: `key_of` the order key of the process that holds a pid now
/// (`None`: it cannot be opened, or is gone), `creator_of` the creator pid on a parent's own handle.
/// Injected like `resolve`, so the filters stay pure.
pub(crate) struct AnchorReads<'a> {
    pub(crate) key_of: &'a dyn Fn(RawPid) -> Option<OrderKey>,
    pub(crate) creator_of: &'a dyn Fn(ProcessId) -> Option<RawPid>,
}

/// The rows of the listing `parents` that stand for processes in the list before `parent` could
/// create anything, and so tell where a candidate it could not read was listed: a candidate listed
/// before such a row entered the list before the parent existed, so it is not the parent's child.
/// This rests on the listing being in process-list insertion order, between unrelated processes too
/// (the candidate is unrelated to the anchor): measured as no inversion in millions of row pairs on
/// Windows 11 and both CI images, and pinned by `windows_tests`. Windows only, where `bound` is the
/// parent's key: elsewhere no row is an anchor.
///
/// An anchor row is one of:
///
/// - the row of the parent's pid (the parent, or an earlier holder of its pid);
/// - the row of a creator `X` shown to be one: some `Y` whose key, read now, is no later than the
///   parent's names `X` as its creator (`Y`'s ppid in the listing; for the parent itself, `creator_of`,
///   its handle's creator pid), and `X`'s key, read now, precedes `Y`'s. `X` held its pid from before
///   `Y` was created until now, so it was in the list before `Y` was allocated, hence before the
///   parent. A pid that changed hands since then reads a newer key, so it only keeps the error.
///
/// A candidate with no anchor row after it stays an error, for the parent may have been created
/// between it and the rows after it (the parent has no row of its own once it exited and its handle
/// is held).
struct Anchors<'a> {
    parents: &'a [(RawPid, RawPid)],
    parent: ProcessId,
    bound: Option<OrderKey>,
    reads: &'a AnchorReads<'a>,
    /// The last anchor row, found at the first use: one pass for all of the parent's candidates.
    last: std::cell::OnceCell<Option<usize>>,
}

impl<'a> Anchors<'a> {
    fn new(
        parents: &'a [(RawPid, RawPid)],
        parent: ProcessId,
        bound: Option<OrderKey>,
        reads: &'a AnchorReads<'a>,
    ) -> Anchors<'a> {
        Anchors {
            parents,
            parent,
            bound,
            reads,
            last: std::cell::OnceCell::new(),
        }
    }

    /// Whether the candidate listed at `parents[row]` is listed before an anchor row.
    fn list_before(&self, row: usize) -> bool {
        self.last.get_or_init(|| self.last_row()).is_some_and(|last| row < last)
    }

    /// The row of the last anchor.
    fn last_row(&self) -> Option<usize> {
        use std::collections::HashMap;

        let bound = self.bound?;
        // A pid's anchor row is its first, so a pid the listing names twice is not read twice.
        let mut first_row: HashMap<RawPid, usize> = HashMap::new();
        let mut made_by: HashMap<RawPid, Vec<RawPid>> = HashMap::new();
        for (row, &(pid, creator)) in self.parents.iter().enumerate() {
            first_row.entry(pid).or_insert(row);
            if pid != creator {
                made_by.entry(creator).or_default().push(pid);
            }
        }
        let parents_creator = (self.reads.creator_of)(self.parent);
        let mut keys: HashMap<RawPid, Option<OrderKey>> = HashMap::new();
        let mut key = |pid| *keys.entry(pid).or_insert_with(|| (self.reads.key_of)(pid));

        for (row, &(pid, _)) in self.parents.iter().enumerate().rev() {
            if first_row[&pid] != row {
                continue;
            }
            if pid == self.parent.pid() {
                return Some(row);
            }
            let made = made_by.get(&pid).map(Vec::as_slice).unwrap_or_default();
            if parents_creator != Some(pid) && made.is_empty() {
                continue;
            }
            let Some(creator_key) = key(pid) else {
                continue;
            };
            let names_it = (parents_creator == Some(pid) && creator_key < bound)
                || made
                    .iter()
                    .any(|&made| key(made).is_some_and(|made| creator_key < made && made <= bound));
            if names_it {
                return Some(row);
            }
        }
        None
    }
}

/// The walk from `root` over `parents`, a snapshot taken BEFORE this call: the one entry to the
/// live walks. `depth` is `Recursive::No` for `root`'s direct children, `Yes` for its whole subtree:
/// the pure filters wired to [`resolve_or_drop`].
///
/// The anchor rule is here, so no caller can walk from a root it has not proved: `root` is proved
/// to hold its pid now ([`anchor`]), and `Ok(None)` means it is gone or another process holds its
/// pid, so there is nothing to walk.
///
/// # Errors
///
/// [`Error::Unassessable`] (or `Unsupported`) when the anchor cannot be proved.
///
/// `root` needs no row in `parents`: the walk reads only the rows that name it as their parent, and
/// a missing row of `root` says nothing about those. Toolhelp, for one, drops the row of an exited
/// process whose handle is held (at once, or a moment after its exit), though its children, which
/// Windows does not reparent, run on. The candidates of such a root that cannot be read are placed
/// by the anchor rows instead, one of which is its creator's row, named by the root's handle
/// ([`Anchors`]).
pub(crate) fn walk_from(
    kernel: &dyn Kernel,
    root: ProcessId,
    parents: &[(RawPid, RawPid)],
    depth: Recursive,
) -> Result<Option<Walk>, Error> {
    let Some(AnchorProof { bound: root_bound }) = anchor(kernel, root)? else {
        return Ok(None);
    };
    let resolve = |pid, parent, bound| resolve_or_drop(kernel, pid, parent, bound);
    let key_of = |pid| match ProcessId::of_ordered_with(kernel, pid, None, None, None).0 {
        Resolved::Found((_, order)) => order,
        Resolved::Gone | Resolved::Unknown => None,
    };
    // The creator pid on the parent's own handle (the one read that names it where its row is gone).
    let creator_of = |parent: ProcessId| match parent.parent_number_and_order_with(kernel).0 {
        Resolved::Found((creator, _)) => Some(creator),
        Resolved::Gone | Resolved::Unknown => None,
    };
    let reads = AnchorReads {
        key_of: &key_of,
        creator_of: &creator_of,
    };
    Ok(Some(match depth {
        Recursive::No => children_of_with(root, root_bound, parents, resolve, &reads),
        Recursive::Yes => descendants_with(root, root_bound, parents, resolve, &reads),
    }))
}

/// Open `id` by identity, for one send. `Ok(None)`: it is gone, or its pid names another process.
/// An identity that cannot be read or proved leaves nothing to send to, so it is the error the walk
/// gives the same pid ([`unqueryable`](crate::identity::unqueryable)). It logs nothing: the walk's
/// caller reports it, once.
///
/// Linux reads the open's failure by call ([`OpenFailure`](crate::os_process::OpenFailure)) to build
/// that error.
#[cfg(any(unix, windows))]
fn open_by_identity<'k>(kernel: &'k dyn Kernel, id: ProcessId) -> Result<Option<Box<dyn OsProcess + 'k>>, Error> {
    crate::os_process::open_with(kernel, id).map_err(|failure| member_error(id.pid(), failure))
}

/// The error a walk gives `pid`, a member that cannot be opened by identity.
#[cfg(any(unix, windows))]
fn member_error(pid: RawPid, failure: crate::os_process::OpenFailure) -> Error {
    use crate::os_process::OpenFailure;

    match failure {
        #[cfg(target_os = "linux")]
        OpenFailure::Call(call) => crate::identity::call_error(&format!("pid {pid}"), call),
        #[cfg(target_os = "linux")]
        OpenFailure::Finished(error @ (Error::Unassessable { .. } | Error::Unsupported { .. })) => error,
        #[cfg(target_os = "linux")]
        OpenFailure::Finished(other) => unproved(pid, other),
        #[cfg(not(target_os = "linux"))]
        OpenFailure::Finished(error) => {
            let _ = pid;
            error
        }
    }
}

/// `error`, which the open of `pid`'s pidfd finished with and which is no refusal of a signal (a
/// live thread that leads no group, a `poll` that reported `POLLERR`), as [`Error::Unassessable`]
/// with `error` as its source.
#[cfg(target_os = "linux")]
fn unproved(pid: RawPid, error: Error) -> Error {
    Error::Unassessable {
        detail: format!("pid {pid} identity could not be confirmed: its pidfd could not be proved to name it"),
        source: Some(Arc::new(error)),
    }
}

/// The one send to a walked member, through `opened`'s handle: nothing is sent to a process that is
/// gone, or that another process's pid names now.
#[cfg(any(unix, windows))]
fn kill_opened(id: ProcessId, opened: Result<Option<Box<dyn OsProcess + '_>>, Error>, sig: Sig) -> KillOutcome {
    match opened {
        Ok(Some(os)) => {
            // Test seam: makes the member exit between its open and its send.
            #[cfg(all(test, windows))]
            fault::run_before_terminate();
            KillOutcome::of(os.signal(sig))
        }
        Ok(None) => {
            log::debug!(
                "treewalk: skipping pid {pid} - identity changed or gone since the snapshot",
                pid = id.pid()
            );
            KillOutcome::AlreadyGone
        }
        Err(error) => KillOutcome::NotAttempted(error),
    }
}

/// The [`Sig`] a walk sends for `signal`: SIGKILL or SIGTERM, the only two it sends.
#[cfg(unix)]
fn sig_of(signal: Signal) -> Sig {
    match signal {
        Signal::SIGKILL => Sig::Kill,
        Signal::SIGTERM => Sig::Term,
        other => unreachable!("a walk sends SIGKILL or SIGTERM, not {other}"),
    }
}

/// Signal `id` through a handle opened by identity ([`open_by_identity`]) — never a recycled pid.
/// The handle pins the process, so a pid reused after the open cannot be hit (macOS: by its audit
/// token, which the kernel checks). Already gone (`Ok(None)` from the open, or the send's own answer)
/// is success. A process that cannot be opened or proved leaves no identity, so nothing is sent:
/// `NotAttempted`. Best-effort.
#[cfg(unix)]
pub(crate) fn kill_by_identity(kernel: &dyn Kernel, id: ProcessId, signal: Signal) -> KillOutcome {
    kill_opened(id, open_by_identity(kernel, id), sig_of(signal))
}

/// Terminate `id` through a handle opened by identity ([`open_by_identity`]). Already gone
/// (unresolvable, or exiting when the call came) is success. Best-effort.
#[cfg(windows)]
pub(crate) fn kill_by_identity(kernel: &dyn Kernel, id: ProcessId) -> KillOutcome {
    kill_opened(id, open_by_identity(kernel, id), Sig::Kill)
}

/// Whether `root`'s exit has begun, as the kernel's exit flag shows (see the module doc), read through
/// the view `table` was; a root that is a zombie, reaped, or no longer holding its pid is past its
/// beginning. Always `false` on Windows. Asked after a walk and before the root is signalled, for a root
/// cosca itself killed would show the flag.
///
/// # Errors
///
/// [`Error::Unassessable`] when the flag cannot be read.
fn exit_begun(kernel: &dyn Kernel, table: &Table, root: ProcessId) -> Result<bool, Error> {
    #[cfg(unix)]
    {
        let (read, cause) = table.exit_begun(kernel, root);
        match read {
            Resolved::Found(begun) => Ok(begun),
            Resolved::Gone => Ok(true),
            Resolved::Unknown => {
                let subject = format!("pid {pid}", pid = root.pid());
                Err(Error::Unassessable {
                    detail: format!(
                        "{subject}: whether the root's exit has begun could not be read, so a walk from it cannot be \
                         told to have reached its tree"
                    ),
                    source: cause.into_error(&subject).map(Arc::new),
                })
            }
        }
    }
    #[cfg(not(unix))]
    {
        let _ = (kernel, table, root);
        Ok(false)
    }
}

/// Hard-kill the tree rooted at `root`: snapshot once, compute
/// genuine descendants, kill the root FIRST then each descendant. SIGKILL on
/// Unix; `TerminateProcess` on Windows. Best-effort; a member that is already gone is success.
///
/// # Errors
///
/// [`TreeKillOutcome::Unwalked`], an [`Error::Unassessable`], when the process snapshot cannot be
/// taken, or `root` cannot be proved to hold its pid after it (a root that exists but cannot be
/// queried). Nothing is killed, the root included: killing the root first would reparent its
/// descendants out of the ppid walk, so a retry could no longer find them. A root that no longer
/// holds its pid is [`TreeKillOutcome::NoRoot`], with nothing killed.
///
/// [`Error::MemberNotKilled`] when the walk ran but left a member behind: a candidate whose identity
/// could not be read (so it and its subtree were not walked), or an identity it resolved whose kill
/// was refused. Everything else was killed. The [`Unkilled`] holds every member left, the root
/// apart: the candidates the walk could not read, in the order it found them, then the descendants
/// whose kill sent nothing, in the order they were tried. It reports none of them: the caller does,
/// once, after the root's death by its handle has had its say ([`Tree::settle`]).
///
/// The root's kill goes through [`Root::signal`] of `held`, which must name `root`
/// ([`ByIdentity`] where the caller holds no handle on it). Each descendant is killed through a
/// handle opened by its identity. The [`TreeKill`] names every descendant whose kill was sent
/// (each re-opened by identity, through `kernel`, when a caller waits), and whether the root's landed.
///
/// A root whose exit has begun, or whose exit flag cannot be read, answers as the module doc says
/// ([`TreeKillOutcome::NoRoot`], [`RootExiting`](TreeKillOutcome::RootExiting),
/// [`ExitUnread`](TreeKillOutcome::ExitUnread), or an [`Unkilled`] that holds an [`Error::Unassessable`]
/// naming no member beside what is left).
///
/// [`Tree::settle`]: crate::containment::Tree::settle
pub(crate) fn hard_kill<'a>(kernel: &'a dyn Kernel, root: ProcessId, held: &dyn Root) -> TreeKill<'a> {
    debug_assert_eq!(held.pid(), root.pid(), "the held root is not the walk's root");
    // Test-only fault seam: skip the root's kill (take semantics — see `fault`).
    #[cfg(test)]
    let skip_root = fault::take_force_root_kill_noop();
    #[cfg(not(test))]
    let skip_root = false;
    let table = match crate::containment::enumerate::process_table(kernel) {
        Ok(table) => table,
        Err(error) => return TreeKill::of(TreeKillOutcome::Unwalked(error)).through(kernel),
    };
    let Walk {
        members: descendants,
        unassessed,
    } = match walk_from(kernel, root, &table.parents, Recursive::Yes) {
        Ok(Some(walk)) => walk,
        Ok(None) => return TreeKill::of(TreeKillOutcome::NoRoot(root.pid(), None)).through(kernel),
        Err(error) => return TreeKill::of(TreeKillOutcome::Unwalked(error)).through(kernel),
    };
    #[cfg(test)]
    fault::note_walk(root.pid());
    // A candidate that could not be read is not killed, and nor is anything under it: left behind.
    let mut left: Vec<Error> = unassessed.into_iter().map(|(pid, why)| not_killed(pid, why)).collect();
    let mut root_left: Option<Error> = None;
    // Forced-incomplete seam: fabricates a refused member.
    #[cfg(all(test, unix))]
    if let Some(forced) = fault::take_force_incomplete() {
        let forced_error = |pid| {
            not_killed(
                pid,
                Error::Unassessable {
                    detail: "the walk was forced incomplete".into(),
                    source: None,
                },
            )
        };
        if forced.leaves_root() {
            root_left = Some(forced_error(root.pid()));
        }
        if forced.leaves_descendant() {
            left.push(forced_error(root.pid().wrapping_add(1)));
        }
    }
    // After the walk and before the root is killed (its own kill would set the flag): a root whose exit
    // had begun when the walk ended may have had children reparented out of it.
    let walked = !descendants.is_empty() || !left.is_empty();
    // The read's error and where it stands among what is left, when the flag could not be read.
    let mut unread: Option<(usize, Error)> = None;
    let begun = match exit_begun(kernel, &table, root) {
        Ok(true) if !walked && root_left.is_none() => {
            return TreeKill::of(TreeKillOutcome::NoRoot(root.pid(), None)).through(kernel);
        }
        Err(unreadable) if !walked && root_left.is_none() => {
            return TreeKill::of(TreeKillOutcome::Unwalked(unreadable)).through(kernel);
        }
        Ok(begun) => begun,
        Err(unreadable) => {
            unread = Some((left.len(), unreadable));
            false
        }
    };
    let mut resolved = Vec::new();
    let mut killed = Vec::new();
    let mut root_killed = false;
    #[cfg(any(unix, windows))]
    {
        if !skip_root {
            let outcome = KillOutcome::of(held.signal(Sig::Kill));
            root_killed = !matches!(outcome, KillOutcome::NotAttempted(_));
            root_left = left_behind(root, outcome).or(root_left);
        }
        for id in descendants {
            let outcome = kill_one(kernel, id);
            if matches!(outcome, KillOutcome::Terminated) {
                killed.push(id);
            }
            if let Some(error) = left_behind(id, outcome) {
                left.push(error);
                resolved.push(id);
            }
        }
    }
    #[cfg(not(any(unix, windows)))]
    let _ = (kernel, root, descendants, skip_root, held);
    let nothing_left = left.is_empty() && root_left.is_none();
    let outcome = if nothing_left {
        match unread {
            Some((_, unreadable)) => TreeKillOutcome::ExitUnread(unreadable),
            // Every member found was killed; the exit may have moved others out of the walk, as a root
            // that had exited when the walk ran leaves none to find.
            None if begun && walked => TreeKillOutcome::RootExiting(root.pid(), None),
            None => TreeKillOutcome::Ran(Ok(())),
        }
    } else {
        if let Some((at, unreadable)) = unread {
            left.insert(at, unreadable);
        }
        // Something is left of a tree whose root's exit had begun: the answer says the tree cannot be
        // vouched for beside it, so a later kill that ends the root does not settle it `Ok`.
        #[cfg(unix)]
        if begun && walked {
            left.push(TreeKillOutcome::exiting_root_error(root.pid()));
        }
        TreeKillOutcome::Ran(Err(Unkilled {
            members: left,
            root: root_left.map(Box::new),
            resolved,
        }))
    };
    TreeKill::of(outcome)
        .through(kernel)
        .reaching(killed)
        .root_killed(root_killed)
}

/// `id`'s SIGKILL by identity (`TerminateProcess` on Windows).
#[cfg(any(unix, windows))]
fn kill_one(kernel: &dyn Kernel, id: ProcessId) -> KillOutcome {
    #[cfg(unix)]
    return kill_by_identity(kernel, id, Signal::SIGKILL);
    #[cfg(windows)]
    kill_by_identity(kernel, id)
}

/// A member of a `TreeWalk` tree that a walk left, as the handle holds it for the next kill
/// ([`with_earlier`]).
#[derive(Debug, Clone)]
pub(crate) enum Left {
    /// The walk read its identity and its kill was refused: a later kill kills it by identity again.
    Resolved(ProcessId),
    /// The walk never read its identity, so nothing can act on it: a later kill reports it again as
    /// the member it was first reported as, [`Error::MemberNotKilled`] with this `source` (the same
    /// `Arc`).
    Unread { pid: RawPid, source: Arc<Error> },
    /// A `SIGTERM` walk reached it while the root ran, and nothing has refused it: a later kill, which
    /// cannot walk to it once the root has exited, kills it by identity. `walk` names the call whose
    /// walk listed the tree whole and reached it, if one did ([`WalkToken`]); a member of a walk that
    /// could not read every candidate, or of a separate `terminate_tree`, has none.
    Termed { id: ProcessId, walk: Option<WalkToken> },
}

/// A call that walked a tree with `SIGTERM` and will sweep it: the tag of the members its complete
/// walk reached ([`Left::Termed`]), which that call's own sweep asks the settlement about. One value
/// per call, equal only to its own clones.
#[derive(Debug, Clone)]
pub(crate) struct WalkToken(Arc<()>);

impl WalkToken {
    pub(crate) fn new() -> WalkToken {
        WalkToken(Arc::new(()))
    }
}

impl PartialEq for WalkToken {
    fn eq(&self, other: &WalkToken) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Left {
    /// Every member `left` names, in order: each [`Error::MemberNotKilled`]. The error of a walk that
    /// was not made, or found no root, or whose root's exit had begun, names no process, so none is
    /// held. A member never read shares its `source` with its `Left`.
    pub(crate) fn of(left: &Unkilled) -> Vec<Left> {
        let resolved = &left.resolved;
        let mut held = Vec::new();
        for member in &left.members {
            let Error::MemberNotKilled { pid, source } = member else {
                debug_assert!(
                    matches!(member, Error::Unassessable { .. } | Error::Unsupported { .. }),
                    "an error that is no member is the walk's not made, or its root's exit begun: {member:?}"
                );
                continue;
            };
            held.push(match resolved.iter().find(|id| id.pid() == *pid) {
                Some(id) => Left::Resolved(*id),
                None => Left::Unread {
                    pid: *pid,
                    source: Arc::clone(source),
                },
            });
        }
        held
    }

    pub(crate) fn pid(&self) -> RawPid {
        match self {
            Left::Resolved(id) | Left::Termed { id, .. } => id.pid(),
            Left::Unread { pid, .. } => *pid,
        }
    }
}

/// `walked`, the answer of a kill that walked a tree, with `earlier`, the members the kills before it
/// left. The root's death reparents a descendant out of any later walk, so such a walk cannot find
/// them: each one read is killed again by its identity, so one that is gone stops failing the call
/// and one that still refuses is `MemberNotKilled` again; one never read is `MemberNotKilled` again
/// as it was. A member the walk names itself is not repeated. The earlier members come first, as the
/// first failure stands. Also the members killed again, which the kill's wait goes on to wait for.
pub(crate) fn with_earlier(
    kernel: &dyn Kernel,
    earlier: Vec<Left>,
    walked: Result<(), Unkilled>,
) -> (Result<(), Unkilled>, Vec<ProcessId>) {
    let mut walked = match walked {
        Ok(()) => Unkilled {
            members: Vec::new(),
            root: None,
            resolved: Vec::new(),
        },
        Err(left) => left,
    };
    let named: Vec<RawPid> = walked
        .members
        .iter()
        .filter_map(|member| match member {
            Error::MemberNotKilled { pid, .. } => Some(*pid),
            _ => None,
        })
        .collect();
    let mut members = Vec::new();
    let mut killed = Vec::new();
    for left in earlier.into_iter().filter(|left| !named.contains(&left.pid())) {
        match left {
            // A member a `SIGTERM` walk reached that this kill refuses becomes a refused one: the
            // next kill finds it `Resolved`.
            Left::Resolved(id) | Left::Termed { id, .. } => {
                #[cfg(any(unix, windows))]
                {
                    let outcome = kill_one(kernel, id);
                    if matches!(outcome, KillOutcome::Terminated) {
                        killed.push(id);
                    }
                    if let Some(error) = left_behind(id, outcome) {
                        members.push(error);
                        walked.resolved.push(id);
                    }
                }
                #[cfg(not(any(unix, windows)))]
                let _ = (kernel, id);
            }
            Left::Unread { pid, source } => members.push(Error::MemberNotKilled { pid, source }),
        }
    }
    if members.is_empty() && walked.members.is_empty() && walked.root.is_none() {
        return (Ok(()), killed);
    }
    members.append(&mut walked.members);
    walked.members = members;
    (Err(walked), killed)
}

/// What a call that kills nothing still owes of `held`: each member an earlier kill refused and that
/// may still run, as that kill's [`Error::MemberNotKilled`] (a member never read as it was reported; a
/// member whose identity was read, and that is not gone, with a source that says this call did not try
/// again). A member a `SIGTERM` walk reached was refused by nothing, so it is not owed.
pub(crate) fn refused_still(kernel: &dyn Kernel, held: &[Left]) -> Vec<Error> {
    held.iter()
        .filter_map(|left| match left {
            Left::Resolved(id) => (id.is_alive_with(kernel) != crate::identity::Liveness::Dead).then(|| {
                not_killed(
                    id.pid(),
                    Error::Unassessable {
                        detail: "an earlier kill could not kill it, and this call, which could not walk the tree, \
                                 did not try again"
                            .into(),
                        source: None,
                    },
                )
            }),
            Left::Unread { pid, source } => Some(Error::MemberNotKilled {
                pid: *pid,
                source: Arc::clone(source),
            }),
            Left::Termed { .. } => None,
        })
        .collect()
}

/// The error for the member `pid` a walk left behind, `source` why.
fn not_killed(pid: RawPid, source: Error) -> Error {
    Error::MemberNotKilled {
        pid,
        source: Arc::new(source),
    }
}

/// `id`'s kill's `outcome` as the error of a member left behind, when it sent nothing to a process
/// that may be running.
#[cfg(any(unix, windows))]
fn left_behind(id: ProcessId, outcome: KillOutcome) -> Option<Error> {
    match outcome {
        KillOutcome::NotAttempted(source) => Some(not_killed(id.pid(), source)),
        KillOutcome::Terminated | KillOutcome::AlreadyGone => None,
    }
}

/// A walk's root for a caller that holds no handle on it: opened by its identity through `kernel`
/// for each send, as a member is.
pub(crate) struct ByIdentity<'k> {
    kernel: &'k dyn Kernel,
    id: ProcessId,
}

impl<'k> ByIdentity<'k> {
    pub(crate) fn new(kernel: &'k dyn Kernel, id: ProcessId) -> ByIdentity<'k> {
        ByIdentity { kernel, id }
    }
}

impl Root for ByIdentity<'_> {
    fn pid(&self) -> u32 {
        self.id.pid()
    }

    fn signal(&self, sig: Sig) -> Result<Sent, Error> {
        match open_by_identity(self.kernel, self.id)? {
            Some(os) => os.signal(sig),
            None => Ok(Sent::Gone),
        }
    }

    /// No handle is held, so none says whether the root was reaped.
    #[cfg(unix)]
    fn state(&self) -> RootState {
        RootState::unheld()
    }

    #[cfg(target_os = "linux")]
    fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
        None
    }
}

/// Test-only: force the NEXT `hard_kill` on THIS thread to skip the root's kill
/// (makes the `kill_tree` handle backstop forcible). Take semantics: `hard_kill` consumes the
/// flag — arm and call on one thread; assert consumption via [`armed`].
#[cfg(test)]
pub(crate) mod fault {
    use std::cell::{Cell, RefCell};
    thread_local! {
        static FORCE_ROOT_KILL_NOOP: Cell<bool> = const { Cell::new(false) };
        static WALKS: RefCell<Option<Vec<u32>>> = const { RefCell::new(None) };
        #[cfg(unix)]
        static FORCE_INCOMPLETE: Cell<Option<LeftBehind>> = const { Cell::new(None) };
        #[cfg(windows)]
        static BEFORE_TERMINATE: RefCell<Option<Box<dyn FnOnce()>>> = const { RefCell::new(None) };
    }

    /// Run `hook` once on this thread in the next Windows `kill_by_identity`, between the identity
    /// check and `TerminateProcess` (where a member can exit on its own).
    #[cfg(windows)]
    pub(crate) fn set_before_terminate(hook: impl FnOnce() + 'static) {
        BEFORE_TERMINATE.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
    }

    #[cfg(windows)]
    pub(super) fn run_before_terminate() {
        if let Some(hook) = BEFORE_TERMINATE.with(|h| h.borrow_mut().take()) {
            hook();
        }
    }

    /// Which member a forced-incomplete walk leaves behind.
    #[cfg(unix)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum LeftBehind {
        /// The root only.
        Root,
        /// A non-root member.
        Descendant,
        /// The root and a non-root member.
        #[cfg(not(target_os = "macos"))]
        RootAndDescendant,
    }

    #[cfg(unix)]
    impl LeftBehind {
        pub(super) fn leaves_root(self) -> bool {
            match self {
                LeftBehind::Root => true,
                LeftBehind::Descendant => false,
                #[cfg(not(target_os = "macos"))]
                LeftBehind::RootAndDescendant => true,
            }
        }

        pub(super) fn leaves_descendant(self) -> bool {
            match self {
                LeftBehind::Root => false,
                LeftBehind::Descendant => true,
                #[cfg(not(target_os = "macos"))]
                LeftBehind::RootAndDescendant => true,
            }
        }
    }

    /// Make the next `hard_kill` on this thread leave `left` behind, as a refused kill would. Consumed
    /// by that call.
    #[cfg(unix)]
    pub(crate) fn force_incomplete_once(left: LeftBehind) {
        FORCE_INCOMPLETE.with(|f| f.set(Some(left)));
    }

    #[cfg(unix)]
    pub(super) fn take_force_incomplete() -> Option<LeftBehind> {
        FORCE_INCOMPLETE.with(|f| f.take())
    }

    /// From now on every ppid walk from a root's pid on THIS thread (`treewalk::hard_kill`,
    /// `terminate`, a macOS fd marker's channel 1+2) records that pid, so a test can tell a walk
    /// ran without a process having to die. The walk itself still runs.
    #[cfg(unix)]
    pub(crate) fn record_walks() -> WalkRecorder {
        WALKS.with(|w| *w.borrow_mut() = Some(Vec::new()));
        WalkRecorder(())
    }

    #[cfg(unix)]
    #[must_use = "recording stops as soon as the recorder is dropped"]
    pub(crate) struct WalkRecorder(());

    #[cfg(unix)]
    impl WalkRecorder {
        /// The root pids walked since the recorder was made.
        pub(crate) fn walked(&self) -> Vec<u32> {
            WALKS.with(|w| w.borrow().clone().expect("the recorder is live"))
        }
    }

    #[cfg(unix)]
    impl Drop for WalkRecorder {
        fn drop(&mut self) {
            WALKS.with(|w| *w.borrow_mut() = None);
        }
    }

    pub(crate) fn note_walk(root_pid: u32) {
        WALKS.with(|w| {
            if let Some(walked) = w.borrow_mut().as_mut() {
                walked.push(root_pid);
            }
        });
    }
    // On macOS, a walk tree (and so `hard_kill`) is only reached when the fd marker
    // failed to install or is suppressed (decision 2: the marker otherwise takes priority) —
    // dispatch_tests.rs's backstop tests exercise the always-installed `fdmarker::fault` seam
    // there instead, leaving these two callers-only-on-other-platforms.
    #[cfg_attr(
        target_os = "macos",
        allow(
            dead_code,
            reason = "dispatch_tests.rs uses the fdmarker::fault seam on macOS instead"
        )
    )]
    pub(crate) fn set_force_root_kill_noop(on: bool) {
        FORCE_ROOT_KILL_NOOP.with(|f| f.set(on));
    }
    pub(crate) fn take_force_root_kill_noop() -> bool {
        FORCE_ROOT_KILL_NOOP.with(|f| f.replace(false))
    }
    #[cfg_attr(
        target_os = "macos",
        allow(
            dead_code,
            reason = "dispatch_tests.rs uses the fdmarker::fault seam on macOS instead"
        )
    )]
    pub(crate) fn armed() -> bool {
        FORCE_ROOT_KILL_NOOP.with(|f| f.get())
    }
}

/// Graceful termination of the tree rooted at `root`.
///
/// Unix: the same snapshot + identity walk with SIGTERM (root then descendants) —
/// cooperative shutdown that still re-verifies identity before each signal, so it
/// reaches the whole genuine tree that the walk could assess, and errors as `hard_kill` does
/// (`# Errors`). Unlike `hard_kill` it does not report a candidate the walk could not assess
/// ([`Walk::unassessed`]), nor a member whose signal was not sent: they are warned of and not
/// signalled, and the result is still `Ok`.
///
/// Windows: send `CTRL_BREAK_EVENT` to the root's process group (the root was
/// spawned with `CREATE_NEW_PROCESS_GROUP`). This is cooperative only and reaches
/// only processes that share the root's console group; a nested *contained*
/// descendant is spawned into its OWN process group (`CREATE_NEW_PROCESS_GROUP`)
/// and therefore does NOT receive this CTRL_BREAK. THIS WALK cannot reach those
/// nested groups — but their own holder can, through the nested child's own handle
/// (see [`Child::terminate`](crate::Child::terminate)). From a single handle, the
/// identity `hard_kill` (`kill_tree`) remains the only op that reaches every member.
/// Best-effort by design.
///
/// # Errors
///
/// As [`hard_kill`] on Unix. Windows: those of `containment::windows::terminate`.
///
/// On Unix the root's `SIGTERM` goes through [`Root::signal`] of `held`, as [`hard_kill`]'s kill does;
/// Windows signals the root's process group and sends it nothing.
///
/// The members it found, the root apart, are its [`Listing`] (none on Windows): once the root exits
/// they are reparented out of every later walk, so a later kill can reach them only by these
/// identities. A root whose exit has begun, reaped or not, and whose walk finds no member sends
/// nothing ([`Terminated::RootExited`], see the module doc); one whose walk finds members signals
/// them, and its [`Listing`] is not complete. So is the listing of a walk whose members were signalled
/// though the flag could not be read; with no member found, that error is the walk's.
pub(crate) fn terminate(kernel: &dyn Kernel, root: ProcessId, held: &dyn Root) -> Result<Terminated, Error> {
    debug_assert_eq!(held.pid(), root.pid(), "the held root is not the walk's root");
    #[cfg(unix)]
    {
        let table = crate::containment::enumerate::process_table(kernel)?;
        let Some(walk) = walk_from(kernel, root, &table.parents, Recursive::Yes)? else {
            return Ok(Terminated::RootExited(exited_root_error(root.pid())));
        };
        #[cfg(test)]
        fault::note_walk(root.pid());
        // A root whose exit has begun, and whose walk finds no member, sends nothing, whether or not the
        // walk could read every candidate: a signal to its zombie reaches no one, and the exit may have
        // reparented every child. Read before the root's own `SIGTERM`, which would begin its exit.
        let begun = match exit_begun(kernel, &table, root) {
            Ok(true) if walk.members.is_empty() => {
                return Ok(Terminated::RootExited(exited_root_error(root.pid())));
            }
            Ok(begun) => begun,
            Err(unreadable) if walk.members.is_empty() => return Err(unreadable),
            // The members are signalled as before the flag was read; the listing cannot vouch for the tree.
            Err(unreadable) => {
                log::warn!(
                    "treewalk: the SIGTERM walk of pid {pid} cannot vouch for its tree: {report}",
                    pid = root.pid(),
                    report = crate::error::Report(&unreadable)
                );
                true
            }
        };
        // Best effort by contract: a candidate that could not be read is warned of and not signalled.
        warn_unassessed(&walk.unassessed);
        warn_if_not_attempted(root, Signal::SIGTERM, &KillOutcome::of(held.signal(Sig::Term)));
        for id in &walk.members {
            warn_if_not_attempted(*id, Signal::SIGTERM, &kill_by_identity(kernel, *id, Signal::SIGTERM));
        }
        Ok(Terminated::Walked(Listing {
            // A root whose exit had begun, or whose flag could not be read, may have had children
            // reparented out of the walk.
            complete: walk.unassessed.is_empty() && !begun,
            members: walk.members,
        }))
    }
    #[cfg(windows)]
    {
        let _ = (kernel, held);
        crate::containment::windows::terminate(root.pid()).map(|()| {
            Terminated::Walked(Listing {
                members: Vec::new(),
                complete: true,
            })
        })
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (kernel, root, held);
        Ok(Terminated::Walked(Listing {
            members: Vec::new(),
            complete: true,
        }))
    }
}

/// The members a `SIGTERM` walk found and signalled, the root apart.
#[derive(Debug)]
pub(crate) struct Listing {
    pub(crate) members: Vec<ProcessId>,
    /// The walk assessed every candidate, so `members` list the tree whole as the walk saw it; one it
    /// could not read is warned of, and a listing without it cannot vouch for the tree.
    pub(crate) complete: bool,
}

/// What [`terminate`]'s walk did, once the process table was read (an unreadable table is its `Err`).
pub(crate) enum Terminated {
    /// The `SIGTERM`s went out to the root and to the members of the listing.
    Walked(Listing),
    /// Nothing was sent: the root has exited and the walk found no member.
    #[cfg_attr(
        windows,
        allow(dead_code, reason = "Windows never reparents, so an exited root's walk stands")
    )]
    RootExited(Error),
}

impl Terminated {
    /// The answer of a `terminate_tree` call: `Ok` once the signals went out, the error of a root that
    /// had exited otherwise.
    pub(crate) fn into_result(self) -> Result<(), Error> {
        match self {
            Terminated::Walked(_) => Ok(()),
            Terminated::RootExited(exited) => Err(exited),
        }
    }
}

/// The error of a `SIGTERM` that sent nothing because the root `pid` has exited.
#[cfg(unix)]
fn exited_root_error(pid: u32) -> Error {
    Error::Unassessable {
        detail: format!(
            "the root (pid {pid}) has exited, so its descendants were reparented and a walk from its pid finds \
             none: nothing was sent"
        ),
        source: None,
    }
}

/// macOS: the skip of a walk that names the tree by the root's pid, when `root` cannot be shown to be
/// this process's unreaped child (`Unpinned` or `Unknown`). Elsewhere the walk is its own guard: it
/// proves its root still holds its pid ([`anchor`]), and a reaped root walks nothing. Without a root
/// to look at there is nothing to skip.
fn skipped_walk(root: Option<&dyn crate::containment::Root>) -> Option<Skip> {
    let root = root?;
    #[cfg(not(target_os = "macos"))]
    let _ = root;
    #[cfg(target_os = "macos")]
    let state = root.look_state();
    #[cfg(all(test, unix))]
    crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
    #[cfg(target_os = "macos")]
    {
        if matches!(
            state,
            crate::signal::RootState::Unpinned | crate::signal::RootState::Unknown(_)
        ) {
            return Some(Skip {
                action: format!("walk the process table from the root's pid (root pid {})", root.pid()),
                why: Why::untrusted(&state),
                root_alone: false,
                holders: None,
            });
        }
    }
    None
}

/// [`hard_kill`] from the host's process table, the root killed through `owner`'s handle if there is
/// one, else by its identity: skipped where the root's number cannot be trusted ([`skipped_walk`]),
/// else walked.
pub(crate) fn kill_tree<'a>(root: ProcessId, owner: Option<&dyn Root>) -> TreeKill<'a> {
    match skipped_walk(owner) {
        Some(skip) => TreeKill::of(TreeKillOutcome::Skipped(skip)),
        None => {
            let kernel = &crate::identity::HostKernel;
            hard_kill(kernel, root, owner.unwrap_or(&ByIdentity::new(kernel, root)))
        }
    }
}

/// [`terminate`] from `kernel`'s process table, as [`kill_tree`] decides it, with the listing of the
/// walk that went out.
pub(crate) fn terminate_tree(
    kernel: &dyn Kernel,
    root: ProcessId,
    owner: Option<&dyn Root>,
) -> (TerminateOutcome, Option<Listing>) {
    match skipped_walk(owner) {
        Some(skip) => (TerminateOutcome::End(skip), None),
        None => {
            // `NotSent` is an error that comes before the first signal: the process table could not be
            // read or the walk made (Unix), or the break could not be sent (Windows). A failed signal to
            // the root or a member is only warned of, so it is `Sent { Ok }`.
            match terminate(kernel, root, owner.unwrap_or(&ByIdentity::new(kernel, root))) {
                Ok(Terminated::Walked(listing)) => (
                    TerminateOutcome::Sent {
                        result: Ok(()),
                        earlier: Some("the SIGTERM"),
                    },
                    Some(listing),
                ),
                Ok(Terminated::RootExited(error)) => (TerminateOutcome::RootExited(error), None),
                Err(not_sent) => (TerminateOutcome::NotSent(not_sent), None),
            }
        }
    }
}

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

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

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

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

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

#[cfg(all(test, windows))]
#[path = "treewalk_toolhelp_tests.rs"]
mod treewalk_toolhelp_tests;