cosca 0.10.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
//! The sync spawn's teardown of the child it holds after the clone (`tear_down_held`), over a
//! real child with scripted answers (`script_over`). Unprivileged: the leaf's subtree is stated, not
//! read from a cgroup.

use std::io;

use super::held_teardown::{tear_down_held, warn_of_teardown_failures, HeldTeardown};
use super::policy::SpawnPolicy;
use super::Diagnosis;
use crate::child::owned::owned_tests::teardown::{
    fire_on_block, held_owned_blocker as held_blocker, held_owned_blocker_reporting, slow_warns_during,
};
use crate::child::owned::owned_tests::teardown_lines::{self, Found, Kill};
use crate::child::owned::teardown::{Disposition, Expect, HandleTeardown, Past};
use crate::child::owned::OwnedChild;
use crate::containment::cgroup::{fault, PlacedAtRemoval, Subtree, Swept};
use crate::elevation::front::Front;
use crate::error::{ChildFate, Error};
use crate::log_capture::warns_since;
use crate::os_process::child::{ExitRecord, Foreign, KillRefusal};
use crate::os_process::fake::{failed_signal, FakeProcess, ReapAnswer};
use crate::test_child::tear_down_held_holding;

/// [`held_blocker`] whose box tracks a `sudo` front.
fn held_front(script: impl FnOnce(FakeProcess) -> FakeProcess) -> (OwnedChild, crate::PipeWriter) {
    held_owned_blocker_reporting(crate::child::front_kill_tests::sudo_report(), script)
}

/// A subtree of a leaf with id 7, killed through, which places a task by its pidfd's cgroup id.
fn killed_subtree() -> Subtree {
    Subtree::new(
        Some(7),
        None,
        None,
        Swept::default(),
        PlacedAtRemoval::default(),
        crate::containment::cgroup::test_support::kill_record(true),
    )
}

/// A child whose kill is refused and whose look then fails is uncollected and still ours: the arm
/// hands it back though its fate is `Unknown`.
///
/// Mutant: only a `Running` fate hands back.
#[skuld::test]
fn a_refused_kill_whose_look_failed_is_handed_back() {
    let (owned, stdin) = held_blocker(|f| {
        f.signals([Err(io::Error::from(io::ErrorKind::PermissionDenied))])
            .reaps([ReapAnswer::Err(io::ErrorKind::Other)])
    });

    let (_, fate, handed_back) = tear_down_held_holding(owned, None, None, &mut Diagnosis::default(), stdin);

    assert_eq!(fate, ChildFate::Unknown);
    handed_back.unreaped();
    handed_back.wait();
}

/// A front whose look fails is uncollected and still ours: handed back, and the error says so.
///
/// Mutants: only a `Running` fate hands back; the note does not say it is handed back.
#[skuld::test]
fn a_front_whose_look_failed_is_handed_back_and_the_error_says_so() {
    let (owned, stdin) = held_front(|f| f.reaps([ReapAnswer::Err(io::ErrorKind::Other)]));

    let (detail, fate, handed_back) = tear_down_held_holding(owned, None, None, &mut Diagnosis::default(), stdin);

    assert_eq!(fate, ChildFate::Unknown);
    handed_back.unreaped();
    let detail = detail.expect("the teardown says what it did with the front");
    assert!(
        detail.contains("could not be waited on") && detail.contains("handed back to the caller"),
        "{detail}"
    );
    handed_back.wait();
}

