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
//! A tree walk whose `/proc` view cannot be trusted errors instead of walking an empty snapshot,
//! and never walks from a root that no longer holds its pid. Every read a walk makes, the
//! per-pid ones included, goes through the kernel it is given. Linux only: the view is a
//! [`FakeKernel`]'s `self/status` row.
//!
//! A live root must come out of every failing walk unsignalled: [`release`] proves it by its exit
//! status.

use crate::child::front_cgroup_tests::pidfd_of;
use crate::containment::dispatch::Unkilled;
use crate::error::Error;
use crate::identity::{
    ticks_host, ticks_id, unreadable, FakeKernel, HostKernel, Kernel, Key, ProcessId, UNREADABLE_STATUS_REASON,
};
use crate::test_child::{
    live_exiting_member as live_member, open_live, release_unsignalled as release, stat_of_a_new_owner,
};
use crate::test_groups::{pidfd_group_signal, Group};
use crate::Recursive;

use super::treewalk_pidfs_tests::{children_of, descendants};

/// `result` is the error of a walk that left `pid` unkilled because its identity could not be read
/// ([`Error::Unassessable`]), and its message says each of `causes`.
#[track_caller]
fn assert_not_killed(result: Result<(), Error>, pid: u32, causes: &[&str]) {
    // A call's error holds every member left ([`Error::MembersLeft`]); a walk's own is the member.
    let first = match &result {
        Err(Error::MembersLeft { members, .. }) => Some(&**members.first()),
        Err(other) => Some(other),
        Ok(()) => None,
    };
    match first {
        Some(Error::MemberNotKilled { pid: named, source }) => {
            assert_eq!(*named, pid, "the first member left behind");
            assert!(matches!(**source, Error::Unassessable { .. }), "{source:?}");
            let said = source.to_string();
            for cause in causes {
                assert!(said.contains(cause), "the error must name {cause:?}: {said}");
            }
        }
        _ => panic!("expected MemberNotKilled for pid {pid} naming {causes:?}, got {result:?}"),
    }
}

fn assert_unassessable_naming(result: Result<(), Error>, causes: &[&str]) {
    match result {
        Err(Error::Unassessable { detail, .. }) => {
            for cause in causes {
                assert!(detail.contains(cause), "the error must name {cause:?}: {detail}");
            }
        }
        other => panic!("expected Unassessable naming {causes:?}, got {other:?}"),
    }
}

/// How a view fails, and what its error names.
#[derive(Clone, Copy)]
enum View {
    Diverged,
    Unreadable,
}

impl View {
    /// `kernel` whose `self/status` reads fail this way from the read that follows `earlier` reads.
    fn fail<'a>(self, kernel: FakeKernel<'a>, earlier: usize) -> FakeKernel<'a> {
        match self {
            View::Diverged => kernel.diverged_view_after(earlier),
            View::Unreadable => kernel.unreadable_view_after(earlier),
        }
    }

    fn cause(self) -> &'static str {
        match self {
            View::Diverged => "outer pid namespace",
            View::Unreadable => UNREADABLE_STATUS_REASON,
        }
    }
}

const VIEWS: [View; 2] = [View::Diverged, View::Unreadable];

type Walk = fn(&dyn Kernel, ProcessId) -> Result<(), Error>;

