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
//! The look arm of the teardown policy of `OwnedChild` over a `FakeProcess`: an elevation front,
//! which is sent nothing (see `owned::teardown`). The signals table of every fake is empty, so a
//! signal panics.

use std::cell::RefCell;
use std::io;
use std::time::Duration;

use super::teardown::{due_now, exit, fake, fire_on_block, id, slow_warns, PID};
use crate::child::owned::teardown::{FrontLook, LookOutcome, Reach};
use crate::child::owned::OwnedChild;
use crate::elevation::front::TrackedKind;
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
use crate::os_process::child::Foreign;
use crate::os_process::fake::{FakeProcess, ReapAnswer};

/// A [`Reach`] with a stated answer, and the pids of the children it was asked about.
pub(super) struct FakeReach {
    answer: Result<bool, Failing>,
    asked: RefCell<Vec<Option<u32>>>,
}

/// How a [`FakeReach`] fails: an I/O error of a kind, or a refusal.
#[derive(Clone, Copy)]
enum Failing {
    Kind(io::ErrorKind),
    Refused,
}

/// The refusal a [`FakeReach::refusing`] answers with.
fn refusal() -> Error {
    Error::Unsupported {
        op: "reading where the front is".to_owned(),
        platform: "linux",
        detail: "cosca requires openat2 (Linux \u{2265} 5.6), refused here".to_owned(),
        source: Some(Error::io_cause(io::Error::from(io::ErrorKind::Other))),
    }
}

impl FakeReach {
    pub(super) fn answering(answer: Result<bool, io::ErrorKind>) -> Self {
        Self {
            answer: answer.map_err(Failing::Kind),
            asked: RefCell::default(),
        }
    }

    /// A reach that answers [`refusal`].
    fn refusing() -> Self {
        Self {
            answer: Err(Failing::Refused),
            asked: RefCell::default(),
        }
    }

    pub(super) fn asked(&self) -> Vec<Option<u32>> {
        self.asked.borrow().clone()
    }
}

impl Reach for FakeReach {
    fn reached(&self, child: &OwnedChild) -> Result<bool, Error> {
        self.asked.borrow_mut().push(child.pid());
        self.would_reach(child)
    }

    fn would_reach(&self, _child: &OwnedChild) -> Result<bool, Error> {
        self.answer.map_err(|failing| match failing {
            Failing::Kind(kind) => Error::Io(io::Error::from(kind)),
            Failing::Refused => refusal(),
        })
    }
}

/// What the look at a front is given to tell whether a kill sent elsewhere reached it: a reach, or
/// none; or the failure of reading the subtree that kill went through.
type Reaches<'a> = Result<Option<&'a dyn Reach>, Error>;

/// `look_at_front(id, reach, warn_after)` over `fake`, and everything it logged on this thread.
fn look_logged(
    fake: &FakeProcess,
    id: Option<ProcessId>,
    reach: Reaches<'_>,
    warn_after: Option<Duration>,
) -> (FrontLook, Vec<(log::Level, String)>) {
    crate::log_capture::install();
    let child = OwnedChild::new(Box::new(fake.clone()), TrackedKind::Own);
    let mark = crate::log_capture::mark();
    let torn = child.look_at_front(id, reach, warn_after);
    (torn, crate::log_capture::records_since_on_current_thread(mark, ""))
}

fn look(fake: &FakeProcess, reach: Option<&dyn Reach>) -> FrontLook {
    look_logged(fake, Some(id()), Ok(reach), None).0
}

/// How the look at a front went, as far as the tests tell it apart.
#[derive(Debug, PartialEq, Eq)]
enum Went {
    /// The look, or the wait after it, ended; the fate says how, and `word_front` words it.
    Ended,
    LeftRunning,
    PlaceUnreadable,
    SubtreeUnreadable,
}

fn went(torn: &FrontLook) -> Went {
    match &torn.look {
        LookOutcome::Ended(_) => Went::Ended,
        LookOutcome::LeftRunning => Went::LeftRunning,
        LookOutcome::PlaceUnreadable(_) => Went::PlaceUnreadable,
        LookOutcome::SubtreeUnreadable(_) => Went::SubtreeUnreadable,
    }
}