/// A front whose place cannot be read is handed back, and the error says where it is cannot be read.
///
/// Mutants: `PlaceUnreadable` maps to `LeftUnreaped`, which words a front that is not placed;
/// the front reads as not a front, so the teardown kills and waits for it.
#[skuld::test]
fn a_front_whose_place_cannot_be_read_is_handed_back_and_the_error_says_so() {
    let record = ExitRecord::Status(std::process::ExitStatus::default());
    let mut fake = None;
    let (owned, stdin) = held_front(|f| {
        fake = Some(f.clone());
        f.reaps([ReapAnswer::Running, ReapAnswer::Exited(record)])
    });
    let pid = owned.pid().expect("the held child has a pid");
    let _fire = fire_on_block(&fake.expect("the script ran"));
    let subtree = killed_subtree();

    let (detail, fate, handed_back) = {
        let _unreadable = fault::fail_pidfd_info();
        tear_down_held_holding(owned, None, Some(&subtree), &mut Diagnosis::default(), stdin)
    };

    assert_eq!(
        crate::wait::block_probe::take(),
        [],
        "a front whose place cannot be read is looked at, never waited for"
    );
    assert!(matches!(fate, ChildFate::Running { .. }), "{fate:?}");
    handed_back.unreaped();
    let detail = detail.expect("the teardown says what it did with the front");
    assert!(
        detail.contains("where it is cannot be read") && detail.contains("handed back to the caller"),
        "{detail}"
    );
    // The scripted `Exited` ends the wait; the real blocker, released by it, is reaped here.
    handed_back.wait();
    crate::child::front_kill_tests::reap(pid);
}

/// A front its leaf's kill reached, whose reap then fails, is `Killed`, uncollected and still ours:
/// handed back, and the error says it could not be waited on, not that it was reaped.
///
/// Mutants: a wait that failed after the kill reads as `Reaped`, or is not handed back;
/// the front reads as not a front, so the teardown kills and waits for it.
#[skuld::test]
fn a_front_whose_reap_failed_after_the_leaf_kill_is_handed_back_and_the_error_says_so() {
    let mut fake = None;
    let (owned, stdin) = held_front(|f| {
        fake = Some(f.clone());
        f.reaps([ReapAnswer::Running, ReapAnswer::Err(io::ErrorKind::Other)])
    });
    let _fire = fire_on_block(&fake.expect("the script ran"));
    let subtree = killed_subtree();

    let (detail, fate, handed_back) = {
        let _placed = fault::force_pidfd_cgroup_id(7);
        tear_down_held_holding(owned, None, Some(&subtree), &mut Diagnosis::default(), stdin)
    };

    assert_eq!(
        crate::wait::block_probe::take(),
        [],
        "the failed reap ends the wait at its first look, with no block"
    );
    assert_eq!(fate, ChildFate::Killed);
    handed_back.unreaped();
    let detail = detail.expect("the teardown says what it did with the front");
    assert!(
        detail.contains("could not be waited on") && detail.contains("handed back to the caller"),
        "{detail}"
    );
    handed_back.wait();
}

/// A child that is not a front is killed and reaped: nothing is handed back, the error is the
/// spawn's own, and nothing warns.
///
/// Mutant: the arm hands back whatever the teardown left.
#[skuld::test]
fn a_child_that_is_not_a_front_is_killed_and_reaped_and_nothing_is_handed_back() {
    crate::log_capture::install();
    let (owned, stdin) = held_blocker(|f| f);
    let pid = owned.pid().expect("the held child has a pid");
    let mark = crate::log_capture::mark();

    let (detail, fate, handed_back) = tear_down_held_holding(owned, None, None, &mut Diagnosis::default(), stdin);

    assert_eq!(fate, ChildFate::Reaped);
    assert!(handed_back.is_none(), "a reaped child is not handed back");
    assert_eq!(detail, None, "a child that is not a front has nothing to say of it");
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
    assert_eq!(
        crate::child::front_kill_tests::reap(pid),
        None,
        "the teardown reaped it"
    );
}

/// A front someone else reaped is noted as it is for a caller that leaves it, not as handed back, and
/// nothing is handed back.
///
/// Mutant: the note is always the hand-back's.
#[skuld::test]
fn a_front_reaped_elsewhere_is_noted_without_a_hand_back() {
    let (owned, stdin) = held_front(|f| f.reaps([ReapAnswer::Foreign(Foreign::Gone)]));

    let (detail, fate, handed_back) = tear_down_held_holding(owned, None, None, &mut Diagnosis::default(), stdin);

    assert_eq!(fate, ChildFate::Gone);
    assert!(handed_back.is_none());
    let detail = detail.expect("the teardown says what it did with the front");
    assert!(
        detail.contains("could not be waited on") && !detail.contains("handed back"),
        "{detail}"
    );
}