/// The walks that take an identity.
fn id_walks() -> [(&'static str, Walk); 2] {
    [
        ("hard_kill", |k, id| {
            super::hard_kill(k, id, &super::ByIdentity::new(k, id))
                .outcome()
                .into_result()
                .map_err(Unkilled::into_error)
        }),
        ("terminate", |k, id| {
            super::terminate(k, id, &super::ByIdentity::new(k, id))
        }),
    ]
}

/// Every walk, `Process`'s included, over an open handle on the live `id`.
fn walks() -> [(&'static str, Walk); 4] {
    let [hard_kill, terminate] = id_walks();
    [
        hard_kill,
        terminate,
        ("kill_tree", |k, id| open_live(id).kill_tree_with("kill_tree", k)),
        ("terminate_tree", |k, id| open_live(id).terminate_tree_with(k)),
    ]
}

// An untrusted view =====

/// Mutant: "`process_parents` yields an empty snapshot when the view is not `Same`", or "signal
/// the root, then return the error": the walk reports success, or kills the root.
#[skuld::test]
fn every_walk_over_an_untrusted_view_errors_and_signals_nothing() {
    for (name, walk) in walks() {
        for view in VIEWS {
            let (child, id) = live_member();
            let kernel = view.fail(FakeKernel::over(&HostKernel), 0);
            let result = walk(&kernel, id);
            assert!(
                matches!(&result, Err(Error::Unassessable { detail, .. }) if detail.contains(view.cause())),
                "{name}: {result:?}"
            );
            release(child);
        }
    }
}

/// The walker's cooperative signal over an untrusted view sent nothing: `NotSent`, with the view's error,
/// so `graceful_shutdown_tree` ends the call. Mutant: the failure is a `Sent { result: Err(..) }`.
#[skuld::test]
fn a_walkers_terminate_over_an_untrusted_view_says_nothing_was_sent() {
    for view in VIEWS {
        let (child, id) = live_member();
        let kernel = view.fail(FakeKernel::over(&HostKernel), 0);
        match super::terminate_tree(&kernel, id, None) {
            crate::containment::TerminateOutcome::NotSent(Error::Unassessable { detail, .. })
                if detail.contains(view.cause()) => {}
            other => panic!("expected NotSent(Unassessable) naming {}, got {other:?}", view.cause()),
        }
        release(child);
    }
}

// The snapshot precedes the anchor =====

type Query = fn(&ProcessId, &dyn Kernel) -> Result<(), Error>;

/// The queries that take the process snapshot. `parent` does not: it reads `self` alone.
fn children_queries() -> [(&'static str, Query); 2] {
    [
        ("children(No)", |p, k| p.children_with(k, Recursive::No).map(|_| ())),
        ("children(Yes)", |p, k| p.children_with(k, Recursive::Yes).map(|_| ())),
    ]
}

/// The snapshot is the first view read, so the anchor that follows it vouches for the pid across
/// the whole snapshot. Mutant: "the anchor is checked before the snapshot" - the failing view lands
/// on the anchor and the error blames the wrong read.
#[skuld::test]
fn children_take_the_snapshot_before_the_anchor() {
    let me = ProcessId::current();
    for (_, query) in children_queries() {
        for view in VIEWS {
            let kernel = view.fail(FakeKernel::over(&HostKernel), 0);
            let result = query(&me, &kernel);
            assert_unassessable_naming(result, &["the process snapshot could not be taken", view.cause()]);
        }
    }
}

/// The anchor failing after a good snapshot names the view that failed it (the one the failing read
/// used, not a second look), and the pid. `parent` reads no snapshot: its first view read is the
/// anchor's. Mutants: "`unqueryable` re-derives the cause" (the view has recovered by then, so the
/// error blames access); "the table read's error is dropped".
#[skuld::test]
fn an_anchor_read_that_fails_names_the_view_that_failed_it() {
    // The `/proc` path: only a `starttime` anchor is read through the view.
    let me = ticks_id(std::process::id());
    let pid = me.pid();
    let parent: (&str, Query) = ("parent", |p, k| p.parent_with(k).map(|_| ()));
    let queries = std::iter::once((parent, 0)).chain(children_queries().map(|query| (query, 1)));
    for ((_, query), snapshot_reads) in queries {
        for view in VIEWS {
            let kernel = view.fail(ticks_host(pid).same_view(), snapshot_reads);
            let result = query(&me, &kernel);
            assert_unassessable_naming(
                result,
                &[&format!("pid {pid} identity could not be read"), view.cause()],
            );
        }
    }
}

// The anchor guards the walk =====

/// A root that no longer holds its pid has no descendants: its pid's new owner's children are not
/// its own, and are never signalled. The signal-only walks are `Ok`; the kills killed nothing, and
/// are `Unassessable` (`Process::kill_tree` included, which has no handle to settle it). Mutants:
/// "walk without an anchor"; "a kill that found no root is `Ok`".
#[skuld::test]
fn every_walk_from_a_root_that_lost_its_pid_signals_nothing_and_a_kill_is_unassessable() {
    for (name, walk) in walks() {
        let (child, id) = live_member();
        // The `/proc` path: the root's `stat` shows another start time, as its pid's new owner's.
        let id = ticks_id(id.pid());
        let pid = id.pid();
        let kernel = FakeKernel::over(&HostKernel)
            .live_without_pidfs(pid, pidfd_of(pid))
            .on_read(&format!("{pid}/stat"), Ok(&stat_of_a_new_owner(pid)));
        let result = walk(&kernel, id);
        if name.contains("kill") {
            assert_unassessable_naming(result, &["no walk ran"]);
        } else {
            assert!(result.is_ok(), "{name}: {result:?}");
        }
        release(child);
    }
}

/// A root whose pid cannot be queried is an error naming the pid and the view, with nothing
/// signalled. Mutants: "an unqueryable root is treated as gone"; "the anchor is skipped". The
/// `/proc` path: only a `starttime` id is proved through the view; a `pidfs` id is proved by its
/// pidfd, in `treewalk_pidfs_tests`.
#[skuld::test]
fn every_walk_from_a_root_that_cannot_be_queried_errors_and_signals_nothing() {
    for (_, walk) in walks() {
        let (child, host_id) = live_member();
        let id = ticks_id(host_id.pid());
        let kernel = View::Unreadable.fail(
            FakeKernel::over(&HostKernel)
                .live_without_pidfs(id.pid(), pidfd_of(id.pid()))
                .same_view(),
            1,
        );
        let result = walk(&kernel, id);
        assert_unassessable_naming(
            result,
            &[
                &format!("pid {} identity could not be read", id.pid()),
                UNREADABLE_STATUS_REASON,
            ],
        );
        release(child);
    }
}

// A live root missing from the table =====

/// A live root with no row in the table has its children walked and killed: the walk reads only the
/// rows that name the root as their parent, and the root's own row says nothing about them. The
/// table lists the descendant alone, so the walk reaches no other host process. Mutant: "a root
/// absent from the table is `Unassessable`, or walks nothing" (`hard_kill` then leaves the
/// descendant, and the root, running).
#[skuld::test]
fn a_live_root_missing_from_the_table_still_has_its_descendant_walked_and_killed() {
    use std::os::unix::process::ExitStatusExt as _;
    let (mut child, root, descendant) = live_member_with_descendant();
    // The `/proc` path: the walk's ids are `starttime` ids.
    let root = ticks_id(root.pid());
    let kernel = FakeKernel::over(&HostKernel)
        .same_view()
        .on_pids(Ok(&[descendant.pid()]))
        .live_without_pidfs(root.pid(), pidfd_of(root.pid()))
        .live_without_pidfs(descendant.pid(), pidfd_of(descendant.pid()));
    for recursive in [Recursive::No, Recursive::Yes] {
        let members = root.children_with(&kernel, recursive).expect("the root's children");
        let pids: Vec<u32> = members.iter().map(ProcessId::pid).collect();
        assert_eq!(pids, [descendant.pid()], "{recursive:?}");
    }
    super::hard_kill(&kernel, root, &super::ByIdentity::new(&kernel, root))
        .outcome()
        .into_result()
        .expect("the walk ran");
    // Both were killed: the root by its signal, the descendant before it could print.
    let mut printed = String::new();
    std::io::Read::read_to_string(&mut child.stdout.take().expect("piped stdout"), &mut printed).expect("read to EOF");
    assert_eq!(printed, "", "the descendant must have been killed");
    assert_eq!(child.wait().expect("reap the root").signal(), Some(libc::SIGKILL));
}

// The per-pid reads go through the walk's kernel =====

/// A pid the kernel refuses to read is an error, as a pid it cannot find would not be, and the walk
/// itself says nothing of it: its caller reports it, once. Mutant: "`resolve_or_drop` resolves
/// through `HostKernel`"; "`resolve_or_drop` warns" (the first member left behind is then reported
/// twice, by the walk and by the error that names it).
#[skuld::test]
fn a_pid_the_kernel_cannot_read_is_an_error_the_walk_does_not_warn_of() {
    crate::log_capture::install();
    let (child, id) = live_member();
    let (kernel, _guard) = unreadable(id.pid());
    let mark = crate::log_capture::mark();
    let Err(Error::Unassessable { detail, .. }) = super::resolve_or_drop(&kernel, id.pid(), ProcessId::current(), None)
    else {
        panic!("an unreadable pid is Unassessable");
    };
    assert!(
        detail.contains(&format!("pid {} exists but could not be queried", id.pid())),
        "{detail}"
    );
    let warned = crate::log_capture::records_since_on_current_thread(mark, "treewalk:");
    assert_eq!(warned, [], "the walk's caller reports the member");
    release(child);
}

/// The error names why the read failed when the read knows, so an unreadable view is not reported as
/// access. The candidate's own read fails with the view, and its parent is held, so the error names
/// the candidate and its cause.
/// Mutants: "`resolve_or_drop` drops the cause": the error says "access denied?"; "a held parent's
/// proof blames the parent": the error names `ppid`.
#[skuld::test]
fn the_error_for_a_dropped_pid_names_the_cause_of_its_own_read_under_a_held_parent() {
    let (child, id) = live_member();
    let me = ProcessId::current();
    let parent = ProcessId::from_parts_for_test(me.pid(), Key::Pidfs(9));
    let kernel = View::Unreadable.fail(
        FakeKernel::over(&HostKernel)
            .on_pidfd_open(me.pid(), Ok(pidfd_of(me.pid())))
            .on_pidfs_ino(me.pid(), Ok(Some(9))),
        0,
    );
    let Err(Error::Unassessable { detail, .. }) = super::resolve_or_drop(&kernel, id.pid(), parent, None) else {
        panic!("an unreadable pid is Unassessable");
    };
    assert!(
        detail.contains(&format!("pid {} identity could not be read", id.pid())),
        "{detail}"
    );
    assert!(detail.contains(View::Unreadable.cause()), "{detail}");
    assert!(!detail.contains("access denied?"), "{detail}");
    assert!(!detail.contains("ppid") && !detail.contains("reading pid"), "{detail}");
    release(child);
}

/// The view fails every read, the parent's proof too (a `Ticks` id is proved by its `stat`), so the
/// error blames the parent, and says which candidate's read was left unanswered. Mutants:
/// "`resolve_or_drop` drops the cause"; "the error does not name the candidate".
#[skuld::test]
fn the_error_for_a_dropped_pid_names_the_cause_of_its_parents_proof() {
    let (child, id) = live_member();
    let me = ProcessId::current();
    let parent = ticks_id(me.pid());
    let kernel = View::Unreadable.fail(FakeKernel::over(&HostKernel), 0);
    let Err(Error::Unassessable { detail, .. }) = super::resolve_or_drop(&kernel, id.pid(), parent, None) else {
        panic!("an unreadable parent proof is Unassessable");
    };
    assert!(
        detail.contains(&format!("ppid {} identity could not be read", me.pid())),
        "{detail}"
    );
    assert!(detail.contains(&format!("reading pid {}", id.pid())), "{detail}");
    assert!(detail.contains(View::Unreadable.cause()), "{detail}");
    assert!(!detail.contains("access denied?"), "{detail}");
    release(child);
}

/// Mutants: "`descendants` resolves through `HostKernel`", "`children_of` resolves through
/// `HostKernel`": the unreadable child is found.
#[skuld::test]
fn descendants_and_children_the_kernel_cannot_read_are_dropped() {
    let (child, id) = live_member();
    let me = ProcessId::current();
    // `me` has a row, as a live root does in a snapshot.
    let parents = [(me.pid(), 1), (id.pid(), me.pid())];
    let (kernel, _guard) = unreadable(id.pid());
    assert!(descendants(&kernel, me, &parents)
        .expect("a readable anchor")
        .is_empty());
    assert!(children_of(&kernel, me, &parents)
        .expect("a readable anchor")
        .is_empty());
    release(child);
}

/// A kill re-verifies through the kernel: a pid it cannot read is not signalled and counts as
/// not attempted; one it shows with another start time is already gone. The member's own pidfd
/// passes the proof's fdinfo check, so the `stat` is what the row is about. Mutants:
/// "`kill_by_identity` re-verifies through `HostKernel`": the member is signalled; "the re-verify
/// ignores the start time": `Terminated` for the new owner.
#[skuld::test]
fn kill_by_identity_spares_a_pid_the_kernel_cannot_read_or_shows_as_another_process() {
    let (child, id) = live_member();
    // The `/proc` path: a `starttime` id is re-verified by its `stat`.
    let id = ticks_id(id.pid());
    let pid = id.pid();
    let unreadable_kernel = FakeKernel::over(&HostKernel)
        .live_without_pidfs(pid, pidfd_of(pid))
        .on_read(&format!("{pid}/stat"), Err(libc::EACCES));
    let outcome = super::kill_by_identity(&unreadable_kernel, id, nix::sys::signal::Signal::SIGTERM);
    assert!(matches!(outcome, super::KillOutcome::NotAttempted(_)), "{outcome:?}");
    let new_owner = FakeKernel::over(&HostKernel)
        .live_without_pidfs(pid, pidfd_of(pid))
        .on_read(&format!("{pid}/stat"), Ok(&stat_of_a_new_owner(pid)));
    let outcome = super::kill_by_identity(&new_owner, id, nix::sys::signal::Signal::SIGTERM);
    assert!(matches!(outcome, super::KillOutcome::AlreadyGone), "{outcome:?}");
    release(child);
}

/// The same re-verify of a `pidfs` id asks the kernel's pidfd: a pid it cannot open is not
/// signalled and counts as not attempted; one it opens to another inode is already gone.
#[skuld::test]
fn kill_by_identity_spares_a_pidfs_pid_the_kernel_cannot_open_or_shows_as_another_process(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    let (child, id) = live_member();
    let pid = id.pid();
    let ino = id.pidfs_ino().expect("a pidfs host makes pidfs ids");
    let refusing = FakeKernel::over(&HostKernel).on_pidfd_open(pid, Err(rustix::io::Errno::MFILE));
    // The reason is the refusal's own, so an error built from it names the process and why.
    let outcome = super::kill_by_identity(&refusing, id, nix::sys::signal::Signal::SIGTERM);
    let super::KillOutcome::NotAttempted(why) = outcome else {
        panic!("expected NotAttempted, got {outcome:?}");
    };
    // An identity that could not be read is `Unassessable`, with the refusal as its source, and
    // the failed call is named.
    let Error::Unassessable { detail, source } = &why else {
        panic!("expected Unassessable, got {why:?}");
    };
    assert!(detail.contains("pidfd_open"), "{detail}");
    assert!(source.is_some(), "{why:?}");
    assert_eq!(crate::error::first_os_code(&why), Some(libc::EMFILE), "{why:?}");
    let new_owner = FakeKernel::over(&HostKernel).on_pidfs_ino(pid, Ok(Some(ino + 1)));
    let outcome = super::kill_by_identity(&new_owner, id, nix::sys::signal::Signal::SIGTERM);
    assert!(matches!(outcome, super::KillOutcome::AlreadyGone), "{outcome:?}");
    release(child);
}

/// The root's `stat` is read three times: by the snapshot, by the anchor, and by the kill's
/// re-verify, which finds another start time. Nothing is signalled. The root's own pidfd passes the
/// proof's fdinfo check, so the `stat` is what the row is about. Mutants: "the walk's kill
/// re-verifies through `HostKernel`"; "the kill ignores a start time that differs".
///
/// Only walks that open their root by identity re-verify it at kill time; a held handle names its
/// root. A descendant's re-verify is pinned by
/// `every_id_walk_re_verifies_a_descendants_kill_through_its_kernel`, through the same loop.
#[skuld::test]
fn every_walk_re_verifies_its_kill_through_its_kernel() {
    for (name, walk) in id_walks() {
        let (child, id) = live_member();
        // The `/proc` path, as above.
        let id = ticks_id(id.pid());
        let kernel = FakeKernel::over(&HostKernel)
            .live_without_pidfs(id.pid(), pidfd_of(id.pid()))
            .on_read_after(&format!("{}/stat", id.pid()), 2, Ok(&stat_of_a_new_owner(id.pid())));
        let result = walk(&kernel, id);
        assert!(result.is_ok(), "{name}: {result:?}");
        release(child);
    }
}

// A descendant's reads go through the walk's kernel =====

/// A live root `sh` that has announced its pid, its identity, and the identity of the `sh` it
/// forked. That descendant prints `released` and exits at the EOF of its stdin, which the test
/// holds the write end of; the root waits for it.
fn live_member_with_descendant() -> (std::process::Child, ProcessId, ProcessId) {
    let mut cmd = std::process::Command::new("/bin/sh");
    cmd.arg("-c")
        .arg("exec 3<&0; sh -c 'read _ignored; echo released' <&3 3<&- & echo $$; wait")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped());
    let mut child = crate::test_spawn::spawn(&mut cmd).expect("spawn the root");
    crate::test_child::await_member_ready(&mut child);
    let root = ProcessId::of(child.id()).found().expect("the live root resolves");
    let descendants = root
        .children_with(&HostKernel, Recursive::No)
        .expect("the root's children are readable");
    let [descendant] = descendants[..] else {
        panic!("the root has exactly one child, got {descendants:?}");
    };
    (child, root, descendant)
}

/// The root was signalled with `signo` and the descendant was not: released by EOF, it still
/// prints. A signalled descendant has nothing to print, and the read ends at EOF without it.
fn release_with_a_signalled_root(who: &str, mut child: std::process::Child, signo: i32) {
    use std::io::Read as _;
    use std::os::unix::process::ExitStatusExt as _;
    drop(child.stdin.take());
    let mut printed = String::new();
    child
        .stdout
        .take()
        .expect("piped stdout")
        .read_to_string(&mut printed)
        .expect("read to EOF");
    assert_eq!(
        printed, "released\n",
        "{who}: the descendant must not have been signalled"
    );
    let status = child.wait().expect("reap the root");
    assert_eq!(
        status.signal(),
        Some(signo),
        "{who}: the walk must have signalled the root"
    );
}

/// The descendant's `stat` is read by the snapshot, then by the walk's resolve of it, then by the
/// kill's re-verify, which the kernel refuses or shows as another start time. Only the root is
/// signalled. Each member's own pidfd passes the proof's fdinfo check, so the `stat` is what the
/// row is about. Mutants: "`descendants` resolves through `HostKernel`" (the re-verify becomes the
/// second read, which the row lets through), "the descendant loop's kill re-verifies through
/// `HostKernel`", "the kill ignores a start time that differs", each in `hard_kill` and in
/// `terminate`: the descendant is signalled.
///
/// A member whose identity cannot be read at kill time is `Unassessable`. `hard_kill` returns it and
/// warns of nothing; `terminate`, which cannot, warns.
#[skuld::test]
fn every_id_walk_re_verifies_a_descendants_kill_through_its_kernel() {
    crate::log_capture::install();
    for ((name, walk), signo) in id_walks().into_iter().zip([libc::SIGKILL, libc::SIGTERM]) {
        for shows_a_new_owner in [false, true] {
            let (child, root, descendant) = live_member_with_descendant();
            let mark = crate::log_capture::mark();
            // The `/proc` path: the walk's ids are `starttime` ids.
            let root = ticks_id(root.pid());
            let new_owner = stat_of_a_new_owner(descendant.pid());
            let answer = if shows_a_new_owner {
                Ok(new_owner.as_slice())
            } else {
                Err(libc::EACCES)
            };
            let kernel = FakeKernel::over(&HostKernel)
                .live_without_pidfs(root.pid(), pidfd_of(root.pid()))
                .live_without_pidfs(descendant.pid(), pidfd_of(descendant.pid()))
                .on_read_after(&format!("{}/stat", descendant.pid()), 2, answer);
            let result = walk(&kernel, root);
            // A refused kill leaves the descendant running, so `hard_kill` names it; `terminate` is
            // best effort. A descendant shown as another process is gone, not left behind.
            let warned: Vec<_> = crate::log_capture::warns_since(mark, "treewalk:")
                .into_iter()
                .filter(|said| said.contains(&descendant.pid().to_string()))
                .collect();
            if name == "hard_kill" && !shows_a_new_owner {
                assert_not_killed(result, descendant.pid(), &[]);
                assert_eq!(warned, Vec::<String>::new(), "the error is the report");
            } else {
                assert!(result.is_ok(), "{name}, new owner {shows_a_new_owner}: {result:?}");
                assert_eq!(
                    warned.len(),
                    usize::from(name == "terminate" && !shows_a_new_owner),
                    "{name}, new owner {shows_a_new_owner}: {warned:?}"
                );
            }
            release_with_a_signalled_root(name, child, signo);
        }
    }
}

/// A live root with one live descendant, and a kernel in which the descendant's identity cannot be
/// read (`EMFILE` on its pidfd). The `/proc` path: the root's id is a `starttime` id.
fn root_with_an_unreadable_descendant() -> (std::process::Child, ProcessId, ProcessId, FakeKernel<'static>) {
    root_whose_descendants_pidfd_open_answers(rustix::io::Errno::MFILE)
}

/// [`root_with_an_unreadable_descendant`], where the descendant's `pidfd_open` answers `errno`.
fn root_whose_descendants_pidfd_open_answers(
    errno: rustix::io::Errno,
) -> (std::process::Child, ProcessId, ProcessId, FakeKernel<'static>) {
    let (child, root, descendant) = live_member_with_descendant();
    let root = ticks_id(root.pid());
    let kernel = FakeKernel::over(&HostKernel)
        .live_without_pidfs(root.pid(), pidfd_of(root.pid()))
        .on_pidfd_open(descendant.pid(), Err(errno));
    (child, root, descendant, kernel)
}

/// A descendant the walk cannot read is not signalled, and `hard_kill` and `Process::kill_tree`
/// are an error naming it and why, so a caller does not take the tree for killed. `terminate` is best
/// effort and stays `Ok`. Mutants: "an `Unknown` read is dropped as `Gone`": `Ok`; "`kill_tree`
/// drops the walk's error"; "`terminate` reports the incomplete walk".
#[skuld::test]
fn a_descendant_that_cannot_be_read_makes_hard_kill_and_kill_tree_err_naming_it_and_leaves_terminate_ok() {
    let (child, root, descendant, kernel) = root_with_an_unreadable_descendant();
    let cause = format!("pid {} identity could not be read", descendant.pid());
    let left = super::hard_kill(&kernel, root, &super::ByIdentity::new(&kernel, root))
        .outcome()
        .into_result()
        .expect_err("a descendant was left");
    assert!(!left.members.is_empty(), "a descendant was left, not only the root");
    assert_not_killed(Err(left.into_error()), descendant.pid(), &[&cause]);
    release_with_a_signalled_root("hard_kill", child, libc::SIGKILL);

    let (child, root, descendant, kernel) = root_with_an_unreadable_descendant();
    let cause = format!("pid {} identity could not be read", descendant.pid());
    assert_not_killed(
        open_live(root).kill_tree_with("kill_tree", &kernel),
        descendant.pid(),
        &[&cause],
    );
    release_with_a_signalled_root("kill_tree", child, libc::SIGKILL);

    let (child, root, _, kernel) = root_with_an_unreadable_descendant();
    super::terminate(&kernel, root, &super::ByIdentity::new(&kernel, root)).expect("best effort");
    release_with_a_signalled_root("terminate", child, libc::SIGTERM);
}

/// A member the walk could not read is reported once, wherever it is reported from: through the real
/// `resolve_or_drop`, `hard_kill` and `children` name it in their error and the walk warns of nothing;
/// `terminate`, which returns none, warns of it once, with its pid and why. Mutant: "the walk warns of
/// a candidate it drops" (the error that names it then reports it a second time).
#[skuld::test]
fn a_descendant_that_cannot_be_read_is_reported_once() {
    crate::log_capture::install();
    let warns_naming = |mark, descendant: ProcessId| -> Vec<String> {
        crate::log_capture::warns_since(mark, &format!("pid {}", descendant.pid()))
    };

    let (child, root, descendant, kernel) = root_with_an_unreadable_descendant();
    let mark = crate::log_capture::mark();
    super::hard_kill(&kernel, root, &super::ByIdentity::new(&kernel, root))
        .outcome()
        .into_result()
        .expect_err("a descendant was left");
    assert_eq!(
        warns_naming(mark, descendant),
        Vec::<String>::new(),
        "the error is the report"
    );
    release_with_a_signalled_root("hard_kill", child, libc::SIGKILL);

    let (child, root, descendant, kernel) = root_with_an_unreadable_descendant();
    let mark = crate::log_capture::mark();
    root.children_with(&kernel, Recursive::Yes)
        .expect_err("a descendant was not read");
    assert_eq!(
        warns_naming(mark, descendant),
        Vec::<String>::new(),
        "the error is the report"
    );
    release(child);

    let (child, root, descendant, kernel) = root_with_an_unreadable_descendant();
    let mark = crate::log_capture::mark();
    super::terminate(&kernel, root, &super::ByIdentity::new(&kernel, root)).expect("best effort");
    let warned = warns_naming(mark, descendant);
    assert_eq!(warned.len(), 1, "{warned:?}");
    assert!(
        warned[0].contains(&format!("pid {} dropped from the walk", descendant.pid())),
        "{warned:?}"
    );
    assert!(warned[0].contains("identity could not be read"), "{warned:?}");
    release_with_a_signalled_root("terminate", child, libc::SIGTERM);
}

/// Every member left behind is in what `hard_kill` returns, the one that could not be read first, and
/// `hard_kill` warns of none: its caller reports, once. The made-up second member is `fault`'s, as no
/// real second descendant refuses a kill without setuid. Mutants: "`hard_kill` drops every member after
/// the first"; "`hard_kill` warns of the members after the first".
#[skuld::test]
fn every_member_left_behind_is_returned_and_none_is_warned_of() {
    use super::fault::{self, LeftBehind};
    crate::log_capture::install();
    let (child, root, descendant, kernel) = root_with_an_unreadable_descendant();
    let second = root.pid().wrapping_add(1);
    let mark = crate::log_capture::mark();
    fault::force_incomplete_once(LeftBehind::Descendant);
    let left = super::hard_kill(&kernel, root, &super::ByIdentity::new(&kernel, root))
        .outcome()
        .into_result()
        .expect_err("two members were left");
    let warned = crate::log_capture::warns_since(mark, "treewalk:");
    let pids: Vec<u32> = left
        .members
        .iter()
        .map(|error| match error {
            Error::MemberNotKilled { pid, .. } => *pid,
            other => panic!("expected MemberNotKilled, got {other:?}"),
        })
        .collect();
    assert_eq!(pids, [descendant.pid(), second], "{left:?}");
    assert!(left.root.is_none(), "{left:?}");
    assert_eq!(warned, Vec::<String>::new(), "the caller reports");
    release_with_a_signalled_root("hard_kill", child, libc::SIGKILL);
}

/// The members an earlier kill left, against a later walk that finds none of them
/// ([`with_earlier`](super::with_earlier)): one whose identity was read is killed by it again, and
/// is `MemberNotKilled` again while the kernel still cannot reach it; one never read is
/// `MemberNotKilled` again with its first cause, and the kernel is not asked about it.
///
/// Mutants: a member left is forgotten; a read member is not killed again; a member never read is
/// acted on by its pid.
#[skuld::test]
fn members_an_earlier_kill_left_are_killed_again_by_identity_or_reported_again() {
    use super::{with_earlier, Left};
    let sends = crate::send_log::Capture::start();
    let (child, _, descendant, kernel) = root_with_an_unreadable_descendant();

    let again = with_earlier(&kernel, vec![Left::Resolved(descendant)], Ok(()))
        .0
        .expect_err("the kernel still cannot reach the descendant");
    assert_eq!(again.members.len(), 1, "{again:?}");
    assert_not_killed(
        Err(again.into_error()),
        descendant.pid(),
        &["identity could not be read: pidfd_open"],
    );
    assert_eq!(sends.by_identity(), [], "nothing was sent to it");

    let unread = Left::Unread {
        pid: descendant.pid(),
        source: std::sync::Arc::new(Error::Unassessable {
            detail: "its identity could not be read".into(),
            source: None,
        }),
    };
    let again = with_earlier(&kernel, vec![unread], Ok(()))
        .0
        .expect_err("never read, so never shown killed");
    assert_not_killed(
        Err(again.into_error()),
        descendant.pid(),
        &["its identity could not be read"],
    );
    assert_eq!(sends.by_identity(), [], "nothing is sent by a bare pid");
    release(child);
}

/// A member the walk never read is reported again with the cause it was first reported with: its OS
/// code is where it was, not folded into text.
///
/// Mutant: the held member keeps only the text of its first error.
#[skuld::test]
fn a_member_never_read_is_reported_again_with_its_os_code() {
    use super::{with_earlier, Left};
    let (child, root, _, kernel) = root_with_an_unreadable_descendant();
    let first = super::hard_kill(&kernel, root, &super::ByIdentity::new(&kernel, root))
        .outcome()
        .into_result()
        .expect_err("the descendant was left");
    let code = crate::error::first_os_code(&first.members[0]);
    assert!(code.is_some(), "the first report carries the OS code: {first:?}");
    let held = Left::of(&first);
    assert!(matches!(held[0], Left::Unread { .. }), "{held:?}");

    let again = with_earlier(&kernel, held, Ok(()))
        .0
        .expect_err("never read, so never shown killed")
        .into_error();

    assert_eq!(crate::error::first_os_code(&again), code, "{again:?}");
    release_with_a_signalled_root("hard_kill", child, libc::SIGKILL);
}

/// A member the walk never read, because the OS refused its pidfd (`Unsupported`, with `EPERM` as its
/// cause), is reported again as the same kind of failure, with the refusal's text and its `EPERM`
/// reachable through `source()`: not as `Unassessable`, and not as text alone.
///
/// Mutants: the held member keeps only the text of its first error; it keeps only an `Unassessable`'s
/// cause; the layers between the member's error and its OS error are dropped.
#[skuld::test]
fn a_member_whose_pidfd_was_refused_is_reported_again_as_a_refusal_with_its_errno() {
    use super::{with_earlier, Left};
    let (child, root, _, kernel) = root_whose_descendants_pidfd_open_answers(rustix::io::Errno::PERM);
    let first = super::hard_kill(&kernel, root, &super::ByIdentity::new(&kernel, root))
        .outcome()
        .into_result()
        .expect_err("the descendant was left");
    let Error::MemberNotKilled { source, .. } = &first.members[0] else {
        panic!("{first:?}");
    };
    let Error::Unsupported { op, detail, .. } = &**source else {
        panic!("the first report is a refusal: {source:?}");
    };
    let (op, detail) = (op.clone(), detail.clone());
    let held = Left::of(&first);

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

    let Error::MemberNotKilled { source, .. } = &again.members[0] else {
        panic!("{again:?}");
    };
    let Error::Unsupported {
        op: again_op,
        detail: again_detail,
        ..
    } = &**source
    else {
        panic!("a refusal is reported again as one: {source:?}");
    };
    assert_eq!((again_op, again_detail), (&op, &detail));
    assert_eq!(
        crate::error::first_os_code(&again.members[0]),
        Some(libc::EPERM),
        "{again:?}"
    );
    release_with_a_signalled_root("hard_kill", child, libc::SIGKILL);
}

/// `children` of a root with a descendant the walk cannot read is an error naming that pid and why,
/// never the short list. Mutant: "`children` takes the members and ignores `unassessed`".
#[skuld::test]
fn children_of_a_root_with_a_descendant_that_cannot_be_read_is_an_error_naming_it() {
    for recursive in [Recursive::No, Recursive::Yes] {
        let (child, root, descendant, kernel) = root_with_an_unreadable_descendant();
        assert_unassessable_naming(
            root.children_with(&kernel, recursive).map(|_| ()),
            &[&format!("pid {} identity could not be read", descendant.pid())],
        );
        release(child);
    }
}

/// The candidate's own `stat` names its parent, and the walk accepts it only under the parent the
/// snapshot gave it: a pid that exited and was reused since the snapshot, by a process of another
/// parent, is dropped. Mutants: "the resolver ignores the parent", "the resolver always drops".
#[skuld::test]
fn a_candidate_whose_stat_shows_another_parent_is_dropped() {
    const PID: u32 = 4242;
    use crate::identity::Key;

    let stat = crate::identity::stat_parse::stat_fixture("S", 777);
    let kernel = ticks_host(PID)
        .same_view()
        .on_read(&format!("{PID}/stat"), Ok(&stat))
        .on_read("1/stat", Ok(&crate::identity::stat_parse::stat_fixture("S", 5)));
    let parent = |pid| ProcessId::from_parts_for_test(pid, Key::for_test(5));
    // `stat_fixture` shows parent 1.
    assert_eq!(
        super::resolve_or_drop(&kernel, PID, parent(99), None).expect("a read"),
        None
    );
    assert!(super::resolve_or_drop(&kernel, PID, parent(1), None)
        .expect("a read")
        .is_some());
}

/// The kill of a `pidfs` id whose pidfd call failed says what the walk says of the same pid: the
/// error built from the same cause, a refusal included (`Unsupported`, with no `Unassessable` around
/// it). Mutant: "the kill wraps what the open failed with in its own `Unassessable`".
#[skuld::test]
fn a_failed_pidfd_call_is_the_same_error_at_the_kill_and_at_the_walk() {
    use rustix::io::Errno;
    const PID: u32 = 4242;
    let id = ProcessId::from_parts_for_test(PID, Key::Pidfs(100));
    // The writers keep each pidfd stand-in from polling readable.
    let mut writers = Vec::new();
    let mut from_pidfs_ino = |errno| {
        let (reader, writer) = std::io::pipe().expect("a pipe");
        writers.push(writer);
        FakeKernel::new()
            .on_pidfd_open(PID, Ok(reader.into()))
            .on_pidfs_ino(PID, Err(errno))
    };
    // A refusal is `Unsupported`; every other failure is `Unassessable` carrying the raw errno.
    let kernels = [
        ("EPERM", FakeKernel::new().on_pidfd_open(PID, Err(Errno::PERM)), None),
        ("ENOSYS", FakeKernel::new().on_pidfd_open(PID, Err(Errno::NOSYS)), None),
        ("EACCES", FakeKernel::new().on_pidfd_open(PID, Err(Errno::ACCESS)), None),
        ("ENODEV", FakeKernel::new().on_pidfd_open(PID, Err(Errno::NODEV)), None),
        (
            "EMFILE",
            FakeKernel::new().on_pidfd_open(PID, Err(Errno::MFILE)),
            Some(Errno::MFILE),
        ),
        ("EBADF from pidfs_ino", from_pidfs_ino(Errno::BADF), Some(Errno::BADF)),
        ("EPERM from pidfs_ino", from_pidfs_ino(Errno::PERM), Some(Errno::PERM)),
        (
            "ENOSYS from pidfs_ino",
            from_pidfs_ino(Errno::NOSYS),
            Some(Errno::NOSYS),
        ),
    ];
    for (row, kernel, errno) in kernels {
        let (_, cause) = ProcessId::of_with(&kernel, PID);
        let walk = crate::identity::unqueryable(&format!("pid {PID}"), cause);
        let outcome = super::kill_by_identity(&kernel, id, nix::sys::signal::Signal::SIGTERM);
        let super::KillOutcome::NotAttempted(kill) = outcome else {
            panic!("{row}: expected NotAttempted, got {outcome:?}");
        };
        assert_eq!(format!("{kill:?}"), format!("{walk:?}"), "{row}");
        match (errno, &kill) {
            (None, Error::Unsupported { .. }) => {}
            (Some(errno), Error::Unassessable { .. }) => {
                assert_eq!(crate::error::first_os_code(&kill), Some(errno.raw_os_error()), "{row}")
            }
            (_, other) => panic!("{row}: wrong shape: {other:?}"),
        }
    }
}

/// What the kill of a member leaves, when the open finished with an error that is no OS refusal of
/// the signal: `Unassessable` naming the pid and that its pidfd could not be proved to name it, the
/// finished error as the source. Neither a live thread nor a `poll` that reported `POLLERR` is a
/// refusal. Mutant: "a finished open error is the kill's own error".
#[track_caller]
fn assert_unproved(row: &str, outcome: super::KillOutcome, pid: u32) {
    let super::KillOutcome::NotAttempted(Error::Unassessable { detail, source }) = outcome else {
        panic!("{row}: expected NotAttempted(Unassessable), got {outcome:?}");
    };
    assert!(
        detail.contains(&format!("pid {pid}")) && detail.contains("its pidfd could not be proved to name it"),
        "{row}: {detail}"
    );
    let Some(source) = source else {
        panic!("{row}: the finished error is the source");
    };
    // The source is not repeated in the text.
    assert!(!detail.contains(&source.to_string()), "{row}: {detail}");
}

#[skuld::test]
fn the_kill_of_a_live_thread_that_leads_no_group_is_unassessable_not_a_refusal() {
    use rustix::io::Errno;
    use rustix::process::PidfdFlags;
    const PID: u32 = 4242;
    // The writer keeps the stand-in from polling readable: the thread is live.
    let (reader, _writer) = std::io::pipe().expect("a pipe");
    let kernel = FakeKernel::new()
        .on_pidfd_open_flags(PID, PidfdFlags::empty(), Err(Errno::INVAL))
        .on_pidfd_open_flags(PID, crate::identity::PIDFD_THREAD, Ok(reader.into()))
        .on_pidfs_ino(PID, Ok(Some(100)));
    let id = ProcessId::from_parts_for_test(PID, Key::Pidfs(100));
    let outcome = super::kill_by_identity(&kernel, id, nix::sys::signal::Signal::SIGTERM);
    assert_unproved("live thread", outcome, PID);
}

/// `POLLERR` has no errno: a pipe's write end with no reader reports it. Mutant: "a finished open
/// error is the kill's own error".
#[skuld::test]
fn the_kill_of_a_member_whose_poll_reports_pollerr_is_unassessable_not_a_refusal() {
    use rustix::io::Errno;
    use rustix::process::PidfdFlags;
    const PID: u32 = 4242;
    let (reader, writer) = std::io::pipe().expect("a pipe");
    drop(reader);
    let kernel = FakeKernel::new()
        .on_pidfd_open_flags(PID, PidfdFlags::empty(), Err(Errno::INVAL))
        .on_pidfd_open_flags(PID, crate::identity::PIDFD_THREAD, Ok(writer.into()))
        .on_pidfs_ino(PID, Ok(Some(100)));
    let id = ProcessId::from_parts_for_test(PID, Key::Pidfs(100));
    let outcome = super::kill_by_identity(&kernel, id, nix::sys::signal::Signal::SIGTERM);
    assert_unproved("POLLERR", outcome, PID);
}

/// A failed inode read says it is the inode read that failed, not `pidfd_open`, and keeps its errno,
/// a refusing one too: only `pidfd_open` is refused.
#[skuld::test]
fn a_failed_inode_read_is_named_by_the_kill() {
    use rustix::io::Errno;
    const PID: u32 = 4242;
    for errno in [Errno::BADF, Errno::PERM, Errno::NOSYS, Errno::ACCESS, Errno::NODEV] {
        let (reader, _writer) = std::io::pipe().expect("a pipe");
        let kernel = FakeKernel::new()
            .on_pidfd_open(PID, Ok(reader.into()))
            .on_pidfs_ino(PID, Err(errno));
        let id = ProcessId::from_parts_for_test(PID, Key::Pidfs(100));
        let outcome = super::kill_by_identity(&kernel, id, nix::sys::signal::Signal::SIGTERM);
        let super::KillOutcome::NotAttempted(Error::Unassessable { detail, source }) = outcome else {
            panic!("{errno}: expected NotAttempted(Unassessable), got {outcome:?}");
        };
        assert!(
            detail.contains("pidfs_ino") && !detail.contains("pidfd_open"),
            "{errno}: {detail}"
        );
        assert_eq!(
            source.and_then(|e| crate::error::first_os_code(&*e)),
            Some(errno.raw_os_error()),
            "{errno}"
        );
    }
}