cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
use super::{Skip, Why};
use crate::containment::dispatch::TreeKillOutcome;
use crate::containment::{Refusal, Tree};

const PID: u32 = 999_999;

fn skip(why: Why) -> Skip {
    Skip {
        action: "kill its process group".to_owned(),
        why,
        root_alone: false,
        holders: None,
    }
}

/// A tree a completed kill settled, and a fresh one.
fn killed(settled: bool) -> Tree {
    let tree = Tree::none();
    if settled {
        tree.settle(TreeKillOutcome::Ran(Ok(())), true)
            .answer
            .expect("a kill that left nothing");
    }
    assert_eq!(tree.is_killed(), settled);
    tree
}

/// A skipped call whose root's handle could not say whether it was reaped answers `Unassessable`
/// with the handle's error as its `source()`, so its OS code is reachable, and not in the `detail`.
/// The `warn` still says the error.
///
/// Mutant: the answer folds the error into its text and keeps no source.
#[skuld::test]
fn a_skip_over_an_unsure_handle_answers_with_its_error_as_the_source() {
    use super::SkipCall;
    use crate::containment::dispatch::TreeSignal;
    use crate::error::Error;

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let os_error = std::io::Error::from_raw_os_error(libc::EPERM).to_string();
    let call = SkipCall {
        op: "skip_cause_probe_7e1",
        pid: PID,
        signal: TreeSignal::Term,
        earlier: None,
    };
    let why = Why::MayNameAnother(
        Refusal::Unsure(PID, std::sync::Arc::new(std::io::Error::from_raw_os_error(libc::EPERM))),
        None,
    );

    let answer = call
        .answer(&killed(false), skip(why), None)
        .answer
        .expect_err("a skipped call is no success");

    let Error::Unassessable { detail, .. } = &answer else {
        panic!("got {answer:?}");
    };
    assert_eq!(crate::error::first_os_code(&answer), Some(libc::EPERM), "{answer:?}");
    assert!(!detail.contains(&os_error), "{detail}");
    let warns = crate::log_capture::warns_since(mark, "skip_cause_probe_7e1");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains(&os_error), "{warns:?}");
}

/// A sweep that skipped what the root's number names, and whose holders' sweep (macOS) failed
/// nowhere, is `Unassessable` with the handle's error behind the skip as its `source()`; a holders'
/// sweep that failed is the answer itself.
///
/// Mutant: the answer folds the error into its text, or keeps no source.
#[skuld::test]
fn a_sweep_that_skipped_has_the_handles_error_as_its_source_unless_the_holders_failed() {
    use crate::error::Error;

    let os_error = std::io::Error::from_raw_os_error(libc::EPERM).to_string();
    let why = || {
        Why::MayNameAnother(
            Refusal::Unsure(PID, std::sync::Arc::new(std::io::Error::from_raw_os_error(libc::EPERM))),
            None,
        )
    };

    let answer = skip(why()).sweep_error();

    let Error::Unassessable { detail, .. } = &answer else {
        panic!("got {answer:?}");
    };
    assert_eq!(crate::error::first_os_code(&answer), Some(libc::EPERM), "{answer:?}");
    assert!(!detail.contains(&os_error), "{detail}");

    let own = Error::Containment {
        detail: "the holders' sweep failed".into(),
        source: None,
    };
    let answer = Skip {
        holders: Some(Err(own)),
        ..skip(why())
    }
    .sweep_error();
    assert!(matches!(answer, Error::Containment { .. }), "{answer:?}");
    assert_eq!(
        crate::error::first_os_code(&answer),
        Some(libc::EPERM),
        "the skip's reason is below the holders' error: {answer:?}"
    );
}

