cosca 0.8.0

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

use super::{descendants_with, Resolution, Walk};
use crate::error::Error;
use crate::identity::{Key, OrderKey, ProcessId, RawPid, UnknownCause};
#[cfg(unix)]
use crate::test_groups::setuid;
use std::collections::HashMap;

const ROOT_PID: RawPid = 100;
const ROOT_TOKEN: u64 = 1_000;

/// A tree call given no owner kills and terminates the root by identity, as a member is: it walks
/// and sends, it does not refuse. The blocker's stdin stays open, so only the kill ends it.
///
/// Mutant: a call given no owner answers `Unwalked` and sends nothing.
#[cfg(any(unix, windows))]
#[skuld::test]
fn a_tree_call_given_no_owner_sends_the_roots_kill_by_identity() {
    let (child, stdin) = crate::test_child::held_uncontained_blocker(false);
    let id = child.id().expect(crate::test_child::IDENTITY_READ);

    super::kill_tree(id, None)
        .outcome()
        .into_result()
        .expect("the walk found the root and killed it");

    let status = child.wait().expect("the killed root is reaped");
    assert!(!status.success(), "the kill ended the root, not its stdin: {status:?}");
    drop(stdin);
}

/// [`a_tree_call_given_no_owner_sends_the_roots_kill_by_identity`], for the `SIGTERM`.
///
/// Mutant: a call given no owner answers an error and sends nothing.
#[cfg(unix)]
#[skuld::test]
fn a_tree_call_given_no_owner_sends_the_roots_term_by_identity() {
    use std::os::unix::process::ExitStatusExt as _;

    let (child, stdin) = crate::test_child::held_uncontained_blocker(false);
    let id = child.id().expect(crate::test_child::IDENTITY_READ);

    match super::terminate_tree(&crate::identity::HostKernel, id, None) {
        crate::containment::TerminateOutcome::Sent { result: Ok(()), .. } => {}
        other => panic!("the walk found the root and signalled it: {other:?}"),
    }

    let status = child.wait().expect("the signalled root is reaped");
    assert_eq!(status.signal(), Some(libc::SIGTERM), "{status:?}");
    drop(stdin);
}

/// An unverified send, which no handle a walk sends through gives, asserts in debug. Mutant: it is
/// read as an ordinary answer.
#[cfg(debug_assertions)]
#[skuld::test]
fn an_unverified_send_is_a_contract_breach() {
    assert!(
        std::panic::catch_unwind(|| super::KillOutcome::of(Ok(crate::signal::Sent::Unverified))).is_err(),
        "the breach did not assert"
    );
}

/// Release reads an unverified send as nothing sent to a process that may be running. Mutant: it
/// is read as delivered or gone.
#[cfg(not(debug_assertions))]
#[skuld::test]
fn an_unverified_send_is_not_attempted_in_release() {
    match super::KillOutcome::of(Ok(crate::signal::Sent::Unverified)) {
        super::KillOutcome::NotAttempted(Error::Unassessable { .. }) => {}
        other => panic!("an unverified send is not attempted, Unassessable: {other:?}"),
    }
}

/// The one reading of a send's answer, for a walk's members and the root alike. Mutants: a refusal
/// is read as delivered or gone.
#[skuld::test]
fn a_sends_answer_is_one_outcome_whoever_sent() {
    use super::KillOutcome;
    use crate::signal::Sent;

    assert!(matches!(KillOutcome::of(Ok(Sent::Delivered)), KillOutcome::Terminated));
    assert!(matches!(KillOutcome::of(Ok(Sent::Gone)), KillOutcome::AlreadyGone));
    match KillOutcome::of(Err(Error::Io(std::io::Error::from(
        std::io::ErrorKind::PermissionDenied,
    )))) {
        KillOutcome::NotAttempted(Error::Io(refused)) => {
            assert_eq!(refused.kind(), std::io::ErrorKind::PermissionDenied);
        }
        other => panic!("a refusal is not attempted, with the OS's own error: {other:?}"),
    }
}

fn id(pid: RawPid, token: u64) -> ProcessId {
    ProcessId::from_parts_for_test(pid, Key::for_test(token))
}

/// The bound a candidate's children follow, as a resolver hands it out where the platform orders.
fn bound_of(token: u64) -> Option<OrderKey> {
    Some(OrderKey::for_test(token))
}

/// What the live resolver returns for a process whose identity token and order key agree.
fn resolved(pid: RawPid, token: u64) -> (ProcessId, Option<OrderKey>) {
    (id(pid, token), bound_of(token))
}

/// Build a resolver from a (pid -> token) table. A pid absent from the table is
/// unresolvable (`Ok(None)`, modelling an already-gone process, or one the read found out of order).
fn resolver(tokens: &HashMap<RawPid, u64>) -> impl Fn(RawPid, ProcessId, Option<OrderKey>) -> Resolution + '_ {
    move |pid, _parent, _bound| Ok(tokens.get(&pid).map(|&t| resolved(pid, t)))
}

/// What the live resolver returns for a pid whose read was `Unknown`.
fn unreadable(pid: RawPid) -> Error {
    crate::identity::unqueryable_read("pid", pid, UnknownCause::default())
}

/// Collect the member pids into a sorted Vec for order-independent comparison.
fn pids(walk: Walk) -> Vec<RawPid> {
    let mut v = walk.members;
    v.sort_by_key(|i| i.pid());
    v.into_iter().map(|i| i.pid()).collect()
}

/// The pids a walk could not assess, sorted.
fn unassessed(walk: &Walk) -> Vec<RawPid> {
    let mut v: Vec<RawPid> = walk.unassessed.iter().map(|&(pid, _)| pid).collect();
    v.sort_unstable();
    v
}

fn root() -> ProcessId {
    id(ROOT_PID, ROOT_TOKEN)
}

fn root_bound() -> Option<OrderKey> {
    bound_of(ROOT_TOKEN)
}

// Deep trees recurse =====

#[skuld::test]
fn recurses_into_deep_tree() {
    // root(100) -> 200 -> 300 -> 400, all created after the root.
    let parents = [(200, ROOT_PID), (300, 200), (400, 300)];
    let tokens = HashMap::from([
        (200u32, ROOT_TOKEN + 1),
        (300u32, ROOT_TOKEN + 2),
        (400u32, ROOT_TOKEN + 3),
    ]);
    let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
    assert_eq!(pids(got), [200, 300, 400]);
}

// A reparented orphan (ppid no longer == root) is honestly missed =====

#[skuld::test]
fn reparented_orphan_is_missed() {
    // 300 was a grandchild, but its parent 200 exited and 300 was reparented to
    // pid 1; its ppid no longer chains to the root, so the walk cannot reach it.
    let parents = [(300, 1)];
    let tokens = HashMap::from([(300u32, ROOT_TOKEN + 9)]);
    let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
    assert!(
        got.members.is_empty(),
        "reparented orphan is honestly missed (documented)"
    );
}