/// The policy words nothing of a front: what the drop says is its own, from the typed look.
#[track_caller]
fn assert_outcome(torn: &FrontLook, fate: ChildFate, went_as: Went) {
    assert_eq!((&torn.fate, went(torn)), (&fate, went_as), "{torn:?}");
}

/// A front that has exited at the look is reaped, and nothing asks where it is.
///
/// Mutant: the reach is asked first.
#[skuld::test]
fn a_front_that_has_exited_is_reaped_without_asking_where_it_is() {
    let fake = fake().reaps([ReapAnswer::Exited(exit())]);
    let reach = FakeReach::answering(Ok(true));
    let torn = look(&fake, Some(&reach));
    assert_outcome(&torn, ChildFate::Reaped, Went::Ended);
    assert_eq!(reach.asked(), []);
}

/// A running front with no reach is left running, not waited for, and not worded by the policy.
///
/// Mutants: it is waited for; it is called reaped; the policy words it.
#[skuld::test]
fn a_running_front_with_no_reach_is_left_running_and_not_waited_for() {
    let fake = fake().reaps([ReapAnswer::Running]);
    let _fire = fire_on_block(&fake);
    let torn = look(&fake, None);
    assert_outcome(&torn, ChildFate::Running { id: Some(id()) }, Went::LeftRunning);
    assert_eq!(fake.looks(), 1);
    assert_eq!(crate::wait::block_probe::take(), [], "no wait");
}

/// A running front the kill did not reach is left, as with no reach, and the reach was asked once
/// about this child.
///
/// Mutant: `Ok(false)` is taken for `Ok(true)`.
#[skuld::test]
fn a_running_front_the_kill_did_not_reach_is_left_running() {
    let fake = fake().reaps([ReapAnswer::Running]);
    let _fire = fire_on_block(&fake);
    let reach = FakeReach::answering(Ok(false));
    let torn = look(&fake, Some(&reach));
    assert_outcome(&torn, ChildFate::Running { id: Some(id()) }, Went::LeftRunning);
    assert_eq!(reach.asked(), [Some(PID)]);
    assert_eq!(crate::wait::block_probe::take(), [], "no wait");
}

/// A running front the kill reached is dying: it is waited for, without a bound, and reaped.
///
/// Mutants: it is left; the wait is a look; the wait is bounded.
#[skuld::test]
fn a_running_front_the_kill_reached_is_waited_for_and_reaped() {
    let fake = fake().reaps([ReapAnswer::Running, ReapAnswer::Running, ReapAnswer::Exited(exit())]);
    let _fire = fire_on_block(&fake);
    let torn = look(&fake, Some(&FakeReach::answering(Ok(true))));
    assert_outcome(&torn, ChildFate::Reaped, Went::Ended);
    assert_eq!(fake.looks(), 3, "the look, the wait's look, the look the wait woke to");
    assert_eq!(crate::wait::block_probe::take(), [None], "one unbounded block");
}

/// A wait for a dying front that fails leaves it unaccounted for. The kill landed, so the fate is
/// `Killed`.
///
/// Mutant: the failure is dropped; the fate is `Unknown`.
#[skuld::test]
fn a_failed_wait_for_a_reached_front_is_unaccounted_for() {
    let fake = fake().reaps([ReapAnswer::Running, ReapAnswer::Err(io::ErrorKind::Other)]);
    let _fire = fire_on_block(&fake);
    let torn = look(&fake, Some(&FakeReach::answering(Ok(true))));
    assert_outcome(&torn, ChildFate::Killed, Went::Ended);
}

