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
//! Unit tests for the public `Child::wait_tree`/`wait_tree_timeout`. Drained-verdict tests run on
//! `drainable_gives` and assert exactly it; `Unsupported` is checked on a mechanism with no kernel
//! drain edge (see each test).

use std::time::Duration;

use crate::test_child::{drainable_gives, Console};
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, Group};
use crate::Containment;

/// The `TreeDrain` variant a fully-drained tree reports on `containment`'s mechanism:
/// `AllMembersExited` everywhere authoritative (cgroup v2, Windows job object), but
/// `AllMarkersClosed` on macOS's advisory fd marker — see `TreeDrain`'s own doc for why the two
/// are not interchangeable. Centralized here so every test below asserts the SAME real,
/// mechanism-correct verdict rather than assuming the authoritative one everywhere.
fn expected_drained_verdict(containment: crate::containment::Containment) -> crate::containment::TreeDrain {
    match containment {
        crate::containment::Containment::FdMarker => crate::containment::TreeDrain::AllMarkersClosed,
        _ => crate::containment::TreeDrain::AllMembersExited,
    }
}

/// A contained blocker and its stdin writer, which the caller must keep for exactly as long as the
/// child must stay running.
fn long_lived_contained_child() -> (crate::Child, crate::PipeWriter) {
    crate::test_child::held_contained_blocker(crate::Stdio::null())
}

/// Kill, release stdin, reap. Releasing after the kill makes a no-op `kill_tree` fail the status
/// assertion.
fn kill_then_release(child: crate::Child, stdin: crate::PipeWriter) {
    child.kill_tree().expect("kill_tree");
    drop(stdin);
    crate::test_child::assert_killed("the blocker", child.wait().expect("reap the blocker"));
}

/// An unbounded `wait_tree()` against a tree that fully exits on its own reports the
/// mechanism-correct drained verdict (`expected_drained_verdict`) of the `expected` mechanism the
/// caller's `.contain()` must get.
fn wait_tree_drained_verdict(expected: Containment) {
    let child = quick_child(|cmd| _ = cmd.contain());
    assert_eq!(child.containment(), expected);
    let result = child.wait_tree();
    assert_eq!(
        result.expect("a fully-exited tree must report a drained verdict"),
        expected_drained_verdict(expected)
    );
    // wait_tree never reaps — the root's exit still needs collecting.
    _ = child.wait();
}

#[cfg(not(target_os = "linux"))]
#[skuld::test]
fn wait_tree_reports_the_drained_verdict_when_the_tree_drains() {
    wait_tree_drained_verdict(drainable_gives());
}

/// A pump that never broadcasts hangs this test; `a_changed_batch_notifies_a_listener_that_was_there_before_it`
/// fails it by assertion.
#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_tree_reports_the_drained_verdict_when_the_tree_drains(#[fixture(cgroup)] _group: &Group) {
    wait_tree_drained_verdict(drainable_gives());
}

/// `wait_tree_timeout` against a tree that is still alive at expiry reports `MembersRemain` — NOT
/// an error, per its own doc.
fn wait_tree_timeout_members_remain(expected: Containment) {
    let (child, stdin) = long_lived_contained_child();
    assert_eq!(child.containment(), expected);
    let result = child.wait_tree_timeout(Duration::from_millis(200));
    assert_eq!(
        result.expect("an unmet deadline on a live tree must not be an error"),
        crate::containment::TreeDrain::MembersRemain
    );
    kill_then_release(child, stdin);
}