// The root itself is never included =====

#[skuld::test]
fn root_is_never_included() {
    // An edge naming the root as its own child would be degenerate; ensure the
    // root pid never appears in the descendant set even if such an edge exists.
    let parents = [(ROOT_PID, ROOT_PID), (200, ROOT_PID)];
    let tokens = HashMap::from([(ROOT_PID, ROOT_TOKEN), (200u32, ROOT_TOKEN + 1)]);
    let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
    assert_eq!(pids(got), [200], "root excluded; genuine child kept");
}

// A duplicate edge enumerates the pid only once =====

#[skuld::test]
fn duplicate_edge_yields_pid_once() {
    // A snapshot that lists the same (pid, ppid) edge twice must not enumerate
    // (or later double-kill) the same process twice.
    let parents = [(200, ROOT_PID), (200, ROOT_PID)];
    let tokens = HashMap::from([(200u32, ROOT_TOKEN + 1)]);
    let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
    assert_eq!(pids(got), [200], "duplicate edge collapses to a single result");
}

// An unresolvable candidate (already gone) is skipped =====

#[skuld::test]
fn unresolvable_candidate_is_skipped() {
    // 200 chains to the root but is absent from the resolver (it exited between
    // snapshot and resolve); it is dropped along with anything under it.
    let parents = [(200, ROOT_PID), (300, 200)];
    let tokens = HashMap::from([(300u32, ROOT_TOKEN + 5)]); // 200 missing
    let got = descendants_with(root(), root_bound(), &parents, resolver(&tokens));
    assert!(got.members.is_empty(), "gone candidate and its subtree are skipped");
    assert!(got.unassessed.is_empty(), "a gone candidate is not unassessed");
}

// A candidate the resolver cannot read is unassessed, and its subtree is pruned =====

#[skuld::test]
fn an_unreadable_candidate_and_its_subtree_are_out_of_the_walk_and_it_is_unassessed() {
    // 200 is unreadable; 300 under it is unreachable through it. 400 is a sibling that reads.
    let parents = [(200, ROOT_PID), (300, 200), (400, ROOT_PID)];
    let tokens = HashMap::from([(300u32, ROOT_TOKEN + 5), (400u32, ROOT_TOKEN + 6)]);
    let read = resolver(&tokens);
    let got = descendants_with(root(), root_bound(), &parents, |pid, parent, bound| {
        if pid == 200 {
            Err(unreadable(200))
        } else {
            read(pid, parent, bound)
        }
    });
    assert_eq!(unassessed(&got), [200]);
    assert!(matches!(&got.unassessed[0].1, Error::Unassessable { detail, .. } if detail.contains("pid 200")));
    assert_eq!(pids(got), [400]);
}

/// `complete_members` is the first unassessed candidate's error, its variant and detail kept, with
/// the first's own cause and every other candidate's whole error below it as a `Several`, in order.
/// No other candidate's words are in the detail.
///
/// Mutants: the others' errors are dropped, or put in the detail as text; the first's own cause is
/// dropped; a `Several` is built of the others alone.
#[skuld::test]
fn complete_members_keeps_every_unassessed_candidate_as_a_cause_in_order() {
    let parents = [(200, ROOT_PID), (300, ROOT_PID), (400, ROOT_PID)];
    // A code per pid, so a cause paired with another candidate fails.
    let os_code = |pid: RawPid| match pid {
        200 => 2,
        300 => 3,
        _ => 5,
    };
    let got = descendants_with(root(), root_bound(), &parents, |pid, _, _| {
        Err(Error::Unassessable {
            detail: format!("cause of {pid}"),
            source: Some(Error::io_cause(std::io::Error::from_raw_os_error(os_code(pid)))),
        })
    });
    let order: Vec<RawPid> = got.unassessed.iter().map(|(pid, _)| *pid).collect();
    let error = got.complete_members().expect_err("three candidates were not assessed");

    let Error::Unassessable {
        detail,
        source: Some(source),
    } = &error
    else {
        panic!("the first's variant is kept: {error:?}");
    };
    assert_eq!(*detail, format!("cause of {}", order[0]));
    let Error::Several(list) = &**source else {
        panic!("expected Several, got {source:?}");
    };
    let codes: Vec<_> = list
        .iter()
        .map(|member| crate::error::first_os_code(&**member))
        .collect();
    assert_eq!(codes, order.iter().map(|pid| Some(os_code(*pid))).collect::<Vec<_>>());
    for other in &order[1..] {
        let member = list
            .iter()
            .nth(order.iter().position(|pid| pid == other).expect("listed"))
            .expect("a member");
        assert!(
            matches!(&**member, Error::Unassessable { detail, .. } if *detail == format!("cause of {other}")),
            "{member:?}"
        );
    }
}

/// When the first unassessed candidate's error is an `Error::Io` (a leaf, with no slot for peers), the
/// answer is an `Unassessable` with that `Io` and every other candidate's error below it, in order.
///
/// Mutants: the others are dropped behind the `Io`; the `Io` is returned bare.
#[skuld::test]
fn complete_members_keeps_every_candidate_below_an_unassessable_when_the_first_is_an_io_error() {
    let parents = [(200, ROOT_PID), (300, ROOT_PID)];
    let got = descendants_with(root(), root_bound(), &parents, |pid, _, _| {
        let code = if pid == 200 { 2 } else { 3 };
        Err(if pid == 200 {
            Error::Io(std::io::Error::from_raw_os_error(code))
        } else {
            Error::Unassessable {
                detail: "the second".to_owned(),
                source: Some(Error::io_cause(std::io::Error::from_raw_os_error(code))),
            }
        })
    });
    let order: Vec<RawPid> = got.unassessed.iter().map(|(pid, _)| *pid).collect();
    assert_eq!(order, [200, 300]);

    let error = got.complete_members().expect_err("two candidates were not assessed");

    let Error::Unassessable {
        source: Some(source), ..
    } = &error
    else {
        panic!("expected Unassessable, got {error:?}");
    };
    let Error::Several(list) = &**source else {
        panic!("expected Several, got {source:?}");
    };
    let codes: Vec<_> = list
        .iter()
        .map(|member| crate::error::first_os_code(&**member))
        .collect();
    assert_eq!(codes, [Some(2), Some(3)]);
}

/// A snapshot that lists the unreadable pid twice reads it once and counts it once.
#[skuld::test]
fn a_duplicate_edge_to_an_unreadable_candidate_is_one_unassessed_entry() {
    let parents = [(200, ROOT_PID), (200, ROOT_PID)];
    let got = descendants_with(root(), root_bound(), &parents, |pid, _, _| Err(unreadable(pid)));
    assert_eq!(unassessed(&got), [200]);
    assert!(got.members.is_empty());
}