/// A front reaped by someone else between the look and the wait is `Killed` (the cgroup kill landed
/// first), unaccounted for, and nothing above `debug` is logged.
///
/// Mutants: the foreign reap is warned of; it is `Gone`.
#[skuld::test]
fn a_front_reaped_elsewhere_between_the_look_and_the_wait_is_killed_and_silent() {
    let fake = fake().reaps([ReapAnswer::Running, ReapAnswer::Foreign(Foreign::Gone)]);
    let _fire = fire_on_block(&fake);
    let (torn, records) = look_logged(&fake, Some(id()), Ok(Some(&FakeReach::answering(Ok(true)))), None);
    assert_outcome(&torn, ChildFate::Killed, Went::Ended);
    assert!(
        records.iter().all(|(level, _)| *level >= log::Level::Debug),
        "{records:?}"
    );
}

/// A front reaped by someone else in the wait for it, whose zombie launchd holds, is `Killed`, as for
/// any foreign reap after the kill, and the policy logs nothing above `debug`: the note is the
/// wording's.
///
/// Mutant: the policy logs the launchd note itself.
#[skuld::test]
fn a_dying_front_launchd_holds_is_killed_and_not_logged_by_the_policy() {
    let fake = fake().reaps([ReapAnswer::Running, ReapAnswer::Foreign(Foreign::Orphaned)]);
    let _fire = fire_on_block(&fake);
    let (torn, records) = look_logged(&fake, Some(id()), Ok(Some(&FakeReach::answering(Ok(true)))), None);
    assert_outcome(&torn, ChildFate::Killed, Went::Ended);
    assert!(
        records.iter().all(|(level, _)| *level < log::Level::Warn),
        "{records:?}"
    );
}

/// A front whose place cannot be read is not waited for. The look saw it running, so its fate is
/// `Running`, and it is left for an unreadable place.
///
/// Mutants: an unreadable place is taken for reached; the fate is `Unknown`.
#[skuld::test]
fn a_front_whose_place_cannot_be_read_is_left_running_and_not_waited_for() {
    let fake = fake().reaps([ReapAnswer::Running]);
    let _fire = fire_on_block(&fake);
    let torn = look(&fake, Some(&FakeReach::answering(Err(io::ErrorKind::Other))));
    assert_outcome(&torn, ChildFate::Running { id: Some(id()) }, Went::PlaceUnreadable);
    assert_eq!(fake.looks(), 1);
    assert_eq!(crate::wait::block_probe::take(), [], "no wait");
}

/// What the test reads an error back by, to tell the error that went in from a copy of it.
#[derive(Debug)]
struct Original;

impl std::fmt::Display for Original {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("the leaf cannot be read")
    }
}

impl std::error::Error for Original {}

/// A front whose leaf's subtree cannot be read is left running for that, not for an unreadable
/// place, with the very error it was given.
///
/// Mutants: an unreadable subtree is reported as an unreadable place; the error is rebuilt from its
/// kind and text; the fate is `Unknown`.
#[skuld::test]
fn a_front_whose_subtree_cannot_be_read_is_left_for_the_subtree_with_its_own_error() {
    let fake = fake().reaps([ReapAnswer::Running]);
    let unreadable = Error::Io(io::Error::new(io::ErrorKind::PermissionDenied, Original));
    let (torn, _) = look_logged(&fake, Some(id()), Err(unreadable), None);
    assert_outcome(&torn, ChildFate::Running { id: Some(id()) }, Went::SubtreeUnreadable);
    let LookOutcome::SubtreeUnreadable(Error::Io(e)) = &torn.look else {
        panic!("{torn:?}");
    };
    assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
    assert!(e.get_ref().is_some_and(|inner| inner.is::<Original>()), "{e:?}");
}

/// A front that has exited is reaped whatever the subtree: the subtree is asked about only for a
/// front still running.
///
/// Mutant: an unreadable subtree is looked at before the front.
#[skuld::test]
fn a_front_that_has_exited_is_reaped_though_its_subtree_cannot_be_read() {
    let fake = fake().reaps([ReapAnswer::Exited(exit())]);
    let (torn, _) = look_logged(
        &fake,
        Some(id()),
        Err(Error::Io(io::Error::from(io::ErrorKind::Other))),
        None,
    );
    assert_outcome(&torn, ChildFate::Reaped, Went::Ended);
}