#[cfg(not(target_os = "linux"))]
#[skuld::test]
fn wait_tree_timeout_reports_members_remain_before_the_deadline() {
    wait_tree_timeout_members_remain(drainable_gives());
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_tree_timeout_reports_members_remain_before_the_deadline(#[fixture(cgroup)] _group: &Group) {
    wait_tree_timeout_members_remain(drainable_gives());
}

/// `Duration::ZERO` against a still-alive tree: a one-shot, non-blocking probe (see
/// `crate::wait::deadline_from`/`remaining`'s own docs) — `MembersRemain`, not an error, and
/// returned without ever entering the backend's blocking wait (every `wait_drained`
/// implementation checks `remaining == Duration::ZERO` before its first blocking syscall).
fn wait_tree_timeout_zero_members_remain(expected: Containment) {
    let (child, stdin) = long_lived_contained_child();
    assert_eq!(child.containment(), expected);
    let result = child.wait_tree_timeout(Duration::ZERO);
    assert_eq!(
        result.expect("a ZERO probe against a live tree must not be an error"),
        crate::containment::TreeDrain::MembersRemain
    );
    kill_then_release(child, stdin);
}

#[cfg(not(target_os = "linux"))]
#[skuld::test]
fn wait_tree_timeout_zero_reports_members_remain_on_a_live_tree() {
    wait_tree_timeout_zero_members_remain(drainable_gives());
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_tree_timeout_zero_reports_members_remain_on_a_live_tree(#[fixture(cgroup)] _group: &Group) {
    wait_tree_timeout_zero_members_remain(drainable_gives());
}

/// `Duration::ZERO` against an ALREADY-drained tree: the one-shot probe must still observe and
/// report the real, mechanism-correct drained verdict — not `MembersRemain` by default, and not
/// blocked on by the deadline being in the past (see `marker_eof::block_until_drained`'s own doc
/// on why a past deadline still performs exactly one check). The unbounded `wait_tree()` call
/// first is the genuine happens-before edge that the tree has fully drained before the ZERO
/// probe below ever runs.
fn wait_tree_timeout_zero_drained_verdict(expected: Containment) {
    let child = quick_child(|cmd| _ = cmd.contain());
    assert_eq!(child.containment(), expected);
    child
        .wait_tree()
        .expect("a fully-exited tree must report a drained verdict");
    assert_eq!(
        child
            .wait_tree_timeout(Duration::ZERO)
            .expect("a ZERO probe against an already-drained tree must not be an error"),
        expected_drained_verdict(expected),
        "a ZERO probe must observe the SAME drained state an unbounded wait already found, \
         not report MembersRemain just because the deadline is already past"
    );
    _ = child.wait();
}

#[cfg(not(target_os = "linux"))]
#[skuld::test]
fn wait_tree_timeout_zero_reports_the_drained_verdict_after_the_tree_has_already_drained() {
    wait_tree_timeout_zero_drained_verdict(drainable_gives());
}

/// A pump that never broadcasts hangs this test; `a_changed_batch_notifies_a_listener_that_was_there_before_it`
/// fails it by assertion.
#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_tree_timeout_zero_reports_the_drained_verdict_after_the_tree_has_already_drained(
    #[fixture(cgroup)] _group: &Group,
) {
    wait_tree_timeout_zero_drained_verdict(drainable_gives());
}

/// A quick, self-terminating child under the containment `contain` asks for: the drain edge (when
/// the mechanism has one) fires almost immediately, so an UNBOUNDED `wait_tree()` on it is a real
/// blocking wait on a genuinely-terminating event, not an indefinite one.
fn quick_child(contain: impl FnOnce(&mut crate::Command)) -> crate::Child {
    let mut cmd = crate::test_child::command(Console::Hidden);
    #[cfg(unix)]
    cmd.args(["true"]);
    #[cfg(windows)]
    cmd.args(["cmd", "/C", "exit 0"]);
    contain(&mut cmd);
    cmd.spawn().expect("spawn")
}

/// A quick-exiting child of an explicit `ContainMode::TreeWalk` request.
fn quick_treewalk_child() -> crate::Child {
    quick_child(|cmd| _ = cmd.contain_with(crate::ContainMode::TreeWalk))
}

/// Every wait of `child` is `Unsupported`, and the child is reaped.
fn assert_wait_tree_unsupported(child: &crate::Child) {
    for result in [
        child.wait_tree_timeout(Duration::from_millis(200)),
        child.wait_tree_timeout(Duration::ZERO),
        child.wait_tree(),
    ] {
        let err = result.expect_err("this mechanism has no kernel drain edge");
        assert!(matches!(err, crate::error::Error::Unsupported { .. }), "got {err:?}");
    }
    _ = child.wait();
}

/// `Unsupported` on a non-drainable mechanism: an explicit `ContainMode::TreeWalk` request, which
/// has no kernel drain edge. macOS does not honor the request (see the test below).
#[cfg(not(target_os = "macos"))]
#[skuld::test]
fn wait_tree_is_unsupported_on_a_non_drainable_mechanism() {
    let child = quick_treewalk_child();
    assert_eq!(child.containment(), crate::test_child::tree_walk_gives());
    assert_wait_tree_unsupported(&child);
}

/// `Unsupported` on a session, which an explicit `ContainMode::Session` request gets on Linux.
#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_tree_is_unsupported_on_a_session() {
    let child = quick_child(|cmd| _ = cmd.contain_with(crate::ContainMode::Session));
    assert_eq!(child.containment(), Containment::Session);
    assert_wait_tree_unsupported(&child);
}