/// Only a candidate the resolver finds gone is logged as "gone, or an impostor"; one it errs on was
/// warned where the read was made, and the filters say nothing more of it. The pids are this row's
/// own, as the capture is shared by parallel rows. Mutant: the `Err` arm logs the same line.
#[skuld::test]
fn only_a_gone_candidate_is_logged_as_gone_or_an_impostor() {
    use super::children_of_with;
    const UNREADABLE: RawPid = 61_001;
    const GONE: RawPid = 61_002;
    crate::log_capture::install();
    let parents = [(UNREADABLE, ROOT_PID), (GONE, ROOT_PID)];
    let resolve = |pid: RawPid, _parent: ProcessId, _bound: Option<OrderKey>| -> Resolution {
        if pid == UNREADABLE {
            Err(unreadable(pid))
        } else {
            Ok(None)
        }
    };
    let mark = crate::log_capture::mark();
    descendants_with(root(), root_bound(), &parents, resolve);
    children_of_with(root(), root_bound(), &parents, resolve);
    assert!(crate::log_capture::contains_since(
        mark,
        &format!("pid {GONE} gone, or an impostor")
    ));
    assert!(!crate::log_capture::contains_since(
        mark,
        &format!("pid {UNREADABLE} gone, or an impostor")
    ));
}

#[skuld::test]
fn an_unreadable_direct_child_is_unassessed_in_the_one_level_filter_too() {
    use super::children_of_with;
    let parents = [(200, ROOT_PID), (200, ROOT_PID), (300, ROOT_PID), (400, 200)];
    let tokens = HashMap::from([(300u32, ROOT_TOKEN + 5)]);
    let read = resolver(&tokens);
    let got = children_of_with(root(), root_bound(), &parents, |pid, parent, bound| {
        if pid == 200 {
            Err(unreadable(200))
        } else {
            read(pid, parent, bound)
        }
    });
    assert_eq!(unassessed(&got), [200]);
    assert_eq!(pids(got), [300]);
}

/// A pid is resolved once however many edges list it: when its first read finds it and a second
/// would be `Unknown`, it is a member, listed once, and not unassessed. Mutant: the one-level filter
/// resolves each duplicate edge again.
#[skuld::test]
fn a_duplicate_edge_is_resolved_once_in_both_filters() {
    use super::children_of_with;
    use std::cell::Cell;

    let parents = [(200, ROOT_PID), (200, ROOT_PID)];
    let reads = Cell::new(0);
    let first_reads_second_does_not = |pid: RawPid, _parent: ProcessId, _bound: Option<OrderKey>| {
        reads.set(reads.get() + 1);
        if reads.get() == 1 {
            Ok(Some(resolved(pid, ROOT_TOKEN + 5)))
        } else {
            Err(unreadable(pid))
        }
    };
    let got = children_of_with(root(), root_bound(), &parents, first_reads_second_does_not);
    assert_eq!((pids(got), reads.get()), (vec![200], 1), "one level");

    reads.set(0);
    let got = descendants_with(root(), root_bound(), &parents, first_reads_second_does_not);
    assert!(got.unassessed.is_empty(), "{:?}", got.unassessed);
    assert_eq!((pids(got), reads.get()), (vec![200], 1), "whole subtree");
}

// One-level child filter keeps only genuine direct children =====

#[skuld::test]
fn children_of_keeps_one_level_genuine_children_only() {
    use super::children_of_with;
    // root 100; direct child 101; grandchild 102 (ppid 101, not one level); 103 ppid 100, which the
    // resolver finds gone (an impostor, or exited).
    let root = id(100, 50);
    let parents = [(101, 100), (102, 101), (103, 100)];
    let tokens = HashMap::from([(101u32, 60), (102u32, 70)]);
    let got = children_of_with(root, bound_of(50), &parents, resolver(&tokens));
    assert!(got.unassessed.is_empty());
    assert_eq!(pids(got), [101]);
}

// A duplicate edge enumerates a direct child only once =====

#[skuld::test]
fn children_of_duplicate_edge_yields_pid_once() {
    use super::children_of_with;
    // A snapshot listing the same (pid, ppid) edge twice must not enumerate (or later
    // double-kill) the same child twice.
    let root = id(100, ROOT_TOKEN);
    let parents = [(101, 100), (101, 100)];
    let tokens = HashMap::from([(101u32, ROOT_TOKEN + 1)]);
    assert_eq!(
        pids(children_of_with(root, root_bound(), &parents, resolver(&tokens))),
        [101],
        "duplicate edge collapses to a single child"
    );
}

/// The resolver is told the accepted process the snapshot made each candidate's parent, so a backend
/// can drop a candidate whose parent's number has another holder now, and the bound it must follow:
/// the accepted parent's, which the resolver handed out with it. The parent of a grandchild is the
/// id the walk accepted for the child. Mutants: "the resolver is asked the root for every
/// candidate"; "the bound is the root's for a deeper candidate".
#[skuld::test]
fn the_resolver_is_asked_for_each_candidates_accepted_parent() {
    use std::cell::RefCell;

    use super::children_of_with;

    let asked = RefCell::new(Vec::new());
    let resolve = |pid: u32, parent: ProcessId, bound: Option<OrderKey>| -> Resolution {
        asked.borrow_mut().push((pid, parent, bound));
        Ok(Some(resolved(pid, ROOT_TOKEN + 1)))
    };
    let parents = [(200, ROOT_PID), (300, 200)];
    descendants_with(root(), root_bound(), &parents, resolve);
    assert_eq!(
        asked.take(),
        [
            (200, root(), root_bound()),
            (300, id(200, ROOT_TOKEN + 1), bound_of(ROOT_TOKEN + 1))
        ]
    );

    children_of_with(root(), root_bound(), &parents, resolve);
    assert_eq!(asked.take(), [(200, root(), root_bound())]);
}

/// The bound the filters hand the resolver for the root's children is the `root_bound` argument,
/// not the root id's token: here the root's token is `ROOT_TOKEN` and its bound is another number,
/// or none, as where no order is relied on. Mutants: "the filters hand out `root.key()`"; "the
/// filters hand out a bound the platform did not give".
#[skuld::test]
fn the_bound_is_the_roots_bound_not_its_id_token() {
    use std::cell::RefCell;

    use super::children_of_with;
    let parents = [(200, ROOT_PID)];
    let asked = RefCell::new(Vec::new());
    let resolve = |pid: u32, _parent: ProcessId, bound: Option<OrderKey>| -> Resolution {
        asked.borrow_mut().push((pid, bound));
        Ok(None)
    };
    for bound in [bound_of(ROOT_TOKEN - 500), None] {
        descendants_with(root(), bound, &parents, resolve);
        assert_eq!(asked.take(), [(200, bound)], "descendants_with");
        children_of_with(root(), bound, &parents, resolve);
        assert_eq!(asked.take(), [(200, bound)], "children_of_with");
    }
}