/// What a drop says of each way it ends a front, word for word as the drop on `azhukova/dev` does:
/// the front's pid, then the cause, with `why` in the running one's. The wording goes through the
/// drop's own rendering, over what `tear_down` returned.
#[cfg(unix)]
mod worded {
    use super::super::teardown::warn_of;
    use super::super::teardown_lines::said_of;
    use super::*;
    use crate::child::lifecycle::Wording;
    use crate::child::owned::teardown::{Disposition, TeardownOutcome};

    const WHY: &str = "the front is not in a cgroup this drop killed";

    /// The two things a caller can do with a front still running. An outcome that hands nothing
    /// back is worded the same under both.
    const BOTH: [Disposition; 2] = [Disposition::Leave, Disposition::HandBack];

    /// The outcome of `tear_down` over `fake`, as the drop words it for a caller that does
    /// `disposition`, and what the wording logged: nothing, the caller logs the clause.
    fn worded_by_the_drop(
        disposition: Disposition,
        fake: &FakeProcess,
        reach: Reaches<'_>,
    ) -> (TeardownOutcome, Vec<(log::Level, String)>) {
        let (torn, _) = look_logged(fake, Some(id()), reach, None);
        let mark = crate::log_capture::mark();
        let worded = crate::child::word_front(PID, &WHY, disposition, torn);
        (
            worded,
            crate::log_capture::records_since_on_current_thread(mark, "elevation front pid"),
        )
    }

    fn cause() -> String {
        crate::error::said(&Error::Io(io::Error::from(io::ErrorKind::Other)))
    }

    /// The clause is a warn that says `wanted`, for the caller's one warn.
    #[track_caller]
    fn assert_left(disposition: Disposition, reach: Reaches<'_>, fake: &FakeProcess, wanted: &str) {
        let _fire = fire_on_block(fake);
        let (worded, records) = worded_by_the_drop(disposition, fake, reach);
        assert_eq!(warn_of(&worded), Some(wanted), "{disposition:?}: {worded:?}");
        assert_eq!(records, [], "the wording logs nothing: the caller does");
    }

    /// The clause is a `debug` line that says `wanted`.
    #[track_caller]
    fn assert_debug(disposition: Disposition, reach: Reaches<'_>, fake: &FakeProcess, wanted: &str) {
        let _fire = fire_on_block(fake);
        let (worded, records) = worded_by_the_drop(disposition, fake, reach);
        assert_eq!(
            said_of(&worded),
            Some((log::Level::Debug, wanted.to_owned())),
            "{disposition:?}: {worded:?}"
        );
        assert_eq!(records, [], "the wording logs nothing: the caller does");
    }

    /// What `word_front` builds is uncollected (`wanted`) or not, as the look left the front.
    #[track_caller]
    fn assert_uncollected(disposition: Disposition, reach: Reaches<'_>, fake: &FakeProcess, wanted: bool) {
        let _fire = fire_on_block(fake);
        let (worded, _) = worded_by_the_drop(disposition, fake, reach);
        assert_eq!(
            matches!(worded.said(), Some(Wording::Uncollected(_))),
            wanted,
            "{disposition:?}: {worded:?}"
        );
        assert_eq!(worded.uncollected(), wanted, "{disposition:?}: {worded:?}");
    }