/// A front with no leaf subtree to say its kill reached it is left running, so it is handed back, and
/// the error says so in the words of a front handed back.
///
/// Mutants: the note says the front is left unreaped;
/// the front reads as not a front, so the teardown kills and waits for it.
#[skuld::test]
fn a_running_front_with_no_subtree_is_handed_back_and_the_error_says_so() {
    let record = ExitRecord::Status(std::process::ExitStatus::default());
    let mut fake = None;
    let (owned, stdin) = held_front(|f| {
        fake = Some(f.clone());
        f.reaps([ReapAnswer::Running, ReapAnswer::Exited(record)])
    });
    let pid = owned.pid().expect("the held child has a pid");
    let _fire = fire_on_block(&fake.expect("the script ran"));

    let (detail, fate, handed_back) = tear_down_held_holding(owned, None, None, &mut Diagnosis::default(), stdin);

    assert_eq!(
        crate::wait::block_probe::take(),
        [],
        "a front with no subtree is looked at, never waited for"
    );
    assert!(matches!(fate, ChildFate::Running { .. }), "{fate:?}");
    handed_back.unreaped();
    let detail = detail.expect("the teardown says what it did with the front");
    assert!(
        detail.contains("the elevated program may be running; handed back to the caller in the error"),
        "{detail}"
    );
    // The scripted `Exited` ends the wait; the real blocker, released by it, is reaped here.
    handed_back.wait();
    crate::child::front_kill_tests::reap(pid);
}

/// The check that failed the spawn leads the teardown's one warn, for a child killed and for a front
/// looked at.
///
/// Mutant: the arm warns the teardown's text alone, and the diagnosis is logged apart.
#[skuld::test]
fn the_diagnosis_leads_the_one_warn_of_the_teardown() {
    crate::log_capture::install();
    for front in [None, Some(Front::Sudo)] {
        let script = |f: FakeProcess| {
            f.signals([failed_signal(libc::EPERM)])
                .reaps([ReapAnswer::Err(io::ErrorKind::Other)])
        };
        let (owned, stdin) = if front.is_some() {
            held_front(script)
        } else {
            held_blocker(script)
        };
        let mut why = Diagnosis::default();
        why.add("diagnosis 7c2e");
        let mark = crate::log_capture::mark();

        let (_, _, handed_back) = tear_down_held_holding(owned, None, None, &mut why, stdin);
        drop(why);

        let warns = warns_since(mark, "");
        assert_eq!(warns.len(), 1, "{front:?}: {warns:?}");
        assert!(
            warns[0].starts_with("teardown after a failed spawn: diagnosis 7c2e; "),
            "{front:?}: {warns:?}"
        );
        handed_back.wait();
    }
}

/// A front that is already a zombie when the teardown looks, because it exited on its own, is reaped
/// by the look: the error says it was reaped and nothing is handed back. The test waits for the
/// front's exit through its handle, so the zombie is there before the look.
///
/// Mutant: a zombie front is left unreaped.
#[skuld::test]
fn a_front_that_has_exited_is_reaped_without_waiting() {
    let (owned, stdin) = held_front(|f| f);
    let mut blocker = ReapsBlocker::new(&owned, stdin);
    blocker.close_stdin();
    assert!(owned.exited_by(None).expect("watch the front"), "the front exited");

    let (detail, fate, handed_back) = tear_down_held_holding(owned, None, None, &mut Diagnosis::default(), ());

    assert_eq!(fate, ChildFate::Reaped);
    assert!(handed_back.is_none());
    let detail = detail.expect("the teardown says what it did with the front");
    assert!(detail.contains("and it was reaped"), "{detail}");
    assert_eq!(blocker.finish(), None, "the teardown reaped the front");
}

/// `tear_down_held` for a caller that leaves what it could not end, with what the teardown is told
/// of the rest as `HeldTeardown` says, over `owned`.
fn tear_down_leaving(owned: OwnedChild, why: &mut Diagnosis) -> (Option<String>, ChildFate, Option<crate::Unreaped>) {
    let how = HeldTeardown {
        id: None,
        reach: None,
        disposition: Disposition::Leave,
        policy: SpawnPolicy::SYNC,
    };
    let (detail, torn) = tear_down_held(owned, how, why);
    (detail, torn.fate, torn.unreaped)
}