/// What the live anchor hands the walk as its children's bound: where the platform orders by
/// creation (Windows) the root's order key, elsewhere none, read through `anchor` itself (this
/// process, live) and not stated. Mutants: the anchor hands out a bound off Windows; it hands out
/// none on Windows.
#[skuld::test]
fn the_anchor_hands_out_a_bound_only_on_windows() {
    let proof = super::anchor(&crate::identity::HostKernel, ProcessId::current())
        .expect("this process reads")
        .expect("this process is live");
    assert_eq!(proof.bound.is_some(), crate::identity::ORDER_AFTER_PARENT);
}

/// `resolve_or_drop` is a named discard site: an access-denied descendant must be dropped
/// from the walk as an error naming it, never be silently folded in with a gone pid. The walk's
/// caller reports it ([`super::warn_unassessed`]), so the walk itself logs nothing.
#[cfg(windows)]
#[skuld::test]
fn resolve_or_drop_drops_an_access_denied_pid_as_an_error() {
    let Some(done) = crate::test_own_process::own_process(
        crate::test_own_process::test_path!(resolve_or_drop_drops_an_access_denied_pid_as_an_error),
        crate::test_spawn::spawn,
    ) else {
        return;
    };
    use windows::Win32::System::Threading::PROCESS_SYNCHRONIZE;
    crate::log_capture::install();
    let denied = crate::identity::windows_fixture::spawn_restricted(&done, PROCESS_SYNCHRONIZE.0);
    assert!(denied.is_running(), "precondition: the subject must be live");
    let mark = crate::log_capture::mark();
    let Err(Error::Unassessable { detail, .. }) =
        super::resolve_or_drop(&crate::identity::HostKernel, denied.pid(), ProcessId::current(), None)
    else {
        panic!("the walk cannot keep what it cannot verify, and an unread pid is not a gone one");
    };
    assert!(
        detail.contains(&format!("pid {} exists but could not be queried", denied.pid())),
        "{detail}"
    );
    assert!(
        !crate::log_capture::contains_since(mark, &format!("treewalk: pid {}", denied.pid())),
        "the walk's caller reports it, not the walk"
    );
    assert!(denied.is_running(), "and dropping it must not have touched it");
}

/// The text of `resolve_or_drop`'s warn for a candidate whose creator-pid query was refused: the
/// cause reaches `unqueryable_read`, which words it, so the warn names the pid and the query, and
/// it does not fall back to "access denied?".
///
/// The failed query itself is not driven through the walk: forcing one needs a hook in production
/// code, and Windows has no `FakeKernel` methods to state it in.
///
/// Mutant: `into_error` drops the creator status.
#[cfg(windows)]
#[skuld::test]
fn a_refused_creator_query_is_worded_with_its_status_in_the_walks_warn_on_windows() {
    let refused = windows::Win32::Foundation::NTSTATUS(0xC000_0004_u32 as i32);
    let cause = crate::identity::UnknownCause::default().with_creator_status(refused);
    let error = crate::identity::unqueryable_read("pid", 7, cause);
    let crate::error::Error::Unassessable { detail, .. } = &error else {
        panic!("a refused creator query is Unassessable");
    };
    assert_eq!(detail, "pid 7 exists but its creator process id query failed");
    // `STATUS_INFO_LENGTH_MISMATCH` as its Win32 code, `ERROR_BAD_LENGTH`.
    assert_eq!(
        crate::error::first_os_code(&error),
        Some(windows::Win32::Foundation::ERROR_BAD_LENGTH.0 as i32)
    );
}

/// The Windows wiring of the walk to the creator read, through `walk_from` with real
/// processes: `x` and `y` are both children of the root (this process). A snapshot that names `x` as
/// `y`'s parent is a stale creator edge: `y`'s own creator is the root, so it is dropped under `x`
/// and kept under the root. `x` is spawned first, so `y`'s key follows `x`'s and the parent-order
/// rule passes the edge: only the creator read drops `y`. (A real edge that breaks the rule names a
/// creator that is not the process's, which the creator read catches first, so the `judged` and
/// bound rows pin that rule.)
/// Mutant: `resolve_or_drop` passes no parent to the read.
#[cfg(windows)]
#[skuld::test]
fn a_real_candidate_is_dropped_under_a_parent_that_is_not_its_creator_on_windows() {
    use crate::identity::HostKernel;
    use crate::test_child::{live_findstr_blocker, release_findstr_unterminated};

    use crate::Recursive;

    let root = ProcessId::current();
    let (x_child, x) = live_findstr_blocker();
    let (y_child, y) = live_findstr_blocker();

    // The root's own row is not read, only the rows that name it as a parent.
    let stale_creator = [(x.pid(), root.pid()), (y.pid(), x.pid())];
    let dropped = super::walk_from(&HostKernel, root, &stale_creator, Recursive::Yes)
        .expect("the root reads")
        .expect("the root is live");
    let genuine = [(x.pid(), root.pid()), (y.pid(), root.pid())];
    let kept = super::walk_from(&HostKernel, root, &genuine, Recursive::Yes)
        .expect("the root reads")
        .expect("the root is live");

    release_findstr_unterminated(x_child);
    release_findstr_unterminated(y_child);
    // A stale creator is dropped as `Gone`, not as unassessed: both of this process's children read.
    assert!(dropped.unassessed.is_empty() && kept.unassessed.is_empty());
    assert_eq!(dropped.members, vec![x]);
    assert_eq!(kept.members, vec![x, y]);
}