    /// A front is worded as uncollected exactly when it is still this process's: seen running (left,
    /// its place or its leaf's subtree unreadable) or whose look or wait failed; one reaped here or
    /// elsewhere is not.
    ///
    /// Mutant: `word_front` builds `Collected(Warn, ..)` for `LeftRunning`, `PlaceUnreadable` or
    /// `SubtreeUnreadable`.
    #[skuld::test]
    fn a_front_is_worded_uncollected_exactly_when_it_is_still_ours() {
        let unreadable = || Err(Error::Io(io::Error::from(io::ErrorKind::Other)));
        for disposition in BOTH {
            let running = || fake().reaps([ReapAnswer::Running]);
            assert_uncollected(disposition, Ok(None), &running(), true);
            assert_uncollected(
                disposition,
                Ok(Some(&FakeReach::answering(Ok(false)))),
                &running(),
                true,
            );
            assert_uncollected(
                disposition,
                Ok(Some(&FakeReach::answering(Err(io::ErrorKind::Other)))),
                &running(),
                true,
            );
            assert_uncollected(disposition, unreadable(), &running(), true);
            let failed = || fake().reaps([ReapAnswer::Err(io::ErrorKind::Other)]);
            assert_uncollected(disposition, Ok(None), &failed(), true);
            assert_uncollected(
                disposition,
                Ok(Some(&FakeReach::answering(Ok(true)))),
                &fake().reaps([ReapAnswer::Running, ReapAnswer::Err(io::ErrorKind::Other)]),
                true,
            );
            assert_uncollected(
                disposition,
                Ok(None),
                &fake().reaps([ReapAnswer::Exited(exit())]),
                false,
            );
            assert_uncollected(
                disposition,
                Ok(None),
                &fake().reaps([ReapAnswer::Foreign(Foreign::Gone)]),
                false,
            );
            assert_uncollected(
                disposition,
                Ok(Some(&FakeReach::answering(Ok(true)))),
                &fake().reaps([ReapAnswer::Running, ReapAnswer::Foreign(Foreign::Gone)]),
                false,
            );
        }
    }

    #[skuld::test]
    fn a_front_left_running_is_worded_with_why() {
        assert_left(
            Disposition::Leave,
            Ok(None),
            &fake().reaps([ReapAnswer::Running]),
            "elevation front pid 4242 is left running and unreaped: the front is not in a cgroup this drop killed, and a kill of the front would orphan the elevated program",
        );
        assert_left(
            Disposition::Leave,
            Ok(Some(&FakeReach::answering(Ok(false)))),
            &fake().reaps([ReapAnswer::Running]),
            "elevation front pid 4242 is left running and unreaped: the front is not in a cgroup this drop killed, and a kill of the front would orphan the elevated program",
        );
    }

    /// A caller that hands the front back says so, where the one that leaves it says it is left.
    ///
    /// Mutant: the wording ignores the disposition.
    #[skuld::test]
    fn a_front_left_running_is_worded_as_handed_back_for_a_caller_that_hands_it_back() {
        assert_left(
            Disposition::HandBack,
            Ok(None),
            &fake().reaps([ReapAnswer::Running]),
            "elevation front pid 4242 is running and unreaped: the front is not in a cgroup this drop killed, and a kill of the front would orphan the elevated program; handed back to the caller in the error",
        );
        assert_left(
            Disposition::HandBack,
            Ok(Some(&FakeReach::answering(Ok(false)))),
            &fake().reaps([ReapAnswer::Running]),
            "elevation front pid 4242 is running and unreaped: the front is not in a cgroup this drop killed, and a kill of the front would orphan the elevated program; handed back to the caller in the error",
        );
    }

    /// Mutant: `Leave` words the front as handed back.
    #[skuld::test]
    fn a_front_whose_place_cannot_be_read_is_worded_as_left_for_a_caller_that_leaves_it() {
        assert_left(
            Disposition::Leave,
            Ok(Some(&FakeReach::answering(Err(io::ErrorKind::Other)))),
            &fake().reaps([ReapAnswer::Running]),
            &format!("elevation front pid 4242 is left unreaped: where it is cannot be read ({}), so it is not known whether the cgroup kill ended it", cause()),
        );
    }

    /// Mutant: `HandBack` words the front as left.
    #[skuld::test]
    fn a_front_whose_place_cannot_be_read_is_worded_as_handed_back_for_a_caller_that_hands_it_back() {
        assert_left(
            Disposition::HandBack,
            Ok(Some(&FakeReach::answering(Err(io::ErrorKind::Other)))),
            &fake().reaps([ReapAnswer::Running]),
            &format!("elevation front pid 4242 is running and unreaped: where it is cannot be read ({}), so it is not known whether the cgroup kill ended it; handed back to the caller in the error", cause()),
        );
    }