/// `Unsupported` on an uncontained child, the one macOS mechanism with no drain edge: every
/// contained request there is promoted to the fd marker.
#[cfg(target_os = "macos")]
#[skuld::test]
fn wait_tree_is_unsupported_on_an_uncontained_child() {
    let child = quick_child(|_| {});
    assert_eq!(child.containment(), Containment::None);
    assert_wait_tree_unsupported(&child);
}

/// On macOS the fd marker is installed for every contained root regardless of the requested mode
/// (it is what survives `setsid`/reparenting/`exec` that a mode-specific mechanism does not), so an explicit `TreeWalk` request comes back
/// `Containment::FdMarker` and drains correctly through it.
#[cfg(target_os = "macos")]
#[skuld::test]
fn a_treewalk_request_is_promoted_to_the_fd_marker_which_drains() {
    let child = quick_treewalk_child();
    assert_eq!(child.containment(), crate::test_child::tree_walk_gives());
    assert_eq!(
        child
            .wait_tree()
            .expect("macOS promotes an explicit TreeWalk request to the drainable fd marker"),
        expected_drained_verdict(Containment::FdMarker),
        "a quick-exiting tree must still be observed as drained through the promoted mechanism"
    );
    _ = child.wait();
}

// `Child::wait_deadline` (portable) =====

use std::time::Instant;

/// A live, uncontained child that blocks on its piped stdin until EOF.
fn spawn_never_exiting() -> (crate::Child, crate::PipeWriter) {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe_in()).expect("configure piped stdin");
    cmd.stdout(crate::Stdio::null()).expect("configure null stdout");
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin was just configured above");
    (child, stdin)
}

/// A deadline in the past against an already-exited child still reports the exit.
///
/// Mutant: return `None` when `remaining` is zero before asking the backend.
#[skuld::test]
fn wait_deadline_in_the_past_reports_an_exited_child() {
    let child = quick_child(|cmd| _ = cmd.contain());
    let waited = child.wait().expect("wait");
    let status = child
        .wait_deadline(Instant::now())
        .expect("an exited child must not fail");
    assert_eq!(status, Some(waited));
}

/// The frozen clock advances by the real elapsed time of each wait exactly once, so a second wait
/// never returns before its own deadline.
fn assert_consecutive_frozen_waits_never_early(child: &crate::Child) {
    let (_clock, at) = crate::wait::test_clock::FrozenClockGuard::install();
    let first = at + Duration::from_millis(50);
    let second = at + Duration::from_millis(100);
    assert!(child.wait_deadline(first).expect("first wait").is_none());
    assert!(child.wait_deadline(second).expect("second wait").is_none());
    assert!(Instant::now() >= second, "the second wait returned before its deadline");
}

/// Mutant (Windows): a second clock advance around `drive::block`'s own `wait_until`.
#[skuld::test]
fn std_child_consecutive_frozen_waits_never_return_early() {
    let (child, _stdin) = spawn_never_exiting();
    assert_consecutive_frozen_waits_never_early(&child);
}