/// A child whose kill is refused, under a caller that leaves it, is left running and warned of, and
/// nothing is handed back. The child is the caller's to reap, and the test does.
///
/// Mutants: the arm hands back what a `Leave` caller leaves; the warn says it is handed back; the child
/// is reported reaped.
#[skuld::test]
fn a_refused_kill_under_leave_is_left_running_and_warned_and_nothing_is_handed_back() {
    crate::log_capture::install();
    let (owned, stdin) = held_blocker(|f| {
        f.signals([Err(io::Error::from(io::ErrorKind::PermissionDenied))])
            .reaps([ReapAnswer::Running])
    });
    let blocker = ReapsBlocker::new(&owned, stdin);
    let mark = crate::log_capture::mark();

    let (_, fate, unreaped) = tear_down_leaving(owned, &mut Diagnosis::default());

    assert_eq!(fate, ChildFate::Running { id: None });
    assert!(unreaped.is_none(), "a caller that leaves it is handed nothing back");
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(
        warns[0].contains("leaving it running") && !warns[0].contains("handed back"),
        "{warns:?}"
    );
    blocker.finish().expect("the left child is still unreaped");
}

/// A front still running, under a caller that leaves it, is noted as left unreaped, and nothing is
/// handed back.
///
/// Mutants: the note says it is handed back; the front is handed back;
/// the front reads as not a front, so the teardown kills and waits for it.
#[skuld::test]
fn a_running_front_under_leave_is_noted_as_left_unreaped_and_nothing_is_handed_back() {
    crate::log_capture::install();
    let record = ExitRecord::Status(std::process::ExitStatus::default());
    let mut fake = None;
    let (owned, stdin) = held_front(|f| {
        fake = Some(f.clone());
        f.reaps([ReapAnswer::Running, ReapAnswer::Exited(record)])
    });
    let blocker = ReapsBlocker::new(&owned, stdin);
    let _fire = fire_on_block(&fake.expect("the script ran"));
    let mark = crate::log_capture::mark();

    let (detail, fate, unreaped) = tear_down_leaving(owned, &mut Diagnosis::default());

    assert_eq!(
        crate::wait::block_probe::take(),
        [],
        "a front under a caller that leaves it is looked at, never waited for"
    );
    assert_eq!(fate, ChildFate::Running { id: None });
    assert!(unreaped.is_none());
    let detail = detail.expect("the teardown says what it did with the front");
    assert!(
        detail.contains("the elevated program may be running; left unreaped") && !detail.contains("handed back"),
        "{detail}"
    );
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(
        warns[0].contains("is left running and unreaped") && !warns[0].contains("handed back"),
        "{warns:?}"
    );
    blocker.finish().expect("the left front is still unreaped");
}

/// A front whose pid is not known (tokio's spawn failed before it returned one) is named so, in the
/// error and in the warn.
///
/// Mutant: the front is named `pid 0`.
#[skuld::test]
fn a_front_with_no_pid_is_named_as_such() {
    crate::log_capture::install();
    let (owned, stdin) = held_blocker(|f| f);
    let blocker = ReapsBlocker::new(&owned, stdin);
    // The same child, named by its pidfd alone: the copy is the pid-less handle's own.
    let pidfd = owned.pidfd().expect("a Linux child has its pidfd");
    let pidless = OwnedChild::over_pidfd(
        crate::identity::HostKernel,
        None,
        pidfd.try_clone_to_owned().expect("dup the pidfd"),
        crate::elevation::front::TrackedKind::Front(Front::Sudo),
    );
    let mark = crate::log_capture::mark();

    let (detail, _, unreaped) = tear_down_leaving(pidless, &mut Diagnosis::default());

    assert!(unreaped.is_none());
    let detail = detail.expect("the teardown says what it did with the front");
    assert!(detail.contains("the spawned child is what sudo left"), "{detail}");
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(
        warns[0].starts_with("teardown after a failed spawn: the elevation front (pid unknown)"),
        "{warns:?}"
    );
    drop(owned);
    blocker.finish().expect("the left front is still unreaped");
}