/// A skip is moot only over a tree this handle killed, and only because the root's number cannot be
/// trusted (macOS): a root reaped elsewhere and a handle that could not say leave the tree's number
/// in doubt for another reason.
///
/// Mutants: any one of the refusals reads as moot; a skip is moot over a tree never killed.
#[skuld::test]
fn a_skip_is_moot_only_over_a_killed_tree_whose_root_is_untrusted() {
    /// A reason, and whether it makes a skip moot over a killed tree.
    type Case = (&'static str, fn() -> Why, bool);
    let whys: [Case; 3] = [
        (
            "reaped elsewhere",
            || Why::MayNameAnother(Refusal::ReapedElsewhere(PID), None),
            false,
        ),
        (
            "handle could not say",
            || {
                Why::MayNameAnother(
                    Refusal::Unsure(PID, std::sync::Arc::new(std::io::Error::other("forced"))),
                    None,
                )
            },
            false,
        ),
        (
            "untrusted",
            || Why::Untrusted {
                why: "forced".to_owned(),
                cause: None,
            },
            true,
        ),
    ];
    for (name, why, moot) in whys {
        assert_eq!(skip(why()).is_moot(&killed(true)), moot, "{name}, tree killed");
        assert!(!skip(why()).is_moot(&killed(false)), "{name}, tree never killed");
    }
}

// A skip over an untrusted root settles the same for a tree call and a drop =====

/// A tree call that skipped an untrusted root answers an error but leaves the tree as it was, so a
/// later drop warns as a drop alone does. `swept`: whether the macOS fd marker's holders were swept.
///
/// Mutant: the tree call settles the skip as a kill that ran and left something, which leaves the
/// tree unvouched, so a drop after it warns that the tree could not be vouched for.
#[skuld::test]
fn a_tree_call_that_skipped_an_untrusted_root_leaves_the_drop_what_a_drop_alone_finds() {
    use super::SkipCall;
    use crate::containment::dispatch::TreeSignal;

    let untrusted = |swept: bool| Skip {
        holders: swept.then_some(Ok(())),
        ..skip(Why::untrusted(&crate::signal::RootState::Unpinned))
    };
    let call = SkipCall {
        op: "skip_untrusted_probe_c3",
        pid: PID,
        signal: TreeSignal::Kill,
        earlier: None,
    };
    for swept in [false, true] {
        let alone = killed(false);
        assert!(
            alone
                .settle_for_drop(TreeKillOutcome::Skipped(untrusted(swept)), false)
                .is_none(),
            "swept {swept}: a drop alone has nothing to warn of"
        );

        let called = killed(false);
        call.answer(&called, untrusted(swept), None)
            .answer
            .expect_err("a skipped kill is no success");
        assert!(!called.is_killed(), "swept {swept}: a skip kills nothing");
        let left = called.settle_for_drop(TreeKillOutcome::Skipped(untrusted(swept)), false);
        assert!(
            left.is_none(),
            "swept {swept}: the drop after a skipped tree call warns as a drop alone does: {:?}",
            left.map(|left| left.text)
        );
    }
}

type Kind = (&'static str, fn() -> Why);

/// The two kinds of skip a tree call settles: the root's number cannot be trusted (macOS), and it may
/// name another process.
fn kinds() -> [Kind; 2] {
    [
        ("untrusted", || Why::untrusted(&crate::signal::RootState::Unpinned)),
        ("may name another", || {
            Why::MayNameAnother(Refusal::ReapedElsewhere(PID), None)
        }),
    ]
}

fn kill_call(op: &'static str) -> super::SkipCall<'static> {
    super::SkipCall {
        op,
        pid: PID,
        signal: crate::containment::dispatch::TreeSignal::Kill,
        earlier: None,
    }
}

/// A tree that names its members by a walk, which settles held members by identity.
fn walking_tree() -> Tree {
    use crate::containment::mechanism::Mechanism;
    Tree::contained(Mechanism::Walk(crate::containment::treewalk::Walker::new(
        crate::identity::ProcessId::current(),
    )))
}

/// Members an earlier kill refused, as a settlement holds them: each is a pid and its identity, if
/// it was read.
fn refused(tree: &Tree, members: &[(u32, Option<crate::identity::ProcessId>)]) {
    use crate::containment::dispatch::Unkilled;
    tree.settle(
        TreeKillOutcome::Ran(Err(Unkilled {
            members: members
                .iter()
                .map(|&(pid, _)| crate::error::Error::MemberNotKilled {
                    pid,
                    source: std::sync::Arc::new(crate::error::Error::Unassessable {
                        detail: "its identity could not be read".into(),
                        source: None,
                    }),
                })
                .collect(),
            root: None,
            resolved: members.iter().filter_map(|&(_, id)| id).collect(),
        })),
        true,
    )
    .answer
    .expect_err("the members were left");
}

/// A skipped kill over a tree that holds a member an earlier kill refused answers that member, for
/// either kind of skip: the answer holds every member the tree is left with, whether or not the
/// skip's sweep of the marker holders ran, and says too that the kill by the root's number was
/// skipped.
///
/// Mutants: the settlement's answer is dropped when no holders were swept; the skip's words are
/// dropped when the settlement left a member.
#[skuld::test]
fn a_skipped_kill_answers_a_member_the_tree_holds_for_either_kind() {
    for (kind, why) in kinds() {
        let tree = walking_tree();
        refused(&tree, &[(7, None)]);

        let answer = kill_call("skip_held_probe_e1")
            .answer(&tree, skip(why()), None)
            .answer
            .expect_err("a skipped kill is no success");

        let members = answer.left_members();
        assert!(
            members
                .iter()
                .any(|member| matches!(member, crate::error::Error::MemberNotKilled { pid: 7, .. })),
            "{kind}: the member the tree holds is named: {answer:?}"
        );
        let said = crate::error::Report(&answer).to_string();
        assert!(
            said.contains("it did not kill its process group"),
            "{kind}: the skip is worded beside the member: {said}"
        );
    }
}

/// A skipped kill over a tree that holds a member it can kill again by identity and one it cannot
/// answers the second, and says the kill by the root's number was skipped and which member it killed,
/// for either kind of skip.
///
/// Mutant: the answer names only the member left, and not the member killed by identity.
#[skuld::test]
fn a_skipped_kill_that_left_a_member_says_what_it_skipped_and_killed() {
    for (kind, why) in kinds() {
        let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
        let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
        let tree = walking_tree();
        refused(&tree, &[(7, None), (id.pid(), Some(id))]);

        let settled = kill_call("skip_left_probe_h1").answer(&tree, skip(why()), None);

        drop(stdin);
        crate::test_child::assert_killed("the held member", blocker.wait().expect("reap the member"));
        assert_eq!(settled.killed_again, vec![id], "{kind}");
        let answer = settled.answer.expect_err("a skipped kill is no success");
        assert!(
            answer
                .left_members()
                .iter()
                .any(|member| matches!(member, crate::error::Error::MemberNotKilled { pid: 7, .. })),
            "{kind}: the member left is named: {answer:?}"
        );
        let said = crate::error::Report(&answer).to_string();
        assert!(
            said.contains(&format!("killed the members it held by identity (pid {})", id.pid())),
            "{kind}: {said}"
        );
        assert!(said.contains("it did not kill its process group"), "{kind}: {said}");
    }
}

/// A skipped kill that killed the members the handle held by identity says so, for either kind of
/// skip, and does not claim it sent nothing.
///
/// Mutant: the answer says "sent nothing" over a settlement that killed a held member.
#[skuld::test]
fn a_skipped_kill_that_killed_a_held_member_says_so_for_either_kind() {
    use crate::error::Error;
    for (kind, why) in kinds() {
        let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
        let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
        let tree = walking_tree();
        refused(&tree, &[(id.pid(), Some(id))]);

        let settled = kill_call("skip_held_probe_e2").answer(&tree, skip(why()), None);

        // Released after the kill: a settlement that sent nothing lets the member exit on EOF, which
        // fails the assertion instead of leaving a wait unbounded.
        drop(stdin);
        crate::test_child::assert_killed("the held member", blocker.wait().expect("reap the member"));
        assert_eq!(settled.killed_again, vec![id], "{kind}");
        let answer = settled.answer.expect_err("a skipped kill is no success");
        let Error::Unassessable { detail, .. } = &answer else {
            panic!("{kind}: got {answer:?}");
        };
        let said = format!("killed the members it held by identity (pid {})", id.pid());
        assert!(detail.contains(&said), "{kind}: {detail}");
        assert!(!detail.contains("sent nothing"), "{kind}: {detail}");
    }
}

/// A skipped kill that sent the root a signal through its handle and killed a held member by identity
/// says both, and never that it sent nothing else; the warn of a skip that may name another process
/// carries the held member too.
///
/// Mutants: a row of the root's words says "sent nothing" or "nothing else" beside a member killed by
/// identity; the "; it also" clause is dropped; the warn omits the member killed by identity.
#[skuld::test]
fn a_skipped_kill_that_signalled_the_root_and_killed_a_held_member_says_both() {
    use crate::error::Error;
    use crate::signal::Sent;
    crate::log_capture::install();
    // What the call sent the root, and the words that say it.
    let rows = [
        (
            Sent::Delivered,
            "killed the root through its pidfd, which names it exactly",
        ),
        (Sent::Gone, "sent nothing to the root: its pidfd shows it is gone"),
    ];
    for (kind, why) in kinds() {
        for (sent, said_of_root) in rows {
            let (blocker, stdin) = crate::test_child::held_uncontained_blocker(false);
            let id = blocker.id().expect(crate::test_child::IDENTITY_READ);
            let tree = walking_tree();
            refused(&tree, &[(id.pid(), Some(id))]);
            let mark = crate::log_capture::mark();

            let settled = kill_call("skip_held_probe_e3").answer(&tree, skip(why()), Some(Ok(sent)));

            drop(stdin);
            crate::test_child::assert_killed("the held member", blocker.wait().expect("reap the member"));
            let answer = settled.answer.expect_err("a skipped kill is no success");
            let Error::Unassessable { detail, .. } = &answer else {
                panic!("{kind}: got {answer:?}");
            };
            let held = format!("killed the members it held by identity (pid {})", id.pid());
            assert!(
                detail.contains(&format!("{said_of_root}; it also {held}")),
                "{kind}: {detail}"
            );
            assert!(!detail.contains("nothing else"), "{kind}: {detail}");
            let warns = crate::log_capture::warns_since(mark, "skip_held_probe_e3");
            if kind == "untrusted" {
                assert!(warns.is_empty(), "{kind}: an untrusted skip never warns: {warns:?}");
            } else {
                assert_eq!(warns.len(), 1, "{kind}: {warns:?}");
                assert!(
                    warns[0].contains(&format!("{said_of_root}; it also {held}")),
                    "{warns:?}"
                );
            }
        }
    }
}

/// A skipped kill whose sweep of the marker holders failed answers that failure and leaves the drop a
/// warn, whichever of the tree call and the drop ran first, for either kind of skip.
///
/// Mutant: a kind of skip settles differently in a tree call than in a drop.
#[skuld::test]
fn a_skipped_kill_whose_holders_failed_leaves_the_drop_a_warn_in_either_order() {
    use crate::error::Error;
    for (kind, why) in kinds() {
        let failing = || Skip {
            holders: Some(Err(Error::Containment {
                detail: "the holders' sweep failed".into(),
                source: None,
            })),
            ..skip(why())
        };
        let call = kill_call("skip_failed_probe_f1");
        let says = |answer: Error| {
            assert!(
                matches!(&answer, Error::Containment { detail, .. } if detail == "the holders' sweep failed"),
                "{kind}: {answer:?}"
            );
        };

        let called_first = killed(false);
        says(
            call.answer(&called_first, failing(), None)
                .answer
                .expect_err("a failed sweep is no success"),
        );
        let after = called_first
            .settle_for_drop(TreeKillOutcome::Skipped(failing()), false)
            .unwrap_or_else(|| panic!("{kind}: the drop after the call warns"));

        let dropped_first = killed(false);
        let before = dropped_first
            .settle_for_drop(TreeKillOutcome::Skipped(failing()), false)
            .unwrap_or_else(|| panic!("{kind}: the drop alone warns"));
        says(
            call.answer(&dropped_first, failing(), None)
                .answer
                .expect_err("a failed sweep is no success"),
        );

        assert_eq!(
            after.text, before.text,
            "{kind}: the drop warns the same in both orders"
        );
    }
}

/// A skipped call over a tree this handle already killed is moot when its reason is one a kill does
/// not outlive (an untrusted root): a kill and a terminate answer `Ok`
/// and warn of nothing. A root reaped elsewhere outlives the kill, so it is the control: it answers
/// an error and warns.
///
/// Mutants: an untrusted skip over a killed tree answers `Unassessable`; a moot skip warns; the
/// control is moot.
#[skuld::test]
fn a_skipped_call_over_a_killed_tree_is_moot_when_a_kill_does_not_outlive_its_reason() {
    use crate::containment::dispatch::TreeSignal;
    crate::log_capture::install();
    type Case = (&'static str, fn() -> Why, bool);
    let cases: [Case; 2] = [
        (
            "untrusted",
            || Why::untrusted(&crate::signal::RootState::Unpinned),
            true,
        ),
        (
            "reaped elsewhere",
            || Why::MayNameAnother(Refusal::ReapedElsewhere(PID), None),
            false,
        ),
    ];
    for (name, why, moot) in cases {
        for signal in [TreeSignal::Kill, TreeSignal::Term] {
            let mark = crate::log_capture::mark();
            let answer = super::SkipCall {
                op: "skip_moot_probe_g1",
                pid: PID,
                signal,
                earlier: None,
            }
            .answer(&killed(true), skip(why()), None)
            .answer;
            let warns = crate::log_capture::warns_since(mark, "skip_moot_probe_g1");
            if moot {
                answer.unwrap_or_else(|e| panic!("{name}, {signal:?}: a moot skip answers Ok: {e:?}"));
                assert!(
                    warns.is_empty(),
                    "{name}, {signal:?}: a moot skip warns of nothing: {warns:?}"
                );
            } else {
                answer.expect_err("a root reaped elsewhere leaves the tree in doubt");
                assert_eq!(warns.len(), 1, "{name}, {signal:?}: {warns:?}");
            }
        }
    }
}

/// A moot skip is decided under the settlement's own lock: over a tree that was killed and then
/// moved off `Killed` (a later kill left a member), the skip is not moot and answers an error.
///
/// Mutant: the skip's moot decision is read before, and apart from, the settlement.
#[skuld::test]
fn a_skip_is_not_moot_over_a_tree_moved_off_killed() {
    let whys: [fn() -> Why; 1] = [|| Why::untrusted(&crate::signal::RootState::Unpinned)];
    for why in whys {
        let tree = walking_tree();
        tree.settle(TreeKillOutcome::Ran(Ok(())), true)
            .answer
            .expect("a kill that left nothing");
        assert!(tree.is_killed());
        refused(&tree, &[(7, None)]);
        assert!(!tree.is_killed(), "a member left moves the tree off killed");

        kill_call("skip_moot_probe_g2")
            .answer(&tree, skip(why()), None)
            .answer
            .expect_err("a skip over a tree that is not killed is not moot");
    }
}

/// A moot skip whose signal to the root failed answers `Ok` and says the failure in a debug line: the
/// killed tree makes it moot, and nothing else reports it.
///
/// Mutant: the root's failure is dropped without a trace.
#[skuld::test]
fn a_moot_skips_root_failure_is_logged_at_debug() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let root = crate::error::Error::Unassessable {
        detail: "the root's signal failed".into(),
        source: None,
    };

    kill_call("skip_moot_probe_g3")
        .answer(
            &killed(true),
            skip(Why::untrusted(&crate::signal::RootState::Unpinned)),
            Some(Err(root)),
        )
        .answer
        .expect("a moot skip answers Ok");

    let records = crate::log_capture::records_since(mark, "skip_moot_probe_g3");
    assert!(
        records
            .iter()
            .any(|record| record.contains("the signal to the root failed")
                && record.contains("the root's signal failed")),
        "{records:?}"
    );
}

// The other failures of a skipped call join the error it returns =====

/// A skip whose reason holds an error with the code `code`.
fn unsure(code: i32) -> Why {
    Why::MayNameAnother(
        Refusal::Unsure(PID, std::sync::Arc::new(std::io::Error::from_raw_os_error(code))),
        None,
    )
}

fn term_call(op: &'static str) -> super::SkipCall<'static> {
    super::SkipCall {
        op,
        pid: PID,
        signal: crate::containment::dispatch::TreeSignal::Term,
        earlier: None,
    }
}

/// The codes of the members of the `Several` an error holds as its source, in order.
fn codes_below(error: &crate::error::Error) -> Vec<Option<i32>> {
    use std::error::Error as _;
    let source = error.source().and_then(|s| s.downcast_ref::<crate::error::Error>());
    let Some(crate::error::Error::Several(list)) = source else {
        panic!("expected a Several below the variant: {error:?}");
    };
    list.iter()
        .map(|member| crate::error::first_os_code(&**member))
        .collect()
}

/// A call whose holders' sweep failed and whose root signal failed too returns the holders' error with
/// the root's failure and the refusal's cause below its variant, in that order. No member's words
/// are in the detail.
///
/// Mutants: the root's failure is dropped when the holders failed; the refusal's cause is dropped.
#[skuld::test]
fn a_skipped_call_whose_holders_and_root_both_failed_keeps_both_and_the_reason() {
    use crate::error::Error;
    let holders = Error::Containment {
        detail: "the holders' sweep failed".into(),
        source: None,
    };
    let root = Error::Unassessable {
        detail: "the root's signal failed".into(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
    };

    let answer = term_call("skip_peers_probe_a1")
        .answer(
            &killed(false),
            Skip {
                holders: Some(Err(holders)),
                ..skip(unsure(libc::EACCES))
            },
            Some(Err(root)),
        )
        .answer
        .expect_err("a skipped call is no success");

    let Error::Containment { detail, .. } = &answer else {
        panic!("the holders' variant is kept: {answer:?}");
    };
    assert_eq!(detail, "the holders' sweep failed");
    assert_eq!(codes_below(&answer), [Some(libc::EPERM), Some(libc::EACCES)]);
}

/// A root signal that failed with a variant that holds a cause (not an `Error::Io`, which keeps its
/// code as it is) takes the refusal's cause as a peer of its own.
#[skuld::test]
fn a_skipped_calls_root_failure_takes_the_reason_as_a_peer() {
    use crate::error::Error;
    let root = Error::Unassessable {
        detail: "the root's signal failed".into(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
    };

    let answer = term_call("skip_peers_probe_a2")
        .answer(&killed(false), skip(unsure(libc::EACCES)), Some(Err(root)))
        .answer
        .expect_err("a skipped call is no success");

    assert!(matches!(&answer, Error::Unassessable { detail, .. } if detail == "the root's signal failed"));
    assert_eq!(codes_below(&answer), [Some(libc::EPERM), Some(libc::EACCES)]);
}

/// A root signal that failed with an `Error::Io`, a leaf with no slot for peers, goes below the call's
/// `Unassessable`, after the refusal's cause: also when nothing else failed. Its code is found down
/// the chain, as `Error`'s "The OS code" section promises.
///
/// Mutants: the `Io` is returned bare; the `Io` is dropped; it comes before the refusal's cause.
#[skuld::test]
fn a_skipped_calls_io_failure_goes_below_the_unassessable_after_the_reason() {
    use crate::error::Error;
    let eperm = || Error::Io(std::io::Error::from_raw_os_error(libc::EPERM));

    let answer = term_call("skip_peers_probe_a3")
        .answer(&killed(false), skip(unsure(libc::EACCES)), Some(Err(eperm())))
        .answer
        .expect_err("a skipped call is no success");
    assert!(matches!(&answer, Error::Unassessable { .. }), "{answer:?}");
    assert_eq!(codes_below(&answer), [Some(libc::EACCES), Some(libc::EPERM)]);

    let alone = term_call("skip_peers_probe_a4")
        .answer(
            &killed(false),
            skip(Why::MayNameAnother(Refusal::ReapedElsewhere(PID), None)),
            Some(Err(eperm())),
        )
        .answer
        .expect_err("a skipped call is no success");
    assert!(matches!(&alone, Error::Unassessable { .. }), "{alone:?}");
    assert_eq!(crate::error::first_os_code(&alone), Some(libc::EPERM), "{alone:?}");
}

/// A call over an untrusted root (macOS) whose holders' sweep failed returns that failure with the
/// error of the root's state below it, which was only a debug line.
#[skuld::test]
fn an_untrusted_roots_cause_joins_the_failed_holders_sweep() {
    use crate::error::Error;
    let untrusted = Why::Untrusted {
        why: "its state could not be read".to_owned(),
        cause: Some(std::sync::Arc::new(std::io::Error::from_raw_os_error(libc::EACCES))),
    };
    let holders = Error::Containment {
        detail: "the holders' sweep failed".into(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
    };

    let answer = term_call("skip_peers_probe_b1")
        .answer(
            &killed(false),
            Skip {
                holders: Some(Err(holders)),
                ..skip(untrusted)
            },
            None,
        )
        .answer
        .expect_err("a skipped call is no success");

    assert!(matches!(&answer, Error::Containment { detail, .. } if detail == "the holders' sweep failed"));
    assert_eq!(codes_below(&answer), [Some(libc::EPERM), Some(libc::EACCES)]);
}

/// A reason that holds two causes (a handle that could not say, and the group probe that failed
/// before it) joins a failed holders' sweep as two more members of one flat list in a sweep's error,
/// and below the skip's own `Unassessable` in a call's.
///
/// Mutant: the reason's `Several` is nested in the sweep's list as one member.
#[skuld::test]
fn a_reason_with_two_causes_joins_the_failed_holders_sweep_flat() {
    use crate::error::Error;
    let reason = || {
        Why::MayNameAnother(
            Refusal::Unsure(
                PID,
                std::sync::Arc::new(std::io::Error::from_raw_os_error(libc::EACCES)),
            ),
            Some(libc::EMFILE),
        )
    };
    let holders = || Error::Containment {
        detail: "the holders' sweep failed".into(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
    };
    let expected = [Some(libc::EPERM), Some(libc::EACCES), Some(libc::EMFILE)];

    // In the call's answer the causes are below the skip's own `Unassessable`, the one peer.
    let answer = term_call("skip_peers_probe_d1")
        .answer(
            &killed(false),
            Skip {
                holders: Some(Err(holders())),
                ..skip(reason())
            },
            None,
        )
        .answer
        .expect_err("a skipped call is no success");
    assert_eq!(
        codes_below(&answer),
        [Some(libc::EPERM), Some(libc::EACCES)],
        "{answer:?}"
    );
    let Some(Error::Several(list)) = std::error::Error::source(&answer).and_then(|s| s.downcast_ref::<Error>()) else {
        panic!("expected a Several below the variant: {answer:?}");
    };
    let skipped = list.iter().nth(1).expect("the skip's own Unassessable is the peer");
    assert!(matches!(&**skipped, Error::Unassessable { .. }), "{skipped:?}");
    let below: Vec<_> = skipped
        .failures_below()
        .into_iter()
        .map(|member| crate::error::first_os_code(member))
        .collect();
    assert_eq!(below, [Some(libc::EACCES), Some(libc::EMFILE)], "{skipped:?}");

    let swept = Skip {
        holders: Some(Err(holders())),
        ..skip(reason())
    }
    .sweep_error();
    assert_eq!(codes_below(&swept), expected, "{swept:?}");
}

/// The kill after a holders-only `SIGTERM` that failed too (macOS) returns the kill's error with the
/// `SIGTERM`'s failure and the skip's reason below its variant, in that order; a kill that left nothing
/// is the call's `Unassessable` with the reason first, then the `SIGTERM`'s failure.
///
/// Mutants: the `SIGTERM`'s failure stays in the warn; it comes after the reason.
#[skuld::test]
fn a_holders_only_kill_that_failed_takes_the_term_and_the_reason_as_peers() {
    use crate::containment::dispatch::Unkilled;
    use crate::error::Error;
    let kill = Error::Containment {
        detail: "a holder refused the kill".into(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
    };
    let term_failed = || Error::Containment {
        detail: "a holder refused the SIGTERM".into(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EIO))),
    };

    let settled = term_call("skip_peers_probe_c1").holders_settled(
        &killed(false),
        Skip {
            holders: Some(Err(term_failed())),
            ..skip(unsure(libc::EACCES))
        },
        TreeKillOutcome::Ran(Err(Unkilled::from(kill))),
    );
    assert!(matches!(&settled.answer, Error::Containment { detail, .. } if detail == "a holder refused the kill"));
    assert_eq!(
        codes_below(&settled.answer),
        [Some(libc::EPERM), Some(libc::EIO), Some(libc::EACCES)]
    );

    let settled = term_call("skip_peers_probe_c2").holders_settled(
        &killed(false),
        Skip {
            holders: Some(Err(term_failed())),
            ..skip(unsure(libc::EACCES))
        },
        TreeKillOutcome::Ran(Ok(())),
    );
    assert!(
        matches!(&settled.answer, Error::Unassessable { .. }),
        "{:?}",
        settled.answer
    );
    assert_eq!(codes_below(&settled.answer), [Some(libc::EACCES), Some(libc::EIO)]);
}

/// A Linux call that signalled the root through its pidfd and failed, over a skip with a reason,
/// returns the signal's error with the reason below its variant, and an `Error::Io` (a leaf) goes below
/// the call's `Unassessable` after the reason.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_pidfd_shutdown_that_failed_takes_the_reason_as_a_peer() {
    use crate::child::graceful::PidfdShutdown;
    use crate::error::Error;
    let failed = |term: Error| {
        let child = crate::child::owned::OwnedChild::new(
            Box::new(crate::os_process::fake::FakeProcess::new([]).with_exact_consume(false)),
            crate::elevation::front::TrackedKind::Own,
        );
        PidfdShutdown::start(&child, || Err(term))
            .expect("the rule let the SIGTERM through")
            .finish(
                &term_call("skip_peers_probe_d1"),
                &skip(unsure(libc::EACCES)),
                None,
                || Ok(crate::signal::Sent::Delivered),
            )
    };

    let answer = failed(Error::Unassessable {
        detail: "the SIGTERM failed".into(),
        source: Some(Error::io_cause(std::io::Error::from_raw_os_error(libc::EPERM))),
    });
    assert!(matches!(&answer, Error::Unassessable { detail, .. } if detail == "the SIGTERM failed"));
    assert_eq!(codes_below(&answer), [Some(libc::EPERM), Some(libc::EACCES)]);

    let answer = failed(Error::Io(std::io::Error::from_raw_os_error(libc::EPERM)));
    assert!(matches!(&answer, Error::Unassessable { .. }), "{answer:?}");
    assert_eq!(codes_below(&answer), [Some(libc::EACCES), Some(libc::EPERM)]);
}