/// Dropping a `Child` kills it and reaps it, by the kill: its stdin is released only once the drop's
/// kill returned.
#[skuld::test]
fn drop_kills_and_reaps_the_child() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    #[cfg(windows)]
    cmd.stdout(crate::Stdio::null()).expect("set stdout null");
    let (stdin, writer) = crate::test_child::held_writer_stdin();
    cmd.stdin(stdin).expect("set stdin");
    let teardown = crate::child::spawn::fault::release_at_drop_kill(writer);
    let child = cmd.spawn().expect("spawn");
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    assert_eq!(
        id.is_alive(),
        crate::identity::Liveness::Alive,
        "child runs while its stdin stays open"
    );

    drop(child); // kill_on_drop default true => SIGKILL/TerminateProcess + reap

    teardown.assert_killed();
    assert_eq!(
        id.is_alive(),
        crate::identity::Liveness::Dead,
        "child must be dead (and reaped) after drop"
    );
}

/// Dropping a `Child` whose tree is contained kills the whole tree, the grandchild too. The tree's
/// stdin is released once the drop's root kill returned, so a drop that sent nothing lets the
/// root exit 0 and the grandchild print `eof`, and fails the assertions instead of hanging in the
/// drop. Both members hold the stdout pipe, so its end is the moment both are gone. `contain` is
/// the mechanism the caller asks for, and `expected` the one it must get.
#[cfg(unix)]
fn drop_kills_a_tree_contained_by(contain: impl FnOnce(&mut crate::Command), expected: crate::Containment) {
    use std::io::Read as _;
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::CAT_TREE_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
    contain(&mut cmd);
    let mut child = cmd.spawn().expect("spawn");
    let stdin = child.stdin().expect("piped stdin");
    let mut stdout = child.stdout().expect("piped stdout");
    let mut ready = [0u8; 2];
    stdout.read_exact(&mut ready).expect("readiness line");
    assert_eq!(&ready, b"r\n");
    // Containment was established, so a tree that survives the drop is a missing kill and not a
    // missing mechanism.
    assert_eq!(child.containment(), expected);
    let teardown = crate::child::spawn::fault::release_at_drop_kill(stdin);

    drop(child);

    teardown.assert_killed();
    let mut rest = Vec::new();
    stdout
        .read_to_end(&mut rest)
        .expect("both members are gone, so the pipe ends");
    assert!(rest.is_empty(), "the drop missed the grandchild: {rest:?}");
}

#[cfg(unix)]
#[skuld::test]
fn drop_kills_a_contained_tree() {
    drop_kills_a_tree_contained_by(
        |cmd| _ = crate::test_child::contain_without_cgroup(cmd),
        crate::test_child::contain_without_cgroup_gives(),
    );
}