/// A root that exits while its handle is held is walked, and its running child is killed. Windows
/// does not reparent: the child's creator pid is still the root's. Toolhelp does not list an exited
/// process whose handle is held (measured on Windows 11 26100.9711), so the snapshot has no row for
/// the root while the walk's edges, which name it as the child's parent, are intact: a missing root
/// row says nothing about them. The root's order key and creator are read from its own handle, which
/// is held.
///
/// The root is a `cmd.exe` that holds its `more.com` child, blocked on a stdin this test holds: it is
/// released (and exits `0`) only after `hard_kill`, so a kill that did not happen fails the assertion
/// on its exit code instead of hanging the wait.
///
/// Mutant: a root with no row in the snapshot is `Unassessable`, or walks nothing.
#[cfg(windows)]
#[skuld::test]
fn a_root_that_exited_while_its_handle_is_held_is_walked_and_its_child_killed() {
    use std::process::Stdio;

    use windows::Win32::Foundation::WAIT_OBJECT_0;
    use windows::Win32::System::Threading::{
        GetExitCodeProcess, WaitForSingleObject, INFINITE, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
    };

    use crate::identity::{windows_close, windows_open_classified, HostKernel, Opened};
    use crate::Recursive;

    // The std `Child` holds the root's process handle until it is dropped, at the end of the row.
    let more = crate::test_child::windows_more();
    let mut shell = crate::test_spawn::spawn(
        std::process::Command::new("cmd.exe")
            .arg("/c")
            .arg(&more)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped()),
    )
    .expect("spawn the root");
    let root = ProcessId::of(shell.id()).found().expect("the live root resolves");
    // `more` inherits the root's pipes. It echoes a line as it reads it, so the first byte read
    // back says it exists. Both pipes stay open: `std`'s `wait` would close the stdin, which ends
    // `more`, and a closed stdout would end it too.
    let mut stdin = shell.stdin.take().expect("piped stdin");
    std::io::Write::write_all(&mut stdin, b"x\r\n").expect("feed the child a line");
    let mut first = [0u8; 1];
    let read = std::io::Read::read(shell.stdout.as_mut().expect("piped stdout"), &mut first).expect("read the echo");
    assert_eq!(read, 1, "the root closed its output before its child echoed");
    // The root's children are its console host and its `more`.
    let children = root.children(Recursive::No).expect("the root's children");
    let held = children
        .into_iter()
        .find(|id| crate::identity::windows_fixture::is_more_com(id.pid()))
        .expect("the root has a `more` child")
        .pid();
    let Opened::Found(held_handle) =
        windows_open_classified(held, PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION)
    else {
        panic!("the child is ours and openable");
    };
    shell.kill().expect("terminate the root");
    shell.wait().expect("the root's exit is recorded");

    let parents = crate::test_child::parents_once_unlisted(root.pid());
    assert!(
        parents.iter().any(|&(pid, ppid)| pid == held && ppid == root.pid()),
        "precondition: the running child must still name the exited root as its creator"
    );

    let children = root.children(Recursive::No).expect("the exited root's children");
    assert!(
        children.iter().any(|id| id.pid() == held),
        "{held} not among {children:?}"
    );
    super::hard_kill(&HostKernel, root, &super::ByIdentity::new(&HostKernel, root))
        .outcome()
        .into_result()
        .expect("an exited root whose handle is held is walked completely");

    // Released only now: a kill that never came ends the child by itself, with code 0, which the
    // assertion below fails.
    drop(stdin);
    // SAFETY: `held_handle` is our live handle with the synchronize right. The wait ends with the
    // kill just asked for, or with the child's release.
    let waited = unsafe { WaitForSingleObject(held_handle, INFINITE) };
    assert_eq!(waited, WAIT_OBJECT_0, "the wait on the child returned {waited:?}");
    let mut code = 0u32;
    // SAFETY: `held_handle` is live with the query right; `code` is a u32.
    unsafe { GetExitCodeProcess(held_handle, &mut code) }.expect("the child's exit code");
    windows_close(held_handle);
    assert_eq!(
        code,
        crate::identity::WINDOWS_TERMINATE_EXIT_CODE,
        "the walk must have terminated the child"
    );
}

/// The handle a walk sends a member's kill through is open for the member's exit: it can be waited
/// on once the kill is sent. A handle opened for `PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION`
/// alone cannot (`WaitForSingleObject` answers `ERROR_ACCESS_DENIED`).
///
/// Mutant: the walk opens its member without `SYNCHRONIZE`.
#[cfg(windows)]
#[skuld::test]
fn a_walk_members_handle_can_be_waited_on_after_its_kill() {
    // The blocker's stdin stays open, so only the kill ends it.
    let (_child, _stdin, id) = crate::test_child::live_blocker();
    let os = super::open_by_identity(&crate::identity::HostKernel, id)
        .expect("a live member opens")
        .expect("a live member is not gone");
    // A handle without `SYNCHRONIZE` cannot show that a running member is running: its look fails.
    assert!(
        matches!(os.exited(), Ok(crate::os_process::Exit::Running(_))),
        "a live member's handle is waited on, not refused"
    );
    let outcome = super::KillOutcome::of(os.signal(crate::signal::Sig::Kill));
    assert!(matches!(outcome, super::KillOutcome::Terminated), "{outcome:?}");
    assert!(
        crate::os_process::drive::exited_held(&*os, None).expect("the member's handle can be waited on"),
        "the wait ended on the member's exit"
    );
}

/// `kill_by_identity`-s pre-open Denied arm - the outcome that can leave a process running.
#[cfg(windows)]
#[skuld::test]
fn kill_by_identity_reports_not_attempted_when_the_open_is_denied() {
    let Some(done) = crate::test_own_process::own_process(
        crate::test_own_process::test_path!(kill_by_identity_reports_not_attempted_when_the_open_is_denied),
        crate::test_spawn::spawn,
    ) else {
        return;
    };
    let child = crate::identity::windows_fixture::spawn_unkillable(&done);
    let id = crate::identity::windows_identity_from_handle_result(child.handle(), child.pid())
        .expect("the owned handle always yields an identity");
    assert!(child.is_running(), "precondition: the subject must be live");
    let outcome = super::kill_by_identity(id);
    assert!(matches!(outcome, super::KillOutcome::NotAttempted(_)), "{outcome:?}");
    assert!(child.is_running(), "a denied open must leave the process running");
}

/// A root the walk may read but not terminate is left running, and `hard_kill` is an error naming it
/// and why: the open succeeds with the rights the process grants, and the kill is refused. Mutant:
/// `hard_kill` drops a `NotAttempted` outcome.
#[cfg(windows)]
#[skuld::test]
fn hard_kill_of_a_root_it_may_read_but_not_terminate_is_an_error_naming_it() {
    let Some(done) = crate::test_own_process::own_process(
        crate::test_own_process::test_path!(hard_kill_of_a_root_it_may_read_but_not_terminate_is_an_error_naming_it),
        crate::test_spawn::spawn,
    ) else {
        return;
    };
    // Readable by pid, but not terminable: the walk anchors on it, and its kill is refused.
    let child = crate::identity::windows_fixture::spawn_query_only(&done);
    let id = crate::identity::windows_identity_from_handle_result(child.handle(), child.pid())
        .expect("the owned handle always yields an identity");
    assert!(child.is_running(), "precondition: the subject must be live");
    let kernel = crate::identity::HostKernel;
    match super::hard_kill(&kernel, id, &super::ByIdentity::new(&kernel, id))
        .outcome()
        .into_result()
    {
        Err(super::Unkilled {
            members,
            root: Some(root),
            ..
        }) if members.is_empty() => {
            let crate::error::Error::MemberNotKilled { pid, source, .. } = *root else {
                panic!("expected MemberNotKilled for the root, got {root:?}");
            };
            assert_eq!(pid, child.pid());
            // The open drops the terminate right the process refuses, and the kill is the OS's
            // refusal, with its error.
            assert!(
                matches!(*source, crate::error::Error::Io(_)),
                "a refused kill is the OS's error: {source:?}"
            );
            assert_eq!(
                crate::error::first_os_code(&*source),
                Some(windows::Win32::Foundation::ERROR_ACCESS_DENIED.0 as i32),
                "{source:?}"
            );
        }
        other => panic!("expected MemberNotKilled for the root, got {other:?}"),
    }
    assert!(child.is_running(), "a refused kill must leave the process running");
}