/// The teardown of the table's row `kill` and `found` over a pidfd, as a caller that leaves the child
/// and knows `past` of the pidfd, and the clause its row says.
fn teardown_of(kill: teardown_lines::Kill, found: teardown_lines::Found, past: Past) -> (HandleTeardown, String) {
    let row = teardown_lines::rows()
        .into_iter()
        .find(|row| row.kill == kill && row.found == found)
        .expect("the table has the row");
    let expect = Expect {
        refusal: KillRefusal::Permission,
        past,
    };
    let torn = HandleTeardown::new(teardown_lines::outcome(&row, Disposition::Leave), expect);
    (torn, row.leave)
}

/// The teardown whose kill was delivered and whose wait then failed: uncollected, and `Killed`, as a
/// failed wait on a pidfd leaves it.
fn after_a_failed_wait(past: Past) -> HandleTeardown {
    teardown_of(Kill::Delivered, Found::WaitFailed, past).0
}

/// A failed wait on a pidfd no look failed on is a breach of the contract, asserted where the warn is
/// logged, whoever the caller is.
///
/// Mutant: `warn_teardown` asserts nothing.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "a wait on a child's own handle failed")]
fn a_failed_wait_on_a_pidfd_nothing_looked_at_breaks_the_contract() {
    crate::log_capture::install();
    after_a_failed_wait(Past::Clean).say_as_failed_spawn(&mut Diagnosis::default());
}

/// A kill of a child that never ran the program is not refused: a child left running breaks the
/// contract.
///
/// Mutant: `Past::Unexecuted` asserts no more than `Past::Clean`.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "never ran the program was refused")]
fn a_refused_kill_of_a_child_that_never_ran_breaks_the_contract() {
    crate::log_capture::install();
    let (torn, _) = teardown_of(Kill::Refused, Found::Running, Past::Unexecuted);
    torn.say_as_failed_spawn(&mut Diagnosis::default());
}

/// A caller that knows a look on the pidfd failed expects nothing of a wait on it: the same
/// teardown is no breach.
///
/// Mutant: `Past::WaitMayFail` asserts like `Past::Clean`.
#[skuld::test]
fn a_failed_wait_on_a_pidfd_a_look_failed_on_is_not_a_breach() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    after_a_failed_wait(Past::WaitMayFail).say_as_failed_spawn(&mut Diagnosis::default());
    assert_eq!(warns_since(mark, "").len(), 1);
}

/// The test's cleanup of a blocker that a teardown may leave running: it exits on its stdin's
/// close, and is the test's to reap. A test that asserts the reap calls [`ReapsBlocker::finish`];
/// otherwise the drop reaps. On unwind the drop closes stdin and neither blocks nor asserts.
struct ReapsBlocker {
    stdin: Option<crate::PipeWriter>,
    pid: Option<u32>,
}

impl ReapsBlocker {
    fn new(owned: &OwnedChild, stdin: crate::PipeWriter) -> ReapsBlocker {
        ReapsBlocker {
            stdin: Some(stdin),
            pid: Some(owned.pid().expect("the held child has a pid")),
        }
    }

    /// Lets the blocker exit, before the test is done with it.
    fn close_stdin(&mut self) {
        drop(self.stdin.take());
    }

    /// Closes stdin and reaps: how the blocker ended, or `None` if something reaped it already.
    fn finish(mut self) -> Option<std::process::ExitStatus> {
        self.close_stdin();
        crate::child::front_kill_tests::reap(self.pid.take().expect("the blocker is not yet reaped"))
    }
}

impl Drop for ReapsBlocker {
    fn drop(&mut self) {
        self.close_stdin();
        if let Some(pid) = self.pid.take() {
            if !std::thread::panicking() {
                crate::child::front_kill_tests::reap(pid);
            }
        }
    }
}