    /// A refusal that hides where a front is reads in its own words, and the failure it leaves is
    /// still the `Unsupported` it was, with its cause.
    ///
    /// Mutants: the refusal is worded as an I/O failure; the failure is rebuilt as `Error::Io`.
    #[skuld::test]
    fn a_front_whose_place_a_refusal_hides_is_worded_in_its_own_words_and_fails_as_unsupported() {
        for disposition in BOTH {
            let fake = fake().reaps([ReapAnswer::Running]);
            let _fire = fire_on_block(&fake);
            let (worded, _) = worded_by_the_drop(disposition, &fake, Ok(Some(&FakeReach::refusing())));
            let said = crate::error::said(&refusal());
            let warn = warn_of(&worded).expect("a warn");
            assert!(
                warn.contains(&format!("where it is cannot be read ({said})")),
                "{disposition:?}: {warn}"
            );
            let failures = worded.remains().failures.expect("the look's failure");
            let listed: Vec<_> = failures.iter().collect();
            let [kept] = listed[..] else {
                panic!("{disposition:?}: {listed:?}");
            };
            let Error::Unsupported { source, .. } = &**kept else {
                panic!("{disposition:?}: {kept:?}");
            };
            assert!(source.is_some(), "{disposition:?}: the refusal's cause is kept");
        }
    }

    /// Mutant: `Leave` words the front as handed back.
    #[skuld::test]
    fn a_front_whose_subtree_cannot_be_read_is_worded_as_left_for_a_caller_that_leaves_it() {
        assert_left(
            Disposition::Leave,
            Err(Error::Io(io::Error::from(io::ErrorKind::Other))),
            &fake().reaps([ReapAnswer::Running]),
            &format!("elevation front pid 4242 is left unreaped: its leaf's subtree cannot be read ({}), so it is not known whether the cgroup kill ended it", cause()),
        );
    }

    /// Mutant: `HandBack` words the front as left.
    #[skuld::test]
    fn a_front_whose_subtree_cannot_be_read_is_worded_as_handed_back_for_a_caller_that_hands_it_back() {
        assert_left(
            Disposition::HandBack,
            Err(Error::Io(io::Error::from(io::ErrorKind::Other))),
            &fake().reaps([ReapAnswer::Running]),
            &format!("elevation front pid 4242 is running and unreaped: its leaf's subtree cannot be read ({}), so it is not known whether the cgroup kill ended it; handed back to the caller in the error", cause()),
        );
    }