/// A member the OS refuses the signal is left running, and `hard_kill`'s error carries the refusal's
/// OS error, so a caller can tell it from one that could not be read. A setuid-root helper refuses
/// the kill of its caller. Mutant: the refusal is flattened to text.
#[cfg(unix)]
#[skuld::test]
fn hard_kill_of_a_root_that_refuses_the_signal_is_an_error_carrying_the_errno(
    #[fixture(setuid)] _group: &crate::test_groups::Group,
) {
    let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let kernel = crate::identity::HostKernel;
    let left = super::hard_kill(&kernel, id, &super::ByIdentity::new(&kernel, id))
        .outcome()
        .into_result()
        .expect_err("the kill is refused");
    assert!(left.members.is_empty(), "the root is the only member the walk left");
    let err = left.root.expect("the root was left");
    // The message names the pid; the OS's own words are the source, each layer said once.
    let os = std::io::Error::from_raw_os_error(libc::EPERM);
    assert_eq!(err.to_string(), format!("pid {} was not killed", child.pid()));
    assert_eq!(
        crate::error::said(&err),
        format!("pid {} was not killed: {}", child.pid(), crate::error::io_said(&os))
    );
    match *err {
        crate::error::Error::MemberNotKilled { pid, source, .. } => {
            assert_eq!(pid, child.pid());
            assert!(
                matches!(*source, crate::error::Error::Io(ref e) if e.raw_os_error() == Some(libc::EPERM)),
                "{source:?}"
            );
        }
        other => panic!("expected MemberNotKilled, got {other:?}"),
    }
    // The helper exits at EOF: nothing killed it.
    drop(stdin);
    assert!(child.wait().expect("the helper exits on EOF").success());
}

/// A descendant the OS refuses the signal is left running by the walk's own loop: the error names it,
/// with the refusal's OS error, and the root, which was killed, is not among what is left. A
/// setuid-root helper under a plain root refuses the kill of its caller.
///
/// Mutants: the loop drops a refused descendant's error; the root is reported left beside it.
#[cfg(unix)]
#[skuld::test]
fn hard_kill_of_a_descendant_that_refuses_the_signal_is_an_error_naming_it_with_the_errno(
    #[fixture(setuid)] _group: &crate::test_groups::Group,
) {
    let (child, stdin) = crate::test_privilege::root_over_setuid_blockers(1, |_| {});

    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let kernel = crate::identity::HostKernel;
    let left = super::hard_kill(&kernel, id, &super::ByIdentity::new(&kernel, id))
        .outcome()
        .into_result()
        .expect_err("the helper refuses the kill");

    assert!(left.root.is_none(), "the root was killed: {:?}", left.root);
    assert_eq!(left.members.len(), 1, "{:?}", left.members);
    match &left.members[0] {
        crate::error::Error::MemberNotKilled { pid, source, .. } => {
            assert_ne!(*pid, child.pid(), "the helper, not the root");
            assert!(
                matches!(**source, crate::error::Error::Io(ref e) if e.raw_os_error() == Some(libc::EPERM)),
                "{source:?}"
            );
        }
        other => panic!("expected MemberNotKilled, got {other:?}"),
    }
    // The helper exits at EOF: nothing killed it.
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().expect("reap the root"));
}

/// `Process::kill_tree` of a root that refuses the signal: nothing after the walk kills the root, so
/// it is left, and the error names it with the refusal's OS error.
///
/// Mutant: a root the walk left is dropped from the report as if its kill had ended it.
#[cfg(unix)]
#[skuld::test]
fn process_kill_tree_of_a_root_that_refuses_the_signal_names_the_root(
    #[fixture(setuid)] _group: &crate::test_groups::Group,
) {
    let (child, stdin) = crate::test_privilege::spawn_setuid_blocker();
    let process = crate::Process::open_pid(child.pid()).expect("open").expect("running");

    let err = process.kill_tree().expect_err("the root refuses the kill");

    let crate::error::Error::MembersLeft { members, .. } = &err else {
        panic!("expected MembersLeft, got {err:?}");
    };
    let [member] = &members.iter().collect::<Vec<_>>()[..] else {
        panic!("the root is the one member left: {members:?}");
    };
    match &***member {
        crate::error::Error::MemberNotKilled { pid, source, .. } => {
            assert_eq!(*pid, child.pid());
            assert!(
                matches!(&**source, crate::error::Error::Io(e) if e.raw_os_error() == Some(libc::EPERM)),
                "{source:?}"
            );
        }
        other => panic!("expected MemberNotKilled, got {other:?}"),
    }
    drop(stdin);
    assert!(child.wait().expect("the helper exits on EOF").success());
}

/// `Process::kill_tree` of a tree with two members that refuse the signal: the error holds both, each
/// named once with the refusal's OS error, and nothing is warned of one by one.
///
/// Mutants: a member is dropped; one is named twice; the members are warned of as well as returned.
#[cfg(unix)]
#[skuld::test]
fn process_kill_tree_returns_every_refusing_member_and_warns_of_none(
    #[fixture(setuid)] _group: &crate::test_groups::Group,
) {
    crate::log_capture::install();
    let (child, stdin) = crate::test_privilege::root_over_setuid_blockers(2, |_| {});
    let process = crate::Process::open_pid(child.pid()).expect("open").expect("running");
    let mark = crate::log_capture::mark();

    let err = process.kill_tree().expect_err("two members refuse the kill");

    let crate::error::Error::MembersLeft { members, .. } = &err else {
        panic!("expected MembersLeft, got {err:?}");
    };
    let mut pids = Vec::new();
    for member in members.iter() {
        let crate::error::Error::MemberNotKilled { pid, .. } = &**member else {
            panic!("expected MemberNotKilled, got {member:?}");
        };
        assert_eq!(crate::error::first_os_code(&**member), Some(libc::EPERM), "{member:?}");
        pids.push(*pid);
    }
    pids.sort_unstable();
    pids.dedup();
    assert_eq!(pids.len(), 2, "each refusing member is named once: {members:?}");
    let warned = crate::log_capture::warns_since(mark, "was not killed");
    assert!(warned.is_empty(), "the members are in the error: {warned:?}");
    drop(stdin);
    crate::test_child::assert_killed("the root", child.wait().expect("reap the root"));
}