/// The pidfd states what its kill may be refused for: permission alone (`EPERM`).
///
/// Mutant: `LinuxProcess` allows no refusal, or any.
#[skuld::test]
fn a_pidfd_allows_a_refusal_of_permission_alone() {
    let (owned, stdin) = held_blocker(|f| f);
    let _reaped = ReapsBlocker::new(&owned, stdin);
    assert_eq!(owned.kill_refusal(), KillRefusal::Permission);
}

/// A failed spawn's teardown of a pidfd whose kill is refused with `errno`: the fate, which the
/// refusal leaves `Running`.
fn after_a_pidfd_kill_refused_with(errno: i32, past: Past) -> ChildFate {
    crate::log_capture::install();
    let (owned, stdin) = held_blocker(|f| f.signals([failed_signal(errno)]));
    let _reaped = ReapsBlocker::new(&owned, stdin);
    super::held_teardown::tear_down_failed_spawn(
        owned,
        None,
        past,
        Disposition::Leave,
        SpawnPolicy::SYNC,
        &mut Diagnosis::default(),
    )
    .fate
}

/// A kill of a pidfd refused with `EPERM` is within the contract, a setuid child's.
///
/// Mutant: the contract refuses every refusal of a pidfd.
#[skuld::test]
fn a_pidfd_kill_refused_with_eperm_is_no_breach() {
    let fate = after_a_pidfd_kill_refused_with(libc::EPERM, Past::Clean);
    assert!(matches!(fate, ChildFate::Running { .. }), "{fate:?}");
}

/// A kill of a pidfd refused with anything else breaks the contract.
///
/// Mutant: the contract allows any refusal of a pidfd.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "for a reason other than permission")]
fn a_pidfd_kill_refused_with_another_errno_breaks_the_contract() {
    after_a_pidfd_kill_refused_with(libc::EIO, Past::Clean);
}

/// A teardown that collected the child, said with a diagnosis still owed, is the event's one warn:
/// the diagnosis leads it, and the clause that stands alone at `debug` says what became of the child
/// in it, under the failed spawn's name.
///
/// Mutant: the clause is logged apart at `debug` and the diagnosis warns unlabelled when dropped.
#[skuld::test]
fn a_clean_teardown_with_a_diagnosis_owed_is_one_labelled_warn() {
    crate::log_capture::install();
    let (torn, clause) = teardown_of(Kill::Delivered, Found::Exited, Past::Clean);
    let mut why = Diagnosis::default();
    why.add("the identity check failed");
    let mark = crate::log_capture::mark();

    torn.say_as_failed_spawn(&mut why);
    drop(why);

    assert_eq!(
        warns_since(mark, ""),
        [format!(
            "teardown after a failed spawn: the identity check failed; {clause}"
        )]
    );
}

// The spawn's policy -----

/// `tear_down_held` over a front, handing back one it cannot end, under `policy`.
fn tear_down_front_under(
    owned: OwnedChild,
    subtree: Option<&Subtree>,
    policy: SpawnPolicy,
) -> (Option<String>, ChildFate, Option<crate::Unreaped>) {
    let how = HeldTeardown {
        id: None,
        reach: subtree.map(|subtree| subtree as &dyn crate::child::owned::teardown::Reach),
        disposition: Disposition::HandBack,
        policy,
    };
    let (detail, torn) = tear_down_held(owned, how, &mut Diagnosis::default());
    (detail, torn.fate, torn.unreaped)
}

/// The wait for a front its leaf's kill reached warns past the threshold the spawn's policy gave
/// the teardown, once. The look, the wait's first bounded try, its second, and the block it ends
/// in, are the four answers; the last is scripted, and the real blocker is reaped by the test.
///
/// Mutant: `tear_down_held` hands the front's look no threshold.
#[skuld::test]
fn the_wait_for_a_front_its_leafs_kill_reached_warns_past_its_policys_threshold() {
    let record = ExitRecord::Status(std::process::ExitStatus::default());
    let mut fake = None;
    let (owned, stdin) = held_front(|f| {
        fake = Some(f.clone());
        f.reaps([
            ReapAnswer::Running,
            ReapAnswer::Running,
            ReapAnswer::Running,
            ReapAnswer::Exited(record),
        ])
    });
    let _blocker = ReapsBlocker::new(&owned, stdin);
    let _fire = fire_on_block(&fake.expect("the script ran"));
    let subtree = killed_subtree();
    let mut handed_back = None;

    let warns = slow_warns_during(|| {
        let _placed = fault::force_pidfd_cgroup_id(7);
        handed_back = Some(tear_down_front_under(owned, Some(&subtree), SpawnPolicy::WARNS_AT_ONCE).2);
    });

    assert!(
        handed_back.expect("the teardown ran").is_none(),
        "a reaped front is not handed back"
    );
    assert_eq!(warns, 1);
}