    /// The suffix of an uncollected front: handed back by a caller that hands it back, left by one
    /// that leaves it.
    ///
    /// Mutant: the wording ignores the disposition.
    fn handed_back(disposition: Disposition) -> &'static str {
        match disposition {
            Disposition::Leave => crate::child::owned::owned_tests::teardown_lines::LEFT,
            Disposition::HandBack => crate::child::owned::owned_tests::teardown_lines::HANDED_BACK,
        }
    }

    /// A look that failed, and a wait that failed after the kill, are the same failed wait.
    #[skuld::test]
    fn a_front_whose_wait_failed_is_worded() {
        let worded = |disposition: Disposition| {
            format!(
                "elevation front pid 4242: the wait failed: {}{}",
                crate::child::owned::owned_tests::teardown_lines::wait_error(),
                handed_back(disposition)
            )
        };
        for disposition in BOTH {
            assert_left(
                disposition,
                Ok(None),
                &fake().reaps([ReapAnswer::Err(io::ErrorKind::Other)]),
                &worded(disposition),
            );
            assert_left(
                disposition,
                Ok(Some(&FakeReach::answering(Ok(true)))),
                &fake().reaps([ReapAnswer::Running, ReapAnswer::Err(io::ErrorKind::Other)]),
                &worded(disposition),
            );
        }
    }

    /// A front reaped with a status is said at `debug` as reaped, "after the kill" only after a wait
    /// that a kill sent elsewhere bounded.
    ///
    /// Mutants: the clause is a warn, or missing; "after the kill" ignores the kill.
    #[skuld::test]
    fn a_front_reaped_with_a_status_is_said_at_debug() {
        for disposition in BOTH {
            assert_debug(
                disposition,
                Ok(None),
                &fake().reaps([ReapAnswer::Exited(exit())]),
                "elevation front pid 4242: reaped it",
            );
            assert_debug(
                disposition,
                Ok(Some(&FakeReach::answering(Ok(true)))),
                &fake().reaps([ReapAnswer::Running, ReapAnswer::Running, ReapAnswer::Exited(exit())]),
                "elevation front pid 4242: reaped it after the kill",
            );
        }
    }

    /// A front whose zombie launchd holds is warned of at the first look and in the wait for it, led
    /// by its name.
    ///
    /// Mutant: the wording is quiet about launchd, or says it at `debug`.
    #[skuld::test]
    fn a_front_launchd_holds_is_warned_of_in_the_wording() {
        let note = "elevation front pid 4242: not ours to reap (launchd holds its zombie, because its tracer died)";
        for disposition in BOTH {
            assert_left(
                disposition,
                Ok(None),
                &fake().reaps([ReapAnswer::Foreign(Foreign::Orphaned)]),
                note,
            );
            assert_left(
                disposition,
                Ok(Some(&FakeReach::answering(Ok(true)))),
                &fake().reaps([ReapAnswer::Running, ReapAnswer::Foreign(Foreign::Orphaned)]),
                note,
            );
        }
    }

    #[skuld::test]
    fn a_front_reaped_by_someone_else_is_said_at_debug() {
        for disposition in BOTH {
            assert_debug(
                disposition,
                Ok(None),
                &fake().reaps([ReapAnswer::Foreign(Foreign::Gone)]),
                "elevation front pid 4242: reaped by someone else",
            );
            assert_debug(
                disposition,
                Ok(Some(&FakeReach::answering(Ok(true)))),
                &fake().reaps([ReapAnswer::Running, ReapAnswer::Foreign(Foreign::Gone)]),
                "elevation front pid 4242: reaped by someone else",
            );
        }
    }
}

/// A front someone else reaped is gone, unaccounted for.
///
/// Mutant: the look reads it as running.
#[skuld::test]
fn a_front_reaped_by_someone_else_is_gone() {
    let fake = fake().reaps([ReapAnswer::Foreign(Foreign::Gone)]);
    let reach = FakeReach::answering(Ok(true));
    let torn = look(&fake, Some(&reach));
    assert_outcome(&torn, ChildFate::Gone, Went::Ended);
    assert_eq!(reach.asked(), []);
}

/// A place a refusal hides is held as the `Unsupported` it was, not rebuilt as an I/O failure.
///
/// Mutant: the look wraps the reach's error as `Error::Io`.
#[skuld::test]
fn a_front_whose_place_a_refusal_hides_keeps_the_refusal() {
    let fake = fake().reaps([ReapAnswer::Running]);
    let torn = look(&fake, Some(&FakeReach::refusing()));
    assert_outcome(&torn, ChildFate::Running { id: Some(id()) }, Went::PlaceUnreadable);
    let LookOutcome::PlaceUnreadable(Error::Unsupported { op, .. }) = &torn.look else {
        panic!("{torn:?}");
    };
    assert_eq!(op, "reading where the front is");
}

/// A front whose zombie launchd holds is gone and collected, and the policy logs nothing above
/// `debug`: the launchd note is the wording's.
///
/// Mutant: the policy logs that launchd holds the zombie.
#[skuld::test]
fn a_front_launchd_holds_is_gone_and_not_logged_by_the_policy() {
    let fake = fake().reaps([ReapAnswer::Foreign(Foreign::Orphaned)]);
    let (torn, records) = look_logged(&fake, Some(id()), Ok(None), None);
    assert_outcome(&torn, ChildFate::Gone, Went::Ended);
    assert!(
        records.iter().all(|(level, _)| *level < log::Level::Warn),
        "{records:?}"
    );
}

/// A front with no pid that launchd holds is as quiet in the policy.
///
/// Mutant: the note is built for a pid-less front.
#[skuld::test]
fn a_pidless_front_launchd_holds_is_gone_and_not_logged_by_the_policy() {
    let fake = FakeProcess::new([]).reaps([ReapAnswer::Foreign(Foreign::Orphaned)]);
    let (torn, records) = look_logged(&fake, None, Ok(None), None);
    assert_outcome(&torn, ChildFate::Gone, Went::Ended);
    assert!(
        records.iter().all(|(level, _)| *level < log::Level::Warn),
        "{records:?}"
    );
}