/// `terminate` is best effort: a member that refuses the `SIGTERM` is warned of once, with its pid and
/// the OS's refusal, and the call is `Ok`.
///
/// Mutants: the refusal is not warned of; it is warned of twice.
#[cfg(unix)]
#[skuld::test]
fn terminate_warns_once_of_a_member_that_refuses_the_signal(#[fixture(setuid)] _group: &crate::test_groups::Group) {
    crate::log_capture::install();
    let (child, stdin) = crate::test_privilege::root_over_setuid_blockers(1, |_| {});
    let mark = crate::log_capture::mark();

    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    let kernel = crate::identity::HostKernel;
    super::terminate(&kernel, id, &super::ByIdentity::new(&kernel, id)).expect("best effort");

    let os = std::io::Error::from_raw_os_error(libc::EPERM);
    let warned = crate::log_capture::warns_since(mark, "was sent no SIGTERM");
    assert_eq!(warned.len(), 1, "{warned:?}");
    assert!(warned[0].starts_with("treewalk: pid "), "{warned:?}");
    assert!(warned[0].contains(&os.to_string()), "{warned:?}");
    drop(stdin);
    child.wait().expect("reap the root");
}

/// `kill_by_identity` must terminate only the process whose START TOKEN matches. A stale
/// identity names a recycled pid, and killing it would kill a stranger.
#[cfg(windows)]
#[skuld::test]
fn kill_by_identity_spares_a_stale_identity_and_kills_a_matching_one() {
    let Some(done) = crate::test_own_process::own_process(
        crate::test_own_process::test_path!(kill_by_identity_spares_a_stale_identity_and_kills_a_matching_one),
        crate::test_spawn::spawn,
    ) else {
        return;
    };
    use windows::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
    // The ACE must grant QUERY_LIMITED: the open needs it to verify the identity, and drops each of
    // SYNCHRONIZE and TERMINATE that the process refuses.
    let (child, stdin) =
        crate::identity::windows_fixture::spawn_restricted_releasable(&done, PROCESS_QUERY_LIMITED_INFORMATION.0);
    let real = crate::identity::windows_identity_from_handle_result(child.handle(), child.pid())
        .expect("the owned handle always yields an identity");
    let stale = real.with_other_value();

    let outcome = super::kill_by_identity(stale);
    assert!(
        matches!(outcome, super::KillOutcome::AlreadyGone),
        "a stale identity names a process that is gone - nothing to terminate: {outcome:?}"
    );
    assert!(
        child.is_running(),
        "a stale identity must never terminate the pid-s occupant"
    );

    let outcome = super::kill_by_identity(real);
    assert!(
        matches!(outcome, super::KillOutcome::Terminated),
        "a matching identity must reach TerminateProcess: {outcome:?}"
    );
    // The child reads `stdin` to its end and exits 0, so a kill that sent nothing ends the wait
    // below with that code, not with the kill's `1`.
    drop(stdin);
    child.await_exit();
    assert_eq!(
        child.exit_code(),
        1,
        "a matching identity must terminate the process, not leave it to exit when released"
    );
}

/// A member that exits between `kill_by_identity`'s identity check and its `TerminateProcess`
/// is gone, not a failed kill: Windows refuses `TerminateProcess` on an exited process with
/// `ERROR_ACCESS_DENIED`. Mutant: the error arm warns and answers `NotAttempted` unconditionally.
#[cfg(windows)]
#[skuld::test]
fn kill_by_identity_reports_a_member_that_exits_before_the_terminate_as_gone() {
    let Some(done) = crate::test_own_process::own_process(
        crate::test_own_process::test_path!(kill_by_identity_reports_a_member_that_exits_before_the_terminate_as_gone),
        crate::test_spawn::spawn,
    ) else {
        return;
    };
    use windows::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
    let _watch = crate::log_capture::warn_watch();
    let (child, _stdin) =
        crate::identity::windows_fixture::spawn_restricted_releasable(&done, PROCESS_QUERY_LIMITED_INFORMATION.0);
    let child = std::rc::Rc::new(child);
    let id = crate::identity::windows_identity_from_handle_result(child.handle(), child.pid())
        .expect("the owned handle always yields an identity");
    let exiter = std::rc::Rc::clone(&child);
    super::fault::set_before_terminate(move || exiter.terminate());

    let outcome = super::kill_by_identity(id);
    assert!(
        matches!(outcome, super::KillOutcome::AlreadyGone),
        "a member that exited before the terminate has nothing left to kill: {outcome:?}"
    );
    assert!(!child.is_running(), "precondition: the hook ended the member");
}