/// The `Unreaped` a failed spawn hands back for a front does what the spawn's policy says when
/// dropped: under `LetGo` it looks once and gives the front up, and does not wait for it. The look
/// after the teardown's own is the scripted `Reaped`, which a `Wait` drop's wait finds as well.
///
/// Mutants: `tear_down_held` hands the front's `Unreaped` the sync drop kind;
/// the front reads as not a front, so the teardown kills and waits for it.
#[skuld::test]
fn the_unreaped_a_failed_spawn_hands_back_for_a_front_does_what_its_policy_says_on_drop() {
    crate::log_capture::install();
    let record = ExitRecord::Status(std::process::ExitStatus::default());
    let mut fake = None;
    let (owned, stdin) = held_front(|f| {
        fake = Some(f.clone());
        f.reaps([ReapAnswer::Running, ReapAnswer::Exited(record)])
    });
    let _blocker = ReapsBlocker::new(&owned, stdin);
    let _fire = fire_on_block(&fake.expect("the script ran"));
    let (_, _, handed_back) = tear_down_front_under(owned, None, SpawnPolicy::LET_GO);
    assert_eq!(
        crate::wait::block_probe::take(),
        [],
        "the teardown looks at the front once and does not wait for it"
    );
    let handed_back = handed_back.expect("a front left running is handed back");
    let mark = crate::log_capture::mark();

    drop(handed_back);

    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(
        warns[0].contains("dropped without wait or leak") && !warns[0].contains("waited for it"),
        "{warns:?}"
    );
}

/// The remains of a failed spawn's teardown with two failures. (No real pidfd teardown fails on
/// demand: a kill is refused only for another user's process, and a wait on a pidfd that is no
/// child's finds it gone, so the remains are stated.)
fn remains_with_two_failures() -> crate::child::owned::teardown::Remains {
    crate::child::owned::teardown::Remains {
        fate: ChildFate::Killed,
        uncollected: false,
        refused: None,
        failures: crate::error::Failures::collect([
            Error::io_cause(std::io::Error::other("refused kill 51f3")),
            Error::io_cause(std::io::Error::other("failed wait 51f3")),
        ]),
    }
}

/// What failed in a failed spawn's teardown of the child it held has no `cleanup` to go to in a
/// `not started` answer, so each failure the teardown's own warn did not say is logged at warn
/// through `Report`.
///
/// Mutant: the teardown's failures are dropped.
#[skuld::test]
fn a_failed_spawns_teardown_failures_its_own_warn_did_not_say_are_each_warned_of() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    warn_of_teardown_failures(&remains_with_two_failures(), false);
    let warns = warns_since(mark, "teardown of its child failed");
    assert_eq!(warns.len(), 2, "{warns:?}");
    assert!(warns[0].contains("refused kill 51f3"), "{warns:?}");
    assert!(warns[1].contains("failed wait 51f3"), "{warns:?}");
}

/// The teardown's own warn (a clause at warn, or the spawn's diagnosis folded into it) holds its
/// failures, and the failed spawn's event has that one warn: nothing is logged a second time.
///
/// Mutant: the failures are logged again beside the teardown's warn.
#[skuld::test]
fn a_failed_spawns_teardown_failures_its_own_warn_said_are_not_warned_of_again() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    warn_of_teardown_failures(&remains_with_two_failures(), true);
    assert_eq!(warns_since(mark, "teardown of its child failed"), Vec::<String>::new());
}