/// A look that fails leaves the front unaccounted for, with an unknown fate.
///
/// Mutant: the failed look is read as an exit or as running.
#[skuld::test]
fn a_failed_look_at_a_front_is_unknown() {
    let fake = fake().reaps([ReapAnswer::Err(io::ErrorKind::Other)]);
    let reach = FakeReach::answering(Ok(true));
    let torn = look(&fake, Some(&reach));
    assert_outcome(&torn, ChildFate::Unknown, Went::Ended);
    assert_eq!(reach.asked(), []);
}

/// A look sends nothing, whatever it finds.
///
/// Mutant: the front is signalled (the empty `signals` table panics, and the send is recorded).
#[skuld::test]
fn a_look_teardown_sends_nothing() {
    let fake = fake().reaps([ReapAnswer::Running]);
    let _ = look(&fake, None);
    assert_eq!(fake.signal_calls(), []);
}

/// The identity the caller read, or its absence, is the one a running front keeps.
///
/// Mutant: the outcome carries a made-up identity.
#[skuld::test]
fn the_identity_passes_into_a_front_left_running() {
    for given in [Some(id()), None] {
        let fake = fake().reaps([ReapAnswer::Running]);
        let (torn, _) = look_logged(&fake, given, Ok(None), None);
        assert_eq!(torn.fate, ChildFate::Running { id: given });
    }
}

/// A front with no pid is left running like any other.
///
/// Mutant: a pid is made up.
#[skuld::test]
fn a_pidless_front_is_left_running() {
    let fake = FakeProcess::new([]).reaps([ReapAnswer::Running]);
    let torn = look(&fake, None);
    assert_eq!(went(&torn), Went::LeftRunning, "{torn:?}");
}

/// A front waited for past the threshold is warned of once before the wait blocks; one that exits
/// before it is not.
///
/// Mutants: no warn; the warn is not conditional on the bounded wait.
#[skuld::test]
fn a_front_waited_for_past_its_threshold_warns_once() {
    // The look sees it running; then the bounded wait either finds it still running (the warn) or
    // reaps it.
    for (reaps, warned) in [
        (
            vec![ReapAnswer::Running, ReapAnswer::Running, ReapAnswer::Exited(exit())],
            1,
        ),
        (vec![ReapAnswer::Running, ReapAnswer::Exited(exit())], 0),
    ] {
        let fake = fake().reaps(reaps);
        let _fire = fire_on_block(&fake);
        let (torn, records) = look_logged(
            &fake,
            Some(id()),
            Ok(Some(&FakeReach::answering(Ok(true)))),
            Some(due_now()),
        );
        assert_outcome(&torn, ChildFate::Reaped, Went::Ended);
        assert_eq!(slow_warns(&records).len(), warned, "{records:?}");
    }
}

/// A front left running is never waited for, so a threshold never has it look for the exit.
///
/// Mutant: the threshold's watch runs whatever the reach said (the empty `exited` table panics).
#[skuld::test]
fn a_front_left_running_never_looks_for_the_exit() {
    let fake = fake().reaps([ReapAnswer::Running]);
    let (torn, records) = look_logged(&fake, Some(id()), Ok(None), Some(due_now()));
    assert_eq!(went(&torn), Went::LeftRunning, "{torn:?}");
    assert_eq!(fake.looks(), 1);
    assert_eq!(slow_warns(&records).len(), 0);
}

/// A look is not a root teardown; a kill is.
///
/// Mutant: the count is taken at the entry point.
#[skuld::test]
fn a_look_teardown_counts_no_root_teardown() {
    let recorder = crate::child::owned::seams::record_root_teardowns();
    let fake = fake().reaps([ReapAnswer::Exited(exit())]);
    let _ = look(&fake, None);
    assert_eq!(recorder.count(), 0);
}