/// A member whose exit is under way but not yet signalled is gone, not a failed kill, and
/// `hard_kill` stays complete.
///
/// Mutant: a refusal is gone only once the process reads signalled, so this one warns and answers
/// `NotAttempted`.
#[cfg(windows)]
#[skuld::test]
fn kill_by_identity_reports_a_member_that_is_exiting_but_not_signalled_as_gone() {
    use std::os::windows::io::AsRawHandle;
    let mut child = crate::test_spawn::spawn(
        std::process::Command::new("cmd")
            .args(["/C", "more"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null()),
    )
    .expect("spawn cmd /C more");
    let id = crate::identity::windows_identity_from_handle_result(
        windows::Win32::Foundation::HANDLE(child.as_raw_handle()),
        child.id(),
    )
    .expect("the owned handle always yields an identity");
    let _refusal = crate::identity::windows_fault::refuse_next_terminate_as_exiting();
    let outcome = super::kill_by_identity(id);
    // The seam sent no terminate: end the fixture before asserting.
    child.kill().expect("end the fixture");
    child.wait().expect("reap the fixture");

    assert!(matches!(outcome, super::KillOutcome::AlreadyGone), "{outcome:?}");
}

/// A walk guards itself by proving its root still holds its pid, so off macOS `kill_tree` and
/// `terminate_tree` walk whatever the root's state says; on macOS they skip a root the handle cannot
/// vouch for (`Unpinned`, `Unknown`) and walk the rest. The root here holds no such pid, so a walk
/// that ran finds no root and kills nothing.
///
/// Mutant: `skipped_walk` skips on `Unknown` or `Reaped` off macOS.
#[cfg(unix)]
#[skuld::test]
fn a_walk_is_skipped_by_the_roots_state_only_on_macos() {
    use crate::containment::dispatch::TreeKillOutcome;
    use crate::containment::TerminateOutcome;
    use crate::signal::RootState;
    use crate::test_support::stated_root::StatedRoot;

    /// A state, and whether macOS cannot vouch for a root in it.
    type Case = (&'static str, fn() -> RootState, bool);
    let states: [Case; 5] = [
        ("unreaped", || RootState::Unreaped, false),
        ("reaped, own", || RootState::Reaped { own: true }, false),
        ("reaped elsewhere", || RootState::Reaped { own: false }, false),
        (
            "unknown",
            || RootState::Unknown(std::sync::Arc::new(std::io::Error::other("forced"))),
            true,
        ),
        ("unpinned", || RootState::Unpinned, true),
    ];
    for (name, state, untrusted) in states {
        let skipped = untrusted && cfg!(target_os = "macos");
        let root = StatedRoot::with_state(ROOT_PID, state);
        let killed = super::kill_tree(self::root(), Some(&root)).outcome();
        assert_eq!(
            matches!(killed, TreeKillOutcome::Skipped(_)),
            skipped,
            "kill, {name}: {killed:?}"
        );
        if !skipped {
            assert!(matches!(killed, TreeKillOutcome::NoRoot), "kill, {name}: {killed:?}");
        }
        let termed = super::terminate_tree(&crate::identity::HostKernel, self::root(), Some(&root));
        assert_eq!(
            matches!(termed, TerminateOutcome::End(_)),
            skipped,
            "terminate, {name}: {termed:?}"
        );
    }
}

/// The held member's `source` is the first report's own `Arc`.
///
/// Mutant: the held member copies the cause or drops the note.
#[skuld::test]
fn a_member_never_read_is_held_with_its_own_cause() {
    use super::{not_killed, Left};
    use crate::containment::dispatch::Unkilled;
    let code = if cfg!(windows) { 5 } else { 13 };
    let Error::MemberNotKilled { pid, source, .. } = not_killed(
        7,
        Error::Unassessable {
            detail: "pid 7 identity could not be confirmed".into(),
            source: Some(std::sync::Arc::new(Error::Containment {
                detail: "the middle layer".into(),
                source: Some(Error::io_cause(std::io::Error::from_raw_os_error(code))),
            })),
        },
    ) else {
        unreachable!("`not_killed` builds a `MemberNotKilled`");
    };
    let member = Error::MemberNotKilled {
        pid,
        source: std::sync::Arc::clone(&source),
    };
    let first = Unkilled {
        members: vec![member],
        root: None,
        resolved: Vec::new(),
    };

    let held = Left::of(&first);

    let [Left::Unread { pid: 7, source: held }] = held.as_slice() else {
        panic!("never read: {held:?}");
    };
    assert!(
        std::sync::Arc::ptr_eq(held, &source),
        "the held source is the member's own"
    );
    assert_eq!(crate::error::first_os_code(&**held), Some(code), "{held:?}");
}

/// A member the walk never read, held over two later `kill_left` rounds, is reported each time as the
/// first round reported it: the `Report` does not grow a layer per round, and a bare OS error stays an
/// `Error::Io` with its code on the `io::Error`, where a caller matches it.
///
/// Each round's member is the first round's own: its `source` is the same `Arc`.
///
/// Mutants: a round wraps the held cause in another layer; the held cause is rebuilt as another
/// variant, so the code is no longer on the `Error::Io`; a round rebuilds the source from parts, so
/// it is not the first round's.
#[skuld::test]
fn a_member_never_read_is_reported_the_same_over_every_round() {
    use super::{not_killed, with_earlier, Left};
    use crate::containment::dispatch::Unkilled;
    let code = if cfg!(windows) { 5 } else { 13 };
    let bare = || std::io::Error::from_raw_os_error(code);
    let layered = || Error::Containment {
        detail: "the middle layer".into(),
        source: Some(Error::io_cause(crate::error::io_context("w", bare()))),
    };
    for (what, below) in [
        ("a bare OS error", Error::Io(bare())),
        ("layers over an OS error", layered()),
    ] {
        let Error::MemberNotKilled { pid, source, .. } = not_killed(
            7,
            Error::Unassessable {
                detail: "pid 7 identity could not be confirmed".into(),
                source: Some(std::sync::Arc::new(below)),
            },
        ) else {
            unreachable!("`not_killed` builds a `MemberNotKilled`");
        };
        let mut round = Unkilled {
            members: vec![Error::MemberNotKilled {
                pid,
                source: std::sync::Arc::clone(&source),
            }],
            root: None,
            resolved: Vec::new(),
        };
        let first = crate::error::said(&round.members[0]);
        for n in 2..=3 {
            let held = Left::of(&round);
            round = with_earlier(&crate::identity::HostKernel, held, Ok(()))
                .0
                .expect_err("never read, so never shown killed");
            assert_eq!(crate::error::said(&round.members[0]), first, "{what}, round {n}");
            let Error::MemberNotKilled { source: again, .. } = &round.members[0] else {
                panic!("{round:?}");
            };
            assert!(
                std::sync::Arc::ptr_eq(again, &source),
                "{what}, round {n}: the first round's source"
            );
        }
        assert_eq!(crate::error::first_os_code(&round.members[0]), Some(code), "{what}");
        let Error::MemberNotKilled { source, .. } = &round.members[0] else {
            panic!("{round:?}");
        };
        let Error::Unassessable {
            source: Some(cause), ..
        } = &**source
        else {
            panic!("{source:?}");
        };
        if what == "a bare OS error" {
            assert!(
                matches!(&**cause, Error::Io(e) if e.raw_os_error() == Some(code)),
                "{cause:?}"
            );
        }
    }
}

/// A member the walk never read, reported as `Unsupported`, is reported again as `Unsupported`, with
/// its `op` and `platform`: not as `Unassessable`.
///
/// Mutant: the held member is re-reported as `Unassessable` whatever its first error was.
#[skuld::test]
fn a_member_never_read_is_reported_again_as_the_variant_it_was() {
    use super::{not_killed, with_earlier, Left};
    use crate::containment::dispatch::Unkilled;
    let first = Unkilled {
        members: vec![not_killed(
            7,
            Error::Unsupported {
                op: "process open".into(),
                platform: "linux",
                detail: "pidfd_open was refused".into(),
                source: None,
            },
        )],
        root: None,
        resolved: Vec::new(),
    };
    let held = Left::of(&first);

    let again = with_earlier(&crate::identity::HostKernel, held, Ok(()))
        .0
        .expect_err("never read, so never shown killed");

    let Error::MemberNotKilled { pid, source, .. } = &again.members[0] else {
        panic!("{again:?}");
    };
    assert_eq!(*pid, 7);
    assert!(
        matches!(&**source, Error::Unsupported { op, platform: "linux", detail, .. }
            if op == "process open" && detail == "pidfd_open was refused"),
        "{source:?}"
    );
}