/// `BestEffort` with no cgroup leaf made (forced, so whatever the host gives) is a process group,
/// the mechanism `.contain()` gives a Linux host that offers no delegated cgroup.
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_kills_a_process_group_contained_tree() {
    let (mode, _forced) = crate::child::spawn::identity_group_tests::Container::Leafless.arm();
    drop_kills_a_tree_contained_by(|cmd| _ = cmd.contain_with(mode), crate::Containment::ProcessGroup);
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_kills_a_cgroup_contained_tree(#[fixture(cgroup)] _group: &Group) {
    drop_kills_a_tree_contained_by(|cmd| _ = cmd.contain(), crate::Containment::CgroupV2);
}

// A zombie launchd holds =====

/// A child whose every reap answers that launchd holds the zombie (macOS: its tracer died).
fn child_of_an_orphaned_zombie(waits: usize) -> crate::Child {
    use crate::os_process::child::Foreign;
    use crate::os_process::fake::{FakeProcess, ReapAnswer};
    crate::test_child::over_fake::child_over(
        &FakeProcess::new([]).reaps(std::iter::repeat_n(ReapAnswer::Foreign(Foreign::Orphaned), waits)),
    )
}

/// The `warn`s this thread logged since `mark` that say a zombie is not ours to reap.
fn orphan_warns_since(mark: usize) -> usize {
    crate::log_capture::warns_since(mark, "not ours to reap").len()
}

/// The error every wait on a child someone else reaped answers.
fn assert_reaped_elsewhere(result: Result<impl std::fmt::Debug, crate::error::Error>) {
    match result {
        Err(crate::error::Error::Io(e)) => {
            #[cfg(unix)]
            assert_eq!(e.raw_os_error(), Some(libc::ECHILD), "{e}");
            #[cfg(windows)]
            assert!(e.to_string().contains("reaped elsewhere"), "{e}");
        }
        other => panic!("expected the reaped-elsewhere error, got {other:?}"),
    }
}

/// `wait`, `wait_deadline` and `wait_timeout` each warn once of a zombie launchd holds.
///
/// Mutant: `Child` writes the warn for some of them only, or for none.
#[skuld::test]
fn a_loud_wait_warns_of_an_orphaned_zombie() {
    crate::log_capture::install();
    let hour = Duration::from_secs(3600);
    for name in ["wait", "wait_deadline", "wait_timeout"] {
        let child = child_of_an_orphaned_zombie(1);
        let mark = crate::log_capture::mark();
        match name {
            "wait" => assert_reaped_elsewhere(child.wait()),
            "wait_deadline" => assert_reaped_elsewhere(child.wait_deadline(crate::wait::now() + hour)),
            _ => assert_reaped_elsewhere(child.wait_timeout(hour)),
        }
        assert_eq!(orphan_warns_since(mark), 1, "{name}");
    }
}

/// `try_wait` leaves the zombie launchd holds unreported: its callers report it with the refusal
/// they go on to make.
///
/// Mutant: `Child` warns whatever the caller asked.
#[cfg(unix)]
#[skuld::test]
fn try_wait_does_not_warn_of_an_orphaned_zombie() {
    crate::log_capture::install();
    let child = child_of_an_orphaned_zombie(2);
    let mark = crate::log_capture::mark();
    assert_reaped_elsewhere(child.try_wait());
    assert_eq!(orphan_warns_since(mark), 0);
}

// `Settlement`: one row per answer of the table in its doc =====

mod settlement {
    use std::io;
    use std::process::ExitStatus;

    use crate::child::lifecycle::{Settlement, Wording};
    use crate::child::owned::owned_tests::teardown_lines::{HANDED_BACK, LEFT};
    use crate::child::owned::teardown::{Disposition, TeardownOutcome};
    use crate::child::owned::ChildWaitOutcome;
    use crate::child::spawn::FrontFate;
    use crate::error::{ChildFate, Error};
    use crate::identity::ProcessId;
    use crate::os_process::child::{ExitRecord, Foreign};

    const PID: u32 = 4242;
    /// Every disposition a caller words a child under, and none: a caller that says where the child
    /// goes itself.
    const EVERY: [Option<Disposition>; 3] = [None, Some(Disposition::Leave), Some(Disposition::HandBack)];
    const RUNNING: &str = "the caller's running clause";

    fn id() -> ProcessId {
        ProcessId::from_parts_for_test(PID, crate::identity::Key::for_test(1))
    }

    fn failure() -> Error {
        Error::Io(io::Error::other("cosca-wait-e5a1"))
    }

    fn exited() -> Result<ChildWaitOutcome, Error> {
        Ok(ChildWaitOutcome::Exited(ExitRecord::Status(ExitStatus::default())))
    }

    fn foreign(foreign: Foreign) -> Result<ChildWaitOutcome, Error> {
        Ok(ChildWaitOutcome::Foreign(foreign))
    }

    fn failed() -> Result<ChildWaitOutcome, Error> {
        Err(failure())
    }

    fn passed() -> Result<ChildWaitOutcome, Error> {
        Ok(ChildWaitOutcome::DeadlinePassed)
    }

    /// The three facts every row states besides the wording: the fate, whether the wording is the
    /// warn of an uncollected child, and the fate of a front.
    #[track_caller]
    fn assert_row(settlement: &Settlement, fate: ChildFate, uncollected: bool, front: FrontFate) {
        assert_eq!(settlement.fate(Some(id())), fate, "{settlement:?}");
        for disposition in EVERY {
            assert_eq!(
                matches!(worded_as_is(settlement, disposition), Wording::Uncollected(_)),
                uncollected,
                "{settlement:?} {disposition:?}"
            );
        }
        assert_eq!(settlement.front_fate(), front, "{settlement:?}");
    }

    /// What the settlement says of the child "S" under `disposition`, with the running clause
    /// [`RUNNING`].
    fn worded_as_is(settlement: &Settlement, disposition: Option<Disposition>) -> Wording {
        settlement.wording("S", Some(RUNNING), disposition)
    }

    /// [`worded_as_is`], as its level and text.
    fn worded(settlement: &Settlement, disposition: Option<Disposition>) -> (log::Level, String) {
        let said = worded_as_is(settlement, disposition);
        (said.level(), said.text().to_owned())
    }

    /// A child that exited with a status is reaped, said at `debug` as "reaped it", "after the kill"
    /// only if a kill reached it.
    ///
    /// Mutants: it is uncollected; it has no clause, or a warn; "after the kill" ignores the kill.
    #[skuld::test]
    fn an_exit_with_a_status_is_reaped_and_said_at_debug() {
        for (killed, said) in [(false, "S: reaped it"), (true, "S: reaped it after the kill")] {
            let settlement = Settlement::new(exited(), killed);
            assert_row(&settlement, ChildFate::Reaped, false, FrontFate::Reaped);
            for disposition in EVERY {
                assert_eq!(
                    worded(&settlement, disposition),
                    (log::Level::Debug, said.to_owned()),
                    "{killed}"
                );
            }
        }
    }

    /// Someone else reaped it: not collected by this handle, so nothing to hand back. The fate says
    /// whether a kill reached it, and the line is `debug`.
    ///
    /// Mutants: the line is a warn; the fate ignores the kill; it is uncollected.
    #[skuld::test]
    fn a_foreign_reap_is_gone_or_killed_and_said_at_debug() {
        for foreign_reap in [Foreign::Gone, Foreign::Other] {
            for (killed, fate) in [(false, ChildFate::Gone), (true, ChildFate::Killed)] {
                let settlement = Settlement::new(foreign(foreign_reap), killed);
                assert_row(&settlement, fate, false, FrontFate::Unaccounted);
                for disposition in EVERY {
                    assert_eq!(
                        worded(&settlement, disposition),
                        (log::Level::Debug, "S: reaped by someone else".to_owned())
                    );
                }
            }
        }
    }

    /// A zombie launchd holds is the same, but warned of, as a clause after the caller's subject.
    ///
    /// Mutants: the line is `debug`; it is not led by the caller's subject, so a subject that names
    /// a refusal loses it.
    #[skuld::test]
    fn a_zombie_launchd_holds_is_gone_or_killed_and_warned_of() {
        for (killed, fate) in [(false, ChildFate::Gone), (true, ChildFate::Killed)] {
            let settlement = Settlement::new(foreign(Foreign::Orphaned), killed);
            assert_row(&settlement, fate, false, FrontFate::Unaccounted);
            for disposition in EVERY {
                assert_eq!(
                    worded(&settlement, disposition),
                    (
                        log::Level::Warn,
                        "S: not ours to reap (launchd holds its zombie, because its tracer died)".to_owned()
                    )
                );
            }
        }
    }

    /// A wait that failed after a kill reached the child: `Killed`, uncollected, and the warn says
    /// where the child goes under the disposition.
    ///
    /// Mutants: the fate is `Unknown`; it is collected; the suffix ignores the disposition.
    #[skuld::test]
    fn a_failed_wait_after_a_kill_is_killed_uncollected_and_warned_of() {
        let settlement = Settlement::new(failed(), true);
        assert_row(&settlement, ChildFate::Killed, true, FrontFate::Unaccounted);
        assert_failed_wait_worded(&settlement);
    }

    /// A failed wait is a warn that says where the uncollected child goes: nothing for a caller that
    /// says so itself, "left unreaped" for one that leaves it, handed back for one that hands it back.
    /// The no-disposition caller returns the text, with the failure in its error (`failure`), so it
    /// does not repeat it; the others log it (chain).
    #[track_caller]
    fn assert_failed_wait_worded(settlement: &Settlement) {
        let returned = "S: the wait failed";
        let logged = format!("S: the wait failed: {}", crate::error::io_said("cosca-wait-e5a1"));
        for (disposition, said, goes) in [
            (None, returned, ""),
            (Some(Disposition::Leave), logged.as_str(), LEFT),
            (Some(Disposition::HandBack), logged.as_str(), HANDED_BACK),
        ] {
            assert_eq!(
                worded(settlement, disposition),
                (log::Level::Warn, format!("{said}{goes}")),
                "{disposition:?}"
            );
        }
    }

    /// A wait that failed with no kill having reached the child shows nothing of what became of it:
    /// `Unknown`, otherwise the row above.
    ///
    /// Mutant: the fate ignores whether a kill reached the child.
    #[skuld::test]
    fn a_failed_wait_without_a_kill_is_unknown_uncollected_and_warned_of() {
        let settlement = Settlement::new(failed(), false);
        assert_row(&settlement, ChildFate::Unknown, true, FrontFate::Unaccounted);
        assert_failed_wait_worded(&settlement);
    }

    /// A deadline that passed, with no kill having reached the child: it is running, uncollected, a
    /// front left unreaped, and the caller's running clause is the warn, as it is.
    ///
    /// Mutants: the fate keeps no identity; it is collected; the clause is prefixed.
    #[skuld::test]
    fn a_deadline_that_passed_is_running_uncollected_and_the_callers_clause() {
        let settlement = Settlement::new(passed(), false);
        assert_row(
            &settlement,
            ChildFate::Running { id: Some(id()) },
            true,
            FrontFate::LeftUnreaped,
        );
        assert_eq!(settlement.fate(None), ChildFate::Running { id: None });
        for disposition in EVERY {
            assert_eq!(worded(&settlement, disposition), (log::Level::Warn, RUNNING.to_owned()));
        }
    }

    /// A wait with no deadline that still answers a deadline passed (a contract breach that a debug
    /// build asserts on elsewhere) is not worded as an empty line in a release build: the caller has
    /// no running clause, so the line names the subject.
    ///
    /// Mutant: the wording returns the caller's clause whether or not there is one, so it is empty.
    #[skuld::test]
    fn a_deadline_that_passed_in_a_wait_with_no_deadline_says_the_wait_ended_with_no_exit() {
        let settlement = Settlement::new(passed(), false);
        for disposition in EVERY {
            assert_eq!(
                settlement.wording("S", None, disposition),
                Wording::Uncollected("S: its wait ended with no exit".to_owned())
            );
        }
    }

    /// `ended` is every answer but a deadline that passed, and `status` the status of an exit.
    ///
    /// Mutant: `ended` reads the fate.
    #[skuld::test]
    fn ended_and_status_state_the_answer() {
        for (settlement, ended, status) in [
            (Settlement::new(exited(), false), true, Some(ExitStatus::default())),
            (Settlement::new(foreign(Foreign::Gone), true), true, None),
            (Settlement::new(failed(), false), true, None),
            (Settlement::new(passed(), false), false, None),
        ] {
            assert_eq!(settlement.ended(), ended, "{settlement:?}");
            assert_eq!(settlement.status(), status, "{settlement:?}");
        }
    }

    /// The failure of a wait is the settlement's failure, shared with the outcome built from it, whose
    /// remains carry it as the teardown's failure; every other answer has none.
    ///
    /// Mutants: the failure is only in the clause; the outcome drops it; an answer with no failure
    /// has one.
    #[skuld::test]
    fn a_failed_wait_is_the_failure_of_its_settlement_and_of_the_teardown_built_from_it() {
        let outcome = |answer| {
            TeardownOutcome::of_settlement(&Settlement::new(answer, false), None, "S", None, Disposition::Leave)
        };
        let failure = Settlement::new(failed(), false).failure().expect("the failed wait");
        let step = crate::error::io_said("waiting for the child: cosca-wait-e5a1");
        assert_eq!(crate::error::said(&*failure), step);

        let remains = outcome(failed()).remains();
        let failures = remains.failures.expect("the teardown's failure");
        assert_eq!(failures.iter().len(), 1, "{failures:?}");
        assert_eq!(crate::error::said(&**failures.first()), step);

        for answer in [passed(), foreign(Foreign::Gone)] {
            assert!(Settlement::new(answer, false).failure().is_none());
        }
        assert!(outcome(passed()).remains().failures.is_none());
    }

    /// A clause at warn is the outcome's warn text for the caller's one warn, and is logged by
    /// nobody; one below it is logged at its level, led by the caller's label and a colon, and
    /// returns nothing. Either way the clause is taken, and what is left is the fate and whether the
    /// child is uncollected.
    ///
    /// Mutants: a debug clause is returned; a warn is logged; the label is dropped; the remains
    /// lose the uncollected child.
    #[skuld::test]
    fn a_clause_at_warn_is_the_warn_and_anything_below_is_logged() {
        crate::log_capture::install();
        let outcome = |answer| {
            TeardownOutcome::of_settlement(&Settlement::new(answer, false), None, "S", None, Disposition::Leave)
        };

        let mark = crate::log_capture::mark();
        let (warn, remains) = outcome(foreign(Foreign::Gone)).take_warn("lead");
        assert_eq!(warn, None);
        assert!(!remains.uncollected);
        let (warn, remains) = outcome(exited()).take_warn("lead");
        assert_eq!(warn, None);
        assert!(!remains.uncollected);
        assert_eq!(
            crate::log_capture::records_since_on_current_thread(mark, "S:"),
            vec![
                (log::Level::Debug, "lead: S: reaped by someone else".to_owned()),
                (log::Level::Debug, "lead: S: reaped it".to_owned()),
            ]
        );

        let mark = crate::log_capture::mark();
        let (warn, remains) = outcome(failed()).take_warn("lead");
        assert_eq!(
            warn.as_deref(),
            Some(format!("S: the wait failed: {}{LEFT}", crate::error::io_said("cosca-wait-e5a1")).as_str())
        );
        assert!(remains.uncollected);
        assert_eq!(
            crate::log_capture::records_since_on_current_thread(mark, "S:"),
            Vec::<(log::Level, String)>::new()
        );
    }

    /// A kill reached the child, and the wait that follows has no deadline: an answer that the
    /// deadline passed breaks that contract.
    ///
    /// Mutant: the contract is not asserted.
    #[cfg(debug_assertions)]
    #[skuld::test]
    fn a_deadline_that_passed_after_a_kill_breaks_the_contract() {
        let built = std::panic::catch_unwind(|| Settlement::new(passed(), true));
        assert!(built.is_err(), "a deadline cannot pass in an unbounded wait");
    }
}

/// A wait never hands back an unreadable exit record (only the consuming reap at the end of a
/// handle can meet one), so a debug build asserts it.
///
/// Mutant: the arm answers an error in a debug build too.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "which is no exit record")]
fn an_unreadable_record_from_a_wait_asserts_in_debug() {
    use super::{status_of_outcome, Orphaned};
    use crate::child::owned::ChildWaitOutcome;
    use crate::os_process::child::ExitRecord;

    let outcome = ChildWaitOutcome::Exited(ExitRecord::Unreadable { si_code: 7 });
    drop(status_of_outcome(Some(1), outcome, Orphaned::Quiet));
}

/// The same record in a release build is an `InvalidData` error that names the code, not a panic
/// in a public call.
///
/// Mutant: the arm panics, or answers a status or a different kind.
#[cfg(not(debug_assertions))]
#[skuld::test]
fn an_unreadable_record_from_a_wait_is_invalid_data_in_release() {
    use super::{status_of_outcome, Orphaned};
    use crate::child::owned::ChildWaitOutcome;
    use crate::error::Error;
    use crate::os_process::child::ExitRecord;

    let outcome = ChildWaitOutcome::Exited(ExitRecord::Unreadable { si_code: 7 });
    let Err(Error::Io(e)) = status_of_outcome(Some(1), outcome, Orphaned::Quiet) else {
        panic!("an unreadable record is an I/O error");
    };
    assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
    assert!(e.to_string().contains("si_code 7"), "{e}");
}